Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
repair file-drift --held: probe dx-native-1 (both engines), KEY_FILES, postgres arm
garrytana4ec501c45e8
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 7f7d4dd282..224893a1a3 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,7 +2,7 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses `source_changed` / detail `canonical_file_missing` with the route `canonicalDeletionState` picks from bounded filter-free Git plumbing (`missingFileRoute`: still committed at HEAD → commit the deletion or `gbrain repair ghost-pages`; gone from HEAD, or no Git or no commit → `gbrain repair file-drift --prefer database|file`). `readReconcileState(..., { fileGone })` instead returns an absent state for a recorded origin: empty preimage bytes, `raw_file_hash` pinned to `ABSENT_FILE_HASH` (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and `assertSoleFileClaim` run with `absent: true` (`file-claims.ts` `absentCanonicalPath`, so a candidate recording the same missing path still claims it). `reconcileReadOptions` derives `adoptSlugPath` and `fileGone` from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (`expectedBeforeHash: null`). Test: `test/repair-file-drift-deleted-6712.test.ts`.+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses `source_changed` / detail `canonical_file_missing` with the route `canonicalDeletionState` picks from bounded filter-free Git plumbing (`missingFileRoute`: still committed at HEAD → commit the deletion or `gbrain repair ghost-pages`; gone from HEAD, or no Git or no commit → `gbrain repair file-drift --prefer database|file`). `readReconcileState(..., { fileGone })` instead returns an absent state for a recorded origin: empty preimage bytes, `raw_file_hash` pinned to `ABSENT_FILE_HASH` (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and `assertSoleFileClaim` run with `absent: true` (`file-claims.ts` `absentCanonicalPath`, so a candidate recording the same missing path still claims it). `reconcileReadOptions` derives `adoptSlugPath` and `fileGone` from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (`expectedBeforeHash: null`). Test: `test/repair-file-drift-deleted-6712.test.ts`. `readDeletedDriftTarget` reads the deleted side of a held file that is present: a deleted page at the origin is `tombstone_edited` (id and revision), otherwise a `deleted` `sync-origin-deleted` marker is `purged_differs` (its value digested); a live claimant, a missing file, no deletion or bytes the marker held return `changed`.- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).@@ -24,7 +24,7 @@- `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). A purge of a shared-origin page refuses and names the soft delete. Tests: `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.+- `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`. Test: `test/repair-file-drift-held-6712.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/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex fec21bc9bb..304bc10f2d 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -16,7 +16,7 @@- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (`sync-group.ts` `dependencyKeys`, `freezeFollowers`' `taken`) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (`groupStep`, `promoteWindow`). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712). `WINDOW_CANCEL_MESSAGE` and `laneFaultCancelMessage` stay only so older receipts still read as legacy knock-ons. Test: `test/sync-group-member-order.test.ts`.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `sync-import-provenance` records (`recordSyncImportProvenance`, batched `recordSyncImportProvenances`) also carry `disk_sha256` / `disk_blob_oid` (the bytes the write left on disk), `revision` and `parser` (`syncImportParser`: `SYNC_IMPORT_PARSER_VERSION`, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `sync-import-provenance` records (`recordSyncImportProvenance`, batched `recordSyncImportProvenances`) also carry `disk_sha256` / `disk_blob_oid` (the bytes the write left on disk), `revision` and `parser` (`syncImportParser`: `SYNC_IMPORT_PARSER_VERSION`, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`. A `file_drift` hold's Decision is `meta.side` (`both`, `unknown`, `deleted`; `fileDriftSide` reads older holds' `sides`) and, for `deleted`, `meta.state` (`tombstone_edited`, `purged_differs`, `file_gone`); `gitHoldItem` lists both, and a deleted hold's fix (`deletedDriftFix`) previews `heldDriftPreviewArgv` for its path and names each option's `fileDriftActionVerb`.- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold (only while it is the `holdObservedAt` observation when the intent carries one, so a hold a newer sync wrote stays) and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. A Markdown import's preparation carries `importProvenance` (`SyncPreparedMutation`); its publication writes it in the publish transaction with the page id, `revision` and the disk half (`syncDiskProvenance` over the canonical writeback, else `syncDiskBytes`), and a no-op waiver writes the same record instead. The checkpoint (`applyManagedSyncCheckpoint`) keeps a repository-root source's pinned slug mode (`sync-slug-mode.ts`). Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md. An intent with `embedDeferred` (#6696) prepares as `noEmbed` whatever the cursor's stored options say.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex b57661367e..c8b6d76923 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -275,8 +275,7 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlaconst group = groups.get(key(target)) ?? { side: target.side, ...(target.state ? { state: target.state } : {}), count: 0 };group.count++; groups.set(key(target), group);}- const narrower = (group: { side: FileDriftSide; state?: FileDriftDeletedState }) => shellQuote([...heldDriftPreviewArgv(sourceId, group.side, group.state, opts.prefer),- ...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])]);+ const narrower = (group: { side: FileDriftSide; state?: FileDriftDeletedState }) => heldCommand(sourceId, group.side, group.state, opts.prefer, opts);const statusFix = readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] });if (!opts.side && groups.size > 1) {const listed = [...groups.entries()].map(([name, group]) => `${name}=${group.count}`).join(', ');@@ -289,11 +288,16 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanotSelected, legacy };}+/** #6712 PR 4b: the `--held` preview of one Decision, keeping the run's `--only` / `--skip` globs. */+function heldCommand(sourceId: string, side: FileDriftSide, state: FileDriftDeletedState | undefined, prefer: DriftSide, opts: Pick<RepairPlanOptions, 'only' | 'skip'>): string {+ const argv = heldDriftPreviewArgv(sourceId, side, state, prefer);+ return shellQuote([...argv.slice(0, -2), ...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob]), ...argv.slice(-2)]);+}+/** #6712 PR 4b: `--side deleted` without `--state` (or a held selection that is all one deleted state) names the state to resolve. */function stateRequired(sourceId: string, opts: RepairPlanOptions, states: readonly FileDriftDeletedState[]): OperationError {const prefer = opts.prefer ?? 'database';- const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];- const commands = states.map(state => `${shellQuote([...heldDriftPreviewArgv(sourceId, 'deleted', state, prefer), ...globs])} (${state}: --prefer ${prefer} ${fileDriftActionVerb('deleted', state, prefer)})`);+ const commands = states.map(state => `${heldCommand(sourceId, 'deleted', state, prefer, opts)} (--prefer ${prefer}: ${fileDriftActionVerb('deleted', state, prefer)})`);return opError('file_drift_state_required', 'Resolving held deleted-side file drift needs --state: --prefer file and --prefer database do opposite things in each state.',`Nothing was previewed. Name the state: ${commands.join('; ')}.`,{ fix: readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) });diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 78215bc04e..bc9eb5ed9f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -180,6 +180,7 @@ test/repair-failed-writes-conflict-6429.test.tstest/repair-failed-writes-drift-w411.test.tstest/repair-fences.test.tstest/repair-file-drift-deleted-6712.test.ts+test/repair-file-drift-held-6712.test.tstest/repair-frontmatter-keys-sweep-6454.test.tstest/repair-frontmatter.test.tstest/repair-receipt-compaction.test.tsdiff --git a/test/repair-file-drift-held-6712.test.ts b/test/repair-file-drift-held-6712.test.tsnew file mode 100644index 0000000000..cc4fdd48e3--- /dev/null+++ b/test/repair-file-drift-held-6712.test.ts@@ -0,0 +1,276 @@+/**+ * #6712 PR 4b (design v3.2 §4, probe dx-native-1): `gbrain repair file-drift --held --side <side> [--state <state>]`+ * resolves the source's held `file_drift` pages of one Decision.+ * - `--side deleted` without `--state` is refused (`file_drift_state_required`): in each deleted state --prefer file and+ * --prefer database do opposite things;+ * - a `--held` selection whose holds are several Decisions is refused (`file_drift_mixed_selection`) with the narrower+ * commands;+ * - each state's preview prints its action verb, and an apply per state does what the deleted-side table says:+ * tombstone_edited: database keeps the deletion and removes the file (a coordinated publication), file restores the page+ * and imports the file's bytes; purged_differs: database removes the file, file imports it as a new page and leaves the+ * deletion marker for sync to retire; file_gone: database recreates the file, file soft-deletes the page.+ * Real PGLite (and Postgres when DATABASE_URL is set) with a claimed canonical Git worktree and real files; no seams.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { gitBlobOid } from '../src/core/persistence/digest.ts';+import { SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass-row.ts';+import { gitHoldItem, readGitHold, writeGitHold, type FileDriftDeletedState, type FileDriftSide } from '../src/core/persistence/sync-holds.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const logger = { info() {}, warn() {}, error() {} };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;++for (const backend of testBackends()) describe(`#6712 PR 4b: repair file-drift --held --side/--state (${backend})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;++ beforeAll(async () => {+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;+ } else {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (closePostgres) await closePostgres(); else await engine.disconnect();+ });++ interface Fixture { root: string; sourceId: string; ctx: OperationContext; incarnation: string }+ async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6712-held-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `held6712-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await run({ root, sourceId, ctx, incarnation: source!.incarnation });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);+ rmSync(dir, { recursive: true, force: true });+ }+ }++ const put = (ctx: OperationContext, slug: string, body: string) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: page(slug, body), request_id: randomUUID() } });+ const snapshot = (sourceId: string, slug: string) => engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ const remove = async (ctx: OperationContext, sourceId: string, slug: string, purge = false) => submitPageMutation(ctx, { operation: 'delete_page',+ params: { slug, request_id: randomUUID(), expected_revision: (await snapshot(sourceId, slug))!.revision, ...(purge ? { purge: true } : {}) } });+ const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-q', '--allow-empty', '-m', message); };+ /** The `file_drift` hold sync writes for a Decision (design v3.2 §4): its side, and for a deleted side its state. */+ const hold = (f: Fixture, input: { path: string; slug: string | null; pageId: number | null; side: FileDriftSide; state?: FileDriftDeletedState; revision?: string }) =>+ engine.transaction(tx => writeGitHold(tx, { source_id: f.sourceId, incarnation: f.incarnation, path: input.path, source_path: input.path, slug: input.slug,+ page_id: input.pageId, code: 'file_drift', message: `${input.path} is held: file drift (${input.side}${input.state ? ` ${input.state}` : ''})`, upstream_version: null,+ observed_at: new Date().toISOString(), run_id: null, mode: 'managed',+ meta: { recovery_version: RECOVERY_VERSION, side: input.side, ...(input.state ? { state: input.state } : {}), ...(input.revision ? { page_revision: input.revision } : {}) } }));+ const run = async (sourceId: string, opts: { side?: string; state?: string; prefer: 'file' | 'database'; only?: string[]; expect?: string }) =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, sourceId),+ { explicit: true, sourceFlag: sourceId, held: true, prefer: opts.prefer, ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),+ ...(opts.only ? { only: opts.only } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });+ const refusal = async (promise: Promise<unknown>) => { try { await promise; } catch (error) { return error as OperationError; } throw new Error('expected a refusal'); };++ /** A soft-deleted page whose file then changed: the tombstone_edited Decision. */+ async function tombstoneEdited(f: Fixture, slug: string): Promise<{ path: string; pageId: number; revision: string }> {+ await put(f.ctx, slug, 'Before the delete.');+ commitAll(f.root, 'page');+ await remove(f.ctx, f.sourceId, slug);+ const path = `${slug}.md`;+ expect(existsSync(join(f.root, path))).toBe(false);+ writeFileSync(join(f.root, path), page(slug, 'Edited after the delete.'));+ const tombstone = (await snapshot(f.sourceId, slug))!;+ expect(tombstone.page.deleted_at).toBeTruthy();+ await hold(f, { path, slug, pageId: Number(tombstone.page.id), side: 'deleted', state: 'tombstone_edited', revision: tombstone.revision });+ return { path, pageId: Number(tombstone.page.id), revision: tombstone.revision };+ }+ /** A purged page whose file came back with other bytes: the purged_differs Decision, with the marker sync writes at purge. */+ async function purgedDiffers(f: Fixture, slug: string): Promise<{ path: string }> {+ await put(f.ctx, slug, 'What the brain held.');+ const path = `${slug}.md`;+ const held = readFileSync(join(f.root, path));+ await remove(f.ctx, f.sourceId, slug, true);+ expect(await snapshot(f.sourceId, slug)).toBeNull();+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,jsonb_build_array($3::text::jsonb))`,+ [SYNC_ORIGIN_DELETED_OP, `${f.sourceId}:${f.incarnation}:${path}`, JSON.stringify({ source_id: f.sourceId, incarnation: f.incarnation, kind: 'deleted',+ blob_oids: [gitBlobOid(held, 'sha1')], sha256: null, revision: null, page_id: null, at: new Date().toISOString() })]);+ writeFileSync(join(f.root, path), page(slug, 'A different file at the purged origin.'));+ await hold(f, { path, slug, pageId: null, side: 'deleted', state: 'purged_differs' });+ return { path };+ }+ /** A live page whose committed file is gone and whose page then changed: the file_gone Decision. */+ async function fileGone(f: Fixture, slug: string): Promise<{ path: string }> {+ await put(f.ctx, slug, 'The page.');+ commitAll(f.root, 'page');+ const path = `${slug}.md`;+ git(f.root, 'rm', '-q', '--', path); git(f.root, 'commit', '-q', '-m', 'remove');+ const live = (await snapshot(f.sourceId, slug))!;+ await hold(f, { path, slug, pageId: Number(live.page.id), side: 'deleted', state: 'file_gone', revision: live.revision });+ return { path };+ }+ const marker = async (f: Fixture, path: string) => (await engine.executeRaw('SELECT 1 FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',+ [SYNC_ORIGIN_DELETED_OP, `${f.sourceId}:${f.incarnation}:${path}`])).length > 0;++ test('--side deleted without --state is refused before anything is read, naming each state with its verb', () => fixture(async f => {+ const refused = await refusal(run(f.sourceId, { side: 'deleted', prefer: 'database' }));+ expect(refused.code).toBe('file_drift_state_required');+ for (const state of ['tombstone_edited', 'purged_differs', 'file_gone']) expect(refused.suggestion).toContain(`--held --side deleted --state ${state}`);+ expect(refused.suggestion).toContain('keep the deletion and remove the file');+ expect(refused.fix?.argv).toEqual(['gbrain', 'sources', 'status', f.sourceId, '--json']);+ expect((await refusal(run(f.sourceId, { state: 'file_gone', prefer: 'file' }))).code).toBe('invalid_params');+ expect((await refusal(run(f.sourceId, { side: 'both', state: 'file_gone', prefer: 'file' }))).code).toBe('invalid_params');+ }), 240_000);++ test('a held selection that mixes sides or states is refused with the narrower commands; one deleted state alone still needs --state', () => fixture(async f => {+ await put(f.ctx, 'notes/both', 'Live page.');+ await hold(f, { path: 'notes/both.md', slug: 'notes/both', pageId: Number((await snapshot(f.sourceId, 'notes/both'))!.page.id), side: 'both' });+ await tombstoneEdited(f, 'notes/tomb');+ await purgedDiffers(f, 'notes/purged');+ const mixed = await refusal(run(f.sourceId, { prefer: 'file' }));+ expect(mixed.code).toBe('file_drift_mixed_selection');+ expect(mixed.message).toContain('3 different Decisions');+ expect(mixed.suggestion).toContain(`gbrain repair file-drift --source ${f.sourceId} --held --side both --prefer file`);+ expect(mixed.suggestion).toContain('--held --side deleted --state tombstone_edited --prefer file');+ expect(mixed.suggestion).toContain('--held --side deleted --state purged_differs --prefer file');+ const states = await refusal(run(f.sourceId, { prefer: 'file', only: ['notes/tomb.md', 'notes/purged.md'] }));+ expect(states.code).toBe('file_drift_mixed_selection');+ const one = await refusal(run(f.sourceId, { prefer: 'file', only: ['notes/tomb.md'] }));+ expect(one.code).toBe('file_drift_state_required');+ expect(one.suggestion).toContain("--held --side deleted --state tombstone_edited --only notes/tomb.md --prefer file");+ expect(existsSync(join(f.root, 'notes/tomb.md'))).toBe(true);+ }), 240_000);++ test('tombstone_edited: --prefer database keeps the deletion and removes the file by a coordinated publication', () => fixture(async f => {+ const { path, revision } = await tombstoneEdited(f, 'notes/tomb');+ const preview = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'database' });+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/tomb', action: 'remove_file', state: 'tombstone_edited', verb: 'keep the deletion and remove the file' })]);+ expect(preview.listing).toEqual(expect.arrayContaining([expect.objectContaining({ detail: `keep the deletion and remove the file: ${path}` })]));+ expect(existsSync(join(f.root, path))).toBe(true);+ const applied = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'database', expect: preview.preview_hash! });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ expect(existsSync(join(f.root, path))).toBe(false);+ const after = (await snapshot(f.sourceId, 'notes/tomb'))!;+ expect(after.page.deleted_at).toBeTruthy();+ expect(after.revision).toBe(revision);+ expect(await readGitHold(engine, f.sourceId, f.incarnation, path)).toBeNull();+ const receipts = await engine.executeRaw<{ state: string; effects: number }>(`SELECT r.state, (SELECT count(*)::int FROM persistence_effects e WHERE e.request_id=r.id AND e.kind='git') AS effects+ FROM persistence_requests r WHERE r.source_id=$1 AND r.intent->>'kind'='managed_maintenance_file_drift_remove'`, [f.sourceId]);+ expect(receipts).toEqual([{ state: 'committed', effects: 1 }]);+ }), 240_000);++ test('tombstone_edited: --prefer file restores the page and imports the file\'s bytes', () => fixture(async f => {+ const { path } = await tombstoneEdited(f, 'notes/tomb');+ const preview = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'file' });+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/tomb', action: 'import_file', verb: 'restore and import' })]);+ expect((await snapshot(f.sourceId, 'notes/tomb'))!.page.deleted_at).toBeTruthy();+ const applied = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'file', expect: preview.preview_hash! });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ const after = (await snapshot(f.sourceId, 'notes/tomb'))!;+ expect(after.page.deleted_at).toBeFalsy();+ expect(after.page.compiled_truth).toContain('Edited after the delete.');+ expect(readFileSync(join(f.root, path), 'utf8')).toContain('Edited after the delete.');+ expect(await readGitHold(engine, f.sourceId, f.incarnation, path)).toBeNull();+ }), 240_000);++ test('tombstone_edited: a file edited after the preview is changed_since_preview and is not removed', () => fixture(async f => {+ const { path } = await tombstoneEdited(f, 'notes/tomb');+ const preview = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'database' });+ writeFileSync(join(f.root, path), page('notes/tomb', 'Edited again after the preview.'));+ const applied = await run(f.sourceId, { side: 'deleted', state: 'tombstone_edited', prefer: 'database', expect: preview.preview_hash! });+ expect(applied.outcomes).toEqual({ changed_since_preview: 1 });+ expect(readFileSync(join(f.root, path), 'utf8')).toContain('Edited again after the preview.');+ expect(await readGitHold(engine, f.sourceId, f.incarnation, path)).not.toBeNull();+ }), 240_000);++ test('purged_differs: --prefer database removes the file and leaves the deletion marker for sync to retire', () => fixture(async f => {+ const { path } = await purgedDiffers(f, 'notes/purged');+ const preview = await run(f.sourceId, { side: 'deleted', state: 'purged_differs', prefer: 'database' });+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/purged', action: 'remove_file', verb: 'remove the file' })]);+ const applied = await run(f.sourceId, { side: 'deleted', state: 'purged_differs', prefer: 'database', expect: preview.preview_hash! });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ expect(existsSync(join(f.root, path))).toBe(false);+ expect(await snapshot(f.sourceId, 'notes/purged')).toBeNull();+ expect(await marker(f, path)).toBe(true);+ expect(await readGitHold(engine, f.sourceId, f.incarnation, path)).toBeNull();+ }), 240_000);++ test('purged_differs: --prefer file imports the file as a new page and leaves the marker for the pass to retire', () => fixture(async f => {+ const { path } = await purgedDiffers(f, 'notes/purged');+ const preview = await run(f.sourceId, { side: 'deleted', state: 'purged_differs', prefer: 'file' });+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/purged', action: 'import_file', verb: 'import as a new page' })]);+ const applied = await run(f.sourceId, { side: 'deleted', state: 'purged_differs', prefer: 'file', expect: preview.preview_hash! });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ const after = (await snapshot(f.sourceId, 'notes/purged'))!;+ expect(after.page.deleted_at).toBeFalsy();+ expect(after.page.source_path).toBe(path);+ expect(after.page.compiled_truth).toContain('A different file at the purged origin.');+ expect(await marker(f, path)).toBe(true);+ expect(await readGitHold(engine, f.sourceId, f.incarnation, path)).toBeNull();+ }), 240_000);++ test('file_gone: --prefer database recreates the file, --prefer file soft-deletes the page', () => fixture(async f => {+ const { path } = await fileGone(f, 'notes/gone');+ const recreate = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'database' });+ expect(recreate.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/gone', action: 'recreate_file', verb: 'recreate the file' })]);+ const soft = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'file' });+ expect(soft.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/gone', action: 'soft_delete', verb: 'soft-delete the page' })]);+ const applied = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'database', expect: recreate.preview_hash! });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ expect(readFileSync(join(f.root, path), 'utf8')).toContain('The page.');++ const second = await fileGone(f, 'notes/drop');+ const drop = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'file', only: [second.path] });+ const dropped = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'file', only: [second.path], expect: drop.preview_hash! });+ expect(dropped.outcomes).toEqual({ repaired: 1 });+ expect((await snapshot(f.sourceId, 'notes/drop'))!.page.deleted_at).toBeTruthy();+ }), 240_000);+});++test('a deleted-side file_drift hold lists its side and state, and its Decision names each option with its verb', () => {+ const base = { source_id: 'alpha', incarnation: 'i', path: 'notes/a.md', source_path: 'notes/a.md', slug: 'notes/a', page_id: 7, code: 'file_drift' as const,+ message: 'held', upstream_version: null, observed_at: 't', held_at: 't', updated_at: 't', run_id: null, mode: 'managed' as const, version: 1 as const };+ const tomb = gitHoldItem({ ...base, meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'tombstone_edited', page_revision: 'r1' } });+ expect(tomb).toMatchObject({ side: 'deleted', state: 'tombstone_edited' });+ expect(tomb.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'alpha', '--held', '--side', 'deleted', '--state', 'tombstone_edited', '--only', 'notes/a.md', '--prefer', 'database']);+ expect(tomb.fix.why).toContain('keep the deletion and remove the file');+ expect(tomb.fix.why).toContain('restore and import');+ const purged = gitHoldItem({ ...base, page_id: null, meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'purged_differs' } });+ expect(purged.fix.why).toContain('remove the file');+ expect(purged.fix.why).toContain('import as a new page');+ const gone = gitHoldItem({ ...base, meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'file_gone' } });+ expect(gone.fix.why).toContain('recreate the file');+ expect(gone.fix.why).toContain('soft-delete the page');+ const legacy = gitHoldItem({ ...base, meta: { recovery_version: RECOVERY_VERSION, sides: 'both' } });+ expect(legacy).toMatchObject({ side: 'both' });+ expect(legacy).not.toHaveProperty('state');+ expect(gitHoldItem({ ...base, meta: { recovery_version: RECOVERY_VERSION, sides: 'database' } })).not.toHaveProperty('side');+});