Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 3 lane 3a: append_page, segmented edit_page with within, edit_target

garrytan387a2d5aeaf3
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index f2c68e4cb1..5f7d804dbc 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 151 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 152 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -168,6 +168,7 @@ Every non-localOnly operation on the MCP surface: 151 tools across 25 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
+| `append_page` | Add text to the end of a page, in time proportional to the text: use it for logs and conversations instead of re-putting a large page. | write | | |
| `cancel_write_request` | Cancel your accepted write before it publishes; returns the receipt. | write | yes | |
| `capture` | Quick note ("just remember this"): slugged under inbox/ by date + content hash, so recapturing is idempotent. | write | yes | |
| `delete_page` | Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). | write | | |
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index c052c89555..c81d2e3b4c 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -37,7 +37,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).
-- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
+- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission; skipped for a segmented page) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`. `within` and the segmented path: [large page writes](core-services-2-continued.md#large-page-writes).
- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index d05ca9ad94..c26b06fca7 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -33,3 +33,13 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`). `DocumentSlab` / `slabWindow` run the same arithmetic on a slice of a larger document and shift the result back to document coordinates.
- `src/core/page-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v253) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page and carrying line counts forward between entries. `segmentedReadWork` (@internal) counts the units and segment bytes a read visits, for the read-cost bounds. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.
+
+## Large page writes
+
+Writes 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/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.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 96498fc49c..46eb009d4b 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -45,7 +45,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`).
- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts.
- `src/core/persistence/large-page-guard.ts` — put_page against a page over 256 KB: `assertLargePageAdmission` (remote, before queueing) refuses `force` without `expected_revision` (`revision_required`) and content under half the stored body (`page_shrink_refused`) unless `allow_shrink`; `assertLargePageReplacement` re-checks the parsed body against the locked snapshot in preparation (`page-prepare.ts`).
-- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
+- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits and the optional `within` range (full surface only), then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). A terminal or recovery-holding receipt also returns `write_error_reason`, `suggestion` and a `diagnosis` from `classifyTerminal` with a rendered `fix` (#6650, `test/write-request-diagnosis-6650.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7684476592..74ff8be131 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3803,6 +3803,14 @@ Reasons: `content_directory`.
|---|---|---|---|---|---|---|
| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade, or set `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, and never pin a release older than 0.60.305.0; then run gbrain sync --source <id> --no-pull. | host_admin | `gbrain doctor --json` | 1 | no |
+### tail_changed
+
+<a id="tail_changed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The end of the page no longer has the sha256 the append expected, so nothing was appended. | append_page's expected_tail_sha256 binds an append to the tail its caller read; another write changed it, and appending anyway could interleave text with a tail the caller never saw. | Read the page again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
+
### tail_exposure_approval
<a id="tail_exposure_approval"></a>
diff --git a/plugin/README.md b/plugin/README.md
index a8021ab4fd..2f6526b21b 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 172
+The plugin's MCP server runs `gbrain serve --surface full` — 173
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 1cffa739dc..37ba1298e8 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -48,6 +48,7 @@ const EXEMPT = {
'src/core/facts/conversation-relink.ts': 'sets entity_slug on database-only conversation fact rows; page text is unchanged',
'src/core/cycle/extract-facts.ts': 'fence reconcile and deleted-page expiry write fact rows only; page text is unchanged',
'src/core/cycle/extract-takes.ts': 'takes reextract writes take rows only; page text is unchanged',
+ 'src/core/persistence/page-edit.ts': 'segmented edit_page splices through page-append.ts prepareSegmentedSpliceMutation, which declines an always-loaded core page to preparePageMutation; the splice never changes frontmatter',
'src/core/repair/take-supersession.ts': 'reprojection writes takes.superseded_by only; fence edits go through put_page (preparePageMutation)',
};
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 7bd5195d64..4c094f8b67 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
+src/core/operations.ts 241 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B PR 3: pageAppendOperations import (spread shares the pages line)
src/core/pglite-engine.ts 3085 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)
src/core/postgres-engine.ts 3107 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 520d590118..f9e6265042 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -582,3 +582,15 @@ src/core/belief/page-at-time.ts livePage field STREAM known_as_of read: a segmen
src/core/ops/known-as-of.ts intervalView field STREAM known_as_of read: a segmented version or page returns body segmented with body_ref (window read via get_page version_id), never a body string; inline bodies only
src/core/ops/known-as-of.ts getVersionsKnownAsOf field STREAM known_as_of read: a segmented version or page returns body segmented with body_ref (window read via get_page version_id), never a body string; inline bodies only
src/core/belief/preimages.ts preimageGaps sql META size only (octet_length) to exempt large pages; segmented pages and versions are excluded by body_storage
+src/core/ops/get-page-body.ts editTarget field INLINE inline branch only (a segmented page maps through the window's segment units); regions read whole within the segmented threshold
+src/core/page-body/tail-digest.ts inlineRegions sql INLINE callers branch on storage: inline pages only, within the segmented threshold
+src/core/page-body/tail-digest.ts inlineRegions field INLINE callers branch on storage: inline pages only, within the segmented threshold
+src/core/page-body/tail-digest.ts inlineTailDigest field INLINE get_page body:'none' of an inline page; a segmented page uses page-window/segmented.ts tailDigest
+src/core/persistence/page-append.ts regionTail field INLINE inline branch; a segmented page reads its tail segments (segmentedRegionTail)
+src/core/persistence/page-append.ts splicedPageFile call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segments
+src/core/persistence/page-append.ts prepareAppendMutation field SEGW inline append, or a segmented page the splice declined within PAGE_MAX_BYTES (materializedSnapshot); over it the append refuses page_body_segmented
+src/core/persistence/page-append.ts prepareAppendMutation call:serializePageToMarkdown SEGW inline append, or a segmented page the splice declined within PAGE_MAX_BYTES (materializedSnapshot); over it the append refuses page_body_segmented
+src/core/persistence/page-append.ts prepareAppendMutation sql META body_bytes, else octet_length of an inline page's regions, after the write
+src/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 first
+src/core/persistence/page-edit.ts applyPageEdits field SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation first
+src/core/persistence/page-edit.ts prepareSegmentedEditMutation call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segments
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 36365ae1cd..d8a253d112 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -650,6 +650,7 @@ export const CODES = {
why: "The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
suggestion: 'Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source.' },
sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade, or set `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, and never pin a release older than 0.60.305.0; then run gbrain sync --source <id> --no-pull.' },
+ tail_changed: { class: 'caller', summary: "The end of the page no longer has the sha256 the append expected, so nothing was appended.", why: "append_page's expected_tail_sha256 binds an append to the tail its caller read; another write changed it, and appending anyway could interleave text with a tail the caller never saw.", suggestion: "Read the page again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and tail_sha256.", requires_exclusive: false } },
tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 02cf6b2e3e..428b3dd49b 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -29,6 +29,7 @@ const load_links = () => import('./ops/links.ts') as Promise<Record<string, unkn
const load_loops = () => import('./ops/loops.ts') as Promise<Record<string, unknown>>;
const load_notices = () => import('./ops/notices.ts') as Promise<Record<string, unknown>>;
const load_orphans = () => import('./ops/orphans.ts') as Promise<Record<string, unknown>>;
+const load_page_append = () => import('./ops/page-append.ts') as Promise<Record<string, unknown>>;
const load_page_batch = () => import('./ops/page-batch.ts') as Promise<Record<string, unknown>>;
const load_page_edit = () => import('./ops/page-edit.ts') as Promise<Record<string, unknown>>;
const load_pages = () => import('./ops/pages.ts') as Promise<Record<string, unknown>>;
@@ -66,6 +67,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"capture": [load_pages, "pagesOperations"],
"fetch": [load_pages, "pagesOperations"],
"edit_page": [load_page_edit, "pageEditOperations"],
+ "append_page": [load_page_append, "pageAppendOperations"],
"put_pages": [load_page_batch, "pageBatchOperations"],
"get_write_request": [load_persistence, "persistenceOperations"],
"list_write_requests": [load_persistence, "persistenceOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 255725fbca..2dc8fb4d90 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -817,6 +817,23 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
}
}
},
+ "within": {
+ "type": "object",
+ "description": "Match only in this stored-body range: edit_target's byte_start/byte_end from a get_page window read.",
+ "fullSurfaceOnly": true,
+ "properties": {
+ "byte_start": {
+ "type": "number",
+ "required": true,
+ "description": "First stored byte."
+ },
+ "byte_end": {
+ "type": "number",
+ "required": true,
+ "description": "End stored byte (exclusive)."
+ }
+ }
+ },
"source_id": {
"type": "string",
"description": "Write source."
@@ -830,6 +847,61 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"scope": "write",
"area": "pages"
},
+ {
+ "name": "append_page",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Add text to the end of a page, in time proportional to the text: use it for logs and conversations instead of re-putting a large page. request_id is required (a retry never appends twice). Optional expected_revision / expected_tail_sha256 (tail_sha256 from get_page body: 'none') refuse with revision_changed / tail_changed when the page moved.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Page slug (an existing page).",
+ "required": true
+ },
+ "text": {
+ "type": "string",
+ "required": true,
+ "description": "Text to add, at most 4194304 bytes; a larger append uses begin_page_upload mode 'append'."
+ },
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "A new UUID per append; reuse only to retry."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Append only while the page is at this revision."
+ },
+ "expected_tail_sha256": {
+ "type": "string",
+ "description": "Append only while the region's last 4096 bytes have this sha256 (get_page body: 'none' tail_sha256)."
+ },
+ "region": {
+ "type": "string",
+ "enum": [
+ "auto",
+ "truth",
+ "timeline"
+ ],
+ "description": "auto (default): the last non-empty region."
+ },
+ "separator": {
+ "type": "string",
+ "enum": [
+ "auto",
+ "none"
+ ],
+ "description": "auto (default): one newline first when the tail lacks one."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "pages"
+ },
{
"name": "put_pages",
"idempotent": true,
diff --git a/src/core/operations.ts b/src/core/operations.ts
index aa19ab0c40..03e29748c6 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -121,6 +121,7 @@ import { entityIdentityOperations } from './ops/entity-identity.ts';
import { requestToolsOperations } from './ops/request-tools.ts';
import { noticesOperations } from './ops/notices.ts';
import { pageEditOperations } from './ops/page-edit.ts';
+import { pageAppendOperations } from './ops/page-append.ts';
import { pageBatchOperations } from './ops/page-batch.ts';
import { feedbackOperations } from './ops/feedback.ts';
import { trustOperations } from './ops/trust.ts';
@@ -141,7 +142,7 @@ export const operations: Operation[] = [
...verbOperations,
// 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, ...pageEditOperations, ...pageBatchOperations,
+ ...pagesOperations, ...pageEditOperations, ...pageAppendOperations, ...pageBatchOperations,
...persistenceOperations,
// Search (search, query) — ops/search.ts
...searchOperations,
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index b05e1060c2..eea9b74510 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -456,6 +456,8 @@ export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
'add_link', 'remove_link', 'add_timeline_entry', 'revert_version',
// #5616: edit_page enforces the slug fence in its handler and submission.
'edit_page',
+ // Wave B: append_page is fenced on submission as edit_page is.
+ 'append_page',
// #6007: put_pages fences every page as the put_page it is submitted as.
'put_pages',
'put_raw_data', 'think',
diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.ts
index 31932259fa..00c81b213f 100644
--- a/src/core/ops/get-page-body.ts
+++ b/src/core/ops/get-page-body.ts
@@ -46,6 +46,8 @@ 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 { inlineRegions, inlineTailDigest } from '../page-body/tail-digest.ts';
+import { TIMELINE_SEPARATOR } from '../page-window/document.ts';
import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';
import { pageTrustForRead, type QuarantinedView } from './get-page-projection.ts';
import { chunkGenerationProbe, chunkManifestReads } from '../search/safe-chunks.ts';
@@ -379,6 +381,52 @@ async function segmentedWindows(ctx: OperationContext, input: PartialReadInput,
} };
}
+/**
+ * Wave B (spec 6.3): the stored-body range under a read-view window, for edit_page's `within`. A row (or an inline
+ * region) whose read projection is its stored bytes maps byte for byte; any other widens to its stored bounds, so the
+ * range always covers the window. A remote caller gets it only while nothing hidden precedes the window's end: stored
+ * offsets would otherwise measure the hidden text.
+ */
+async function editTarget(ctx: OperationContext, page: Page, doc: WindowDocument, win: WindowSlice, revision: string):
+ Promise<{ revision: string; byte_start: number; byte_end: number } | undefined> {
+ const remote = ctx.remote !== false;
+ if (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;
+ const u = seg.units[seg.unitAt(side === 'end' ? Math.max(0, p - 1) : p)];
+ if (!u) return 0;
+ if (u.row < 0) return truthBytes;
+ const row = rows[u.row]!;
+ if (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;
+ const start = map(win.byte_start, 'start');
+ return { revision, byte_start: start, byte_end: Math.max(start, map(win.byte_end, 'end')) };
+ }
+ const { truth, timeline } = await inlineRegions(ctx.engine, page.id);
+ const truthBytes = Buffer.byteLength(truth, 'utf8'), bodyBytes = truthBytes + Buffer.byteLength(timeline, 'utf8');
+ const raw = timeline.trim() ? truth + TIMELINE_SEPARATOR + timeline : truth;
+ const bytes = doc.inline!.bytes;
+ if (bytes.equals(Buffer.from(raw, 'utf8'))) {
+ const at = (p: number) => p <= truthBytes ? p : p < truthBytes + Buffer.byteLength(TIMELINE_SEPARATOR) ? truthBytes : p - Buffer.byteLength(TIMELINE_SEPARATOR);
+ return { revision, byte_start: at(win.byte_start), byte_end: at(win.byte_end) };
+ }
+ if (remote) return undefined;
+ const timelineAt = doc.inline!.timelineByte;
+ const inTruth = timelineAt < 0 || win.byte_end <= timelineAt - Buffer.byteLength(TIMELINE_SEPARATOR);
+ const inTimeline = timelineAt >= 0 && win.byte_start >= timelineAt;
+ return { revision, byte_start: inTimeline ? truthBytes : 0, byte_end: inTruth ? truthBytes : bodyBytes };
+}
+
/** next_cursor plus `next`, the exact call that reads on (the starter surface does not advertise `cursor`; dispatch accepts it). */
function setNext(out: Record<string, unknown>, page: Page, cursor: string, markdown: boolean): void {
out.next_cursor = cursor;
@@ -426,6 +474,7 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI
total_bytes: whole.bytes.length, total_lines: totalLines(whole.bytes),
...(whole.timelineByte >= 0 ? { timeline_byte_start: whole.timelineByte } : {}),
...(markdown ? { sha256: sha256Hex(whole.bytes) } : {}),
+ ...(mode === 'none' ? await inlineTailDigest(ctx.engine, page.id, ctx.remote !== false) : {}),
};
doc = inlineDocument(whole);
}
@@ -491,6 +540,8 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI
const win = await select(maxBytes);
if (!win) return confirmed({ ...out, truncated: true });
out.window = { ...win, text: envelopeText(win.text, quarantined, trust) };
+ const target = markdown || typeof win.byte_start !== 'number' ? undefined : await editTarget(ctx, page, doc, win, revision);
+ if (target) out.edit_target = target; else delete out.edit_target;
out.truncated = win.byte_start > 0 || win.byte_end < doc.total;
if (win.byte_end < doc.total) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax }), markdown);
else { delete out.next_cursor; delete out.next; }
diff --git a/src/core/ops/page-append.ts b/src/core/ops/page-append.ts
new file mode 100644
index 0000000000..31d9260e79
--- /dev/null
+++ b/src/core/ops/page-append.ts
@@ -0,0 +1,54 @@
+/**
+ * Wave B (spec 6.1): append_page adds text to the end of a page in time proportional to the text added, idempotent by
+ * request_id (persistence/page-append.ts). Never import from '../operations.ts' here (cycle).
+ */
+import type { Operation } from './contract.ts';
+import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from './context.ts';
+import { pageMutationSource } from '../persistence/page-mutations.ts';
+import { PAGE_MUTATION_PARAMS } from '../persistence/params.ts';
+import { admitPageAppend, APPEND_TEXT_MAX_BYTES, type AppendRegion, type AppendSeparator } from '../persistence/page-append.ts';
+
+const append_page: Operation = {
+ name: 'append_page',
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description: 'Add text to the end of a page, in time proportional to the text: use it for logs and conversations instead of re-putting a large page. '
+ + 'request_id is required (a retry never appends twice). Optional expected_revision / expected_tail_sha256 (tail_sha256 from get_page body: \'none\') refuse with revision_changed / tail_changed when the page moved.',
+ params: {
+ slug: { type: 'string', description: 'Page slug (an existing page).', required: true },
+ text: { type: 'string', required: true, description: `Text to add, at most ${APPEND_TEXT_MAX_BYTES} bytes; a larger append uses begin_page_upload mode 'append'.` },
+ request_id: { type: 'string', required: true, description: 'A new UUID per append; reuse only to retry.' },
+ expected_revision: { type: 'string', description: 'Append only while the page is at this revision.' },
+ expected_tail_sha256: { type: 'string', description: "Append only while the region's last 4096 bytes have this sha256 (get_page body: 'none' tail_sha256)." },
+ region: { type: 'string', enum: ['auto', 'truth', 'timeline'], description: 'auto (default): the last non-empty region.' },
+ separator: { type: 'string', enum: ['auto', 'none'], description: 'auto (default): one newline first when the tail lacks one.' },
+ source_id: PAGE_MUTATION_PARAMS.source_id,
+ },
+ mutating: true,
+ scope: 'write',
+ area: 'pages',
+ handler: async (ctx, p) => {
+ pageMutationSource(ctx, p, 'append_page');
+ if (ctx.dryRun) {
+ if (typeof p.slug === 'string') {
+ validatePageSlug(p.slug);
+ enforceClientSlugFence(ctx, p.slug, 'append_page');
+ enforceSubagentSlugFence(ctx, p.slug, 'append_page');
+ }
+ return { dry_run: true, action: 'append_page', slug: p.slug };
+ }
+ const response = await admitPageAppend(ctx, { slug: p.slug as string, text: p.text as string, request_id: p.request_id as string,
+ ...(p.source_id !== undefined ? { source_id: p.source_id as string } : {}),
+ ...(p.expected_revision !== undefined ? { expected_revision: p.expected_revision as string } : {}),
+ ...(p.expected_tail_sha256 !== undefined ? { expected_tail_sha256: p.expected_tail_sha256 as string } : {}),
+ ...(p.region !== undefined ? { region: p.region as AppendRegion } : {}),
+ ...(p.separator !== undefined ? { separator: p.separator as AppendSeparator } : {}),
+ ...(p.wait_ms !== undefined ? { wait_ms: p.wait_ms } : {}) });
+ const outcome = (response.outcome ?? {}) as Record<string, unknown>;
+ return { slug: outcome.slug ?? p.slug, revision: response.revision, body_bytes: outcome.body_bytes, appended_bytes: outcome.appended_bytes,
+ chunks_new: outcome.chunks_new, ...(outcome.size_state !== undefined ? { size_state: outcome.size_state } : {}),
+ ...(outcome.rescanned ? { rescanned: true } : {}), receipt: response.write_request ?? response };
+ },
+};
+
+export const pageAppendOperations: Operation[] = [append_page];
diff --git a/src/core/ops/page-edit.ts b/src/core/ops/page-edit.ts
index 3389443006..93c31f5787 100644
--- a/src/core/ops/page-edit.ts
+++ b/src/core/ops/page-edit.ts
@@ -5,7 +5,7 @@ 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';
+import { EDIT_PAGE_MAX_EDITS, parseEditWithin, parsePageEdits } from '../persistence/page-edit.ts';
const edit_page: Operation = {
name: 'edit_page',
@@ -26,6 +26,15 @@ const edit_page: Operation = {
},
},
},
+ within: {
+ type: 'object',
+ description: "Match only in this stored-body range: edit_target's byte_start/byte_end from a get_page window read.",
+ fullSurfaceOnly: true,
+ properties: {
+ byte_start: { type: 'number', required: true, description: 'First stored byte.' },
+ byte_end: { type: 'number', required: true, description: 'End stored byte (exclusive).' },
+ },
+ },
source_id: PAGE_MUTATION_PARAMS.source_id,
request_id: WRITE_REQUEST_PARAM,
},
@@ -35,6 +44,7 @@ const edit_page: Operation = {
handler: async (ctx, p) => {
pageMutationSource(ctx, p, 'edit_page');
parsePageEdits(p.edits);
+ parseEditWithin(p.within);
if (ctx.dryRun) {
if (typeof p.slug === 'string') {
validatePageSlug(p.slug);
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 9268ac9014..d6b332309c 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -158,10 +158,10 @@ const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
const sameBytes = (a: Uint8Array, b: Uint8Array) => Buffer.from(a).equals(Buffer.from(b));
/** An occurrence is its bytes, entry state and the trust its stored regions were computed under: a trust flip rechunks the region. */
-const occurrenceKey = (sha256: Uint8Array, entryState: unknown, trust: 'trusted' | 'void') => `${hex(sha256)}|${stableJson(entryState)}|${trust}`;
+export const occurrenceKey = (sha256: Uint8Array, entryState: unknown, trust: 'trusted' | 'void') => `${hex(sha256)}|${stableJson(entryState)}|${trust}`;
/** Every coordinate of a live row equals the row the new segment would get, so the row stays. */
-function rowUnchanged(live: ManifestRow, next: ManifestRowInput): boolean {
+export function rowUnchanged(live: ManifestRow, next: ManifestRowInput): boolean {
return live.seq === next.seq && live.region === next.region && Number(live.byteStart) === next.byteStart
&& live.byteLen === next.byteLen && Number(live.lineStart) === next.lineStart && live.cutKind === next.cutKind
&& sameBytes(live.hashState, next.hashState) && stableJson(live.protectedRegions) === stableJson(next.protectedRegions)
diff --git a/src/core/page-body/splice.ts b/src/core/page-body/splice.ts
new file mode 100644
index 0000000000..ea90cf1968
--- /dev/null
+++ b/src/core/page-body/splice.ts
@@ -0,0 +1,417 @@
+/**
+ * Splicing a segmented body (Wave B, spec 6.1 and 6.3): replace stored byte
+ * ranges of a segmented page's live generation and stage the next generation
+ * from the segments the change touches, never from the whole body.
+ *
+ * Segmentation is append-stable and resumable (segmenter.ts): a run started
+ * at a segment's entry state over its bytes reproduces a full run's cuts. So
+ * a splice resumes at the last clean entry point at or before the first
+ * replaced byte, feeds the touched segments with the replacements applied,
+ * and stops at the first old segment boundary where the new run's exit state
+ * equals that segment's entry state: every segment after it keeps its bytes,
+ * text and chunks and only moves (a new manifest row under the same
+ * occurrence, its offsets and content_hash midstate recomputed). An append is
+ * an insertion at the end of its region, so it re-segments the old tail and
+ * the new text and moves nothing.
+ *
+ * Work is O(touched segments + replacement bytes) in segmentation, plus the
+ * text of every moved segment for the content_hash stream (O(suffix) for an
+ * edit, nothing for an append). New segments equal to a replaced one keep its
+ * occurrence and chunks; the rest are chunked here, with vectors reused by
+ * chunk text from the replaced occurrences' rows (spec 4.4).
+ *
+ * A change that flips a region's global fence trust (1.3) restages the whole
+ * body ('rescanned'), as does a caller that forces it ('full').
+ */
+import type { BrainEngine } from '../engine.ts';
+import { stableJson } from '../persistence/digest.ts';
+import { faultPoint } from '../persistence/fault-points.ts';
+import type { Principal } from '../persistence/model.ts';
+import { BODY_LEAD_BYTES, STAGE_BATCH_BYTES } from './limits.ts';
+import type { BodyRegion, JsonObject, ManifestRow, ManifestRowInput, SegmentedBodyColumns, SegmentTextInput } from './types.ts';
+import { regionFlags, regionTrust, segmentStream, SEGMENTER_VERSION, type SegmentOut, type StoredRegion } from './segmenter.ts';
+import { isCleanResumePoint, readEntryState, timelineEntryState, type EntryState } from './entry-state.ts';
+import { ContentHashStream } from './content-hash-stream.ts';
+import { occurrenceKey, occurrencesWithoutChunks, openSegmentedStaging, prepareSegmentedBody, rowUnchanged, segmentWriteScope, stageOccurrenceChunks,
+ utf8Prefix, type PreparedSegmentedBody, type SegmentChunkingContext, type SegmentedStagingOwner } from './ingest.ts';
+
+/** Stored range [start, end) of the live body replaced by bytes; start === end inserts. Sorted, disjoint, each inside one region. */
+export interface BodyReplacement { start: number; end: number; bytes: Uint8Array }
+
+/** The live segmented page a splice changes (metadata only: no body). */
+export interface SplicePage {
+ id: number;
+ generation: number;
+ title: string;
+ type: string;
+ flags: JsonObject | null;
+ truthLead: string;
+ timelineLead: string;
+ bodyBytes: number;
+ truthBytes: number;
+ bodyLines: number;
+ segmentCount: number;
+ /** The projection is sealed now; an unsealed page stays unsealed and its projection runs after commit. */
+ sealed: boolean;
+ /** The tier and corpus generation its stored vectors were embedded under (its contextual-retrieval stamp), for vector reuse. */
+ crTier: 'title' | 'none';
+ corpusGeneration: string | null;
+ pageKind: string;
+}
+
+export interface SegmentedSpliceInput {
+ sourceId: string;
+ slug: string;
+ page: SplicePage;
+ frontmatter: JsonObject;
+ tags: readonly string[];
+ replacements: readonly BodyReplacement[];
+ owner: SegmentedStagingOwner;
+ chunking: SegmentChunkingContext;
+ /** Restage the whole body (the forced full-rewrite probe of the append cost test). */
+ full?: boolean;
+}
+
+export interface SegmentedSplice {
+ prepared: PreparedSegmentedBody;
+ /** The whole body was restaged: a region's fence trust flipped, or 'full'. */
+ rescanned: boolean;
+}
+
+/**
+ * @internal Deterministic work counters for the append and edit cost tests: bytes fed to the segmenter
+ * ('segmented'), segment text bytes read back ('read') and manifest rows loaded ('rows'). Counts, never time.
+ */
+export const spliceWork = { segmented: 0, read: 0, rows: 0 };
+
+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
+const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
+const missing = (row: ManifestRow) => new Error('Segment text ' + hex(row.sha256) + ' of page ' + row.pageId + ' is missing.');
+
+/** A row whose stored metadata names no stored-stream position (nothing open across its cut), so it can move unchanged. */
+function positionFree(row: ManifestRow): boolean {
+ const entry = readEntryState(row.entryState);
+ if (!entry) return false;
+ if (entry.trusted.open || entry.untrusted.open || entry.trusted.truncatedAt !== null || entry.untrusted.truncatedAt !== null) return false;
+ const opens = (list: unknown[]) => (list as Array<{ open_start?: number; open_end?: number }>).some(r => r.open_start !== undefined || r.open_end !== undefined);
+ return !opens(row.protectedRegions) && !opens(row.factsSlots);
+}
+
+/** Whether replacements touch a row, and its bytes with them applied ('first': the row starts its region, so an insertion at its start is its own). */
+function applyToRow(row: Pick<ManifestRow, 'byteStart' | 'byteLen'>, reps: readonly BodyReplacement[], first: boolean):
+ { touched: boolean; pieces: (bytes: Uint8Array) => Uint8Array[] } {
+ const start = Number(row.byteStart), end = start + row.byteLen;
+ const mine = reps.filter(r => r.start === r.end ? (r.start > start || (first && r.start === start)) && r.start <= end : r.start < end && r.end > start);
+ return { touched: mine.length > 0, pieces: bytes => {
+ const out: Uint8Array[] = [];
+ let cur = start;
+ for (const r of mine) {
+ if (r.start === r.end || r.start >= start) {
+ if (r.start > cur) out.push(bytes.subarray(cur - start, r.start - start));
+ out.push(r.bytes);
+ cur = r.start === r.end ? r.start : Math.min(r.end, end);
+ } else cur = Math.max(cur, Math.min(r.end, end));
+ }
+ if (cur < end) out.push(bytes.subarray(cur - start));
+ return out;
+ } };
+}
+
+/** Net bytes the replacements ending at or before stored byte p add. */
+const shiftAt = (reps: readonly BodyReplacement[], p: number) => reps.reduce((n, r) => r.end <= p ? n + r.bytes.length - (r.end - r.start) : n, 0);
+
+async function readTexts(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[]): Promise<Map<string, Uint8Array>> {
+ const texts = await engine.readSegmentTexts(sourceId, rows.map(row => row.sha256));
+ for (const row of rows) {
+ const text = texts.get(hex(row.sha256));
+ if (!text) throw missing(row);
+ spliceWork.read += text.length;
+ }
+ return texts;
+}
+
+/** The live rows of the page from seq 'from' to the end. */
+async function suffixRows(engine: BrainEngine, page: SplicePage, from: number): Promise<ManifestRow[]> {
+ const rows = await engine.readManifest(page.id, { generation: page.generation, lastN: Math.max(0, page.segmentCount - from) });
+ spliceWork.rows += rows.length;
+ if (rows.length !== page.segmentCount - from || (rows[0] && rows[0].seq !== from)) {
+ throw new Error('Page ' + page.id + ' generation ' + page.generation + ' does not tile seq ' + from + '..' + (page.segmentCount - 1) + '; read it again.');
+ }
+ return rows;
+}
+
+/** Seq of the live row holding stored byte p (the last row starting at or before it). */
+async function rowAt(engine: BrainEngine, page: SplicePage, p: number): Promise<number> {
+ const [row] = await engine.executeRaw<{ seq: number }>('SELECT seq FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=$2'
+ + ' AND (gen_to IS NULL OR gen_to>$2) AND byte_start<=$3 ORDER BY byte_start DESC, seq DESC LIMIT 1', [page.id, page.generation, p]);
+ return Number(row?.seq ?? 0);
+}
+
+/** One region of the whole body with the replacements applied (the rescan path). */
+async function* virtualRegion(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], reps: readonly BodyReplacement[], region: BodyRegion): AsyncIterable<Uint8Array> {
+ const mine = rows.filter(row => row.region === region);
+ const batchBytes = STAGE_BATCH_BYTES[engine.kind];
+ for (let i = 0; i < mine.length;) {
+ let j = i, bytes = 0;
+ while (j < mine.length && (j === i || bytes + mine[j]!.byteLen <= batchBytes)) bytes += mine[j++]!.byteLen;
+ const batch = mine.slice(i, j);
+ const texts = await readTexts(engine, sourceId, batch);
+ for (const row of batch) {
+ for (const piece of applyToRow(row, reps, row === mine[0]).pieces(texts.get(hex(row.sha256))!)) {
+ if (!piece.length) continue;
+ spliceWork.segmented += piece.length;
+ yield piece;
+ }
+ }
+ i = j;
+ }
+}
+
+/** Restage the whole body with the replacements applied under 'flags' (the rescan of spec 1.3). */
+async function restageWhole(engine: BrainEngine, input: SegmentedSpliceInput, flags: JsonObject): Promise<PreparedSegmentedBody> {
+ const { page } = input;
+ const rows = await engine.readManifest(page.id, { generation: page.generation });
+ spliceWork.rows += rows.length;
+ const delta = input.replacements.reduce((n, r) => n + r.bytes.length - (r.end - r.start), 0);
+ return prepareSegmentedBody(engine, { sourceId: input.sourceId, slug: input.slug, title: page.title, type: page.type, frontmatter: input.frontmatter, tags: input.tags,
+ live: { id: page.id, generation: page.generation, storage: 'segmented', title: page.title, type: page.type, flags: page.flags },
+ truth: virtualRegion(engine, input.sourceId, rows, input.replacements, 'truth'), timeline: virtualRegion(engine, input.sourceId, rows, input.replacements, 'timeline'),
+ hasTimeline: page.bodyBytes > page.truthBytes, flags, declaredBytes: page.bodyBytes + delta, owner: input.owner, chunking: input.chunking });
+}
+
+interface NewRow { row: ManifestRowInput; text: Uint8Array; segment?: SegmentOut; moved?: ManifestRow }
+type RowCore = Omit<ManifestRowInput, 'seq' | 'byteStart' | 'lineStart' | 'hashState' | 'pageId' | 'genFrom' | 'stagingId' | 'sourceId'>;
+
+const segmentCore = (segment: SegmentOut): RowCore => ({ occurrenceId: 0, region: segment.region, sha256: segment.sha256, byteLen: segment.bytes.length,
+ lineCount: segment.lineCount, cutKind: segment.cutKind, entryState: segment.entryState as unknown as JsonObject, protectedRegions: segment.protectedRegions,
+ factsSlots: segment.factsSlots, staticProjBytes: segment.staticProjBytes, staticProjLines: segment.staticProjLines, outline: segment.outline,
+ dateMin: segment.dateMin, dateMax: segment.dateMax });
+
+const rowCore = (row: ManifestRow): RowCore => ({ occurrenceId: Number(row.occurrenceId), region: row.region, sha256: row.sha256, byteLen: row.byteLen,
+ lineCount: row.lineCount, cutKind: row.cutKind, entryState: row.entryState, protectedRegions: row.protectedRegions, factsSlots: row.factsSlots,
+ staticProjBytes: row.staticProjBytes, staticProjLines: row.staticProjLines, outline: row.outline, dateMin: row.dateMin, dateMax: row.dateMax });
+
+/**
+ * Stage the next generation of a segmented page with 'replacements' applied. Null when the change empties or creates
+ * a region, which this path does not do: the caller takes its whole-body path.
+ */
+export async function spliceSegmentedBody(engine: BrainEngine, input: SegmentedSpliceInput): Promise<SegmentedSplice | null> {
+ const { page, replacements: reps } = input;
+ const flags = page.flags ?? {};
+ if (!reps.length) throw new Error('spliceSegmentedBody: no replacements.');
+ const hasTimeline = page.bodyBytes > page.truthBytes;
+ const regionOf = (r: BodyReplacement): BodyRegion => hasTimeline && (r.start === r.end ? r.start > page.truthBytes : r.start >= page.truthBytes) ? 'timeline' : 'truth';
+ for (const r of reps) {
+ const [lo, hi] = regionOf(r) === 'truth' ? [0, page.truthBytes] : [page.truthBytes, page.bodyBytes];
+ if (lo === hi || r.start < lo || r.end > hi || (r.start === lo && r.end === hi && r.bytes.length === 0)) return null;
+ }
+ if (input.full) return { prepared: await restageWhole(engine, input, flags), rescanned: true };
+
+ // Resume at the last clean entry point at or before the row holding the first replaced byte.
+ const first = reps[0]!;
+ const firstSeq = await rowAt(engine, page, first.start === first.end ? Math.max(0, first.start - 1) : first.start);
+ let base = Math.max(0, firstSeq - 4);
+ let rows = await suffixRows(engine, page, base);
+ const clean = (row: ManifestRow) => { const entry = readEntryState(row.entryState); return !!entry && isCleanResumePoint(entry); };
+ let f = firstSeq - base;
+ for (;;) {
+ while (f > 0 && rows[f - 1]!.region === rows[f]!.region && !clean(rows[f]!)) f--;
+ if (clean(rows[f]!) || base === 0 || f > 0) break;
+ const more = Math.max(0, base - 64);
+ rows = await suffixRows(engine, page, more);
+ f += base - more;
+ base = more;
+ }
+ if (!clean(rows[f]!) || rows.slice(f).some(row => !readEntryState(row.entryState))) return null;
+ const prior = base + f === 0 ? null : f > 0 ? rows[f - 1]! : (await suffixRows(engine, page, base - 1))[0]!;
+
+ const writes = await segmentWriteScope(engine, input.sourceId, { kind: input.owner.principalKind as Principal['kind'], id: input.owner.principalId });
+ const live = { id: page.id, generation: page.generation, storage: 'segmented' as const, title: page.title, type: page.type, flags: page.flags };
+ const stagingId = await openSegmentedStaging(engine, { sourceId: input.sourceId, slug: input.slug, declaredBytes: page.bodyBytes, live, owner: input.owner });
+ try {
+ const generation = page.generation + 1;
+ const out: NewRow[] = [];
+ const replaced: ManifestRow[] = [];
+ const exits: Partial<Record<BodyRegion, EntryState>> = {};
+ const touchedAt = rows.map((row, i) => applyToRow(row, reps, base + i === 0 || (i > 0 && rows[i - 1]!.region !== row.region)
+ || (i === 0 && prior !== null && prior.region !== row.region)));
+ const hasher = prior ? ContentHashStream.fromState(prior.hashState) : ContentHashStream.begin({ title: page.title, type: page.type });
+ let byteStart = Number(rows[f]!.byteStart), lineStart = Number(rows[f]!.lineStart), seq = base + f;
+ const push = (core: RowCore, text: Uint8Array, extra: Pick<NewRow, 'segment' | 'moved'>) => {
+ const decoded = utf8.decode(text);
+ if (core.region === 'truth') hasher.pushTruth(decoded); else hasher.pushTimeline(decoded);
+ out.push({ ...extra, text, row: { ...core, pageId: page.id, genFrom: generation, seq: seq++, byteStart, lineStart, hashState: hasher.exportState(),
+ sourceId: input.sourceId, stagingId } });
+ byteStart += text.length;
+ lineStart += core.lineCount;
+ };
+ const regionEndOf = (i: number) => { let j = i; while (j < rows.length && rows[j]!.region === rows[i]!.region) j++; return j; };
+ /** Rows from k to the next touched row (or the region's end) move by delta; a touched row there resumes from its own entry state. */
+ const canMove = (k: number, delta: number) => {
+ const end = regionEndOf(k);
+ let j = k;
+ for (; j < end && !touchedAt[j]!.touched; j++) if (delta !== 0 && !positionFree(rows[j]!)) return false;
+ return j >= end || (clean(rows[j]!) && (delta === 0 || positionFree(rows[j]!)));
+ };
+
+ let i = f;
+ let entryOverride: EntryState | null = null;
+ while (i < rows.length) {
+ const row = rows[i]!;
+ const regionEnd = regionEndOf(i);
+ const stored = readEntryState(row.entryState)!;
+ const delta = shiftAt(reps, Number(row.byteStart));
+ if (i !== f && !touchedAt[i]!.touched && (!entryOverride || stableJson(entryOverride) === stableJson(stored)) && canMove(i, delta)) {
+ entryOverride = null;
+ let until = i;
+ while (until < regionEnd && !touchedAt[until]!.touched) until++;
+ for (let at = i; at < until;) {
+ let to = at, bytes = 0;
+ while (to < until && (to === at || bytes + rows[to]!.byteLen <= STAGE_BATCH_BYTES[engine.kind])) bytes += rows[to++]!.byteLen;
+ const texts = await readTexts(engine, input.sourceId, rows.slice(at, to));
+ for (const moved of rows.slice(at, to)) push(rowCore(moved), texts.get(hex(moved.sha256))!, { moved });
+ at = to;
+ }
+ i = until;
+ continue;
+ }
+ // Segment from row i with the replacements applied, until an old boundary resynchronizes or the region ends.
+ const entry = entryOverride ?? stored;
+ entryOverride = null;
+ let consumed = i;
+ const source = async function* () {
+ for (let j = i; j < regionEnd; j++) {
+ consumed = j + 1;
+ const texts = await readTexts(engine, input.sourceId, [rows[j]!]);
+ for (const piece of touchedAt[j]!.pieces(texts.get(hex(rows[j]!.sha256))!)) {
+ if (!piece.length) continue;
+ spliceWork.segmented += piece.length;
+ yield piece;
+ }
+ }
+ };
+ const end = row.region === 'truth' && hasTimeline ? 'region_end' as const : 'eof' as const;
+ let resync = -1;
+ let last: SegmentOut | null = null;
+ for await (const segment of segmentStream(source(), entry, { byteStart, lineStart, fenceTrust: regionTrust(flags, row.region), end })) {
+ push(segmentCore(segment), segment.bytes, { segment });
+ last = segment;
+ // A cut on an old boundary with that row's entry state: every row after it is unchanged.
+ for (let k = i + 1; k < regionEnd && k <= consumed; k++) {
+ const oldStart = Number(rows[k]!.byteStart);
+ if (oldStart + shiftAt(reps, oldStart) !== byteStart) continue;
+ if (!touchedAt[k]!.touched && stableJson(segment.exitState) === stableJson(rows[k]!.entryState) && clean(rows[k]!) && canMove(k, shiftAt(reps, oldStart))) resync = k;
+ break;
+ }
+ if (resync >= 0) break;
+ }
+ replaced.push(...rows.slice(i, resync >= 0 ? resync : regionEnd));
+ if (resync >= 0) { i = resync; continue; }
+ if (last) exits[row.region] = last.exitState;
+ if (row.region === 'truth' && last && regionEnd < rows.length) entryOverride = timelineEntryState(last.exitState);
+ i = regionEnd;
+ }
+
+ // A region re-segmented to its end may have flipped its fence trust (1.3): the whole body is restaged under the new trust.
+ const flipped: JsonObject = { ...flags };
+ let flip = false;
+ for (const region of ['truth', 'timeline'] as const) {
+ const exit = exits[region];
+ if (!exit) continue;
+ const observed = regionFlags(exit, regionTrust(flags, region)).observedFenceTrust;
+ if (observed === regionTrust(flags, region)) continue;
+ flipped[region === 'truth' ? 'fence_trust' : 'timeline_fence_trust'] = observed;
+ flip = true;
+ }
+ if (flip) {
+ await engine.setBodyStagingState(stagingId, 'aborted').catch(() => undefined);
+ return { prepared: await restageWhole(engine, input, flipped), rescanned: true };
+ }
+
+ // New segments equal to a replaced occurrence keep it (and its chunks); moved rows keep theirs.
+ const byKey = new Map<string, ManifestRow[]>();
+ for (const row of replaced) {
+ const key = occurrenceKey(row.sha256, row.entryState, regionTrust(flags, row.region));
+ byKey.set(key, [...(byKey.get(key) ?? []), row]);
+ }
+ const used = new Set<ManifestRow>();
+ const fresh: NewRow[] = [];
+ const changed: ManifestRowInput[] = [];
+ const closeOccurrences: number[] = [];
+ const pending: SegmentTextInput[] = [];
+ for (const item of out) {
+ let keep = item.moved;
+ if (!keep) {
+ const candidates = (byKey.get(occurrenceKey(item.row.sha256, item.row.entryState, item.segment!.fenceTrust)) ?? []).filter(row => !used.has(row));
+ keep = candidates.find(row => row.seq === item.row.seq) ?? candidates[0];
+ if (keep) used.add(keep);
+ }
+ if (keep) {
+ item.row.occurrenceId = Number(keep.occurrenceId);
+ if (rowUnchanged(keep, item.row)) continue;
+ changed.push(item.row);
+ closeOccurrences.push(item.row.occurrenceId);
+ continue;
+ }
+ fresh.push(item);
+ changed.push(item.row);
+ pending.push({ sha256: item.row.sha256, body: item.text, lineCount: item.row.lineCount });
+ }
+ const ids = fresh.length ? await engine.allocateBodyOccurrenceIds(fresh.length) : [];
+ fresh.forEach((item, k) => { item.row.occurrenceId = ids[k]!; });
+ const retireChunkOccurrences = replaced.filter(row => !used.has(row)).map(row => Number(row.occurrenceId));
+ closeOccurrences.push(...retireChunkOccurrences);
+
+ if (pending.length) await writes(exec => exec.stageSegmentTexts(input.sourceId, pending, { stagingId }));
+ await faultPoint('segmented:texts_staged', { sourceId: input.sourceId });
+ if (changed.length) await writes(exec => exec.stageManifestRows(changed));
+ await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });
+
+ const lastOld = rows[rows.length - 1]!;
+ const delta = byteStart - (Number(lastOld.byteStart) + lastOld.byteLen);
+ const truthDelta = reps.filter(r => regionOf(r) === 'truth').reduce((n, r) => n + r.bytes.length - (r.end - r.start), 0);
+ const lines = out.reduce((n, item) => n + item.row.lineCount, 0) - rows.slice(f).reduce((n, row) => n + row.lineCount, 0);
+ const lead = (region: BodyRegion, kept: string) => {
+ const head = out.find(item => item.row.region === region);
+ const startsRegion = !!head && (region === 'truth' ? head.row.byteStart === 0 : head.row.byteStart === page.truthBytes + truthDelta);
+ return startsRegion && !head!.moved ? utf8Prefix(head!.text, BODY_LEAD_BYTES) : kept;
+ };
+ const body: SegmentedBodyColumns = {
+ content_hash: hasher.finish({ frontmatter: input.frontmatter, tags: [...input.tags] }),
+ body_bytes: page.bodyBytes + delta, truth_bytes: page.truthBytes + truthDelta, body_lines: page.bodyLines + lines,
+ segment_count: seq, segmenter_version: SEGMENTER_VERSION,
+ truth_lead: lead('truth', page.truthLead), timeline_lead: lead('timeline', page.timelineLead),
+ body_flags: { ...flags, has_protected: flags.has_protected === true || out.some(item => (item.row.protectedRegions as StoredRegion[]).length > 0) },
+ };
+ const chunkable = await occurrencesWithoutChunks(engine, page.id, page.generation, changed);
+ const chunks = await stageOccurrenceChunks(engine, { pageId: page.id, sourceId: input.sourceId, slug: input.slug, generation, occurrences: chunkable,
+ title: page.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking, retiredOccurrences: retireChunkOccurrences });
+ await faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });
+ const kept = new Set(out.filter(item => !fresh.includes(item)).map(item => item.row.occurrenceId));
+ retireChunkOccurrences.push(...chunkable.filter(row => kept.has(row.occurrenceId)).map(row => row.occurrenceId));
+ await engine.setBodyStagingState(stagingId, 'prepared');
+ return { rescanned: false, prepared: { stagingId, expectedGeneration: page.generation, newGeneration: generation, createRows: null, createChunks: null,
+ closeOccurrences, retireChunkOccurrences, unchunked: input.chunking.quarantined ? 0 : chunkable.length - chunks.occurrences, priorStale: !page.sealed, body,
+ bodyUnchanged: changed.length === 0 && retireChunkOccurrences.length === 0, rows: { texts: fresh.length, manifest: changed.length, chunks: chunks.rows },
+ stagedChunkIndexes: chunks.indexes } };
+ } catch (error) {
+ await engine.setBodyStagingState(stagingId, 'aborted').catch(() => undefined);
+ throw error;
+ }
+}
+
+/** The live segmented page a splice reads, from its row (metadata only); null when the page is not segmented. */
+export async function splicePage(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<SplicePage | null> {
+ const [row] = await engine.executeRaw<{ id: number; body_generation: string; title: string; type: string; body_flags: JsonObject | null; truth_lead: string | null;
+ timeline_lead: string | null; body_bytes: string; truth_bytes: string; body_lines: string; segment_count: number; sealed: boolean; body_storage: string;
+ contextual_retrieval_mode: string | null; corpus_generation: string | null; page_kind: string }>(
+ 'SELECT id, body_generation::text AS body_generation, title, type, body_flags, truth_lead, timeline_lead, body_bytes::text AS body_bytes,'
+ + ' truth_bytes::text AS truth_bytes, body_lines::text AS body_lines, segment_count, body_storage, contextual_retrieval_mode, corpus_generation, page_kind,'
+ + ' (text_projection_revision = knowledge_revision) IS TRUE AS sealed FROM pages WHERE id=$1', [pageId]);
+ if (!row || row.body_storage !== 'segmented') return null;
+ const title = row.contextual_retrieval_mode === 'title';
+ return { id: Number(row.id), generation: Number(row.body_generation), title: row.title, type: row.type, flags: row.body_flags, truthLead: row.truth_lead ?? '',
+ timelineLead: row.timeline_lead ?? '', bodyBytes: Number(row.body_bytes), truthBytes: Number(row.truth_bytes), bodyLines: Number(row.body_lines),
+ segmentCount: Number(row.segment_count), sealed: row.sealed, crTier: title ? 'title' : 'none', corpusGeneration: title ? row.corpus_generation : null,
+ pageKind: row.page_kind };
+}
diff --git a/src/core/page-body/tail-digest.ts b/src/core/page-body/tail-digest.ts
new file mode 100644
index 0000000000..76b9636290
--- /dev/null
+++ b/src/core/page-body/tail-digest.ts
@@ -0,0 +1,44 @@
+/**
+ * The append precondition's tail digest (Wave B, spec 6.1): sha256 of a region's last min(4096, region bytes) raw
+ * stored bytes. get_page body:'none' returns it (tail_sha256) and append_page's expected_tail_sha256 compares against
+ * it. A remote caller is never given, and cannot test, a tail holding protected or facts text: a hash of hidden text
+ * is a guessing oracle. Segmented pages: page-window/segmented.ts tailDigest; inline pages: here.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { PROTECTED_PAIRS } from '../remote-body.ts';
+import { protectedRegions } from '../fence-scan.ts';
+
+export const APPEND_TAIL_BYTES = 4096;
+
+export interface RegionTail {
+ region: 'truth' | 'timeline';
+ /** The region's last min(APPEND_TAIL_BYTES, region bytes) raw bytes. */
+ bytes: Uint8Array;
+ /** Those bytes hold protected or facts text: withheld from (and not testable by) a remote caller. */
+ guarded: boolean;
+}
+
+export const tailSha256 = (tail: RegionTail) => createHash('sha256').update(tail.bytes).digest('hex');
+
+/** The tail of an inline region's raw text, guarded when a facts or takes fence (or an unclosed opener) reaches it. */
+export function inlineRegionTail(text: string, region: 'truth' | 'timeline'): RegionTail {
+ const raw = Buffer.from(text, 'utf8');
+ const from = Math.max(0, raw.length - APPEND_TAIL_BYTES);
+ const { regions, truncatedAt } = protectedRegions(text, PROTECTED_PAIRS);
+ const at = (index: number) => Buffer.byteLength(text.slice(0, index), 'utf8');
+ return { region, bytes: raw.subarray(from), guarded: (truncatedAt !== -1 && at(truncatedAt) < raw.length) || regions.some(r => at(r.end) > from) };
+}
+
+/** An inline page's stored regions, read raw (no withdrawal overlay), as the append path compares them. */
+export async function inlineRegions(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<{ truth: string; timeline: string }> {
+ const [row] = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>('SELECT compiled_truth, timeline FROM pages WHERE id=$1', [pageId]);
+ return { truth: row?.compiled_truth ?? '', timeline: row?.timeline ?? '' };
+}
+
+/** get_page body:'none' for an inline page: the digest of its last non-empty region's tail, as tailDigest reports a segmented page's. */
+export async function inlineTailDigest(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, remote: boolean): Promise<{ tail_sha256: string; tail_region: string } | Record<string, never>> {
+ const { truth, timeline } = await inlineRegions(engine, pageId);
+ const tail = timeline ? inlineRegionTail(timeline, 'timeline') : inlineRegionTail(truth, 'truth');
+ return remote && tail.guarded ? {} : { tail_sha256: tailSha256(tail), tail_region: tail.region };
+}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index cb7b8e8569..104af67d38 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -360,7 +360,7 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Prepared
outcome.persistence = { mode: fileCount ? 'filesystem' : 'database', ...(fileCount ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };
outcome.write_through = fileCount ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };
if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';
- if ((row.operation === 'put_page' || row.operation === 'edit_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);
+ if ((row.operation === 'put_page' || row.operation === 'edit_page' || row.operation === 'append_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);
if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {
outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };
}
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index 2e3e7a7a97..020b4f4721 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -17,7 +17,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', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page',
+ 'put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'append_page',
'remember', 'forget', 'extract_facts', 'get_write_request', 'list_write_requests', 'cancel_write_request',
'get_page', 'fetch', 'get_recent_transcripts',
'list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack',
@@ -37,7 +37,7 @@ export const LOCAL_CLI_OWNER_OPERATIONS: ReadonlySet<string> = new Set(['purge_f
export type PersistenceIpcOperation = typeof PERSISTENCE_IPC_OPERATIONS[number];
const OPERATIONS = new Set<string>(PERSISTENCE_IPC_OPERATIONS);
const MUTATIONS = new Set<string>([
- 'put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'remember', 'forget', 'extract_facts',
+ 'put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'append_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', 'takes_remove', 'takes_rebuild',
]);
diff --git a/src/core/persistence/page-append.ts b/src/core/persistence/page-append.ts
new file mode 100644
index 0000000000..80d9c4c550
--- /dev/null
+++ b/src/core/persistence/page-append.ts
@@ -0,0 +1,402 @@
+/**
+ * Wave B (spec 6.1): append_page. Text added to the end of a page region, idempotent by request_id, in time
+ * proportional to the text added. The journal intent holds the appended text (or, from an upload session, a
+ * reference to its staged parts), never the body.
+ *
+ * - A segmented page splices the text onto its region's tail (page-body/splice.ts): the tail segment is segmented
+ * again with the text, its new segments are staged and chunked, the content_hash resumes from the midstate before
+ * it, and nothing before the tail is read. A change of the region's fence trust restages the whole body
+ * (`rescanned: true` in the receipt).
+ * - An inline page composes the new body and takes put_page's write path, which promotes it when the result crosses
+ * the segmented threshold.
+ *
+ * Preconditions are optional: `expected_revision` (`revision_changed`) and `expected_tail_sha256`, the sha256 of the
+ * region's last min(4096, region bytes) raw bytes as get_page body:'none' returns it (`tail_changed`). A remote
+ * caller is never shown, and cannot test, a tail that holds protected or facts text (a hash of hidden text is a
+ * guessing oracle), as get_page withholds it.
+ *
+ * The segmented path writes its derived rows for the appended text after commit as any segmented write does (chunks,
+ * embeddings); links, timeline rows and fence projections of the appended text follow PR 4's incremental derivation.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { OperationContext } from '../operations.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
+import { serializePageToMarkdown, timelineSentinelKind } from '../markdown.ts';
+import { isQuarantined } from '../quarantine.ts';
+import { sizeStateField } from '../page-embedding-budget.ts';
+import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+import { loadImportSanityConfig } from '../import-screen.ts';
+import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
+import { pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
+import { readPageBodyPolicy } from '../page-body/limits.ts';
+import { isSegmentedPage, withoutBody } from '../page-body/page-shape.ts';
+import { openSegmentedBody, readBodyRange } from '../page-body/read-range.ts';
+import { ledgerApplies } from '../page-body/segment-ledger.ts';
+import { buildSegmentedProjection } from '../page-body/projection.ts';
+import { segmentWriteScope } from '../page-body/ingest.ts';
+import { spliceSegmentedBody, splicePage, type BodyReplacement, type SplicePage } from '../page-body/splice.ts';
+import { TIMELINE_SEPARATOR } from '../page-window/document.ts';
+import { APPEND_TAIL_BYTES, inlineRegions, inlineRegionTail, type RegionTail } from '../page-body/tail-digest.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { pageIdentityError } from './page-identity.ts';
+import { remoteLinkHint } from './page-advisories.ts';
+import { applySegmentedBody, materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';
+import { StreamedFileContent } from './large-file.ts';
+import { pageDatabaseOnlyPublication, pageFix, pageRefusal, preparePageMutation, prepareFileTarget, snapshotLedger } from './page-prepare.ts';
+import { submitPageMutation } from './page-mutations.ts';
+import { isWriteRequestId } from './types.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import type { WriteRequest } from './model.ts';
+import type { ClaimPhaseClock } from './claim-phase.ts';
+
+/** The most text one append_page call carries; a larger append goes through an upload session (mode 'append'). */
+export const APPEND_TEXT_MAX_BYTES = 4 * 1024 * 1024;
+
+export type AppendRegion = 'auto' | 'truth' | 'timeline';
+export type AppendSeparator = 'auto' | 'none';
+/** Staged parts of an upload session holding the text (lane 3b's commit_page_upload, mode 'append'). */
+export interface AppendBodyRef { kind: 'staging'; staging_id: string; sha256: string; bytes: number }
+
+export interface AppendPageInput {
+ slug: string;
+ source_id?: string;
+ /** Exactly one of text and body_ref. */
+ text?: string;
+ body_ref?: AppendBodyRef;
+ request_id: string;
+ expected_revision?: string;
+ expected_tail_sha256?: string;
+ region?: AppendRegion;
+ separator?: AppendSeparator;
+ wait_ms?: unknown;
+}
+
+interface AppendIntent {
+ kind: 'append_page';
+ text?: string;
+ body_ref?: AppendBodyRef;
+ region: AppendRegion;
+ separator: AppendSeparator;
+ preconditions: { expected_revision?: string; expected_tail_sha256?: string };
+}
+
+/**
+ * @internal The forced probe of the append cost test (test/large-pages/append-cost.test.ts): every segmented append
+ * restages the whole body, as an append by put_page rewrite would.
+ */
+export const appendProbe = { fullRewrite: false };
+
+const MARKERS = [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END];
+const SHA256 = /^[0-9a-f]{64}$/;
+const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion);
+
+/** Rejects appended text append_page never writes; the same rules for an inline and a segmented page. */
+function assertAppendText(text: string): void {
+ if (!text.length) throw invalid('append_page text is empty.', 'Pass the text to add as text.');
+ if (text.includes('\0')) throw invalid('append_page text contains a NUL byte.', 'Pass text without NUL bytes; binary files are stored with file_upload.');
+ if (!text.isWellFormed()) throw invalid('append_page text contains a lone UTF-16 surrogate.', 'Pass well-formed text.');
+ if (MARKERS.some(marker => text.includes(marker))) {
+ throw invalid('append_page text contains a protected facts or takes fence marker.',
+ 'Write facts with remember and takes with takes_add; append_page adds ordinary text only.');
+ }
+ if (text.split('\n').some(line => timelineSentinelKind(line.trim()) === 'marker')) {
+ throw invalid('append_page text contains a timeline sentinel line.', 'Pass region: \'timeline\' to add to the timeline, and drop the sentinel line from text.');
+ }
+}
+
+function parseAppendInput(input: AppendPageInput): AppendIntent {
+ if (typeof input.slug !== 'string' || !input.slug) throw invalid('append_page requires slug.', 'Pass the slug of the page to append to.');
+ if (typeof input.request_id !== 'string' || !input.request_id) {
+ throw invalid('append_page requires request_id.', 'Pass a new request_id (a UUID) for each append; a retry with the same request_id never appends twice.');
+ }
+ const region = input.region ?? 'auto';
+ if (!['auto', 'truth', 'timeline'].includes(region)) throw invalid('region must be auto, truth or timeline.', 'Omit region to append to the last non-empty region.');
+ const separator = input.separator ?? 'auto';
+ if (!['auto', 'none'].includes(separator)) throw invalid('separator must be auto or none.', 'Omit separator to insert one newline when the tail lacks one.');
+ if (input.expected_revision !== undefined && !isWriteRequestId(input.expected_revision)) {
+ throw invalid('expected_revision must be the UUID returned by a page read.', 'Read the page with get_page body: \'none\' and pass its revision unchanged.');
+ }
+ const tail = input.expected_tail_sha256;
+ if (tail !== undefined && (typeof tail !== 'string' || !SHA256.test(tail.toLowerCase()))) {
+ throw invalid('expected_tail_sha256 must be a lowercase hex sha256.', 'Pass tail_sha256 from get_page body: \'none\' unchanged.');
+ }
+ if ((input.text === undefined) === (input.body_ref === undefined)) throw invalid('append_page takes exactly one of text and body_ref.', 'Pass the text to add as text.');
+ if (input.text !== undefined) {
+ if (typeof input.text !== 'string') throw invalid('append_page text must be a string.', 'Pass the text to add as text.');
+ const bytes = Buffer.byteLength(input.text, 'utf8');
+ if (bytes > APPEND_TEXT_MAX_BYTES) {
+ throw opError('request_too_large', `append_page text is ${bytes} bytes, over the ${APPEND_TEXT_MAX_BYTES}-byte limit of one call.`,
+ 'Nothing was admitted. Send a larger append through an upload session: begin_page_upload with mode: \'append\', then upload_page_part and commit_page_upload.');
+ }
+ assertAppendText(input.text);
+ } else {
+ const ref = input.body_ref!;
+ if (ref?.kind !== 'staging' || !isWriteRequestId(ref.staging_id) || typeof ref.sha256 !== 'string' || !SHA256.test(ref.sha256)
+ || !Number.isSafeInteger(ref.bytes) || ref.bytes <= 0) throw invalid('body_ref must name a sealed upload staging.', 'Commit the upload session with commit_page_upload.');
+ }
+ return { kind: 'append_page', ...(input.text !== undefined ? { text: input.text } : { body_ref: { kind: 'staging', staging_id: input.body_ref!.staging_id,
+ sha256: input.body_ref!.sha256, bytes: input.body_ref!.bytes } }), region, separator,
+ preconditions: { ...(input.expected_revision ? { expected_revision: input.expected_revision.toLowerCase() } : {}),
+ ...(tail ? { expected_tail_sha256: tail.toLowerCase() } : {}) } };
+}
+
+/**
+ * Admit one append (append_page, and lane 3b's commit_page_upload for mode 'append' with `body_ref`) and wait for its
+ * receipt as put_page does. A `tail_changed` refusal carries the current tail digest when the caller may see it.
+ */
+export async function admitPageAppend(ctx: OperationContext, input: AppendPageInput): Promise<Record<string, unknown>> {
+ const intent = parseAppendInput(input);
+ const params = { slug: input.slug, ...(input.source_id !== undefined ? { source_id: input.source_id } : {}), request_id: input.request_id,
+ ...(input.wait_ms !== undefined ? { wait_ms: input.wait_ms } : {}), ...intent };
+ try {
+ return await submitPageMutation(ctx, { operation: 'append_page', params });
+ } catch (error) {
+ if (!(error instanceof OperationError) || (error.canonical ?? error.code) !== 'tail_changed') throw error;
+ const sourceId = String(error.receiptFields?.source_id ?? input.source_id ?? ctx.sourceId ?? 'default');
+ const slug = String(error.receiptFields?.slug ?? input.slug).toLowerCase();
+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId });
+ const found = snapshot && !snapshot.page.deleted_at ? await regionTail(ctx.engine, snapshot, intent.region) : null;
+ const tail = found && !(ctx.remote !== false && found.guarded) ? found : null;
+ Object.assign(error, tailChangedError(sourceId, slug, tail));
+ throw error;
+ }
+}
+
+/** The region an append targets: `auto` is the last non-empty region (the timeline when it holds text). */
+const targetRegion = (region: AppendRegion, hasTimeline: boolean): 'truth' | 'timeline' => region === 'auto' ? (hasTimeline ? 'timeline' : 'truth') : region;
+const sha256Hex = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+
+/** The tail of a segmented region: its last rows' raw text, guarded when one of those rows holds a protected or facts region. */
+async function segmentedRegionTail(engine: BrainEngine, sourceId: string, page: Pick<SplicePage, 'id' | 'generation'>, region: 'truth' | 'timeline'): Promise<RegionTail> {
+ const rows = await engine.executeRaw<{ sha256: Uint8Array; byte_len: number; guarded: boolean }>(`SELECT sha256, byte_len,
+ (protected_regions <> '[]'::jsonb OR facts_slots <> '[]'::jsonb) AS guarded FROM page_body_manifest
+ WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2) AND region=$3 AND byte_len > 0
+ ORDER BY seq DESC LIMIT 8`, [page.id, page.generation, region]);
+ const tail: typeof rows = [];
+ for (let i = 0, bytes = 0; i < rows.length && bytes < APPEND_TAIL_BYTES; i++) { tail.unshift(rows[i]!); bytes += Number(rows[i]!.byte_len); }
+ if (!tail.length) return { region, bytes: new Uint8Array(), guarded: false };
+ const texts = await engine.readSegmentTexts(sourceId, tail.map(r => r.sha256));
+ const raw = Buffer.concat(tail.map(r => {
+ const text = texts.get(Buffer.from(r.sha256).toString('hex'));
+ if (!text) throw new Error(`Segment text ${Buffer.from(r.sha256).toString('hex')} of page ${page.id} is missing.`);
+ return text;
+ }));
+ return { region, bytes: raw.subarray(Math.max(0, raw.length - APPEND_TAIL_BYTES)), guarded: tail.some(r => r.guarded) };
+}
+
+/** The tail an append to `region` of the page in `snapshot` extends, raw; null for a segmented page that stopped being one. */
+async function regionTail(engine: BrainEngine, snapshot: PageSnapshot, region: AppendRegion): Promise<RegionTail | null> {
+ if (isSegmentedPage(snapshot.page)) {
+ const page = await splicePage(engine, Number(snapshot.page.id));
+ return page && segmentedRegionTail(engine, snapshot.page.source_id, page, targetRegion(region, page.bodyBytes > page.truthBytes));
+ }
+ const { truth, timeline } = await inlineRegions(engine, Number(snapshot.page.id));
+ const target = targetRegion(region, !!timeline);
+ return inlineRegionTail(target === 'timeline' ? timeline : truth, target);
+}
+
+function tailChangedError(sourceId: string, slug: string, tail: RegionTail | null): { fix: ReturnType<typeof readFix>; detail: string } {
+ const current = tail ? sha256Hex(tail.bytes) : null;
+ const read = readFix(current ? `Returns the current revision and tail_sha256 (now ${current}).` : 'Returns the current revision and size.', {
+ argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } } });
+ return { detail: JSON.stringify({ current_tail_sha256: current, ...(tail ? { tail_region: tail.region } : {}) }),
+ fix: current ? { ...read, then: { mcp: { tool: 'append_page', arguments: { slug, source_id: sourceId, expected_tail_sha256: current } }, consent: [], actor: 'agent',
+ why: 'Appends against the current tail, once the reread shows the text is still missing.', requires_exclusive: false,
+ inputs: [{ name: 'text', how: 'the text to add' }, { name: 'request_id', how: 'a new request_id' }] } } : read };
+}
+
+function tailRefusal(row: WriteRequest, region: string): OperationError {
+ return opError('tail_changed', `The ${region} tail of page ${row.slug} no longer has the expected sha256, so nothing was appended.`,
+ `Another write changed the end of the page. Read it again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id.`,
+ { fix: pageFix(row.source_id, row.slug) });
+}
+
+function revisionRefusal(row: WriteRequest, current: string): OperationError {
+ return opError('revision_changed', `Page ${row.slug} changed since expected_revision was read (now ${current}), so nothing was appended.`,
+ 'Read the page again with get_page body: \'none\' and append against its current revision with a new request_id, or omit expected_revision to append unconditionally.',
+ { detail: JSON.stringify({ current_revision: current }),
+ fix: readFix('Returns the current revision and size.', { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug],
+ mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id, body: 'none' } } }) });
+}
+
+/** The appended text: the intent's, or an upload session's staged parts read back in order and checked against the reference. */
+async function appendedText(engine: BrainEngine, intent: AppendIntent): Promise<string> {
+ if (intent.text !== undefined) return intent.text;
+ const ref = intent.body_ref!;
+ const parts = await engine.executeRaw<{ body: Uint8Array }>('SELECT body FROM page_body_staging_parts WHERE staging_id=$1::uuid ORDER BY part_no', [ref.staging_id]);
+ const raw = Buffer.concat(parts.map(part => Buffer.from(part.body)));
+ if (raw.length !== ref.bytes || sha256Hex(raw) !== ref.sha256) {
+ throw opError('body_staging_expired', 'The staged text of this append is gone or changed, so nothing was appended.',
+ 'Begin a new upload session and send the text again.', { detail: JSON.stringify({ staging_id: ref.staging_id }) });
+ }
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw);
+ assertAppendText(text);
+ return text;
+}
+
+/** The new Markdown file of a segmented page: its stored regions with `replacements` applied (a ledger that rewrites bytes refuses: null). */
+async function splicedPageFile(engine: BrainEngine, snapshot: PageSnapshot, frontmatter: Record<string, unknown>, replacements: readonly BodyReplacement[],
+ appendTo?: 'truth' | 'timeline'): Promise<StreamedFileContent | null> {
+ const ledger = snapshotLedger(snapshot);
+ if (!appendTo && (ledgerApplies(ledger) || replacements.some(r => r.start === r.end))) return null;
+ const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), frontmatter, compiled_truth: '', timeline: '' } as never, snapshot.tags).slice(0, -1);
+ const pageId = Number(snapshot.page.id);
+ const produce = async function* (exec: BrainEngine): AsyncIterable<Uint8Array | string> {
+ const body = await openSegmentedBody(exec, { pageId, ledger });
+ yield head;
+ let separated = false;
+ for (const region of ['truth', 'timeline'] as const) {
+ const pieces = async function* (): AsyncIterable<Uint8Array> {
+ for await (const piece of readBodyRange(exec, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region, body })) {
+ if (appendTo) { yield piece.bytes; continue; }
+ const start = piece.storedStart, end = start + piece.bytes.length;
+ let at = 0;
+ for (const r of replacements) {
+ if (r.start >= end || r.end <= start) continue;
+ if (r.start > start + at) yield piece.bytes.subarray(at, r.start - start);
+ if (r.start >= start) yield r.bytes;
+ at = Math.max(at, Math.min(r.end, end) - start);
+ }
+ if (at < piece.bytes.length) yield piece.bytes.subarray(at);
+ }
+ if (appendTo === region) for (const r of replacements) yield r.bytes;
+ };
+ for await (const bytes of pieces()) {
+ if (!bytes.length) continue;
+ if (region === 'timeline' && !separated) { yield TIMELINE_SEPARATOR; separated = true; }
+ yield bytes;
+ }
+ }
+ yield '\n';
+ };
+ return StreamedFileContent.measure(engine, produce);
+}
+
+export interface SegmentedSpliceRequest {
+ /** The replacements to publish, from the live page's metadata; null declines (the caller takes its whole-body path). */
+ replacements(page: SplicePage): Promise<{ replacements: BodyReplacement[]; appendTo?: 'truth' | 'timeline'; outcome?: Record<string, unknown> } | null>;
+ /** Restage the whole body (appendProbe). */
+ full?: boolean;
+}
+
+/**
+ * The publication of a splice of a segmented page (append_page, segmented edit_page): stage the touched segments,
+ * then, in the publication transaction, version the page, flip the generation and reseal it when every occurrence has
+ * chunks; as put_page, the write stamps the writer's trust marker and files a lowering. Null when the splice does not
+ * apply: an external_untrusted write the gate scans whole, an always-loaded core page, a change that creates or empties
+ * a region, or a file a withdrawal ledger rewrites. The caller then takes its whole-body path.
+ */
+export async function prepareSegmentedSpliceMutation(engine: BrainEngine, row: WriteRequest, stored: PageSnapshot, request: SegmentedSpliceRequest): Promise<PreparedMutation | null> {
+ const source = { sourceId: row.source_id };
+ const frontmatter: Record<string, unknown> = { ...(stored.page.frontmatter ?? {}) };
+ if (frontmatter.always_load !== undefined || frontmatter.core_priority !== undefined) return null;
+ const [, pack, storedTier] = await Promise.all([assertKnowledgePublicationAllowed(engine, row),
+ loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null), storedPageTier(engine, row.source_id, row.slug)]);
+ const trust = pageWriteTrust(row, frontmatter);
+ const gateTrust = pageGateTrust(row, trust, storedTier);
+ if (gateTrust?.tier === 'external_untrusted' && writeGateApplies(gateTrust.tier, (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) return null;
+ const pageId = Number(stored.page.id);
+ const page = await splicePage(engine, pageId);
+ if (!page) return null;
+ const built = await request.replacements(page);
+ if (!built) return null;
+ stampPageTrustMarker(row, frontmatter, trust, storedTier);
+ const content = row.worktree_id ? await splicedPageFile(engine, stored, frontmatter, built.replacements, built.appendTo) : undefined;
+ if (content === null) return null;
+ const quarantined = isQuarantined(frontmatter);
+ const splice = await spliceSegmentedBody(engine, { sourceId: row.source_id, slug: row.slug, page, frontmatter, tags: stored.tags, replacements: built.replacements,
+ owner: { kind: row.operation === 'append_page' ? 'append' : 'edit', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: stored.revision },
+ chunking: { quarantined, tier: page.crTier, corpusGeneration: page.corpusGeneration }, full: request.full });
+ if (!splice) return null;
+ const { prepared } = splice;
+ const abort = () => engine.setBodyStagingState(prepared.stagingId, 'aborted').catch(() => undefined);
+ try {
+ const file = content ? await prepareFileTarget(engine, row, stored, content, undefined, { activePack: pack?.manifest, remote: row.authority.remote }) : undefined;
+ const { flipRetireMaxRows } = await readPageBodyPolicy(engine);
+ let applied: { complete: boolean } | null = null;
+ return { observedRevision: stored.revision, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(trust ? { trust } : {}),
+ apply: async tx => {
+ await tx.createVersion(row.slug, source);
+ applied = await applySegmentedBody(tx, { slug: row.slug, sourceId: row.source_id, pageId, prepared, promotion: false, retireMaxRows: flipRetireMaxRows,
+ meta: { title: stored.page.title, type: stored.page.type, frontmatter: frontmatter as never, page_kind: page.pageKind as never } });
+ const lowered = storedTier ? await recordAgentPageLowering(tx, row, { tier: storedTier, revision: stored.revision }) : null;
+ if (applied.complete) await sealSegmentedPage(tx, pageId);
+ const [after] = await tx.executeRaw<{ body_bytes: string }>('SELECT body_bytes::text AS body_bytes FROM pages WHERE id=$1', [pageId]);
+ return { ...remoteLinkHint(row), status: 'created_or_updated', slug: row.slug, source_id: row.source_id, chunks: prepared.rows.chunks, noop: false,
+ searchable: quarantined ? false : applied.complete ? true : 'pending', ...(applied.complete ? {} : { projection: 'pending' }),
+ ...(splice.rescanned ? { rescanned: true } : {}), ...(lowered ? { trust_lowered: lowered } : {}),
+ body_bytes: Number(after?.body_bytes ?? prepared.body.body_bytes), chunks_new: prepared.rows.chunks, ...built.outcome,
+ ...await sizeStateField(tx, row.source_id, row.slug, { body_storage: 'segmented', body_bytes: prepared.body.body_bytes, frontmatter }) };
+ },
+ afterCommit: async target => {
+ if (!applied) { await abort(); return; }
+ if (!applied.complete) await buildSegmentedProjection(target, { sourceId: row.source_id, slug: row.slug }).catch(() => undefined);
+ await segmentWriteScope(target, row.source_id).then(writes => writes(exec => exec.sweepSegments({ pageId }))).catch(() => undefined);
+ } };
+ } catch (error) {
+ await abort();
+ throw error;
+ }
+}
+
+/** The preparer of an append_page request (service.ts dispatch). */
+export async function prepareAppendMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
+ signal?.throwIfAborted();
+ const intent = row.intent as unknown as AppendIntent;
+ const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ if (!stored || stored.page.deleted_at) throw pageRefusal('page_not_found', 'Page not found.', row,
+ `Page ${row.slug} does not exist in source ${row.source_id} or is deleted, so nothing was appended. Create it with put_page; restore a deleted page with restore_page.`,
+ pageFix(row.source_id, row.slug));
+ if ((stored.page.id ?? null) !== row.page_id) throw pageIdentityError(true, 'The accepted page was deleted or recreated.');
+ const expected = intent.preconditions?.expected_revision;
+ if (expected && expected !== stored.revision) throw revisionRefusal(row, stored.revision);
+ const text = await appendedText(engine, intent);
+ const remote = row.authority.remote;
+ const expectedTail = intent.preconditions?.expected_tail_sha256;
+ const checkTail = (tail: RegionTail) => {
+ if (expectedTail && ((remote && tail.guarded) || sha256Hex(tail.bytes) !== expectedTail)) throw tailRefusal(row, tail.region);
+ };
+ const separatorFor = (tail: RegionTail) => intent.separator === 'auto' && tail.bytes.length > 0 && tail.bytes[tail.bytes.length - 1] !== 0x0a ? '\n' : '';
+
+ if (isSegmentedPage(stored.page)) {
+ const prepared = await prepareSegmentedSpliceMutation(engine, row, stored, { full: appendProbe.fullRewrite, replacements: async page => {
+ const region = targetRegion(intent.region, page.bodyBytes > page.truthBytes);
+ const tail = await segmentedRegionTail(engine, row.source_id, page, region);
+ checkTail(tail);
+ if (region === 'timeline' && page.bodyBytes === page.truthBytes) return null;
+ const bytes = Buffer.from(separatorFor(tail) + text, 'utf8');
+ const at = region === 'truth' ? page.truthBytes : page.bodyBytes;
+ return { replacements: [{ start: at, end: at, bytes }], appendTo: region, outcome: { appended_bytes: bytes.length, region } };
+ } });
+ if (prepared) return prepared;
+ if (Number((stored.page as { body_bytes?: number | null }).body_bytes ?? 0) + Buffer.byteLength(text, 'utf8') + 1 > PAGE_MAX_BYTES) {
+ throw opError('page_body_segmented', `Page ${row.slug} cannot take this append in segments (an external_untrusted write the gate scans whole, an always-loaded core page, or an append that starts a region), and it is over the ${PAGE_MAX_BYTES}-byte limit of a whole-body write. Nothing was appended.`,
+ 'Append to the last non-empty region (omit region), or write from a trusted caller.', { fix: pageFix(row.source_id, row.slug) });
+ }
+ }
+ // Inline (or a segmented page the splice declined, within the whole-body limit): compose the body and take put_page's path.
+ const snapshot = (await materializedSnapshot(engine, stored))!;
+ const page = snapshot.page;
+ const region = targetRegion(intent.region, !!(page.timeline ?? ''));
+ const before = (region === 'timeline' ? page.timeline : page.compiled_truth) ?? '';
+ checkTail((await regionTail(engine, stored, region))!);
+ const after = before + separatorFor(inlineRegionTail(before, region)) + text;
+ const content = serializePageToMarkdown({ ...page, ...(region === 'timeline' ? { timeline: after } : { compiled_truth: after }) }, snapshot.tags);
+ const beforeBytes = Buffer.byteLength(page.compiled_truth ?? '', 'utf8') + Buffer.byteLength(page.timeline ?? '', 'utf8');
+ const prepared = await preparePageMutation(engine, row, config, { content, expectedRevision: stored.revision }, signal, { clock });
+ const apply = prepared.apply.bind(prepared);
+ return { ...prepared, apply: async (tx, preimage) => {
+ const outcome = await apply(tx, preimage);
+ const [row2] = await tx.executeRaw<{ bytes: string | null }>(`SELECT COALESCE(body_bytes, octet_length(COALESCE(compiled_truth,'')) + octet_length(COALESCE(timeline,'')))::text AS bytes
+ FROM pages WHERE id=$1`, [stored.page.id]);
+ const bodyBytes = Number(row2?.bytes ?? 0);
+ return { ...outcome, body_bytes: bodyBytes, appended_bytes: Math.max(0, bodyBytes - beforeBytes), chunks_new: Number(outcome.chunks ?? 0), region };
+ } } as PreparedMutation;
+}
diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.ts
index 9b803a55be..56ad237631 100644
--- a/src/core/persistence/page-edit.ts
+++ b/src/core/persistence/page-edit.ts
@@ -22,6 +22,18 @@ import { serializePageToMarkdown } from '../markdown.ts';
import { insertNoNewlineMarkers, splitLines, unifiedDiff } from '../skillpack/diff-text.ts';
import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { scanCanonicalFences, targetFenceRefusal } from '../fence-repair/refusal.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+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 { STAGE_BATCH_BYTES } from '../page-body/limits.ts';
+import { TIMELINE_SEPARATOR } from '../page-window/document.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import type { WriteRequest } from './model.ts';
+import type { PreparedMutation } from './coordinator.ts';
export const EDIT_PAGE_MAX_EDITS = 50;
export const EDIT_PAGE_DIFF_MAX_BYTES = 8 * 1024;
@@ -34,6 +46,8 @@ const EDIT_PAGE_DIFF_CONTEXT = 3;
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; }
+/** A stored-body byte range (truth bytes then timeline bytes, as get_page window reads return it in `edit_target`) that every match must lie in. */
+export interface EditWithin { byte_start: number; byte_end: number; }
interface Segment { canonical: string; view: string; editable: boolean; }
const MARKERS = [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END];
@@ -71,6 +85,19 @@ export function parsePageEdits(value: unknown): PageEdit[] {
});
}
+/** Validates `within`: integer stored-body offsets with byte_start < byte_end. */
+export function parseEditWithin(value: unknown): EditWithin | undefined {
+ if (value === undefined || value === null) return undefined;
+ const record = value as Record<string, unknown>;
+ if (typeof value !== 'object' || Array.isArray(value) || Object.keys(record).some(k => k !== 'byte_start' && k !== 'byte_end')
+ || !Number.isSafeInteger(record.byte_start) || !Number.isSafeInteger(record.byte_end)
+ || (record.byte_start as number) < 0 || (record.byte_end as number) <= (record.byte_start as number)) {
+ throw editError('edit_invalid', 'within must be { byte_start, byte_end } with 0 <= byte_start < byte_end.',
+ "Pass edit_target's byte_start and byte_end from a get_page window read unchanged, or omit within.");
+ }
+ return { byte_start: record.byte_start as number, byte_end: record.byte_end as number };
+}
+
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.',
@@ -143,19 +170,43 @@ function occurrences(haystack: string, needle: string): number[] {
* 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 } {
+export function applyPageEdits(page: Page, tags: string[], remote: boolean, edits: PageEdit[], within?: EditWithin): { content: string; before: string; after: string } {
// #6188 (D19): edit_page never rewrites a fence; a stored fence that does not compile refuses typed, location only.
const [defect] = scanCanonicalFences(page).defects;
if (defect) throw targetFenceRefusal(defect, page.slug, page.source_id);
let segments = pageSegments(page, tags, remote);
const before = join(segments, 'view');
+ // `within` is in stored-body bytes of the page as read: canonical positions map back through the edits applied so far.
+ const head = serializePageToMarkdown({ ...page, compiled_truth: '', timeline: '' }, tags).slice(0, -1).length;
+ const truth = page.compiled_truth ?? '', timeline = page.timeline ?? '';
+ const timelineAt = head + truth.length + '\n\n<!-- timeline -->\n\n'.length;
+ const applied: Array<{ start: number; oldLen: number; newLen: number }> = [];
+ const original = (pos: number, side: 'start' | 'end') => {
+ for (let k = applied.length - 1; k >= 0; k--) {
+ const a = applied[k]!;
+ if (pos <= a.start) continue;
+ pos = pos >= a.start + a.newLen ? pos - (a.newLen - a.oldLen) : side === 'start' ? a.start : a.start + a.oldLen;
+ }
+ return pos;
+ };
+ 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;
+ const inRange = (start: number, end: number) => {
+ if (!within) return true;
+ const s = storedByte(original(start, 'start')), e = storedByte(original(end, 'end'));
+ return s >= 0 && e >= 0 && s >= within.byte_start && e <= within.byte_end;
+ };
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 ranges: Array<{ start: number; end: number; index: number; canonical: number }> = [];
+ let offset = 0, canonicalOffset = 0;
+ segments.forEach((segment, i) => {
+ ranges.push({ start: offset, end: offset + segment.view.length, index: i, canonical: canonicalOffset });
+ offset += segment.view.length; canonicalOffset += segment.canonical.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 canonicalAt = (at: number) => { const r = inside(at)!; return r.canonical + at - r.start; };
+ const all = occurrences(view, edit.old_text).filter(at => !within || (inside(at) ? inRange(canonicalAt(at), canonicalAt(at) + edit.old_text.length) : true));
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.`,
@@ -175,6 +226,7 @@ export function applyPageEdits(page: Page, tags: string[], remote: boolean, edit
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);
+ applied.push({ start: range.canonical + local, oldLen: edit.old_text.length, newLen: edit.new_text.length });
segments = segments.map((s, i) => i === range.index ? text(replaced) : s);
});
return { content: join(segments, 'canonical'), before, after: join(segments, 'view') };
@@ -264,8 +316,11 @@ export function boundedUnifiedDiff(
* `diff_coarse` marks a changed region too large to line-diff
* (boundedUnifiedDiff).
*/
-export function editDiff(slug: string, before: string, after: string): { diff: string; diff_truncated?: true; diff_coarse?: true } {
- const { diff, coarse } = boundedUnifiedDiff(before, after, `a/${slug}.md`, `b/${slug}.md`);
+export function editDiff(slug: string, before: string, after: string, lineOffset = 0): { diff: string; diff_truncated?: true; diff_coarse?: true } {
+ const bounded = boundedUnifiedDiff(before, after, `a/${slug}.md`, `b/${slug}.md`);
+ const { coarse } = bounded;
+ const diff = lineOffset === 0 ? bounded.diff : bounded.diff.replace(/^@@ -(\d+)((?:,\d+)?) \+(\d+)((?:,\d+)?) @@/gm,
+ (_, a: string, b: string, c: string, d: string) => `@@ -${Number(a) + lineOffset}${b} +${Number(c) + lineOffset}${d} @@`);
const [{ diff: full }] = redactRetrievalOutput([{ diff }], {}).results;
const marked = coarse ? { diff_coarse: true as const } : {};
if (encodedBytes(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full, ...marked };
@@ -288,3 +343,240 @@ export function assertEditRevision(current: string | null, expected: unknown): v
'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}`);
}
+
+
+/** Stored region kinds an edit never matches into: fence bodies and markers (a PEM block is ordinary text to edit_page). */
+const PROTECTED_KINDS = new Set(['facts', 'takes', 'tail', 'marker']);
+/** Virtual bytes a segmented scan searches per window before it carries |old_text| - 1 bytes on. */
+const SCAN_WINDOW_BYTES = 1024 * 1024;
+/** Context a segmented edit's receipt diff shows around its touched range, each side, before line rounding. */
+const DIFF_CONTEXT_BYTES = 2048;
+/** A touched range longer than this is diffed at its first replacement only (diff_truncated). */
+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 }
+
+/** 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]> {
+ for (let i = 0; i < rows.length;) {
+ let j = i, bytes = 0;
+ while (j < rows.length && (j === i || bytes + rows[j]!.byteLen <= STAGE_BATCH_BYTES[engine.kind])) bytes += rows[j++]!.byteLen;
+ const batch = rows.slice(i, j);
+ const texts = await engine.readSegmentTexts(sourceId, batch.map(row => row.sha256));
+ for (const row of batch) {
+ const text = texts.get(hexOf(row.sha256));
+ if (!text) throw new Error(`Segment text ${hexOf(row.sha256)} of page ${row.pageId} is missing.`);
+ spliceWork.read += text.length;
+ yield [row, text];
+ }
+ i = j;
+ }
+}
+
+/** 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);
+ 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 (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 };
+ if (!emitted.has(r)) { emitted.add(r); yield { origStart: r.start, origEnd: r.end, bytes: r.bytes, replaced: true }; }
+ cur = Math.min(r.end, end);
+ }
+ if (cur < end) yield { origStart: cur, origEnd: end, bytes: text.subarray(cur - start, end - start), replaced: false };
+ }
+}
+
+interface Match { start: number; end: number; prefix: Uint8Array; suffix: Uint8Array }
+
+/**
+ * Every match of `needle` in one region's edited bytes over original [from, to), mapped back to original stored
+ * 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,
+ needle: Buffer): 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() };
+ 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) => {
+ const limit = final ? buf.length : buf.length - (needle.length - 1);
+ for (let at = buf.indexOf(needle); at !== -1 && at < limit; at = buf.indexOf(needle, at + 1)) {
+ const s = locate(at, 'start'), e = locate(at + needle.length, 'end');
+ found.push({ start: s.orig, end: e.orig, prefix: s.rest, suffix: e.rest });
+ }
+ if (final) return;
+ const keep = Math.max(0, buf.length - (needle.length - 1));
+ map = 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)) {
+ if (!piece.bytes.length) continue;
+ map.push({ ...piece, v: buf.length });
+ buf = Buffer.concat([buf, piece.bytes]);
+ if (buf.length >= SCAN_WINDOW_BYTES) search(false);
+ }
+ search(true);
+ return found;
+}
+
+/** Stored spans (absolute) an edit never matches into. */
+/** Facts, takes and tail text as whole stored runs: the pieces of one region that segment cuts split are joined. */
+function hiddenRuns(rows: readonly ManifestRow[]): Array<{ start: number; end: number }> {
+ const runs: Array<{ start: number; end: number }> = [];
+ for (const span of protectedSpans(rows, false).sort((x, y) => x.start - y.start)) {
+ const last = runs[runs.length - 1];
+ if (last && span.start <= last.end) last.end = Math.max(last.end, span.end);
+ else runs.push({ ...span });
+ }
+ return runs;
+}
+
+/**
+ * Newlines of the caller's view before stored byte `at` (a line start in `timeline` or truth): the head, the rows'
+ * 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[],
+ 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'));
+ let lines = count(Buffer.from(input.head + (timeline ? TIMELINE_SEPARATOR : ''), 'utf8'));
+ for (const row of before) if (Number(row.byteStart) + row.byteLen <= at) lines += row.lineCount;
+ const containing = before.filter(row => Number(row.byteStart) + row.byteLen > at);
+ for 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);
+ }
+ return lines;
+}
+
+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 })));
+}
+
+export interface LocatedSegmentedEdits {
+ replacements: BodyReplacement[];
+ /** The receipt diff fields (editDiff over the touched range). */
+ diff: Record<string, unknown>;
+}
+
+/**
+ * edit_page's matching on a segmented page (spec 6.3), without materializing it: each old_text is found by a
+ * streaming scan of the stored body (the edits before it applied), across segment boundaries, in `within` when given
+ * (O(range)) or the whole body. The rules are applyPageEdits': exactly one match outside protected takes and facts
+ * text, all or none; a remote caller never matches into text its view hides (such a match counts as absent). Null
+ * declines to the whole-body path: an old_text that names the timeline sentinel or also occurs in the frontmatter
+ * 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> {
+ const { page, within } = input;
+ const rows = await engine.readManifest(page.id, { generation: page.generation });
+ spliceWork.rows += rows.length;
+ 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') }];
+ let reps: BodyReplacement[] = [];
+ for (const [index, edit] of input.edits.entries()) {
+ if (edit.old_text.includes('<!-- timeline -->') || (!within && input.head.includes(edit.old_text))) return null;
+ const needle = Buffer.from(edit.old_text, 'utf8');
+ const matches: Match[] = [];
+ for (const region of regions) {
+ const 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) continue;
+ matches.push(...await regionMatches(engine, input.sourceId, region.rows, reps, from, to, needle));
+ }
+ const touches = (m: Match) => guarded.some(g => m.start < g.end && g.start < m.end);
+ const visible = input.remote ? matches.filter(m => !touches(m)) : matches;
+ const allowed = visible.filter(m => !touches(m));
+ if (allowed.length === 0 && visible.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) {
+ if (!within && page.bodyBytes <= PAGE_MAX_BYTES) return null;
+ throw editError('edit_no_match', `Edit ${index}'s old_text was not found in the page${within ? ' range' : ''}.`,
+ `${within ? 'Read the range again (get_page body: \'window\' returns edit_target), or omit within to search the whole page. ' : ''}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${within ? '' : ', or pass within (edit_target from a get_page window read) to search one range'}.`,
+ `edit_index=${index} match_count=${allowed.length}`);
+ }
+ const m = allowed[0]!;
+ const absorbed = reps.filter(r => r.start >= m.start && r.end <= m.end);
+ reps = [...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) };
+}
+
+/** 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[],
+ 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.
+ 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;
+ }
+ 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 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);
+ 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 } }) };
+}
+
+/**
+ * The segmented branch of edit_page's preparation (spec 6.3): locate the edits by streaming the segments, then splice
+ * the touched range through the generation flip (persistence/page-append.ts prepareSegmentedSpliceMutation). Null
+ * declines to the whole-body path (locateSegmentedEdits, or a splice that does not apply).
+ */
+export async function prepareSegmentedEditMutation(engine: BrainEngine, row: WriteRequest, stored: PageSnapshot): Promise<PreparedMutation | null> {
+ assertEditRevision(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 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 });
+ return located && { replacements: located.replacements, outcome: located.diff };
+ } });
+}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index c96e4c5a94..3ab5ff545f 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -37,7 +37,7 @@ import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';
import { assertRestoreOrigin } from './detached-pages.ts';
import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
import { publishesDatabaseOnly } from './page-prepare.ts';
-import { materializedSnapshot } from './segmented-apply.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
import { liveSearchable } from './searchable.ts';
import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';
import { pipelined } from '../page-state/transactions.ts';
@@ -365,10 +365,17 @@ 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, parsePageEdits } = await import('./page-edit.ts');
+ const { applyPageEdits, assertEditRevision, 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);
- applyPageEdits((await materializedSnapshot(ctx.engine, snapshot))!.page, snapshot.tags, ctx.remote !== false, parsePageEdits(p.edits));
+ 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);
+ }
+ // 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)) {
+ throw new OperationError('page_not_found', `Page not found: ${slug}`, 'append_page adds to an existing page; create it with put_page.');
}
let binding = boundAtStart;
const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index cb2c2bccb0..06093a7103 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -75,7 +75,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';
+import { applyPageEdits, editDiff, parseEditWithin, parsePageEdits, prepareSegmentedEditMutation } from './page-edit.ts';
import { carryCoreMarking, prepareCoreGuard } from './core-guard.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
@@ -94,7 +94,7 @@ import { bindOrigin } from './origin-guard.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
-const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,
+export const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,
{ argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } });
/**
@@ -102,7 +102,7 @@ const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page
* suggestion stands alone: the cause and next step, then the request to
* inspect before anything is resubmitted.
*/
-function pageRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string, fix?: Action): OperationError {
+export function pageRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string, fix?: Action): OperationError {
return opError(code, message,
`${cause} Request ${row.request_id} in source ${row.source_id} was refused; inspect it before resubmitting, and use a new request_id for any corrected write.`,
{ fix: fix ?? (row.principal_kind === 'local_cli'
@@ -208,7 +208,7 @@ function importedFileType(parsed: ParsedMarkdown, page: Pick<Page, 'type' | 'fro
return parsed.type;
}
/** The withdrawal ledger readPageSnapshot overlaid the snapshot's body with, for a segmented body read under it. */
-function snapshotLedger(snapshot: PageSnapshot): BodyLedger {
+export function snapshotLedger(snapshot: PageSnapshot): BodyLedger {
return { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) };
}
/**
@@ -407,7 +407,7 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'sou
export function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>, file: PreparedMutation['file']): Pick<PreparedMutation, 'databaseOnlyReason'> {
return row.worktree_id && !file ? { databaseOnlyReason: 'db_only' } : {};
}
-async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {
+export async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {
const reason = databaseOnlyPublication(row, file);
if (reason.databaseOnlyReason && (await sourceMirrorReadOnly(engine, row.source_id) || await isMirrorOnlyPage(engine, row.source_id, row.slug))) {
return { databaseOnlyReason: 'mirror_read_only' };
@@ -666,6 +666,10 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
() => engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }),
() => loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null),
]) as [unknown, PageSnapshot | null, Awaited<ReturnType<typeof loadActivePackForEngine>> | null];
+ // Wave B (spec 6.3): edit_page on a segmented page splices the touched segments; a declined edit takes the string path.
+ const segmented = row.operation === 'edit_page' && stored && !stored.page.deleted_at && isSegmentedPage(stored.page) && stored.page.id === row.page_id
+ ? await prepareSegmentedEditMutation(engine, row, stored) : null;
+ if (segmented) return segmented;
// Wave B: a segmented page within the single-string ceiling is compared and merged as strings.
const snapshot = await materializedSnapshot(unbounded, stored);
signal?.throwIfAborted();
@@ -954,5 +958,5 @@ function editLockedPage(row: WriteRequest, snapshot: PageSnapshot | null) {
if (!snapshot || snapshot.page.deleted_at) throw pageRefusal('page_not_found', 'Page not found.', row,
`Page ${row.slug} does not exist in source ${row.source_id} or is deleted, so the edit changed nothing. If it is soft-deleted, restore it with restore_page; otherwise write it whole with put_page.`,
pageFix(row.source_id, row.slug));
- return applyPageEdits(snapshot.page, snapshot.tags, row.authority.remote, parsePageEdits(row.intent?.edits));
+ return applyPageEdits(snapshot.page, snapshot.tags, row.authority.remote, parsePageEdits(row.intent?.edits), parseEditWithin(row.intent?.within));
}
diff --git a/src/core/persistence/semantic.ts b/src/core/persistence/semantic.ts
index 892bff5f5c..946dc7023c 100644
--- a/src/core/persistence/semantic.ts
+++ b/src/core/persistence/semantic.ts
@@ -8,6 +8,8 @@ export const SEMANTIC_PAGE_OPERATIONS: ReadonlySet<string> = new Set([
* recomputable as the mid-preparation `revision_conflict`; a stale supplied revision is neither.
*/
export function mayReprepare(row: WriteRequest, error: { code?: string }): boolean {
+ // An append moved under by another write prepares again against the new tail; its own preconditions decide there.
+ if (row.operation === 'append_page') return error.code === 'revision_conflict';
return (error.code === 'revision_conflict' || error.code === 'revision_required') && row.intent?.expected_revision === undefined
&& (SEMANTIC_PAGE_OPERATIONS.has(row.operation) || row.intent?.force === true);
}
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 2f4ad55a24..bcbebed017 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -103,6 +103,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);
if (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].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 (row.operation === 'append_page') return (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock);
if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,
{ coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock });
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index bb520a4eff..cbfbea5f24 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -19,7 +19,7 @@ export const WRITE_ERROR_CODES = [
'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
'timeline_rows_would_be_removed', 'purged_content', 'preparation_stalled',
- 'fence_unrenderable', 'page_body_segmented',
+ 'fence_unrenderable', 'page_body_segmented', 'revision_changed', 'tail_changed',
'write_outcome_unknown', 'write_interrupted',
] as const;
diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.ts
index b3cff4e2b6..5edc28591d 100644
--- a/src/core/trust/channel.ts
+++ b/src/core/trust/channel.ts
@@ -31,7 +31,7 @@ import {
/** Journaled verbs an agent (remote or local) calls directly; their rows are agent_written unless lowered. */
export const AGENT_WRITE_OPERATIONS: readonly string[] = [
- 'put_page', 'put_pages', 'capture', 'edit_page', 'delete_page', 'restore_page', 'revert_version', 'remember',
+ 'put_page', 'put_pages', 'capture', 'edit_page', 'append_page', 'delete_page', 'restore_page', 'revert_version', 'remember',
'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',
'takes_remove', 'loops_close', 'relink_facts', 'decide_proposal',
];
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index c8c72b6660..4989e95d16 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -31,7 +31,7 @@ import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, minTrust, storedTr
const FENCE_EDIT_OPERATIONS = ['remember', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',
'decide_proposal', 'loops_close', 'relink_facts', 'add_timeline_entry'];
/** Page writes whose caller supplies the page content: they stamp the marker and can lower the page (CEO-12). */
-const CONTENT_OPERATIONS = ['put_page', 'capture', 'edit_page', 'revert_version', 'restore_page'];
+const CONTENT_OPERATIONS = ['put_page', 'capture', 'edit_page', 'append_page', 'revert_version', 'restore_page'];
export function isFenceEditWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): boolean {
return FENCE_EDIT_OPERATIONS.includes(row.operation) || row.intent?.kind === 'managed_facts_entity';
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 275c321be8..0f18ab0b8c 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 243872,
- "stdoutSha256": "6ee4209e4e99064f148052de48a83f11e600ff47fc3bb720a6a9394bb59e2737",
+ "stdoutBytes": 246776,
+ "stdoutSha256": "0b1b2aa71cd142ac0f304d17e9b8eed82b477b5237dff59c059899276b3c9c5a",
"toolNames": [
"remember",
"entity",
@@ -18,6 +18,7 @@
"capture",
"fetch",
"edit_page",
+ "append_page",
"put_pages",
"get_write_request",
"list_write_requests",
@@ -1017,7 +1018,8 @@
"expected_revision": "string",
"request_id": "string?",
"slug": "string",
- "source_id": "string?"
+ "source_id": "string?",
+ "within": "object?"
},
"required_scopes": [],
"schema": {
@@ -1059,6 +1061,25 @@
"source_id": {
"description": "Write source.",
"type": "string"
+ },
+ "within": {
+ "additionalProperties": false,
+ "description": "Match only in this stored-body range: edit_target's byte_start/byte_end from a get_page window read.",
+ "properties": {
+ "byte_end": {
+ "description": "End stored byte (exclusive).",
+ "type": "number"
+ },
+ "byte_start": {
+ "description": "First stored byte.",
+ "type": "number"
+ }
+ },
+ "required": [
+ "byte_start",
+ "byte_end"
+ ],
+ "type": "object"
}
},
"required": [
@@ -1070,6 +1091,76 @@
},
"scope": "write"
},
+ {
+ "description": "Add text to the end of a page, in time proportional to the text: use it for logs and conversations instead of re-putting a large page. request_id is required (a retry never appends twice). Optional expected_revision / expected_tail_sha256 (tail_sha256 from get_page body: 'none') refuse with revision_changed / tail_changed when the page moved.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
+ "name": "append_page",
+ "parameters": {
+ "expected_revision": "string?",
+ "expected_tail_sha256": "string?",
+ "region": "string?",
+ "request_id": "string",
+ "separator": "string?",
+ "slug": "string",
+ "source_id": "string?",
+ "text": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "expected_revision": {
+ "description": "Append only while the page is at this revision.",
+ "type": "string"
+ },
+ "expected_tail_sha256": {
+ "description": "Append only while the region's last 4096 bytes have this sha256 (get_page body: 'none' tail_sha256).",
+ "type": "string"
+ },
+ "region": {
+ "description": "auto (default): the last non-empty region.",
+ "enum": [
+ "auto",
+ "truth",
+ "timeline"
+ ],
+ "type": "string"
+ },
+ "request_id": {
+ "description": "A new UUID per append; reuse only to retry.",
+ "type": "string"
+ },
+ "separator": {
+ "description": "auto (default): one newline first when the tail lacks one.",
+ "enum": [
+ "auto",
+ "none"
+ ],
+ "type": "string"
+ },
+ "slug": {
+ "description": "Page slug (an existing page).",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Write source.",
+ "type": "string"
+ },
+ "text": {
+ "description": "Text to add, at most 4194304 bytes; a larger append uses begin_page_upload mode 'append'.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "slug",
+ "text",
+ "request_id"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
{
"description": "Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned `next`. Needs put_page permission.",
"idempotent": true,
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 64dcc560e8..465124f940 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6331,7 +6331,7 @@
"kind": "type",
"name": "ErrorCode",
"signature": [
- "\"rate_limited\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
+ "\"rate_limited\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
]
},
{
@@ -6421,7 +6421,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
@@ -6442,10 +6442,10 @@
"stack?: string | undefined",
"suggestion?: string | undefined",
"syncRefusal?: Record<string, unknown> | undefined",
- "toJSON: () => { contract_version?: 1 | undefined; withdrawn?: WithdrawnDetail | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined; request_id?: string | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
+ "toJSON: () => { contract_version?: 1 | undefined; withdrawn?: WithdrawnDetail | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined; request_id?: string | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
"why?: string | undefined",
"withdrawn?: WithdrawnDetail | undefined",
- "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined",
+ "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined",
"writeRequest?: WriteReceipt | undefined"
],
"name": "OperationError",
diff --git a/test/helpers/append-brain.ts b/test/helpers/append-brain.ts
new file mode 100644
index 0000000000..4744e01697
--- /dev/null
+++ b/test/helpers/append-brain.ts
@@ -0,0 +1,88 @@
+/**
+ * A database-only brain for the append_page / segmented edit_page tests (Wave B PR 3): PGLite, or an isolated
+ * Postgres database when kind is 'postgres'; `pages.segmented_storage` on; a fake embedder that records every text it
+ * is asked to embed; `call` runs one MCP tool call as the trusted local CLI, or as a remote writer bound to notes/.
+ */
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { isolatedPersistencePostgres } from './persistence-postgres.ts';
+import { withEnv } from './with-env.ts';
+
+export interface AppendBrain {
+ engine: BrainEngine;
+ /** The canonical checkout when opened with `repo` (write-through on), else null. */
+ root: string | null;
+ /** Every text the fake embedder was asked to embed, in order. */
+ embedded: string[];
+ /** A direct import (the seed path for pages too large to put in one call). */
+ seed(slug: string, content: string): Promise<void>;
+ call(name: string, params: Record<string, unknown>, opts?: { remote?: boolean }): Promise<{ isError: boolean; body: Record<string, any> }>;
+ /** The stored body (truth + timeline), however it is stored. */
+ body(slug: string): Promise<{ storage: string; truth: string; timeline: string }>;
+ close(): Promise<void>;
+}
+
+export async function openAppendBrain(kind: 'pglite' | 'postgres', opts: { repo?: boolean } = {}): Promise<AppendBrain> {
+ let engine: BrainEngine;
+ let closeEngine: () => Promise<void>;
+ if (kind === 'postgres') ({ engine, close: closeEngine } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema();
+ engine = lite; closeEngine = () => lite.disconnect();
+ }
+ const dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;
+ const embedded: string[] = [];
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };
+ }) as never);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-append-'));
+ const env = { GBRAIN_HOME: join(dir, 'home') };
+ const root = opts.repo ? join(dir, 'brain') : null;
+ if (root) {
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ await engine.setConfig('sync.repo_path', root);
+ await engine.setConfig('sync.write_through', 'true');
+ await withEnv(env, () => claimWorktree(engine, 'default', root));
+ }
+ const [cli, remote] = await withEnv(env, async () => [await registerLocalWriter(engine, 'cli'),
+ await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] })] as [LocalRegistration, LocalRegistration]);
+ const remoteAuth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] };
+ return {
+ engine, root, embedded,
+ seed: async (slug, content) => { await importFromContent(engine, slug, content, { noEmbed: true }); },
+ call: async (name, params, opts = {}) => withEnv(env, async () => {
+ const response = await withVerifiedLocalRegistration(engine, opts.remote ? remote : cli, () => dispatchToolCall(engine, name, params, {
+ remote: opts.remote === true, config: { engine: kind }, sourceId: 'default', ...(opts.remote ? { auth: remoteAuth } : {}),
+ logger: { info() {}, warn() {}, error() {} } }));
+ return { isError: response.isError === true, body: JSON.parse((response.content[0] as { text: string }).text) };
+ }),
+ body: async slug => {
+ const [row] = await engine.executeRaw<{ id: number; body_storage: string; compiled_truth: string | null; timeline: string | null }>(
+ "SELECT id, body_storage, compiled_truth, timeline FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ if (row!.body_storage !== 'segmented') return { storage: row!.body_storage, truth: row!.compiled_truth ?? '', timeline: row!.timeline ?? '' };
+ const stored = await materializeSegmentedBody(engine, Number(row!.id), 'default');
+ return { storage: 'segmented', truth: stored.compiled_truth, timeline: stored.timeline ?? '' };
+ },
+ close: async () => {
+ __setEmbedTransportForTests(null);
+ await disposePersistenceConsumer(engine);
+ await closeEngine();
+ resetGateway();
+ rmSync(dir, { recursive: true, force: true });
+ },
+ };
+}
diff --git a/test/large-pages/append-concurrency.test.ts b/test/large-pages/append-concurrency.test.ts
new file mode 100644
index 0000000000..f6bc509b57
--- /dev/null
+++ b/test/large-pages/append-concurrency.test.ts
@@ -0,0 +1,135 @@
+/**
+ * Wave B PR 3 (spec 6.1): append_page under concurrency, replay and preconditions.
+ *
+ * 1. Protects: two appends with distinct request_ids both land once each, whole and in order (one prepares again
+ * against the other's tail); a replay of a request_id appends nothing, and the same id with other text is an
+ * idempotency_conflict; a stale expected_tail_sha256 refuses with tail_changed and a fix naming the current tail,
+ * a stale expected_revision with revision_changed; an inline page appends in place, reports tail_sha256 on
+ * body:'none', and is promoted once the result crosses 1 MiB; a remote caller never sees or tests a tail that holds
+ * a facts fence; an append while an embed run is chunking converges to a sealed, fully embedded page; a file-backed
+ * page's canonical file gains exactly the appended bytes.
+ * 2. Fails when: an append is lost, duplicated or interleaved, a replay appends again, a precondition passes stale, a
+ * hidden tail leaks its digest to a remote caller, or the file and the database disagree.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';
+import { FACTS_BLOCK } from '../helpers/segment-bodies.ts';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { runEmbedCore } from '../../src/commands/embed.ts';
+
+const LOG = 'notes/append-log';
+const SMALL = 'notes/append-small';
+const GUARDED = 'notes/append-guarded';
+const FILED = 'notes/append-filed';
+const fm = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n`;
+
+for (const kind of testBackends()) {
+ describe(`append_page concurrency and preconditions (${kind})`, () => {
+ let brain: AppendBrain;
+ const append = (slug: string, text: string, extra: Record<string, unknown> = {}, remote = false) =>
+ brain.call('append_page', { slug, text, request_id: randomUUID(), ...extra }, { remote });
+ const none = async (slug: string, remote = false) => (await brain.call('get_page', { slug, body: 'none' }, { remote })).body;
+
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ await brain.seed(LOG, conversationPage(1_500_000, { seed: 11 }));
+ expect((await brain.body(LOG)).storage).toBe('segmented');
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('two appenders land once each, whole and in order; a replay appends nothing', async () => {
+ const before = (await brain.body(LOG)).truth;
+ expect(await append(LOG, 'first sequential turn')).toMatchObject({ isError: false });
+ expect(await append(LOG, 'second sequential turn')).toMatchObject({ isError: false });
+ expect((await brain.body(LOG)).truth === before + '\nfirst sequential turn\nsecond sequential turn').toBe(true);
+
+ const both = await Promise.all([append(LOG, 'racing turn alpha'), append(LOG, 'racing turn bravo')]);
+ expect(both.map(r => r.isError)).toEqual([false, false]);
+ const raced = (await brain.body(LOG)).truth;
+ const tail = raced.slice(raced.length - '\nracing turn alpha\nracing turn bravo'.length);
+ expect(['\nracing turn alpha\nracing turn bravo', '\nracing turn bravo\nracing turn alpha']).toContain(tail);
+ expect(raced.length).toBe(before.length + '\nfirst sequential turn\nsecond sequential turn\nracing turn alpha\nracing turn bravo'.length);
+
+ const request_id = randomUUID();
+ const once = await brain.call('append_page', { slug: LOG, text: 'replayed turn', request_id });
+ const again = await brain.call('append_page', { slug: LOG, text: 'replayed turn', request_id });
+ expect(again.body.revision).toBe(once.body.revision);
+ expect((await brain.body(LOG)).truth.split('replayed turn').length).toBe(2);
+ expect((await brain.call('append_page', { slug: LOG, text: 'other text', request_id })).body.error).toBe('idempotency_conflict');
+ }, 600_000);
+
+ test('stale preconditions refuse with tail_changed and revision_changed', async () => {
+ const read = await none(LOG);
+ expect(read.size.tail_sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(await append(LOG, 'moves the tail')).toMatchObject({ isError: false });
+ const stale = await append(LOG, 'never lands', { expected_tail_sha256: read.size.tail_sha256 });
+ expect(stale.body.error).toBe('tail_changed');
+ const current = (await none(LOG)).size.tail_sha256;
+ expect(stale.body.fix.then.mcp.arguments.expected_tail_sha256).toBe(current);
+ expect(JSON.parse(stale.body.detail).current_tail_sha256).toBe(current);
+ const moved = await append(LOG, 'never lands either', { expected_revision: read.revision });
+ expect(moved.body.error).toBe('revision_changed');
+ expect((await brain.body(LOG)).truth.includes('never lands')).toBe(false);
+ expect(await append(LOG, 'lands on the current tail', { expected_tail_sha256: current, expected_revision: (await none(LOG)).revision })).toMatchObject({ isError: false });
+ expect((await append(LOG, 'bad <!--- gbrain:facts:begin --> marker')).body.error).toBe('invalid_params');
+ }, 600_000);
+
+ test('an inline page appends in place and is promoted past 1 MiB; a guarded tail stays hidden from remote callers', async () => {
+ expect(await brain.call('put_page', { slug: SMALL, content: fm('Small') + 'Opening line.\n', request_id: randomUUID() })).toMatchObject({ isError: false });
+ const tail = (await none(SMALL)).size.tail_sha256;
+ expect(tail).toMatch(/^[0-9a-f]{64}$/);
+ expect(await append(SMALL, 'Second line.', { expected_tail_sha256: tail })).toMatchObject({ isError: false });
+ expect(await brain.body(SMALL)).toMatchObject({ storage: 'inline', truth: 'Opening line.\nSecond line.' });
+ const big = await append(SMALL, conversationBody(1_100_000, { seed: 12 }));
+ expect(big).toMatchObject({ isError: false });
+ expect((await brain.body(SMALL)).storage).toBe('segmented');
+
+ expect(await brain.call('put_page', { slug: GUARDED, content: fm('Guarded') + 'Intro.\n\n' + FACTS_BLOCK, request_id: randomUUID() })).toMatchObject({ isError: false });
+ expect((await none(GUARDED)).size.tail_sha256).toMatch(/^[0-9a-f]{64}$/);
+ const hidden = await none(GUARDED, true);
+ expect(hidden.size.tail_sha256).toBeUndefined();
+ const guess = await append(GUARDED, 'remote text', { expected_tail_sha256: (await none(GUARDED)).size.tail_sha256 }, true);
+ expect(guess.body.error).toBe('tail_changed');
+ expect(JSON.parse(guess.body.detail).current_tail_sha256).toBeNull();
+ expect(await append(GUARDED, 'remote text', {}, true)).toMatchObject({ isError: false });
+ }, 600_000);
+
+ test('an append while an embed run is chunking converges', async () => {
+ const page = (await brain.engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [LOG]))[0]!;
+ const text = conversationBody(20_000, { seed: 13 });
+ const [, appended] = await Promise.all([runEmbedCore(brain.engine, { stale: true, quiet: true } as never), append(LOG, text)]);
+ expect(appended).toMatchObject({ isError: false });
+ expect((await brain.body(LOG)).truth.endsWith('\n' + text)).toBe(true);
+ await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);
+ const [state] = await brain.engine.executeRaw<{ unembedded: number; sealed: boolean }>(`SELECT
+ (SELECT count(*)::int FROM content_chunks WHERE page_id=$1 AND embedded_at IS NULL) AS unembedded,
+ (SELECT text_projection_revision = knowledge_revision FROM pages WHERE id=$1) AS sealed`, [page.id]);
+ expect(state).toEqual({ unembedded: 0, sealed: true });
+ }, 600_000);
+ });
+
+ describe(`append_page on a file-backed page (${kind})`, () => {
+ let brain: AppendBrain;
+ beforeAll(async () => { brain = await openAppendBrain(kind, { repo: true }); }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test("the canonical file gains exactly the appended bytes", async () => {
+ expect(await brain.call('put_page', { slug: FILED, content: conversationPage(1_200_000, { seed: 14 }), request_id: randomUUID() })).toMatchObject({ isError: false });
+ expect((await brain.body(FILED)).storage).toBe('segmented');
+ const file = join(brain.root!, FILED + '.md');
+ const before = readFileSync(file, 'utf8');
+ const res = await brain.call('append_page', { slug: FILED, text: 'a turn appended to the file', request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false, body: { receipt: { write_through: { written: true } } } });
+ const after = readFileSync(file, 'utf8');
+ // A segmented flip renders the head from the stored frontmatter (as a segmented tag write does): same keys, stored order.
+ const split = (text: string) => { const at = text.indexOf('\n---\n\n'); return { head: text.slice(0, at).split('\n').sort(), body: text.slice(at + 6) }; };
+ expect(split(after).head).toEqual(split(before).head);
+ expect(split(after).body === split(before).body.slice(0, -1) + '\na turn appended to the file\n').toBe(true);
+ }, 600_000);
+ });
+}
diff --git a/test/large-pages/append-cost.test.ts b/test/large-pages/append-cost.test.ts
new file mode 100644
index 0000000000..7c36f3baad
--- /dev/null
+++ b/test/large-pages/append-cost.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Wave B PR 3 (spec 6.1): append_page on a segmented page costs the text added plus one tail segment.
+ *
+ * 1. Protects: a 10 KB append to a 4 MB and to a 16 MB segmented page segments exactly the old tail segment plus the
+ * text, reads only that segment (page-body/splice.ts spliceWork), loads the same manifest rows at either size, writes manifest rows for the tail and
+ * the new segments only, gives the body, content_hash and segment cuts a fresh import of the whole result gives,
+ * and the embedder sees only new chunk text after it.
+ * 2. Fails when: an append restages or rescans the whole body (the forced probe sets appendProbe.fullRewrite and shows
+ * the same bound failing), resumes the content hash or the segmenter from the wrong state, or re-embeds chunks whose
+ * text it did not change.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Work is counted, never timed.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { spliceWork } from '../../src/core/page-body/splice.ts';
+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { appendProbe } from '../../src/core/persistence/page-append.ts';
+import { runEmbedCore } from '../../src/commands/embed.ts';
+
+const SMALL = 'notes/append-cost-small';
+const BIG = 'notes/append-cost-big';
+const TWIN = 'notes/append-cost-twin';
+/** About 10 KB of conversation turns, without a trailing newline (a fresh import trims one). */
+const TEXT = conversationBody(10_000, { seed: 99 });
+const BOUND = SEGMENT_MAX_BYTES + Buffer.byteLength(TEXT) + 1;
+
+for (const kind of testBackends()) {
+ describe(`append_page cost (${kind})`, () => {
+ let brain: AppendBrain;
+ const pageRow = async (slug: string) => (await brain.engine.executeRaw<{ id: number; body_generation: string; content_hash: string }>(
+ "SELECT id, body_generation::text AS body_generation, content_hash FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!;
+ const cuts = async (slug: string) => {
+ const page = await pageRow(slug);
+ return (await brain.engine.readManifest(Number(page.id))).map(r => [r.region, Number(r.byteStart), r.byteLen, Buffer.from(r.sha256).toString('hex')]);
+ };
+ /** One append with its work counters and the manifest rows it wrote. */
+ const measured = async (slug: string) => {
+ const before = await pageRow(slug);
+ const tail = (await brain.engine.readManifest(Number(before.id), { lastN: 1 }))[0]!.byteLen;
+ Object.assign(spliceWork, { segmented: 0, read: 0, rows: 0 });
+ const res = await brain.call('append_page', { slug, text: TEXT, request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false });
+ const work = { ...spliceWork };
+ const [written] = await brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from=$2',
+ [before.id, Number(before.body_generation) + 1]);
+ return { res: res.body, work, tail, written: Number(written!.n) };
+ };
+
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ await brain.seed(SMALL, conversationPage(4_000_000, { seed: 1 }));
+ await brain.seed(BIG, conversationPage(16_000_000, { seed: 2 }));
+ expect((await brain.body(SMALL)).storage).toBe('segmented');
+ expect((await brain.body(BIG)).storage).toBe('segmented');
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('a 10 KB append does the same bounded work at 4 MB and 16 MB, and equals a fresh import of the result', async () => {
+ const original = await brain.body(SMALL);
+ const small = await measured(SMALL);
+ const big = await measured(BIG);
+ // Exactly the old tail segment and the text, at either size: nothing before the tail is segmented or read.
+ for (const { work, tail } of [small, big]) {
+ expect(work.segmented).toBe(tail + Buffer.byteLength(TEXT) + 1);
+ expect(work.read).toBe(tail);
+ expect(work.segmented).toBeLessThanOrEqual(BOUND);
+ expect(work.rows).toBeLessThanOrEqual(16);
+ }
+ expect(big.work.rows).toBe(small.work.rows);
+ expect(big.written).toBeLessThanOrEqual(small.written + 1);
+ expect(small.written).toBeLessThanOrEqual(3);
+ expect(small.res).toMatchObject({ slug: SMALL, appended_bytes: Buffer.byteLength(TEXT) + 1, body_bytes: Buffer.byteLength(original.truth) + Buffer.byteLength(TEXT) + 1 });
+ expect(small.res.rescanned).toBeUndefined();
+
+ const after = await brain.body(SMALL);
+ expect(after.truth === original.truth + '\n' + TEXT).toBe(true);
+ await brain.seed(TWIN, `---\ntitle: Conversation log\ntype: note\ntrust_tier: agent_written\n---\n\n${after.truth}\n`);
+ expect((await pageRow(SMALL)).content_hash).toBe((await pageRow(TWIN)).content_hash);
+ expect(await cuts(SMALL)).toEqual(await cuts(TWIN));
+ }, 600_000);
+
+ test('the embedder sees only chunk text the append changed', async () => {
+ await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);
+ const page = await pageRow(BIG);
+ const old = new Set((await brain.engine.executeRaw<{ chunk_text: string }>('SELECT chunk_text FROM content_chunks WHERE page_id=$1', [page.id])).map(r => r.chunk_text));
+ expect(old.size).toBeGreaterThan(100);
+ brain.embedded.length = 0;
+ await measured(BIG);
+ await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);
+ expect(brain.embedded.length).toBeGreaterThan(0);
+ expect(brain.embedded.length).toBeLessThanOrEqual(8);
+ expect(brain.embedded.filter(text => old.has(text))).toEqual([]);
+ expect(brain.embedded.some(text => text.includes(TEXT.slice(-40)))).toBe(true);
+ }, 600_000);
+
+ test('forced probe: an append that restages the whole body fails the bound', async () => {
+ const before = await brain.body(SMALL);
+ appendProbe.fullRewrite = true;
+ let probe;
+ try { probe = await measured(SMALL); } finally { appendProbe.fullRewrite = false; }
+ expect(probe.res.rescanned).toBe(true);
+ expect(probe.work.segmented).toBeGreaterThan(BOUND);
+ expect(probe.work.segmented).not.toBe(probe.tail + Buffer.byteLength(TEXT) + 1);
+ expect((await brain.body(SMALL)).truth === before.truth + '\n' + TEXT).toBe(true);
+ }, 600_000);
+ });
+}
diff --git a/test/large-pages/edit-segmented.test.ts b/test/large-pages/edit-segmented.test.ts
new file mode 100644
index 0000000000..553f4ee8d6
--- /dev/null
+++ b/test/large-pages/edit-segmented.test.ts
@@ -0,0 +1,163 @@
+/**
+ * Wave B PR 3 (spec 6.3): edit_page on a segmented page, and `within` from a window read's `edit_target`.
+ *
+ * 1. Protects: a window read returns edit_target (stored coordinates, the page revision); edit_page with `within` set
+ * to it picks one of two identical lines and reads only that range's segments plus the suffix the content hash
+ * streams; an old_text that spans a segment cut matches; the result equals a fresh import of the edited body
+ * (body, content_hash, segment cuts). A range read before the page moved is stale (revision_conflict), and a range
+ * that misses the text matches nothing. Fences stay protected: a trusted edit into a facts fence is
+ * edit_protected_span, a remote one finds nothing, and a remote window read past hidden text gets no edit_target.
+ * `within` works on an inline page too. A remote edit's diff context never starts inside hidden text, and its hunk
+ * lines count the remote view (hidden runs rendered as get_page renders them).
+ * 2. Fails when: `within` is ignored or mis-mapped, a match across a cut is missed, the splice publishes a body or hash
+ * a fresh import would not give, or stored offsets leak hidden text lengths to a remote reader.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { FACTS_BLOCK } from '../helpers/segment-bodies.ts';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { spliceWork } from '../../src/core/page-body/splice.ts';
+import { sanitizeRemoteBody } from '../../src/core/remote-body.ts';
+
+const DUP = '**alice-example**: the duplicate status line.';
+const PAGE = 'notes/edit-segmented';
+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 fm = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n`;
+
+for (const kind of testBackends()) {
+ describe(`segmented edit_page (${kind})`, () => {
+ let brain: AppendBrain;
+ const row = async (slug: string) => (await brain.engine.executeRaw<{ id: number; content_hash: string; body_bytes: string }>(
+ "SELECT id, content_hash, body_bytes::text AS body_bytes FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!;
+ const cuts = async (slug: string) => (await brain.engine.readManifest(Number((await row(slug)).id))).map(r => [r.region, Number(r.byteStart), r.byteLen]);
+ const revision = async (slug: string, remote = false) => (await brain.call('get_page', { slug, body: 'none' }, { remote })).body.revision as string;
+ const edit = (slug: string, rev: string, old_text: string, new_text: string, within?: unknown, remote = false) =>
+ brain.call('edit_page', { slug, expected_revision: rev, edits: [{ old_text, new_text }], request_id: randomUUID(), ...(within ? { within } : {}) }, { remote });
+ /** The edited page equals a fresh import of its own body (the CLI writer stamps agent_written, as the twin carries). */
+ const matchesFreshImport = async (slug: string, twin: string) => {
+ const body = await brain.body(slug);
+ await brain.seed(twin, '---\ntitle: Edit\ntype: note\ntrust_tier: agent_written\n---\n\n' + body.truth + '\n');
+ expect((await row(slug)).content_hash).toBe((await row(twin)).content_hash);
+ expect(await cuts(slug)).toEqual(await cuts(twin));
+ };
+
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ const body = [conversationBody(1_000_000, { seed: 5 }), DUP, conversationBody(1_000_000, { seed: 6 }), DUP, conversationBody(100_000, { seed: 7 })].join('\n\n');
+ await brain.seed(PAGE, fm('Edit') + body + '\n');
+ await brain.seed(FENCED, fm('Fenced') + 'Intro.\n\n' + FACTS_BLOCK + '\n' + conversationBody(1_200_000, { seed: 8 }) + '\n');
+ expect((await brain.body(PAGE)).storage).toBe('segmented');
+ expect((await brain.body(FENCED)).storage).toBe('segmented');
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('within from a window read picks one of two identical lines, reading only that range', async () => {
+ const before = (await brain.body(PAGE)).truth;
+ const rev = await revision(PAGE);
+ expect((await edit(PAGE, rev, DUP, 'x')).body.error).toBe('edit_ambiguous_match');
+ const second = Buffer.from(before).lastIndexOf(Buffer.from(DUP));
+ const win = (await brain.call('get_page', { slug: PAGE, body: 'window', bytes: { offset: second - 50, length: 300 } })).body;
+ expect(win.window.text).toContain(DUP);
+ expect(win.edit_target).toMatchObject({ revision: rev });
+ expect(win.edit_target.byte_start).toBeLessThanOrEqual(second);
+ expect(win.edit_target.byte_end).toBeGreaterThanOrEqual(second + DUP.length);
+ const rows = await brain.engine.readManifest(Number((await row(PAGE)).id));
+ const touched = rows.filter(r => Number(r.byteStart) <= second).at(-1)!;
+ Object.assign(spliceWork, { segmented: 0, read: 0, rows: 0 });
+ const res = await edit(PAGE, rev, DUP, '**alice-example**: the edited status line.', { byte_start: win.edit_target.byte_start, byte_end: win.edit_target.byte_end });
+ expect(res).toMatchObject({ isError: false, body: { status: 'created_or_updated' } });
+ expect(res.body.diff).toContain('+**alice-example**: the edited status line.');
+ // The range's segment (located, spliced, diffed) and the suffix the content hash streams; nothing before the range.
+ const suffix = Buffer.byteLength(before) - Number(touched.byteStart);
+ expect(spliceWork.read).toBeLessThanOrEqual(2 * suffix + 2 * touched.byteLen);
+ expect(spliceWork.read).toBeLessThan(Number(touched.byteStart));
+ const after = (await brain.body(PAGE)).truth;
+ expect(after === before.slice(0, second) + '**alice-example**: the edited status line.' + before.slice(second + DUP.length)).toBe(true);
+ await matchesFreshImport(PAGE, 'notes/edit-twin-1');
+ }, 600_000);
+
+ test('an old_text across a segment cut matches; a stale or missing range refuses', async () => {
+ const before = (await brain.body(PAGE)).truth;
+ const rows = await brain.engine.readManifest(Number((await row(PAGE)).id));
+ const cut = Number(rows[3]!.byteStart);
+ const old = before.slice(cut - 30, cut + 30);
+ expect(before.indexOf(old)).toBe(before.lastIndexOf(old));
+ const rev = await revision(PAGE);
+ const win = (await brain.call('get_page', { slug: PAGE, body: 'window', bytes: { offset: 10, length: 200 } })).body;
+ expect((await edit(PAGE, rev, old, 'x', { byte_start: win.edit_target.byte_start, byte_end: win.edit_target.byte_end })).body.error).toBe('edit_no_match');
+ const res = await edit(PAGE, rev, old, 'SPANNED');
+ expect(res).toMatchObject({ isError: false });
+ expect((await brain.body(PAGE)).truth === before.slice(0, cut - 30) + 'SPANNED' + before.slice(cut + 30)).toBe(true);
+ await matchesFreshImport(PAGE, 'notes/edit-twin-2');
+ // The range was read at rev; the page has moved since, so it is stale.
+ expect((await edit(PAGE, rev, 'SPANNED', 'y', { byte_start: 0, byte_end: Number((await row(PAGE)).body_bytes) })).body.error).toBe('revision_conflict');
+ }, 600_000);
+
+ test('fences stay protected, and a remote reader past hidden text gets no edit_target', async () => {
+ const body = (await brain.body(FENCED)).truth;
+ const rev = await revision(FENCED);
+ expect((await edit(FENCED, rev, 'private thing', 'x')).body.error).toBe('edit_protected_span');
+ expect((await edit(FENCED, await revision(FENCED, true), 'private thing', 'x', undefined, true)).body.error).toBe('edit_no_match');
+ const offset = Buffer.byteLength(body) - 5000;
+ const trusted = (await brain.call('get_page', { slug: FENCED, body: 'window', bytes: { offset, length: 200 } })).body;
+ expect(trusted.edit_target).toMatchObject({ revision: rev });
+ const remote = (await brain.call('get_page', { slug: FENCED, body: 'window', bytes: { offset: 0, length: 200 } }, { remote: true })).body;
+ expect(remote.window.text.length).toBeGreaterThan(0);
+ const later = (await brain.call('get_page', { slug: FENCED, body: 'window', bytes: { offset: 100_000, length: 200 } }, { remote: true })).body;
+ expect(later.window.text.length).toBeGreaterThan(0);
+ expect(later.edit_target).toBeUndefined();
+ expect((await brain.call('get_page', { slug: FENCED, body: 'none' }, { remote: true })).body.size.tail_sha256).toBeDefined();
+ }, 600_000);
+
+ test('a remote edit after hidden text: the diff never shows it, and its line numbers are the remote view\'s', async () => {
+ // A takes fence longer than the 2 KB of diff context, right before the edited line: the context starts inside it.
+ const takes = '<!--- gbrain:takes:begin -->\n' + Array.from({ length: 150 }, (_, i) => `A private take line ${i}.\n`).join('') + '<!--- gbrain:takes:end -->\n';
+ const tail = conversationBody(1_200_000, { seed: 9 });
+ const body = 'Intro.\n\n' + FACTS_BLOCK + '\n' + takes + '\n' + tail;
+ for (const slug of [HIDDEN_A, HIDDEN_B]) await brain.seed(slug, fm('Hidden') + body + '\n');
+ const at = body.length - tail.length;
+ const old = body.slice(at, at + 60);
+ expect(body.indexOf(old)).toBe(body.lastIndexOf(old));
+ /** The new-side line number of the added line holding `marker`. */
+ const addedLine = (diff: string, marker: string) => {
+ let line = 0;
+ for (const l of diff.split('\n')) {
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(l);
+ if (hunk) { line = Number(hunk[1]); continue; }
+ if (l.startsWith('+') && !l.startsWith('+++') && l.includes(marker)) return line;
+ if (l.startsWith(' ') || (l.startsWith('+') && !l.startsWith('+++'))) line++;
+ }
+ return -1;
+ };
+ const trusted = await edit(HIDDEN_A, await revision(HIDDEN_A), old, 'TRUSTED-EDIT');
+ const remote = await edit(HIDDEN_B, await revision(HIDDEN_B, true), old, 'REMOTE-EDIT', undefined, true);
+ expect(trusted).toMatchObject({ isError: false });
+ expect(remote).toMatchObject({ isError: false });
+ for (const hidden of ['private thing', 'private take', 'gbrain:facts', 'gbrain:takes']) expect(remote.body.diff).not.toContain(hidden);
+ const newlines = (text: string) => text.split('\n').length - 1;
+ const view = (text: string) => sanitizeRemoteBody(text, { includeWithdrawn: true, keepMaterializedMarkers: true });
+ const prefix = body.slice(0, at);
+ expect(addedLine(trusted.body.diff, 'TRUSTED-EDIT')).toBeGreaterThan(newlines(prefix));
+ expect(addedLine(trusted.body.diff, 'TRUSTED-EDIT') - addedLine(remote.body.diff, 'REMOTE-EDIT')).toBe(newlines(prefix) - newlines(view(prefix)));
+ expect(newlines(prefix) - newlines(view(prefix))).toBeGreaterThan(0);
+ }, 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 });
+ const truth = (await brain.body(INLINE)).truth;
+ const second = Buffer.from(truth).lastIndexOf(Buffer.from(DUP));
+ const win = (await brain.call('get_page', { slug: INLINE, body: 'window', bytes: { offset: second, length: DUP.length } }, { remote: true })).body;
+ expect(win.edit_target).toMatchObject({ byte_start: second, byte_end: second + DUP.length });
+ const res = await edit(INLINE, win.edit_target.revision, DUP, 'Second status.', { byte_start: win.edit_target.byte_start, byte_end: win.edit_target.byte_end }, true);
+ expect(res).toMatchObject({ isError: false });
+ expect((await brain.body(INLINE)).truth).toBe(truth.slice(0, second) + 'Second status.' + truth.slice(second + DUP.length));
+ }, 120_000);
+ });
+}
diff --git a/test/large-pages/segmented-get-page-parity.test.ts b/test/large-pages/segmented-get-page-parity.test.ts
index 1185b06fae..6196a24477 100644
--- a/test/large-pages/segmented-get-page-parity.test.ts
+++ b/test/large-pages/segmented-get-page-parity.test.ts
@@ -49,6 +49,7 @@ function comparable(r: Record<string, any>): Record<string, any> {
delete out.revision;
delete out.body_storage;
delete out.chunks;
+ if (out.edit_target) delete out.edit_target.revision;
if (out.size) for (const k of ['body_bytes', 'body_lines', 'tail_sha256', 'tail_region']) delete out.size[k];
if (out.next_cursor) {
const c = decodeCursor(out.next_cursor)!;
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index 5b40945850..d36c72d386 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -46,6 +46,7 @@ const LEDGER: Record<string, string> = {
unpurge_page: 'test/page-purge.test.ts',
capture: 'test/capture-op.test.ts',
edit_page: 'test/edit-page.test.ts',
+ append_page: 'test/large-pages/append-concurrency.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',
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 2820763030..fb68f73975 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -86,11 +86,14 @@ test/import-revision-concurrency.test.ts
test/keyword-statement-timeout-knob-6495.test.ts
test/keyword-timeout-negative-cache-6495.test.ts
test/lane-apply-pipelining.test.ts
+test/large-pages/append-concurrency.test.ts
+test/large-pages/append-cost.test.ts
test/large-pages/chunk-retirement-plan.test.ts
test/large-pages/chunk-visibility.test.ts
test/large-pages/contextual-reembed-segmented.test.ts
test/large-pages/credential-reseal-segments.test.ts
test/large-pages/doctor-skipped-segmented.test.ts
+test/large-pages/edit-segmented.test.ts
test/large-pages/forget-reason-segmented.test.ts
test/large-pages/forget-scope.test.ts
test/large-pages/gbra117-segmented-classes-window.test.ts
diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.ts
index 4191ed23c3..62a7894c4c 100644
--- a/test/remote-privacy-sweep.test.ts
+++ b/test/remote-privacy-sweep.test.ts
@@ -195,6 +195,8 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {
put_pages: { request_id: '6007a5e0-0000-4000-8000-000000000001', pages: [{ slug: 'notes/sweep-fresh-batch', content: '# Fresh batch\n\nNew content.\n' }] },
// A stale revision on the fence-bearing page: the refusal must not echo it.
edit_page: { slug: WORLD_FENCE_SLUG, expected_revision: '00000000-0000-4000-8000-000000000000', edits: [{ old_text: 'x', new_text: 'y' }] },
+ // A stale revision on the fence-bearing page: the refusal must not echo it or its tail.
+ append_page: { slug: WORLD_FENCE_SLUG, request_id: '6007a5e0-0000-4000-8000-000000000002', expected_revision: '00000000-0000-4000-8000-000000000000', text: 'fresh sweep append' },
remember: { fact: 'fresh sweep fact', provenance: 'sweep', entity: 'people/sweep-fresh-entity' },
capture: { content: 'fresh sweep capture' },
add_tag: { slug: WORLD_PAGE_SLUG, tag: 'sweep-tag' },
@@ -212,7 +214,7 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {
// carries ctx.auth; the scalar shape — like the stdio transport — doesn't).
// These operations enforce durable write authority inside the shared dispatcher.
// Other scope checks remain transport-owned and outside this privacy harness.
-const COORDINATED_WRITES = new Set(['put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page',
+const COORDINATED_WRITES = new Set(['put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'append_page',
'remember', 'forget', 'add_tag', 'remove_tag', 'add_timeline_entry',
'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',
'get_write_request', 'list_write_requests', 'cancel_write_request']);
@@ -361,6 +363,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {
cancel_write_request: 'error',
revert_version: 'error',
edit_page: 'error',
+ append_page: 'error',
put_raw_data: 'error',
log_ingest: 'error',
takes_add: 'ok',