Skip to content

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

Rust

feat(mcp): add atomic anchored page patches

AkitaOnRailsd301aedd521e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85ed1d80..ca2009cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):
### Added
+- Added `memory_patch_page` for atomic, heading-anchored edits to an existing
+ Markdown page without re-emitting its body or metadata. It requires the
+ page's current `page_id`; section replacement additionally requires the
+ bounded SHA-256 token returned by `memory_read_page`. Missing, duplicate or
+ fenced-code headings, stale tokens, conflicting edits, failed admission and
+ concurrent writes leave the page unchanged. The typed TypeScript client
+ exposes the same contract as `pages.patch` (#1697).
+
- Added `[briefing] inject_on_subagent_start` to `.ai-memory.toml`. A project
that sets it hands each `claude-code` subagent the project brief when the
subagent starts: the same pinned, `_rules/` and `_slots/` brief that
diff --git a/Cargo.lock b/Cargo.lock
index 71de19a9..c79a5f23 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -241,6 +241,7 @@ dependencies = [
"secrecy",
"serde",
"serde_json",
+ "sha2",
"subtle",
"tar",
"tempfile",
diff --git a/companions/ai-memory-ts/README.md b/companions/ai-memory-ts/README.md
index ada5d75d..a90e3051 100644
--- a/companions/ai-memory-ts/README.md
+++ b/companions/ai-memory-ts/README.md
@@ -117,6 +117,7 @@ scope. Arguments are the server's wire names in camelCase
|---|---|
| `pages.write` | `memory_write_page` |
| `pages.update` | `memory_write_page`, `memory_read_page` |
+| `pages.patch` | `memory_patch_page` |
| `pages.read` | `memory_read_page` |
| `pages.delete` | `memory_delete_page` |
| `query` | `memory_query` |
diff --git a/companions/ai-memory-ts/docs/arguments.md b/companions/ai-memory-ts/docs/arguments.md
index 4c764020..8b3cbbba 100644
--- a/companions/ai-memory-ts/docs/arguments.md
+++ b/companions/ai-memory-ts/docs/arguments.md
@@ -28,6 +28,18 @@ Methods: `pages.write`, `pages.update`
| `expected_page_id` | `expectedPageId` |
| `create_only` | `createOnly` |
+## `memory_patch_page`
+
+Methods: `pages.patch`
+
+| Wire name | SDK name |
+|---|---|
+| `workspace` | `workspace` |
+| `project` | `project` |
+| `path` | `path` |
+| `expected_page_id` | `expectedPageId` |
+| `edits` | `edits` |
+
## `memory_read_page`
Methods: `pages.read`, `pages.update`
diff --git a/companions/ai-memory-ts/schema/tools.json b/companions/ai-memory-ts/schema/tools.json
index 5146a071..670a6c55 100644
--- a/companions/ai-memory-ts/schema/tools.json
+++ b/companions/ai-memory-ts/schema/tools.json
@@ -548,6 +548,39 @@
"to_workspace"
]
},
+ "memory_patch_page": {
+ "properties": {
+ "edits": {
+ "items": {
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "expected_page_id": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "project": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "workspace": {
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ },
+ "required": [
+ "edits",
+ "expected_page_id",
+ "path"
+ ]
+ },
"memory_query": {
"properties": {
"answer": {
diff --git a/companions/ai-memory-ts/src/client.ts b/companions/ai-memory-ts/src/client.ts
index 1c708a65..4c2173f6 100644
--- a/companions/ai-memory-ts/src/client.ts
+++ b/companions/ai-memory-ts/src/client.ts
@@ -64,6 +64,9 @@ import type {
Page,
PageChange,
PageMetadata,
+ PagePatchEdit,
+ PatchPageArgs,
+ PatchPageResult,
PopMessageArgs,
ProjectQueryArgs,
PopMessageResult,
@@ -218,6 +221,66 @@ export class PagesNamespace {
};
}
+ /**
+ * Atomically patch an existing page by Markdown heading while preserving
+ * all frontmatter. Every edit is resolved against the same base version.
+ */
+ async patch(args: PatchPageArgs, options?: CallOptions): Promise<PatchPageResult> {
+ const where = "pages.patch";
+ const a = argsObject(args, where);
+ const scope = this.#core.scope(a.scope, where);
+ requireText(a.path, "path", where);
+ requireText(a.expectedPageId, "expectedPageId", where);
+ if (!Array.isArray(a.edits) || a.edits.length === 0) {
+ throw new ArgumentError(`${where}: edits must be a non-empty array`);
+ }
+ const edits = a.edits.map((edit: PagePatchEdit, index: number) => {
+ const item = argsObject(edit, `${where}.edits[${index}]`);
+ requireText(item.op, "op", `${where}.edits[${index}]`);
+ if (typeof item.content !== "string") {
+ throw new ArgumentError(`${where}.edits[${index}]: content must be a string`);
+ }
+ if (item.op === "replace_section") {
+ requireText(item.anchor, "anchor", `${where}.edits[${index}]`);
+ requireText(item.sectionSha256, "sectionSha256", `${where}.edits[${index}]`);
+ } else if (item.op === "add_section") {
+ requireText(item.anchor, "anchor", `${where}.edits[${index}]`);
+ } else if (item.op === "append") {
+ if (item.target === "section") requireText(item.anchor, "anchor", `${where}.edits[${index}]`);
+ else if (item.target !== "end_of_page") {
+ throw new ArgumentError(`${where}.edits[${index}]: unknown append target`);
+ }
+ } else {
+ throw new ArgumentError(`${where}.edits[${index}]: unknown operation`);
+ }
+ return wire({
+ op: item.op,
+ target: "target" in item ? item.target : undefined,
+ anchor: item.anchor,
+ section_sha256: "sectionSha256" in item ? item.sectionSha256 : undefined,
+ content: item.content,
+ });
+ });
+ const decoded = await this.#core.invoke(
+ "memory_patch_page",
+ wire({
+ ...scopeWire(scope),
+ path: a.path,
+ expected_page_id: a.expectedPageId,
+ edits,
+ }),
+ true,
+ options,
+ );
+ const o = record(decoded, "memory_patch_page");
+ return {
+ pageId: str(o, "page_id", "memory_patch_page"),
+ path: str(o, "path", "memory_patch_page"),
+ checkpoint: nullableStr(o, "checkpoint", "memory_patch_page"),
+ raw: o,
+ };
+ }
+
/**
* Read one page by exact `path`, or the top hit of a `query`.
*
@@ -250,6 +313,14 @@ export class PagesNamespace {
);
const o = record(decoded, "memory_read_page");
const frontmatter = o["frontmatter"];
+ const sections = requiredList(o, "sections", "memory_read_page", (value, where) => {
+ const section = record(value, where);
+ return {
+ anchor: str(section, "anchor", where),
+ level: num(section, "level", where),
+ sha256: str(section, "sha256", where),
+ };
+ });
return {
pageId: str(o, "page_id", "memory_read_page"),
path: str(o, "path", "memory_read_page"),
@@ -259,6 +330,8 @@ export class PagesNamespace {
frontmatter !== null && typeof frontmatter === "object" && !Array.isArray(frontmatter)
? (frontmatter as Raw)
: {},
+ sections,
+ sectionsTruncated: bool(o, "sections_truncated", "memory_read_page"),
related: Array.isArray(o["related"])
? list(o, "related", "memory_read_page", relatedPage)
: undefined,
diff --git a/companions/ai-memory-ts/src/coverage.ts b/companions/ai-memory-ts/src/coverage.ts
index 944ef109..c537da5d 100644
--- a/companions/ai-memory-ts/src/coverage.ts
+++ b/companions/ai-memory-ts/src/coverage.ts
@@ -57,6 +57,12 @@ export const TOOL_COVERAGE: Readonly<Record<string, ToolClassification>> = {
"create_only",
],
},
+ memory_patch_page: {
+ status: "wrapped",
+ methods: ["pages.patch"],
+ phase: 2,
+ sends: [...SCOPE, "path", "expected_page_id", "edits"],
+ },
memory_read_page: {
status: "wrapped",
methods: ["pages.read", "pages.update"],
diff --git a/companions/ai-memory-ts/src/types.ts b/companions/ai-memory-ts/src/types.ts
index ab87023f..26026465 100644
--- a/companions/ai-memory-ts/src/types.ts
+++ b/companions/ai-memory-ts/src/types.ts
@@ -102,6 +102,70 @@ export interface WritePageResult {
readonly raw: Raw;
}
+/** A bounded heading token returned by `memory_read_page`. */
+export interface PageSection {
+ /** Heading text without Markdown markers. */
+ readonly anchor: string;
+ /** ATX heading level, 1 through 6. */
+ readonly level: number;
+ /** SHA-256 of the exact section bytes, including its heading. */
+ readonly sha256: string;
+}
+
+/** One atomic anchored page edit. */
+export type PagePatchEdit =
+ | {
+ /** Append operation. */
+ op: "append";
+ /** Insert before the next same-or-higher-level heading. */
+ target: "section";
+ /** Unique existing heading. */
+ anchor: string;
+ /** Markdown to append. */
+ content: string;
+ }
+ | {
+ /** Append operation. */
+ op: "append";
+ /** Insert at the end of the page. */
+ target: "end_of_page";
+ /** An EOF append has no heading anchor. */
+ anchor?: never;
+ /** Markdown to append. */
+ content: string;
+ }
+ | {
+ /** Add a new section at EOF. */
+ op: "add_section";
+ /** Unique ATX level 2-6 heading, for example `## Decisions`. */
+ anchor: string;
+ /** New section body. */
+ content: string;
+ }
+ | {
+ /** Replace one existing section body. */
+ op: "replace_section";
+ /** Unique existing heading. */
+ anchor: string;
+ /** Exact section token returned by {@link Page.sections}. */
+ sectionSha256: string;
+ /** Replacement section body, excluding the heading. */
+ content: string;
+ };
+
+/** Arguments of {@link PagesNamespace.patch}. */
+export interface PatchPageArgs extends ScopedArgs {
+ /** Existing page path. */
+ path: string;
+ /** Required latest page version returned by a read or mutation. */
+ expectedPageId: string;
+ /** Bounded batch resolved against one base body and committed atomically. */
+ edits: readonly PagePatchEdit[];
+}
+
+/** Result of {@link PagesNamespace.patch}. */
+export type PatchPageResult = WritePageResult;
+
/** Options shared by both forms of {@link ReadPageArgs}. */
export interface ReadPageBase extends ScopedArgs {
/** Also walk the link graph and return the reachable pages in `related`. */
@@ -157,6 +221,10 @@ export interface Page {
readonly body: UntrustedText;
/** Parsed frontmatter (tags, tier, pinned and other metadata). Untrusted. */
readonly frontmatter: Readonly<Record<string, unknown>>;
+ /** Bounded heading hashes for anchored patches. */
+ readonly sections: readonly PageSection[];
+ /** True when the page has more sections than the response cap. */
+ readonly sectionsTruncated: boolean;
/** Pages reachable through links, present only with `includeRelated`. */
readonly related: readonly RelatedPage[] | undefined;
/** The server's decoded JSON. */
diff --git a/companions/ai-memory-ts/test/integration/pages.test.ts b/companions/ai-memory-ts/test/integration/pages.test.ts
index c546bf39..634b8c35 100644
--- a/companions/ai-memory-ts/test/integration/pages.test.ts
+++ b/companions/ai-memory-ts/test/integration/pages.test.ts
@@ -129,6 +129,52 @@ describe("pages against a real server", () => {
assert.equal((await memory.pages.read({ path: "notes/meta.md" })).body, "# Meta\nother writer");
});
+ it("patch replaces one section and preserves frontmatter", async () => {
+ await memory.pages.write({
+ path: "notes/patch.md",
+ body: "# Status\n## Log\nold\n## Open\none\n",
+ tags: ["living"],
+ abstract: "preserved",
+ });
+ const base = await memory.pages.read({ path: "notes/patch.md" });
+ const log = base.sections.find((section) => section.anchor === "Log");
+ assert.ok(log !== undefined);
+ const patched = await memory.pages.patch({
+ path: "notes/patch.md",
+ expectedPageId: base.pageId,
+ edits: [
+ {
+ op: "replace_section",
+ anchor: "Log",
+ sectionSha256: log.sha256,
+ content: "new",
+ },
+ { op: "append", target: "end_of_page", content: "tail" },
+ ],
+ });
+ const page = await memory.pages.read({ path: "notes/patch.md" });
+ assert.equal(page.pageId, patched.pageId);
+ assert.equal(page.body, "# Status\n## Log\nnew\n## Open\none\ntail\n");
+ assert.deepEqual(page.frontmatter["tags"], ["living"]);
+ assert.equal(page.frontmatter["abstract"], "preserved");
+ await assert.rejects(
+ memory.pages.patch({
+ path: "notes/patch.md",
+ expectedPageId: patched.pageId,
+ edits: [
+ {
+ op: "replace_section",
+ anchor: "Log",
+ sectionSha256: log.sha256,
+ content: "stale",
+ },
+ ],
+ }),
+ InvalidParamsError,
+ );
+ assert.doesNotMatch((await memory.pages.read({ path: "notes/patch.md" })).body, /stale/);
+ });
+
it("superseded versions come back only when asked", async () => {
await memory.pages.write({ path: "notes/versions.md", body: "# Versions\nzebra one" });
await memory.pages.write({ path: "notes/versions.md", body: "# Versions\nzebra two" });
diff --git a/companions/ai-memory-ts/test/support/payloads.ts b/companions/ai-memory-ts/test/support/payloads.ts
index 62cab684..d06a2049 100644
--- a/companions/ai-memory-ts/test/support/payloads.ts
+++ b/companions/ai-memory-ts/test/support/payloads.ts
@@ -11,6 +11,7 @@ export const MESSAGE_ID = "01a135d1-3ecf-79d3-a65b-c0094a535f63";
export const SESSION_ID = "b2f3725b-265c-5da4-9866-35db4765d1b9";
export const write = { page_id: NEXT_PAGE_ID, path: "notes/retries.md", checkpoint: "b04977fb" };
+export const patch = write;
export const read = {
path: "notes/retries.md",
@@ -30,6 +31,8 @@ export const read = {
type: "Note",
generated: { by: "process:ai-memory/3.0.0", at: "2026-10-13T15:10:47Z" },
},
+ sections: [{ anchor: "Retry policy", level: 1, sha256: "a".repeat(64) }],
+ sections_truncated: false,
};
export const del = {
diff --git a/companions/ai-memory-ts/test/unit/client.test.ts b/companions/ai-memory-ts/test/unit/client.test.ts
index 5d62ca1f..d8d6daf2 100644
--- a/companions/ai-memory-ts/test/unit/client.test.ts
+++ b/companions/ai-memory-ts/test/unit/client.test.ts
@@ -94,6 +94,40 @@ describe("pages", () => {
);
});
+ it("patch sends typed anchored edits and decodes the new version", async () => {
+ const { server, memory } = setup();
+ server.tools.set("memory_patch_page", () => payloads.patch);
+ const result = await memory.pages.patch({
+ path: "notes/retries.md",
+ expectedPageId: payloads.PAGE_ID,
+ edits: [
+ { op: "append", target: "section", anchor: "Log", content: "next" },
+ {
+ op: "replace_section",
+ anchor: "Open",
+ sectionSha256: "a".repeat(64),
+ content: "none",
+ },
+ ],
+ });
+ assert.deepEqual(server.lastArgs(), {
+ workspace: "demo",
+ project: "app",
+ path: "notes/retries.md",
+ expected_page_id: payloads.PAGE_ID,
+ edits: [
+ { op: "append", target: "section", anchor: "Log", content: "next" },
+ {
+ op: "replace_section",
+ anchor: "Open",
+ section_sha256: "a".repeat(64),
+ content: "none",
+ },
+ ],
+ });
+ assert.equal(result.pageId, payloads.NEXT_PAGE_ID);
+ });
+
it("read by path or query, never both, and decodes the page", async () => {
const { server, memory } = setup();
server.tools.set("memory_read_page", () => payloads.read);
@@ -101,6 +135,8 @@ describe("pages", () => {
assert.deepEqual(server.lastArgs(), { workspace: "demo", project: "app", path: "notes/retries.md" });
assert.equal(page.pageId, payloads.PAGE_ID);
assert.equal(page.body, payloads.read.body);
+ assert.equal(page.sections[0]?.anchor, "Retry policy");
+ assert.equal(page.sectionsTruncated, false);
assert.equal(page.related, undefined);
await memory.pages.read({ query: "retry", includeRelated: true, relatedDepth: 2 });
assert.deepEqual(server.lastArgs(), {
@@ -546,6 +582,16 @@ describe("wire names", () => {
expectedPageId: "v",
}),
memory.pages.write({ path: "p", body: "b", createOnly: true }),
+ memory.pages.patch({
+ path: "p",
+ expectedPageId: "v",
+ edits: [
+ { op: "append", target: "section", anchor: "A", content: "a" },
+ { op: "append", target: "end_of_page", content: "b" },
+ { op: "add_section", anchor: "## B", content: "c" },
+ { op: "replace_section", anchor: "C", sectionSha256: "h", content: "d" },
+ ],
+ }),
memory.pages.read({ path: "p", includeRelated: true, relatedDepth: 2 }),
memory.pages.read({ query: "q" }),
memory.pages.delete({ path: "p", expectedPageId: "v" }),
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index a643f1a2..23a26587 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -48,6 +48,7 @@ getrandom.workspace = true
# timestamps + delta against now). The rest of the crate doesn't
# need a clock dep.
jiff.workspace = true
+sha2.workspace = true
[dev-dependencies]
ai-memory-core.workspace = true
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index 919f91f1..374a7729 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -15,6 +15,7 @@ pub mod auth;
pub mod human_auth;
pub mod identity;
pub mod metrics;
+mod page_patch;
pub mod self_service_keys;
mod server;
pub mod session_management;
diff --git a/crates/ai-memory-mcp/src/page_patch.rs b/crates/ai-memory-mcp/src/page_patch.rs
new file mode 100644
index 00000000..977058dd
--- /dev/null
+++ b/crates/ai-memory-mcp/src/page_patch.rs
@@ -0,0 +1,500 @@
+use std::collections::{HashMap, HashSet};
+use std::ops::Range;
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+pub(crate) const MAX_EDITS: usize = 32;
+pub(crate) const MAX_EDIT_CHARS: usize = 64 * 1024;
+pub(crate) const MAX_CHANGED_CHARS: usize = 256 * 1024;
+pub(crate) const MAX_SECTION_HASHES: usize = 100;
+
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+pub(crate) struct SectionHash {
+ pub anchor: String,
+ pub level: u8,
+ pub sha256: String,
+}
+
+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum AppendTarget {
+ Section,
+ EndOfPage,
+}
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(tag = "op", rename_all = "snake_case")]
+pub(crate) enum PagePatchEdit {
+ Append {
+ target: AppendTarget,
+ #[serde(default)]
+ anchor: Option<String>,
+ content: String,
+ },
+ AddSection {
+ anchor: String,
+ content: String,
+ },
+ ReplaceSection {
+ anchor: String,
+ section_sha256: String,
+ content: String,
+ },
+}
+
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub(crate) enum PatchError {
+ #[error("at least one edit is required")]
+ Empty,
+ #[error("too many edits (maximum {MAX_EDITS})")]
+ TooMany,
+ #[error("edit content is too large")]
+ ContentTooLarge,
+ #[error("combined edit content is too large")]
+ BatchTooLarge,
+ #[error("append target section requires an anchor")]
+ MissingAnchor,
+ #[error("append target end_of_page cannot have an anchor")]
+ UnexpectedAnchor,
+ #[error("anchor not found: {0}")]
+ AnchorNotFound(String),
+ #[error("anchor is ambiguous: {0}")]
+ AmbiguousAnchor(String),
+ #[error("more than one edit targets anchor: {0}")]
+ DuplicateTarget(String),
+ #[error("add_section anchor must be one ATX level 2-6 heading")]
+ InvalidNewHeading,
+ #[error("heading already exists: {0}")]
+ HeadingExists(String),
+ #[error("section precondition failed: {0}")]
+ SectionPreconditionFailed(String),
+ #[error("edits overlap")]
+ Overlapping,
+}
+
+#[derive(Debug, Clone)]
+struct Section {
+ anchor: String,
+ normalized: String,
+ level: u8,
+ whole: Range<usize>,
+ content: Range<usize>,
+}
+
+#[derive(Debug)]
+struct Change {
+ range: Range<usize>,
+ replacement: String,
+}
+
+pub(crate) fn section_hashes(body: &str) -> (Vec<SectionHash>, bool) {
+ let sections = parse_sections(body);
+ let truncated = sections.len() > MAX_SECTION_HASHES;
+ let hashes = sections
+ .into_iter()
+ .take(MAX_SECTION_HASHES)
+ .map(|section| SectionHash {
+ anchor: section.anchor,
+ level: section.level,
+ sha256: hash(&body.as_bytes()[section.whole]),
+ })
+ .collect();
+ (hashes, truncated)
+}
+
+pub(crate) fn apply(body: &str, edits: &[PagePatchEdit]) -> Result<String, PatchError> {
+ validate_bounds(edits)?;
+ let sections = parse_sections(body);
+ let mut by_anchor: HashMap<&str, Vec<&Section>> = HashMap::new();
+ for section in &sections {
+ by_anchor
+ .entry(section.normalized.as_str())
+ .or_default()
+ .push(section);
+ }
+
+ let mut targets = HashSet::new();
+ let mut added = HashSet::new();
+ let mut changes = Vec::with_capacity(edits.len());
+ for edit in edits {
+ let change = match edit {
+ PagePatchEdit::Append {
+ target: AppendTarget::EndOfPage,
+ anchor,
+ content,
+ } => {
+ if anchor
+ .as_deref()
+ .is_some_and(|value| !value.trim().is_empty())
+ {
+ return Err(PatchError::UnexpectedAnchor);
+ }
+ if !targets.insert("\0eof".to_string()) {
+ return Err(PatchError::DuplicateTarget("end_of_page".into()));
+ }
+ Change {
+ range: body.len()..body.len(),
+ replacement: appended(body, content),
+ }
+ }
+ PagePatchEdit::Append {
+ target: AppendTarget::Section,
+ anchor,
+ content,
+ } => {
+ let raw = anchor.as_deref().ok_or(PatchError::MissingAnchor)?;
+ let section = find_section(&by_anchor, raw)?;
+ if !targets.insert(section.normalized.clone()) {
+ return Err(PatchError::DuplicateTarget(section.anchor.clone()));
+ }
+ Change {
+ range: section.whole.end..section.whole.end,
+ replacement: appended(&body[section.whole.clone()], content),
+ }
+ }
+ PagePatchEdit::AddSection { anchor, content } => {
+ let (level, title) = parse_single_heading(anchor)?;
+ let normalized = normalize_anchor(&title);
+ if by_anchor.contains_key(normalized.as_str()) || !added.insert(normalized.clone())
+ {
+ return Err(PatchError::HeadingExists(title));
+ }
+ targets.insert(format!("\0add:{normalized}"));
+ let heading = format!("{} {}", "#".repeat(level as usize), title);
+ Change {
+ range: body.len()..body.len(),
+ replacement: appended(body, &format!("{heading}\n{content}")),
+ }
+ }
+ PagePatchEdit::ReplaceSection {
+ anchor,
+ section_sha256,
+ content,
+ } => {
+ let section = find_section(&by_anchor, anchor)?;
+ if !targets.insert(section.normalized.clone()) {
+ return Err(PatchError::DuplicateTarget(section.anchor.clone()));
+ }
+ if !constant_time_eq(
+ section_sha256.trim(),
+ &hash(&body.as_bytes()[section.whole.clone()]),
+ ) {
+ return Err(PatchError::SectionPreconditionFailed(
+ section.anchor.clone(),
+ ));
+ }
+ Change {
+ range: section.content.clone(),
+ replacement: section_content(content),
+ }
+ }
+ };
+ changes.push(change);
+ }
+
+ changes.sort_by_key(|change| (change.range.start, change.range.end));
+ let mut merged: Vec<Change> = Vec::with_capacity(changes.len());
+ for change in changes {
+ if let Some(previous) = merged.last_mut()
+ && previous.range.is_empty()
+ && change.range == previous.range
+ {
+ previous.replacement.push_str(&change.replacement);
+ continue;
+ }
+ if merged
+ .last()
+ .is_some_and(|previous| previous.range.end > change.range.start)
+ {
+ return Err(PatchError::Overlapping);
+ }
+ merged.push(change);
+ }
+ let mut result = body.to_owned();
+ for change in merged.into_iter().rev() {
+ result.replace_range(change.range, &change.replacement);
+ }
+ Ok(result)
+}
+
+fn validate_bounds(edits: &[PagePatchEdit]) -> Result<(), PatchError> {
+ if edits.is_empty() {
+ return Err(PatchError::Empty);
+ }
+ if edits.len() > MAX_EDITS {
+ return Err(PatchError::TooMany);
+ }
+ let sizes = edits.iter().map(|edit| match edit {
+ PagePatchEdit::Append { content, .. }
+ | PagePatchEdit::AddSection { content, .. }
+ | PagePatchEdit::ReplaceSection { content, .. } => content.chars().count(),
+ });
+ let mut total = 0usize;
+ for size in sizes {
+ if size > MAX_EDIT_CHARS {
+ return Err(PatchError::ContentTooLarge);
+ }
+ total = total.saturating_add(size);
+ }
+ if total > MAX_CHANGED_CHARS {
+ return Err(PatchError::BatchTooLarge);
+ }
+ Ok(())
+}
+
+fn find_section<'a>(
+ sections: &'a HashMap<&str, Vec<&Section>>,
+ anchor: &str,
+) -> Result<&'a Section, PatchError> {
+ let normalized = normalize_anchor(anchor);
+ match sections.get(normalized.as_str()).map(Vec::as_slice) {
+ None | Some([]) => Err(PatchError::AnchorNotFound(anchor.to_owned())),
+ Some([section]) => Ok(section),
+ Some(_) => Err(PatchError::AmbiguousAnchor(anchor.to_owned())),
+ }
+}
+
+fn parse_sections(body: &str) -> Vec<Section> {
+ let mut headings = Vec::new();
+ let mut offset = 0usize;
+ let mut fence: Option<(char, usize)> = None;
+ for line_with_newline in body.split_inclusive('\n') {
+ let line = line_with_newline
+ .strip_suffix('\n')
+ .unwrap_or(line_with_newline);
+ if let Some((marker, width)) = fence {
+ if closes_fence(line, marker, width) {
+ fence = None;
+ }
+ } else if let Some(marker) = fence_marker(line) {
+ fence = Some(marker);
+ } else if let Some((level, anchor)) = heading(line) {
+ headings.push((offset, offset + line_with_newline.len(), level, anchor));
+ }
+ offset += line_with_newline.len();
+ }
+ headings
+ .iter()
+ .enumerate()
+ .map(|(index, (start, content_start, level, anchor))| {
+ let end = headings[index + 1..]
+ .iter()
+ .find(|(_, _, next_level, _)| next_level <= level)
+ .map(|(next_start, _, _, _)| *next_start)
+ .unwrap_or(body.len());
+ Section {
+ anchor: anchor.clone(),
+ normalized: normalize_anchor(anchor),
+ level: *level,
+ whole: *start..end,
+ content: *content_start..end,
+ }
+ })
+ .collect()
+}
+
+fn heading(line: &str) -> Option<(u8, String)> {
+ let trimmed = line
+ .strip_prefix(" ")
+ .unwrap_or(line.trim_start_matches(' '));
+ if line.len() - trimmed.len() > 3 {
+ return None;
+ }
+ let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();
+ if !(1..=6).contains(&hashes)
+ || !trimmed
+ .as_bytes()
+ .get(hashes)
+ .is_none_or(u8::is_ascii_whitespace)
+ {
+ return None;
+ }
+ let mut title = trimmed[hashes..].trim().to_owned();
+ if let Some(without_closing) = title.strip_suffix('#') {
+ title = without_closing.trim_end_matches('#').trim_end().to_owned();
+ }
+ (!title.is_empty()).then_some((hashes as u8, title))
+}
+
+fn fence_marker(line: &str) -> Option<(char, usize)> {
+ let trimmed = line.trim_start_matches(' ');
+ if line.len() - trimmed.len() > 3 {
+ return None;
+ }
+ let marker = trimmed.chars().next()?;
+ if marker != '`' && marker != '~' {
+ return None;
+ }
+ let width = trimmed.chars().take_while(|c| *c == marker).count();
+ (width >= 3).then_some((marker, width))
+}
+
+fn closes_fence(line: &str, marker: char, width: usize) -> bool {
+ let trimmed = line.trim_start_matches(' ');
+ if line.len() - trimmed.len() > 3 {
+ return false;
+ }
+ let count = trimmed
+ .chars()
+ .take_while(|candidate| *candidate == marker)
+ .count();
+ count >= width && trimmed[count..].trim().is_empty()
+}
+
+fn parse_single_heading(raw: &str) -> Result<(u8, String), PatchError> {
+ if raw.contains('\n') {
+ return Err(PatchError::InvalidNewHeading);
+ }
+ let (level, title) = heading(raw).ok_or(PatchError::InvalidNewHeading)?;
+ if level == 1 {
+ return Err(PatchError::InvalidNewHeading);
+ }
+ Ok((level, title))
+}
+
+fn normalize_anchor(raw: &str) -> String {
+ let title = heading(raw)
+ .map(|(_, title)| title)
+ .unwrap_or_else(|| raw.to_owned());
+ title
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .to_lowercase()
+}
+
+fn appended(existing: &str, content: &str) -> String {
+ let prefix = if existing.is_empty() || existing.ends_with('\n') {
+ ""
+ } else {
+ "\n"
+ };
+ let suffix = if content.ends_with('\n') { "" } else { "\n" };
+ format!("{prefix}{content}{suffix}")
+}
+
+fn section_content(content: &str) -> String {
+ let suffix = if content.is_empty() || content.ends_with('\n') {
+ ""
+ } else {
+ "\n"
+ };
+ format!("{content}{suffix}")
+}
+
+fn hash(bytes: &[u8]) -> String {
+ format!("{:x}", Sha256::digest(bytes))
+}
+
+fn constant_time_eq(left: &str, right: &str) -> bool {
+ left.len() == right.len()
+ && left
+ .bytes()
+ .zip(right.bytes())
+ .fold(0u8, |different, (a, b)| different | (a ^ b))
+ == 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hashes_ignore_headings_inside_fences_and_flag_duplicates() {
+ let body = "# T\n## Same\na\n```md\n## Hidden\n```\n## Same\nb\n";
+ let (sections, truncated) = section_hashes(body);
+ assert!(!truncated);
+ assert_eq!(sections.iter().filter(|s| s.anchor == "Same").count(), 2);
+ assert!(!sections.iter().any(|s| s.anchor == "Hidden"));
+ assert_eq!(
+ apply(
+ body,
+ &[PagePatchEdit::Append {
+ target: AppendTarget::Section,
+ anchor: Some("same".into()),
+ content: "x".into(),
+ }]
+ ),
+ Err(PatchError::AmbiguousAnchor("same".into()))
+ );
+ }
+
+ #[test]
+ fn replaces_one_section_only_with_its_hash() {
+ let body = "# T\n## One\nold\n### Child\nkept in section\n## Two\nother\n";
+ let hash = section_hashes(body)
+ .0
+ .into_iter()
+ .find(|section| section.anchor == "One")
+ .unwrap()
+ .sha256;
+ let patched = apply(
+ body,
+ &[PagePatchEdit::ReplaceSection {
+ anchor: "## One".into(),
+ section_sha256: hash,
+ content: "new".into(),
+ }],
+ )
+ .unwrap();
+ assert_eq!(patched, "# T\n## One\nnew\n## Two\nother\n");
+ }
+
+ #[test]
+ fn stale_hash_and_conflicting_targets_fail_without_output() {
+ let body = "# T\n## One\nold\n";
+ assert!(matches!(
+ apply(
+ body,
+ &[PagePatchEdit::ReplaceSection {
+ anchor: "One".into(),
+ section_sha256: "0".repeat(64),
+ content: "new".into(),
+ }]
+ ),
+ Err(PatchError::SectionPreconditionFailed(_))
+ ));
+ let edits = [
+ PagePatchEdit::Append {
+ target: AppendTarget::Section,
+ anchor: Some("One".into()),
+ content: "a".into(),
+ },
+ PagePatchEdit::Append {
+ target: AppendTarget::Section,
+ anchor: Some("one".into()),
+ content: "b".into(),
+ },
+ ];
+ assert!(matches!(
+ apply(body, &edits),
+ Err(PatchError::DuplicateTarget(_))
+ ));
+ }
+
+ #[test]
+ fn appends_to_section_or_page_and_adds_a_unique_section() {
+ let body = "# T\n## Log\none\n## Tail\ntwo";
+ let patched = apply(
+ body,
+ &[
+ PagePatchEdit::Append {
+ target: AppendTarget::Section,
+ anchor: Some("Log".into()),
+ content: "next".into(),
+ },
+ PagePatchEdit::AddSection {
+ anchor: "## Fresh".into(),
+ content: "new".into(),
+ },
+ ],
+ )
+ .unwrap();
+ assert_eq!(
+ patched,
+ "# T\n## Log\none\nnext\n## Tail\ntwo\n## Fresh\nnew\n"
+ );
+ }
+}
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index b41a86e1..c79f45d1 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -373,6 +373,11 @@ should be proposed from a completed session, or at explicit wrap-up \
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_patch_page` — when changing or appending to one or more Markdown \
+ sections of an existing page. Read the page first, then pass its required \
+ `page_id` and the returned section hash for every `replace_section`. The \
+ whole batch is atomic, preserves frontmatter, and rejects missing or \
+ ambiguous headings; use `memory_write_page` for a full replacement.\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 \
@@ -1714,6 +1719,24 @@ struct ReadPageArgs {
related_depth: Option<u8>,
}
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+struct PatchPageArgs {
+ /// Existing page path to patch.
+ path: String,
+ /// Required latest page version from `memory_read_page`. The entire batch
+ /// fails if another writer changed or deleted the page.
+ expected_page_id: String,
+ /// Anchored edits, all resolved against the same captured base body.
+ edits: Vec<crate::page_patch::PagePatchEdit>,
+ /// Project containing the existing page. Static clients pass this with
+ /// `workspace`; partial explicit scope fails closed.
+ #[serde(default)]
+ project: Option<String>,
+ /// Workspace containing the existing page, together with `project`.
+ #[serde(default)]
+ workspace: Option<String>,
+}
+
/// Bounds for `memory_read_session_observations`. The defaults keep one call
/// well under a context window; the ceilings match what the store keeps per
/// body (16 KiB) so a caller can always read a whole observation in one go.
@@ -4939,6 +4962,139 @@ impl AiMemoryServer {
ok_json(&result)
}
+ /// Apply a bounded batch of heading-anchored edits to an existing page.
+ #[tool(
+ annotations(
+ title = "Patch memory page",
+ read_only_hint = false,
+ destructive_hint = true,
+ idempotent_hint = false,
+ open_world_hint = false
+ ),
+ description = "Patch an existing Markdown page without re-emitting its full body or metadata. Requires `expected_page_id` from `memory_read_page`; every edit is materialized against that one base version and the whole batch either commits through the normal write path or writes nothing. `append` requires `target: section` plus an unambiguous heading anchor, or `target: end_of_page` with no anchor. `add_section` requires a unique ATX level 2-6 heading as its anchor. `replace_section` requires both an unambiguous heading anchor and the exact `section_sha256` returned by `memory_read_page`. Headings inside fenced code are ignored. All existing frontmatter is preserved. Static clients pass `workspace` and `project` together."
+ )]
+ async fn memory_patch_page(
+ &self,
+ Parameters(args): Parameters<PatchPageArgs>,
+ OptionalParts(parts): OptionalParts,
+ ) -> Result<CallToolResult, McpError> {
+ let Some(wiki) = self.wiki.as_ref() else {
+ return Err(McpError::internal_error(
+ "memory_patch_page requires the server to be built with a wiki handle",
+ None,
+ ));
+ };
+ let expected = PageId::from_str(args.expected_page_id.trim()).map_err(|error| {
+ McpError::invalid_params(format!("invalid expected_page_id: {error}"), None)
+ })?;
+ let path = PagePath::new(args.path)
+ .and_then(|path| path.ensure_portable().map(|()| path))
+ .map_err(|error| McpError::invalid_params(format!("invalid path: {error}"), None))?;
+ let path = self.place_slot_write(path, &parts).await?;
+ let aps_actor = Self::actor_key_from_parts(Some(&parts));
+ let (workspace_id, project_id) = self
+ .effective_ids_for_mutation_args_with_actor(
+ args.workspace.as_deref(),
+ args.project.as_deref(),
+ &aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
+ )
+ .await?;
+ let current = self
+ .reader
+ .latest_page_id_by_ids(workspace_id, project_id, path.to_string())
+ .await
+ .map_err(|error| McpError::internal_error(error.to_string(), None))?;
+ if current != Some(expected) {
+ return Err(precondition_failed(
+ &path,
+ Some(ai_memory_store::PagePrecondition::Latest(expected)),
+ current,
+ ));
+ }
+ let page = wiki
+ .read_page(workspace_id, project_id, &path)
+ .map_err(|error| {
+ if is_missing_wiki_file(&error) {
+ McpError::invalid_params(
+ format!("page {} does not exist on disk", path.as_str()),
+ Some(serde_json::json!({
+ "reason": "not_found",
+ "path": path.as_str(),
+ })),
+ )
+ } else {
+ McpError::internal_error(error.to_string(), None)
+ }
+ })?;
+ let body = crate::page_patch::apply(&page.body, &args.edits)
+ .map_err(|error| page_patch_error(&path, error))?;
+ let tier_name = page
+ .frontmatter
+ .get("tier")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("semantic");
+ let tier = tier_name.parse::<Tier>().map_err(|_| {
+ McpError::invalid_params(
+ format!("existing page has unknown tier '{tier_name}'"),
+ Some(serde_json::json!({ "reason": "invalid_existing_page" })),
+ )
+ })?;
+ let pinned = page
+ .frontmatter
+ .get("pinned")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+ let actor = crate::actor::actor_from_parts(&parts);
+ let author_id = crate::actor::author_id_from_parts(&parts);
+ let skip_webhooks = crate::actor::skip_webhooks_from_parts(&parts);
+ let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {
+ Some(ai_memory_wiki::AdmissionContext {
+ op: ai_memory_wiki::AdmissionOp::WritePage,
+ skip_webhooks,
+ ..ai_memory_wiki::AdmissionContext::default()
+ })
+ } else {
+ None
+ };
+ let result = wiki
+ .write_page_if(
+ WritePageRequest {
+ workspace_id,
+ project_id,
+ path: path.clone(),
+ frontmatter: page.frontmatter,
+ body,
+ tier,
+ pinned,
+ title: None,
+ admission_ctx,
+ author_id,
+ actor,
+ evidence: Vec::new(),
+ },
+ ai_memory_store::PagePrecondition::Latest(expected),
+ )
+ .await
+ .map_err(|error| McpError::internal_error(error.to_string(), None))?;
+ let page_id = match result {
+ ai_memory_wiki::ConditionalWrite::Written(page_id) => page_id,
+ ai_memory_wiki::ConditionalWrite::Mismatch { current } => {
+ return Err(precondition_failed(
+ &path,
+ Some(ai_memory_store::PagePrecondition::Latest(expected)),
+ current,
+ ));
+ }
+ };
+ let checkpoint = checkpoint_or_warn(wiki, format!("memory_patch_page: {}", path.as_str()));
+ ok_json(&serde_json::json!({
+ "page_id": page_id.to_string(),
+ "path": path.to_string(),
+ "checkpoint": checkpoint,
+ }))
+ }
+
/// Fetch the full body of a single wiki page.
#[tool(
annotations(
@@ -4962,8 +5118,10 @@ impl AiMemoryServer {
Follow the client-aware project-scope instructions: static clients pass \
`workspace` + `project` together for every project-scoped call. Use \
this when the user asks to read, open, or show a specific page by \
- name or topic — not just snippets. Returns `{ path, title, body, \
- frontmatter }` (plus `served_from` when a missing markdown file is \
+ name or topic — not just snippets. Returns `{ path, page_id, title, \
+ body, frontmatter, sections, sections_truncated }`; each bounded \
+ section entry has its heading `anchor`, `level`, and exact-content \
+ `sha256` for `memory_patch_page`. Also returns `served_from` when a missing markdown file is \
served from the DB fallback, and `expired: true` when the page's \
`expires_at` TTL has passed: an exact-path read still returns such a \
page, which `memory_query` and `memory_recent` no longer surface). \
@@ -5139,12 +5297,15 @@ impl AiMemoryServer {
// frontmatter title was never filled otherwise read back
// titleless despite a proper `# Heading` (#599).
let title = ai_memory_wiki::derive_title(&md.frontmatter, &md.body, &page_path);
+ let (sections, sections_truncated) = crate::page_patch::section_hashes(&md.body);
ok_json(&annotate(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,
+ "sections": sections,
+ "sections_truncated": sections_truncated,
})))
}
Err(disk_err) if is_missing_wiki_file(&disk_err) => {
@@ -5163,12 +5324,16 @@ impl AiMemoryServer {
.and_then(|v| v.as_str())
.map(str::to_string)
.or(Some(stored.title));
+ let (sections, sections_truncated) =
+ crate::page_patch::section_hashes(&stored.body);
ok_json(&annotate(serde_json::json!({
"path": page_path.to_string(),
"page_id": page_id.map(|id| id.to_string()),
"title": title,
"body": stored.body,
"frontmatter": frontmatter,
+ "sections": sections,
+ "sections_truncated": sections_truncated,
"served_from": "db-fallback",
})))
}
@@ -7644,6 +7809,35 @@ fn precondition_failed(
)
}
+fn page_patch_error(path: &PagePath, error: crate::page_patch::PatchError) -> McpError {
+ use crate::page_patch::PatchError;
+ let (reason, anchor) = match &error {
+ PatchError::AnchorNotFound(anchor) => ("anchor_not_found", Some(anchor.as_str())),
+ PatchError::AmbiguousAnchor(anchor) => ("ambiguous_anchor", Some(anchor.as_str())),
+ PatchError::HeadingExists(anchor) => ("heading_exists", Some(anchor.as_str())),
+ PatchError::SectionPreconditionFailed(anchor) => {
+ ("section_precondition_failed", Some(anchor.as_str()))
+ }
+ PatchError::DuplicateTarget(anchor) => ("duplicate_target", Some(anchor.as_str())),
+ PatchError::Overlapping => ("overlapping_edits", None),
+ PatchError::Empty
+ | PatchError::TooMany
+ | PatchError::ContentTooLarge
+ | PatchError::BatchTooLarge
+ | PatchError::MissingAnchor
+ | PatchError::UnexpectedAnchor
+ | PatchError::InvalidNewHeading => ("invalid_patch", None),
+ };
+ McpError::invalid_params(
+ format!("cannot patch {path}: {error}; nothing was changed"),
+ Some(serde_json::json!({
+ "reason": reason,
+ "path": path.as_str(),
+ "anchor": anchor,
+ })),
+ )
+}
+
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))?;
@@ -9905,6 +10099,7 @@ mod tests {
"memory_consolidate",
"memory_auto_improve",
"memory_write_page",
+ "memory_patch_page",
"memory_read_page",
"memory_read_session_observations",
"memory_delete_page",
@@ -9932,6 +10127,7 @@ mod tests {
"memory_consolidate",
"memory_auto_improve",
"memory_write_page",
+ "memory_patch_page",
"memory_read_page",
"memory_read_session_observations",
"memory_delete_page",
@@ -18298,6 +18494,240 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn memory_patch_page_preserves_metadata_and_enforces_both_preconditions() {
+ let (tmp, store, server, ws, proj) = setup_server().await;
+ let server = server.with_wiki(Wiki::new(tmp.path(), store.writer.clone()).unwrap());
+ let write = server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ metadata: serde_json::from_value(serde_json::json!({
+ "kind": "fact",
+ "abstract": "preserve me"
+ }))
+ .unwrap(),
+ path: "notes/status.md".into(),
+ body: "# Status\n## Log\nold\n".into(),
+ title: None,
+ tier: Some("procedural".into()),
+ tags: vec!["customer".into()],
+ pinned: true,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ session_id: None,
+ create_only: false,
+ expected_page_id: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let first = call_tool_json(write);
+ let page_id = first["page_id"].as_str().unwrap().to_owned();
+ let page = server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ path: Some("notes/status.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ include_related: false,
+ related_depth: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let page = call_tool_json(page);
+ let section_sha256 = page["sections"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|section| section["anchor"] == "Log")
+ .unwrap()["sha256"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+
+ let patch = |page_id: String, section_sha256: String, content: &str| PatchPageArgs {
+ path: "notes/status.md".into(),
+ expected_page_id: page_id,
+ edits: vec![crate::page_patch::PagePatchEdit::ReplaceSection {
+ anchor: "Log".into(),
+ section_sha256,
+ content: content.into(),
+ }],
+ project: None,
+ workspace: None,
+ };
+ let patched = server
+ .memory_patch_page(
+ Parameters(patch(page_id.clone(), section_sha256.clone(), "new")),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let patched = call_tool_json(patched);
+ assert_ne!(patched["page_id"], page_id);
+ let stored = server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .read_page(ws, proj, &PagePath::new("notes/status.md").unwrap())
+ .unwrap();
+ assert_eq!(stored.body, "# Status\n## Log\nnew\n");
+ assert_eq!(stored.frontmatter["kind"], "fact");
+ assert_eq!(stored.frontmatter["abstract"], "preserve me");
+ assert_eq!(stored.frontmatter["tier"], "procedural");
+ assert_eq!(stored.frontmatter["pinned"], true);
+ assert_eq!(stored.frontmatter["tags"], serde_json::json!(["customer"]));
+
+ let stale_page = server
+ .memory_patch_page(
+ Parameters(patch(page_id, section_sha256.clone(), "lost")),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(stale_page.data.unwrap()["reason"], "precondition_failed");
+ let fresh_id = patched["page_id"].as_str().unwrap().to_owned();
+ let stale_section = server
+ .memory_patch_page(
+ Parameters(patch(fresh_id, section_sha256, "lost")),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ stale_section.data.unwrap()["reason"],
+ "section_precondition_failed"
+ );
+ let stored = server
+ .wiki
+ .as_ref()
+ .unwrap()
+ .read_page(ws, proj, &PagePath::new("notes/status.md").unwrap())
+ .unwrap();
+ assert!(!stored.body.contains("lost"));
+ }
+
+ #[tokio::test]
+ async fn memory_patch_page_requires_write_access_and_one_concurrent_writer_wins() {
+ 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 user = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "patcher".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let write = server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ metadata: Default::default(),
+ path: "notes/shared.md".into(),
+ body: "# Shared\n".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: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let page_id = call_tool_json(write)["page_id"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ let args = |content: &str| PatchPageArgs {
+ path: "notes/shared.md".into(),
+ expected_page_id: page_id.clone(),
+ edits: vec![crate::page_patch::PagePatchEdit::Append {
+ target: crate::page_patch::AppendTarget::EndOfPage,
+ anchor: None,
+ content: content.into(),
+ }],
+ project: Some("scratch".into()),
+ workspace: Some("default".into()),
+ };
+ let mut user_parts = test_parts_default();
+ user_parts.extensions.insert(AuthLevel::User);
+ user_parts.extensions.insert(user);
+ user_parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(user));
+ let denied = server
+ .memory_patch_page(Parameters(args("denied")), OptionalParts(user_parts))
+ .await;
+ assert!(denied.is_err());
+
+ grant_writer(store.db_path(), user, proj);
+ let mut granted_parts = test_parts_default();
+ granted_parts.extensions.insert(AuthLevel::User);
+ granted_parts.extensions.insert(user);
+ granted_parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(user));
+ server
+ .memory_patch_page(Parameters(args("granted")), OptionalParts(granted_parts))
+ .await
+ .unwrap();
+
+ let current = server
+ .reader
+ .latest_page_id_by_ids(
+ _ws,
+ proj,
+ PagePath::new("notes/shared.md").unwrap().to_string(),
+ )
+ .await
+ .unwrap()
+ .unwrap()
+ .to_string();
+ let concurrent = |content: &str| PatchPageArgs {
+ expected_page_id: current.clone(),
+ ..args(content)
+ };
+ let (left, right) = tokio::join!(
+ server.memory_patch_page(
+ Parameters(concurrent("left")),
+ OptionalParts(test_parts_default())
+ ),
+ server.memory_patch_page(
+ Parameters(concurrent("right")),
+ OptionalParts(test_parts_default())
+ )
+ );
+ assert_ne!(
+ left.is_ok(),
+ right.is_ok(),
+ "exactly one CAS writer must win"
+ );
+ }
+
/// A malformed path, tier or scope is the caller's mistake, so the page
/// tools answer `invalid params` like their siblings, not an internal
/// error a client would read as "the server broke, retry".
diff --git a/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs b/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
index 645220dd..ed173bc7 100644
--- a/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
+++ b/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
@@ -268,7 +268,7 @@ async fn read_page_throttle_no_double_bump() {
}
/// The bump is additive: a plain read's response payload is exactly the
-/// documented fields, unchanged by reinforcement.
+/// documented fields, including bounded patch tokens, and no access metadata.
#[tokio::test]
async fn read_page_response_payload_unchanged() {
let h = harness().await;
@@ -285,7 +285,15 @@ async fn read_page_response_payload_unchanged() {
keys.sort_unstable();
assert_eq!(
keys,
- vec!["body", "frontmatter", "page_id", "path", "title"],
+ vec![
+ "body",
+ "frontmatter",
+ "page_id",
+ "path",
+ "sections",
+ "sections_truncated",
+ "title",
+ ],
"reinforcement must not add fields to the read_page payload: {resp}"
);
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 00ccbf4b..6809249d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -745,7 +745,8 @@ does not need to ride on the public protocol change.
|---|---|---|
| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF + observation-evidence stream (on by default) search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; single-project calls (project implicit or named with `workspace`+`project`) also union the reserved `_global` preferences scope as `global_scope_hits`, and only an explicit multi-`scopes` set opts out (#930); `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, the matched observation ids when the observation stream voted, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list and a `timings` object with each stream's wall time in milliseconds (`fts_ms`, `entity_ms`, `vector_ms` for the stored-vector scans, `graph_ms`, `observation_ms`, `rerank_ms`; a stream that did not run is left out, and `scopes` searches sum per stream). Timings are read only on an explained query; the normal path takes no clock reading for them. The global FTS-only ranker reports its active stream and `fts_ms` without per-hit details; `as_of` reports no timings. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`. Citation paths must identify exactly one supplied page version, including supplemental preferences. Repeated citations are deduplicated in model order. An unknown path or a path shared by distinct page IDs withholds the whole answer and returns `answer_unavailable` with the unchanged retrieval hits; this includes same-path historical versions. Empty citations remain valid for abstention. This validates source identity, not the truth of generated claims. With no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Optional `[query_answer] max_context_tokens` bounds synthesis admission while preserving all retrieval hits. Each UTF-8 input byte counts as one estimated token; serialized schema bytes and a fixed 1024-unit provider-envelope allowance also count, and the reasoning tier's output allowance is reserved separately. This is a conservative admission contract, not a guarantee for every provider's tokenizer or framing. Answer admission gives known supersession successors priority over predecessors, and newer evidence priority within the same workspace/project and normalized exact title. A bounded metadata query reads only already-authorized hit IDs; canonical session pages use session start time rather than ingestion time. Unrelated evidence retains retrieval order. Whole snippets are admitted before any clipping. Otherwise-unused space may hold one final complete trailing sentence or statement, with ellipses marking removed text; a fragment with no complete boundary is omitted. The boundary rule recognizes sentence punctuation and code statement terminators and does not perform semantic inference. Empty and punctuation-only snippets are omitted. `answer_context` reports `admitted`, `omitted`, `clipped`, `estimated_input_tokens`, `reserved_output_tokens` and `max_context_tokens`; it appears only when admission runs. If fixed content or evidence cannot fit, the provider is not called and `answer_unavailable` accompanies the full hits. The question is never silently clipped. Citation validation uses only admitted sources. Superseded status is explicit in budgeted prompts. Clipping can remove a qualification or correction; callers should inspect the receipt and original hits. An explicit zero or undersized limit prevents synthesis; only omission disables admission. Omitted configuration preserves existing wire request and response bytes. Answer quality is not yet eval-validated. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). Optional `kind`, `tag`, `tier` and `path_prefix` filters narrow candidates before ranking, on every stream including the CJK substring search. |
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
-| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). The response carries the page's current version as `page_id`, the value compare-and-write calls pass back. A page whose `expires_at` TTL has passed is still returned and carries `expired: true`; a live page's response has no such field. |
+| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). The response carries the page's current version as `page_id`, the value compare-and-write calls pass back, plus at most 100 parsed Markdown headings with exact section SHA-256 tokens for `memory_patch_page` (`sections_truncated` reports overflow). Fenced-code headings are excluded. A page whose `expires_at` TTL has passed is still returned and carries `expired: true`; a live page's response has no such field. |
+| `memory_patch_page` | destructive | Atomically append inside a parsed Markdown section or at EOF, add a unique level 2-6 section, or replace a section. It requires the current page id; replacement also requires the read-returned exact section hash. All edits resolve against one captured body, ambiguity/conflicts fail before writing, and the resulting full page goes through `Wiki::write_page_if`, preserving frontmatter and the normal sanitizer, admission, attribution, supersession, index, rollback and git-checkpoint boundaries. Existing-scope write authorization is fail-closed and cannot create a target. |
| `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the visible session with the newest captured work other than the caller's own, ended or cut off (`ReaderPool::recent_session_activity` over 30 days, preferring the caller session's cwd), else the latest completed visible session. |
| `memory_status` | read-only | Counts, paths, version, plus the `scope` that answered: `workspace`, `project`, and `resolved_by` (`explicit`, `session`, `shared_slot`, `startup_seed`, `default`, `default_after_mismatch`). Unscoped reads resolved by `startup_seed` or `default_after_mismatch` also log a server warning. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Project-scoped snapshots also carry a bounded `pinned` list (up to 10) of the project's pinned latest pages (`pinned = 1`, newest first) as standing SessionStart hot-context, distinct from `slots`, which is keyed by the `_slots/` path prefix; empty and omitted from JSON when the project has no pins, so the default shape is unchanged. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. `scope` names the workspace/project briefed and `resolved_by` how it was chosen. |
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 6608d28b..43adb2bf 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -81,6 +81,7 @@ the legitimate restricted-project control and the failed-query cases.
| 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; `ai-memory-mcp/src/server.rs` `sanitize_feedback_reason` scrubs the reason *before* the 500-char cap; `ai-memory-hooks/src/router.rs` `durable_body` scrubs the full excerpt *before* the per-event body caps (`payload::durable_body_cap`), which no longer run at excerpt extraction; `ai-memory-hooks/src/payload.rs` `cap_object_fields` scrubs with the built-in sanitizer *before* the client spool cap; `WriterHandle::insert_observation` requires `Sanitized`; `ops` crate-private; `Sanitizer::scrub` matches each pattern through invisible formatting characters (a `Shadow` copy without `Default_Ignorable_Code_Point` characters, each match mapped back to its original span) and stores non-matching text byte for byte, `strip_control` removes stray tag characters (an emoji flag's tag run is kept), a non-leading U+FEFF and U+2061–2064, the private-key rules run first and cover PGP armor and a block with no end line once a key-body line follows the header, the allowlist never exempts `private_key` and ignores blank entries (`ai-memory-cli/src/config.rs` `drop_blank_sanitize_allowlist_entries` drops and warns at load); `companions/ai-memory-client/src/scrub.rs` `sanitize_external_text` mirrors the invisible-character, hidden-text and key rules | 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) + `ai-memory-mcp::server` `feedback_reason_is_scrubbed_before_the_500_char_cap` (#1109) + `ai-memory-hooks::router` `issue_1114_user_prompt_body_is_sanitized_before_the_16kib_cap`, `issue_1114_post_compaction_body_is_sanitized_before_the_16kib_cap`, `issue_1114_tool_body_is_sanitized_before_the_2kb_cap`, `tool_body_cap_keeps_the_utf8_boundary` + `ai-memory-hooks::payload` `client_body_cap_scrubs_before_truncating` (each places a secret straddling the cap and asserts a `[REDACTED:…]` marker survives with no raw fragment; #1114) + `ai-memory-core::sanitize` `shared_sanitizer_vectors_hold` (credentials split by each invisible-character family, complete, PGP and end-line-less key blocks, and controls that must stay byte-identical: emoji ZWJ sequences, keycaps, a subdivision flag, Persian ZWNJ, Indic ZWJ, Thai ZWSP, Hebrew RLM, a soft hyphen, prose and code naming a key header; the same `tests/fixtures/sanitizer_vectors.json` drives `ai-memory-client` `shared_sanitizer_vectors_hold`), `invisible_character_inside_an_operator_pattern_match_is_redacted`, `invisible_characters_neither_break_nor_bypass_the_allowlist`, `characters_that_hide_text_are_stripped`, `pgp_private_key_block_is_redacted`, `private_key_block_without_an_end_line_is_redacted`, `key_rules_run_before_token_rules_can_split_a_key_body`, `allowlist_never_exempts_a_private_key`, `blank_allowlist_entries_are_ignored` + `ai-memory-hooks::router` `user_prompt_secret_split_by_an_invisible_character_is_redacted` + `ai-memory-cli::config` `config_load_drops_blank_sanitize_allowlist_entries` + `ai-memory-client` `characters_that_hide_text_or_split_a_credential_are_removed` (GHSA-jpcg-w5c5-wcv6) | STRONG (structural) |
| 7a | Eval observations: server provenance and reason privacy | `ai-memory-consolidate/src/auto_improve.rs` constructs private results from the existing execution, ignores extra model/scorer result fields and all eval results on report deserialization, hashes the evaluated request/bodies, and scrubs reasons before the 2,048-character cap and pending persistence; changed bodies cannot receive the earlier result | `auto_improve::tests::structured_eval_records_server_observation`; `tests/suite/eval_results.rs` `eval_reason_is_sanitized_before_pending_storage_with_legitimate_control` attempts forged deserialized reports and IDs/digests and malicious reasons with secrets/control characters, checks report and stored evidence before sidecar rendering, and preserves a legitimate reason and external evidence without independent results; fails with reason scrubbing or the report deserialization guard removed | STRONG |
| 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 |
+| 7c | Anchored page edits cannot bypass page authorization, metadata preservation, admission, or compare-and-write | `ai-memory-mcp/src/server.rs` `memory_patch_page` resolves an existing scope with write access, requires `expected_page_id`, reads one disk base and commits one full result with `Wiki::write_page_if`; `page_patch.rs` parses ATX headings outside fences, bounds hashes and edit sizes, rejects ambiguity/conflicts, and requires an exact section hash for replacement | `server.rs` `memory_patch_page_preserves_metadata_and_enforces_both_preconditions`; `page_patch.rs` parser tests cover fenced and duplicate headings, stale hashes, duplicate targets and section/EOF mutations. The wiki admission and conditional-write suites cover rejection rollback and simultaneous `write_page_if` writers through the same final boundary | STRONG for patch parsing, CAS and metadata; shared wiki tests cover the reused admission/concurrency primitive |
| 7c | A compaction checkpoint cannot bypass `consolidate` admission by deferring its provider rewrite (#1229) | `ai-memory-hooks/src/router.rs` `write_checkpoint_page` gives the PreCompact / PostCompaction rule-based write the `consolidate` admission operation whenever a consolidator is configured, and `process_authorized` queues the durable rewrite only after that write succeeds; the worker's rewrite runs admission again through `Consolidator::consolidate_session` | `router.rs` `checkpoint_admission_refusal_writes_no_page_and_queues_no_rewrite` (a policy refusing `consolidate` leaves no page and no queued job; control: a policy gating only `handoff_begin` writes the page and queues the job), `checkpoint_preserves_the_consolidate_admission_operation` (the hook path sends exactly one `consolidate` admission call and never calls the provider); both bite-checked with the admission context removed | STRONG |
| 7d | The Cursor Agent CLI child, which reads captured session text, never sees the server's own credentials | `ai-memory-llm/src/cursor_agent.rs` `complete_text` spawns `agent` with `env_clear()` plus `CursorAuth::child_env`, which `CursorAuth::new` filters through `cursor_child_env` (an allowlist of `PATH`/`HOME`/user, locale, temp/XDG, session bus, proxy/CA and Windows basics, plus `LC_*`/`CURSOR_*`); the environment and the workspace root are captured once by `ai-memory-cli/src/config.rs` `Config::cursor_auth`, so the provider reads no environment itself; a relative workspace root is refused | `cursor_provider.rs` `the_child_gets_only_the_allowlisted_environment` (`AI_MEMORY_AUTH_TOKEN` and `OPENAI_API_KEY` canaries and the test process's own `CARGO_*` variables never reach the child; control: `PATH`, `HOME` and `CURSOR_API_KEY` do, and the workspace sits under the injected root; bite-checked by dropping `env_clear()`), `a_relative_workspace_root_is_refused`; `config.rs` `cursor_provider_hands_the_child_only_allowlisted_env` | STRONG |
| 7e | Executable auto-improvement eval policy is server-owned | `ai-memory-mcp/src/admin.rs` retains the legacy request `eval` key only as a rejected compatibility field and builds `AutoImproveReviewConfig.eval` exclusively from `AdminState`; `ai-memory-cli/src/commands/auto_improve.rs` sends no executable policy over HTTP | MCP `auto_improve_admin_refuses_request_eval_and_inherits_server_defaults` sends a request-controlled program path and receives 422, then omits the field and proves the configured server gate still runs | STRONG |
diff --git a/docs/usage.md b/docs/usage.md
index a0de1c9e..f9d10d94 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -220,6 +220,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.
| "Write this session's page yourself" / an in-session "consolidate this session" | `memory_read_session_observations`, then `memory_write_page` with `session_id` and `path: sessions/<id>.md` | The agent compiles the session page with its own model instead of the server's provider. To match the server's multi-page layout it may also write up to four more pages with the same `session_id`: `concepts/<slug>.md` (`tier: semantic`, `kind: fact`), `decisions/<short>.md` (`kind: decision`), `gotchas/<slug>.md` (`kind: gotcha`) and `_rules/<slug>.md` (`kind: rule`); the session page is `tier: episodic`, `kind: fact`. The session must belong to the project the page is written to; the page records it as evidence, gets the same session-page frontmatter (plus `consolidated_by: agent`) and duplicate-title suffix, and the session's queued SessionEnd job is marked completed. The write uses the `write_page` admission op, so a webhook that filters on `consolidate` does not see it. A pinned page is never overwritten this way. SessionEnd keeps the page: neither the rule-based summary nor the opt-in SessionEnd worker replaces it, even when the session went on after the write, and a PreCompact or PostCompaction checkpoint leaves it alone too. |
| "What did we learn from this session?" / "what memory should we add?" | `memory_auto_improve` | Without a session ID, reviews the newest completed session with no persisted auto-improvement run, advancing past preflight skips on repeated calls; pass an ID for a targeted rerun. The server also runs scheduled auto-improvement for new completed sessions when an LLM is configured. `[auto_improve.scheduler] enabled = false` disables automatic review; `[auto_improve] require_approval = true` leaves scheduled and manual proposals in pending-writes for review. |
| "Remember this permanently" / "add an annotation" | `memory_write_page` | Writes durable wiki knowledge; not a single-use handoff. |
+| "Append this action to the Log section" / "replace only Open issues" | `memory_read_page`, then `memory_patch_page` | Patches an existing Markdown page without re-emitting its full body or frontmatter. Pass the required `page_id`; section replacement also passes the section's returned `sha256`. The batch writes all edits or none. |
| "Remember this until Friday" / "expire this after the migration" | `memory_write_page` with `expires_at` | Writes a time-bounded page. Use RFC3339 or `YYYY-MM-DD` (end of day UTC); normal retrieval hides it after expiry and the next forget sweep deletes it; a `memory_read_page` by exact path still returns it, marked `expired: true`. TTL outranks `pinned`. |
| "Search expired notes for X" | `memory_query` with `include_expired: true` | Opts an explicit project, sibling-scope, or global search into expired historical pages; ordinary searches exclude them. |
| "Search only Rust release runbooks" | `memory_query` with `path_prefix: "procedures/"`, `tag: "rust"`, and optionally `kind` / `tier` | Narrows every page retrieval stream before ranking. Filters also constrain global, time-travel, profile, and `pin_first` results. A filtered miss has no raw-observation fallback because observations have no page metadata. |
@@ -405,6 +406,45 @@ neither. See
[Change a page only if nobody else has](programmatic-memory.md#change-a-page-only-if-nobody-else-has)
for conditional writes.
+### Patching a section without replacing the page
+
+`memory_read_page` returns at most 100 parsed Markdown headings in `sections`,
+each with its `anchor`, `level`, and exact `sha256`; `sections_truncated` says
+whether more exist. Headings inside fenced code are not sections. Read the page
+immediately before patching, then call `memory_patch_page` with that required
+`page_id`:
+
+```json
+{
+ "workspace": "customers",
+ "project": "aran",
+ "path": "STATUS.md",
+ "expected_page_id": "019...",
+ "edits": [
+ {
+ "op": "append",
+ "target": "section",
+ "anchor": "Recent actions",
+ "content": "| 2026-10-26 | SMTP fixed |"
+ },
+ {
+ "op": "replace_section",
+ "anchor": "Open issues",
+ "section_sha256": "9f...",
+ "content": "| None |"
+ }
+ ]
+}
+```
+
+Use `target: "end_of_page"` with no anchor to append at EOF. `add_section`
+requires an ATX level 2-6 heading such as `## Decisions` and rejects a heading
+that already exists after whitespace/case normalization. Duplicate headings,
+stale page or section tokens, overlapping targets, failed admission, or a
+concurrent writer reject the whole batch. Existing frontmatter is preserved;
+the final body still passes through the normal sanitizer, admission,
+attribution, versioning, index and git-checkpoint path.
+
## Install the routing snippet and Agent Skills
From an agent, say: