Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b lane F: one odd file never stops a managed source (GBRA-133 S-39, S-33, S-22, S-63, S-64)

garrytan234c2a09ca43
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.md
index c40a4d7d4d..b4f7f343a8 100644
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@ -22,6 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/persistence/sync-prescreen.ts` — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After `discoverManagedSync` freezes identities, `prescreenSyncEntries` reads the pinned blobs (`readTreeBlobs`, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and `classifyBaseline` marks each `prescreened` (disk blob, revision and `syncImportParserFor` fingerprint all match; bypassed under `--full` and for held paths) or `drift` (`database`: the page moved, the file did not; `both`/`unknown` in a tree walk or for a `file_drift` hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through `git` effect), is not guarded (`fileBackedRevisions`), and drifted pages under `storage.keep_db` prefixes leave the manifest as drift candidates (`releaseKeepDbDrift`, `recordDriftSkip`). The run passes prescreened entries through `waivePrescreenedRun` (`sync-waivers.ts`); `freezeEntry` holds a drifted import `file_drift` (`fileDriftHold`, `sync-page-fault.ts`) unless `sameContentAtOrigin` proves it a no-op. `movedDriftHolds` re-screens drift holds whose page moved. Tests: `test/sync-prescreen-drift-6712.test.ts` (both engines).
- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.
- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path; `slug` is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through `bindOrigin` (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM), `streamed-sync-origin-b14.test.ts` (both engines).
+- `src/core/persistence/sync-entry-fault.ts` — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. `nullBytesRefusal` holds a Markdown text with U+0000 `content_null_bytes` (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from `screenFrozenImport` with holds on and as a typed run stop under `sync.holds=fail`. `committedContentOrMissing` (called by `pinnedContent` when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws `git_object_missing`. `directoryAt` lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). `freezeFaultHold` is `freezeEntry`'s catch (`sync-run.ts` wraps `freezeEntryOnce`): `git_object_missing` is held under its code, any other `OperationError` and every run-scoped error (`classifyItemFailure` scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held `page_write_failed` with `write_failure.origin: 'freeze'` and `request_id: null`, re-tested by every sync until held `HOLD_ATTEMPTS_NEEDS_HUMAN` times; a run with `ITEM_BREAKER_MIN_ITEMS` faults and no more clean freezes than faults is systemic and rethrows.
- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.
- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 18ca058d42..c0d28db3ab 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -748,6 +748,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/troubleshooting.md#consumers-without-heartbeat](../../docs/guides/troubleshooting.md#consumers-without-heartbeat)
+### content_null_bytes
+
+<a id="content_null_bytes"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A synced Markdown file holds NUL bytes (U+0000), so managed sync holds that file alone. | Page text is stored as UTF-8 without NUL bytes, so the file cannot be imported as it stands; NUL bytes usually mean a UTF-16 save (a Windows "Unicode" file), a binary file named .md or a crash-padded file. The rest of the source keeps syncing. | Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with sync.exclude), then commit and sync again. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#content_null_bytes](../../docs/guides/write-refusals.md#content_null_bytes)
+
### content_receipt_stale
<a id="content_receipt_stale"></a>
@@ -1546,6 +1556,16 @@ More: [docs/guides/concurrent-writes.md#git-durability-at-activation](../../docs
|---|---|---|---|---|---|---|
| Git index stale. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### git_object_missing
+
+<a id="git_object_missing"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone. | An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing. | Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#git_object_missing](../../docs/guides/write-refusals.md#git_object_missing)
+
### git_operation_in_progress
<a id="git_operation_in_progress"></a>
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 13c0ac7795..136a929c1e 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -135,6 +135,8 @@ Every hold and error has three fields, from one table
| `settle_mismatch` | page | none | yes | always: the pass cannot tell why the path does not settle |
| `page_write_failed` | page | upgrade | yes | always: the writer cannot place the failure |
| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
+| `content_null_bytes` | page | none | yes | always: only an edit to the file or its removal clears it |
+| `git_object_missing` | page | none | yes | always: only restoring the Git object clears it |
| `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
| `page_identity_decision` | page | none | yes | always: only a person decides which page the file is |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 81f0047976..4a1176fb92 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -99,7 +99,9 @@ of making a duplicate.
| <a id="purge_mirror_unwritable"></a>`purge_mirror_unwritable` | `purge_mirror_unwritable` | A fact or page purge appends a text-free `intent` line to the purge mirror (`<brain home>/.gbrain/purge-events.jsonl`) and fsyncs it before it commits, so a later restore of an older backup can replay the purge. The mirror could not be written (a directory in its place, a read-only home, a full disk), so the purge was refused: nothing was removed, tombstoned or redacted. Do not assume the requested content was erased. | Make the mirror a writable regular file owned by the brain's user (mode 0600), then run the purge again with a new `request_id`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="file_unreadable"></a>`file_unreadable` (sync hold) | `file_unreadable` | A managed sync held one file because it is not a readable regular file inside the source root: a symlink (to a file outside the root or inside it), a non-regular file, or a permission or loop error. Sync never reads or follows it. Until GBRA-130 the whole sync stopped at that file on every run and the rest of the source never imported; now only the file waits. A source root that is itself replaced by a symlink still refuses the whole sync. | Make the file a readable regular file in the checkout (replace the symlink with the file, fix its permissions) or exclude it with `sync.exclude`, and commit. A commit that changes it re-screens the hold on the next sync; after a permission fix run `gbrain sources retry-held <source>`, then the same sync. |
-| <a id="page_write_failed"></a>`page_write_failed` (sync hold) | `page_write_failed` | A managed sync held one file because its write failed the same way three times (the same code, origin, error class and SQLSTATE in this source), with an error gbrain cannot classify: an owner exception (for example Postgres 54000 when a frontmatter tag is too long for its index), or a refusal the receipt does not explain. Until GBRA-130 every sync stopped `blocked_by_failures` at that file and the rest of the source never imported; now the file is held and the rest of the source syncs. The first two failures still stop the run, so a one-off defect never holds a file. | Read the receipt the hold names (`gbrain write-request <request_id>`, read-only). Fix the file when the error names its content (shorten the tag, split the page), or report the receipt with the gbrain version. Then `gbrain sources retry-held <source>` and the same sync. An upgrade re-tests the file on its own. |
+| <a id="page_write_failed"></a>`page_write_failed` (sync hold) | `page_write_failed` | A managed sync held one file because its write failed the same way three times (the same code, origin, error class and SQLSTATE in this source), with an error gbrain cannot classify: an owner exception (for example Postgres 54000 when a frontmatter tag is too long for its index), or a refusal the receipt does not explain. Until GBRA-130 every sync stopped `blocked_by_failures` at that file and the rest of the source never imported; now the file is held and the rest of the source syncs. The first two failures still stop the run, so a one-off defect never holds a file. | Read the receipt the hold names (`gbrain write-request <request_id>`, read-only). Fix the file when the error names its content (shorten the tag, split the page), or report the receipt with the gbrain version. Then `gbrain sources retry-held <source>` and the same sync. An upgrade re-tests the file on its own. A hold whose `meta.write_failure.origin` is `freeze` (GBRA-133) is different: sync could not even prepare the file (an unexpected error while reading or screening it, before any request was admitted), so it holds it on the first failure and names the error in the hold message; the next syncs re-test it on their own until it has been held 3 times, so a transient fault clears without help. When most files of one run fail that way the run stops instead (the cause is not the files). |
+| <a id="content_null_bytes"></a>`content_null_bytes` (sync hold) | `content_null_bytes` | A managed sync held one Markdown file because its text holds NUL bytes (U+0000). Page text is stored as UTF-8 without NUL bytes. The usual cause is a UTF-16 file (a Windows "Unicode" save; the hold says so when the file starts with a UTF-16 byte order mark), a binary file named `.md` or a crash-padded file. Until GBRA-133 the whole managed sync stopped at that file on every run (`storage_error`, SQLSTATE 22P05) and the rest of the source never imported; now only the file waits. With `sync.holds=fail` the run stops with `content_null_bytes` instead of holding. | Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with `sync.exclude`), then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. |
+| <a id="git_object_missing"></a>`git_object_missing` (sync hold) | `git_object_missing` | A managed sync held one committed file because the commit names a Git object the checkout no longer has (an interrupted `git gc`, a partial clone without its promisor remote, disk corruption) and the working-tree copy differs from it or is gone. When the working-tree bytes hash to the committed blob id, sync imports them and holds nothing. Until GBRA-133 the whole managed sync stopped at that file on every run. | Run `git fsck --connectivity-only` in the checkout to see what is missing, restore it with `git fetch` (a partial or shallow clone) or from a backup, then `gbrain sync --source <source> --no-pull`. Every sync re-tests the hold. |
| <a id="write_interrupted"></a>`write_interrupted` | `write_interrupted` | The database ended this managed write's own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, and the request reached `persistence.max_preparation_attempts` (default 2) counted attempts, so the owner finished it `failed` instead of preparing it again. Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Each interruption throws the preparation away, so it counts with the preparations cut off at their deadline ([`preparation_stalled`](#preparation_stalled)); before, a write the database ended every time (a large page publishing under the 5-second statement bound on a loaded host) was released as `database_contention` and prepared again, its whole body streamed again, without limit. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is still released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the attempts, the limit and the SQLSTATE (`sqlstate`, public). A managed sync member is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. Only the database ending the write's own statement counts: a group's shared read the database cancels is charged once, to the first member that settles with it, never to every member, so a read cancelled on every pass still ends each member `write_interrupted` at the limit; and the charge commits with the claim's release, so a crash between them never counts it twice. With `persistence.preparation_deadlines` off nothing is counted, as before. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_preparation_attempts` to get past it. |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
| <a id="page_body_segmented"></a>`page_body_segmented` | `page_body_segmented` (a memory verb: `invalid_params` with `write_error: page_body_segmented`) | The target page stores its body in segments (a page over 1 MiB written while `pages.segmented_storage` was on), and this write needs the whole body as one string: `remember` against an entity page over 24 MiB (named, or inferred from the fact), and the other whole-body writers listed under [page_body_segmented](windowed-reads.md#page_body_segmented). It refused before changing anything and is not retryable. | For `remember`, save the claim without an entity (`infer_entity: false`); remembering it with `entity` once that page accepts fact rows replaces that copy. Otherwise edit the page's file and sync it, or read it with `get_page` `body: "auto"`. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index a634c4bbde..34063663bd 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 1988 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6712 PR 4b: sync.admission KNOWN_CONFIG_KEYS row (value logic in persistence/sync-admission.ts); re-summed at the #6712 PR 4b merge of master v0.60.296.0 (both the 4b and #6948 rows); re-summed at the #6712 PR 4b merge of master v0.60.300.0 (1988 measured: the 4b sync.admission row and the #6948 sweep C-9 row)
-src/core/persistence/sync-run.ts 1669 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); re-summed at the #6712 PR 4b merge of master v0.60.296.0 (#6948 freezeEntry hold on the cursor path); re-summed at the #6712 PR 4b merge of master v0.60.300.0 (1669 measured: 4b keeps convertBlockedCursor retired, so master's +113 does not land)
+src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); re-summed at the #6712 PR 4b merge of master v0.60.296.0 (#6948 freezeEntry hold on the cursor path); re-summed at the #6712 PR 4b merge of master v0.60.300.0 (1669 measured: 4b keeps convertBlockedCursor retired, so master's +113 does not land); +12 GBRA-133 lane F (#6712 PR 4b): freezeEntry wraps its private freezeEntryOnce so an entry whose freeze throws is held alone (S-63), the sync.holds=fail NUL refusal (S-39), the directory-at-a-deleted-path read (S-22) and the bulk follower catch (S-64); the classification and the holds live in persistence/sync-entry-fault.ts
src/core/bootstrap/harness.ts 2584 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 716 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b94077f59d..7afea9963c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -928,6 +928,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.300.0', text: 'A managed sync pass that runs 4 rounds without the source settling (another writer keeps changing it) stops `not_converged`: outcome `resumable`, exit 0, everything it admitted stands, and `next` reruns the same sync. After 3 such passes in a row, `next` switches to a report: `gbrain sync status --source <id> --json` with `safe_to_loop: false` and `fix.next: report`, and a sync job ends needing an operator, so an agent loop stops instead of retrying. The count resets when a pass converges.' },
{ since: '0.60.300.0', text: 'New explicit repair `gbrain repair legacy-twins --source <id>` (#6885) merges the page pairs syncs before #6857 forked: a legacy page with no recorded file whose slug spells the file\'s name differently from today\'s slug rules, and the twin at today\'s slug that records the file. The read-only preview lists each pair (both pages\' ids, slugs and revisions, the file, whether the contents match) and lists as decisions, never merged, pairs whose contents differ, several legacy pages for one twin, twins whose file is missing or drifted, and twins holding a link, relationship date, timeline entry or raw data row the legacy page holds differently (`twin_evidence_conflicts`). `--apply --expect <hash> --yes` merges exactly the approved pairs: the legacy page takes over the file and keeps its id, links and history, the twin\'s links and their dated transitions, timeline, raw data, user-added tags, aliases and the facts other pages state about it move over through the same twin merge as `gbrain repair origin-twins` (#6948), its slug becomes an alias, and the twin is soft-deleted (its file untouched) and purged after 72 hours. It refuses off the owner host (`not_owner_host`), when the checkout cannot be read (`legacy_twins_storage_unknown`), and when the pairs are more than half of a source\'s file-backed pages (`legacy_twin_mass_merge_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`). Nothing changes on upgrade; it runs only when named.' },
{ since: '0.60.300.0', text: 'A managed sync of a non-company source that cannot decide which page a file is no longer stops the whole source with `page_identity_changed`: the file alone is held `page_identity_changed` (it needs a person; `meta.reason` names why) and the rest of the source syncs. `several_tombstones`: several deleted pages record the file as their origin; `spelling`: files differing only by letter case or separator (both are held); `identity_differs`: a file whose frontmatter id differs from the page at its slug, which keeps its id, body and slug while its old file\'s deletion waits. A dry run (and a company source) still refuses the source as before, so `gbrain sync --dry-run` reports a refusal where the sync itself holds one file; a remote sync leaves such files for the owner\'s sync to hold.' },
+ { since: '0.60.300.0', text: 'A managed sync no longer stops a whole source at a Markdown file whose text holds NUL bytes (U+0000: a UTF-16 "Unicode" save, a binary file named .md, a crash-padded file). Before, every run failed at that file with `storage_error` (SQLSTATE 22P05) and nothing after it synced; now the file alone is held `content_null_bytes`, its message names the file and the first NUL\'s line (and says to save it as UTF-8 when it starts with a UTF-16 byte order mark), and the rest of the source syncs. With `sync.holds=fail` the run stops with `content_null_bytes` instead. Classic (unmanaged) sync is unchanged.' },
+ { since: '0.60.300.0', text: 'A managed sync no longer stops a whole source at a committed file whose Git object the checkout lost (an interrupted gc, a partial clone): it imports the working-tree bytes when they hash to the committed blob id, and otherwise holds that file `git_object_missing` (run `git fsck`, restore the object with `git fetch` or from a backup; every sync re-tests it). An imported file that became a directory (`notes/a.md` turned into `notes/a.md/x.md`) no longer stops the source with `page_identity_changed`: its page is deleted and the new file imports.' },
+ { since: '0.60.300.0', text: 'When managed sync hits an unexpected error while preparing one file (before anything is admitted), it now holds that file `page_write_failed` with `meta.write_failure.origin` `freeze` and the error in the hold message, and the rest of the source syncs; before, the source stopped on that file on every run. The next syncs re-test the file on their own until it has been held 3 times, so a passing fault clears without help. A deliberate refusal still stops the run, and so does a run in which most files fail that way (5 or more, and at least as many as prepared cleanly), which looks systemic. In a bulk group (Postgres) the failure is reported on the file that failed, not on the group\'s first file.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 88905767a3..d28bd5862a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -169,6 +169,7 @@ export const CODES = {
fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
why: 'Read-only: lists the held file with the two slugs and the rendered paragraph; the user decides which page keeps the slug before anything is edited.',
verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
+ content_null_bytes: { class: 'caller', summary: "A synced Markdown file holds NUL bytes (U+0000), so managed sync holds that file alone.", why: "Page text is stored as UTF-8 without NUL bytes, so the file cannot be imported as it stands; NUL bytes usually mean a UTF-16 save (a Windows \"Unicode\" file), a binary file named .md or a crash-padded file. The rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#content_null_bytes', suggestion: 'Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with sync.exclude), then commit and sync again.' },
content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
continuation_unproven: { class: 'retryable', summary: "Claude Code continued an answer past its output cap and gbrain could not prove the full text, so the claude-cli call returned no text and no tool calls and finished as length.", why: "Print mode reports only the text after an automatic continuation; parsing or dispatching that tail as a complete answer would act on a fragment. The caller retries or escalates as for any capped answer; the gateway does not resend it to a fallback model.", reasons: ['events_missing', 'no_assistant_events', 'segments_unmatched'], docs: 'docs/ai-providers/claude-cli.md#claude-cli-troubleshooting', fix: { argv: ['gbrain', 'config', 'set', '<KEY>', '<TOKENS>'], inputs: [{ name: 'KEY', how: "The output cap the failing caller's truncation warning names (for example dream.propose_takes.max_tokens, facts.extraction_max_tokens or models.synopsis_max_tokens)." }, { name: 'TOKENS', how: 'A larger whole number of output tokens; ask the user, since a larger cap can cost more per call.' }], consent: [], actor: 'agent', ask_user: true, why: 'A cap the whole answer fits under ends the call before Claude Code continues it, so the full text arrives in one response.', requires_exclusive: false } },
corpus_chat_unavailable: { class: 'unavailable', summary: "The sweep's corpus pass stopped because the extraction model is not servable in this process; the captured session files stay pending (no `.ingested` sidecar), so nothing was lost.",
@@ -301,6 +302,7 @@ export const CODES = {
git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },
git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
git_unavailable: { class: 'retryable', summary: "A git command did not complete." },
+ git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },
graduation_drain_timeout: { class: 'retryable', summary: "Queued or running writes did not drain within --drain-timeout; the move stopped before copying and the source is unchanged.", docs: 'docs/guides/move-to-postgres.md#drain', reasons: ['progressing', 'blocked'], exit: 11 },
graduation_embedding_dimension_mismatch: { class: 'caller', summary: "An existing, non-empty target database has a different embedding column layout than the brain being moved.", docs: 'docs/guides/move-to-postgres.md#embeddings' },
graduation_foreign_host_binding: { class: 'host_only', summary: "A source's worktree is owned by another host, so this host cannot move it to Postgres.", docs: 'docs/guides/move-to-postgres.md#hosts' },
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 85cb80160c..c4bdb08787 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -50,6 +50,8 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
permission_denied: 'permission',
owner_unavailable: 'config', writer_coordinator_required: 'config', write_quota_exhausted: 'config', write_quota_insufficient: 'config', plan_stale: 'config',
slug_root_mode_mismatch: 'config', invalid_params: 'config',
+ // GBRA-133 (#6712 PR 4b lane F): a file whose text holds NUL bytes, and a committed file whose Git object is gone.
+ content_null_bytes: 'content_refused', git_object_missing: 'storage',
};
/** A registry code's class, for a code neither table names. */
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 0350f5f51d..3fb3e8a0b6 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -188,6 +188,8 @@ export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'git
return { mode, kind, object, name: row.slice(tab + 1) };
}).filter(item => item.name === part || process.platform === 'win32' && item.name.toLowerCase() === part.toLowerCase());
if (!matches.length) return;
+ // GBRA-133 S-22: a directory where the deleted file was (notes/a.md became notes/a.md/x.md) means the file origin is gone.
+ if (index === parts.length - 1 && matches.every(item => item.kind === 'tree')) return;
if (matches.length !== 1 || index === parts.length - 1 || matches[0].kind !== 'tree') {
throw new OperationError('page_identity_changed', 'The pinned Git target still contains or aliases the origin selected for deletion.',
'Inspect the source identity, then explicitly retry failed sync discovery; the accepted request has not been rewritten.');
diff --git a/src/core/persistence/sync-entry-fault.ts b/src/core/persistence/sync-entry-fault.ts
new file mode 100644
index 0000000000..3605150d5f
--- /dev/null
+++ b/src/core/persistence/sync-entry-fault.ts
@@ -0,0 +1,113 @@
+/**
+ * GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze. One odd file never stops its source: a fault
+ * that belongs to the entry is held on that file alone, and only run-scoped failures (the binding, the writer, the
+ * schema, recovery, a lost connection, an abort) stop the run.
+ *
+ * - `nullBytesRefusal` (S-39/S-44/S-53): a Markdown file whose text holds U+0000 (a binary file named `.md`, a
+ * crash-padded file, a UTF-16 save) cannot be stored as text or carried in a write intent, so it is held
+ * `content_null_bytes` with the first NUL's line instead of failing the admission with 22P05 forever.
+ * - `committedContentOrMissing` (S-33): a committed file whose Git blob is gone (an interrupted gc, a partial clone
+ * without its promisor, disk corruption) imports from the working tree when those bytes hash to the committed blob
+ * id; otherwise it is refused `git_object_missing`, which the freeze holds, naming `git fsck` / `git fetch`.
+ * - `freezeFaultHold` (S-63/S-64): any other unexpected throw while freezing one entry (a Git read, the in-process
+ * screen, a TypeError) is held `page_write_failed` (origin `freeze`) with the error class and message, re-screened
+ * by the next syncs until it has been held `HOLD_ATTEMPTS_NEEDS_HUMAN` times, so a transient fault clears on its own.
+ * Deliberate refusals (an `OperationError`) keep their own route; a run where most freezes fault is systemic and
+ * stops instead of holding every file.
+ */
+import { lstatSync } from 'node:fs';
+import { join } from 'node:path';
+import { OperationError, opError } from '../ops/contract.ts';
+import { classifyItemFailure, ITEM_BREAKER_MIN_ITEMS } from '../item-failure.ts';
+import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
+import { LockStolenError } from '../db-lock.ts';
+import { RECOVERY_VERSION } from '../markdown.ts';
+import { VERSION } from '../../version.ts';
+import { isWriteCapacityWait } from './admission-retry.ts';
+import { gitBlobOid } from './digest.ts';
+import { readBlobBytes, type TreeBlob } from './sync-blobs.ts';
+import { readSyncFile, type SyncEntry } from './sync-discovery.ts';
+import type { GitHoldRecord } from './sync-holds.ts';
+
+type HoldEntry = Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>;
+type HeldFault = Pick<GitHoldRecord, 'path' | 'source_path' | 'slug' | 'page_id' | 'code' | 'message' | 'upstream_version' | 'meta'>;
+
+/** S-39: the `content_null_bytes` refusal of a Markdown text holding U+0000 (the first one's 1-based line), or null. */
+export function nullBytesRefusal(path: string, content: string): { code: 'content_null_bytes'; line: number; message: string } | null {
+ const at = content.indexOf('\u0000');
+ if (at < 0) return null;
+ const line = content.slice(0, at).split('\n').length;
+ // A UTF-16 byte order mark (FF FE or FE FF) reads as two replacement characters in UTF-8.
+ const utf16 = content.startsWith('\uFFFD\uFFFD');
+ return { code: 'content_null_bytes', line, message: `${path} holds a NUL byte (U+0000) on line ${line}${utf16 ? ' and starts with a UTF-16 byte order mark, so it is UTF-16 text, not UTF-8' : ''}; `
+ + 'gbrain stores page text as UTF-8 without NUL bytes, so sync held this file and the rest of the source synced. '
+ + `${utf16 ? 'Save it as UTF-8' : 'Remove the NUL bytes (or, for a binary file, remove it or exclude it with sync.exclude)'}, then commit and sync again.` };
+}
+
+/**
+ * S-33: the content of a committed entry whose pinned read failed with `error`. When the commit names a blob for the path
+ * that the repository no longer has, the working-tree bytes are used if they hash to that blob id (the same bytes);
+ * otherwise `git_object_missing` is thrown. Any other failure (no blob at the path, the object present) is rethrown.
+ */
+export function committedContentOrMissing(cursor: { root: string; gitRoot: string; sourceId: string }, entry: Pick<SyncEntry, 'path'>, blob: TreeBlob | null, error: unknown): string {
+ if (!blob || readBlobBytes(cursor.gitRoot, [blob]).has(blob.oid)) throw error;
+ let bytes: Buffer | null = null;
+ try { bytes = readSyncFile(cursor.root, entry.path); } catch { bytes = null; }
+ if (bytes && gitBlobOid(bytes, blob.oid.length === 64 ? 'sha256' : 'sha1') === blob.oid) return bytes.toString('utf8');
+ throw opError('git_object_missing', `The Git object of ${entry.path} at the synced commit is missing from the repository.`,
+ `${entry.path} is committed as blob ${blob.oid}, but the repository of source ${cursor.sourceId} no longer has that object${bytes ? ' and the working-tree file differs from it' : ' and the working tree has no copy of it'}, so nothing was imported from it. `
+ + `Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then run gbrain sync --source ${cursor.sourceId} --no-pull.`,
+ { detail: blob.oid, fix: { argv: ['git', '-C', cursor.gitRoot, 'fsck', '--connectivity-only'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Lists the missing objects (read-only); git fetch, or a restore from a backup, brings them back.', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] } } });
+}
+
+/** S-22: whether a directory stands where an entry's file was (a deleted file whose name became a folder); nothing is read from it. */
+export function directoryAt(root: string, path: string): boolean {
+ try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; }
+}
+
+/** Freeze faults and successes of one run (keyed by its screen run), for the systemic breaker. */
+const tallies = new WeakMap<object, { faults: number; frozen: number }>();
+/** S-63: counts one entry frozen without a fault in `run`. */
+export function noteFrozen(run: object | null | undefined): void {
+ if (!run) return;
+ const tally = tallies.get(run) ?? { faults: 0, frozen: 0 };
+ tally.frozen++; tallies.set(run, tally);
+}
+
+/** Errors that are never one entry's: an abort, a lost connection or lock, back-pressure, or anything the item classifier scopes to the run. */
+function runScoped(error: unknown): boolean {
+ return (error as { name?: unknown } | null)?.name === 'AbortError' || error instanceof LockStolenError || isWriteCapacityWait(error)
+ || isRetryableConnError(error) || isStatementTimeoutError(error) || classifyItemFailure(error).scope !== 'item';
+}
+
+/**
+ * S-63/S-64/S-33: the hold a throw while freezing one entry earns when holds are on, or null to rethrow it. A
+ * `git_object_missing` refusal is held under its code; any other `OperationError` is a deliberate refusal and keeps
+ * its route. An unexpected throw is held `page_write_failed` (origin `freeze`) unless it is run-scoped or the run
+ * looks systemic (`ITEM_BREAKER_MIN_ITEMS` faults and at least as many faults as clean freezes).
+ */
+export function freezeFaultHold(run: object, entry: HoldEntry, slug: string, pageId: number | null, error: unknown, blob: () => TreeBlob | null): HeldFault | null {
+ const missing = error instanceof OperationError && error.code === 'git_object_missing';
+ if (!missing && (error instanceof OperationError || runScoped(error))) return null;
+ if (!missing) {
+ const tally = tallies.get(run) ?? { faults: 0, frozen: 0 };
+ tally.faults++; tallies.set(run, tally);
+ if (tally.faults >= ITEM_BREAKER_MIN_ITEMS && tally.faults >= tally.frozen) return null;
+ }
+ let pinned: TreeBlob | null = null;
+ try { pinned = entry.working ? null : blob(); } catch { pinned = null; }
+ const rename = entry.renameFrom ?? entry.renameHeld;
+ const meta = { recovery_version: RECOVERY_VERSION, ...(pinned ? { blob_oid: pinned.oid } : {}), ...(entry.working ? { working: true as const } : {}),
+ ...(rename ? { rename_from: rename } : {}), ...(entry.action === 'delete' ? { deleted: true as const } : {}) };
+ if (missing) return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: 'git_object_missing',
+ message: `${(error as OperationError).message} ${(error as OperationError).suggestion ?? ''}`.trim(), upstream_version: null, meta };
+ const name = error instanceof Error ? error.name : typeof error;
+ const errno = (error as { code?: unknown } | null)?.code;
+ const text = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 300);
+ return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: 'page_write_failed',
+ message: `${entry.path}: sync could not prepare its ${entry.action === 'delete' ? 'deletion' : 'import'} (${name}: ${text}), so it is held and the rest of the source synced. `
+ + 'The next syncs re-test it; if it stays held, report it with the gbrain version or fix the file when the error names it, then gbrain sources retry-held.',
+ upstream_version: null,
+ meta: { ...meta, write_failure: { code: 'storage_error', origin: 'freeze', error_class: name, errno: typeof errno === 'string' ? errno.slice(0, 32) : null, request_id: null, attempts: 1, gbrain_version: VERSION } } };
+}
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index a15e20c9c5..bd6b780b2b 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -92,6 +92,12 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// GBRA-130 A-7: the file is not a readable regular file inside the source root (a symlink, a non-regular file, a permission error).
{ code: 'file_unreadable', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a change to the checkout makes the file readable',
human_reason: 'Sync cannot read this file as a regular file inside the source root (a symlink, a non-regular file or a permission error) and never follows it; make it a readable regular file in the checkout (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held <source>.' },
+ // GBRA-133 S-39: the file's text holds NUL bytes (a UTF-16 save, a binary file, a padded file); only an edit or its removal clears it.
+ { code: 'content_null_bytes', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only an edit to the file or its removal clears it',
+ human_reason: 'The file holds NUL bytes, which page text cannot store; save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or exclude it with sync.exclude), and commit.' },
+ // GBRA-133 S-33: the commit names a Git object the checkout no longer has and the working-tree copy differs; only restoring the object clears it.
+ { code: 'git_object_missing', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only restoring the Git object clears it',
+ human_reason: 'The checkout lost the Git object of this committed file and its working-tree copy differs or is gone; run git fsck in the checkout, restore the object with git fetch or from a backup, then sync (every sync re-tests the hold).' },
// #6948: several live pages record the file as their origin; the sync-time heal resolves verified duplicates, a person decides the rest.
{ code: 'origin_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off',
human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 6eb5a646a4..eeffada7ca 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -80,9 +80,15 @@ export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regre
/** GBRA-130 A-17/B-3/B-4: a path whose page identity sync cannot decide (several tombstones, a spelling twin, a takeover whose ids differ). */
| 'page_identity_changed'
/** #6712 PR 4b (S-47): bytes an older gbrain imported and validated whose frontmatter aliases expand past #7018's bound; held alone, never a parser regression. */
- | 'frontmatter_alias_limit';
+ | 'frontmatter_alias_limit'
+ /** GBRA-133 S-39: a Markdown file whose text holds a NUL byte (U+0000): a binary file, a padded file, a UTF-16 save. */
+ | 'content_null_bytes'
+ /** GBRA-133 S-33: a committed file whose Git blob the repository no longer has, and whose working-tree copy differs or is gone. */
+ | 'git_object_missing';
/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */
-export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null; request_id: string; attempts: number; gbrain_version: string }
+export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null;
+ /** The newest failed receipt; null for a GBRA-133 S-63 freeze fault (origin `freeze`), which threw before any request was admitted. */
+ request_id: string | null; attempts: number; gbrain_version: string }
/**
* Flip lane C: the holds of a write that ran out of attempts, its preparation never settling (`preparation_stalled`)
* or its statements ended by the database every time (`write_interrupted`). The file is not the problem: they route to
@@ -551,10 +557,12 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so
* `origin_conflict` hold, which rests on the twin pages the heal, the repair or a person removes. GBRA-130: and a `page_identity_changed`
* hold, which rests on pages (tombstones, a page at the slug) or spellings a person changes. A `frontmatter_alias_limit` hold
* rests on the file's bytes alone (the bound is intended, not transient), so like `invalid_frontmatter` it re-screens when
- * the file changes.
+ * the file changes. GBRA-133: a `git_object_missing` hold rests on the repository's objects (a fetch restores them
+ * under the same blob id), so it re-screens on every sync; a `page_write_failed` hold of a freeze fault (origin `freeze`,
+ * S-63) is re-tested by every sync until it has been held `HOLD_ATTEMPTS_NEEDS_HUMAN` times, so a transient fault clears.
*/
export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {
- return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict', 'page_identity_changed'].includes(record.code)
+ return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict', 'page_identity_changed', 'git_object_missing'].includes(record.code)
// #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.
|| (outOfAttemptsHold(record.code) && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)
|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())
@@ -562,7 +570,8 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re
|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)
|| (outOfAttemptsHold(record.code) && record.meta.stall?.gbrain_version !== VERSION)
// GBRA-130 A-6: an owner fault is the writer's, not the file's: an upgrade re-tests the path.
- || (record.code === 'page_write_failed' && record.meta.write_failure?.gbrain_version !== VERSION);
+ || (record.code === 'page_write_failed' && record.meta.write_failure?.gbrain_version !== VERSION)
+ || (record.code === 'page_write_failed' && record.meta.write_failure?.origin === 'freeze' && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN);
}
/**
@@ -692,6 +701,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
case 'page_write_failed': {
const failure = record.meta.write_failure;
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ // GBRA-133 S-63: a freeze fault threw before any request was admitted, so there is no receipt; the hold names the error.
+ if (failure?.origin === 'freeze') return { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#page_write_failed',
+ why: `Sync could not prepare ${record.path} (${failure.error_class ?? 'an unexpected error'}${failure.errno ? `, ${failure.errno}` : ''}; the hold message names it), so it held that file and the rest of the source kept syncing. `
+ + `The next syncs re-test it on their own; once it has been held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times, fix the file when the error names it, or report it with the gbrain version, then schedule the re-test.`,
+ verify };
return { argv: ['gbrain', 'write-request', '--', failure?.request_id ?? '<request_id>'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#page_write_failed',
why: `The write of ${record.path} failed the same way ${failure?.attempts ?? 'several'} times (${failure?.origin ?? failure?.code ?? 'an unclassified failure'}${failure?.errno ? `, SQLSTATE ${failure.errno}` : ''}${failure?.error_class ? `, ${failure.error_class}` : ''}), so sync held it and the rest of the source kept syncing. `
+ 'The receipt (read-only) names the error; report it with the gbrain version, or fix the file when the error names its content. An upgrade re-tests the path on its own.',
@@ -805,6 +819,16 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
user_message: `${record.path} nests YAML aliases in its frontmatter that expand past gbrain's size limit, so sync holds it and the rest of source ${source} keeps syncing. An older gbrain imported these bytes; this version refuses them on purpose. Reduce the alias nesting in its frontmatter (or write the values out), or remove the file, then commit and run gbrain sync --source ${source} --no-pull.`,
why: 'The alias bound (#7018) stops a few hundred bytes of nested anchors from expanding into gigabytes; it is intended, so the page keeps its last imported version until the file changes.',
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
+ case 'content_null_bytes':
+ return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),
+ user_message: `${record.path} holds NUL bytes (U+0000${record.meta.line !== undefined ? `, first on line ${record.meta.line}` : ''}), so sync holds it and the rest of source ${source} keeps syncing. A UTF-16 file (a Windows "Unicode" save) looks like this: save it as UTF-8. Otherwise remove the NUL bytes, or remove a binary file (or leave it out with sync.exclude), then commit and run gbrain sync --source ${source} --no-pull.`,
+ why: 'Page text is stored as UTF-8 without NUL bytes, so these bytes cannot be imported as they stand; the hold re-screens when the file changes.',
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
+ case 'git_object_missing':
+ return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),
+ user_message: `The Git object of ${record.path}${record.meta.blob_oid ? ` (blob ${record.meta.blob_oid})` : ''} is missing from the checkout of source ${source}, and its working-tree copy differs or is gone, so sync holds it and the rest of the source keeps syncing. Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then run gbrain sync --source ${source} --no-pull.`,
+ why: 'An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names; nothing is imported from a guess, and every sync re-tests the hold.',
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
case 'parser_regression':
return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index d1badd2df4..c41ab72d4b 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -33,6 +33,7 @@ import { preserveProtectedTakes } from './protected-takes.ts';
import { getWorktreeBinding } from './ownership.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { assertConfiguredSyncRoot, assertSyncEntryOrigin, readSyncFile, syncGit, syncRawHash, type SyncRename } from './sync-discovery.ts';
+import { directoryAt } from './sync-entry-fault.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, validateSyncAuthority, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import type { PreparedContentImport } from './prepared-import.ts';
@@ -717,7 +718,8 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
`sync.admission is not normal, so the deletion of ${row.slug} in ${row.source_id} published nothing; the page stays live and the next pass re-reads the level.`);
},
async () => {
- if (p.path !== null && !p.body_ref && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,
+ // GBRA-133 S-22: a deletion whose name became a directory has no file to compare.
+ if (p.path !== null && !p.body_ref && (p.kind === 'managed_sync_delete' && directoryAt(root, p.path) ? null : syncRawHash(root, p.path)) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,
`The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);
},
async () => {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 72299991cb..1a151ec3a2 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -54,6 +54,7 @@ import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { dependentHold, fileDriftHold, sharedOriginSurvivor, fileChangedAfterAdmission, headCommittedBytes, liveRevision, idempotentDeletionProof, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
import { faultPoint } from './fault-points.ts';
+import { directoryAt, freezeFaultHold, noteFrozen, nullBytesRefusal } from './sync-entry-fault.ts';
import { syncCursorOptions } from './sync-slices.ts';
import { pipelined } from '../page-state/transactions.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -321,7 +322,16 @@ function remember(snapshot: PageSnapshot | null | undefined, pending: Pending):
if (snapshot !== undefined) frozenSnapshots.set(pending, snapshot);
return pending;
}
-async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,
+/** GBRA-133 S-63: one entry whose freeze throws is held alone when holds are on (sync-entry-fault.ts); run-scoped faults and deliberate refusals still stop. */
+async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void, run: Parameters<typeof freezeEntryOnce>[4]): Promise<Pending | Held | Settled> {
+ const entry = cursor.entries[cursor.index];
+ try { const frozen = await freezeEntryOnce(engine, cursor, key, assertActive, run); noteFrozen(run.screen); return frozen; } catch (error) {
+ const hold = entry && run.screen && !cursor.companyPlan && !run.signal?.aborted ? freezeFaultHold(run.screen, entry, entry.slug!, entry.pageId ?? null, error, () => pinnedBlob(cursor, entry.path)) : null;
+ if (!hold) throw error;
+ return { hold };
+ }
+}
+async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,
run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal; embedDeferred?: boolean }): Promise<Pending | Held | Settled> {
assertActive();
const entry = cursor.entries[cursor.index];
@@ -364,7 +374,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
return { hold: await originFaultHold(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, entry, observed: snapshot, message: occupant.originFault.message }), overtaken: true };
}
let bytes: Buffer | null = null;
- try { bytes = readSyncFile(cursor.root, entry.path); }
+ try { bytes = entry.action === 'delete' && directoryAt(cursor.root, entry.path) ? null : readSyncFile(cursor.root, entry.path); } // GBRA-133 S-22: a directory is no file
catch (error) {
if (!isSyncReadBound(error)) { const held = holdsOn ? unreadableFileHold(entry, entry.slug!, entry.pageId ?? null, error, () => pinnedBlob(cursor, entry.path)) : null; if (held) return { hold: held }; throw error; } // GBRA-130 A-7
// Wave B: with segmented storage on, a Markdown file over the read bound is frozen by reference and streamed by its owner.
@@ -393,6 +403,8 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
assertActive();
} else content = imageBytes ? frozenImageIntent(imageBytes).content : entry.action === 'import' && !oversize && !bodyRef ? pinnedContent(cursor, entry) : null;
+ const nul = !screening && content !== null && !image ? nullBytesRefusal(entry.path, content) : null; // GBRA-133 S-39 with sync.holds=fail
+ if (nul) throw syncRunRefusal('content_null_bytes', 'A synced Markdown file holds NUL bytes.', retry, nul.message);
// #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a
// live checkout) are imported as HEAD has them; the pin..HEAD diff later re-imports the same bytes as a no-op.
// Uncommitted bytes keep the pinned content and reach the publication screen (idea from PR #6323).
@@ -1496,7 +1508,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
continue;
}
- const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'requestId' in frozen ? frozen : null; };
+ const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun).catch(() => null); return frozen && 'requestId' in frozen ? frozen : null; }; // GBRA-133 S-64: a follower's throw is raised by the single path, naming its own entry
if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000, ...whileHeld }, drainStartedAt, opts.onProgress,
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 348f8c6fb0..db1a0be2a0 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -35,6 +35,7 @@ import { listTrustAllowRules } from '../trust/allow-rules.ts';
import { readSyncContent, readSyncFile, syncGitPath, UNREADABLE_SYNC_FILE, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
import { pinnedWindowBlock, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';
+import { committedContentOrMissing, nullBytesRefusal } from './sync-entry-fault.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldCode, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';
import type { WriteRequest } from './model.ts';
@@ -91,7 +92,12 @@ export function driftBaselineContent(gitRoot: string, entry: Pick<SyncEntry, 'dr
/** The frozen import content of one entry (`readSyncContent`); a committed entry's pinned blob is read with the entries after it. */
export function pinnedContent(cursor: SyncDiscovery & { index: number }, entry: SyncEntry): string {
const content = entry.working ? null : readPinnedContent(cursor.gitRoot, cursor.target, syncGitPath(cursor, entry.path), upcomingGitPaths(cursor));
- return content ?? readSyncContent(cursor, entry);
+ if (content !== null) return content;
+ try { return readSyncContent(cursor, entry); } catch (error) {
+ // GBRA-133 S-33: a committed blob the repository lost reads from identical working-tree bytes, or is refused git_object_missing.
+ if (entry.working) throw error;
+ return committedContentOrMissing(cursor, entry, pinnedBlob(cursor, entry.path), error);
+ }
}
/**
@@ -328,6 +334,9 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor
return { ...held, meta: { ...held.meta, legacy_slugs: entry.legacySlugs } };
}
if (content === null) return null;
+ // GBRA-133 S-39: text holding NUL cannot be stored or carried in the write intent; only this file is held.
+ const nul = nullBytesRefusal(entry.path, content);
+ if (nul) return heldEntry(entry, slug, pageId, nul, content, blob);
// #6188: a fence Tier 1 rewrites is admitted (publication writes the normalized file back); with fences.normalize=false it is held.
const screen = await screenFrozenContent(await frozenImportScreenInput(engine, { ...input, content }, run), run);
if (screen.status === 'importable' && screen.fences?.fixes.length) input.onNormalized?.(screen.fences.fixes);
diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.ts
index 1964939d8e..19236a6ed9 100644
--- a/test/behavior-change-notice-6712-block.test.ts
+++ b/test/behavior-change-notice-6712-block.test.ts
@@ -12,7 +12,7 @@ import { join } from 'node:path';
import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';
const MARKER = '// #6712 PR 4b (the level-triggered sync pass';
-const ROWS = 24;
+const ROWS = 27;
const NOTICE_CAP = 2_000;
/** The array literal's row lines in order, and where the block's rows start and how many there are. */
diff --git a/test/e2e/sync-entry-faults-6712-postgres.test.ts b/test/e2e/sync-entry-faults-6712-postgres.test.ts
new file mode 100644
index 0000000000..d552ba16e1
--- /dev/null
+++ b/test/e2e/sync-entry-faults-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-entry-faults-6712.test.ts'));
diff --git a/test/sync-entry-faults-6712.test.ts b/test/sync-entry-faults-6712.test.ts
new file mode 100644
index 0000000000..b410b34536
--- /dev/null
+++ b/test/sync-entry-faults-6712.test.ts
@@ -0,0 +1,168 @@
+/**
+ * GBRA-133 (#6712 PR 4b lane F): one odd file never stops a managed source. Each case commits one odd input beside a
+ * healthy file, syncs, then commits another healthy file and syncs again.
+ *
+ * Protects (each red at ed7e8e017, where the source stopped on every rerun and `last_commit` froze):
+ * - S-39/S-44/S-53: a NUL byte in a Markdown file (and a UTF-16 save with a byte order mark) failed the admission insert
+ * with 22P05 (`storage_error`); it is held `content_null_bytes` naming the file and line, and with `sync.holds=fail`
+ * the run stops with that typed code instead of `storage_error`.
+ * - S-33: a committed file whose Git blob is gone imports from identical working-tree bytes, and is held
+ * `git_object_missing` when the working tree differs.
+ * - S-22: an imported file that became a directory (`notes/fd.md/x.md`) stopped the source with
+ * `page_identity_changed`; its page is deleted and the new file imports.
+ * - S-63: an unexpected throw while freezing one entry is held `page_write_failed` (origin `freeze`) and re-tested by
+ * the next sync, which imports the file once the fault is gone; a deliberate refusal still stops the run, and a run where
+ * most freezes throw is systemic and stops without holding (guards).
+ * - S-64: on Postgres, where bulk groups are on, the same throw in a group follower is held on the follower's own path,
+ * and with `sync.holds=fail` the run stops naming the follower (the group head's path before).
+ * The deliberate-refusal and systemic guards pass before and after.
+ *
+ * PGLite here; Postgres through test/e2e/sync-entry-faults-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\n\nThe body of ${title}.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/seed.md'), note('notes/seed')); writeFileSync(join(root, 'notes/fd.md'), note('notes/fd'));
+ commit(root, 'seed');
+};
+const live = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);
+const holds = async (engine: BrainEngine) => ((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? []);
+const atHead = async (engine: BrainEngine, root: string) => (await engine.executeRaw<{ c: string | null }>("SELECT last_commit AS c FROM sources WHERE id='default'"))[0]!.c === git(root, 'rev-parse', 'HEAD');
+const dropBlob = (root: string, path: string) => { const oid = git(root, 'rev-parse', `HEAD:${path}`); rmSync(join(root, '.git/objects', oid.slice(0, 2), oid.slice(2))); return oid; };
+/** The odd commit beside a healthy file, the sync, then a later healthy commit and its sync: the source keeps moving. */
+async function oddThenHealthy(engine: BrainEngine, root: string, odd: () => void, committed: () => void = () => {}) {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/ok.md'), note('notes/ok'));
+ odd(); commit(root, 'odd'); committed();
+ const first = await performManagedSync(engine, OPTS);
+ expect(await atHead(engine, root)).toBe(true);
+ writeFileSync(join(root, 'notes/ok2.md'), note('notes/ok2')); commit(root, 'ok2');
+ const second = await performManagedSync(engine, OPTS);
+ expect(second.status).toBe('synced');
+ expect(await atHead(engine, root)).toBe(true);
+ return first;
+}
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-133: one odd file never stops a managed source`, () => {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });
+
+ test('S-39: a NUL byte in a Markdown file is held content_null_bytes naming the file and line; the rest syncs', () => brain(async ({ engine, root }) => {
+ const first = await oddThenHealthy(engine, root, () => writeFileSync(join(root, 'notes/odd.md'), '---\ntitle: odd\n---\nfirst line\nbody\u0000here\n'));
+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/odd.md', 'content_null_bytes']]);
+ const [hold] = await holds(engine);
+ expect(hold).toMatchObject({ path: 'notes/odd.md', code: 'content_null_bytes', meta: { line: 5 } });
+ expect(hold!.message).toContain('notes/odd.md holds a NUL byte (U+0000) on line 5');
+ expect(await live(engine)).toEqual(['notes/fd', 'notes/ok', 'notes/ok2', 'notes/seed']);
+ }), 240_000);
+
+ test('S-53: a UTF-16 save with a byte order mark is held content_null_bytes and told to save as UTF-8', () => brain(async ({ engine, root }) => {
+ const first = await oddThenHealthy(engine, root, () => writeFileSync(join(root, 'notes/odd.md'), Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(note('notes/odd'), 'utf16le')])));
+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/odd.md', 'content_null_bytes']]);
+ expect((await holds(engine))[0]!.message).toContain('UTF-16');
+ expect(await live(engine)).toEqual(['notes/fd', 'notes/ok', 'notes/ok2', 'notes/seed']);
+ }), 240_000);
+
+ test('S-39 with sync.holds=fail: the run stops with the typed content_null_bytes refusal, never storage_error', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.setConfig('sync.holds', 'fail');
+ writeFileSync(join(root, 'notes/odd.md'), 'body\u0000here\n'); commit(root, 'odd');
+ await expect(performManagedSync(engine, OPTS)).rejects.toMatchObject({ code: 'content_null_bytes' });
+ }), 240_000);
+
+ test('S-33: a lost committed blob imports from identical working-tree bytes', () => brain(async ({ engine, root }) => {
+ const first = await oddThenHealthy(engine, root, () => writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')), () => dropBlob(root, 'notes/odd.md'));
+ expect(first.held ?? []).toEqual([]);
+ expect(await live(engine)).toEqual(['notes/fd', 'notes/odd', 'notes/ok', 'notes/ok2', 'notes/seed']);
+ }), 240_000);
+
+ test('S-33: a lost committed blob whose working-tree copy differs is held git_object_missing; the rest syncs', () => brain(async ({ engine, root }) => {
+ // Git itself cannot build a later tree while the index names the lost object, so the rerun (not a new commit) shows the source is not stopped.
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/ok.md'), note('notes/ok')); writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')); commit(root, 'odd');
+ const oid = dropBlob(root, 'notes/odd.md');
+ writeFileSync(join(root, 'notes/odd.md'), note('notes/odd edited'));
+ git(root, 'update-index', '--assume-unchanged', 'notes/odd.md');
+ const first = await performManagedSync(engine, OPTS);
+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/odd.md', 'git_object_missing']]);
+ expect(await atHead(engine, root)).toBe(true);
+ expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures');
+ const [hold] = await holds(engine);
+ expect(hold).toMatchObject({ code: 'git_object_missing', meta: { blob_oid: oid } });
+ expect(hold!.message).toContain('git fsck');
+ expect(await live(engine)).toEqual(['notes/fd', 'notes/ok', 'notes/seed']);
+ }), 240_000);
+
+ test('S-22: an imported file that became a directory deletes its page and imports the new file', () => brain(async ({ engine, root }) => {
+ const first = await oddThenHealthy(engine, root, () => { rmSync(join(root, 'notes/fd.md')); mkdirSync(join(root, 'notes/fd.md')); writeFileSync(join(root, 'notes/fd.md/x.md'), note('notes/x')); });
+ expect(first.held ?? []).toEqual([]);
+ expect(await live(engine)).toEqual(['notes/fd.md/x', 'notes/ok', 'notes/ok2', 'notes/seed']);
+ }), 240_000);
+
+ test('S-63/S-64: an unexpected throw while freezing one file is held page_write_failed on that file; the next sync re-tests and imports it', () => brain(async ({ engine, root }) => {
+ let failing = true;
+ installFaultHook((point, detail) => { if (failing && point === 'sync:after_freeze' && detail.path === 'notes/b.md') throw new TypeError('synthetic freeze fault'); });
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`));
+ commit(root, 'four');
+ // The CLI's bulk settings: on for Postgres (b is the first group's follower), off for PGLite.
+ const bulk = { ...OPTS, bulk: await resolveBulkSettings(engine, undefined) };
+ const first = await performManagedSync(engine, bulk);
+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/b.md', 'page_write_failed']]);
+ expect(await atHead(engine, root)).toBe(true);
+ const [hold] = await holds(engine);
+ expect(hold!.meta.write_failure).toMatchObject({ origin: 'freeze', error_class: 'TypeError', request_id: null });
+ expect(hold!.message).toContain('synthetic freeze fault');
+ expect(await live(engine)).toEqual(['notes/a', 'notes/c', 'notes/d', 'notes/fd', 'notes/seed']);
+ failing = false;
+ writeFileSync(join(root, 'notes/e.md'), note('notes/e')); commit(root, 'e');
+ expect((await performManagedSync(engine, bulk)).status).toBe('synced');
+ expect(await live(engine)).toEqual(['notes/a', 'notes/b', 'notes/c', 'notes/d', 'notes/e', 'notes/fd', 'notes/seed']);
+ expect(await holds(engine)).toEqual([]);
+ }), 240_000);
+
+ test('S-64 with sync.holds=fail: a group follower\'s throw stops the run naming the follower, not the group head', () => brain(async ({ engine, root }) => {
+ installFaultHook((point, detail) => { if (point === 'sync:after_freeze' && detail.path === 'notes/b.md') throw new TypeError('synthetic follower fault'); });
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.setConfig('sync.holds', 'fail');
+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`));
+ commit(root, 'four');
+ const failure = await performManagedSync(engine, { ...OPTS, bulk: await resolveBulkSettings(engine, undefined) }).then(() => null, (error: Error) => error.message);
+ expect(failure).toContain('path=notes/b.md');
+ expect(failure).toContain('synthetic follower fault');
+ }), 240_000);
+
+ test('S-63 guard: a deliberate refusal thrown while freezing still stops the run and holds nothing', () => brain(async ({ engine, root }) => {
+ installFaultHook((point, detail) => { if (point === 'sync:after_freeze' && detail.path === 'notes/b.md') throw opError('plan_stale', 'synthetic deliberate refusal', 'none'); });
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/b.md'), note('notes/b')); commit(root, 'b');
+ await expect(performManagedSync(engine, OPTS)).rejects.toMatchObject({ code: 'plan_stale' });
+ expect(await holds(engine)).toEqual([]);
+ }), 240_000);
+
+ test('S-63 guard: when most freezes of a run throw, the run is systemic and stops without holding every file', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ installFaultHook(point => { if (point === 'sync:after_freeze') throw new TypeError('synthetic systemic fault'); });
+ for (let i = 0; i < 8; i++) writeFileSync(join(root, `notes/n${i}.md`), note(`notes/n${i}`));
+ commit(root, 'eight');
+ await expect(performManagedSync(engine, OPTS)).rejects.toThrow('synthetic systemic fault');
+ expect((await holds(engine)).length).toBeLessThan(8);
+ }), 240_000);
+});