Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(pages): edit_page partial edits through the coordinated write path (#5616)
garrytanb25ed496b90b
diff --git a/src/core/operations.ts b/src/core/operations.tsindex 623385bd36..70594523f5 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -115,6 +115,7 @@ import { chronicleOperations } from './ops/chronicle.ts';import { extractionOperations } from './ops/extraction.ts';import { entityIdentityOperations } from './ops/entity-identity.ts';import { requestToolsOperations } from './ops/request-tools.ts';+import { pageEditOperations } from './ops/page-edit.ts';// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`// verb (verbs.ts) loads it from THIS module at runtime — re-exported so every@@ -133,6 +134,8 @@ export const operations: Operation[] = [// Page CRUD (get_page, put_page, delete_page, list_pages + the v0.26.5// destructive-guard ops restore_page, purge_deleted_pages) — ops/pages.ts...pagesOperations,+ // #5616 partial page edit (edit_page) — ops/page-edit.ts+ ...pageEditOperations,...persistenceOperations,// Search (search, query) — ops/search.ts...searchOperations,diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 6852bb3060..4ee1465261 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -308,6 +308,8 @@ export function normalizeSlugPrefix(prefix: string): string {export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set(['put_page', 'delete_page', 'restore_page', 'add_tag', 'remove_tag','add_link', 'remove_link', 'add_timeline_entry', 'revert_version',+ // #5616: edit_page enforces the slug fence in its handler and submission.+ 'edit_page','put_raw_data', 'think',// submit_agent enforces bound_slug_prefixes itself (it is the op the column// was introduced for — see its bound_* binding check), so denying it herediff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex ea97b6d09e..0d2aebbae7 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -133,6 +133,8 @@ export interface ParamDef {default?: unknown;enum?: string[];items?: ParamDef;+ /** Object members (O-DX-3); a member with `required: true` lands in the schema's `required`. */+ properties?: Record<string, ParamDef>;}export interface Logger {diff --git a/src/core/ops/page-edit.ts b/src/core/ops/page-edit.tsnew file mode 100644index 0000000000..9b8a3c3abc--- /dev/null+++ b/src/core/ops/page-edit.ts@@ -0,0 +1,49 @@+/**+ * #5616 partial page edit. Never import from '../operations.ts' here (cycle).+ */+import type { Operation } from './contract.ts';+import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from './context.ts';+import { pageMutationSource, submitPageMutation } from '../persistence/page-mutations.ts';+import { PAGE_MUTATION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/params.ts';+import { EDIT_PAGE_MAX_EDITS, parsePageEdits } from '../persistence/page-edit.ts';++const edit_page: Operation = {+ name: 'edit_page',+ outputRedaction: { exempt: "the diff is the caller's own authorized view of the page it just edited, the get_page boundary (CEO-17 raw-read exception)" },+ description: 'Change part of an existing page without resending it: prefer this over put_page for small changes to large pages. Read get_page with include_content:true and pass its revision as expected_revision. Each edit replaces old_text with new_text; edits apply in order, each to the text the previous edit produced, and each old_text must match exactly once in that content. Protected takes and facts sections never match (use the takes_* operations or remember/forget). All edits publish together or none do, through the same receipts, fences and write-through as put_page. Returns the new revision and a unified diff of your view (at most 8 KB). Refusals name the edit: edit_no_match, edit_ambiguous_match (with match_count), edit_protected_span, edit_invalid; a stale revision returns revision_conflict with current_revision. Retain request_id and repeat identical arguments after a pending receipt.',+ params: {+ slug: { type: 'string', required: true, description: 'Slug of the existing page to edit.' },+ expected_revision: { type: 'string', required: true, description: 'The `revision` from get_page include_content:true. The edit is refused if the page changed since.' },+ edits: {+ type: 'array', required: true,+ description: `1 to ${EDIT_PAGE_MAX_EDITS} replacements, applied in order and all or nothing.`,+ items: {+ type: 'object',+ properties: {+ old_text: { type: 'string', required: true, description: 'Exact existing text (including whitespace) to replace; must occur exactly once in the current content.' },+ new_text: { type: 'string', required: true, description: 'Replacement text; empty deletes old_text.' },+ },+ },+ },+ source_id: PAGE_MUTATION_PARAMS.source_id,+ request_id: WRITE_REQUEST_PARAM,+ },+ mutating: true,+ scope: 'write',+ area: 'pages',+ handler: async (ctx, p) => {+ pageMutationSource(ctx, p, 'edit_page');+ parsePageEdits(p.edits);+ if (ctx.dryRun) {+ if (typeof p.slug === 'string') {+ validatePageSlug(p.slug);+ enforceClientSlugFence(ctx, p.slug, 'edit_page');+ enforceSubagentSlugFence(ctx, p.slug, 'edit_page');+ }+ return { dry_run: true, action: 'edit_page', slug: p.slug };+ }+ return submitPageMutation(ctx, { operation: 'edit_page', params: p });+ },+};++export const pageEditOperations: Operation[] = [edit_page];diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex f8917efc60..7f07995645 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -14,7 +14,7 @@ export const PERSISTENCE_IPC_VERSION = 1;export const PERSISTENCE_IPC_MAX_BYTES = 32 * 1024 * 1024;export const PERSISTENCE_IPC_MAX_CONNECTIONS = 8;export const PERSISTENCE_IPC_OPERATIONS = [- 'put_page', 'capture', 'delete_page', 'restore_page', 'revert_version',+ 'put_page', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page','remember', 'forget', 'extract_facts', 'get_write_request', 'list_write_requests', 'cancel_write_request','get_page', 'fetch','list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack',@@ -26,7 +26,7 @@ export const PERSISTENCE_IPC_OPERATIONS = [export type PersistenceIpcOperation = typeof PERSISTENCE_IPC_OPERATIONS[number];const OPERATIONS = new Set<string>(PERSISTENCE_IPC_OPERATIONS);const MUTATIONS = new Set<string>([- 'put_page', 'capture', 'delete_page', 'restore_page', 'revert_version', 'remember', 'forget', 'extract_facts',+ 'put_page', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'remember', 'forget', 'extract_facts','put_skill', 'delete_skill', 'import_skill_proposal','add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',]);diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsnew file mode 100644index 0000000000..a85eaeef05--- /dev/null+++ b/src/core/persistence/page-edit.ts@@ -0,0 +1,187 @@+/**+ * #5616 edit_page: ordered exact-string replacements applied server-side to+ * the caller's authorized view of a page (the `content` get_page returns to+ * that caller with include_content:true), mapped back onto the canonical body+ * without moving or exposing protected takes/facts fences.+ *+ * The canonical serialization is split into editable text and protected+ * segments. A protected segment renders as itself for trusted local callers;+ * for remote callers a takes fence renders as nothing and a facts fence as+ * its world-visible rows, exactly as get_page sanitizes them. An edit must+ * match exactly once inside editable text; a match that touches or crosses a+ * protected segment is refused, so canonical bytes outside the edited spans+ * are preserved byte for byte.+ */+import type { Page } from '../types.ts';+import { OperationError } from '../ops/contract.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { sanitizeText } from '../batch-rows.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { unifiedDiff } from '../skillpack/diff-text.ts';++export const EDIT_PAGE_MAX_EDITS = 50;+export const EDIT_PAGE_DIFF_MAX_BYTES = 8 * 1024;+export const EDIT_PAGE_DOCS = 'docs/protocol/MEMORY_VERBS_v1.md#partial-page-edits-edit_page';++export interface PageEdit { old_text: string; new_text: string; }+interface Segment { canonical: string; view: string; editable: boolean; }++const MARKERS = [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END];+const MARKER_PATTERN = new RegExp(MARKERS.map(m => m.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g');+const REMOTE_VIEW = { includeWithdrawn: true, keepMaterializedMarkers: true } as const;++function editError(code: string, message: string, suggestion: string, detail?: string): OperationError {+ const error = new OperationError(code, message, suggestion, EDIT_PAGE_DOCS);+ if (detail !== undefined) error.detail = detail;+ return error;+}++/** Validates the wire shape: 1-50 `{ old_text, new_text }` objects, `old_text` non-empty. */+export function parsePageEdits(value: unknown): PageEdit[] {+ if (!Array.isArray(value) || value.length < 1 || value.length > EDIT_PAGE_MAX_EDITS) {+ throw editError('edit_invalid', `edits must be an array of 1 to ${EDIT_PAGE_MAX_EDITS} replacements.`,+ 'Pass edits: [{ "old_text": "…", "new_text": "…" }] in the order to apply them.');+ }+ return value.map((edit, index) => {+ const record = edit as Record<string, unknown> | null;+ if (!record || typeof record !== 'object' || Array.isArray(record) || Object.keys(record).some(k => k !== 'old_text' && k !== 'new_text')+ || typeof record.old_text !== 'string' || typeof record.new_text !== 'string') {+ throw editError('edit_invalid', `Edit ${index} must be an object with string old_text and new_text.`,+ 'Each edit is exactly { "old_text": "…", "new_text": "…" }.', `edit_index=${index}`);+ }+ if (record.old_text.length === 0) {+ throw editError('edit_invalid', `Edit ${index} has an empty old_text.`,+ 'Quote enough existing text to match exactly once; use put_page to write a new page.', `edit_index=${index}`);+ }+ if (MARKERS.some(marker => (record.new_text as string).includes(marker))) {+ throw editError('edit_protected_span', `Edit ${index} would write a protected fence marker.`,+ 'Use the takes_* operations or remember/forget for takes and facts.', `edit_index=${index}`);+ }+ return { old_text: record.old_text, new_text: record.new_text };+ });+}++function bodySegments(body: string, remote: boolean): Segment[] {+ if (remote && sanitizeText(body) !== body) {+ throw editError('edit_invalid', 'This page contains bytes the remote view cannot reproduce.',+ 'Edit it from the brain host with put_page or the local CLI.');+ }+ const segments: Segment[] = [];+ let cursor = 0;+ let open: { start: number; end: string } | undefined;+ for (const token of body.matchAll(MARKER_PATTERN)) {+ const marker = token[0];+ if (!open) {+ if (marker !== FACTS_FENCE_BEGIN && marker !== TAKES_FENCE_BEGIN) continue;+ if (token.index > cursor) segments.push(text(body.slice(cursor, token.index)));+ open = { start: token.index, end: marker === FACTS_FENCE_BEGIN ? FACTS_FENCE_END : TAKES_FENCE_END };+ continue;+ }+ if (marker !== open.end) throw unrepairedFence();+ cursor = token.index + marker.length;+ const fence = body.slice(open.start, cursor);+ segments.push({ canonical: fence, view: remote ? sanitizeRemoteBody(fence, REMOTE_VIEW) : fence, editable: false });+ open = undefined;+ }+ if (open) throw unrepairedFence();+ if (cursor < body.length) segments.push(text(body.slice(cursor)));+ return segments;+}++function text(value: string): Segment { return { canonical: value, view: value, editable: true }; }+function unrepairedFence(): OperationError {+ return editError('edit_invalid', 'A takes or facts fence on this page is malformed.',+ 'Repair the fence (gbrain doctor names the page) before editing it.');+}++/**+ * Mirrors serializeMarkdown's layout so the view is byte-equal to get_page's+ * `content`; adjacent editable pieces coalesce so a match may span the+ * frontmatter, body and timeline sentinel like any ordinary text.+ */+function pageSegments(page: Page, tags: string[], remote: boolean): Segment[] {+ const head = serializePageToMarkdown({ ...page, compiled_truth: '', timeline: '' }, tags).slice(0, -1);+ const timeline = bodySegments(page.timeline ?? '', remote);+ const sentinel = '\n\n<!-- timeline -->\n\n';+ // A remote view whose whole timeline is protected has no sentinel either.+ const sentinelSegment = timeline.some(segment => segment.view.length > 0) ? text(sentinel) : { canonical: sentinel, view: '', editable: false };+ const pieces = [text(head), ...bodySegments(page.compiled_truth ?? '', remote),+ ...(page.timeline ? [sentinelSegment, ...timeline] : []), text('\n')];+ return pieces.reduce<Segment[]>((out, piece) => {+ const last = out[out.length - 1];+ if (last?.editable && piece.editable) out[out.length - 1] = text(last.canonical + piece.canonical);+ else out.push(piece);+ return out;+ }, []);+}++const join = (segments: Segment[], key: 'canonical' | 'view') => segments.map(segment => segment[key]).join('');++/** The text a caller matches against: get_page `content` for that caller. */+export function editableView(page: Page, tags: string[], remote: boolean): string {+ return join(pageSegments(page, tags, remote), 'view');+}++function occurrences(haystack: string, needle: string): number[] {+ const found: number[] = [];+ for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + 1)) found.push(at);+ return found;+}++/**+ * Applies the edits in order, each to the text produced by the previous one,+ * all or nothing. Returns the canonical content to publish and the caller's+ * view before and after (the only text a diff or receipt may show).+ */+export function applyPageEdits(page: Page, tags: string[], remote: boolean, edits: PageEdit[]): { content: string; before: string; after: string } {+ let segments = pageSegments(page, tags, remote);+ const before = join(segments, 'view');+ edits.forEach((edit, index) => {+ const view = join(segments, 'view');+ const ranges: Array<{ start: number; end: number; index: number }> = [];+ let offset = 0;+ segments.forEach((segment, i) => { ranges.push({ start: offset, end: offset + segment.view.length, index: i }); offset += segment.view.length; });+ const inside = (at: number) => ranges.find(r => segments[r.index].editable && at >= r.start && at + edit.old_text.length <= r.end);+ const all = occurrences(view, edit.old_text);+ const allowed = all.filter(at => inside(at));+ if (allowed.length === 0 && all.length > 0) {+ throw editError('edit_protected_span', `Edit ${index}'s old_text touches a protected takes or facts section.`,+ 'Use the takes_* operations or remember/forget for takes and facts, and quote only ordinary page text.', `edit_index=${index}`);+ }+ if (allowed.length === 0) {+ throw editError('edit_no_match', `Edit ${index}'s old_text was not found in the page.`,+ 'Read get_page with include_content:true and copy old_text exactly, including whitespace; earlier edits in the same call have already been applied to the text it matches.',+ `edit_index=${index} match_count=0`);+ }+ if (allowed.length > 1) {+ throw editError('edit_ambiguous_match', `Edit ${index}'s old_text matches ${allowed.length} places.`,+ 'Include surrounding text in old_text so it matches exactly once.', `edit_index=${index} match_count=${allowed.length}`);+ }+ const at = allowed[0];+ const range = inside(at)!;+ const segment = segments[range.index];+ const local = at - range.start;+ const replaced = segment.canonical.slice(0, local) + edit.new_text + segment.canonical.slice(local + edit.old_text.length);+ segments = segments.map((s, i) => i === range.index ? text(replaced) : s);+ });+ return { content: join(segments, 'canonical'), before, after: join(segments, 'view') };+}++/** The caller-view unified diff, capped at 8 KB on a line boundary. */+export function editDiff(slug: string, before: string, after: string): { diff: string; diff_truncated?: true } {+ const full = unifiedDiff(before, after, { oldPath: `a/${slug}.md`, newPath: `b/${slug}.md` });+ if (Buffer.byteLength(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full };+ let cut = full.slice(0, EDIT_PAGE_DIFF_MAX_BYTES);+ while (Buffer.byteLength(cut) > EDIT_PAGE_DIFF_MAX_BYTES) cut = cut.slice(0, -1);+ return { diff: cut.slice(0, cut.lastIndexOf('\n') + 1), diff_truncated: true };+}++/** Submission preflight and publication share one check of the stated revision. */+export function assertEditRevision(current: string | null, expected: unknown): void {+ if (current !== null && expected === current) return;+ throw editError('revision_conflict', current === null ? 'The page does not exist.' : 'The page changed since expected_revision was read.',+ 'Read get_page with include_content:true again, rebuild the edits against that content, and resend with its revision.',+ current === null ? undefined : `current_revision=${current}`);+}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 582997a39c..9fd8d2a71a 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -146,6 +146,13 @@ export async function submitPageMutation(ctx: OperationContext,const authority = await submissionAuthority(ctx, input.operation, sourceId, source.incarnation, slug);await assertKnowledgePublicationAllowed(ctx.engine, { source_id: sourceId, source_incarnation: source.incarnation, slug });const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ // #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.+ if (input.operation === 'edit_page') {+ const { applyPageEdits, assertEditRevision, parsePageEdits } = await import('./page-edit.ts');+ if (!snapshot || snapshot.page.deleted_at) throw new OperationError('page_not_found', `Page not found: ${slug}`, 'edit_page changes an existing page; create it with put_page.');+ assertEditRevision(snapshot.revision, p.expected_revision);+ applyPageEdits(snapshot.page, snapshot.tags, ctx.remote !== false, parsePageEdits(p.edits));+ }let binding = await getWorktreeBinding(ctx.engine, sourceId);const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(await ctx.engine.getConfig('sync.write_through') ?? 'true');diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 3b4bd4c43f..d309aaee28 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -34,6 +34,7 @@ import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { readSlugRootMode } from '../sync-anchor.ts';+import { applyPageEdits, editDiff, parsePageEdits } from './page-edit.ts';const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';@@ -199,7 +200,9 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestrecoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };} };}- let content = preparedIntent?.content ?? p.content as string;+ // #5616: edits apply to the caller's view of the locked snapshot (revision checked above).+ const edited = row.operation === 'edit_page' ? editLockedPage(row, snapshot) : undefined;+ let content = edited?.content ?? preparedIntent?.content ?? p.content as string;let versionTags: string[] | undefined = preparedIntent?.tags;// A replacement/restore publishes a live page. Only a recorded version may// explicitly restore a tombstone; legacy versions leave this state unchanged.@@ -230,7 +233,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);}const projected = !(row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));- const writer = row.operation === 'put_page' && p.kind !== 'managed_maintenance_page'+ const writer = (row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'&& (preparedIntent !== undefined || typeof p.expected_revision === 'string') ? 'editing' : 'preserving';// #5567: database-only timeline rows are written back into the page before// the no-op check, digest, rendering and chunking see the body.@@ -289,7 +292,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst logicalNoop = snapshot !== null && digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(ready.parsedPage, tags));const noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;- const ordinaryPage = ['put_page','capture','restore_page','revert_version'].includes(row.operation);+ const ordinaryPage = ['put_page','capture','restore_page','revert_version','edit_page'].includes(row.operation);const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage);// A managed maintenance page (e.g. the dream write-back after grounding// quarantine) republishes a body; its automatic links follow that body.@@ -334,6 +337,12 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestslug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),- ...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}) };+ ...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),+ ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}) };} };}++function editLockedPage(row: WriteRequest, snapshot: PageSnapshot | null) {+ if (!snapshot || snapshot.page.deleted_at) throw new OperationError('page_not_found', 'Page not found.');+ return applyPageEdits(snapshot.page, snapshot.tags, row.authority.remote, parsePageEdits(row.intent?.edits));+}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex e147fc3897..dd12071b5c 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -45,7 +45,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);if (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);- if (['put_page','capture','delete_page','restore_page','revert_version'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);+ if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.');}export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex 69603b5166..db6f791844 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -96,6 +96,9 @@ export const STARTER_OPS: ReadonlySet<string> = new Set([// starter connect lanes retire the "unknown tool: capture" FAQ, which only// works if the starter surface actually lists it.'capture',+ // #5616: the small-change companion of put_page (a direct literal, like+ // capture, so subagents do not gain a new write tool).+ 'edit_page','get_write_request', 'list_write_requests', 'cancel_write_request','list_skills', 'get_skill', 'list_brain_skillpack', 'get_skill_asset','join_brain', 'sync_brain_skills', 'leave_brain', 'put_skill', 'delete_skill',diff --git a/src/mcp/tool-defs.ts b/src/mcp/tool-defs.tsindex a34ca77c0b..eec4d3f36c 100644--- a/src/mcp/tool-defs.ts+++ b/src/mcp/tool-defs.ts@@ -24,7 +24,8 @@ export interface McpToolDef {}/**- * Convert a single ParamDef to a JSON Schema fragment. Recursive on `items`.+ * Convert a single ParamDef to a JSON Schema fragment. Recursive on `items`+ * and object `properties` (closed, with member `required`).** Single source of truth for ParamDef→JSON Schema mapping. Consumed by:* - buildToolDefs (stdio MCP server.ts via tool-defs.ts)@@ -47,6 +48,11 @@ export function paramDefToSchema(p: ParamDef): Record<string, unknown> {...(p.enum ? { enum: p.enum } : {}),...(p.default !== undefined ? { default: p.default } : {}),...(p.items ? { items: paramDefToSchema(p.items) } : {}),+ ...(p.properties ? {+ properties: Object.fromEntries(Object.entries(p.properties).map(([k, v]) => [k, paramDefToSchema(v)])),+ required: Object.entries(p.properties).filter(([, v]) => v.required).map(([k]) => k),+ additionalProperties: false,+ } : {}),};}diff --git a/test/edit-page.test.ts b/test/edit-page.test.tsnew file mode 100644index 0000000000..0a20387332--- /dev/null+++ b/test/edit-page.test.ts@@ -0,0 +1,229 @@+/**+ * #5616 edit_page (O-DX-3, O-ENG-6): exact-string partial edits through the+ * coordinated write path, matched against the caller's authorized view.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test as bunTest } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { buildToolDefs } from '../src/mcp/tool-defs.ts';+import { operations } from '../src/core/operations.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { renderTakesFence } from '../src/core/takes-fence.ts';+import { editableView } from '../src/core/persistence/page-edit.ts';+import { STARTER_OPS } from '../src/mcp/surface.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import type { Page } from '../src/core/types.ts';++let engine: PGLiteEngine;+let fixture: string;+let remoteRegistration: LocalRegistration;+let cliRegistration: LocalRegistration;+const remoteAuth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] };+const SECRET_FACT = 'private-fact-canary-example';+const SECRET_TAKE = 'private-take-canary-example';++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ _resetWriteThroughCacheForTest();+ fixture = mkdtempSync(join(tmpdir(), 'gb-edit-page-'));+ mkdirSync(join(fixture, 'brain'));+ await engine.setConfig('sync.repo_path', join(fixture, 'brain'));+});+afterEach(async () => { await disposePersistenceConsumer(engine); rmSync(fixture, { recursive: true, force: true }); });++function test(name: string, run: () => Promise<void>, timeout = 30_000) {+ bunTest(name, () => withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {+ remoteRegistration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] });+ cliRegistration = await registerLocalWriter(engine, 'cli');+ try { await run(); } finally { await disposePersistenceConsumer(engine); }+ }), timeout);+}++async function call(name: string, params: Record<string, unknown>, remote = true) {+ const response = await withVerifiedLocalRegistration(engine, remote ? remoteRegistration : cliRegistration, () => dispatchToolCall(engine, name, params, {+ remote, config: { engine: 'pglite' }, sourceId: 'default', ...(remote ? { auth: remoteAuth } : {}),+ logger: { info() {}, warn() {}, error() {} },+ }));+ const text = (response.content[0] as { text: string }).text;+ return { isError: response.isError === true, body: JSON.parse(text), text };+}+async function read(slug: string, remote = true) {+ const result = await call('get_page', { slug, include_content: true }, remote);+ expect(result.isError).toBe(false);+ return result.body as { content: string; revision: string };+}+async function edit(slug: string, edits: Array<{ old_text: string; new_text: string }>, opts: { remote?: boolean; revision?: string; request_id?: string } = {}) {+ const revision = opts.revision ?? (await read(slug, opts.remote ?? true)).revision;+ const params = { slug, expected_revision: revision, edits, request_id: opts.request_id ?? randomUUID() };+ return { ...await call('edit_page', params, opts.remote ?? true), params };+}+const fm = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n`;+const fencedBody = () => [+ 'Intro line.',+ 'Line one.',+ renderTakesFence([{ rowNum: 1, claim: SECRET_TAKE, kind: 'take', holder: 'people/alice-example', weight: 0.6, active: true } as never]),+ 'Line two to change.',+ renderFactsTable([+ { rowNum: 1, claim: 'Public fact example', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true } as never,+ { rowNum: 2, claim: SECRET_FACT, kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true } as never,+ ]),+ 'Line three.',+].join('\n\n');+async function seed(slug: string, body: string) {+ const put = await call('put_page', { slug, content: fm('Example') + body, request_id: randomUUID() }, false);+ expect({ isError: put.isError, text: put.text }).toMatchObject({ isError: false });+}+const versions = async (slug: string) => (await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug=$1', [slug]))[0].n;++describe('edit_page schema and catalog', () => {+ bunTest('tools/list shows the nested, closed edit object schema', () => {+ const def = buildToolDefs(operations.filter(op => op.name === 'edit_page'))[0];+ expect(def.inputSchema.required).toEqual(['slug', 'expected_revision', 'edits']);+ expect(def.inputSchema.properties.edits).toMatchObject({ type: 'array', items: {+ type: 'object', required: ['old_text', 'new_text'], additionalProperties: false,+ properties: { old_text: { type: 'string' }, new_text: { type: 'string' } } } });+ expect(def.description).toContain('prefer this over put_page');+ expect(STARTER_OPS.has('edit_page')).toBe(true);+ });+});++describe('edit_page matching', () => {+ test('a unique match publishes one new revision with a caller-view diff and write-through', async () => {+ await seed('notes/a', 'First line.\n\nSecond line.\n');+ const before = await read('notes/a');+ const result = await edit('notes/a', [{ old_text: 'Second line.', new_text: 'Second line, edited.' }]);+ expect({ isError: result.isError, text: result.text }).toMatchObject({ isError: false });+ expect(result.body.state).toBe('committed');+ expect(result.body.revision).toBeString();+ expect(result.body.revision).not.toBe(before.revision);+ expect(result.body.diff).toContain('-Second line.');+ expect(result.body.diff).toContain('+Second line, edited.');+ expect((await read('notes/a')).content).toBe(before.content.replace('Second line.', 'Second line, edited.'));+ expect(readFileSync(join(fixture, 'brain', 'notes/a.md'), 'utf8')).toContain('Second line, edited.');+ });++ test('zero and multiple matches refuse with the edit index and match count, admitting nothing', async () => {+ await seed('notes/b', 'Repeat.\n\nRepeat.\n\nOnce.\n');+ const requests = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests')).at(0)!.n;+ const admitted = await requests();+ const none = await edit('notes/b', [{ old_text: 'Once.', new_text: 'One.' }, { old_text: 'Missing', new_text: 'x' }]);+ expect(none.body).toMatchObject({ error: 'edit_no_match', detail: 'edit_index=1 match_count=0' });+ const many = await edit('notes/b', [{ old_text: 'Repeat.', new_text: 'x' }]);+ expect(many.body).toMatchObject({ error: 'edit_ambiguous_match', detail: 'edit_index=0 match_count=2' });+ const empty = await edit('notes/b', [{ old_text: '', new_text: 'x' }]);+ expect(empty.body).toMatchObject({ error: 'edit_invalid', detail: 'edit_index=0' });+ expect(await requests()).toBe(admitted);+ });++ test('edits apply in order against the previous result, and a failing third edit rolls back all three', async () => {+ await seed('notes/c', 'Alpha.\n\nBeta.\n');+ const before = await read('notes/c');+ const chained = await edit('notes/c', [{ old_text: 'Alpha.', new_text: 'Gamma.' }, { old_text: 'Gamma.', new_text: 'Delta.' }]);+ expect(chained.isError).toBe(false);+ expect((await read('notes/c')).content).toContain('Delta.');+ const mid = await read('notes/c');+ const failed = await edit('notes/c', [{ old_text: 'Delta.', new_text: 'One.' }, { old_text: 'Beta.', new_text: 'Two.' }, { old_text: 'Alpha.', new_text: 'Three.' }]);+ expect(failed.body).toMatchObject({ error: 'edit_no_match', detail: 'edit_index=2 match_count=0' });+ expect(await read('notes/c')).toEqual(mid);+ expect(mid.revision).not.toBe(before.revision);+ });++ test('a stale revision is a revision_conflict that carries the current revision', async () => {+ await seed('notes/d', 'Body.\n');+ const stale = (await read('notes/d')).revision;+ expect((await edit('notes/d', [{ old_text: 'Body.', new_text: 'Changed.' }])).isError).toBe(false);+ const current = (await read('notes/d')).revision;+ const conflict = await edit('notes/d', [{ old_text: 'Changed.', new_text: 'Again.' }], { revision: stale });+ expect(conflict.body).toMatchObject({ error: 'revision_conflict', detail: `current_revision=${current}` });+ });++ test('a bound client cannot edit outside its slug prefix', async () => {+ await seed('other/e', 'Body.\n');+ const refused = await call('edit_page', { slug: 'other/e', expected_revision: (await read('other/e', false)).revision,+ edits: [{ old_text: 'Body.', new_text: 'x' }], request_id: randomUUID() });+ expect(refused.body.error).toBe('permission_denied');+ });+});++describe('edit_page protected fences and privacy', () => {+ test('protected text never matches; canonical fences stay in place; private rows never reach diff, receipt, replay or poll', async () => {+ await seed('notes/f', fencedBody());+ const canonicalBefore = (await read('notes/f', false)).content;+ expect(canonicalBefore).toContain(SECRET_FACT);+ expect(canonicalBefore).toContain(SECRET_TAKE);+ // Local callers see the fences but may not edit inside them.+ expect((await edit('notes/f', [{ old_text: SECRET_TAKE, new_text: 'x' }], { remote: false })).body.error).toBe('edit_protected_span');+ expect((await edit('notes/f', [{ old_text: 'Public fact example', new_text: 'x' }], { remote: false })).body.error).toBe('edit_protected_span');+ // Remote callers cannot see hidden rows: they do not match and are never echoed.+ const hidden = await edit('notes/f', [{ old_text: SECRET_FACT, new_text: 'x' }]);+ expect(hidden.body.error).toBe('edit_no_match');+ expect(hidden.text).not.toContain(SECRET_FACT);+ expect((await edit('notes/f', [{ old_text: 'Public fact example', new_text: 'x' }])).body.error).toBe('edit_protected_span');+ expect((await edit('notes/f', [{ old_text: 'Line one.\n\n\n\nLine two', new_text: 'x' }])).body.error).toBe('edit_protected_span');+ const result = await edit('notes/f', [{ old_text: 'Line two to change.', new_text: 'Line two, changed.' }]);+ expect({ isError: result.isError, text: result.text }).toMatchObject({ isError: false });+ const replay = await call('edit_page', result.params);+ const poll = await call('get_write_request', { request_id: result.params.request_id });+ for (const surface of [result.text, replay.text, poll.text]) {+ expect(surface).not.toContain(SECRET_FACT);+ expect(surface).not.toContain(SECRET_TAKE);+ }+ expect(replay.body.revision).toBe(result.body.revision);+ expect(result.body.diff).toContain('+Line two, changed.');+ const canonicalAfter = (await read('notes/f', false)).content;+ expect(canonicalAfter).toBe(canonicalBefore.replace('Line two to change.', 'Line two, changed.'));+ });++ test('the edit surface is byte-equal to get_page content for remote and local readers', async () => {+ const bodies = ['Plain body.\n', fencedBody(), `${fencedBody()}\n\n<!-- timeline -->\n\n- 2026-01-02 Example entry`,+ `Body.\n\n<!-- timeline -->\n\n${renderTakesFence([{ rowNum: 1, claim: SECRET_TAKE, kind: 'take', holder: 'people/alice-example', weight: 0.5, active: true } as never])}`];+ for (const [i, body] of bodies.entries()) {+ const slug = `notes/view-${i}`;+ await seed(slug, body);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ for (const remote of [true, false]) {+ expect({ slug, remote, view: editableView(snapshot.page as Page, snapshot.tags, remote) }).toEqual({ slug, remote, view: (await read(slug, remote)).content });+ }+ expect(serializePageToMarkdown(snapshot.page as Page, snapshot.tags)).toBe((await read(slug, false)).content);+ }+ });+});++describe('edit_page timeline semantics', () => {+ test('removing a materialized timeline bullet deletes its row in one version; replay changes nothing', async () => {+ await seed('notes/t', 'Body.\n');+ const entry = await call('add_timeline_entry', { slug: 'notes/t', date: '2026-03-04', summary: 'Example milestone', request_id: randomUUID() });+ expect({ isError: entry.isError, text: entry.text }).toMatchObject({ isError: false });+ expect((await engine.getTimeline('notes/t', { sourceId: 'default' })).length).toBe(1);+ const view = (await read('notes/t')).content;+ const lines = view.split('\n');+ const bullet = lines.findIndex(line => line.includes('Example milestone'));+ expect(bullet).toBeGreaterThan(0);+ const marker = lines[bullet - 1].includes('gbrain:materialized') ? `${lines[bullet - 1]}\n` : '';+ const versionsBefore = await versions('notes/t');+ const removed = await edit('notes/t', [{ old_text: `${marker}${lines[bullet]}\n`, new_text: '' }]);+ expect({ isError: removed.isError, text: removed.text }).toMatchObject({ isError: false });+ expect((await read('notes/t')).content).not.toContain('Example milestone');+ expect(await engine.getTimeline('notes/t', { sourceId: 'default' })).toEqual([]);+ expect(await versions('notes/t')).toBe(versionsBefore + 1);+ const poll = await call('get_write_request', { request_id: removed.params.request_id });+ expect(poll.body.operation).toBe('edit_page');+ const replay = await call('edit_page', removed.params);+ expect(replay.body.revision).toBe(removed.body.revision);+ expect(await versions('notes/t')).toBe(versionsBefore + 1);+ expect(await engine.getTimeline('notes/t', { sourceId: 'default' })).toEqual([]);+ });+});diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.tsindex e8ef659442..b577126bae 100644--- a/test/mcp-tool-defs.test.ts+++ b/test/mcp-tool-defs.test.ts@@ -33,7 +33,10 @@ type ParamDefLike = {enum?: string[];default?: unknown;items?: ParamDefLike;+ required?: boolean;+ properties?: Record<string, ParamDefLike>;};+// #5616 (O-DX-3): object members map to closed `properties` + `required`.function referenceParamDefToSchema(p: ParamDefLike): Record<string, unknown> {return {type: p.type === 'array' ? 'array' : p.type,@@ -41,6 +44,11 @@ function referenceParamDefToSchema(p: ParamDefLike): Record<string, unknown> {...(p.enum ? { enum: p.enum } : {}),...(p.default !== undefined ? { default: p.default } : {}),...(p.items ? { items: referenceParamDefToSchema(p.items) } : {}),+ ...(p.properties ? {+ properties: Object.fromEntries(Object.entries(p.properties).map(([k, v]) => [k, referenceParamDefToSchema(v)])),+ required: Object.entries(p.properties).filter(([, v]) => v.required).map(([k]) => k),+ additionalProperties: false,+ } : {}),};}function legacyInlineMap(ops: typeof operations) {diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 09bf74e7ea..74d86c2f00 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -40,6 +40,7 @@ const LEDGER: Record<string, string> = {restore_page: 'test/pages-source-scoping-4329.test.ts',purge_deleted_pages: 'test/operations-trust-boundary.test.ts',capture: 'test/capture-op.test.ts',+ edit_page: 'test/edit-page.test.ts',get_write_request: 'test/persistence-receipt-operations.test.ts',list_write_requests: 'test/persistence-receipt-operations.test.ts',cancel_write_request: 'test/persistence-receipt-operations.test.ts',