Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(wave-b): segmented edit_page reads through the withdrawal overlay, refuses a remote within past hidden text, append_page in page-write lists
garrytan83f2448a9a83
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 8e72299fea..488e12681d 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -43,6 +43,6 @@ Writes that change part of a page in time proportional to the change (Wave B spe- `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; an insertion at the truth/timeline boundary belongs to truth (`replacementRegion`), so exactly one row owns it. 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 and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; 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.+- `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 (`read-range.ts` `hiddenBefore`).-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; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) 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.+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 remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. 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; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) 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 at or inside hidden facts or takes text, nor ends inside it, 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). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). 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/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.tsindex f45a1215dd..babf288802 100644--- a/src/core/chronicle/ledger.ts+++ b/src/core/chronicle/ledger.ts@@ -15,7 +15,7 @@ import { isChronicleEligible, isChronicleShaped } from './eligibility.ts';import { chronicleBackstopReceipt, type ChronicleBackstopReceipt, type ChronicleReasonCode, type ChronicleReasonContext } from './reasons.ts';/** Publications that import page content and therefore carry a decision (C1). */-const DECIDING_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'restore_page', 'revert_version']);+const DECIDING_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'append_page', 'restore_page', 'revert_version']);const DECIDING_INTENTS = new Set(['managed_sync_import', 'connector_v2_import']);/** Skip reasons after which an earlier extracted generation of the page is retired (E8). */export const RETIRE_REASONS = ['not_chronicle_shaped', 'dream_generated', 'too_short'] as const;diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex ac968b640d..37bbbb039e 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -45,7 +45,7 @@ import {import {markdownDigest, markdownHead, readViewLines, segmentedMarkdownDocument, segmentedOutline, segmentedReadDocument, tailDigest, type SegmentedDocument,} from '../page-window/segmented.ts';-import { confirmBodyPin, openSegmentedBody, type BodyPin } from '../page-body/read-range.ts';+import { confirmBodyPin, hiddenBefore, openSegmentedBody, type BodyPin } from '../page-body/read-range.ts';import { inlineRegions, inlineTailDigest } from '../page-body/tail-digest.ts';import { TIMELINE_SEPARATOR } from '../page-window/document.ts';import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';@@ -393,7 +393,6 @@ async function editTarget(ctx: OperationContext, page: Page, doc: WindowDocumentif (doc.segments) {const seg = doc.segments;const { rows, truthBytes, bodyBytes } = seg.body;- let hidden = false;/** Stored offset of read-view byte `p`: a window start (the unit holding p) or end (the unit holding p - 1). */const map = (p: number, side: 'start' | 'end') => {if (p >= seg.total) return bodyBytes;@@ -404,11 +403,7 @@ async function editTarget(ctx: OperationContext, page: Page, doc: WindowDocumentif (u.bytes === row.byteLen && !row.hasFacts) return row.byteStart + Math.min(row.byteLen, p - u.start);return side === 'start' ? row.byteStart : row.byteStart + row.byteLen;};- for (const u of seg.units) {- if (u.start >= win.byte_end) break;- if (u.row < 0 ? u.text !== TIMELINE_SEPARATOR : (u.bytes !== rows[u.row]!.byteLen || rows[u.row]!.hasFacts)) hidden = true;- }- if (remote && hidden) return undefined;+ if (remote && await hiddenBefore(ctx.engine, seg.body, win.byte_end, 'projected')) return undefined;const start = map(win.byte_start, 'start');return { revision, byte_start: start, byte_end: Math.max(start, map(win.byte_end, 'end')) };}diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex 864951fcac..750eaec0e1 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -366,6 +366,18 @@ export function projectedUnits(body: SegmentedBody, layout: ProjectedLayout): Unreturn out;}+/**+ * Whether text the read projection hides or rewrites starts before `end` (read-view bytes, or stored bytes): a row whose+ * projection is not its stored bytes or that holds facts, the low-tier block, or (stored) a timeline the view omits.+ * Stored offsets past such text would measure it for a remote caller (get_page edit_target, edit_page `within`).+ */+export async function hiddenBefore(engine: BrainEngine, body: SegmentedBody, end: number, space: 'projected' | 'stored'): Promise<boolean> {+ const layout = await projectedLayout(engine, body);+ if (space === 'stored' && layout.timelineByte < 0 && body.bodyBytes > body.truthBytes && end > body.truthBytes) return true;+ return projectedUnits(body, layout).some(u => (space === 'projected' ? u.start : u.kind === 'row' ? body.rows[u.index]!.byteStart : u.storedStart) < end+ && (u.kind === 'text' ? u.text !== TIMELINE_SEPARATOR : layout.rowBytes[u.index] !== body.rows[u.index]!.byteLen || body.rows[u.index]!.hasFacts));+}+const unitBytes = (u: Unit, layout: ProjectedLayout) => u.kind === 'row' ? layout.rowBytes[u.index]! : Buffer.byteLength(u.text, 'utf8');/** One segment of the trusted body: its row, its stored bytes and entry state, and its text after the withdrawal overlay in pieces. */diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 8e806516a2..0f7ca821f7 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -87,7 +87,7 @@ function syncMember(row: WriteRequest): boolean {}/** Single page writes that may publish as a group of one (Phase 4.1); owner-internal kinds keep the single path. */-const SINGLE_GROUP_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'delete_page', 'restore_page', 'revert_version']);+const SINGLE_GROUP_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'append_page', 'delete_page', 'restore_page', 'revert_version']);export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): boolean {return SINGLE_GROUP_OPERATIONS.has(row.operation) && !row.intent?.kind && publicationGroupKey(row) === null;}diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.tsindex 93d37e7b0e..cbe0a7b6b1 100644--- a/src/core/persistence/page-advisories.ts+++ b/src/core/persistence/page-advisories.ts@@ -92,7 +92,7 @@ export function remoteLinkHint(row: WriteRequest): Record<string, unknown> {hint: 'Body wikilinks are saved as text but NOT reconciled into the graph inline. With mention_links: queued, a post-commit `links` effect (listed by get_write_request) adds plain mention edges to existing pages this connection can read; typed and frontmatter edges are not added. 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', 'edit_page'].includes(row.operation) ? { facts_backstop: { skipped: 'not_imported' } } : {}) };+ return { ...remoteLinkHint(row), ...(['put_page', 'capture', 'edit_page', 'append_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, before: PageSnapshot | null = null) {@@ -101,7 +101,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', 'edit_page'].includes(row.operation)+ const facts = ['put_page', 'capture', 'edit_page', 'append_page'].includes(row.operation)? await prepareFactsBackstop(engine, row, page, before).catch(() => ({ skipped: 'backstop_error' })) : undefined;const grammar = await lineGrammarAdvisory(engine, row, visible).catch((e: unknown): Record<string, unknown> => ({ state: 'diagnostics_failed',message: `Line-grammar diagnostics failed (${e instanceof Error ? e.message : String(e)}); the page was saved, but nothing is known about its typed lines.`,diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsindex d97c639bda..64ee7e685c 100644--- a/src/core/persistence/page-edit.ts+++ b/src/core/persistence/page-edit.ts@@ -28,8 +28,11 @@ import type { ManifestRow } from '../page-body/types.ts';import type { StoredRegion } from '../page-body/segmenter.ts';import type { BodyReplacement, SplicePage } from '../page-body/splice.ts';import { spliceWork } from '../page-body/splice.ts';-import { withoutBody } from '../page-body/page-shape.ts';+import { isSegmentedPage, withoutBody } from '../page-body/page-shape.ts';import { STAGE_BATCH_BYTES } from '../page-body/limits.ts';+import { readEntryState } from '../page-body/entry-state.ts';+import { hiddenBefore, openSegmentedBody, trustedSegments, type SegmentedBody } from '../page-body/read-range.ts';+import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';import { TIMELINE_SEPARATOR } from '../page-window/document.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import type { WriteRequest } from './model.ts';@@ -53,6 +56,8 @@ 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;+/** A segmented page's remote edit view, spliced or whole-body: as in its remote windows (read-range.ts), a withdrawn fact row is not shown. */+const SEGMENTED_REMOTE_VIEW = { 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);@@ -98,7 +103,22 @@ export function parseEditWithin(value: unknown): EditWithin | undefined {return { byte_start: record.byte_start as number, byte_end: record.byte_end as number };}-function bodySegments(body: string, remote: boolean): Segment[] {+/**+ * A remote caller's `within` that reaches past text its view hides would measure that text (get_page withholds+ * edit_target for such a range): one refusal for every such range and every edit, before anything is matched.+ */+function hiddenWithinError(): OperationError {+ return editError('edit_invalid', 'within reaches past text this caller cannot see, so it cannot be used here.',+ 'Omit within and quote text that occurs once, or pass the edit_target of a get_page window read unchanged (it is given only for a range with nothing hidden before it).');+}++/** The remote `within` check of a segmented page: the read projection's hidden text, as get_page's editTarget tests it. */+async function assertSegmentedWithinVisible(engine: BrainEngine, page: { pageId: number; generation?: number; ledger?: BodyLedger }, within: EditWithin | undefined, remote: boolean): Promise<void> {+ if (!remote || !within) return;+ if (await hiddenBefore(engine, await openSegmentedBody(engine, page), within.byte_end, 'stored')) throw hiddenWithinError();+}++function bodySegments(body: string, remote: boolean, segmented: 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.');@@ -117,7 +137,7 @@ function bodySegments(body: string, remote: boolean): Segment[] {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 });+ segments.push({ canonical: fence, view: remote ? sanitizeRemoteBody(fence, segmented ? SEGMENTED_REMOTE_VIEW : REMOTE_VIEW) : fence, editable: false });open = undefined;}if (open) throw unrepairedFence();@@ -138,11 +158,12 @@ function unrepairedFence(): OperationError {*/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 segmented = isSegmentedPage(page);+ const timeline = bodySegments(page.timeline ?? '', remote, segmented);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),+ const pieces = [text(head), ...bodySegments(page.compiled_truth ?? '', remote, segmented),...(page.timeline ? [sentinelSegment, ...timeline] : []), text('\n')];return pieces.reduce<Segment[]>((out, piece) => {const last = out[out.length - 1];@@ -191,6 +212,13 @@ export function applyPageEdits(page: Page, tags: string[], remote: boolean, edit};const storedByte = (pos: number) => pos >= head && pos <= head + truth.length ? Buffer.byteLength(truth.slice(0, pos - head), 'utf8'): page.timeline && pos >= timelineAt && pos <= timelineAt + timeline.length ? Buffer.byteLength(truth, 'utf8') + Buffer.byteLength(timeline.slice(0, pos - timelineAt), 'utf8') : -1;+ if (remote && within) {+ let at = 0;+ for (const segment of segments) {+ if (segment.view !== segment.canonical && Math.max(0, storedByte(at)) < within.byte_end) throw hiddenWithinError();+ at += segment.canonical.length;+ }+ }const inRange = (start: number, end: number) => {if (!within) return true;const s = storedByte(original(start, 'start')), e = storedByte(original(end, 'end'));@@ -356,8 +384,13 @@ const DIFF_SCOPE_MAX_BYTES = 256 * 1024;const hexOf = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');-/** A run of the edited body: original stored bytes [origStart, origEnd), or a replacement's bytes standing for that span. */-interface Piece { origStart: number; origEnd: number; bytes: Uint8Array; replaced: boolean }+/**+ * A run of the edited body: original stored bytes [origStart, origEnd), or a replacement's bytes standing for that span. A+ * block the page's withdrawal overlay rewrote is one piece: `bytes` is the overlaid text, `withdrawn` the stored bytes.+ */+interface Piece { origStart: number; origEnd: number; bytes: Uint8Array; replaced: boolean; withdrawn?: Uint8Array }+/** Where a segmented edit reads stored text: with `body` (opened with a ledger that applies) through the withdrawal overlay. */+interface TextSource { sourceId: string; body?: SegmentedBody }/** Live rows' texts, read in batches of at most STAGE_BATCH_BYTES. */async function* rowTexts(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[]): AsyncIterable<[ManifestRow, Uint8Array]> {@@ -376,14 +409,47 @@ async function* rowTexts(engine: BrainEngine, sourceId: string, rows: readonly M}}+/**+ * One region's text over original [from, to), as the caller's reader sees it: the stored bytes, or with a ledger that+ * applies the trusted body after the withdrawal overlay (read-range.ts trustedSegments), whose rows are widened to whole+ * fence blocks so the overlay sees each block whole; a block it rewrote is emitted whole when it touches the range.+ */+async function* storedPieces(engine: BrainEngine, src: TextSource, rows: readonly ManifestRow[], from: number, to: number): AsyncIterable<Piece> {+ let i = rows.findIndex(row => Number(row.byteStart) + row.byteLen > from);+ let j = rows.findIndex(row => Number(row.byteStart) >= to);+ if (j === -1) j = rows.length;+ if (i === -1 || i >= j) return;+ if (!src.body) {+ for await (const [row, text] of rowTexts(engine, src.sourceId, rows.slice(i, j))) {+ const start = Number(row.byteStart), cur = Math.max(from, start), end = Math.min(to, start + row.byteLen);+ yield { origStart: cur, origEnd: end, bytes: text.subarray(cur - start, end - start), replaced: false };+ }+ return;+ }+ const open = (row: ManifestRow) => readEntryState(row.entryState)?.withdrawal.open === true;+ while (i > 0 && open(rows[i]!)) i--;+ while (j < rows.length && open(rows[j]!)) j++;+ const starts = new Set(rows.slice(i, j).map(row => Number(row.byteStart)));+ for await (const seg of trustedSegments(engine, src.body, src.body.rows.filter(row => starts.has(row.byteStart)))) {+ for (const piece of seg.pieces) {+ const s = seg.row.byteStart + piece.rawStart, e = seg.row.byteStart + piece.rawEnd;+ const bytes = Buffer.from(piece.text, 'utf8');+ if (piece.linear) {+ if (e > from && s < to) yield { origStart: Math.max(from, s), origEnd: Math.min(to, e), bytes: bytes.subarray(Math.max(from, s) - s, Math.min(to, e) - s), replaced: false };+ } else if ((e > from && s < to) || (s === e && s >= from && s < to)) {+ yield { origStart: s, origEnd: e, bytes, replaced: false, withdrawn: seg.raw.subarray(piece.rawStart, piece.rawEnd) };+ }+ }+ }+}+/** The body's bytes over original [from, to) of one region with `reps` applied, as pieces in order. */-async function* virtualPieces(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], reps: readonly BodyReplacement[], from: number, to: number): AsyncIterable<Piece> {- const covering = rows.filter(row => Number(row.byteStart) < to && Number(row.byteStart) + row.byteLen > from);+async function* virtualPieces(engine: BrainEngine, src: TextSource, rows: readonly ManifestRow[], reps: readonly BodyReplacement[], from: number, to: number): AsyncIterable<Piece> {const emitted = new Set<BodyReplacement>();- for await (const [row, text] of rowTexts(engine, sourceId, covering)) {- const start = Number(row.byteStart);- let cur = Math.max(from, start);- const end = Math.min(to, start + row.byteLen);+ for await (const piece of storedPieces(engine, src, rows, from, to)) {+ if (piece.withdrawn) { yield piece; continue; }+ const { origStart: start, origEnd: end, bytes: text } = piece;+ let cur = start;for (const r of reps) {if (r.end <= cur || r.start >= end) continue;if (r.start > cur) yield { origStart: cur, origEnd: r.start, bytes: text.subarray(cur - start, r.start - start), replaced: false };@@ -401,14 +467,14 @@ interface Match { start: number; end: number; prefix: Uint8Array; suffix: Uint8A* coordinates: a match end inside a replacement takes that replacement's whole span, and the replacement's bytes* before (`prefix`) and after (`suffix`) the match. Memory is one scan window plus |needle| - 1 bytes.*/-async function regionMatches(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], reps: readonly BodyReplacement[], from: number, to: number,+async function regionMatches(engine: BrainEngine, src: TextSource, rows: readonly ManifestRow[], reps: readonly BodyReplacement[], from: number, to: number,needle: Buffer, accept: (m: Match) => boolean, limit: number): Promise<Match[]> {const found: Match[] = [];let buf = Buffer.alloc(0);let map: Array<Piece & { v: number }> = [];const locate = (v: number, side: 'start' | 'end') => {const p = side === 'start' ? map.find(m => v >= m.v && v < m.v + m.bytes.length)! : map.find(m => v > m.v && v <= m.v + m.bytes.length)!;- if (!p.replaced) return { orig: p.origStart + (v - p.v), rest: new Uint8Array() };+ if (!p.replaced && !p.withdrawn) return { orig: p.origStart + (v - p.v), rest: new Uint8Array() };return side === 'start' ? { orig: p.origStart, rest: p.bytes.subarray(0, v - p.v) } : { orig: p.origEnd, rest: p.bytes.subarray(v - p.v) };};const search = (final: boolean) => {@@ -416,7 +482,8 @@ async function regionMatches(engine: BrainEngine, sourceId: string, rows: readonfor (let at = buf.indexOf(needle); at !== -1 && at < end && found.length < limit; at = buf.indexOf(needle, at + 1)) {const s = locate(at, 'start'), e = locate(at + needle.length, 'end');const match = { start: s.orig, end: e.orig, prefix: s.rest, suffix: e.rest };- if (!accept(match)) continue;+ // A match into a block the withdrawal overlay rewrote is never kept: accept still sees its whole stored span.+ if (!accept(match) || map.some(m => m.withdrawn && m.v < at + needle.length && m.v + m.bytes.length > at)) continue;spliceWork.matches++;found.push(match);}@@ -425,7 +492,7 @@ async function regionMatches(engine: BrainEngine, sourceId: string, rows: readonmap = map.filter(m => m.v + m.bytes.length > keep).map(m => ({ ...m, v: m.v - keep }));buf = buf.subarray(keep);};- for await (const piece of virtualPieces(engine, sourceId, rows, reps, from, to)) {+ for await (const piece of virtualPieces(engine, src, rows, reps, from, to)) {if (!piece.bytes.length) continue;map.push({ ...piece, v: buf.length });buf = Buffer.concat([buf, piece.bytes]);@@ -453,7 +520,7 @@ function hiddenRuns(rows: readonly ManifestRow[]): Array<{ start: number; end: n* line counts, the separator before the timeline and the containing row's prefix. A remote view renders each hidden* run before `at` as sanitizeRemoteBody does, so only those runs are read, never the ordinary text before `at`.*/-async function viewNewlinesBefore(engine: BrainEngine, input: { sourceId: string; remote: boolean; head: string }, rows: readonly ManifestRow[],+async function viewNewlinesBefore(engine: BrainEngine, input: TextSource & { remote: boolean; head: string }, rows: readonly ManifestRow[],timeline: boolean, at: number): Promise<number> {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 before = rows.filter(row => Number(row.byteStart) < at && (timeline || row.region === 'truth'));@@ -463,10 +530,10 @@ async function viewNewlinesBefore(engine: BrainEngine, input: { sourceId: stringfor await (const [row, text] of rowTexts(engine, input.sourceId, containing)) lines += count(text.subarray(0, at - Number(row.byteStart)));if (!input.remote) return lines;for (const run of hiddenRuns(rows).filter(r => r.end <= at)) {- const raw: Buffer[] = [];- for await (const piece of virtualPieces(engine, input.sourceId, rows, [], run.start, run.end)) raw.push(Buffer.from(piece.bytes));- const text = Buffer.concat(raw);- lines += count(Buffer.from(sanitizeRemoteBody(text.toString('utf8'), REMOTE_VIEW), 'utf8')) - count(text);+ const text: Buffer[] = [];+ let stored = 0;+ for await (const piece of virtualPieces(engine, input, rows, [], run.start, run.end)) { text.push(Buffer.from(piece.bytes)); stored += count(piece.withdrawn ?? piece.bytes); }+ lines += count(Buffer.from(sanitizeRemoteBody(Buffer.concat(text).toString('utf8'), SEGMENTED_REMOTE_VIEW), 'utf8')) - stored;}return lines;}@@ -513,7 +580,8 @@ async function assertSegmentedFencesCompile(engine: BrainEngine, input: { source}/** 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> {+export async function assertSegmentedEditFences(engine: BrainEngine, page: { id?: number | null; slug: string; source_id: string }, within: EditWithin | undefined, remote: boolean): Promise<void> {+ await assertSegmentedWithinVisible(engine, { pageId: Number(page.id) }, within, remote);await assertSegmentedFencesCompile(engine, { sourceId: page.source_id, slug: page.slug }, await engine.readManifest(Number(page.id)), within);}@@ -537,11 +605,13 @@ export interface LocatedSegmentedEdits {* head, or (without `within`, within the whole-body limit) one the body does not hold, which that path settles exactly.*/export async function locateSegmentedEdits(engine: BrainEngine, input: { sourceId: string; slug: string; page: SplicePage; edits: PageEdit[]; within?: EditWithin;- remote: boolean; head: string }): Promise<LocatedSegmentedEdits | null> {+ remote: boolean; head: string; ledger: BodyLedger }): Promise<LocatedSegmentedEdits | null> {const { page, within } = input;const rows = await engine.readManifest(page.id, { generation: page.generation });spliceWork.rows += rows.length;+ await assertSegmentedWithinVisible(engine, { pageId: page.id, generation: page.generation, ledger: input.ledger }, within, input.remote);await assertSegmentedFencesCompile(engine, input, rows, within);+ const src: TextSource = { sourceId: input.sourceId, ...(ledgerApplies(input.ledger) ? { body: await openSegmentedBody(engine, { pageId: page.id, generation: page.generation, ledger: input.ledger }) } : {}) };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') }];@@ -561,7 +631,7 @@ export async function locateSegmentedEdits(engine: BrainEngine, input: { sourceIconst from = within ? Math.max(region.lo, within.byte_start) : region.lo;const to = within ? Math.min(region.hi, within.byte_end) : region.hi;if (from >= to || allowed.length >= 2) continue;- for (const m of await regionMatches(engine, input.sourceId, region.rows, reps, from, to, needle, keep, 2 - allowed.length)) allowed.push(m);+ for (const m of await regionMatches(engine, src, region.rows, reps, from, to, needle, keep, 2 - allowed.length)) allowed.push(m);}if (allowed.length === 0 && protectedHit) {throw editError('edit_protected_span', `Edit ${index}'s old_text touches a protected takes or facts section.`,@@ -583,40 +653,55 @@ export async function locateSegmentedEdits(engine: BrainEngine, input: { sourceIreps = [...reps.filter(r => !absorbed.includes(r)), { start: m.start, end: m.end, bytes: Buffer.concat([m.prefix, Buffer.from(edit.new_text, 'utf8'), m.suffix]) }].sort((a, b) => a.start - b.start);}- return { replacements: reps, diff: await segmentedEditDiff(engine, input, rows, regions, reps) };+ return { replacements: reps, diff: await segmentedEditDiff(engine, { ...input, ...src }, rows, regions, reps) };}-/** editDiff over the touched range (line-rounded, with context), in the caller's view: remote text is sanitized as get_page shows it. */-async function segmentedEditDiff(engine: BrainEngine, input: { sourceId: string; slug: string; remote: boolean; head: string }, rows: readonly ManifestRow[],+/**+ * editDiff over the touched range (line-rounded, with context), in the caller's view: the text after the withdrawal+ * overlay, and for a remote caller sanitized as its windows show it.+ */+async function segmentedEditDiff(engine: BrainEngine, input: TextSource & { slug: string; remote: boolean; head: string }, rows: readonly ManifestRow[],regions: ReadonlyArray<{ lo: number; hi: number; rows: ManifestRow[] }>, reps: readonly BodyReplacement[]): Promise<Record<string, unknown>> {let scoped = reps;if (reps[reps.length - 1]!.end - reps[0]!.start > DIFF_SCOPE_MAX_BYTES || regions.some(r => reps[0]!.start < r.hi && reps[reps.length - 1]!.end > r.hi)) scoped = reps.slice(0, 1);const region = regions.find(r => scoped[0]!.start >= r.lo && scoped[0]!.start < r.hi) ?? regions[0]!;let from = Math.max(region.lo, scoped[0]!.start - DIFF_CONTEXT_BYTES), to = Math.min(region.hi, scoped[scoped.length - 1]!.end + DIFF_CONTEXT_BYTES);- // Context never starts or ends inside hidden text: a slice of a fence is not sanitized as the fence is.+ // Context never starts at or inside hidden text, nor ends inside it: line rounding would cut a fence's marker off, and a slice of a fence is not sanitized as the fence is.for (const run of hiddenRuns(rows)) {- if (run.start < from && from < run.end) from = run.end;- if (run.start < to && to < run.end) to = run.start;+ if (run.start <= from && from < run.end) from = run.end;+ if (run.start < to && to <= run.end) to = run.start;}- const original: Buffer[] = [];- for await (const piece of virtualPieces(engine, input.sourceId, region.rows, [], from, to)) original.push(Buffer.from(piece.bytes));- let raw = Buffer.concat(original);- let lo = scoped[0]!.start - from, hi = scoped[scoped.length - 1]!.end - from;+ const pieces: Array<Piece & { v: number }> = [];+ let size = 0;+ for await (const piece of virtualPieces(engine, input, region.rows, [], from, to)) { pieces.push({ ...piece, v: size }); size += piece.bytes.length; }+ let raw = Buffer.concat(pieces.map(p => p.bytes));+ /** A stored byte of the context (in ordinary text or at a piece's edge) as a byte of `raw`. */+ const viewAt = (stored: number) => {+ const p = pieces.find(q => stored >= q.origStart && stored <= q.origEnd);+ if (!p) return stored < from ? 0 : raw.length;+ return p.withdrawn ? (stored === p.origStart ? p.v : p.v + p.bytes.length) : p.v + stored - p.origStart;+ };+ /** A byte of `raw` as a stored byte (a block the overlay rewrote maps to its edges). */+ const storedAt = (v: number) => {+ const p = pieces.find(q => v >= q.v && v <= q.v + q.bytes.length);+ if (!p) return v <= 0 ? from : to;+ return p.withdrawn ? (v === p.v ? p.origStart : p.origEnd) : p.origStart + v - p.v;+ };+ const lo = viewAt(scoped[0]!.start), hi = viewAt(scoped[scoped.length - 1]!.end);const head = from === region.lo ? 0 : raw.indexOf(0x0a) + 1;const tailNl = to === region.hi ? raw.length : raw.lastIndexOf(0x0a) + 1;const start = head > 0 && head <= lo ? head : (from === region.lo ? 0 : lo), end = tailNl >= hi && tailNl > 0 ? tailNl : hi;const slice = (buf: Buffer, a: number, b: number) => { while (a > 0 && (buf[a]! & 0xc0) === 0x80) a--; while (b < buf.length && (buf[b]! & 0xc0) === 0x80) b++; return [a, b] as const; };const [a, b] = slice(raw, start, end);- raw = raw.subarray(a, b);- lo -= a; hi -= a;const after: Buffer[] = [];- let cur = 0;- for (const r of scoped) { after.push(raw.subarray(cur, r.start - from - a), Buffer.from(r.bytes)); cur = r.end - from - a; }- after.push(raw.subarray(cur));- const view = (bytes: Buffer) => { const text = bytes.toString('utf8'); return input.remote ? sanitizeRemoteBody(text, REMOTE_VIEW) : text; };- const lineOffset = await viewNewlinesBefore(engine, input, rows, region !== regions[0], from + a);+ let cur = a;+ for (const r of scoped) { after.push(raw.subarray(cur, viewAt(r.start)), Buffer.from(r.bytes)); cur = viewAt(r.end); }+ after.push(raw.subarray(cur, b));+ raw = raw.subarray(a, b);+ const view = (bytes: Buffer) => { const text = bytes.toString('utf8'); return input.remote ? sanitizeRemoteBody(text, SEGMENTED_REMOTE_VIEW) : text; };+ const lineOffset = await viewNewlinesBefore(engine, input, rows, region !== regions[0], storedAt(a));return { ...editDiff(input.slug, view(raw), view(Buffer.concat(after)), lineOffset), ...(scoped.length < reps.length ? { diff_truncated: true as const } : {}),- ...(input.remote ? {} : { diff_scope: { byte_start: from + a, byte_end: from + b } }) };+ ...(input.remote ? {} : { diff_scope: { byte_start: storedAt(a), byte_end: storedAt(b) } }) };}/**@@ -628,10 +713,10 @@ export async function prepareSegmentedEditMutation(engine: BrainEngine, row: WriassertEditRevision(stored.revision, row.intent?.expected_revision);const edits = parsePageEdits(row.intent?.edits);const within = parseEditWithin(row.intent?.within);- const { prepareSegmentedSpliceMutation } = await import('./page-append.ts');+ const [{ prepareSegmentedSpliceMutation }, { snapshotLedger }] = await Promise.all([import('./page-append.ts'), import('./page-prepare.ts')]);const head = serializePageToMarkdown({ ...withoutBody(stored.page), compiled_truth: '', timeline: '' } as Page, stored.tags).slice(0, -1);return prepareSegmentedSpliceMutation(engine, row, stored, { replacements: async page => {- const located = await locateSegmentedEdits(engine, { sourceId: row.source_id, slug: row.slug, page, edits, within, remote: row.authority.remote, head });+ const located = await locateSegmentedEdits(engine, { sourceId: row.source_id, slug: row.slug, page, edits, within, remote: row.authority.remote, head, ledger: snapshotLedger(stored) });return located && { replacements: located.replacements, outcome: located.diff };} });}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex d915b6eec9..23e85cb6dd 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -380,7 +380,7 @@ export async function preparePageAdmission(ctx: OperationContext,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); await assertSegmentedEditFences(ctx.engine, snapshot.page, within); }+ else { parsePageEdits(p.edits); await assertSegmentedEditFences(ctx.engine, snapshot.page, within, ctx.remote !== false); }}// 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/src/core/repair/attribution-backfill.ts b/src/core/repair/attribution-backfill.tsindex af8054a03f..fa52196fa1 100644--- a/src/core/repair/attribution-backfill.ts+++ b/src/core/repair/attribution-backfill.ts@@ -48,7 +48,7 @@ async function withoutNestedLoops<T>(engine: BrainEngine, fn: (tx: BrainEngine)const FACT_ID = "CASE WHEN r.outcome->>'id' ~ '^[0-9]{1,18}$' THEN (r.outcome->>'id')::bigint END";/** A committed request that changed the page to the revision it reports. */-const MUTATED_PAGE = `(r.operation IN ('put_page','capture','edit_page','delete_page','restore_page','revert_version')+const MUTATED_PAGE = `(r.operation IN ('put_page','capture','edit_page','append_page','delete_page','restore_page','revert_version')AND r.outcome->>'status' IN ('created_or_updated','restored','reverted','soft_deleted')AND COALESCE(r.outcome->>'noop', 'false') <> 'true'OR r.operation = 'remember' AND r.outcome->>'status' IN ('inserted','superseded') AND EXISTS (diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.tsindex 354fa52754..334519b7df 100644--- a/src/core/trust/backfill.ts+++ b/src/core/trust/backfill.ts@@ -150,7 +150,7 @@ function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilinWHEN ${r}.authority->>'remote' = 'true' THEN ${rank('agent_written')}WHEN ${kind} LIKE 'managed\\_sync\\_%' OR ${kind} IN ('managed_file_import','canonical_reconcile','managed_file_repair') THEN ${rank('operator_curated')}WHEN ${kind} LIKE 'managed\\_facts\\_%' OR ${kind} LIKE 'managed\\_atom\\_%' OR ${kind} LIKE 'managed\\_maintenance\\_%' THEN ${rank('agent_written')}- WHEN ${r}.intent IS NOT NULL AND ${kind} IS NULL AND ${r}.operation IN ('put_page','capture','remember','edit_page','delete_page','restore_page',+ WHEN ${r}.intent IS NOT NULL AND ${kind} IS NULL AND ${r}.operation IN ('put_page','capture','remember','edit_page','append_page','delete_page','restore_page','revert_version','add_tag','remove_tag','add_timeline_entry','takes_add','takes_update','takes_supersede','takes_resolve','takes_remove') THEN ${rank('agent_written')}END`;};diff --git a/src/core/write-gate-scan.ts b/src/core/write-gate-scan.tsindex 9d1d431e81..eca4acdf6a 100644--- a/src/core/write-gate-scan.ts+++ b/src/core/write-gate-scan.ts@@ -95,7 +95,7 @@ const REQUEST_SIGNAL = (pr: string) => `CASEWHEN ${pr}.intent->>'kind' LIKE 'connector_%' OR ${pr}.intent->>'kind' LIKE 'managed_connector_%' THEN 'external_untrusted'WHEN ${pr}.authority->>'remote' = 'true' THEN 'agent_written'WHEN ${pr}.intent->>'kind' LIKE 'managed_sync_%' OR ${pr}.intent->>'kind' IN ('managed_file_import','managed_file_repair','canonical_reconcile','managed_grandfather') THEN 'operator_curated'- WHEN ${pr}.operation IN ('put_page','capture','edit_page','remember','takes_add','takes_update','takes_supersede','add_timeline_entry','extract_facts','restore_page','revert_version') THEN 'agent_written'+ WHEN ${pr}.operation IN ('put_page','capture','edit_page','append_page','remember','takes_add','takes_update','takes_supersede','add_timeline_entry','extract_facts','restore_page','revert_version') THEN 'agent_written'END`;/** Fact provenance tags of agent writes and derivers (extraction, backstop, hooks): capped at agent_written. */diff --git a/test/append-page-operation-lists.test.ts b/test/append-page-operation-lists.test.tsnew file mode 100644index 0000000000..5d66ca519f--- /dev/null+++ b/test/append-page-operation-lists.test.ts@@ -0,0 +1,53 @@+/**+ * Wave B PR 3 (N5): append_page is a page write like edit_page wherever an operation list means "an agent's page write".+ *+ * 1. Protects: the lists that attribute, tier, chronicle, group-publish and backstop a page write name append_page+ * beside edit_page; the two lists it stays out of say why below.+ * 2. Fails when: a list is extended for edit_page without append_page, or append_page is added to a list it must not join.+ * 3. Pure (source text and exported predicates); no database.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { singleWrite } from '../src/core/persistence/group-publish.ts';+import { pageNoopAdvisories } from '../src/core/persistence/page-advisories.ts';+import { queuesMentionLinks } from '../src/core/persistence/effect-journal.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';++/** The operation list that starts at `anchor` in `file`: from the anchor through the bracket that closes after 'edit_page'. */+function list(file: string, anchor: string): string {+ const source = readFileSync(join(import.meta.dir, '..', file), 'utf8');+ const at = source.indexOf(anchor);+ expect(at).toBeGreaterThanOrEqual(0);+ const edit = source.indexOf("'edit_page'", at);+ return source.slice(at, source.slice(edit).search(/[)\]]/) + edit);+}++describe('append_page in operation lists', () => {+ test.each([+ ['src/core/repair/attribution-backfill.ts', 'const MUTATED_PAGE'],+ ['src/core/trust/backfill.ts', "${r}.intent IS NOT NULL AND ${kind} IS NULL AND"],+ ['src/core/write-gate-scan.ts', "WHEN ${pr}.operation IN ("],+ ['src/core/chronicle/ledger.ts', 'const DECIDING_OPERATIONS'],+ ])('%s names append_page beside edit_page', (file, anchor) => {+ const ops = list(file, anchor);+ expect(ops).toContain("'edit_page'");+ expect(ops).toContain("'append_page'");+ });++ test('an append publishes as a single write and offers the facts backstop as edit_page does', () => {+ for (const operation of ['edit_page', 'append_page']) {+ expect(singleWrite({ operation, intent: {} } as Pick<WriteRequest, 'operation' | 'intent'>)).toBe(true);+ expect(pageNoopAdvisories({ operation, authority: { remote: false } } as unknown as WriteRequest)).toHaveProperty('facts_backstop');+ }+ });++ test('append_page stays out of the owner-edit and remote-mention lists', () => {+ // Owner edits can release a purge redaction: an append cannot write facts or takes (fence markers are refused).+ expect(list('src/core/belief/ledger.ts', 'const OWNER_EDIT_OPERATIONS')).not.toContain("'append_page'");+ // A remote mention links effect re-reads the whole page; an append's links follow the incremental derivation instead.+ const remote = { remote: true, autoLinkTrusted: false } as WriteRequest['authority'];+ expect(queuesMentionLinks({ operation: 'edit_page', authority: remote })).toBe(true);+ expect(queuesMentionLinks({ operation: 'append_page', authority: remote })).toBe(false);+ });+});diff --git a/test/large-pages/edit-segmented.test.ts b/test/large-pages/edit-segmented.test.tsindex af084165d6..7890fc13b8 100644--- a/test/large-pages/edit-segmented.test.ts+++ b/test/large-pages/edit-segmented.test.ts@@ -28,6 +28,11 @@ 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 WITHDRAWN_A = 'notes/edit-withdrawn-a';+const WITHDRAWN_B = 'notes/edit-withdrawn-b';+const BOUNDARY = 'notes/edit-boundary';+const WITHIN_SEG = 'notes/edit-within-seg';+const WITHIN_INLINE = 'notes/edit-within-inline';const MALFORMED = 'notes/edit-malformed';const INLINE_MALFORMED = 'notes/edit-malformed-inline';const GATED = 'notes/edit-gated';@@ -152,6 +157,89 @@ for (const kind of testBackends()) {expect(newlines(prefix) - newlines(view(prefix))).toBeGreaterThan(0);}, 600_000);+ test('a withdrawn fact row stays out of a segmented edit\'s diff and receipt, local and remote, and is never matched', async () => {+ const claim = 'Withdrawn world claim';+ // The withdrawn world row is the fence's last row, so it falls inside the diff's three context lines.+ const lines = FACTS_BLOCK.split('\n');+ [lines[3], lines[4]] = [lines[4]!.replace('| 2 |', '| 1 |'), lines[3]!.replace('| 1 | likes tea |', `| 2 | ${claim} |`)];+ const facts = lines.join('\n');+ const body = 'Intro.\n\n' + facts + '\nAfter the fence line.\n\n' + conversationBody(1_200_000, { seed: 11 });+ for (const slug of [WITHDRAWN_A, WITHDRAWN_B]) {+ await brain.seed(slug, fm('Withdrawn') + body + '\n');+ expect((await brain.body(slug)).storage).toBe('segmented');+ await brain.engine.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', $1, gbrain_fact_fingerprint($2))", [slug, claim]);+ }+ const receipt = async (requestId: string) => JSON.stringify((await brain.engine.executeRaw<{ outcome: unknown }>(+ 'SELECT outcome FROM persistence_requests WHERE request_id=$1', [requestId]))[0]?.outcome ?? null);+ const editRecorded = async (slug: string, remote: boolean, marker: string) => {+ const request_id = randomUUID();+ const res = await brain.call('edit_page', { slug, expected_revision: await revision(slug, remote), request_id,+ edits: [{ old_text: 'After the fence line.', new_text: `After the fence line ${marker}.` }] }, { remote });+ expect(res).toMatchObject({ isError: false, body: { status: 'created_or_updated' } });+ expect(res.body.diff).toContain(`+After the fence line ${marker}.`);+ expect(res.body.diff).toContain('gbrain:facts:end');+ return { diff: res.body.diff as string, outcome: await receipt(request_id) };+ };+ const remote = await editRecorded(WITHDRAWN_A, true, 'R');+ expect(remote.diff).not.toContain(claim);+ expect(remote.outcome).toContain('After the fence line R.');+ expect(remote.outcome).not.toContain(claim);+ // A trusted caller sees the row as the overlay strikes it, never as a live row.+ const local = await editRecorded(WITHDRAWN_B, false, 'L');+ expect(local.diff).toContain('forgotten: memory withdrawn');+ expect(local.diff).not.toContain(`| ${claim} |`);+ expect(local.outcome).not.toContain(`| ${claim} |`);+ expect((await edit(WITHDRAWN_A, await revision(WITHDRAWN_A, true), claim, 'x', undefined, true)).body.error).toBe('edit_no_match');+ expect((await edit(WITHDRAWN_B, await revision(WITHDRAWN_B), claim, 'x')).body.error).toBe('edit_protected_span');+ }, 600_000);++ test('a remote edit whose diff context would start on a fence\'s first byte never shows its private rows', async () => {+ // The edit sits exactly 2048 bytes (the diff context) after the fence begins: line rounding would cut the begin marker off.+ const lead = 'Intro.\n\n', target = 'Boundary target line.';+ const filler = 'f'.repeat(2048 - Buffer.byteLength(FACTS_BLOCK) - 1) + '\n';+ await brain.seed(BOUNDARY, fm('Boundary') + lead + FACTS_BLOCK + filler + target + '\n\n' + conversationBody(1_200_000, { seed: 12 }) + '\n');+ const truth = Buffer.from((await brain.body(BOUNDARY)).truth);+ expect(truth.indexOf(Buffer.from(target)) - truth.indexOf(Buffer.from('<!--- gbrain:facts:begin'))).toBe(2048);+ const res = await edit(BOUNDARY, await revision(BOUNDARY, true), target, 'Boundary target line, edited.', undefined, true);+ expect(res).toMatchObject({ isError: false });+ expect(res.body.diff).toContain('+Boundary target line, edited.');+ expect(res.body.diff).not.toContain('private thing');+ }, 600_000);++ test('a remote within past hidden text refuses alike for every range and edit; a range get_page returns as edit_target still edits', async () => {+ const before = 'Visible line before the fence.', after = 'Visible line after the fence.';+ const fenced = FACTS_BLOCK + '\n' + after + '\n\n';+ // On the segmented page the fence sits segments after the first line, so a window over that line gets edit_target.+ await brain.seed(WITHIN_SEG, fm('Within') + before + '\n\n' + conversationBody(300_000, { seed: 14 }) + '\n\n' + fenced + conversationBody(900_000, { seed: 13 }) + '\n');+ expect(await brain.call('put_page', { slug: WITHIN_INLINE, content: fm('Within inline') + before + '\n\n' + fenced + 'Last line.\n', request_id: randomUUID() })).toMatchObject({ isError: false });+ expect((await brain.body(WITHIN_SEG)).storage).toBe('segmented');+ expect((await brain.body(WITHIN_INLINE)).storage).toBe('inline');+ const refusal = (res: { body: Record<string, any> }) => ({ error: res.body.error, message: res.body.message, detail: res.body.detail });+ for (const slug of [WITHIN_SEG, WITHIN_INLINE]) {+ const truth = Buffer.from((await brain.body(slug)).truth);+ const at = truth.indexOf(Buffer.from(after));+ const rev = await revision(slug, true);+ const call = (edits: Array<{ old_text: string; new_text: string }>, within: { byte_start: number; byte_end: number }) =>+ brain.call('edit_page', { slug, expected_revision: rev, edits, within, request_id: randomUUID() }, { remote: true });+ // Exactly around the line (base: edited) and one byte short (base: edit_no_match) would measure the hidden rows.+ const probes = [+ await call([{ old_text: after, new_text: 'x' }], { byte_start: at, byte_end: at + after.length }),+ await call([{ old_text: after, new_text: 'x' }], { byte_start: at, byte_end: at + after.length - 1 }),+ await call([{ old_text: before, new_text: 'y' }, { old_text: after, new_text: 'x' }], { byte_start: 0, byte_end: at + after.length }),+ ];+ for (const res of probes) expect(refusal(res)).toEqual({ error: 'edit_invalid', message: refusal(probes[0]!).message, detail: undefined });+ expect((await brain.body(slug)).truth).toBe(truth.toString('utf8'));+ }+ // A range with nothing hidden before it: edit_target is given (segmented) and works, as a range before the fence does inline.+ const win = (await brain.call('get_page', { slug: WITHIN_SEG, body: 'window', bytes: { offset: 0, length: before.length } }, { remote: true })).body;+ expect(win.edit_target).toMatchObject({ byte_start: 0 });+ const ok = await edit(WITHIN_SEG, win.edit_target.revision, before, 'Edited before the fence.', { byte_start: win.edit_target.byte_start, byte_end: win.edit_target.byte_end }, true);+ expect(ok).toMatchObject({ isError: false });+ const inline = await edit(WITHIN_INLINE, await revision(WITHIN_INLINE, true), before, 'Edited before the fence.', { byte_start: 0, byte_end: before.length }, true);+ expect(inline).toMatchObject({ isError: false });+ for (const slug of [WITHIN_SEG, WITHIN_INLINE]) expect((await brain.body(slug)).truth.startsWith('Edited before the fence.\n')).toBe(true);+ }, 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';