Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): file wins keeps the file's bytes and appends only protected parts

garrytane64e9b65c569
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 2a16e55cd0..d0fba1098a 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -34,7 +34,7 @@ See [generations](generations.md).
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). An owner purge of a shared-origin page refuses and names the soft delete (the retention purge for a tombstone). #7311: the retention purge of a shared-origin tombstone is database-only like an `origin_twin` page's (`sharedRetention`: no file target, applied with `source_path`/`source_uri` forgotten, so no deletion marker names the survivor's file); `validate` re-runs the census, and a changed one refuses `revision_conflict` (`sharedTombstoneChanged`, a purge deferral), so the next run takes the normal path. Tests: `test/purge-shared-origin-tombstone-7311.test.ts` (Postgres: `test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts`), `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).
-- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`. A held page whose page and file agree (`liveFileDrift` reason `agrees`) is a `ReleasePage` (`release_hold`): its apply re-checks the pinned page revision and file hash, then schedules a re-screen of that one held path (`requestGitHoldRetry`, as `sources retry-held` does), and the next sync releases it. A page with no file origin (`recordsNoFileOrigin` in `unbound-pages.ts`: no source path and no `file:` source URI) adopts its slug-path file, which `slugPathFile` resolves to the spelling sync imports as the slug (`README.md` for `readme`), as `prepareFileTarget` and `liveFileDrift` do. Test: `test/sync-holds-wave-gbra133.test.ts`.
+- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`. GBRA-133: an agreeing hold is a `ReleasePage` (`release_hold`; apply re-checks the pins, then `requestGitHoldRetry` for its path); a page with no file origin (`recordsNoFileOrigin`) adopts `slugPathFile` (the spelling sync imports); file wins writes `fileWinsContent` (file bytes plus appended protected keys and timeline rows) or refuses `file_wins_rewrite`. Test: `test/sync-holds-wave-gbra133.test.ts`.
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index ba0b140410..a34471e320 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1547,6 +1547,16 @@ Reasons: `symlink_in_repo`, `symlink_outside_root`, `symlink_dangling`, `symlink
More: [docs/guides/write-refusals.md#file_unreadable](../../docs/guides/write-refusals.md#file_unreadable)
+### file_wins_rewrite
+
+<a id="file_wins_rewrite"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain repair file-drift --prefer file refused a page because keeping its file would need a full re-render of the file, not only appended protected parts; nothing was written. | File wins keeps the canonical file's bytes and adds only what reconcile's protections keep from the database: protected frontmatter keys the file lacks and database-only timeline rows, appended. A result that also changes a value, a tag, the title or the body would re-render the whole file (keys reordered, lists re-emitted, rules and headings rewritten), which is not the file winning. | Show the user the page's exceptions in the preview. Commit the database-only differences into the file through the door (gbrain git commit-push) and preview again, or preview --prefer database if the database copy should win. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#file_wins_rewrite](../../docs/guides/write-refusals.md#file_wins_rewrite)
+
### fix_not_writable
<a id="fix_not_writable"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index b82138ca89..147b21056b 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2450,6 +2450,11 @@ the two `--prefer` values do opposite things in each state.
| `purged_differs` | Removes the file. | Imports the file as a new page. |
| `file_gone` | Recreates the file from the page. | Soft-deletes the page (the mass-delete valve applies). |
+`--prefer file` keeps the file's bytes: it adds only protected frontmatter keys the
+file lacks and database-only timeline rows, and refuses
+[`file_wins_rewrite`](write-refusals.md#file_wins_rewrite) when the result
+would change anything else.
+
A held page whose page and file agree now is listed `release_hold` under
either `--prefer`: its apply writes nothing to the page or the file, and only
asks the next sync to re-screen the file, which releases the hold. A page with
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 34ca15cc5c..4a91db9960 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -229,6 +229,7 @@ with each file and fix the ones that need no guessing."*
| <a id="rename_reconcile_failed"></a>`rename_reconcile_failed` | Classic sync (GBRA-133 S-67): a rename fell back to importing the new file, and removing the page of the old name then failed with an unexpected error (the hold records its class and code, never its message). The old page was kept and may duplicate the new one; the rest of the source keeps syncing. A transient database error and the reconcile's own "staleness unprovable" verdict still record the `<rename:…>` marker, which a later run converges. | Ask the user before `gbrain sync --source <source> --full --no-pull`: the full walk removes pages whose file is gone after checking each one (it re-reads the whole source). Or remove the old page with `gbrain delete --source <source> -- <slug>` (recoverable for 72 h). |
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. |
+| <a id="file_wins_rewrite"></a>`file_wins_rewrite` | `gbrain repair file-drift --prefer file` keeps the canonical file's bytes and adds only the protected parts reconcile keeps from the database: protected frontmatter keys the file lacks (inserted before the closing `---`) and database-only timeline rows (appended to the file's timeline, with a `<!-- timeline -->` line above a bare `## Timeline` heading so they stay in it). When the resolved page also differs in anything else (a value, a tag, the title, the body), keeping the file would mean re-rendering all of it, so the preview refuses the page and nothing is written. | Show the user the page's differences. Commit them into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win. |
| <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. |
| <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880). `put_page`, `edit_page`, `capture` and `ingest_capture` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |
| <a id="parser_regression"></a>`parser_regression` | A file whose exact bytes imported under an earlier gbrain is now refused. It is held and the rest of the source syncs (the default; `GBRAIN_SYNC_PARSER_REGRESSION=stop` stops the run instead). This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 624e962c17..3973331e6e 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -299,6 +299,7 @@ export const CODES = {
file_drift_state_required: { class: 'caller', summary: "gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed.", why: "In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
file_unreadable: { class: 'caller', retryable: false, reasons: ['symlink_in_repo', 'symlink_outside_root', 'symlink_dangling', 'symlink_loop', 'permission_denied', 'not_regular_file'], summary: "Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced.", why: "Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run.", docs: 'docs/guides/write-refusals.md#file_unreadable', suggestion: 'Replace the symlink with the regular file (or delete it), make the file readable to the account gbrain runs as, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it.' },
+ file_wins_rewrite: { class: 'caller', retryable: false, actor: 'user', summary: "gbrain repair file-drift --prefer file refused a page because keeping its file would need a full re-render of the file, not only appended protected parts; nothing was written.", why: "File wins keeps the canonical file's bytes and adds only what reconcile's protections keep from the database: protected frontmatter keys the file lacks and database-only timeline rows, appended. A result that also changes a value, a tag, the title or the body would re-render the whole file (keys reordered, lists re-emitted, rules and headings rewritten), which is not the file winning.", docs: 'docs/guides/write-refusals.md#file_wins_rewrite', suggestion: 'Show the user the page\'s exceptions in the preview. Commit the database-only differences into the file through the door (gbrain git commit-push) and preview again, or preview --prefer database if the database copy should win.' },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
diff --git a/src/core/persistence/file-wins-content.ts b/src/core/persistence/file-wins-content.ts
new file mode 100644
index 0000000000..a5bd78739c
--- /dev/null
+++ b/src/core/persistence/file-wins-content.ts
@@ -0,0 +1,68 @@
+/**
+ * GBRA-133: the canonical file a file-wins reconcile (`repair file-drift --prefer file`, `keep_file_bytes`) leaves. The file
+ * keeps its own bytes. Only what reconcile's protections kept from the database is added: protected frontmatter keys the file
+ * lacks (inserted before the closing `---`) and database-only timeline rows (appended after the file's timeline, at the end of
+ * the file; a timeline the file keeps under a bare `## Timeline` heading gets the `<!-- timeline -->` sentinel above it, so the
+ * appended rows stay in it). Anything else the result changes (a key's value, a tag, the title, the body, a timeline that is not
+ * an extension of the file's) would need a re-render that reorders keys, re-emits lists and rewrites the body, so it refuses.
+ */
+import type { ParsedPage } from '../import-file.ts';
+import { opError } from '../ops/contract.ts';
+import { dumpFrontmatterYaml } from '../data-frontmatter.ts';
+import { digest } from './digest.ts';
+import { protectedReconcileKey } from './reconcile-merge.ts';
+
+const SENTINEL = '<!-- timeline -->';
+
+/** The added protected keys and timeline text, or null when the result changes the file anywhere else. */
+function appendedParts(file: ParsedPage, result: ParsedPage): { keys: Record<string, unknown>; timeline: string } | null {
+ if (file.type !== result.type || file.title !== result.title || file.compiled_truth !== result.compiled_truth) return null;
+ if (digest([...file.tags].sort()) !== digest([...result.tags].sort())) return null;
+ for (const key of Object.keys(file.frontmatter)) if (digest(file.frontmatter[key] ?? null) !== digest(result.frontmatter[key] ?? null)) return null;
+ const keys: Record<string, unknown> = {};
+ for (const key of Object.keys(result.frontmatter)) {
+ if (Object.hasOwn(file.frontmatter, key)) continue;
+ if (!protectedReconcileKey(key)) return null;
+ keys[key] = result.frontmatter[key];
+ }
+ const base = file.timeline.trimEnd();
+ if (!result.timeline.startsWith(base)) return null;
+ return { keys, timeline: result.timeline.slice(base.length) };
+}
+
+/** The file with the protected keys inserted before its closing `---`, or null when it has no frontmatter block to extend. */
+function withKeys(raw: string, keys: Record<string, unknown>): string | null {
+ if (!Object.keys(keys).length) return raw;
+ const close = raw.startsWith('---\n') ? raw.indexOf('\n---', 3) : -1;
+ if (close === -1 || (close + 4 < raw.length && raw[close + 4] !== '\n')) return null;
+ return `${raw.slice(0, close + 1)}${dumpFrontmatterYaml(keys).trimEnd()}\n${raw.slice(close + 1)}`;
+}
+
+/** Each way to append the timeline text, in order of fewer touched bytes. */
+function withTimeline(text: string, fileTimeline: string, appended: string): string[] {
+ if (!appended) return [text];
+ const body = text.replace(/\n+$/, '');
+ if (!fileTimeline.trim()) return [`${body}\n\n${SENTINEL}\n\n${appended.replace(/^\n+/, '')}\n`];
+ const out = [`${body}${appended}\n`];
+ const at = body.lastIndexOf(fileTimeline.trimEnd());
+ if (at > 0 && !body.includes(SENTINEL)) out.push(`${body.slice(0, at)}${SENTINEL}\n\n${body.slice(at)}${appended}\n`);
+ return out;
+}
+
+/**
+ * The file bytes with the protected parts appended, verified by reading them back (`reparse`) to exactly `result`.
+ * Throws `file_wins_rewrite` when no such append reaches the result.
+ */
+export function fileWinsContent(raw: string, file: ParsedPage, result: ParsedPage, reparse: (text: string) => ParsedPage,
+ page: { sourceId: string; slug: string }): string {
+ if (digest(file) === digest(result)) return raw;
+ const parts = raw.includes('\r') ? null : appendedParts(file, result);
+ const keyed = parts ? withKeys(raw, parts.keys) : null;
+ for (const text of keyed === null ? [] : withTimeline(keyed, file.timeline, parts!.timeline)) {
+ try { if (digest(reparse(text)) === digest(result)) return text; } catch { /* the next candidate, or the refusal below */ }
+ }
+ throw opError('file_wins_rewrite', 'File wins would rewrite the canonical file beyond the protected parts it keeps.',
+ `Nothing was written. The resolved result of ${page.slug} in '${page.sourceId}' differs from its file in more than appended protected frontmatter keys and database-only timeline rows, so keeping the file would need a full re-render of it. `
+ + 'Commit the differences into the file through the door (gbrain git commit-push), or preview --prefer database, then preview again.',
+ { detail: 'file_wins_rewrite' });
+}
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 848937fd6d..7813bc6fa9 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -22,7 +22,8 @@ import { preserveProtectedTakes } from './protected-takes.ts';
import { digest, sha256 } from './digest.ts';
import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reconcile-merge.ts';
import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
-import { ABSENT_FILE_HASH, assertReconcilePins, readReconcileState, reconcileFileReading, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
+import { fileWinsContent } from './file-wins-content.ts';
+import { ABSENT_FILE_HASH, assertReconcilePins, readCanonicalFileText, readReconcileState, reconcileFileReading, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
import { assertAutoDecisions } from './reconcile-additive.ts';
import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
@@ -155,12 +156,13 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);
const prepared = await prepareReconcileResult(engine, state, artifact.decisions);
if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('canonical policy result changed');
- // #6643: a request that asks to keep the file's bytes (repair file-drift --prefer file) leaves a file that already parses to the
- // reviewed result as it is; any other difference (a protected key, a tag union, a kept private row) renders the result.
+ // #6643 / GBRA-133: a request that asks to keep the file's bytes (repair file-drift --prefer file) leaves the file as it is plus
+ // the protected parts reconcile kept (appended keys and timeline rows), and refuses any result that would re-render the file.
// #6712 wave: a preview that observed the file absent recreates it from the page and expects no bytes there.
const absent = state.pins.raw_file_hash === ABSENT_FILE_HASH;
- const keep = !absent && row.intent.keep_file_bytes === true && digest(reconcileCanonical(state.file, state.file.tags)) === artifact.result_digest;
- const content = keep ? state.raw.toString('utf8') : serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);
+ const content = !absent && row.intent.keep_file_bytes === true
+ ? fileWinsContent(state.raw.toString('utf8'), state.file, prepared.result, text => readCanonicalFileText(state, row.slug, text), { sourceId: row.source_id, slug: row.slug })
+ : serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);
const ready = prepared.ready;
return {
observedRevision: state.snapshot.revision, trust: await ownerImportTrust(engine, row, prepared.result.frontmatter, state.path),
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 2b9b12e4ac..469fc669f3 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -382,6 +382,13 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {
* inferring import wrote the row); a row imported without inference (`gbrain reindex` on an unmanaged brain) is
* compared with the raw bytes. An inferred `type:` is not one the file declared: the caller keeps the stored type.
*/
+/** GBRA-133: a canonical file's text as `readReconcileState` reads it (the reconcile canonical form of the page it imports). */
+export function readCanonicalFileText(state: Pick<ReconcileState, 'importPath' | 'snapshot'>, slug: string, text: string): ParsedPage {
+ const reading = reconcileFileReading(text, state.importPath, state.snapshot.page);
+ const parsed = parseMarkdown(reading.content, `${slug}.md`, { validate: true, expectedSlug: slug });
+ alignWithStored(parsed, state.snapshot.page, reading.inferred);
+ return reconcileCanonical(parsed, parsed.tags);
+}
export function reconcileFileReading(text: string, sourcePath: string, stored: { frontmatter?: Record<string, unknown> | null }): { content: string; inferred: boolean } {
const reading = readCanonicalAsImported(text, sourcePath);
if (!reading.inferred) return reading;
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 13b4e6d1ef..a3ef4bc78d 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -71,7 +71,8 @@ import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, sa
import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
import { auditDriftConflicts, DRIFT_CLASSES, driftClass, liveFileDrift, type DriftClass } from '../persistence/drift-conflicts.ts';
import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type ReconcileDecision } from '../persistence/reconcile-merge.ts';
-import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readDeletedDriftTarget, readReconcileState, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { fileWinsContent } from '../persistence/file-wins-content.ts';
+import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readCanonicalFileText, readDeletedDriftTarget, readReconcileState, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
import { clearGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, requestGitHoldRetry, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';
import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
@@ -497,6 +498,8 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, sl
const prepared = await prepareReconcileResult(engine, state, decisions);
if (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',
`Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);
+ // GBRA-133: file wins keeps the file's bytes and only appends protected parts; a result that needs a re-render refuses here.
+ if (prefer === 'file' && !opts.fileGone) fileWinsContent(state.raw.toString('utf8'), state.file, prepared.result, text => readCanonicalFileText(state, slug, text), { sourceId, slug });
const preview: ReconcileArtifact = { format_version: 1, preview_id: randomUUID(), preconditions: state.pins,
preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };
diff --git a/test/sync-holds-wave-gbra133.test.ts b/test/sync-holds-wave-gbra133.test.ts
index 1cb1b9c39a..3dc2537883 100644
--- a/test/sync-holds-wave-gbra133.test.ts
+++ b/test/sync-holds-wave-gbra133.test.ts
@@ -11,12 +11,17 @@
* and nothing re-screened one whose page did not move. Such a sync re-screens it now, and the `--held` preview lists an
* agreeing hold as `release_hold`, whose apply schedules its re-screen. A hold that still differs stays held.
*
+ * 4. File wins (`--prefer file`) on a page whose database copy keeps protected parts (a database-only timeline row, a
+ * protected frontmatter key) rewrote the whole file through the serializer: keys reordered, lists re-emitted, the body
+ * re-rendered. It now keeps the file's bytes and appends only the protected parts; a result that would need any other
+ * change (here a database-only tag) refuses `file_wins_rewrite` in the preview and writes nothing.
+ *
* Holds exist only where sync imports a Git checkout, so there is no repo-less arm.
*/
import { expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
@@ -67,6 +72,25 @@ async function heldUnknownPage(engine: BrainEngine, root: string): Promise<void>
expect(await holds(engine)).toEqual(['notes/n0.md file_drift unknown']);
}
+/** A hand-written file: keys in the author's order, a block list, a rule under a text line, a bare timeline heading. */
+const HAND_WRITTEN = '---\ntitle: Alpha Example\ntype: concept\naliases:\n - alpha-one\n - alpha-two\nstatus: active\n---\n\n'
+ + 'Intro paragraph.\n\nSection text above a rule\n---\n\nAfter the rule.\n\n## Timeline\n\n- 2026-01-01: First event.\n';
+
+/** notes/alpha as an older gbrain left it, with a database-only timeline row and protected key, then a commit edits its file: held unknown. */
+async function heldProtectedPage(engine: BrainEngine, root: string): Promise<void> {
+ writeFileSync(join(root, 'notes/alpha.md'), HAND_WRITTEN); commitAll(root, 'alpha');
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await coordinated(engine, `DELETE FROM op_checkpoints WHERE op='sync-import-provenance'
+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug='notes/alpha')`);
+ await coordinated(engine, `UPDATE pages SET frontmatter = frontmatter || '{"embed_skip": true}'::jsonb, knowledge_revision=$1::uuid, revision_write_request_id=NULL
+ WHERE source_id='default' AND slug='notes/alpha'`, [randomUUID()]);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTimelineEntry('notes/alpha',
+ { date: '2026-02-01', summary: 'A database-only event.', source: 'example', detail: '' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ writeFileSync(join(root, 'notes/alpha.md'), HAND_WRITTEN.replace('Intro paragraph.', 'Intro paragraph, edited.')); commitAll(root, 'edit alpha');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/alpha.md file_drift unknown']);
+}
+
for (const backend of testBackends()) {
const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
const setup = ({ root }: { root: string }) => {
@@ -138,4 +162,30 @@ for (const backend of testBackends()) {
expect(await holds(engine)).toEqual([]);
expect((await origin(engine, 'notes/n0'))?.source_path).toBe('notes/n0.md');
}, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: file wins keeps the file's bytes and appends only the protected key and the database-only timeline row`, () => managedBrain(async ({ engine, root }) => {
+ await heldProtectedPage(engine, root);
+ const before = readFileSync(join(root, 'notes/alpha.md'), 'utf8');
+ const preview = await heldPreview(engine, 'file');
+ expect(listing(preview)).toEqual(['default:notes/alpha prefer_file']);
+ expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });
+ const after = readFileSync(join(root, 'notes/alpha.md'), 'utf8');
+ const [head, body] = [before.slice(0, before.indexOf('\n---\n', 3) + 1), before.slice(before.indexOf('\n---\n', 3) + 1)];
+ const timelineAt = body.indexOf('## Timeline');
+ expect(after.startsWith(`${head}embed_skip: true\n${body.slice(0, timelineAt)}<!-- timeline -->\n\n${body.slice(timelineAt)}`)).toBe(true);
+ expect(after.slice(before.length + 'embed_skip: true\n<!-- timeline -->\n\n'.length)).toMatch(/^<!-- gbrain:materialized v1 [0-9a-f]+ -->\n- \*\*2026-02-01\*\* \| example — A database-only event\.\n$/);
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ }, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: file wins refuses file_wins_rewrite in the preview when keeping the file would need a re-render, and writes nothing`, () => managedBrain(async ({ engine, root }) => {
+ await heldProtectedPage(engine, root);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTag('notes/alpha', 'database-only-tag', { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ const before = readFileSync(join(root, 'notes/alpha.md'), 'utf8');
+ const preview = await heldPreview(engine, 'file');
+ expect((preview as { listing?: Array<{ class: string; detail: string }> }).listing?.map(row => `${row.class} ${row.detail.split(':')[0]}`)).toEqual(['refused file_wins_rewrite']);
+ expect(preview.details?.pages ?? []).toEqual([]);
+ expect(readFileSync(join(root, 'notes/alpha.md'), 'utf8')).toBe(before);
+ expect(await holds(engine)).toEqual(['notes/alpha.md file_drift unknown']);
+ }, { databaseUrl, setup }), 180_000);
}