Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 3 lane 3a: segmented edit_page refuses a stored fence that does not compile
garrytan6b51e2d8a853
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex c26b06fca7..2868dc2e1d 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -39,7 +39,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the shareWrites that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): `append_page`, segmented `edit_page` and the splice engine both use. Tests: `test/large-pages/append-cost.test.ts`, `test/large-pages/append-concurrency.test.ts` and `test/large-pages/edit-segmented.test.ts`, PGLite and Postgres (helper `test/helpers/append-brain.ts`).- `src/core/page-body/splice.ts` + `tail-digest.ts` — byte-range splices of a segmented body. `spliceSegmentedBody` replaces stored byte ranges of the live generation (`BodyReplacement`) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (`rescanned`). `splicePage` reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); `spliceWork` counts segments segmented, bytes read and manifest rows (the cost tests' work counters). `tail-digest.ts` is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (`inlineTailDigest`; segmented pages use `page-window/segmented.ts` `tailDigest`); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (`appendProbe.fullRewrite`) fails the bound.-- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page shares; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write; links, timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter re-rendered in stored key order.+- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page shares; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write; links, timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end.-Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts or ends inside hidden facts or takes text, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.+Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts or ends inside hidden facts or takes text, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex f9e6265042..3b719f36e1 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -594,3 +594,4 @@ src/core/persistence/page-append.ts prepareAppendMutation sql META body_bytes, esrc/core/persistence/page-edit.ts applyPageEdits call:serializePageToMarkdown SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation firstsrc/core/persistence/page-edit.ts applyPageEdits field SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation firstsrc/core/persistence/page-edit.ts prepareSegmentedEditMutation call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segments+src/core/persistence/page-edit.ts assertSegmentedFencesCompile field NONE the fields hold only the stored fence text laid out at its lines (scanCanonicalFences input); no page body is readdiff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsindex 56ad237631..17393fba5b 100644--- a/src/core/persistence/page-edit.ts+++ b/src/core/persistence/page-edit.ts@@ -467,6 +467,52 @@ async function viewNewlinesBefore(engine: BrainEngine, input: { sourceId: stringreturn lines;}+/**+ * #6188 (D19) on a segmented page: scanCanonicalFences over the stored fence text (facts, takes, an unclosed tail's+ * first piece, stray markers), each piece at its own line of its section, so the refusal is the whole-body scan's,+ * location included. Only segments holding fence text are read. With `within`, only the fences in the segments it+ * touches and those crossing into them are checked.+ */+async function assertSegmentedFencesCompile(engine: BrainEngine, input: { sourceId: string; slug: string }, rows: readonly ManifestRow[], within?: EditWithin): Promise<void> {+ let pieces = rows.flatMap(row => (row.protectedRegions as StoredRegion[]).filter(r => PROTECTED_KINDS.has(r.kind))+ .map(r => ({ row, kind: r.kind, start: Number(row.byteStart) + r.start, end: Number(row.byteStart) + r.end }))).sort((x, y) => x.start - y.start);+ const firstTail = pieces.findIndex(p => p.kind === 'tail');+ if (firstTail !== -1) pieces = pieces.filter((p, i) => p.kind !== 'tail' || i === firstTail);+ if (within) {+ const touched = rows.filter(row => Number(row.byteStart) < within.byte_end && Number(row.byteStart) + row.byteLen > within.byte_start);+ if (!touched.length) return;+ const lo = Math.min(...touched.map(row => Number(row.byteStart))), hi = Math.max(...touched.map(row => Number(row.byteStart) + row.byteLen));+ const runs: Array<typeof pieces> = [];+ for (const piece of pieces) {+ const run = runs[runs.length - 1];+ if (run && piece.start <= run[run.length - 1]!.end) run.push(piece); else runs.push([piece]);+ }+ pieces = runs.filter(run => run[0]!.start < hi && run[run.length - 1]!.end > lo).flat();+ }+ if (!pieces.length) return;+ const count = (b: Uint8Array) => { let n = 0; for (let i = b.indexOf(0x0a); i !== -1; i = b.indexOf(0x0a, i + 1)) n++; return n; };+ const texts = new Map<number, Uint8Array>();+ for await (const [row, text] of rowTexts(engine, input.sourceId, [...new Set(pieces.map(p => p.row))])) texts.set(Number(row.byteStart), text);+ const sections = { truth: { text: [] as Buffer[], lines: 0, first: 0 }, timeline: { text: [] as Buffer[], lines: 0, first: 0 } };+ for (const region of ['truth', 'timeline'] as const) sections[region].first = rows.find(row => row.region === region)?.lineStart ?? 0;+ for (const piece of pieces) {+ const section = sections[piece.row.region === 'timeline' ? 'timeline' : 'truth'];+ const text = texts.get(Number(piece.row.byteStart))!, at = piece.start - Number(piece.row.byteStart);+ const line = piece.row.lineStart - section.first + count(text.subarray(0, at));+ if (line > section.lines) { section.text.push(Buffer.from('\n'.repeat(line - section.lines))); section.lines = line; }+ const bytes = Buffer.from(text.subarray(at, piece.end - Number(piece.row.byteStart)));+ section.text.push(bytes);+ section.lines += count(bytes);+ }+ const [defect] = scanCanonicalFences({ compiled_truth: Buffer.concat(sections.truth.text).toString('utf8'), timeline: Buffer.concat(sections.timeline.text).toString('utf8') }).defects;+ if (defect) throw targetFenceRefusal(defect, input.slug, input.sourceId);+}++/** Submission's fence check of a segmented page's live body, as applyPageEdits refuses an inline one before admission; preparation repeats it. */+export async function assertSegmentedEditFences(engine: BrainEngine, page: { id?: number | null; slug: string; source_id: string }, within?: EditWithin): Promise<void> {+ await assertSegmentedFencesCompile(engine, { sourceId: page.source_id, slug: page.slug }, await engine.readManifest(Number(page.id)), within);+}+function protectedSpans(rows: readonly ManifestRow[], markers = true): Array<{ start: number; end: number }> {return rows.flatMap(row => (row.protectedRegions as StoredRegion[]).filter(r => PROTECTED_KINDS.has(r.kind) && (markers || r.kind !== 'marker')).map(r => ({ start: Number(row.byteStart) + r.start, end: Number(row.byteStart) + r.end })));@@ -491,6 +537,7 @@ export async function locateSegmentedEdits(engine: BrainEngine, input: { sourceIconst { page, within } = input;const rows = await engine.readManifest(page.id, { generation: page.generation });spliceWork.rows += rows.length;+ await assertSegmentedFencesCompile(engine, input, rows, within);const guarded = protectedSpans(rows);const regions = [{ lo: 0, hi: page.truthBytes, rows: rows.filter(r => r.region === 'truth') },{ lo: page.truthBytes, hi: page.bodyBytes, rows: rows.filter(r => r.region === 'timeline') }];diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 3ab5ff545f..078e5ac723 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -365,13 +365,13 @@ export async function preparePageAdmission(ctx: OperationContext,? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at) : null;// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.if (input.operation === 'edit_page') {- const { applyPageEdits, assertEditRevision, parseEditWithin, parsePageEdits } = await import('./page-edit.ts');+ const { applyPageEdits, assertEditRevision, assertSegmentedEditFences, parseEditWithin, 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);const within = parseEditWithin(p.within);// A segmented page is matched by its preparation, which streams the segments (spec 6.3): never read whole here.if (!isSegmentedPage(snapshot.page)) applyPageEdits(snapshot.page, snapshot.tags, ctx.remote !== false, parsePageEdits(p.edits), within);- else parsePageEdits(p.edits);+ else { parsePageEdits(p.edits); await assertSegmentedEditFences(ctx.engine, snapshot.page, within); }}// Wave B: an append names an existing page; its preconditions are checked when it is prepared, on the page it extends.if (input.operation === 'append_page' && (!snapshot || snapshot.page.deleted_at)) {diff --git a/test/large-pages/edit-segmented.test.ts b/test/large-pages/edit-segmented.test.tsindex 553f4ee8d6..8f5fc53aa8 100644--- a/test/large-pages/edit-segmented.test.ts+++ b/test/large-pages/edit-segmented.test.ts@@ -28,6 +28,8 @@ const FENCED = 'notes/edit-fenced';const INLINE = 'notes/edit-inline';const HIDDEN_A = 'notes/edit-hidden-a';const HIDDEN_B = 'notes/edit-hidden-b';+const MALFORMED = 'notes/edit-malformed';+const INLINE_MALFORMED = 'notes/edit-malformed-inline';const fm = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n`;for (const kind of testBackends()) {@@ -148,6 +150,31 @@ for (const kind of testBackends()) {expect(newlines(prefix) - newlines(view(prefix))).toBeGreaterThan(0);}, 600_000);+ test('a stored fence that does not compile refuses the edit as the whole-body path does', async () => {+ const bad = '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n'+ + '| 1 | a synthetic claim | fact | 1.0 | blorp | medium | 2026-01-01 | | chat | |\n<!--- gbrain:facts:end -->\n';+ const tail = conversationBody(1_200_000, { seed: 10 });+ await brain.seed(MALFORMED, fm('Malformed') + 'Intro.\n\n' + bad + '\n' + tail + '\n');+ expect((await brain.body(MALFORMED)).storage).toBe('segmented');+ const truth = (await brain.body(MALFORMED)).truth;+ const far = truth.slice(truth.length - 5000, truth.length - 4940);+ const near = truth.slice(truth.indexOf(tail), truth.indexOf(tail) + 60);+ for (const old of [far, near]) expect(truth.indexOf(old)).toBe(truth.lastIndexOf(old));+ const rev = await revision(MALFORMED);+ const refused = (res: { body: Record<string, any> }) => ({ error: res.body.error, code: res.body.code, reason: res.body.reason, fence: res.body.fence });+ // The whole-body path's refusal, on an inline page holding the same fence.+ expect(await brain.call('put_page', { slug: INLINE_MALFORMED, content: fm('Inline') + 'Intro.\n\nSynthetic prose.\n', request_id: randomUUID() })).toMatchObject({ isError: false });+ await brain.engine.executeRaw("UPDATE pages SET compiled_truth=$2 WHERE source_id='default' AND slug=$1", [INLINE_MALFORMED, 'Intro.\n\n' + bad + '\nSynthetic prose.\n']);+ const expected = refused(await edit(INLINE_MALFORMED, await revision(INLINE_MALFORMED), 'Synthetic prose.', 'x'));+ expect(expected).toMatchObject({ error: 'invalid_params', code: 'invalid_fence', reason: 'target_fence_malformed', fence: { fence: 'facts', section: 'body', rows: [1], line: 6 } });+ // No within: the whole page is checked, so an edit far from the fence refuses.+ expect(refused(await edit(MALFORMED, rev, far, 'x'))).toEqual(expected);+ // within: the touched segments and the fences crossing into them are checked.+ const at = Buffer.byteLength(truth.slice(0, truth.indexOf(near)));+ expect(refused(await edit(MALFORMED, rev, near, 'x', { byte_start: 0, byte_end: at + 60 }))).toEqual(expected);+ expect(await revision(MALFORMED)).toBe(rev);+ }, 600_000);+test('within on an inline page and from a remote writer', async () => {const content = fm('Inline') + ['Intro line.', DUP, 'Middle line.', DUP, 'Last line.'].join('\n\n') + '\n';expect(await brain.call('put_page', { slug: INLINE, content, request_id: randomUUID() })).toMatchObject({ isError: false });