Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(edit_page): review findings — bounded, redacted retained diff; usage and backstop parity
garrytanf39b1a9ce13f
diff --git a/src/core/mcp-usage.ts b/src/core/mcp-usage.tsindex e1193eaa02..4baf53469b 100644--- a/src/core/mcp-usage.ts+++ b/src/core/mcp-usage.ts@@ -14,7 +14,8 @@* 'tools/call:<name>' — the prefix is stripped and the row counts as <name>.* - 'surface_change' audit rows (ENG-8, src/core/surface-audit.ts) are* bookkeeping, not usage — dropped.- * - Only successful calls count ('success' / 'success_with_warnings').+ * - Only successful calls count ('success' / 'success_with_warnings' /+ * 'accepted_pending', an admitted write still in flight, #5249).* Denied and errored rows are not usage: a client repeatedly bouncing off* a gated op must not "use" its way into starter-set derivation or an* advisor fit finding (that would let denial traffic curate the catalog).@@ -129,7 +130,7 @@ export async function readClientOpUsage(FROM mcp_request_logWHERE created_at > now() - ($1::int * interval '1 day')AND token_name IS NOT NULL- AND status IN ('success', 'success_with_warnings')+ AND status IN ('success', 'success_with_warnings', 'accepted_pending')GROUP BY token_name, operation`,[days],);diff --git a/src/core/ops/page-edit.ts b/src/core/ops/page-edit.tsindex 9b8a3c3abc..6be8546b03 100644--- a/src/core/ops/page-edit.ts+++ b/src/core/ops/page-edit.ts@@ -9,7 +9,7 @@ import { EDIT_PAGE_MAX_EDITS, parsePageEdits } from '../persistence/page-edit.tsconst 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)" },+ outputRedaction: { exempt: "the diff is the caller's own authorized view of the page it just edited (the get_page boundary), secret-redacted when created because the receipt retains it" },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.' },diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.tsindex 977146bd14..faaa349eed 100644--- a/src/core/persistence/page-advisories.ts+++ b/src/core/persistence/page-advisories.ts@@ -13,7 +13,7 @@ export function remoteLinkHint(row: WriteRequest): Record<string, unknown> {hint: 'Body wikilinks are saved as text but NOT reconciled into the graph. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` (delegates to a live serve over IPC), use trusted local capture/put_page for inline link extraction, or add_link for edges needed now.' } } : {};}export function pageNoopAdvisories(row: WriteRequest): Record<string, unknown> {- return { ...remoteLinkHint(row), ...(['put_page', 'capture'].includes(row.operation) ? { facts_backstop: { skipped: 'not_imported' } } : {}) };+ return { ...remoteLinkHint(row), ...(['put_page', 'capture', 'edit_page'].includes(row.operation) ? { facts_backstop: { skipped: 'not_imported' } } : {}) };}/** Optional lint reads are outside publication locks; its bounded result is retained in the receipt. */export async function preparePageAdvisories(engine: BrainEngine, row: WriteRequest, page: ParsedPage) {@@ -22,7 +22,7 @@ export async function preparePageAdvisories(engine: BrainEngine, row: WriteRequeconst lint = await writerLintForPutPage(engine, row.slug, { sourceId: row.source_id, noLog: true, page: visible });const sanitized = lint && 'top_findings' in lint ? { ...lint,top_findings: lint.top_findings.map(finding => ({ ...finding, message: LINT_MESSAGES[finding.validator] ?? `${finding.validator} validation finding.` })) } : lint;- const facts = ['put_page', 'capture'].includes(row.operation)+ const facts = ['put_page', 'capture', 'edit_page'].includes(row.operation)? await prepareFactsBackstop(engine, row, page).catch(() => ({ skipped: 'backstop_error' })) : undefined;return { ...remoteLinkHint(row), ...(sanitized ? { writer_lint: sanitized } : {}), ...(facts ? { facts_backstop: facts } : {}) };}diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsindex a85eaeef05..5eb3fbebb1 100644--- a/src/core/persistence/page-edit.ts+++ b/src/core/persistence/page-edit.ts@@ -20,6 +20,7 @@ import { sanitizeRemoteBody } from '../remote-body.ts';import { sanitizeText } from '../batch-rows.ts';import { serializePageToMarkdown } from '../markdown.ts';import { unifiedDiff } from '../skillpack/diff-text.ts';+import { redactRetrievalOutput } from '../search/output-redaction.ts';export const EDIT_PAGE_MAX_EDITS = 50;export const EDIT_PAGE_DIFF_MAX_BYTES = 8 * 1024;@@ -169,15 +170,28 @@ export function applyPageEdits(page: Page, tags: string[], remote: boolean, editreturn { content: join(segments, 'canonical'), before, after: join(segments, 'view') };}-/** The caller-view unified diff, capped at 8 KB on a line boundary. */+const encodedBytes = (text: string) => Buffer.byteLength(JSON.stringify(text));++/**+ * The caller-view unified diff, secret-redacted like retrieval output (it is+ * retained in the receipt), cut on a line boundary so its JSON encoding fits+ * 8 KB: the receipt reserves exactly that much (EDIT_PAGE_RECEIPT_RESERVE).+ */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 };+ const [{ diff: full }] = redactRetrievalOutput([{ diff: unifiedDiff(before, after, { oldPath: `a/${slug}.md`, newPath: `b/${slug}.md` }) }], {}).results;+ if (encodedBytes(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full };+ const lines = full.split('\n');+ let kept = '';+ for (const line of lines) {+ if (encodedBytes(`${kept}${line}\n`) > EDIT_PAGE_DIFF_MAX_BYTES) break;+ kept += `${line}\n`;+ }+ return { diff: kept, diff_truncated: true };}+/** Extra terminal-receipt bytes an edit_page admission reserves for its diff. */+export const EDIT_PAGE_RECEIPT_RESERVE = EDIT_PAGE_DIFF_MAX_BYTES + 512;+/** 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;diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 9fd8d2a71a..b8e67406af 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -202,6 +202,8 @@ export async function submitPageMutation(ctx: OperationContext,}const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,+ ...(input.operation === 'edit_page' ? { terminalReservation: Math.max(16_384, Buffer.byteLength(JSON.stringify(authority)) + 8192)+ + (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE } : {}),worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, input.waitMs ?? ctx.writeWaitMs));}diff --git a/test/edit-page.test.ts b/test/edit-page.test.tsindex 5948c63bf6..51d021661e 100644--- a/test/edit-page.test.ts+++ b/test/edit-page.test.ts@@ -141,6 +141,17 @@ describe('edit_page matching', () => {expect(mid.revision).not.toBe(before.revision);});+ test('a large edit still commits; its retained diff is capped at 8 KB encoded and marked truncated', async () => {+ const lines = Array.from({ length: 400 }, (_, i) => `Line ${i} "quoted" text with a tab\tand more words to widen it.`);+ await seed('notes/big', `${lines.join('\n')}\n`);+ const result = await edit('notes/big', [{ old_text: lines.join('\n'), new_text: lines.map(line => `${line} Edited.`).join('\n') }]);+ expect({ isError: result.isError, text: result.text.slice(0, 300) }).toMatchObject({ isError: false });+ expect(result.body.diff_truncated).toBe(true);+ expect(Buffer.byteLength(JSON.stringify(result.body.diff))).toBeLessThanOrEqual(8 * 1024);+ const poll = await call('get_write_request', { request_id: result.params.request_id });+ expect(poll.body.outcome.diff).toBe(result.body.diff);+ });+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;