Skip to content

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

Rust

feat(mcp): conditional page writes and deletes (#986 slice 2)

AkitaOnRails8ab422554c2b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5dfcc094..9daea926 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `memory_write_page` accepts `expected_page_id` (write only if that is still
+ the page's latest version) or `create_only` (write only if the page does not
+ exist), and `memory_delete_page` accepts `expected_page_id`. A precondition
+ that no longer holds fails with `reason: "precondition_failed"` and the
+ current version, and changes nothing. `memory_read_page` returns the version
+ as `page_id` and `/api/v1` pages as `id`. This is the compare-and-write the
+ team-wiki sync needed (#986).
- `ai-memory doctor` now reports three silent capture failures: an unreachable
server (reported instead of aborting the check), a hook spool that is full and
evicting undelivered events, and installed ai-memory Codex hooks that Codex
diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rs
index 52c4f149..67e56b43 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -603,7 +603,7 @@ pub async fn run_sweep_with_hygiene(
};
let result = match wiki {
Some(w) => match w
- .delete_page_if_latest(workspace_id, project_id, &path, page.id, None)
+ .delete_page_if_latest(workspace_id, project_id, &path, page.id, None, None)
.await
{
Ok(true) => Ok(()),
diff --git a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs b/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
index 30b59a6d..b674defc 100644
--- a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
+++ b/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
@@ -577,6 +577,7 @@ async fn ttl_expiry_lifecycle_end_to_end() {
proj,
&PagePath::new("notes/refreshed.md").unwrap(),
stale_expired_id,
+ None,
None
)
.await
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 688befba..5322a2c8 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -345,7 +345,10 @@ should be proposed from a completed session, or at explicit wrap-up \
time-bounded note, pass `expires_at` as RFC3339 or `YYYY-MM-DD`; the \
TTL hides the page after expiry and outranks `pinned`. Optional `kind`, \
`entities`, `abstract`, and `relations` carry bounded metadata; writes \
- replace the whole page, and omitted metadata is cleared.\n\
+ replace the whole page, and omitted metadata is cleared. To change a \
+ page only if nobody else has, pass the `page_id` `memory_read_page` \
+ returned as `expected_page_id` (or `create_only: true` for a new page); \
+ a stale one fails with `precondition_failed` and writes nothing.\n\
- `memory_read_page` — when the user asks to read, open, or show the \
full content of a specific page. Accepts a `query` (searches FTS5 and \
returns the top hit's full body) or a `path` (direct lookup). Follow \
@@ -366,7 +369,8 @@ should be proposed from a completed session, or at explicit wrap-up \
remove a specific page (by exact path). Idempotent; fires the \
admission chain so mirrors/backups stay consistent. Follow the client-aware \
project-scope rule above; missing explicit sibling scopes fail closed \
- instead of falling back.\n\
+ instead of falling back. Pass `expected_page_id` to delete only the \
+ version you read.\n\
- `memory_feedback` — right after a `memory_query` / `memory_read_page` \
hit proves useful or misleading, and whenever the user says a recalled \
page is out of date or wrong. Pass the exact `path` from the hit plus \
@@ -1586,6 +1590,13 @@ struct DeletePageArgs {
/// `workspace`/`project`.
#[serde(default)]
scope: Option<String>,
+ /// Delete only if this is still the page's latest version id (the
+ /// `page_id` that `memory_read_page` returned). If the page changed or is
+ /// already gone, nothing is deleted and the call fails with
+ /// `reason: "precondition_failed"` and the current id. Omit for a normal
+ /// delete.
+ #[serde(default)]
+ expected_page_id: Option<String>,
}
/// Write one durable wiki page. Optional metadata (`kind`, `entities`,
@@ -1654,6 +1665,18 @@ struct WritePageArgs {
/// with its own model. Not combinable with `scope: "global"`.
#[serde(default)]
session_id: Option<String>,
+ /// Write only if this is still the page's latest version id (the
+ /// `page_id` that `memory_read_page` or an earlier write returned). If
+ /// someone changed the page since, nothing is written and the call fails
+ /// with `reason: "precondition_failed"` and the current id. Omit for a
+ /// normal write. Not combinable with `create_only`.
+ #[serde(default)]
+ expected_page_id: Option<String>,
+ /// Write only if no page exists at `path` yet; otherwise fail with
+ /// `reason: "precondition_failed"`. Not combinable with
+ /// `expected_page_id`.
+ #[serde(default)]
+ create_only: bool,
}
#[tool_router]
@@ -4314,6 +4337,7 @@ impl AiMemoryServer {
.map(SessionId::from_str)
.transpose()
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
+ let precondition = page_precondition(args.expected_page_id.as_deref(), args.create_only)?;
let path = PagePath::new(args.path.clone())
.map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;
path.ensure_portable()
@@ -4516,34 +4540,45 @@ impl AiMemoryServer {
None
};
- let page_id = wiki
- .write_page(WritePageRequest {
- workspace_id: ws,
- project_id: proj,
- path: path.clone(),
- frontmatter,
- body,
- tier,
- pinned: args.pinned,
- title,
- admission_ctx,
- author_id,
- actor,
- evidence: session_id
- .map(|id| ai_memory_core::PageEvidence {
- kind: ai_memory_core::PageEvidenceKind::Session,
- source_id: id.to_string(),
- })
- .into_iter()
- .collect(),
- })
- .await
- .map_err(|e| {
- Self::with_manifest_warning(
- McpError::internal_error(e.to_string(), None),
- manifest_warning.as_ref(),
- )
- })?;
+ let request = WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter,
+ body,
+ tier,
+ pinned: args.pinned,
+ title,
+ admission_ctx,
+ author_id,
+ actor,
+ evidence: session_id
+ .map(|id| ai_memory_core::PageEvidence {
+ kind: ai_memory_core::PageEvidenceKind::Session,
+ source_id: id.to_string(),
+ })
+ .into_iter()
+ .collect(),
+ };
+ let written = match precondition {
+ None => wiki
+ .write_page(request)
+ .await
+ .map(ai_memory_wiki::ConditionalWrite::Written),
+ Some(precondition) => wiki.write_page_if(request, precondition).await,
+ }
+ .map_err(|e| {
+ Self::with_manifest_warning(
+ McpError::internal_error(e.to_string(), None),
+ manifest_warning.as_ref(),
+ )
+ })?;
+ let page_id = match written {
+ ai_memory_wiki::ConditionalWrite::Written(page_id) => page_id,
+ ai_memory_wiki::ConditionalWrite::Mismatch { current } => {
+ return Err(precondition_failed(&path, precondition, current));
+ }
+ };
let checkpoint = checkpoint_or_warn(wiki, format!("memory_write_page: {}", path.as_str()));
// Only the session page settles the job: evidence on another page
// must not close it while `sessions/<id>.md` is still missing.
@@ -4705,12 +4740,14 @@ impl AiMemoryServer {
// only on the success paths below, so an error read reinforces nothing.
let bump_actor = Self::bump_actor_from_parts(&parts);
let mut bump_ids: Vec<PageId> = Vec::new();
- if let Some(seed_id) = self
+ // Also returned as `page_id`: the version token a conditional
+ // `memory_write_page`/`memory_delete_page` passes back.
+ let page_id = self
.reader
.latest_page_id_by_ids(ws, proj, page_path.to_string())
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?
- {
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ if let Some(seed_id) = page_id {
bump_ids.push(seed_id);
}
if let Some(nodes) = &related {
@@ -4727,6 +4764,7 @@ impl AiMemoryServer {
let title = ai_memory_wiki::derive_title(&md.frontmatter, &md.body, &page_path);
ok_json(&attach_related(serde_json::json!({
"path": page_path.to_string(),
+ "page_id": page_id.map(|id| id.to_string()),
"title": title,
"body": md.body,
"frontmatter": md.frontmatter,
@@ -4750,6 +4788,7 @@ impl AiMemoryServer {
.or(Some(stored.title));
ok_json(&attach_related(serde_json::json!({
"path": page_path.to_string(),
+ "page_id": page_id.map(|id| id.to_string()),
"title": title,
"body": stored.body,
"frontmatter": frontmatter,
@@ -4996,6 +5035,10 @@ impl AiMemoryServer {
None,
));
};
+ let expected = match page_precondition(args.expected_page_id.as_deref(), false)? {
+ Some(ai_memory_store::PagePrecondition::Latest(id)) => Some(id),
+ _ => None,
+ };
let path = PagePath::new(args.path.clone())
.map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;
let (path, (ws, proj)) = match args.scope.as_deref().map(str::trim) {
@@ -5052,13 +5095,43 @@ impl AiMemoryServer {
None
};
+ // A conditional delete that cannot succeed leaves no checkpoint behind.
+ if let Some(expected) = expected {
+ let current = self.latest_page_id(ws, proj, &path).await?;
+ if current != Some(expected) {
+ return Err(precondition_failed(
+ &path,
+ Some(ai_memory_store::PagePrecondition::Latest(expected)),
+ current,
+ ));
+ }
+ }
let pre_checkpoint =
checkpoint_or_mcp(wiki, format!("pre-memory_delete_page: {}", path.as_str()))?;
let author_id = crate::actor::author_id_from_parts(&parts);
- wiki.delete_page(ws, proj, &path, admission_ctx, author_id)
- .await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ match expected {
+ None => wiki
+ .delete_page(ws, proj, &path, admission_ctx, author_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,
+ Some(expected) => {
+ // The authority: re-checked under the exclusive mutation lock
+ // and in the delete transaction.
+ let deleted = wiki
+ .delete_page_if_latest(ws, proj, &path, expected, admission_ctx, author_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ if !deleted {
+ let current = self.latest_page_id(ws, proj, &path).await?;
+ return Err(precondition_failed(
+ &path,
+ Some(ai_memory_store::PagePrecondition::Latest(expected)),
+ current,
+ ));
+ }
+ }
+ }
let checkpoint = checkpoint_or_warn(wiki, format!("memory_delete_page: {}", path.as_str()));
ok_json(&serde_json::json!({
@@ -6696,6 +6769,19 @@ fn select_bumpable(
}
impl AiMemoryServer {
+ /// The latest version id of a page in an already-authorized scope.
+ async fn latest_page_id(
+ &self,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ path: &PagePath,
+ ) -> Result<Option<ai_memory_core::PageId>, McpError> {
+ self.reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().to_string())
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))
+ }
+
/// The caller's typed identity for keying the bump throttle and the
/// `page_access` rows it feeds. One derivation for both:
/// a throttle keyed one way and a table keyed another would throttle one
@@ -6813,6 +6899,56 @@ fn profile_page_path(path: PagePath) -> Result<PagePath, McpError> {
.map_err(|e| McpError::invalid_params(format!("invalid path: {e}"), None))
}
+/// The precondition a conditional page write or delete asked for, `None` for
+/// a normal one.
+fn page_precondition(
+ expected_page_id: Option<&str>,
+ create_only: bool,
+) -> Result<Option<ai_memory_store::PagePrecondition>, McpError> {
+ let expected = expected_page_id.map(str::trim).filter(|id| !id.is_empty());
+ match (expected, create_only) {
+ (Some(_), true) => Err(McpError::invalid_params(
+ "expected_page_id and create_only cannot be combined",
+ None,
+ )),
+ (Some(id), false) => ai_memory_core::PageId::from_str(id)
+ .map(|id| Some(ai_memory_store::PagePrecondition::Latest(id)))
+ .map_err(|_| {
+ McpError::invalid_params(format!("expected_page_id {id:?} is not a page id"), None)
+ }),
+ (None, true) => Ok(Some(ai_memory_store::PagePrecondition::Absent)),
+ (None, false) => Ok(None),
+ }
+}
+
+/// The error for a conditional write or delete whose precondition no longer
+/// holds. Nothing was changed; `data` carries the ids so a client can re-read
+/// and decide.
+fn precondition_failed(
+ path: &PagePath,
+ precondition: Option<ai_memory_store::PagePrecondition>,
+ current: Option<ai_memory_core::PageId>,
+) -> McpError {
+ let expected = match precondition {
+ Some(ai_memory_store::PagePrecondition::Latest(id)) => Some(id.to_string()),
+ _ => None,
+ };
+ let current = current.map(|id| id.to_string());
+ McpError::invalid_request(
+ format!(
+ "precondition failed for {path}: expected {}, latest is {}; nothing was changed",
+ expected.as_deref().unwrap_or("no page"),
+ current.as_deref().unwrap_or("no page"),
+ ),
+ Some(serde_json::json!({
+ "reason": "precondition_failed",
+ "path": path.as_str(),
+ "expected_page_id": expected,
+ "current_page_id": current,
+ })),
+ )
+}
+
fn ok_json<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
let s = serde_json::to_string_pretty(value)
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -9850,6 +9986,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts),
)
@@ -10532,6 +10670,8 @@ mod tests {
scope: scope.map(str::to_string),
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
};
server
@@ -13937,6 +14077,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts),
)
@@ -14029,6 +14171,8 @@ mod tests {
expires_at: None,
session_id: Some(session_id.to_string()),
metadata: Default::default(),
+ create_only: false,
+ expected_page_id: None,
}
}
@@ -14324,6 +14468,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -14369,6 +14515,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -14437,6 +14585,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts),
)
@@ -14546,6 +14696,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -14597,6 +14749,7 @@ mod tests {
path: "notes/keep.md".into(),
project: None,
workspace: None,
+ expected_page_id: None,
}),
OptionalParts(parts_as_reader()),
)
@@ -14608,6 +14761,97 @@ mod tests {
"the refusal must name both levels: {message}"
);
+ // A precondition is no way around the grant, and the refusal never
+ // reveals the page's current version: right id or wrong, the reader
+ // gets the authorization error, not a precondition mismatch.
+ let seeded = server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ include_related: false,
+ related_depth: None,
+ path: Some("notes/keep.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let seeded: serde_json::Value =
+ serde_json::from_str(&seeded.content[0].as_text().unwrap().text).unwrap();
+ let right = seeded["page_id"].as_str().unwrap().to_owned();
+ let wrong = ai_memory_core::PageId::new().to_string();
+ for expected in [right.clone(), wrong] {
+ let err = server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ metadata: Default::default(),
+ path: "notes/keep.md".into(),
+ body: "# Keep\n\nOverwritten by a reader.".into(),
+ title: None,
+ tier: None,
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ session_id: None,
+ create_only: false,
+ expected_page_id: Some(expected.clone()),
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect_err("a reader must not write, with or without a precondition");
+ assert!(
+ err.data.is_none(),
+ "no version data for a refused caller: {err:?}"
+ );
+ let err = server
+ .memory_delete_page(
+ Parameters(DeletePageArgs {
+ scope: None,
+ path: "notes/keep.md".into(),
+ project: None,
+ workspace: None,
+ expected_page_id: Some(expected),
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect_err("a reader must not delete, with or without a precondition");
+ assert!(
+ err.message
+ .contains("you have read access and this needs write"),
+ "{err:?}"
+ );
+ assert!(err.data.is_none(), "{err:?}");
+ }
+ let after: serde_json::Value = serde_json::from_str(
+ &server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ include_related: false,
+ related_depth: None,
+ path: Some("notes/keep.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap()
+ .content[0]
+ .as_text()
+ .unwrap()
+ .text,
+ )
+ .unwrap();
+ assert_eq!(after["page_id"], right.as_str());
+
let err = server
.memory_feedback(
Parameters(FeedbackArgs {
@@ -14706,6 +14950,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -14718,6 +14964,7 @@ mod tests {
path: "notes/mine.md".into(),
project: None,
workspace: None,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -14806,6 +15053,8 @@ mod tests {
expires_at: None,
session_id: None,
metadata: Default::default(),
+ create_only: false,
+ expected_page_id: None,
}
}
@@ -14872,6 +15121,7 @@ mod tests {
path: "preferences.md".into(),
project: Some("_global".into()),
workspace: Some("default".into()),
+ expected_page_id: None,
}),
OptionalParts(parts_as_user(maria)),
)
@@ -14982,6 +15232,8 @@ mod tests {
expires_at: None,
session_id: None,
metadata: Default::default(),
+ create_only: false,
+ expected_page_id: None,
}
}
@@ -15158,6 +15410,7 @@ mod tests {
path: "profile/tools/pnpm.md".into(),
project: Some(joaos.clone()),
workspace: Some("default".into()),
+ expected_page_id: None,
}),
OptionalParts(parts_as_user(maria)),
)
@@ -15187,6 +15440,7 @@ mod tests {
path: "tools/pnpm.md".into(),
project: None,
workspace: None,
+ expected_page_id: None,
}),
OptionalParts(parts_as_user(joao)),
)
@@ -15420,6 +15674,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(alice_parts),
)
@@ -15823,6 +16079,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts),
)
@@ -15919,6 +16177,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts),
)
@@ -16023,6 +16283,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -16091,6 +16353,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -16104,6 +16368,7 @@ mod tests {
path: "notes/temp.md".into(),
project: None,
workspace: None,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -16185,6 +16450,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -16198,6 +16465,7 @@ mod tests {
path: "notes/keep.md".into(),
project: Some("typo".into()),
workspace: None,
+ expected_page_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -16283,6 +16551,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -16303,6 +16573,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -16317,6 +16589,7 @@ mod tests {
path: "notes/twin.md".into(),
project: Some("shared".into()),
workspace: Some("beta".into()),
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -16409,6 +16682,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -18566,6 +18841,8 @@ mod tests {
scope: None,
expires_at: None,
session_id: None,
+ create_only: false,
+ expected_page_id: None,
}),
OptionalParts(parts()),
)
@@ -19085,4 +19362,215 @@ mod tests {
assert!(locked.pending.is_empty());
assert!(!locked.flush_scheduled);
}
+
+ /// #986 slice 2: `memory_write_page`/`memory_delete_page` act only on the
+ /// version the caller saw when it passes `expected_page_id`.
+ mod conditional_page_writes {
+ use super::*;
+
+ async fn server(with_reader: bool) -> (TempDir, AiMemoryServer) {
+ 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();
+ store
+ .writer
+ .get_or_create_project(ws, "other", None)
+ .await
+ .unwrap();
+ let mut wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ if with_reader {
+ wiki = wiki.with_store_reader(store.reader.clone());
+ }
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+ (tmp, server)
+ }
+
+ fn write(path: &str, body: &str, project: &str) -> WritePageArgs {
+ WritePageArgs {
+ metadata: Default::default(),
+ path: path.into(),
+ body: body.into(),
+ title: None,
+ tier: None,
+ tags: vec![],
+ pinned: false,
+ project: Some(project.into()),
+ workspace: Some("default".into()),
+ scope: None,
+ expires_at: None,
+ session_id: None,
+ expected_page_id: None,
+ create_only: false,
+ }
+ }
+
+ fn delete(path: &str, expected: Option<&str>) -> DeletePageArgs {
+ DeletePageArgs {
+ path: path.into(),
+ project: Some("scratch".into()),
+ workspace: Some("default".into()),
+ scope: None,
+ expected_page_id: expected.map(str::to_owned),
+ }
+ }
+
+ fn json(result: &CallToolResult) -> serde_json::Value {
+ let text = result.content[0].as_text().expect("tool text").text.clone();
+ serde_json::from_str(&text).unwrap()
+ }
+
+ async fn put(server: &AiMemoryServer, args: WritePageArgs) -> Result<String, McpError> {
+ server
+ .memory_write_page(Parameters(args), OptionalParts(test_parts_default()))
+ .await
+ .map(|r| json(&r)["page_id"].as_str().unwrap().to_owned())
+ }
+
+ async fn read(server: &AiMemoryServer, path: &str) -> serde_json::Value {
+ let result = server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ query: None,
+ path: Some(path.into()),
+ project: Some("scratch".into()),
+ workspace: Some("default".into()),
+ include_related: false,
+ related_depth: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ json(&result)
+ }
+
+ fn assert_precondition_failed(err: &McpError, current: Option<&str>) {
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_REQUEST, "{err:?}");
+ let data = err.data.as_ref().expect("precondition data");
+ assert_eq!(data["reason"], "precondition_failed", "{data}");
+ assert_eq!(data["current_page_id"].as_str(), current, "{data}");
+ }
+
+ #[tokio::test]
+ async fn a_write_lands_only_on_the_version_it_saw() {
+ for with_reader in [true, false] {
+ let (_tmp, server) = server(with_reader).await;
+ let first = put(&server, write("notes/a.md", "# A\n\none", "scratch"))
+ .await
+ .unwrap();
+ assert_eq!(read(&server, "notes/a.md").await["page_id"], first.as_str());
+
+ let mut next = write("notes/a.md", "# A\n\ntwo", "scratch");
+ next.expected_page_id = Some(first.clone());
+ let second = put(&server, next).await.unwrap();
+ assert_ne!(second, first);
+
+ // A writer still holding the first version is refused and the
+ // page keeps the second.
+ let mut stale = write("notes/a.md", "# A\n\nstale", "scratch");
+ stale.expected_page_id = Some(first.clone());
+ let err = put(&server, stale).await.unwrap_err();
+ assert_precondition_failed(&err, Some(&second));
+ let page = read(&server, "notes/a.md").await;
+ assert_eq!(page["page_id"], second.as_str(), "reader={with_reader}");
+ assert!(page["body"].as_str().unwrap().contains("two"), "{page}");
+
+ // create_only refuses an existing page and creates a new one.
+ let mut again = write("notes/a.md", "# A\n\nagain", "scratch");
+ again.create_only = true;
+ assert_precondition_failed(&put(&server, again).await.unwrap_err(), Some(&second));
+ let mut fresh = write("notes/b.md", "# B", "scratch");
+ fresh.create_only = true;
+ put(&server, fresh).await.unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn malformed_or_combined_preconditions_are_invalid_params() {
+ let (_tmp, server) = server(true).await;
+ let mut both = write("notes/a.md", "# A", "scratch");
+ both.expected_page_id = Some(ai_memory_core::PageId::new().to_string());
+ both.create_only = true;
+ let mut malformed = write("notes/a.md", "# A", "scratch");
+ malformed.expected_page_id = Some("not-a-page".into());
+ for args in [both, malformed] {
+ let err = put(&server, args).await.unwrap_err();
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS, "{err:?}");
+ }
+ }
+
+ /// A version id from another project never matches: the precondition
+ /// is checked against the resolved scope's own latest row.
+ #[tokio::test]
+ async fn an_id_from_another_project_is_a_mismatch() {
+ let (_tmp, server) = server(true).await;
+ let theirs = put(&server, write("notes/a.md", "# Theirs", "other"))
+ .await
+ .unwrap();
+ let ours = put(&server, write("notes/a.md", "# Ours", "scratch"))
+ .await
+ .unwrap();
+ let mut cross = write("notes/a.md", "# Hijack", "scratch");
+ cross.expected_page_id = Some(theirs);
+ assert_precondition_failed(&put(&server, cross).await.unwrap_err(), Some(&ours));
+ assert!(
+ read(&server, "notes/a.md").await["body"]
+ .as_str()
+ .unwrap()
+ .contains("Ours")
+ );
+ }
+
+ #[tokio::test]
+ async fn a_delete_removes_only_the_version_it_saw() {
+ for with_reader in [true] {
+ let (_tmp, server) = server(with_reader).await;
+ let first = put(&server, write("notes/a.md", "# A\n\none", "scratch"))
+ .await
+ .unwrap();
+ let mut next = write("notes/a.md", "# A\n\ntwo", "scratch");
+ next.expected_page_id = Some(first.clone());
+ let second = put(&server, next).await.unwrap();
+
+ let err = server
+ .memory_delete_page(
+ Parameters(delete("notes/a.md", Some(&first))),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_precondition_failed(&err, Some(&second));
+ assert_eq!(
+ read(&server, "notes/a.md").await["page_id"],
+ second.as_str()
+ );
+
+ server
+ .memory_delete_page(
+ Parameters(delete("notes/a.md", Some(&second))),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let err = server
+ .memory_delete_page(
+ Parameters(delete("notes/a.md", Some(&second))),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_precondition_failed(&err, None);
+ }
+ }
+ }
}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index c566a055..5290cfd6 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -61,15 +61,15 @@ pub use error::{
pub use grants::{GrantFilter, GrantListing, GrantOutcome, ProjectGrant};
pub use maintenance::MaintenanceJob;
pub use ops::{
- AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DateOnlyTtlPage,
- DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,
+ AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, ConditionalUpsert,
+ DateOnlyTtlPage, DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,
HookSessionAdmission, IdentityResolution, IngestObservationOutcome, LifecycleOnlyEndOutcome,
MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,
- OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode,
- ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary, ReorgSummary,
- RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason,
- SkippedSessionTimes, StaleAfterRepair, backfill_entity_index, backfill_page_windows,
- backfill_page_windows_in_batches, purge_session, record_embed_failure,
+ OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PagePrecondition, PageWindowBackfillSummary,
+ PagesMode, ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary,
+ ReorgSummary, RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate,
+ SessionTimesSkipReason, SkippedSessionTimes, StaleAfterRepair, backfill_entity_index,
+ backfill_page_windows, backfill_page_windows_in_batches, purge_session, record_embed_failure,
};
pub use profile::{
NewProfileCandidate, PROFILE_CANDIDATES_LIMIT, PROFILE_ENTRIES_LIMIT, PROFILE_HARVEST_BATCH,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 4444e5ed..6e01d362 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -203,6 +203,66 @@ pub fn upsert_page(conn: &mut Connection, page: &NewPage) -> StoreResult<PageId>
Ok(result_id)
}
+/// What a conditional page write requires of the current latest version.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PagePrecondition {
+ /// No latest version exists at the path: the write creates the page.
+ Absent,
+ /// The latest version at the path is this one.
+ Latest(PageId),
+}
+
+/// The outcome of [`upsert_page_if`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConditionalUpsert {
+ /// The precondition held and the page was written; the id is current.
+ Upserted(PageId),
+ /// The precondition did not hold and nothing was written.
+ Mismatch {
+ /// The latest version id at the path, `None` when there is none.
+ current: Option<PageId>,
+ },
+}
+
+/// [`upsert_page`] only when `precondition` holds, checked in the same
+/// transaction as the write so no other writer can land in between.
+pub fn upsert_page_if(
+ conn: &mut Connection,
+ page: &NewPage,
+ precondition: PagePrecondition,
+) -> StoreResult<ConditionalUpsert> {
+ let now = Timestamp::now().as_microsecond();
+ let tx = conn.transaction()?;
+ let current = latest_page_id_in_tx(&tx, page)?;
+ let holds = match precondition {
+ PagePrecondition::Absent => current.is_none(),
+ PagePrecondition::Latest(expected) => current == Some(expected),
+ };
+ if !holds {
+ return Ok(ConditionalUpsert::Mismatch { current });
+ }
+ let id = upsert_page_in_tx(&tx, page, now)?;
+ tx.commit()?;
+ Ok(ConditionalUpsert::Upserted(id))
+}
+
+fn latest_page_id_in_tx(tx: &Transaction<'_>, page: &NewPage) -> StoreResult<Option<PageId>> {
+ let raw: Option<Vec<u8>> = tx
+ .query_row(
+ "SELECT id FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",
+ params![
+ page.workspace_id.as_bytes(),
+ page.project_id.as_bytes(),
+ page.path.as_str(),
+ ],
+ |row| row.get(0),
+ )
+ .optional()?;
+ raw.map(|bytes| PageId::from_slice(&bytes).map_err(StoreError::from))
+ .transpose()
+}
+
/// Resolve a workspace by name, creating it if missing. Atomic.
pub fn get_or_create_workspace(
conn: &mut Connection,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 750a5681..30e1c360 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1642,6 +1642,9 @@ pub struct PageAuthor {
/// Returned by [`ReaderPool::page_meta`].
#[derive(Debug, Clone, Serialize)]
pub struct PageMeta {
+ /// Id of this (latest) version: the token a conditional write or delete
+ /// passes back to act only on the version it saw.
+ pub id: PageId,
/// Name of the workspace.
pub workspace_name: String,
/// Name of the project.
@@ -7480,7 +7483,7 @@ impl ReaderPool {
{kind_expr}, \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path, \
- au.username, au.name, au.email, pg.expires_at \
+ au.username, au.name, au.email, pg.expires_at, pg.id \
FROM pages pg \
JOIN projects p ON p.id = pg.project_id \
JOIN workspaces w ON w.id = pg.workspace_id \
@@ -7513,7 +7516,7 @@ impl ReaderPool {
{kind_expr}, \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path, \
- au.username, au.name, au.email, pg.expires_at \
+ au.username, au.name, au.email, pg.expires_at, pg.id \
FROM pages pg \
JOIN projects p ON p.id = pg.project_id \
JOIN workspaces w ON w.id = pg.workspace_id \
@@ -8412,7 +8415,7 @@ impl ReaderPool {
{kind_expr}, \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path, \
- au.username, au.name, au.email, pg.expires_at \
+ au.username, au.name, au.email, pg.expires_at, pg.id \
FROM pages pg \
JOIN projects p ON p.id = pg.project_id \
JOIN workspaces w ON w.id = pg.workspace_id \
@@ -10397,6 +10400,7 @@ fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<P
let author_name: Option<String> = row.get(13)?;
let author_email: Option<String> = row.get(14)?;
let expires_us: Option<i64> = row.get(15)?;
+ let id_bytes: Vec<u8> = row.get(16)?;
let author = author_username.map(|username| PageAuthor {
username,
name: author_name,
@@ -10407,6 +10411,8 @@ fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<P
.map_err(|_| rusqlite::Error::IntegralValueOutOfRange(2, 0))?;
let project_id = ProjectId::from_slice(&proj_id_bytes)
.map_err(|_| rusqlite::Error::IntegralValueOutOfRange(3, 0))?;
+ let id = PageId::from_slice(&id_bytes)
+ .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(16, 0))?;
let created_at = jiff::Timestamp::from_microsecond(created_us)
.map(|ts| ts.to_string())
@@ -10420,6 +10426,7 @@ fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<P
.map(|ts| ts.to_string());
Ok(Ok(PageMeta {
+ id,
workspace_name,
project_name,
workspace_id,
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 64d668d5..b35de8d3 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -174,6 +174,11 @@ pub(crate) enum WriteCmd {
page: NewPage,
reply: oneshot::Sender<StoreResult<PageId>>,
},
+ UpsertPageIf {
+ page: NewPage,
+ precondition: ops::PagePrecondition,
+ reply: oneshot::Sender<StoreResult<ops::ConditionalUpsert>>,
+ },
UpsertPageBatch {
pages: Vec<NewPage>,
reply: oneshot::Sender<StoreResult<Vec<PageId>>>,
@@ -192,6 +197,7 @@ pub(crate) enum WriteCmd {
project_id: ProjectId,
path: PagePath,
expected_latest_id: PageId,
+ author_id: Option<ai_memory_core::UserId>,
reply: oneshot::Sender<StoreResult<bool>>,
},
BeginSession {
@@ -2665,6 +2671,27 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// [`Self::upsert_page`] only when `precondition` holds for the latest
+ /// version at the page's path, checked in the write's own transaction.
+ ///
+ /// # Errors
+ /// As [`Self::upsert_page`]. A precondition that does not hold is not an
+ /// error: it returns [`ops::ConditionalUpsert::Mismatch`] and writes nothing.
+ pub async fn upsert_page_if(
+ &self,
+ page: NewPage,
+ precondition: ops::PagePrecondition,
+ ) -> StoreResult<ops::ConditionalUpsert> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::UpsertPageIf {
+ page,
+ precondition,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Delete every version of a page (by path) from the index. The wiki file
/// removal is the caller's concern; this drops the derived rows so the
/// page stops appearing in search/recent (the watcher does NOT reconcile
@@ -2705,6 +2732,7 @@ impl WriterHandle {
project_id: ProjectId,
path: PagePath,
expected_latest_id: PageId,
+ author_id: Option<ai_memory_core::UserId>,
) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::DeletePageIfLatest {
@@ -2712,6 +2740,7 @@ impl WriterHandle {
project_id,
path,
expected_latest_id,
+ author_id,
reply: tx,
})
.await?;
@@ -3748,6 +3777,14 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::upsert_page(&mut conn, &page);
send_or_warn(reply, result, "upsert_page");
}
+ WriteCmd::UpsertPageIf {
+ page,
+ precondition,
+ reply,
+ } => {
+ let result = ops::upsert_page_if(&mut conn, &page, precondition);
+ send_or_warn(reply, result, "upsert_page_if");
+ }
WriteCmd::DeletePage {
workspace_id,
project_id,
@@ -3764,6 +3801,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
project_id,
path,
expected_latest_id,
+ author_id,
reply,
} => {
let result = ops::delete_page_if_latest(
@@ -3772,7 +3810,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
project_id,
&path,
expected_latest_id,
- None,
+ author_id,
);
send_or_warn(reply, result, "delete_page_if_latest");
}
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index 6f62abf0..ade14c37 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -22,8 +22,8 @@ use ai_memory_core::{
owner_stamp,
};
use ai_memory_store::{
- LinkOrAdoptManagedRunSession, ManagedRunSessionLink, PrepareWorkstreamRun, Store, StoreError,
- WorkstreamSelection,
+ ConditionalUpsert, LinkOrAdoptManagedRunSession, ManagedRunSessionLink, PagePrecondition,
+ PrepareWorkstreamRun, Store, StoreError, WorkstreamSelection,
};
fn operator(name: &str) -> String {
@@ -87,6 +87,103 @@ fn page(ws: WorkspaceId, proj: ProjectId, path: &str, title: &str, body: &str) -
}
}
+/// #986 slice 2 under invariant #16: two harnesses edit one page from the
+/// same version with a precondition. Exactly one wins; the loser writes
+/// nothing, and the version both started from stays reachable as superseded.
+/// Without the in-transaction check both would supersede it and the first
+/// winner's text would be buried under the second.
+#[tokio::test]
+async fn conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed() {
+ let tmp = tempfile::tempdir().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, "shared", None)
+ .await
+ .unwrap();
+ let base = store
+ .writer
+ .upsert_page(page(ws, proj, "notes/plan.md", "Plan", "# Plan\n\nbase"))
+ .await
+ .unwrap();
+
+ let (a, b) = tokio::join!(
+ store.writer.upsert_page_if(
+ page(
+ ws,
+ proj,
+ "notes/plan.md",
+ "Plan",
+ "# Plan\n\nfrom harness A"
+ ),
+ PagePrecondition::Latest(base),
+ ),
+ store.writer.upsert_page_if(
+ page(
+ ws,
+ proj,
+ "notes/plan.md",
+ "Plan",
+ "# Plan\n\nfrom harness B"
+ ),
+ PagePrecondition::Latest(base),
+ ),
+ );
+ let outcomes = [a.unwrap(), b.unwrap()];
+ let winners: Vec<_> = outcomes
+ .iter()
+ .filter_map(|outcome| match outcome {
+ ConditionalUpsert::Upserted(id) => Some(*id),
+ ConditionalUpsert::Mismatch { .. } => None,
+ })
+ .collect();
+ assert_eq!(winners.len(), 1, "{outcomes:?}");
+ assert!(
+ outcomes.contains(&ConditionalUpsert::Mismatch {
+ current: Some(winners[0])
+ }),
+ "the loser is told the winner's version: {outcomes:?}"
+ );
+
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ let rows: Vec<(String, i64)> = conn
+ .prepare(
+ "SELECT body, is_latest FROM pages WHERE path = 'notes/plan.md' ORDER BY created_at",
+ )
+ .unwrap()
+ .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
+ .unwrap()
+ .map(Result::unwrap)
+ .collect();
+ assert_eq!(
+ rows.len(),
+ 2,
+ "base plus one winner, no loser row: {rows:?}"
+ );
+ assert_eq!((rows[0].0.as_str(), rows[0].1), ("# Plan\n\nbase", 0));
+ assert_eq!(rows[1].1, 1);
+
+ // A precondition naming no page, against an existing page, writes nothing.
+ assert_eq!(
+ store
+ .writer
+ .upsert_page_if(
+ page(ws, proj, "notes/plan.md", "Plan", "# Plan\n\nfresh"),
+ PagePrecondition::Absent,
+ )
+ .await
+ .unwrap(),
+ ConditionalUpsert::Mismatch {
+ current: Some(winners[0])
+ }
+ );
+}
+
/// #1033 under invariant #16: two operators on two clones of one repository,
/// in folders named differently, use the default `path` style and capture at
/// the same time. They must land in one project — the same name and the same row —
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index 6071ce13..42ae0401 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -216,6 +216,7 @@ async fn page_handler(
.map_err(internal_error)?;
let page = ApiPage {
+ id: meta.id.to_string(),
backlinks: links.backlinks,
body_markdown: markdown.body,
created_at: meta.created_at,
@@ -1482,6 +1483,9 @@ struct ApiSessionObservations {
#[derive(Debug, Serialize)]
struct ApiPage {
+ /// Id of the latest version, the token a conditional MCP write or delete
+ /// passes back. It changes with every new version, so the ETag does too.
+ id: String,
workspace: String,
project: String,
path: String,
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index bc1e3778..aa54dae2 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -769,7 +769,8 @@ async fn api_page_returns_markdown_and_metadata() {
.get_or_create_project(ws, "scratch", None)
.await
.unwrap();
- wiki.write_page(wiki_req(ws, proj, "foo.md", "# Foo\n\nHello world"))
+ let page_id = wiki
+ .write_page(wiki_req(ws, proj, "foo.md", "# Foo\n\nHello world"))
.await
.unwrap();
@@ -785,6 +786,8 @@ async fn api_page_returns_markdown_and_metadata() {
.await
.unwrap();
let json: Value = serde_json::from_slice(&body).unwrap();
+ // The latest version id: the token a conditional MCP write passes back.
+ assert_eq!(json["id"], page_id.to_string());
assert_eq!(json["workspace"], "default");
assert_eq!(json["project"], "scratch");
assert_eq!(json["path"], "foo.md");
diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index da4daa14..8a1be1e9 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -29,7 +29,10 @@ pub use ledger::is_rotated_event_ledger;
pub use markdown::{Markdown, derive_title, emit, 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};
+pub use wiki::{
+ ConditionalWrite, MoveSessionOutcome, PurgeSessionOutcome, SessionPageFile, Wiki,
+ WritePageRequest,
+};
// Integration tests compile into this crate's test harness instead of a
// separate binary: every test binary is another link and, on macOS and
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 5ce3a2fe..41b9a89a 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -11,8 +11,9 @@ use ai_memory_core::{
use ai_memory_llm::Embedder;
use ai_memory_store::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,
- FailAutoImproveProposal, MoveSessionSummary, MoveSummary, PagesMode, PurgeSessionSummary,
- ReaderPool, ScopeRow, WriterHandle, artifact_path_for, f32_vec_to_bytes,
+ ConditionalUpsert, FailAutoImproveProposal, MoveSessionSummary, MoveSummary, PagePrecondition,
+ PagesMode, PurgeSessionSummary, ReaderPool, ScopeRow, WriterHandle, artifact_path_for,
+ f32_vec_to_bytes,
};
use tokio::sync::RwLock;
@@ -1020,6 +1021,7 @@ impl Wiki {
path: &PagePath,
expected_latest_id: PageId,
admission_ctx: Option<AdmissionContext>,
+ author_id: Option<UserId>,
) -> WikiResult<bool> {
self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.write().await;
@@ -1040,7 +1042,7 @@ impl Wiki {
path,
admission_ctx,
PageStoreRemoval::Delete {
- author_id: None,
+ author_id,
expected_latest_id: Some(expected_latest_id),
},
)
@@ -1215,11 +1217,17 @@ impl Wiki {
let delete_result = match removal {
PageStoreRemoval::Delete {
+ author_id,
expected_latest_id: Some(expected),
- ..
} => {
self.writer
- .delete_page_if_latest(workspace_id, project_id, path.clone(), expected)
+ .delete_page_if_latest(
+ workspace_id,
+ project_id,
+ path.clone(),
+ expected,
+ author_id,
+ )
.await
}
PageStoreRemoval::Delete {
@@ -2640,6 +2648,39 @@ impl Wiki {
/// # Errors
/// Returns [`WikiError`] for any filesystem, parsing, or store error.
pub async fn write_page(&self, req: WritePageRequest) -> WikiResult<PageId> {
+ match self.write_page_inner(req, None).await? {
+ ConditionalWrite::Written(id) => Ok(id),
+ ConditionalWrite::Mismatch { .. } => Err(ai_memory_wiki_error(
+ "an unconditional page write reported a precondition mismatch",
+ )),
+ }
+ }
+
+ /// [`Self::write_page`] only when `precondition` holds for the page's
+ /// latest version. A mismatch writes nothing: no file change, no new
+ /// version, no webhook dispatch.
+ ///
+ /// Checked twice under the page lock: before the file is replaced, so a
+ /// normal mismatch never touches disk, and again in the store transaction
+ /// that writes the version, which is the authority (a plain delete takes
+ /// only the shared mutation lock and can land between the two); a
+ /// mismatch there restores the file.
+ ///
+ /// # Errors
+ /// As [`Self::write_page`].
+ pub async fn write_page_if(
+ &self,
+ req: WritePageRequest,
+ precondition: PagePrecondition,
+ ) -> WikiResult<ConditionalWrite> {
+ self.write_page_inner(req, Some(precondition)).await
+ }
+
+ async fn write_page_inner(
+ &self,
+ req: WritePageRequest,
+ precondition: Option<PagePrecondition>,
+ ) -> WikiResult<ConditionalWrite> {
self.confined_page_path(
req.workspace_id,
req.project_id,
@@ -2762,30 +2803,51 @@ impl Wiki {
self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
+ if let (Some(precondition), Some(reader)) = (precondition, &self.store_reader) {
+ let current = reader
+ .latest_page_id_by_ids(workspace_id, project_id, path.as_str().to_string())
+ .await?;
+ if !precondition_holds(precondition, current) {
+ return Ok(ConditionalWrite::Mismatch { current });
+ }
+ }
let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;
let installed =
replace_file_with_rollback_snapshot(&self.git, &abs, emitted.as_bytes())?; // lgtm [rust/path-injection]
- match self
- .writer
- .upsert_page(NewPage {
- workspace_id,
- project_id,
- path,
- title,
- body: final_body.clone(),
- tier,
- frontmatter_json: final_frontmatter,
- pinned,
- links,
- author_id,
- expires_at,
- entities,
- evidence,
- })
- .await
- {
- Ok(id) => id,
+ let page = NewPage {
+ workspace_id,
+ project_id,
+ path,
+ title,
+ body: final_body.clone(),
+ tier,
+ frontmatter_json: final_frontmatter,
+ pinned,
+ links,
+ author_id,
+ expires_at,
+ entities,
+ evidence,
+ };
+ let written = match precondition {
+ None => self
+ .writer
+ .upsert_page(page)
+ .await
+ .map(ConditionalUpsert::Upserted),
+ Some(precondition) => self.writer.upsert_page_if(page, precondition).await,
+ };
+ match written {
+ Ok(ConditionalUpsert::Upserted(id)) => id,
+ Ok(ConditionalUpsert::Mismatch { current }) => {
+ rollback_or_inconsistent(
+ &self.git,
+ std::slice::from_ref(&installed),
+ &"a page write precondition no longer held",
+ )?;
+ return Ok(ConditionalWrite::Mismatch { current });
+ }
Err(e) => {
rollback_or_inconsistent(&self.git, std::slice::from_ref(&installed), &e)?;
return Err(e.into());
@@ -2810,7 +2872,7 @@ impl Wiki {
ctx,
);
}
- Ok(page_id)
+ Ok(ConditionalWrite::Written(page_id))
}
/// Embed `body` (and its L0 `abstract:` line, if present) into
@@ -2913,6 +2975,18 @@ impl Wiki {
}
}
+/// The outcome of [`Wiki::write_page_if`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConditionalWrite {
+ /// The precondition held and the page was written; the id is current.
+ Written(PageId),
+ /// The precondition did not hold and nothing was written.
+ Mismatch {
+ /// The latest version id at the path, `None` when there is none.
+ current: Option<PageId>,
+ },
+}
+
/// Input bundle for [`Wiki::write_page`]. Carries the full 3-tuple
/// identity (`workspace_id`, `project_id`, `path`) plus body & metadata.
#[derive(Debug, Clone)]
@@ -3254,6 +3328,13 @@ fn rollback_installed_files(git: &GitAdapter, installed: &[InstalledFile]) -> Wi
Ok(())
}
+fn precondition_holds(precondition: PagePrecondition, current: Option<PageId>) -> bool {
+ match precondition {
+ PagePrecondition::Absent => current.is_none(),
+ PagePrecondition::Latest(expected) => current == Some(expected),
+ }
+}
+
fn rollback_or_inconsistent<E: std::fmt::Display>(
git: &GitAdapter,
installed: &[InstalledFile],
diff --git a/docs/companion-crates.md b/docs/companion-crates.md
index 9c1c15f6..56f9fa9b 100644
--- a/docs/companion-crates.md
+++ b/docs/companion-crates.md
@@ -317,8 +317,10 @@ rewrites and the upgrade of a slice 1 export.
### Roadmap (#986)
1. Read-only export into a project repository (shipped).
-2. Conditional mutation seam (compare-and-write) in core, if independently
- justified.
+2. Conditional mutation seam in core (shipped in 2.7: `expected_page_id` /
+ `create_only` on `memory_write_page`, `expected_page_id` on
+ `memory_delete_page`, and the version id on `memory_read_page` and
+ `/api/v1` pages).
3. Bidirectional apply through public write tools (shipped as `sync`).
4. Deletes and conflict reporting.
5. Post-merge hook / CI integration.
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index adcfd3b2..b5acdd01 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -181,6 +181,7 @@ links + back-links.
```json
{
+ "id": "01a11da7-0604-7cc1-b518-1f0e0f2d4705",
"project": "ai-memory",
"path": "decisions/0007-db.md",
"title": "Standardised on Postgres",
@@ -197,6 +198,10 @@ links + back-links.
}
```
+`id` is the latest version's id. It changes with every new version, so it is
+the token to pass back as `expected_page_id` to a conditional
+`memory_write_page` or `memory_delete_page`.
+
`404` for missing workspace/project, missing page row, or missing file
on disk (the body is read from the markdown file at request time).
diff --git a/docs/programmatic-memory.md b/docs/programmatic-memory.md
index 7ddb1c3b..03a9a5f0 100644
--- a/docs/programmatic-memory.md
+++ b/docs/programmatic-memory.md
@@ -76,6 +76,18 @@ If SessionStart already owns delivery, let that hook claim it.
These calls work without an LLM provider. Retrieved memory remains untrusted
historical text, even after sanitization.
+## Change a page only if nobody else has
+
+`memory_read_page` returns the page's current version as `page_id` (`/api/v1`
+returns it as `id`). Pass it back as `expected_page_id` to `memory_write_page`
+or `memory_delete_page` and the call acts only if that is still the latest
+version; pass `create_only: true` to a write that must not overwrite an existing
+page. When the page changed in between, nothing is written or deleted and the
+call fails with JSON-RPC `invalid_request` whose `data` is
+`{"reason": "precondition_failed", "path", "expected_page_id",
+"current_page_id"}`; re-read the page and decide. A caller without write access
+gets the usual authorization error, never the current version.
+
## Read changed pages
These JSON endpoints require `serve --enable-api` (or `--enable-web`, which
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 41b6f3c8..35e4290e 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -46,6 +46,7 @@ boundary not yet built.
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | STRONG |
| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |
| 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI |
+| 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged) | STRONG |
| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed` | STRONG |
| 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG |
| 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG |