Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(uploads): refuse streamed replace over hidden facts rows, bind commit to its own request, lapsed sessions off the brain cap, part limit

garrytan2ab3cfce9490
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 8e72299fea..d75cb5dca9 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -23,9 +23,9 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`: the `since` of the BEHAVIOR_CHANGES row with id `segmented_switch_on`, this build's VERSION while it is `TBD`, so the merge-slot stamp edits only that row) or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the larger of the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) and the largest page stored in segments (deleted pages included; one probe of `pages_segmented_body_bytes_idx`, v260, or the engine ceiling while that index is not valid, so a limit read never scans `pages`) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate, and turning the switch off or lowering `pages.max_bytes` never strands a stored page. `readPageBodyPolicy` treats a failed read of the switch or `pages.max_bytes` as off, never as unset. Doctor `segmented_storage` reports a hold left only by this host's pre-upgrade writes as information with its clear time when, for each, this build has since made the same kind of write (role and principal, `segmentedGateEvidence` `first_seen`) after it; otherwise (a cron or npx gbrain on the host) it warns. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`, `test/large-pages/recovery-budget-ceiling.slow.test.ts`.
-- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does, runs put_page's grant and visibility authorization before reading the page (a private page answers as a missing one), and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id; abort needs only the creating principal, its source and the slug fences, so a session whose page or incarnation moved can still be freed. A refusal at commit (stale revision, sha mismatch) and a commit whose write ended without committing discard the session. Commit claims the session with an atomic open-to-sealed `sealUpload` before hashing; a call that loses the claim, or finds a lapsed session another call already moved on (`settleLapse`), reads the session again and follows its real state (sealed or committing replays the commit, committed returns the first receipt), so `upload_expired` is answered only when this call expired it (`uploadCommitProbe` is the forced-race seam, `test/large-pages/upload-review.test.ts`). After the hash check commit submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.
-- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`, which deletes the parts in the same statement; the segment sweep expires lapsed sessions the same way). An open session expires past its idle or hard deadline, a sealed one only past its hard deadline, which sealing extends by one idle period; `expireIfLapsed` reports whether its update changed the row. `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.
-- `src/core/persistence/upload-streamed.ts` — a committed upload over PAGE_MAX_BYTES: the sealed parts are spooled one part at a time into a private temporary file that the segmented streamed import (page-body/streamed-import.ts) reads, verifying the admitted sha256; the spool is removed before publication. A remote replace of a page holding a takes fence or timeline rows (without `drop_timeline`) refuses `upload_protected_content`, since put_page's whole-body takes and timeline checks cannot run streamed. A remote writer gets put_page's gate and page tier (`content.writer`), so where the write gate applies the commit refuses `file_too_large`; a trusted local writer takes the source owner's tier, as a streamed local `put --file` does. A worktree-bound page publishes database-only (`db_only`).
+- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does, runs put_page's grant and visibility authorization before reading the page (a private page answers as a missing one), and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id; abort needs only the creating principal, its source and the slug fences, so a session whose page or incarnation moved can still be freed. A refusal at commit (stale revision, sha mismatch) and a commit whose write ended without committing discard the session; only a write whose `body_ref` names the session is recorded as its commit, so a begin request_id another write already used attaches nothing. Commit claims the session with an atomic open-to-sealed `sealUpload` before hashing; a call that loses the claim, or finds a lapsed session another call already moved on (`settleLapse`), reads the session again and follows its real state (sealed or committing replays the commit, committed returns the first receipt), so `upload_expired` is answered only when this call expired it (`uploadCommitProbe` is the forced-race seam, `test/large-pages/upload-review.test.ts`). After the hash check commit submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.
+- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`, which deletes the parts in the same statement; the segment sweep expires lapsed sessions the same way). An open session expires past its idle or hard deadline, a sealed one only past its hard deadline, which sealing extends by one idle period; a lapsed session is never sealed, so the brain-wide sum at begin leaves out other principals' lapsed sessions; `expireIfLapsed` reports whether its update changed the row. A session takes at most `uploadPartLimit` parts (64 plus one per 64 KiB declared) unless the part completes it (`upload_too_many_parts`). `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.
+- `src/core/persistence/upload-streamed.ts` — a committed upload over PAGE_MAX_BYTES: the sealed parts are spooled one part at a time into a private temporary file that the segmented streamed import (page-body/streamed-import.ts) reads, verifying the admitted sha256; the spool is removed before publication. A remote replace of a page holding a takes fence, a facts fence with a non-world row (or one that does not parse; `segmentedFactsFenceView` reads only the fence runs of a segmented page), or timeline rows (without `drop_timeline`) refuses `upload_protected_content`, since put_page's whole-body takes, hidden-facts and timeline checks cannot run streamed. A remote writer gets put_page's gate and page tier (`content.writer`), so where the write gate applies the commit refuses `file_too_large`; a trusted local writer takes the source owner's tier, as a streamed local `put --file` does. A worktree-bound page publishes database-only (`db_only`).
- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads; a trusted read (`trustedSegments`) joins the segments it spans, and a segment ending inside a facts marker with the next, and overlays them whole, refusing `page_body_segmented` above `FENCE_MAX_BYTES` (limits.ts: counted from the begin marker through the end marker, the bound withdrawal discovery's `readStoredFence`, the purge rewrite and the file's overlaid digest share), or `page_projection_stale` when the read starts inside the block) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).
- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` (read-range.ts) with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index eaf73e0fa4..96503daff6 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4249,9 +4249,19 @@ More: [docs/guides/write-refusals.md#unsupported_path](../../docs/guides/write-r
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence remote reads hide, or timeline rows. | put_page keeps a hidden takes fence and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them. | Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended. | agent | `repeat the read that failed` | 1 | no |
+| A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence or facts rows remote reads hide, or timeline rows. | put_page keeps a hidden takes fence and hidden facts rows and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them. | Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended. | agent | `repeat the read that failed` | 1 | no |
-Reasons: `takes`, `timeline`.
+Reasons: `takes`, `facts`, `timeline`.
+
+### upload_too_many_parts
+
+<a id="upload_too_many_parts"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An upload part was refused because the session reached its part limit (64 plus one per 64 KiB of total_bytes) without completing the content. | Each part is a stored row; the limit keeps a session of tiny parts from growing without bound, and a client cutting parts near part_max_frame_bytes never reaches it. | Send the rest of the content in that part (within part_max_frame_bytes), or abort and begin again cutting parts near part_max_frame_bytes. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#upload_too_many_parts](../../docs/guides/write-refusals.md#upload_too_many_parts)
### upstream
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 1918189bb2..f50db6b34b 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -115,8 +115,9 @@ of making a duplicate.
| <a id="write_quota_exhausted"></a>`write_quota_exhausted` (exit 12) | `write_quota_exhausted` | A cumulative write cap is full: permanent request ids (`persistence.limits.principal_lifetime_ids` or `brain_lifetime_ids`, `reason: lifetime_ids`) or reserved receipt bytes (`principal_terminal_bytes` or `brain_terminal_bytes`, `reason: terminal_bytes`). `begin_page_upload` refuses the same way at the staged-upload caps: staged bytes (`principal_staged_bytes` or `brain_staged_bytes`, `reason: staged_bytes`) or open sessions (`principal_uploads`, `reason: open_uploads`); those free when a session commits, aborts or expires, so `abort_page_upload` on an abandoned session also helps. `detail` names the limit key. Waiting does not help: ids are permanent and receipt bytes free only as receipts compact. Nothing changed. | Run the `fix` on the brain host: `gbrain config set <key> <value>` (the value covers about one more year at the current rate; undo with `gbrain config unset <key>`), then retry with the same `request_id`. For receipt bytes with reclaimable slack, `gbrain repair receipt-compaction` second previews the retained bytes compaction would free (ids: only the raise helps). Verify with `gbrain doctor --only persistence_capacity --json`. [Runbook](concurrent-writes.md#quota-near-exhaustion). |
| <a id="upload_not_found"></a>`upload_not_found` | `upload_not_found` | An upload call (`upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) named a session this connection cannot use: no such `upload_id`, another connection's session, a source outside your grant or since re-created, a page deleted or re-created since begin (for mode `create`, a page now at the slug), or an aborted session. Every case gets the same answer, so an `upload_id` reveals nothing. Nothing was written. | Begin a new upload with `begin_page_upload` and a new `request_id`, then send its parts from part 0. |
| <a id="upload_expired"></a>`upload_expired` | `upload_expired` | The upload session passed its idle deadline (`persistence.limits.upload_idle_seconds`, 1 hour since its last part) or its hard deadline (`upload_max_seconds`, 24 hours since begin) before it was committed. Its parts were discarded and its staged bytes released; nothing was written. | Run the `fix`: `begin_page_upload` again with a new `request_id` and send every part from part 0. An expired session never resumes. |
-| <a id="upload_protected_content"></a>`upload_protected_content` (`reason`: `takes` or `timeline`) | `upload_protected_content` | A remote `commit_page_upload` replacing a page with content over 24 MiB was refused: the page holds a takes fence that remote reads hide (`takes`), or timeline rows (`timeline`). put_page keeps the hidden fence and checks which timeline rows its content omits by comparing whole bodies; a body this size is never held whole, so the upload refuses instead of dropping them. The session was discarded and its staged bytes released; nothing was written. | `takes`: replace the page with content of at most 24 MiB through put_page (which carries the fence over), or ask the user to write it on the brain host. `timeline`: upload again and commit with `drop_timeline: true` only if deleting every timeline entry is intended; otherwise send at most 24 MiB through put_page. |
+| <a id="upload_protected_content"></a>`upload_protected_content` (`reason`: `takes`, `facts` or `timeline`) | `upload_protected_content` | A remote `commit_page_upload` replacing a page with content over 24 MiB was refused: the page holds a takes fence that remote reads hide (`takes`), a facts fence with a row remote reads hide (a non-world row, or a fence that does not parse: `facts`), or timeline rows (`timeline`). put_page keeps the hidden fence and rows and checks which timeline rows its content omits by comparing whole bodies; a body this size is never held whole, so the upload refuses instead of dropping them. The session was discarded and its staged bytes released; nothing was written. | `takes` or `facts`: replace the page with content of at most 24 MiB through put_page (which carries the fence or the hidden rows over), or ask the user to write it on the brain host. `timeline`: upload again and commit with `drop_timeline: true` only if deleting every timeline entry is intended; otherwise send at most 24 MiB through put_page. |
| <a id="part_too_large"></a>`part_too_large` | `part_too_large` | An `upload_page_part` call's encoded arguments are over this connection's `part_max_frame_bytes` (its inbound request cap, at most 4 MiB, minus a 4 KiB envelope; `detail` names both sizes). JSON escaping counts quotes, backslashes and control characters at their escaped size. The part was not stored. | Cut the part smaller and send it again with the same part number; `get_page_upload` returns `part_max_frame_bytes` and `next_part`. |
+| <a id="upload_too_many_parts"></a>`upload_too_many_parts` | `upload_too_many_parts` | An `upload_page_part` call would be part number 64 plus one per 64 KiB of the declared `total_bytes` (one per eighth of `part_max_frame_bytes` when that is under 512 KiB) or later without completing the content. Each part is a stored row, so a session of tiny parts is bounded. The part was not stored. | Send all remaining bytes in that part if they fit within `part_max_frame_bytes`; otherwise abort and begin again, cutting parts near `part_max_frame_bytes` (`get_page_upload` returns it). |
| <a id="part_splits_code_point"></a>`part_splits_code_point` | `part_splits_code_point` | An `upload_page_part` text starts or ends with half of a surrogate pair, which has no UTF-8 encoding on its own. The part was not stored. | Move the cut before the high surrogate so the pair travels in one part, then send the part again. |
| <a id="write_quota_insufficient"></a>`write_quota_insufficient` (exit 12) | `write_quota_insufficient` | A bulk run (a managed sync catch-up, a reclone, a repair) estimated from its manifest more new receipts (ids and 16 KiB reservations) than the capacity left before its producer's pause line, so it did not start. Other writes still work. | Run the `gbrain config set <key> <value>` the message prints on the brain host, then rerun the same command. Verify with `gbrain doctor --only persistence_capacity --json`. |
| <a id="write_capacity_low"></a>`write_capacity_low` (notice) | `write_capacity_low` | Not a refusal: a `[gbrain notice]` on write receipts, `sync` receipts, `gbrain sync status` and autopilot cycle output when a cumulative cap is at or past 80% or would run out within `persistence.capacity.warn_days` (30) days at its 7-day rate. Receipts carry it at most once an hour per process and scope; `sync status` and doctor carry it every time. The structured `capacity` object names the scope, resource, days left and the config command. | Follow the [runbook](concurrent-writes.md#quota-near-exhaustion): raise the cap it names with the printed `gbrain config set`, then verify with `gbrain doctor --only persistence_capacity --json`. |
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index a63044ae9d..92d54a4686 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -719,7 +719,8 @@ export const CODES = {
unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },
upload_expired: { class: 'caller', summary: "The upload session passed its idle or hard deadline before it was committed, so its parts were discarded and nothing was written.", why: "Open sessions hold staged bytes against per-connection and per-brain quotas; persistence.limits.upload_idle_seconds (1 h) and upload_max_seconds (24 h) bound how long they may.", suggestion: 'Begin the upload again with a new request_id and send every part from part 0.' },
upload_not_found: { class: 'caller', summary: "No open upload session matches this upload_id for this connection.", why: "A session answers only its creating connection, in its source, while the page it began against is unchanged; every other case gets this same answer so an upload_id reveals nothing.", suggestion: 'Begin a new upload with begin_page_upload and a new request_id.' },
- upload_protected_content: { class: 'caller', reasons: ['takes', 'timeline'], summary: "A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence remote reads hide, or timeline rows.", why: "put_page keeps a hidden takes fence and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them.", suggestion: 'Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended.' },
+ upload_protected_content: { class: 'caller', reasons: ['takes', 'facts', 'timeline'], summary: "A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence or facts rows remote reads hide, or timeline rows.", why: "put_page keeps a hidden takes fence and hidden facts rows and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them.", suggestion: 'Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended.' },
+ upload_too_many_parts: { class: 'caller', summary: "An upload part was refused because the session reached its part limit (64 plus one per 64 KiB of total_bytes) without completing the content.", why: "Each part is a stored row; the limit keeps a session of tiny parts from growing without bound, and a client cutting parts near part_max_frame_bytes never reaches it.", docs: 'docs/guides/write-refusals.md#upload_too_many_parts', suggestion: 'Send the rest of the content in that part (within part_max_frame_bytes), or abort and begin again cutting parts near part_max_frame_bytes.' },
upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },
upstream_diverged: { class: 'caller', actor: 'agent', summary: "A classic source's pull cannot fast-forward: the checkout has commits that are not on the upstream and the upstream moved forward; local HEAD keeps syncing.", why: "The upstream still contains the commit this checkout last pulled, so nothing was force-pushed: bringing the upstream in beside the local commits loses nothing.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Run gbrain git commit-push --pull --path <checkout>, then gbrain sync --source <id>.' },
upstream_rewritten: { class: 'consent', actor: 'user', summary: "A classic source's upstream was force-pushed: the upstream commit the checkout last contained is not in the new upstream history, so the pull cannot fast-forward; local HEAD keeps syncing.", why: "Merging would bring back the commits the force-push removed, so the fix resets the checkout to the new upstream after the user agrees, keeping the old history under a backup ref.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then run the gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> command doctor sync_failures prints (preview with --dry-run), then gbrain sync --source <id>.' },
diff --git a/src/core/ops/page-upload.ts b/src/core/ops/page-upload.ts
index 86dfdec8aa..393ba97262 100644
--- a/src/core/ops/page-upload.ts
+++ b/src/core/ops/page-upload.ts
@@ -33,7 +33,7 @@ import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
import { admitPageAppend } from '../persistence/page-append.ts';
import {
abortUpload, appendPart, expireIfLapsed, partBytes, partMaxFrameBytes, partSha256, readUpload, readUploadByRequest, reserveUpload,
- sealUpload, stagedSha256, transitionUploads, uploadExpired, uploadNotFound, uploadPartFrameBytes, type StagingBodyRef, type UploadMode, type UploadRow,
+ isStagingBodyRef, sealUpload, stagedSha256, transitionUploads, uploadExpired, uploadNotFound, uploadPartFrameBytes, uploadPartLimit, type StagingBodyRef, type UploadMode, type UploadRow,
} from '../persistence/page-upload.ts';
const MODES: readonly UploadMode[] = ['create', 'replace', 'append'];
@@ -257,6 +257,11 @@ const upload_page_part: Operation = {
if (part !== row.next_part) {
throw opError('invalid_params', `Parts are sent in order: this upload expects part ${row.next_part}, not ${part}.`, `Send part ${row.next_part} next.`, { fix: statusFix(row.id) });
}
+ const limit = uploadPartLimit(row.declared_bytes, cap);
+ if (part >= limit && row.received_bytes + bytes.byteLength < row.declared_bytes) {
+ throw opError('upload_too_many_parts', `This upload takes at most ${limit} parts for its ${row.declared_bytes} bytes, and part ${part} does not complete it, so it was not stored.`,
+ `Send the remaining ${row.declared_bytes - row.received_bytes} bytes in part ${part}, cut near part_max_frame_bytes (${cap}); or abort this upload and begin again with larger parts.`, { fix: statusFix(row.id) });
+ }
if (row.received_bytes + bytes.byteLength > row.declared_bytes) {
throw invalidParam(`This part would make the upload ${row.received_bytes + bytes.byteLength} bytes, over its declared total_bytes (${row.declared_bytes}).`,
'Send only the remaining bytes of the content, or abort and begin again with the right total_bytes.');
@@ -340,7 +345,7 @@ const commit_page_upload: Operation = {
throw opError('invalid_params', `This upload has ${row.received_bytes} of its ${row.declared_bytes} bytes, so it cannot be committed yet.`,
`Send part ${row.next_part} and the rest, then commit.`, { fix: statusFix(row.id) });
}
- if (!await sealUpload(ctx.engine, row.id)) row = await boundUpload(ctx, principal, row.id);
+ if (!await sealUpload(ctx.engine, row.id)) row = await settleLapse(ctx, principal, await boundUpload(ctx, principal, row.id));
else {
const hashed = await stagedSha256(ctx.engine, row);
await uploadCommitProbe.afterHash?.(row.id);
@@ -393,7 +398,8 @@ const commit_page_upload: Operation = {
/** Records the session's commit request, and ends the session when that write ended without committing (releasing its bytes). */
async function settleCommit(ctx: OperationContext, principal: Principal, row: UploadRow): Promise<void> {
const request = await getWriteRequest(ctx.engine, principal, row.client_request_id);
- if (!request) return;
+ const ref = (request?.intent as Record<string, unknown> | undefined)?.body_ref;
+ if (!request || !isStagingBodyRef(ref) || ref.staging_id !== row.id) return;
await ctx.engine.executeRaw('UPDATE page_body_stagings SET commit_request_id = COALESCE(commit_request_id, $2::uuid) WHERE id = $1::uuid', [row.id, request.id]);
if (isTerminal(request) && request.state !== 'committed') await transitionUploads(ctx.engine, 'aborted', 's.id = $1::uuid', [row.id]);
}
diff --git a/src/core/persistence/page-upload.ts b/src/core/persistence/page-upload.ts
index 708ccd7668..35774825d4 100644
--- a/src/core/persistence/page-upload.ts
+++ b/src/core/persistence/page-upload.ts
@@ -50,6 +50,15 @@ export function partMaxFrameBytes(ctx: Pick<OperationContext, 'remote' | 'transp
return Math.min(inbound, UPLOAD_PART_FRAME_CAP_BYTES) - UPLOAD_FRAME_RESERVE_BYTES;
}
+/**
+ * The most parts one session takes: 64 plus one per 64 KiB of its declared bytes (one per eighth of the part limit on a
+ * connection whose limit is under 512 KiB), so a client cutting parts near part_max_frame_bytes, even of fully escaped
+ * text, never reaches it while a session of tiny parts cannot grow its part rows without bound.
+ */
+export function uploadPartLimit(declaredBytes: number, partFrameBytes: number): number {
+ return 64 + Math.ceil(declaredBytes / Math.min(64 * 1024, Math.floor(partFrameBytes / 8)));
+}
+
/** The encoded size of one `upload_page_part` call's arguments, the measure clients cut parts by (egress-budget.ts). */
export function uploadPartFrameBytes(args: { upload_id: string; part: number; text: string; part_sha256: string }): number {
return encodedFrameBytes({ upload_id: args.upload_id, part: args.part, text: args.text, part_sha256: args.part_sha256 });
@@ -177,7 +186,8 @@ export interface UploadReservation {
/**
* Begin: in one transaction, lock the caller's and the brain's staged counters (key order), expire the caller's lapsed
- * sessions, recount every live session, refuse past a cap (`write_quota_exhausted`), insert the session and store the
+ * sessions, recount every live session (the brain sum leaves out other principals' lapsed sessions, which the sweep
+ * expires and which nothing revives: a lapsed session takes no part and cannot be sealed), refuse past a cap (`write_quota_exhausted`), insert the session and store the
* counts with its reservation.
*/
export async function reserveUpload(engine: BrainEngine, input: UploadReservation): Promise<void> {
@@ -190,10 +200,10 @@ export async function reserveUpload(engine: BrainEngine, input: UploadReservatio
await tx.executeRaw(LOCK_COUNTERS_SQL, [all]);
await transitionUploads(tx, 'expired', `s.principal_kind = $1 AND s.principal_id = $2 AND ${LAPSED_SQL}`, owner);
const [usage] = await tx.executeRaw<{ staged: unknown; brain: unknown; uploads: unknown }>(`SELECT
- COALESCE(SUM(reserved_bytes) FILTER (WHERE principal_kind = $1 AND principal_id = $2), 0)::text AS staged,
- COALESCE(SUM(reserved_bytes), 0)::text AS brain,
- (count(*) FILTER (WHERE principal_kind = $1 AND principal_id = $2))::text AS uploads
- FROM page_body_stagings WHERE kind = 'upload' AND state = ANY(${LIVE})`, owner);
+ COALESCE(SUM(s.reserved_bytes) FILTER (WHERE s.principal_kind = $1 AND s.principal_id = $2), 0)::text AS staged,
+ COALESCE(SUM(s.reserved_bytes) FILTER (WHERE NOT ${LAPSED_SQL}), 0)::text AS brain,
+ (count(*) FILTER (WHERE s.principal_kind = $1 AND s.principal_id = $2))::text AS uploads
+ FROM page_body_stagings s WHERE s.kind = 'upload' AND s.state = ANY(${LIVE})`, owner);
const staged = Number(usage?.staged ?? 0), brain = Number(usage?.brain ?? 0), uploads = Number(usage?.uploads ?? 0);
if (uploads + 1 > limits.principalUploads) throw stagedQuotaExhausted('open upload sessions for this connection', 'principalUploads', uploads, limits.principalUploads, 1, 'open_uploads');
if (staged + input.totalBytes > limits.principalStagedBytes) throw stagedQuotaExhausted('staged upload bytes for this connection', 'principalStagedBytes', staged, limits.principalStagedBytes, input.totalBytes, 'staged_bytes');
@@ -249,9 +259,9 @@ export async function stagedSha256(exec: SqlEngine, row: Pick<UploadRow, 'id' |
*/
export async function sealUpload(exec: SqlEngine, id: string): Promise<boolean> {
const limits = await readUploadLimits(exec);
- const sealed = await exec.executeRaw<{ id: string }>(`UPDATE page_body_stagings SET state = 'sealed', updated_at = now(),
- hard_expires_at = GREATEST(hard_expires_at, now() + $2::bigint * interval '1 second')
- WHERE id = $1::uuid AND state = 'open' RETURNING id::text AS id`, [id, limits.uploadIdleSeconds]);
+ const sealed = await exec.executeRaw<{ id: string }>(`UPDATE page_body_stagings s SET state = 'sealed', updated_at = now(),
+ hard_expires_at = GREATEST(s.hard_expires_at, now() + $2::bigint * interval '1 second')
+ WHERE s.id = $1::uuid AND s.state = 'open' AND NOT ${LAPSED_SQL} RETURNING s.id::text AS id`, [id, limits.uploadIdleSeconds]);
return sealed.length > 0;
}
diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.ts
index bfa59f55a8..ce46ea0347 100644
--- a/src/core/persistence/upload-streamed.ts
+++ b/src/core/persistence/upload-streamed.ts
@@ -28,6 +28,8 @@ import { coreMarking } from '../core-memory.ts';
import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { inlineRegions } from '../page-body/tail-digest.ts';
+import { segmentedFactsFenceView } from '../page-body/segment-facts.ts';
+import { parseFactsFence, type FactsFenceParseResult } from '../facts-fence.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { bodyStagingGoneError } from '../engine-sql/page-body.ts';
@@ -42,10 +44,12 @@ import type { WriteRequest } from './model.ts';
const text = (value: unknown) => (typeof value === 'string' ? value : null);
/**
- * put_page keeps, for a remote writer, the takes fence remote reads hide (preserveProtectedTakes) and refuses to drop
- * timeline rows its content omits (assertTimelineNotOmitted); both compare whole bodies. Streamed, this refuses
- * instead: a remote replace over the ceiling of a page holding a takes fence, or timeline rows (unless drop_timeline),
- * is `upload_protected_content`. Bounded: one probe of the live manifest and of timeline_entries.
+ * put_page keeps, for a remote writer, the takes fence and the non-world facts rows remote reads hide
+ * (preserveProtectedTakes, mergeHiddenFactRowsIntoBody) and refuses to drop timeline rows its content omits
+ * (assertTimelineNotOmitted); all compare whole bodies. Streamed, this refuses instead: a remote replace over the
+ * ceiling of a page holding a takes fence, a facts fence with a non-world row (or one that does not parse), or timeline
+ * rows (unless drop_timeline), is `upload_protected_content`. Bounded: one probe of the live manifest and of
+ * timeline_entries, and the facts fence alone (segmentedFactsFenceView reads only the runs holding a fence marker).
*/
async function assertNothingHiddenDropped(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, p: Record<string, unknown>): Promise<void> {
const [found] = await engine.executeRaw<{ has_takes: boolean; has_timeline: boolean }>(`SELECT
@@ -53,15 +57,23 @@ async function assertNothingHiddenDropped(engine: BrainEngine, row: WriteRequest
AND m.gen_from <= pg.body_generation AND (m.gen_to IS NULL OR m.gen_to > pg.body_generation)
AND m.protected_regions @> '[{"kind":"takes"}]'::jsonb) AS has_takes,
EXISTS (SELECT 1 FROM timeline_entries WHERE page_id = $1) AS has_timeline`, [Number(snapshot.page.id)]);
- const inlineTakes = !isSegmentedPage(snapshot.page)
- && Object.values(await inlineRegions(engine, Number(snapshot.page.id))).some(region => region.includes(TAKES_FENCE_BEGIN));
- const reason = found?.has_takes || inlineTakes ? 'takes' : found?.has_timeline && p.drop_timeline !== true ? 'timeline' : null;
+ const segmented = isSegmentedPage(snapshot.page);
+ const inline = segmented ? null : await inlineRegions(engine, Number(snapshot.page.id));
+ const fences = inline ? Object.values(inline).map(region => parseFactsFence(region))
+ : Object.values(await segmentedFactsFenceView(engine, { id: Number(snapshot.page.id), slug: row.slug, source_id: row.source_id }))
+ .filter((value): value is FactsFenceParseResult => typeof value === 'object' && value !== null && 'facts' in value);
+ const hiddenFacts = fences.some(fence => fence.warnings.length > 0 || fence.facts.some(fact => fact.visibility !== 'world'));
+ const reason = found?.has_takes || (inline && Object.values(inline).some(region => region.includes(TAKES_FENCE_BEGIN))) ? 'takes'
+ : hiddenFacts ? 'facts'
+ : found?.has_timeline && p.drop_timeline !== true ? 'timeline' : null;
if (!reason) return;
throw opError('upload_protected_content', reason === 'takes'
? `Page ${row.slug} holds a takes fence that remote reads hide, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot carry it over, so nothing was written.`
- : `Page ${row.slug} has timeline rows, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot check which of them its content keeps, so nothing was written.`,
- reason === 'takes'
- ? `Replace the page with content of at most ${PAGE_MAX_BYTES} bytes (put_page keeps the hidden takes fence), or ask the user to write it locally on the brain host.`
+ : reason === 'facts'
+ ? `Page ${row.slug} holds facts rows that remote reads hide, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot carry them over, so nothing was written.`
+ : `Page ${row.slug} has timeline rows, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot check which of them its content keeps, so nothing was written.`,
+ reason === 'takes' || reason === 'facts'
+ ? `Replace the page with content of at most ${PAGE_MAX_BYTES} bytes (put_page keeps the hidden ${reason === 'takes' ? 'takes fence' : 'facts rows'}), or ask the user to write it locally on the brain host.`
: `Upload the page again and commit it with drop_timeline: true only if deleting every timeline entry of the page is intended; otherwise replace it with content of at most ${PAGE_MAX_BYTES} bytes, which put_page checks entry by entry.`,
{ reason, docs: 'docs/guides/write-refusals.md#upload_protected_content' });
}
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 18c7b8087f..de6eb6e6a5 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6423,7 +6423,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\" | \"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\" | \"admission_paused\" | \"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_null_bytes\" | \"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_drift_mixed_selection\" | \"file_drift_state_required\" | \"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\" | \"notifier_stalled\" | \"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\" | \"git_object_missing\" | \"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\" | \"grant_scope\" | \"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_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"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_converged\" | \"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\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"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_host_required\" | \"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\" | \"settle_mismatch\" | \"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_admission_restricted\" | \"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\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"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\" | \"admission_paused\" | \"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_null_bytes\" | \"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_drift_mixed_selection\" | \"file_drift_state_required\" | \"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\" | \"notifier_stalled\" | \"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\" | \"git_object_missing\" | \"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\" | \"grant_scope\" | \"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_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"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_converged\" | \"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\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"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_host_required\" | \"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\" | \"settle_mismatch\" | \"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_admission_restricted\" | \"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\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"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",
diff --git a/test/large-pages/upload-over-ceiling.test.ts b/test/large-pages/upload-over-ceiling.test.ts
index cccc1358bd..8e90a29320 100644
--- a/test/large-pages/upload-over-ceiling.test.ts
+++ b/test/large-pages/upload-over-ceiling.test.ts
@@ -22,6 +22,9 @@ import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
import { stagedUploadWork } from '../../src/core/persistence/page-upload.ts';
import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
import { ContentHashStream } from '../../src/core/page-body/content-hash-stream.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../../src/core/facts-fence.ts';
+import { segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { testBackends } from '../helpers/test-backends.ts';
@@ -89,6 +92,14 @@ for (const kind of testBackends()) {
.map(row => [row.key, [Number(row.intent_bytes), Number(row.outstanding_count)]]));
const setConfig = async (key: string, value: string) =>
engine.executeRaw('INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value', [key, value]);
+ const privateFactRows = async (slug: string) => {
+ const [row] = await engine.executeRaw<{ id: number; storage: string; truth: string | null; timeline: string | null }>(
+ 'SELECT id, body_storage AS storage, compiled_truth AS truth, timeline FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]);
+ const fences = row!.storage === 'segmented'
+ ? await segmentedFactsFenceView(engine, { id: Number(row!.id), slug, source_id: 'default' }).then(view => [view.body, view.timeline])
+ : [parseFactsFence(row!.truth ?? ''), parseFactsFence(row!.timeline ?? '')];
+ return fences.flatMap(fence => fence.facts).filter(fact => fact.visibility !== 'world').map(fact => fact.claim);
+ };
const revisionOf = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;
beforeAll(async () => {
@@ -156,21 +167,28 @@ for (const kind of testBackends()) {
await expectStoredBody(slug, smaller);
}, 900_000);
- test('a remote replace over 24 MiB of a page with a hidden takes fence or timeline rows refuses upload_protected_content and releases its bytes', async () => {
- const cases: Array<['takes' | 'timeline', string, () => Promise<unknown>]> = [
+ test('a remote replace over 24 MiB of a page with a hidden takes fence, private facts rows or timeline rows refuses upload_protected_content and releases its bytes', async () => {
+ const cases: Array<['takes' | 'facts' | 'timeline', string, () => Promise<unknown>]> = [
['takes', 'notes/huge-with-takes', () => call('takes_add', { slug: 'notes/huge-with-takes', claim: 'Launch slips to Q3.', kind: 'take', holder: 'world', request_id: randomUUID() })],
+ ['facts', 'notes/huge-with-facts', () => call('remember', { fact: 'Private launch budget is forty thousand.', provenance: 'upload-test', entity: 'notes/huge-with-facts', visibility: 'private', request_id: randomUUID() })],
+ ['facts', 'notes/segmented-with-facts', async () => {
+ await importFromContent(engine, 'notes/segmented-with-facts', `---\ntitle: Segmented facts\ntype: note\n---\n\n${conversation(2 * MiB, 'segmented-facts')}\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | Private launch budget is forty thousand. | fact | 1.0 | private | high | 2026-01-01 | | s | |\n${FACTS_FENCE_END}\n`, { sourceId: 'default', noEmbed: true });
+ expect((await stored('notes/segmented-with-facts')).body_storage).toBe('segmented');
+ }],
['timeline', 'notes/huge-with-timeline', () => call('add_timeline_entry', { slug: 'notes/huge-with-timeline', date: '2026-01-02', summary: 'Kickoff held', request_id: randomUUID() })],
];
await setConfig('write_gate.agent_mode', 'off');
for (const [reason, slug, protect] of cases) {
- await call('put_page', { slug, content: `---\ntitle: Protected ${reason}\ntype: note\n---\n\n# Protected ${reason}\n\nShort page.\n`, request_id: randomUUID(), wait_ms: 30_000 });
+ if (slug !== 'notes/segmented-with-facts') await call('put_page', { slug, content: `---\ntitle: Protected ${reason}\ntype: note\n---\n\n# Protected ${reason}\n\nShort page.\n`, request_id: randomUUID(), wait_ms: 30_000 });
await protect();
+ if (reason === 'facts') expect(await privateFactRows(slug)).toEqual(['Private launch budget is forty thousand.']);
const prior = await counters();
const before = await engine.readPageSnapshot(slug, { sourceId: 'default' });
const id = await staged(conversation(25 * MiB, `protected-${reason}`), slug, { mode: 'replace', expected_revision: before!.revision });
const refused = await commitRefusal({ upload_id: id });
- expect({ reason, code: refused.code, names: refused.message.includes(reason === 'takes' ? 'takes fence' : 'timeline rows') }).toEqual({ reason, code: 'upload_protected_content', names: true });
+ expect({ reason, code: refused.code, names: refused.message.includes(({ takes: 'takes fence', facts: 'facts rows', timeline: 'timeline rows' })[reason]) }).toEqual({ reason, code: 'upload_protected_content', names: true });
expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision).toBe(before!.revision);
+ if (reason === 'facts') expect(await privateFactRows(slug)).toEqual(['Private launch budget is forty thousand.']);
const after = await counters();
for (const [key, value] of Object.entries(after)) expect([reason, key, value]).toEqual([reason, key, prior[key] ?? [0, 0]]);
}
diff --git a/test/large-pages/upload-review.test.ts b/test/large-pages/upload-review.test.ts
index c163b7d2a8..d820cd4215 100644
--- a/test/large-pages/upload-review.test.ts
+++ b/test/large-pages/upload-review.test.ts
@@ -183,6 +183,51 @@ for (const kind of testBackends()) {
}
}, 120_000);
+ test('a begin request_id that already named a put_page attaches no session to that write, and abort still frees the session', async () => {
+ const requestId = randomUUID();
+ const other = slugOf();
+ await call('put_page', { slug: other, content: pageText('other'), request_id: requestId, wait_ms: 30_000 });
+ const prior = await counters();
+ const slug = slugOf();
+ const text = pageText('reused');
+ const session = await begin(slug, text, { request_id: requestId });
+ await send(session.upload_id, halves(text));
+ expect((await refusal('commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 })).code).toBe('idempotency_conflict');
+ const [row] = await engine.executeRaw<{ commit_request_id: string | null }>('SELECT commit_request_id::text AS commit_request_id FROM page_body_stagings WHERE id = $1::uuid', [session.upload_id]);
+ expect(row!.commit_request_id).toBeNull();
+ expect((await call('abort_page_upload', { upload_id: session.upload_id })).state).toBe('aborted');
+ await expectReleased(prior);
+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toBeNull();
+ }, 120_000);
+
+ test("another principal's lapsed session does not count against the brain-wide cap at begin", async () => {
+ const heldText = pageText('lapsed', 5000);
+ const text = pageText('fits', 5000);
+ const cap = Buffer.byteLength(heldText) + Buffer.byteLength(text) - 1;
+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('persistence.limits.brain_staged_bytes', $1) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", [String(cap)]);
+ try {
+ const held = await begin(slugOf(), heldText, {}, ctx('review-b'));
+ await engine.executeRaw("UPDATE page_body_stagings SET idle_expires_at = now() - interval '1 second' WHERE id = $1::uuid", [held.upload_id]);
+ const session = await begin(slugOf(), text);
+ expect(session.state).toBe('open');
+ expect((await refusal('get_page_upload', { upload_id: held.upload_id }, ctx('review-b'))).code).toBe('upload_expired');
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key = 'persistence.limits.brain_staged_bytes'");
+ }
+ }, 120_000);
+
+ test('a session of tiny parts stops at its part limit unless the part completes the content', async () => {
+ const text = 'x'.repeat(200);
+ const session = await begin(slugOf(), text);
+ for (let part = 0; part < 65; part++) await call('upload_page_part', { upload_id: session.upload_id, part, text: 'x', part_sha256: hex('x') });
+ const refused = await refusal('upload_page_part', { upload_id: session.upload_id, part: 65, text: 'x', part_sha256: hex('x') });
+ expect(refused.code).toBe('upload_too_many_parts');
+ expect(refused.message).toContain('at most 65 parts');
+ expect(wire(refused)).toContain('get_page_upload');
+ const rest = text.slice(65);
+ expect((await call('upload_page_part', { upload_id: session.upload_id, part: 65, text: rest, part_sha256: hex(rest) })).received_bytes).toBe(200);
+ }, 120_000);
+
test('a slug fence the caller gained after begin closes the session to part, status and abort', async () => {
const slug = slugOf();
const text = pageText('fenced');