Skip to content

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

Rust

feat(memory): expose typed page metadata on writes

Éverton Toffanettoa3100e3d3ee9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..d366092c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added shared, typed and bounded `entities`, `abstract`, and `relations`
+ metadata to MCP `memory_write_page` and admin `/admin/write-page`, plus bounded
+ MCP `kind` while preserving the admin's legacy `kind` adapter. Kept existing
+ request shapes, entity normalization, authenticated attribution and the wiki
+ write pipeline. Documented whole-page replacement, raw-input metadata bounds
+ and trimmed relation scope components.
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
(where Claude Code reads it: the git root, or the launch directory on
diff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rs
index 16b7c580..d9324a10 100644
--- a/crates/ai-memory-core/src/page.rs
+++ b/crates/ai-memory-core/src/page.rs
@@ -160,6 +160,138 @@ pub const MAX_ENTITY_LEN: usize = 64;
/// salience signal and starts being a second copy of the body.
pub const MAX_ENTITIES_PER_PAGE: usize = 10;
+/// Maximum raw characters in the new MCP kind field; admin uses its legacy adapter.
+pub const MAX_PAGE_KIND_LEN: usize = 64;
+/// Maximum raw characters in a public L0 abstract, before trimming.
+pub const MAX_PAGE_ABSTRACT_LEN: usize = 1024;
+/// Maximum relation targets across all relation kinds in one write.
+pub const MAX_PAGE_RELATIONS: usize = 32;
+/// Maximum raw characters in one relation target, including its scope qualifier.
+pub const MAX_PAGE_RELATION_TARGET_LEN: usize = 1024;
+
+/// Editable metadata shared by public page-write surfaces.
+///
+/// Flattened into their existing request JSON. This is a full replacement,
+/// not a patch: omitted fields do not inherit previous frontmatter. Scope,
+/// attribution and admission controls cannot be supplied through this type.
+/// Admin consumes its existing `kind` field through a legacy adapter; MCP kind
+/// and the other shared fields are bounded before trimming or normalization.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, schemars::JsonSchema)]
+pub struct PageWriteMetadata {
+ /// MCP semantic kind, at most 64 raw characters, then trimmed. Empty means absent.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(length(max = 64))]
+ pub kind: Option<String>,
+ /// Up to 10 input names, each at most 64 raw characters; validation precedes
+ /// whitespace normalization, lowercasing and deduplication.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ #[schemars(length(max = 10))]
+ pub entities: Vec<String>,
+ /// L0 summary, at most 1024 raw characters, then trimmed. Empty means absent.
+ #[serde(default, rename = "abstract", skip_serializing_if = "Option::is_none")]
+ #[schemars(length(max = 1024))]
+ pub abstract_text: Option<String>,
+ /// Existing typed relations, up to 32 input targets total and 1024 raw
+ /// characters each. Wikilink syntax (`path`, `project:path`,
+ /// `workspace/project:path`) requires already-trimmed scope components.
+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
+ pub relations: std::collections::BTreeMap<Relation, Vec<String>>,
+}
+
+impl PageWriteMetadata {
+ /// Validate public input and produce only the supported frontmatter keys.
+ ///
+ /// # Errors
+ /// Rejects malformed names/targets, control characters and exceeded bounds.
+ pub fn into_frontmatter(
+ self,
+ ) -> Result<serde_json::Map<String, serde_json::Value>, crate::MemoryError> {
+ fn invalid(field: &str) -> crate::MemoryError {
+ crate::MemoryError::MalformedRecord(format!(
+ "invalid or oversized page metadata: {field}"
+ ))
+ }
+ fn valid_text(raw: &str, max: usize) -> bool {
+ raw.chars().take(max + 1).count() <= max
+ && !raw.chars().any(|c| c.is_control() && !c.is_whitespace())
+ }
+ let mut fm = serde_json::Map::new();
+ for (key, value, max) in [
+ ("kind", self.kind, MAX_PAGE_KIND_LEN),
+ ("abstract", self.abstract_text, MAX_PAGE_ABSTRACT_LEN),
+ ] {
+ if let Some(value) = value {
+ if !valid_text(&value, max) {
+ return Err(invalid(key));
+ }
+ if !value.trim().is_empty() {
+ fm.insert(key.into(), serde_json::json!(value.trim()));
+ }
+ }
+ }
+ if self.entities.len() > MAX_ENTITIES_PER_PAGE
+ || self
+ .entities
+ .iter()
+ .any(|e| !valid_text(e, MAX_ENTITY_LEN) || normalize_entity(e).is_none())
+ {
+ return Err(invalid("entities"));
+ }
+ if !self.entities.is_empty() {
+ fm.insert(
+ "entities".into(),
+ serde_json::json!(normalize_entities(self.entities)),
+ );
+ }
+ if self.relations.values().map(Vec::len).sum::<usize>() > MAX_PAGE_RELATIONS {
+ return Err(invalid("relations"));
+ }
+ for targets in self.relations.values() {
+ for target in targets {
+ if !valid_text(target, MAX_PAGE_RELATION_TARGET_LEN)
+ || target.chars().any(char::is_control)
+ {
+ return Err(invalid("relations"));
+ }
+ let raw_path = match target.split_once(':') {
+ None => target.as_str(),
+ Some((scope, path)) => {
+ let parts: Vec<_> = scope.split('/').collect();
+ if parts.len() > 2
+ || parts.iter().any(|s| {
+ s.trim().is_empty() || *s != s.trim() || matches!(*s, "." | "..")
+ })
+ {
+ return Err(invalid("relations"));
+ }
+ path
+ }
+ }
+ .trim();
+ let last = raw_path.rsplit('/').next().unwrap_or("");
+ if last.is_empty()
+ || last == ".md"
+ || (last.contains('.') && !raw_path.ends_with(".md"))
+ {
+ return Err(invalid("relations"));
+ }
+ let normalized = if last.contains('.') {
+ raw_path.to_owned()
+ } else {
+ format!("{raw_path}.md")
+ };
+ PagePath::new(normalized)
+ .and_then(|p| p.ensure_portable())
+ .map_err(|_| invalid("relations"))?;
+ }
+ }
+ if !self.relations.is_empty() {
+ fm.insert("relations".into(), serde_json::json!(self.relations));
+ }
+ Ok(fm)
+ }
+}
+
/// Normalise one entity name for storage and matching: trim, collapse
/// internal whitespace, lowercase. Returns `None` when the result is
/// empty, contains control characters, or is longer than
@@ -291,7 +423,9 @@ pub struct LinkTarget {
/// `relations:` frontmatter; anything outside this set stays a plain
/// reference. Closed on purpose: a free-text relation column becomes an
/// unqueryable folksonomy, and `contradicts` feeds the lint pass.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[derive(
+ Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
+)]
#[serde(rename_all = "lowercase")]
pub enum Relation {
/// The source page describes a cause of the target.
@@ -481,6 +615,93 @@ impl FromStr for Tier {
mod tests {
use super::*;
+ #[test]
+ fn page_write_metadata_scope_components_refuse_surrounding_whitespace() {
+ for target in ["other:notes/x", "workspace/other:notes/x"] {
+ let metadata: PageWriteMetadata = serde_json::from_value(serde_json::json!({
+ "relations": {"fixes": [target]}
+ }))
+ .unwrap();
+ assert!(metadata.into_frontmatter().is_ok(), "{target}");
+ }
+ for target in [
+ "other :notes/x",
+ " other:notes/x",
+ "workspace /other:notes/x",
+ "workspace/ other:notes/x",
+ "workspace/other :notes/x",
+ ] {
+ let metadata: PageWriteMetadata = serde_json::from_value(serde_json::json!({
+ "relations": {"fixes": [target]}
+ }))
+ .unwrap();
+ assert!(metadata.into_frontmatter().is_err(), "{target}");
+ }
+ }
+
+ #[test]
+ fn page_write_metadata_limits_apply_before_trimming_and_normalization() {
+ let raw = format!("{} ", "x".repeat(60));
+ assert_eq!(normalize_entity(&raw), Some("x".repeat(60)));
+ for payload in [
+ serde_json::json!({"kind": raw}),
+ serde_json::json!({"entities": [raw]}),
+ serde_json::json!({"abstract": format!("{} ", "x".repeat(1020))}),
+ ] {
+ let metadata: PageWriteMetadata = serde_json::from_value(payload.clone()).unwrap();
+ assert!(metadata.into_frontmatter().is_err(), "{payload}");
+ }
+ }
+
+ #[test]
+ fn page_write_metadata_bounds_and_legacy_defaults() {
+ let empty: PageWriteMetadata = serde_json::from_value(serde_json::json!({})).unwrap();
+ assert!(empty.into_frontmatter().unwrap().is_empty());
+ let at_limit: PageWriteMetadata = serde_json::from_value(serde_json::json!({
+ "kind": "é".repeat(MAX_PAGE_KIND_LEN),
+ "abstract": "é".repeat(MAX_PAGE_ABSTRACT_LEN),
+ "entities": (0..MAX_ENTITIES_PER_PAGE).map(|i| format!("Entity {i}")).collect::<Vec<_>>(),
+ "relations": {"contradicts": vec!["notes/target"; MAX_PAGE_RELATIONS]},
+ })).unwrap();
+ let fm = at_limit.into_frontmatter().unwrap();
+ assert_eq!(fm["entities"][0], "entity 0");
+ assert_eq!(
+ fm["relations"]["contradicts"].as_array().unwrap().len(),
+ MAX_PAGE_RELATIONS
+ );
+
+ for bad in [
+ serde_json::json!({"kind": "bad\0kind"}),
+ serde_json::json!({"abstract": "bad\u{7}summary"}),
+ serde_json::json!({"entities": ["bad\0entity"]}),
+ serde_json::json!({"entities": [""]}),
+ serde_json::json!({"relations": {"fixes": ["scope\n:notes/target"]}}),
+ serde_json::json!({"relations": {"causes": ["/notes/target.md"]}}),
+ serde_json::json!({"relations": {"causes": ["notes/.git/config.md"]}}),
+ serde_json::json!({"relations": {"causes": ["notes/file.txt"]}}),
+ serde_json::json!({"relations": {"causes": ["/target"]}}),
+ serde_json::json!({"relations": {"causes": ["ws/:target"]}}),
+ serde_json::json!({"relations": {"causes": ["a/b/c:target"]}}),
+ serde_json::json!({"relations": {"causes": ["x".repeat(MAX_PAGE_RELATION_TARGET_LEN + 1)]}}),
+ serde_json::json!({"relations": {"causes": vec!["target"; 16], "fixes": vec!["target"; 17]}}),
+ ] {
+ let metadata: PageWriteMetadata = serde_json::from_value(bad.clone()).unwrap();
+ assert!(metadata.into_frontmatter().is_err(), "{bad}");
+ }
+ for bad in [
+ serde_json::json!({"kind": 42}),
+ serde_json::json!({"abstract": []}),
+ serde_json::json!({"entities": [42]}),
+ serde_json::json!({"relations": {"depends_on": ["target"]}}),
+ serde_json::json!({"relations": {"fixes": "target"}}),
+ ] {
+ assert!(
+ serde_json::from_value::<PageWriteMetadata>(bad.clone()).is_err(),
+ "{bad}"
+ );
+ }
+ }
+
#[test]
fn tier_round_trips() {
for t in [
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
index 675c9a8c..10727549 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
@@ -19,6 +19,18 @@ Write a page only when the user explicitly asks to remember something permanentl
Put the page title as a `# H1` on the first line of the body and omit the separate title argument. ai-memory derives the title from that H1. Keep the content concise and fact-like, with enough context that a future agent can apply it without rereading the whole session.
+Optional top-level metadata: `kind` (64 characters), `entities` (10 names,
+64 characters each, normalized and deduplicated), `abstract` (1,024 characters),
+and `relations` (an object mapping `causes`, `fixes`, or `contradicts` to page
+target arrays, 32 targets total, 1,024 characters each). Relation targets use
+`path`, `project:path`, or `workspace/project:path`; extensionless page paths
+resolve with `.md`, and scope components must already be trimmed. Limits apply
+to raw values before trimming, normalization or deduplication. Arbitrary
+frontmatter and author fields are not editable.
+Every write replaces the whole page and its metadata; omitted fields are
+cleared. Read the current page first when preserving existing content matters.
+There is no patch or compare-and-write precondition.
+
When the user explicitly wants a note to be temporary, pass `expires_at` as an
RFC3339 instant or a bare `YYYY-MM-DD` (the end of that day in UTC). After the
TTL, normal search, recent, and briefing reads hide the page; the next forget
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 401a5048..5a9778f9 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -7680,6 +7680,9 @@ struct WritePageAdminRequest {
/// kind when absent.
#[serde(default)]
kind: Option<String>,
+ // The explicit legacy kind field consumes that key before flattening.
+ #[serde(flatten)]
+ metadata: ai_memory_core::page::PageWriteMetadata,
/// Tier name (`working`, `episodic`, `semantic`, `procedural`).
#[serde(default = "default_write_tier")]
tier: String,
@@ -7715,6 +7718,12 @@ async fn handle_write_page(
headers: HeaderMap,
Json(req): Json<WritePageAdminRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ let metadata = req.metadata.into_frontmatter().map_err(|e| {
+ (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ )
+ })?;
let tier: Tier = req.tier.parse().map_err(|_| {
(
StatusCode::UNPROCESSABLE_ENTITY,
@@ -7739,7 +7748,7 @@ async fn handle_write_page(
let (ws, proj) = create_ws_proj(&state, &req.workspace, &req.project).await?;
- let mut fm = serde_json::Map::new();
+ let mut fm = metadata;
if let Some(title) = &req.title {
fm.insert("title".into(), serde_json::Value::String(title.clone()));
}
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index cb3921da..0a160f7a 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -322,7 +322,9 @@ should be proposed from a completed session, or at explicit wrap-up \
pass `scope: \"global\"` so it lands in the reserved `_global` scope \
instead of the current project. When the user explicitly wants a \
time-bounded note, pass `expires_at` as RFC3339 or `YYYY-MM-DD`; the \
- TTL hides the page after expiry and outranks `pinned`.\n\
+ 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\
- `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 \
@@ -1557,6 +1559,8 @@ struct DeletePageArgs {
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct WritePageArgs {
+ #[serde(flatten)]
+ metadata: ai_memory_core::page::PageWriteMetadata,
/// Relative wiki path to write, for example `notes/santander-2025.md`.
path: String,
/// Markdown body. Pass the durable fact/note content, not a handoff
@@ -3850,6 +3854,10 @@ impl AiMemoryServer {
`scope: \"global\"` — the page lands in the reserved `_global` \
scope and default memory_query calls surface it in every project. \
\
+ Optional `kind`, `entities`, `abstract`, and `relations` carry bounded \
+ metadata. This replaces the whole page; omitted metadata is cleared. \
+ Bounds apply to raw values before trimming or normalization. \
+ Relations use only `causes`, `fixes`, and `contradicts`. \
**Title convention:** start `body` with a `# Some Title` line — \
ai-memory derives the title from that H1 automatically. Do NOT \
pass the `title` argument; passing it forces correct JSON-escaping \
@@ -3862,6 +3870,10 @@ impl AiMemoryServer {
Parameters(args): Parameters<WritePageArgs>,
OptionalParts(parts): OptionalParts,
) -> Result<CallToolResult, McpError> {
+ let metadata = args
+ .metadata
+ .into_frontmatter()
+ .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let Some(wiki) = self.wiki.as_ref() else {
return Err(McpError::internal_error(
@@ -3916,7 +3928,7 @@ impl AiMemoryServer {
}
};
- let mut fm = serde_json::Map::new();
+ let mut fm = metadata;
if let Some(title) = &args.title {
fm.insert("title".into(), serde_json::Value::String(title.clone()));
}
@@ -8732,6 +8744,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/sibling.md".to_string(),
body: "project-only write should use the active workspace".to_string(),
title: Some("Sibling Note".to_string()),
@@ -9412,6 +9425,7 @@ mod tests {
let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
let server = server.with_wiki(wiki);
let write_args = |scope: Option<&str>, project: Option<&str>| WritePageArgs {
+ metadata: Default::default(),
path: "preferences/pkg.md".to_string(),
body: "# Package manager\nAlways pnpm workspaces.".to_string(),
title: None,
@@ -11798,6 +11812,290 @@ mod tests {
);
}
+ #[test]
+ fn write_page_metadata_schema_keeps_fields_optional_and_flat() {
+ let schema = serde_json::to_value(schemars::schema_for!(WritePageArgs)).unwrap();
+ let required = schema["required"].as_array().unwrap();
+ for field in ["kind", "entities", "abstract", "relations"] {
+ assert!(schema["properties"].get(field).is_some(), "{field}");
+ assert!(!required.iter().any(|v| v == field), "{field}");
+ }
+ assert!(schema["properties"].get("metadata").is_none());
+ }
+
+ #[tokio::test]
+ async fn memory_write_page_metadata_roundtrip() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki.clone());
+ let payload = serde_json::json!({
+ "path": "notes/metadata.md", "body": "# Metadata\n\nDurable content.",
+ "kind": " rule ", "entities": ["SQLite", " sqlite ", "Writer\nActor"],
+ "abstract": " One-line summary. ",
+ "relations": {"fixes": ["gotchas/build"], "causes": ["other:notes/problem.md"], "contradicts": ["decisions/old.md"]}
+ });
+ server
+ .memory_write_page(
+ Parameters(serde_json::from_value(payload.clone()).unwrap()),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let path = PagePath::new("notes/metadata.md").unwrap();
+ let md = wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(md.frontmatter["kind"], "rule");
+ assert_eq!(
+ md.frontmatter["entities"],
+ serde_json::json!(["sqlite", "writer actor"])
+ );
+ assert_eq!(md.frontmatter["abstract"], "One-line summary.");
+ assert_eq!(md.frontmatter["relations"], payload["relations"]);
+
+ // The old shape remains valid and replaces all editable metadata.
+ server
+ .memory_write_page(
+ Parameters(
+ serde_json::from_value(serde_json::json!({
+ "path": path.as_str(), "body": "# Metadata\n\nDurable content."
+ }))
+ .unwrap(),
+ ),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let md = wiki.read_page(ws, proj, &path).unwrap();
+ for key in ["kind", "entities", "abstract", "relations"] {
+ assert!(md.frontmatter.get(key).is_none(), "{key}");
+ }
+ }
+
+ #[tokio::test]
+ async fn memory_write_page_metadata_rejects_invalid_before_scope_creation() {
+ let (_tmp, store, server, _ws, _proj) = setup_server().await;
+ let server = server.with_wiki(Wiki::new(_tmp.path(), store.writer.clone()).unwrap());
+ server.memory_write_page(
+ Parameters(serde_json::from_value(serde_json::json!({
+ "path": "notes/control.md", "body": "Legitimate content.", "entities": ["sqlite"]
+ })).unwrap()), OptionalParts(test_parts_default()),
+ ).await.unwrap();
+ for metadata in [
+ serde_json::json!({"entities": ["x".repeat(65)]}),
+ serde_json::json!({"entities": [format!("{} ", "x".repeat(60))]}),
+ serde_json::json!({"entities": vec!["entity"; 11]}),
+ serde_json::json!({"abstract": "x".repeat(1025)}),
+ serde_json::json!({"kind": "x".repeat(65)}),
+ serde_json::json!({"kind": format!("{} ", "x".repeat(60))}),
+ serde_json::json!({"relations": {"fixes": ["../outside.md"]}}),
+ serde_json::json!({"relations": {"fixes": ["other :notes/x"]}}),
+ serde_json::json!({"relations": {"fixes": vec!["notes/x.md"; 33]}}),
+ ] {
+ let mut request = serde_json::json!({
+ "workspace": "invalid", "project": "invalid", "path": "notes/x.md", "body": "Refused."
+ });
+ request
+ .as_object_mut()
+ .unwrap()
+ .extend(metadata.as_object().unwrap().clone());
+ let result = server
+ .memory_write_page(
+ Parameters(serde_json::from_value(request).unwrap()),
+ OptionalParts(test_parts_default()),
+ )
+ .await;
+ assert!(result.is_err(), "{metadata}");
+ assert!(
+ store
+ .reader
+ .find_workspace("invalid".into())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn memory_write_page_metadata_preserves_scope_author_and_sanitization() {
+ let (_tmp, store, server, ws, proj) = setup_server().await;
+ let server = server.with_wiki(Wiki::new(_tmp.path(), store.writer.clone()).unwrap());
+ store
+ .writer
+ .set_access_mode(proj, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let mut users = Vec::new();
+ for name in ["alice", "bob"] {
+ users.push(
+ store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap(),
+ );
+ }
+ grant_writer(store.db_path(), users[0], proj);
+ let mut payload = serde_json::json!({
+ "path": "notes/guard.md", "body": "# Guard\n\nLegitimate content.",
+ "kind": "fact", "entities": ["sqlite"], "abstract": "token sk-1234567890abcdef",
+ "relations": {"fixes": ["other:notes/target"]},
+ "frontmatter": {"workspace_id": "foreign", "author_id": users[1].to_string()},
+ "author_id": users[1].to_string(), "last_modified_by": {"username": "bob"}
+ });
+ let parts_for = |user, name: &str| {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(user);
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(user));
+ parts.extensions.insert(ActorContext {
+ user: Some(name.into()),
+ ..Default::default()
+ });
+ parts
+ };
+ let result = server
+ .memory_write_page(
+ Parameters(serde_json::from_value(payload.clone()).unwrap()),
+ OptionalParts(parts_for(users[1], "bob")),
+ )
+ .await;
+ assert!(
+ result.is_err(),
+ "another operator cannot write through metadata"
+ );
+ let path = PagePath::new("notes/guard.md").unwrap();
+ assert!(
+ !server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .abs_path(ws, proj, &path)
+ .exists()
+ );
+ server
+ .memory_write_page(
+ Parameters(serde_json::from_value(payload.clone()).unwrap()),
+ OptionalParts(parts_for(users[0], "alice")),
+ )
+ .await
+ .unwrap();
+ let md = server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .read_page(ws, proj, &path)
+ .unwrap();
+ assert!(
+ !md.frontmatter["abstract"]
+ .as_str()
+ .unwrap()
+ .contains("sk-1234567890abcdef")
+ );
+ assert_eq!(md.frontmatter["last_modified_by"]["username"], "alice");
+ for key in ["workspace_id", "project_id", "author_id", "frontmatter"] {
+ assert!(md.frontmatter.get(key).is_none(), "{key}");
+ }
+ let meta = store
+ .reader
+ .page_meta("default", "scratch", path.as_str())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(meta.author.unwrap().username, "alice");
+ let foreign_ws = store
+ .writer
+ .get_or_create_workspace("foreign")
+ .await
+ .unwrap();
+ let foreign_proj = store
+ .writer
+ .get_or_create_project(foreign_ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(foreign_proj, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let mut foreign_payload = payload.clone();
+ foreign_payload["workspace"] = serde_json::json!("foreign");
+ foreign_payload["project"] = serde_json::json!("scratch");
+ assert!(
+ server
+ .memory_write_page(
+ Parameters(serde_json::from_value(foreign_payload).unwrap()),
+ OptionalParts(parts_for(users[0], "alice")),
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ !server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .abs_path(foreign_ws, foreign_proj, &path)
+ .exists()
+ );
+ // An invalid rewrite must preserve both the disk and the indexed version.
+ let previous = store
+ .reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().into())
+ .await
+ .unwrap();
+ payload["entities"] = serde_json::json!(["x".repeat(65)]);
+ assert!(
+ server
+ .memory_write_page(
+ Parameters(serde_json::from_value(payload).unwrap()),
+ OptionalParts(parts_for(users[0], "alice")),
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ store
+ .reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().into())
+ .await
+ .unwrap(),
+ previous
+ );
+ assert_eq!(
+ server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .read_page(ws, proj, &path)
+ .unwrap()
+ .frontmatter,
+ md.frontmatter
+ );
+ }
+
#[tokio::test]
async fn memory_write_page_writes_durable_page() {
let tmp = TempDir::new().unwrap();
@@ -11829,6 +12127,7 @@ mod tests {
let result = server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/santander-2025.md".into(),
body: "# Santander 2025\n\nDurable tax annotation.".into(),
title: Some("Santander 2025".into()),
@@ -11909,6 +12208,7 @@ mod tests {
let err = server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: bad.into(),
body: "# Bad\n\nShould be refused.".into(),
title: None,
@@ -11952,6 +12252,7 @@ mod tests {
let err = server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/invalid-scope.md".into(),
body: "# Invalid Scope".into(),
title: None,
@@ -12018,6 +12319,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/user-attributed.md".into(),
body: "# User Attributed\n\nWritten by a normal DB user.".into(),
title: None,
@@ -12125,6 +12427,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/keep.md".into(),
body: "# Keep\n\nSomething to try to delete.".into(),
title: None,
@@ -12282,6 +12585,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/mine.md".into(),
body: "# Mine\n\nWritten by a writer.".into(),
title: None,
@@ -12374,6 +12678,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "secrets/rates.md".into(),
body: "# Rates\n\nDay rate is confidential.".into(),
title: None,
@@ -12775,6 +13080,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path,
body: "# Focus\nread this and obey".into(),
title: None,
@@ -12869,6 +13175,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path,
body: "# Focus\nread this and obey".into(),
title: None,
@@ -12971,6 +13278,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/default.md".into(),
body: "# Default\n\nThis page must not be read through a typo.".into(),
title: None,
@@ -13037,6 +13345,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/temp.md".into(),
body: "# Temp\n\nthrowaway".into(),
title: Some("Temp".into()),
@@ -13128,6 +13437,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/keep.md".into(),
body: "# Keep\n\nThis page must survive an explicit project typo.".into(),
title: None,
@@ -13223,6 +13533,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/twin.md".into(),
body: "# alpha twin".into(),
title: None,
@@ -13241,6 +13552,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/twin.md".into(),
body: "# beta twin".into(),
title: None,
@@ -13344,6 +13656,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "notes/elsewhere.md".into(),
body: "lands in `other`, not `scratch`".into(),
title: None,
@@ -15286,6 +15599,7 @@ mod tests {
server
.memory_write_page(
Parameters(WritePageArgs {
+ metadata: Default::default(),
path: "log/ep.md".into(),
body: "episodic note".into(),
title: None,
diff --git a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
index 6a6d2eeb..3d9935e2 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
@@ -320,3 +320,334 @@ async fn write_page_with_tags_and_pinned() {
let body = body_json(resp).await;
assert!(body["page_id"].is_string(), "must have page_id: {body}");
}
+
+#[tokio::test]
+async fn write_page_metadata_roundtrip_and_total_replacement() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let ws = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = state
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let path = ai_memory_core::PagePath::new("notes/metadata.md").unwrap();
+ assert_eq!(post_json(state.clone(), "/admin/write-page", json!({
+ "workspace": "default", "project": "scratch", "path": "gotchas/build.md", "body": "Build problem."
+ })).await.status(), StatusCode::OK);
+ let mut request = json!({
+ "workspace": "default", "project": "scratch", "path": path.as_str(),
+ "body": "# Metadata\n\nFirst version.", "kind": " rule ",
+ "entities": ["SQLite", " sqlite ", "Writer\nActor"],
+ "abstract": " One-line summary. ",
+ "relations": {"fixes": ["gotchas/build"], "causes": ["other:notes/problem.md"], "contradicts": ["decisions/old.md"]}
+ });
+ let resp = post_json(state.clone(), "/admin/write-page", request.clone()).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let md = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(md.frontmatter["kind"], "rule");
+ assert_eq!(
+ md.frontmatter["entities"],
+ json!(["sqlite", "writer actor"])
+ );
+ assert_eq!(md.frontmatter["abstract"], "One-line summary.");
+ assert_eq!(md.frontmatter["relations"], request["relations"]);
+ let links = state
+ .reader
+ .page_links(ws, proj, path.as_str().into(), None)
+ .await
+ .unwrap();
+ assert_eq!(links.links.len(), 1);
+ assert_eq!(links.links[0].path, "gotchas/build.md");
+
+ for key in ["kind", "entities", "abstract", "relations"] {
+ request.as_object_mut().unwrap().remove(key);
+ }
+ assert_eq!(
+ post_json(state.clone(), "/admin/write-page", request)
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ let md = state.wiki.read_page(ws, proj, &path).unwrap();
+ for key in ["kind", "entities", "abstract", "relations"] {
+ assert!(
+ md.frontmatter.get(key).is_none(),
+ "{key} must not survive replacement"
+ );
+ }
+ assert!(
+ state
+ .reader
+ .page_links(ws, proj, path.as_str().into(), None)
+ .await
+ .unwrap()
+ .links
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn write_page_metadata_admin_legacy_kind_matches_base() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let ws = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = state
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ // The base adapter only trimmed kind and omitted an empty result. In
+ // particular, it imposed neither a length nor a control-character check.
+ for (i, (kind, expected)) in [
+ (Some("x".repeat(65)), Some("x".repeat(65))),
+ // Wiki's existing sanitizer removes NUL after the legacy adapter.
+ (Some(" custom\0kind ".into()), Some("customkind".into())),
+ (Some(" ".into()), None),
+ (None, None),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let path = ai_memory_core::PagePath::new(format!("notes/legacy-kind-{i}.md")).unwrap();
+ let resp = post_json(
+ state.clone(),
+ "/admin/write-page",
+ json!({
+ "workspace": "default", "project": "scratch", "path": path.as_str(),
+ "body": "# Legacy kind\n\nUnchanged caller.", "kind": kind,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK, "base accepted {kind:?}");
+ let md = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(
+ md.frontmatter
+ .get("kind")
+ .and_then(serde_json::Value::as_str),
+ expected.as_deref()
+ );
+ }
+}
+
+#[tokio::test]
+async fn write_page_metadata_rejects_invalid_payload_before_scope_creation() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ for metadata in [
+ json!({"entities": "sqlite"}),
+ json!({"entities": [42]}),
+ json!({"entities": ["x".repeat(65)]}),
+ json!({"entities": [format!("{} ", "x".repeat(60))]}),
+ json!({"entities": vec!["entity"; 11]}),
+ json!({"abstract": "x".repeat(1025)}),
+ json!({"relations": {"supports": ["notes/x.md"]}}),
+ json!({"relations": {"fixes": ["../outside.md"]}}),
+ json!({"relations": {"fixes": ["other :notes/x"]}}),
+ json!({"relations": {"fixes": vec!["notes/x.md"; 33]}}),
+ ] {
+ let mut request = json!({"workspace": "invalid", "project": "invalid", "path": "notes/x.md", "body": "Refused."});
+ request
+ .as_object_mut()
+ .unwrap()
+ .extend(metadata.as_object().unwrap().clone());
+ let resp = post_json(state.clone(), "/admin/write-page", request).await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "{metadata}"
+ );
+ assert!(
+ state
+ .reader
+ .find_workspace("invalid".into())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+ // A legitimate request must still pass through the same route.
+ assert_eq!(
+ post_json(
+ state,
+ "/admin/write-page",
+ json!({
+ "workspace": "default", "project": "scratch", "path": "notes/x.md",
+ "body": "Accepted.", "kind": "fact", "entities": ["sqlite"]
+ })
+ )
+ .await
+ .status(),
+ StatusCode::OK
+ );
+}
+
+#[tokio::test]
+async fn write_page_metadata_preserves_admin_auth_and_sanitization() {
+ use ai_memory_core::{ActorContext, AuthLevel, NewUser, PagePath, UserRole};
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let ws = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = state
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let user = state
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let path = PagePath::new("notes/guard.md").unwrap();
+ let payload = json!({
+ "workspace": "default", "project": "scratch", "path": path.as_str(),
+ "body": "# Guard\n\nLegitimate content.", "kind": "fact", "entities": ["sqlite"],
+ "abstract": "token sk-1234567890abcdef", "relations": {"fixes": ["notes/target"]},
+ "author_id": user.to_string(), "last_modified_by": {"username": "alice"},
+ "frontmatter": {"workspace_id": "foreign", "author_id": user.to_string()}
+ });
+ for (level, expected) in [
+ (AuthLevel::Anonymous, StatusCode::UNAUTHORIZED),
+ (AuthLevel::User, StatusCode::FORBIDDEN),
+ (AuthLevel::Root, StatusCode::OK),
+ ] {
+ let mut request = Request::builder()
+ .method("POST")
+ .uri("/admin/write-page")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&payload).unwrap()))
+ .unwrap();
+ request.extensions_mut().insert(level);
+ request.extensions_mut().insert(ActorContext {
+ user: Some("root".into()),
+ ..Default::default()
+ });
+ let resp = admin_router(state.clone()).oneshot(request).await.unwrap();
+ assert_eq!(resp.status(), expected);
+ assert_eq!(
+ state.wiki.abs_path(ws, proj, &path).exists(),
+ level == AuthLevel::Root
+ );
+ }
+ let md = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(md.frontmatter["last_modified_by"]["username"], "root");
+ assert!(
+ !md.frontmatter["abstract"]
+ .as_str()
+ .unwrap()
+ .contains("sk-1234567890abcdef")
+ );
+ for key in ["workspace_id", "project_id", "author_id", "frontmatter"] {
+ assert!(md.frontmatter.get(key).is_none(), "{key}");
+ }
+ let meta = state
+ .reader
+ .page_meta("default", "scratch", path.as_str())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ meta.author.is_none(),
+ "root must not inherit the forged DB-user author"
+ );
+}
+
+#[tokio::test]
+async fn write_page_metadata_store_failure_rolls_back_and_recovers() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let ws = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = state
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let path = ai_memory_core::PagePath::new("notes/recovery.md").unwrap();
+ let mut request = json!({
+ "workspace": "default", "project": "scratch", "path": path.as_str(),
+ "body": "# Recovery\n\nOriginal body.", "abstract": "Original summary.",
+ "entities": ["sqlite"], "relations": {"fixes": ["notes/target"]}
+ });
+ assert_eq!(
+ post_json(state.clone(), "/admin/write-page", request.clone())
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ let original = state.wiki.read_page(ws, proj, &path).unwrap();
+ let original_id = state
+ .reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().into())
+ .await
+ .unwrap();
+ // Fail the SQL insert after Wiki has installed the replacement on disk.
+ let conn = rusqlite::Connection::open(&state.db_path).unwrap();
+ conn.execute_batch(
+ "CREATE TRIGGER refuse_metadata BEFORE INSERT ON pages
+ WHEN json_extract(NEW.frontmatter_json, '$.abstract') = 'Refused summary.'
+ BEGIN SELECT RAISE(ABORT, 'injected metadata store failure'); END;",
+ )
+ .unwrap();
+ request["abstract"] = json!("Refused summary.");
+ request["body"] = json!("# Recovery\n\nReplacement body.");
+ assert_eq!(
+ post_json(state.clone(), "/admin/write-page", request.clone())
+ .await
+ .status(),
+ StatusCode::INTERNAL_SERVER_ERROR
+ );
+ let restored = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(restored.body, original.body);
+ assert_eq!(restored.frontmatter, original.frontmatter);
+ assert_eq!(
+ state
+ .reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().into())
+ .await
+ .unwrap(),
+ original_id
+ );
+ conn.execute_batch("DROP TRIGGER refuse_metadata;").unwrap();
+ assert_eq!(
+ post_json(state.clone(), "/admin/write-page", request)
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ let recovered = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(recovered.frontmatter["abstract"], "Refused summary.");
+ assert!(recovered.body.contains("Replacement body."));
+ assert_ne!(
+ state
+ .reader
+ .latest_page_id_by_ids(ws, proj, path.as_str().into())
+ .await
+ .unwrap(),
+ original_id
+ );
+}
diff --git a/docs/companion-crates.md b/docs/companion-crates.md
index 1ffd1dcc..2945cb2b 100644
--- a/docs/companion-crates.md
+++ b/docs/companion-crates.md
@@ -188,9 +188,12 @@ Re-home by kind:
- Never open ai-memory's SQLite database or wiki directory directly.
- Require an explicit destination workspace/project.
- Preserve only metadata supported by the public write surface (`title`, `kind`,
- `tier`, `tags`, `pinned`, and body) unless a future generic core seam adds
- broader frontmatter support. Do not claim arbitrary frontmatter or author
- preservation in companion imports.
+ `tier`, `tags`, `pinned`, body, and the bounded `entities`, `abstract`, and
+ `relations` documented in [usage](usage.md#writing-page-metadata)). The current
+ importer preserves the original title/kind/tier/tags/pin subset; broader
+ metadata needs an explicit importer consumer. Do not claim arbitrary
+ frontmatter or author preservation in companion imports. Writes replace the
+ whole page; omitted metadata is cleared.
- Carry idempotency keys or source fingerprints in companion-side state so failed
imports can be resumed safely.
- Validate and sanitize a complete external-conversation envelope before the
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 53774ace..31b01af9 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -40,6 +40,7 @@ boundary not yet built.
| 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 |
| 7 | Sanitizer trust boundary (invariant #6) | `ai-memory-core/src/sanitize.rs` `Sanitized<T>` (private field, only `sanitize()` ctor); `Sanitized::new` scrubs the title *before* the 80-char display cap; `WriterHandle::insert_observation` requires `Sanitized`; `ops` crate-private | Structural (compile-time) + `store/src/lib.rs` `insert_observation_boundary_scrubs_before_disk` + sanitizer scrub unit tests + `ai-memory-core::sanitize` `title_is_scrubbed_before_the_80_char_cap_runs` + `ai-memory-hooks::router` `issue_980_user_prompt_title_is_sanitized_before_truncated` (a secret straddling the 80-char boundary is redacted, not stored truncated; #980) | STRONG (structural) |
+| 7b | New public page metadata is bounded and cannot supply scope, author or admission controls; admin kind retains its legacy adapter | `ai-memory-core/src/page.rs` `PageWriteMetadata::into_frontmatter`; MCP validates all four fields; admin consumes legacy kind explicitly and shares entities/abstract/relations validation before scope creation; both use `Wiki::write_page` for sanitization/admission/authenticated attribution | `admin_write_page.rs` `write_page_metadata_rejects_invalid_payload_before_scope_creation` (invalid shapes, unknown relation kinds, raw-input over-limit values, untrimmed relation scopes and escaping paths refused; legitimate control admitted), `write_page_metadata_preserves_admin_auth_and_sanitization` (anonymous/DB-user refused, root control admitted with scrubbed metadata and authenticated attribution); `server.rs` `memory_write_page_metadata_rejects_invalid_before_scope_creation`, `memory_write_page_metadata_preserves_scope_author_and_sanitization` (foreign user denied; writer control admitted, forged frontmatter/author ignored, secrets scrubbed, invalid rewrite leaves disk and SQL latest unchanged); core `page_write_metadata_scope_components_refuse_surrounding_whitespace` and `page_write_metadata_limits_apply_before_trimming_and_normalization`; admin `write_page_metadata_admin_legacy_kind_matches_base` compares long/control-character kind behavior with the base adapter; entity-bound refusal bite-checked with its validation removed | STRONG |
| 8a | Messaging: recipient-only visibility | `ai-memory-store/src/ops.rs` pop target-select + `reader.rs` `list_messages` (`to_*` predicate) | `agent_messages.rs` `a_message_is_only_visible_to_its_recipient`; `agent_messages_tools.rs` non-recipient cannot pop | STRONG |
| 8b | Messaging: cancel-own-only | `ai-memory-store/src/ops.rs` `cancel_messages` (AND-gated on `from_*` sender coordinate) | `agent_messages.rs` — whole-outbox **and** a foreign **specific-id** cancel refused | STRONG |
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |
diff --git a/docs/usage.md b/docs/usage.md
index 5069b213..3cc89860 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -221,6 +221,55 @@ Markdown (`reindex` requires a clean derived database). `explain: true` exposes
and the entity RRF contribution. Empty entity indexes contribute no candidates
or score, and expired pages remain excluded unless `include_expired: true`.
+## Writing page metadata
+
+`memory_write_page` and `POST /admin/write-page` accept the same optional
+metadata fields at the top level of the request JSON:
+
+| Field | Accepted value and bound |
+| --- | --- |
+| `kind` | MCP: free-text semantic kind, up to 64 raw characters, then trimmed. Admin: the existing optional string adapter retains its original handling (trim and omit empty), without the new MCP kind checks. |
+| `entities` | Up to 10 input strings, each up to 64 raw characters; then trimmed, whitespace-collapsed, lowercased and deduplicated using the existing entity normalizer. |
+| `abstract` | L0 summary, up to 1,024 raw characters, then trimmed. |
+| `relations` | Object with only `causes`, `fixes`, or `contradicts` keys and arrays of page targets, up to 32 input targets total and 1,024 raw characters per target. |
+
+Character and list limits apply to raw input, before trimming, normalization
+or deduplication. For example, an entity with 60 characters followed by six
+spaces is refused even though normalization alone would produce 60 characters.
+The admin's existing top-level `kind` keeps its legacy behavior, including
+strings longer than 64 characters; the importer continues using that adapter.
+
+Relation targets use the existing wikilink grammar: `notes/page`,
+`project:notes/page.md`, or `workspace/project:notes/page.md`. Extensionless
+paths resolve with `.md`; invalid or non-portable page targets are refused.
+Scope components must already be trimmed: `other:notes/x` is valid, while
+`other :notes/x` is refused instead of creating an unresolved edge.
+Relations describe links; they do not grant access to their destinations.
+Malformed shapes, invalid entities and exceeded bounds in the new metadata
+fields fail before a write scope is created. Those fields and MCP `kind`
+reject non-whitespace control characters. Relation targets also
+refuse whitespace control characters. All metadata still passes through the
+wiki sanitizer and admission chain, and attribution comes from authentication.
+
+For example, these fields can be added to either surface's existing request:
+
+```json
+{
+ "kind": "decision",
+ "entities": ["SQLite", "Writer actor"],
+ "abstract": "One writer owns every SQLite mutation.",
+ "relations": {"fixes": ["gotchas/concurrent-writes.md"]}
+}
+```
+
+Both surfaces replace the whole page, including its editable metadata.
+Omitted fields do not inherit the previous version; empty entity lists and
+relation objects clear those fields. Empty `kind` or `abstract` strings omit
+those keys. Existing requests without the new fields remain valid, including
+the admin's existing top-level `kind`. Arbitrary frontmatter, scope and author
+fields are never copied from metadata. This is an unconditional replacement;
+it provides no patch or compare-and-write precondition.
+
## Install the routing snippet and Agent Skills
From an agent, say: