Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Read-only mirrors: "keep it deleted" now sticks until upstream edits the file again (#9607)
Garry Tan9bdc2628cf6b
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 1c1d2382b0..b532bc81da 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -201,14 +201,16 @@ jobs:# file; the PGLite arm also runs in the unit lane). The list is test/postgres-unit-arms.txt;# scripts/check-postgres-lane-coverage.ts fails a new DATABASE_URL-gated arm# until it is listed there or wrapped in a test/e2e registerPostgresTests- # file. The twenty-two shards (ARM_SHARDS in scripts/postgres-unit-arms.ts) are+ # file. The twenty-three shards (ARM_SHARDS in scripts/postgres-unit-arms.ts) are# balanced by measured runtime (scripts/postgres-arm-weights.json, mined# from this job's ARM_FILE lines). Each job runs two files at a time, each# worker against its own PostgreSQL service; a shard's two-worker makespan,# doubled for a slow runner, must end a minute inside the step's 20 minutes# (ARM_SHARD_BUDGET_MS, 570 s). On 2026-11-14 (gbrain#9342) the list filled# 21 shards to the budget, so one more arm file put 19 shards over; 22 shards- # bring the largest to 545.6 s. The job runs both arms of+ # brought the largest to 545.6 s. On 2026-11-17 (gbrain#9607) the list filled+ # 22 shards to 99.8% of the budget and 13 went over; 23 shards bring the+ # largest to 546.7 s. The job runs both arms of# every listed file: the unit shards skip *.slow.test.ts, so this lane is the# only GitHub lane that runs the PGLite side of the listed slow# testBackends() suites.@@ -216,14 +218,14 @@ jobs:# pull request (cheap tier) runs only the crash robot and convergence here. The# full-ci dispatch on its head, every push and the nightly run this lane.unit-postgres-arms:- name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/22 / Bun ${{ matrix.bun }}+ name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/23 / Bun ${{ matrix.bun }}if: ${{ github.event_name != 'pull_request' }}runs-on: ubicloud-standard-4-ubuntu-2404timeout-minutes: 30strategy:fail-fast: falsematrix:- shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]+ shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]bun: ['1.4.4']# Event parity: every event, pull requests and merge-queue runs# included, runs every supported Bun version (docs/TESTING.md#event-parity).@@ -278,7 +280,7 @@ jobs:GBRAIN_TEST_ALLOW_DATABASE_URL: '1'GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receiptsGBRAIN_TEST_RECEIPT_LANE: pg-arms-bun-${{ matrix.bun }}- run: bun scripts/postgres-unit-arms.ts run ${{ matrix.shard }} 22+ run: bun scripts/postgres-unit-arms.ts run ${{ matrix.shard }} 23- name: Upload receiptsif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4diff --git a/behavior-changes.d/mirror_keep_deleted.md b/behavior-changes.d/mirror_keep_deleted.mdnew file mode 100644index 0000000000..07148fb72c--- /dev/null+++ b/behavior-changes.d/mirror_keep_deleted.md@@ -0,0 +1,4 @@+---+kind: fix+---+On a read-only mirror source, keeping the deletion of a page whose file the upstream edited after you deleted it now sticks. gbrain repair file-drift --held --side deleted --state tombstone_edited --prefer database lists such a page keep_deleted instead of removing a file gbrain never writes, and its apply (the user's yes on the preview hash) records the decision on the hold. The hold stays and is reported carried with reason mirror_keep_deleted, with needs_human false, in gbrain sources status, gbrain sync status and doctor, so it no longer asks again on every re-check; a re-check of the same file bytes keeps the decision. A new upstream edit of the file or gbrain restore of the page makes it ask again, and purging the deleted page moves the decision to the purged_differs hold. Nothing is deleted, restored or written into the mirror. Writable sources behave as before.diff --git a/changelog.d/mirror-keep-deleted.md b/changelog.d/mirror-keep-deleted.mdnew file mode 100644index 0000000000..2c3b67d908--- /dev/null+++ b/changelog.d/mirror-keep-deleted.md@@ -0,0 +1,6 @@+**Keeping a deletion on a read-only mirror now sticks: the held page stops asking again on every re-check.**++<!-- behavior-change: mirror_keep_deleted -->++### Fixed+- On a read-only mirror, `gbrain repair file-drift --held --side deleted --state tombstone_edited --prefer database` lists each page `keep_deleted` and, once the user agrees to the preview's hash, records the decision on its hold instead of trying to remove a file gbrain never writes. The hold stays, reported carried with reason `mirror_keep_deleted` and `needs_human: false` in `gbrain sources status`, `gbrain sync status` and doctor. A re-check of the same file bytes keeps the decision; a new upstream edit or `gbrain restore` asks again; a purge moves it to the `purged_differs` hold, where it stays while the file bytes are the same. The caller's CLI grant must cover the page, as for every other file-drift repair. Nothing is deleted, restored or written into the mirror, and writable sources behave as before.diff --git a/docs/architecture/key-files/canonical-reconciliation-continued.md b/docs/architecture/key-files/canonical-reconciliation-continued.mdindex cdbfb9f8aa..d9a529bf52 100644--- a/docs/architecture/key-files/canonical-reconciliation-continued.md+++ b/docs/architecture/key-files/canonical-reconciliation-continued.md@@ -11,3 +11,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/persistence/grandfather.ts` — the retired v0.13.1 grandfather's request preparer (#7814). Upgrades no longer stamp `validate: false` into pages, so a `managed_grandfather` put_page request an older binary admitted and left queued is refused `revision_conflict` (the request ends `conflict`) and the page, its file and its revision stay unchanged. The refusal records origin `grandfather_retired` (it outlives receipt compaction), and `classifyTerminal` reads it, or an uncompacted `managed_grandfather` intent, as the always-historical `retired_operation` category, so doctor `persistence_terminal_failures` counts it as history with a "retired grandfather, nothing to do" note (#7837). Neither file holds a canonical write reference any more, so neither has a `canonical-writers.tsv` row and a new write there trips the census. `test/grandfather-managed.test.ts` covers it.- `src/core/persistence/unimported-file.ts` — GST-2579: `unimportedFile(engine, state)` reports a page file whose bytes are neither in sync's import record (`raw_sha256`/`disk_sha256`) nor a git effect gbrain wrote for a revision the page has held (live `knowledge_revision` or a `page_versions` row), with the last commit that touched it (`lastCommitOf` in `pending-import.ts`); no import record counts as newer. `discardedFilePaths` names the decided paths whose result drops the file's value. `repair/file-drift.ts` skips such pages in bulk (`kept_newer_file`; a recreate over another writer's delete is `kept_newer_delete`), names the commit for `--slug`, and `fileDriftConsentText` lists them in the consent the registry's `consent: 'destructive'` asks for. `reconcile.ts` refuses a preview, and an admitted apply (the `guard` on `admitReconcileArtifact`; keep_db passes none), whose result takes the database over such a file (`unimportedFileRefusal`, `source_changed` / `unimported_file_edit`). Test: `test/db-wins-unimported-gst2579.test.ts`.+- `src/core/persistence/sync-holds-carried.ts` — the holds a source carries by design: `mirrorDatabaseOnlyHold`, `mirrorKeepDeletedHold`, `carriedHolds` and `heldDriftPreviewArgv` (re-exported from `sync-holds.ts`). Keep the deletion on a mirror: on a read-only mirror (`sourceMirrorReadOnly`), `deletedPage` turns `--held --side deleted --state tombstone_edited --prefer database` into a `KeepDeletedPage` (`keep_deleted`) bound to the same `DeletedDriftPin`; `applyKeepDeleted` re-checks the pin and records `meta.keep_deleted` on the hold (`recordKeepDeleted` in `sync-holds.ts`, guarded on the observed hold), writing no file or page, and a decided hold previews `mirror_keep_deleted`. `writeGitHold` carries the decision across a rewrite with the same `blob_oid` and state (`carriedKeepDeleted`; a tombstone purged to `purged_differs` rebinds it to the deletion marker's digest); `holdBasisMoved` re-checks a kept hold whose tombstone was restored, purged or rewritten, which drops it. `mirrorKeepDeletedHold` makes the hold carried (`carriedHolds` class `mirror_keep_deleted`, fault row `mirror_keep_deleted`, needs_human false), and `passBanked` never counts its rewrite as saved work. Test: `test/mirror-keep-deleted.test.ts`.diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 4322d8175d..ccb9c99e3b 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/check-test-env-opt-ins.ts` + `test/helpers/operator-env-policy.ts` — the opt-in naming rule. The policy (`STRIP_PREFIX`, `KEEP_EXACT`, `KEEP_PREFIX`, `RENAMED`, `isStripped`) is shared by `test/helpers/operator-env-preload.ts`, which deletes stripped `GBRAIN_*` names before any test loads and stops the run with the rename command when an old opt-in name is set, and by the guard (`check:test-env-opt-ins`, in `verify`), which parses test files and fails on a test that gates execution on a stripped name. Test opt-ins are `GBRAIN_TEST_<AREA>_<WHAT>`, paid ones `GBRAIN_TEST_LIVE_<WHAT>`. The same guard fails `test_env_snapshot_module_scope`: a `delete` of or assignment to `process.env.GBRAIN_PGLITE_SNAPSHOT` outside every function body in a file the unit matrix loads (`*.serial.test.ts`, `test/e2e/` and `*-preload.ts` are exempt: own process, or process-wide by design). `scripts/test-shard.sh` runs a whole shard in one bun process, so such a change persists for every later file and each of their PGLite engines cold-boots (~3 s); the accepted shape is save+delete in `beforeAll`, restore in `afterAll`, or `test/helpers/with-snapshot.ts` per test. Tests: `test/scripts/test-env-opt-ins-guard.test.ts`, `test/operator-env-preload.test.ts`.- `scripts/check-postgres-lane-coverage.ts` — `check:postgres-lanes` (in `verify`). TypeScript-AST scan of every `test/` file outside `test/e2e/` and `test/fixtures/` for a `DATABASE_URL`-gated PostgreSQL arm (zero-argument `testBackends()`, or a `DATABASE_URL` read used as a condition, connection argument or `database_url` value; `withEnv`-supplied URLs excluded) and a lane that runs it (a workflow step with `DATABASE_URL` naming the file, a `test/e2e/` importer, a `tests/heavy/` script, or a `scripts/e2e-backend-matrix.txt` row). `ALLOWLIST` rows name a reason and TODO; stale rows fail. A `test/postgres-unit-arms.txt` row is a lane; a malformed, duplicate, unsorted, missing-file or arm-less row fails (`postgres_arm_list_invalid`, `postgres_arm_list_stale`). `postgresArm`, `postgresLanes` and `armedFiles` are exported for the stress runner. Tests: `test/scripts/postgres-lane-coverage.test.ts`.- `scripts/check-item-allowlist-catches.ts` + `scripts/item-allowlist-catches-baseline.tsv` — `check:item-allowlist-catches` (in `verify`). TypeScript-AST scan of `src/**/*.ts` (no `*.generated.ts`, `.d.ts`) for catch clauses in a per-item loop (a for/for-of/for-in/while/do-while body, or a `.forEach`/`.map` callback, up to the nearest function boundary) whose block tests the caught error's code against a set, list or literal (direct, cast, aliased or destructured) and rethrows the caught error. Per-file counts only shrink: growth, a new file, a count under its row, a row with no sites or no file, and malformed, duplicate or unsorted rows fail, pointing at `classifyItemFailure` / `ItemRun` (`src/core/item-failure.ts`) and `test/pathological/`. `--update` rewrites the baseline after a shrink. `findAllowlistCatches` and `compareBaseline` are exported for `test/scripts/check-item-allowlist-catches.test.ts`; self-test fixtures under `test/fixtures/guards/check-item-allowlist-catches.ts/`.-- `test/postgres-unit-arms.txt` + `scripts/postgres-unit-arms.ts` + `scripts/postgres-arm-weights.json` — the one list of unit-lane files whose PostgreSQL arm has no other owner (sorted, one path per line, `#` comments). Read by persistence-validation.yml's `unit-postgres-arms` job (`ARM_SHARDS` = 22 shards, `shard <n> <m>`: LPT over the mined per-file weights, p75 fallback; `run <n> <m> [--postgres-only]`: `ARM_WORKERS` = 2 files at a time, one Bun process per file, each worker on its own URL from `GBRAIN_ARM_DATABASE_URLS`, output buffered per file and printed in queue order in `::group::` blocks ending in an `ARM_FILE … ms=…` line, one receipt triple per file; `--postgres-only` (a manual mode; CI runs both arms) sets `GBRAIN_TEST_BACKEND=postgres` and reads `ARM_WEIGHTS_POSTGRES_ONLY` when it exists; each shard's two-worker makespan at most `ARM_SHARD_BUDGET_MS`, 570 s, so twice that still ends a minute inside the 20-minute `ARM_STEP_TIMEOUT_MS` step; no machine-exclusive serial file may be listed), the scheduled race hunt and the lane guard. `mine [--postgres-only] <job.log>…` rewrites the cell's weights from a green run's `ARM_FILE` lines (older logs: `##[group]<file>` to the next group or endgroup). Tests: `test/scripts/postgres-unit-arms.test.ts`.+- `test/postgres-unit-arms.txt` + `scripts/postgres-unit-arms.ts` + `scripts/postgres-arm-weights.json` — the one list of unit-lane files whose PostgreSQL arm has no other owner (sorted, one path per line, `#` comments). Read by persistence-validation.yml's `unit-postgres-arms` job (`ARM_SHARDS` = 23 shards, `shard <n> <m>`: LPT over the mined per-file weights, p75 fallback; `run <n> <m> [--postgres-only]`: `ARM_WORKERS` = 2 files at a time, one Bun process per file, each worker on its own URL from `GBRAIN_ARM_DATABASE_URLS`, output buffered per file and printed in queue order in `::group::` blocks ending in an `ARM_FILE … ms=…` line, one receipt triple per file; `--postgres-only` (a manual mode; CI runs both arms) sets `GBRAIN_TEST_BACKEND=postgres` and reads `ARM_WEIGHTS_POSTGRES_ONLY` when it exists; each shard's two-worker makespan at most `ARM_SHARD_BUDGET_MS`, 570 s, so twice that still ends a minute inside the 20-minute `ARM_STEP_TIMEOUT_MS` step; no machine-exclusive serial file may be listed), the scheduled race hunt and the lane guard. `mine [--postgres-only] <job.log>…` rewrites the cell's weights from a green run's `ARM_FILE` lines (older logs: `##[group]<file>` to the next group or endgroup). Tests: `test/scripts/postgres-unit-arms.test.ts`.- `scripts/serial-files.tsv` + `scripts/lib/serial-manifest.ts` — the serial manifest: every `*.serial.test.ts` outside `test/e2e/` with its class (`R1`, `R2`, `global-state`, `exclusive`) and a reason. `checkSerialManifest` (pure) requires the manifest to match the tree exactly, classes to match what the file does (env mutation, `mock.module`, `EXCLUSIVE_FILES`) and reasons to be specific; each failure prints Why/Fix/Docs with `bash scripts/check-test-isolation.sh --as-parallel <file>` as the first step. Tests: `test/scripts/serial-files.test.ts`.- `test/helpers/brain-template.ts` — disk-backed PGLite brains cloned from one initialized template per process and embedding shape. The template is captured right after `initSchema` with no source, writer or physical-root reservation (asserted); only the data directory is copied; each clone regenerates `brain_id`, the default source incarnation and the shared-skill token secret and serving epoch. Used by `test/helpers/connector-fixture.ts`. Tests: `test/helpers/brain-template.test.ts`.- `scripts/test-agent-voice.sh` — `bun run test:agent-voice`: the agent-voice recipe's vitest unit suite (`recipes/agent-voice/tests/unit`), with pinned vitest and ws installed into a temporary prefix linked as the recipe's `node_modules`. Needs node, npm and registry access; CI runs it in test.yml's verify job.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 3d8b1eb132..0fd17658cc 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -3779,13 +3779,43 @@ count. Read those lines before you agree to the apply.| State | `--prefer database` | `--prefer file` ||---|---|---|-| `tombstone_edited` | Keeps the deletion and removes the file. | Restores the page and imports the file. |+| `tombstone_edited` | Keeps the deletion and removes the file (on a read-only mirror: [records the kept deletion](#mirror-keep-deleted), removes nothing). | Restores the page and imports the file. || `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). |A `file_gone` page whose file moved is listed `moved_to <slug>` under either `--prefer` and resolved by neither: itsline names [`gbrain repair moved-pages`](#moved-pages), which folds it into the moved page.+<a id="mirror-keep-deleted"></a>**Keep it deleted on a read-only mirror.** On a+[read-only mirror](multi-source-brains.md#read-only-mirror-sources) gbrain never+writes the checkout, so a page you deleted whose file the upstream then edited+can't be settled by removing the file. Keep the deletion with the same+per-window command:++```bash+gbrain repair file-drift --source <id> --held --side deleted --state tombstone_edited --prefer database # preview: keep_deleted+gbrain repair file-drift --source <id> --held --side deleted --state tombstone_edited --prefer database --apply --expect <hash> --yes+```++The preview lists each page `keep_deleted`, and the apply records the decision+on the hold (`keep_deleted`: the request id, when, and the tombstone's page id+and revision) once the user agrees. A page or file that changed since the+preview is skipped `changed_since_preview`. Nothing is deleted, restored or+written: the tombstone stays, no file is removed from the mirror and no page+content changes. The hold stays too, decided: `gbrain sources status <id>`,+`gbrain sync status --source <id>` and doctor report it carried with reason+`mirror_keep_deleted` (beside `mirror_database_only`) and `needs_human: false`,+and later previews list it `mirror_keep_deleted` instead of asking again. Sync+does nothing new: it already leaves an unchanged held file alone. The decision+holds for the file version the hold pinned, so a re-check of the same bytes+(an upgrade that re-screens holds) carries it. It is void, and the hold asks+again, when the upstream edits the file again or the page is restored (`gbrain+restore`); when the tombstone is purged, the decision moves to the+`purged_differs` hold, bound to the deletion marker. On a writable source the+command removes the file as before, and a decision recorded while the source was+a mirror no longer counts. A brain with no Git repository holds no files, so the+preview finds nothing and exits 0.+`--prefer file` keeps the file's bytes: it adds only protected frontmatter keys thefile lacks and database-only timeline rows, and refuses[`file_wins_rewrite`](write-refusals.md#file_wins_rewrite) when the resultdiff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 1dbed1abc3..8df602494b 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -166,6 +166,7 @@ Every hold and error has three fields, from one table| `rename_reconcile_failed` | page | none | yes | always: the old page may be a duplicate || `file_drift_unknown` | page | reconcile | yes | always: the file and the page differ and no import record says which changed || `file_drift_mirror_database_only` | page | none | no | never: the page stays live and database-only because gbrain never writes a read-only mirror |+| `mirror_keep_deleted` | page | none | no | never: the user kept the deletion; a new upstream edit of the file or a restore asks again || `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names || `page_identity_decision` | page | none | yes | always: only a person decides which page the file is || `absent_from_worktree` | page | none | yes | always: only a person decides whether the file comes back or its deletion is committed |@@ -284,6 +285,12 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) andgbrain never writes the mirror. These holds never block the pass and are notre-screened every sync; the run and `sync status` report them as `carried`(class, count, a sample and the preview that lists them).+- `mirror_keep_deleted`: on a read-only mirror the user kept the deletion of+ a page whose file the upstream edited+ ([keep it deleted](repair.md#mirror-keep-deleted)). The hold stays, decided:+ it never blocks the pass, needs nobody, and the run and `sync status` report+ it `carried` with this class. Nothing to unblock; a new upstream edit of the+ file or `gbrain restore` makes it ask again.- A symlink whose target does not exist is not a page: sync skips it andcounts it (`skipped.symlink_dangling`) instead of holding it as unreadable,and releases an unreadable hold an older release wrote for it. A danglingdiff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.jsonindex 0e0c25cc86..9474e18bfd 100644--- a/scripts/postgres-arm-weights-postgres-only.json+++ b/scripts/postgres-arm-weights-postgres-only.json@@ -207,6 +207,7 @@"test/managed-sync-stale-group-head.test.ts": 8354,"test/migration-persistence-request-id-index.test.ts": 6848,"test/migration-persistence-request-slug-index.test.ts": 6202,+ "test/mirror-keep-deleted.test.ts": 22107,"test/on-commit-embedding.serial.test.ts": 10151,"test/origin-guard-6948.test.ts": 18397,"test/origin-twins-6948.test.ts": 1635,diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex ae1a7937c0..b32f169742 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -334,6 +334,7 @@"test/migration-persistence-foreground-committed-index.test.ts": 9311,"test/migration-persistence-request-id-index.test.ts": 10916,"test/migration-persistence-request-slug-index.test.ts": 13917,+ "test/mirror-keep-deleted.test.ts": 44596,"test/notifier-passed-freshness-marker-7941.test.ts": 31038,"test/notifier-retry-unwatched-gst2515.test.ts": 6875,"test/on-commit-embedding.serial.test.ts": 13575,diff --git a/scripts/postgres-unit-arms.ts b/scripts/postgres-unit-arms.tsindex e710b2fcf2..36a6050234 100644--- a/scripts/postgres-unit-arms.ts+++ b/scripts/postgres-unit-arms.ts@@ -44,7 +44,7 @@ export const ARMS_LIST = 'test/postgres-unit-arms.txt';export const ARM_WEIGHTS = 'scripts/postgres-arm-weights.json';export const ARM_WEIGHTS_POSTGRES_ONLY = 'scripts/postgres-arm-weights-postgres-only.json';/** persistence-validation's unit-postgres-arms matrix size; test/scripts/postgres-unit-arms.test.ts pins the workflow to it. */-export const ARM_SHARDS = 22;+export const ARM_SHARDS = 23;/** Files run at once per job, each against its own PostgreSQL service; the workflow lists one URL per worker. */export const ARM_WORKERS = 2;/** The workflow step's `timeout-minutes: 20`: a shard whose files run longer is cut off mid-list. */diff --git a/scripts/ubicloud/README.md b/scripts/ubicloud/README.mdindex c22955a6c3..0983bd860c 100644--- a/scripts/ubicloud/README.md+++ b/scripts/ubicloud/README.md@@ -169,7 +169,7 @@ runs every file in `test/postgres-unit-arms.txt` the way persistence-validation'`unit-postgres-arms` step does (`bun --no-env-file test --timeout=120000`,`GBRAIN_TEST_ALLOW_DATABASE_URL=1`, no timeout multiplier) against the slot'sown empty `gbrain_arms_test` database. The summary takes the two-worker makespan of its-measured durations over that job's `ARM_SHARDS` partition (22 shards, `ARM_WORKERS` = 2+measured durations over that job's `ARM_SHARDS` partition (23 shards, `ARM_WORKERS` = 2files at a time), and a shard over the step's 20-minute timeoutfails the run, since GitHub would cut that shard off mid-list. The committedweights must also fit each shard twice over with a minute to sparediff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 71096b82cf..d4de0dcf5b 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -173,7 +173,9 @@ Options:file-drift: select the source's held file_drift pages of one Decision. --side deleted needs --state,because --prefer file and --prefer database do opposite things in each state (tombstone_edited: restoreand 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). Held pages of several sides or states are+ file; file_gone: soft-delete the page, or recreate the file). On a read-only mirror tombstone_edited+ --prefer database removes no file: it records the kept deletion on the hold (mirror_keep_deleted), which+ stops asking until the upstream edits the file again. Held pages of several sides or states arerefused without --side; the preview prints each page's action. One preview covers a window of at most200 held pages (or 60 s of work) in held-path order, reports progress on stderr, and its hash covers onlythat window; a partial window prints next_cursor and the next preview command.diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 098a806207..674df9b05f 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -285,7 +285,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'stateconst c = status.cursor;switch (status.reason) {case 'nothing_pending': return `Source ${status.source_id} is synced${c?.done ? ` (last run ${status.run_id?.slice(0, 8) ?? '?'} finished at ${c.index}/${c.total})` : ''}.`;- case 'held_by_design': return `Source ${status.source_id} is synced; ${status.holds.length} file(s) stay held by design${(status.carried ?? []).map(carried => `; ${carried.count} ${carried.class} (database-only pages this read-only mirror keeps, e.g. ${carried.sample[0]}; list: ${carried.list.join(' ')})`).join('')}.`;+ case 'held_by_design': return `Source ${status.source_id} is synced; ${status.holds.length} file(s) stay held by design${(status.carried ?? []).map(carried => `; ${carried.count} ${carried.class} (${carried.class === 'mirror_keep_deleted' ? 'deleted pages the user kept deleted although this read-only mirror\'s upstream edited their files' : 'database-only pages this read-only mirror keeps'}, e.g. ${carried.sample[0]}; list: ${carried.list.join(' ')})`).join('')}.`;case 'held_needs_human': return `Source ${status.source_id} is synced except ${status.holds.length} held file(s), some waiting on a person (see NEEDS HUMAN below); the rest keeps syncing.`;case 'live_job': return `Source ${status.source_id} is resumable: sync job #${status.live_job_id} is draining it.`;case 'cursor_unfinished': return `Source ${status.source_id} is resumable: run ${status.run_id?.slice(0, 8) ?? '?'} stands at ${c?.index ?? '?'}/${c?.total ?? '?'}; the next sync resumes it.`;diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0087a8bbb6..30abefb100 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embed', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--only', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--room', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--created-before', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--ids-file', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--undo', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],@@ -136,7 +136,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--reason', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--apply', '--brain', '--card', '--client', '--dir', '--drop-field', '--dry-run', '--expect', '--expected-revision', '--finalize', '--from-prefix', '--help', '--id', '--json', '--jsonl', '--no-pull', '--only', '--out', '--patch', '--plan', '--push-remote', '--repo', '--restore-only', '--restored-to', '--scopes', '--source', '--status', '--store', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--room', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--calls', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--calls', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dir', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--from', '--full', '--held', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--room', '--since', '--source', '--source-id', '--timeout', '--timings', '--to', '--wait'],diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.tsindex 0fdb0c1fa7..f5e9586f5d 100644--- a/src/core/persistence/public-category.ts+++ b/src/core/persistence/public-category.ts@@ -33,7 +33,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {- worktree_dirty: 'drift', file_drift: 'drift', file_drift_unknown: 'drift', file_drift_mirror_database_only: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',+ worktree_dirty: 'drift', file_drift: 'drift', file_drift_unknown: 'drift', file_drift_mirror_database_only: 'drift', mirror_keep_deleted: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict', origin_conflict_decision: 'conflict', page_identity_decision: 'conflict',settle_mismatch: 'defect', page_write_failed: 'defect', freeze_page_body_segmented: 'defect', freeze_page_body_rows_unreadable: 'storage',invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex eb1e4640ed..57fe5e6ad2 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -33,6 +33,16 @@ function grantFix(): Action {}/** The trusted CLI grant check every reconcile entry point (and `gbrain repair file-drift`'s preview) runs per page. */export async function authorizeReconcile(engine: BrainEngine, sourceId: unknown, slug: unknown) {+ const granted = await authorizeReconcileGrant(engine, sourceId, slug);+ const authority = await submissionAuthority({ engine, remote: false, sourceId: granted.sourceId } as OperationContext, 'put_page', granted.sourceId, granted.incarnation, granted.slug);+ return { sourceId: granted.sourceId, slug: granted.slug, authority };+}++/**+ * The CLI grant and source checks of `authorizeReconcile` without its write authority: a decision recorded only on a hold+ * (a read-only mirror's kept deletion) writes no page or file, so it needs the caller's grant on the page but no submission.+ */+export async function authorizeReconcileGrant(engine: BrainEngine, sourceId: unknown, slug: unknown): Promise<{ sourceId: string; slug: string; incarnation: string }> {const verified = currentVerifiedLocalWriter();if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Reconciliation requires a verified trusted local CLI caller.');if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw opError('invalid_params', 'One explicit source ID and page slug are required.',@@ -55,8 +65,7 @@ export async function authorizeReconcile(engine: BrainEngine, sourceId: unknown,if (!source || source.archived) throw opError('source_changed', 'The explicit source is missing or archived.',`Source '${sourceId}' is missing or archived. Check it with the command in fix, and restore an archived source before reconciling its pages.`,{ fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });- const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext, 'put_page', sourceId, source.incarnation, slug);- return { sourceId, slug, authority };+ return { sourceId, slug, incarnation: source.incarnation };}function assertPreimages(artifact: ReconcileArtifact, state: ReconcileState): void {assertReconcilePins(artifact.preconditions, state.pins);diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 666f5e85c0..6341edabe9 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -142,6 +142,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [human_reason: 'The file and the database page differ, and sync has no import record to tell which one changed since the last import, so it held the file instead of overwriting the page; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },// GBRA-542: a deleted-side `file_drift` hold on a read-only mirror (sync-holds.ts mirrorDatabaseOnlyHold): the page stays live and database-only by design.{ code: 'file_drift_mirror_database_only', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: the page stays live and database-only because gbrain never writes a read-only mirror' },+ // A deleted-side `file_drift` hold on a read-only mirror the user decided to keep deleted (sync-holds.ts mirrorKeepDeletedHold).+ { code: 'mirror_keep_deleted', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: the user kept the deletion; a new upstream edit of the file or a restore asks again' },{ code: 'origin_conflict_decision', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pages differ, their ids conflict or none is the page the path names',human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },// GBRA-130 A-17/B-3/B-4: a held `page_identity_changed` path (sync-status.ts holdVerdict): several tombstones, a spelling twin or a takeover whose ids differ.diff --git a/src/core/persistence/sync-holds-carried.ts b/src/core/persistence/sync-holds-carried.tsnew file mode 100644index 0000000000..eb6d5830fa--- /dev/null+++ b/src/core/persistence/sync-holds-carried.ts@@ -0,0 +1,68 @@+/**+ * The holds a source carries by design (sync-holds.ts readers mark a read-only mirror's records `read_only_checkout`):+ * a mirror's database-only pages (`mirror_database_only`) and the deletions the user kept on a mirror (`mirror_keep_deleted`),+ * with the keep-the-deletion decision a rewrite of the same file carries.+ */+import type { BrainEngine } from '../engine.ts';+import { digest } from './digest.ts';+import type { FileDriftDeletedState, FileDriftSide, GitHoldRecord } from './sync-holds.ts';+import { SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++/** The user's keep-the-deletion decision on a mirror's deleted-side `file_drift` hold: the apply's request, when, and what it was bound to. */+export interface KeepDeletedDecision { request_id: string; decided_at: string; page_id: number | null; revision: string | null; marker_digest?: string }++/**+ * GBRA-542: a deleted-side `file_drift` hold on a read-only mirror whose file Git committed and the upstream removed while the+ * page changed in the database (or has no import record). gbrain never writes the mirror's files, so the page stays live and+ * database-only: the hold is carried by design (class `mirror_database_only`), never re-screened by a plain sync and never a+ * person's to clear. Deleting the page as the upstream did stays the owner's explicit `--prefer file` repair.+ */+export function mirrorDatabaseOnlyHold(record: Pick<GitHoldRecord, 'code' | 'meta' | 'read_only_checkout'>): boolean {+ return record.read_only_checkout === true && record.code === 'file_drift' && record.meta.side === 'deleted' && record.meta.state === 'file_gone' && !record.meta.reason;+}++/**+ * A deleted-side `file_drift` hold on a read-only mirror whose page the user decided to keep deleted (`meta.keep_deleted`): the+ * hold stays, decided and carried (class `mirror_keep_deleted`), and needs nobody until the upstream edits the file again.+ */+export function mirrorKeepDeletedHold(record: Pick<GitHoldRecord, 'code' | 'meta' | 'read_only_checkout'>): boolean {+ return record.read_only_checkout === true && record.code === 'file_drift' && record.meta.side === 'deleted' && !!record.meta.keep_deleted+ && (record.meta.state === 'tombstone_edited' || record.meta.state === 'purged_differs');+}++/**+ * The keep-the-deletion decision a rewrite of the same bytes carries, as repair verdicts are carried: the same state when the+ * pass did not re-check the hold because its tombstone moved, or, when the tombstone was purged, rebound to its deletion marker.+ */+export async function carriedKeepDeleted(tx: Exec, existing: GitHoldRecord, input: Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'>): Promise<KeepDeletedDecision | undefined> {+ const decision = existing.meta.keep_deleted;+ const bytes = existing.meta.blob_oid ?? existing.meta.working_hash;+ if (!decision || input.code !== existing.code || input.meta.side !== 'deleted' || !bytes || (input.meta.blob_oid ?? input.meta.working_hash) !== bytes) return undefined;+ if (input.meta.state === existing.meta.state && !input.meta.basis_moved) return decision;+ if (existing.meta.state !== 'tombstone_edited' || input.meta.state !== 'purged_differs') return undefined;+ const [marker] = await tx.executeRaw<{ value: { kind?: string } | null }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',+ [SYNC_ORIGIN_DELETED_OP, `${input.source_id}:${input.incarnation}:${input.source_path}`]);+ return marker?.value?.kind === 'deleted' ? { ...decision, marker_digest: digest(marker.value) } : undefined;+}++/** GBRA-542: one class of holds carried by design, with a sample of its paths and the read-only command that lists them. */+export interface CarriedHolds { class: 'mirror_database_only' | 'mirror_keep_deleted'; count: number; sample: string[]; list: string[] }+export const CARRIED_SAMPLE = 5;++/** GBRA-542: the carried classes among one source's holds (empty when there are none). */+export function carriedHolds(records: ReadonlyArray<Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta' | 'read_only_checkout'>>): CarriedHolds[] {+ const mirror = records.filter(mirrorDatabaseOnlyHold);+ const keptDeleted = records.filter(mirrorKeepDeletedHold);+ return [...mirror.length ? [{ class: 'mirror_database_only' as const, count: mirror.length, sample: mirror.slice(0, CARRIED_SAMPLE).map(record => record.path),+ list: heldDriftPreviewArgv(mirror[0]!.source_id, 'deleted', 'file_gone', 'file') }] : [],+ ...keptDeleted.length ? [{ class: 'mirror_keep_deleted' as const, count: keptDeleted.length, sample: keptDeleted.slice(0, CARRIED_SAMPLE).map(record => record.path),+ list: ['gbrain', 'sources', 'status', keptDeleted[0]!.source_id, '--json'] }] : []];+}++/** #6712 PR 4b: the bulk preview of the held `file_drift` pages of one side (and deleted state), narrowed to `path` when given. */+export function heldDriftPreviewArgv(sourceId: string, side: FileDriftSide, state: FileDriftDeletedState | undefined, prefer: 'file' | 'database', path?: string): string[] {+ return ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--held', '--side', side, ...(side === 'deleted' && state ? ['--state', state] : []),+ ...(path ? ['--only', path] : []), '--prefer', prefer];+}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 40f41b6e00..81e07c5d24 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -54,6 +54,8 @@ import { VERSION } from '../../version.ts';import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';import { chunkerStamp } from '../chunkers/code.ts';import { gitBlobOid, sha256 } from './digest.ts';+import { carriedKeepDeleted, heldDriftPreviewArgv, mirrorDatabaseOnlyHold, mirrorKeepDeletedHold, type KeepDeletedDecision } from './sync-holds-carried.ts';+export { CARRIED_SAMPLE, carriedHolds, heldDriftPreviewArgv, mirrorDatabaseOnlyHold, mirrorKeepDeletedHold, type CarriedHolds, type KeepDeletedDecision } from './sync-holds-carried.ts';import { HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from './sync-fault-class.ts';import { retiredSyncSetting, type RetiredSyncKeyName } from '../sync-config-keys.ts';@@ -217,6 +219,8 @@ export interface GitHoldMeta {identity_ids?: { page: string; file: string };/** #8072 `file_too_large`: the streamed (segmented) preparation read the whole file to refuse it, under this gbrain; it re-screens when the file changes, on retry, or under another gbrain. */streamed?: { gbrain_version: string };+ /** A read-only mirror's deleted-side `file_drift` hold whose deletion the user kept (sync-holds-carried.ts): decided and carried for the pinned `blob_oid`. */+ keep_deleted?: KeepDeletedDecision;}/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */@@ -299,6 +303,8 @@ export interface GitHoldItem {/** #6712 PR 4b `file_drift`: the Decision's side, and for a deleted side its state (`GitHoldMeta.side` / `state`). */side?: FileDriftSide;state?: FileDriftDeletedState;+ /** A read-only mirror's deleted-side hold the user decided to keep deleted (`GitHoldMeta.keep_deleted`). */+ keep_deleted?: KeepDeletedDecision;message: string;slug: string | null;/** True when a page exists and keeps its last good revision; false when the file's page is missing. */@@ -358,16 +364,6 @@ async function readRow(tx: Exec, sourceId: string, incarnation: string, path: st/** GBRA-542: the hold record as readers return it, marked when its source is a read-only mirror (`s`: the sources row). */const READ_HOLD_RECORD_SQL = `CASE WHEN COALESCE(s.config->>'mirror_read_only','false')='true' THEN jsonb_set(h.completed_keys->0,'{read_only_checkout}','true'::jsonb) ELSE h.completed_keys->0 END`;-/**- * GBRA-542: a deleted-side `file_drift` hold on a read-only mirror whose file Git committed and the upstream removed while the- * page changed in the database (or has no import record). gbrain never writes the mirror's files, so the page stays live and- * database-only: the hold is carried by design (class `mirror_database_only`), never re-screened by a plain sync and never a- * person's to clear. Deleting the page as the upstream did stays the owner's explicit `--prefer file` repair.- */-export function mirrorDatabaseOnlyHold(record: Pick<GitHoldRecord, 'code' | 'meta' | 'read_only_checkout'>): boolean {- return record.read_only_checkout === true && record.code === 'file_drift' && record.meta.side === 'deleted' && record.meta.state === 'file_gone' && !record.meta.reason;-}-/*** Records or replaces a hold. Call it inside the transaction that advances the* run past the file. Idempotent on (path, upstream_version); returns `skipped`@@ -382,9 +378,10 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'versionconst attempts = existing && existing.code === input.code ? (existing.meta.attempts ?? 1) + 1 : 1;// #6188/#6377: a re-screen of the same bytes under the same code keeps the last repair verdict; a changed file drops it.const sameBytes = existing && existing.code === input.code && existing.upstream_version === input.upstream_version;+ const keepDeleted = existing && !input.meta.keep_deleted ? await carriedKeepDeleted(tx, existing, input) : undefined;const kept = sameBytes ? { ...(existing.meta.fence_repair && !input.meta.fence_repair ? { fence_repair: existing.meta.fence_repair } : {}),...(existing.meta.content_repair && !input.meta.content_repair ? { content_repair: existing.meta.content_repair } : {}) } : {};- const record: GitHoldRecord = { version: 1, ...input, meta: { ...kept, ...input.meta, attempts, ...escalationStamps(existing, input, now) },+ const record: GitHoldRecord = { version: 1, ...input, meta: { ...kept, ...(keepDeleted ? { keep_deleted: keepDeleted } : {}), ...input.meta, attempts, ...escalationStamps(existing, input, now) },held_at: existing && existing.upstream_version === input.upstream_version && existing.code === input.code ? existing.held_at : now, updated_at: now };await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,@@ -453,6 +450,15 @@ async function rewriteHoldMeta(tx: Exec, input: { sourceId: string; incarnation:return rows.length ? record : null;}+/**+ * Records the user's keep-the-deletion decision on the mirror hold at `path`, guarded on the hold the preview observed+ * (`observedAt`) still being that deleted-side `file_drift` hold in `state`; false when it moved meanwhile. The hold stays.+ */+export function recordKeepDeleted(tx: Exec, input: { sourceId: string; incarnation: string; path: string; observedAt: string; state: FileDriftDeletedState; decision: KeepDeletedDecision }): Promise<boolean> {+ return rewriteHoldMeta(tx, { ...input, code: 'file_drift' }, existing => existing.observed_at === input.observedAt && existing.meta.side === 'deleted' && existing.meta.state === input.state+ ? { keep_deleted: input.decision } : null).then(record => record !== null);+}+/*** Clears a path's hold. Call it only inside the transaction that commits the* file's import, deletion or no-op; `observedAt` is the discovery time of the@@ -622,13 +628,21 @@ export async function readGitHoldCodeCounts(engine: Exec, sourceIds: string[]):*/export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, holds: ReadonlyMap<string, Pick<GitHoldRecord, 'code' | 'page_id' | 'meta'>>,paths: readonly string[]): Promise<Set<string>> {- const watched = paths.flatMap(path => { const hold = holds.get(path); return hold?.code === 'concurrent_write' && hold.page_id != null && hold.meta.page_revision ? [Number(hold.page_id)] : []; });- const revisions = new Map(watched.length ? (await engine.executeRaw<{ id: number; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])',- [sourceId, watched])).map(row => [Number(row.id), row.revision]) : []);+ const kept = (hold: Pick<GitHoldRecord, 'code' | 'meta'> | undefined) => hold?.code === 'file_drift' && hold.meta.state === 'tombstone_edited' && hold.meta.keep_deleted?.page_id != null+ ? hold.meta.keep_deleted : undefined;+ const watched = paths.flatMap(path => { const hold = holds.get(path); return hold?.code === 'concurrent_write' && hold.page_id != null && hold.meta.page_revision ? [Number(hold.page_id)]+ : kept(hold) ? [Number(kept(hold)!.page_id)] : []; });+ const rows = watched.length ? await engine.executeRaw<{ id: number; revision: string; deleted: boolean }>('SELECT id, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND id=ANY($2::int[])',+ [sourceId, watched]) : [];+ const revisions = new Map(rows.map(row => [Number(row.id), row.revision]));+ const tombstones = new Map(rows.filter(row => row.deleted).map(row => [Number(row.id), row.revision]));return new Set(paths.filter(path => {const hold = holds.get(path);if (!hold) return false;if (hold.meta.blocked_on && !holds.has(hold.meta.blocked_on)) return true;+ // A kept deletion rests on its tombstone: a restore, a purge or another write to it re-checks the hold.+ const decision = kept(hold);+ if (decision) return tombstones.get(Number(decision.page_id)) !== decision.revision;return hold.code === 'concurrent_write' && hold.page_id != null && !!hold.meta.page_revision && revisions.get(Number(hold.page_id)) !== hold.meta.page_revision;}));}@@ -775,23 +789,6 @@ export function fileDriftActionVerb(side: FileDriftSide, state: FileDriftDeletedreturn prefer === 'database' ? 'recreate the file' : 'soft-delete the page';}-/** GBRA-542: one class of holds carried by design, with a sample of its paths and the read-only command that lists them. */-export interface CarriedHolds { class: 'mirror_database_only'; count: number; sample: string[]; list: string[] }-export const CARRIED_SAMPLE = 5;--/** GBRA-542: the carried classes among one source's holds (empty when there are none). */-export function carriedHolds(records: ReadonlyArray<Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta' | 'read_only_checkout'>>): CarriedHolds[] {- const mirror = records.filter(mirrorDatabaseOnlyHold);- return mirror.length ? [{ class: 'mirror_database_only', count: mirror.length, sample: mirror.slice(0, CARRIED_SAMPLE).map(record => record.path),- list: heldDriftPreviewArgv(mirror[0]!.source_id, 'deleted', 'file_gone', 'file') }] : [];-}--/** #6712 PR 4b: the bulk preview of the held `file_drift` pages of one side (and deleted state), narrowed to `path` when given. */-export function heldDriftPreviewArgv(sourceId: string, side: FileDriftSide, state: FileDriftDeletedState | undefined, prefer: 'file' | 'database', path?: string): string[] {- return ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--held', '--side', side, ...(side === 'deleted' && state ? ['--state', state] : []),- ...(path ? ['--only', path] : []), '--prefer', prefer];-}-/** GST-2584: the read-only preview of `gbrain repair moved-pages`, which folds a page whose file moved into the moved page. */export function movedPagesPreviewArgv(sourceId: string, slug?: string | null): string[] {return ['gbrain', 'repair', 'moved-pages', '--source', sourceId, ...(slug ? ['--slug', slug] : [])];@@ -817,6 +814,11 @@ function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'metwhy: `${record.path} is gone from the read-only mirror's last commit, and page ${slug}${revision} changed in the database or has no import record, so sync keeps the page. gbrain never writes this mirror's files, so the page stays live and database-only: the hold is carried by design (mirror_database_only), never re-screened by a plain sync, and needs nothing. Only if the owner wants the page gone as the upstream did, this preview (writes nothing) shows what --prefer file deletes; its apply needs the user's consent.`,verify };}+ if (mirrorKeepDeletedHold({ ...record, code: 'file_drift' })) {+ return { argv: preview('file'), consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/repair.md#mirror-keep-deleted',+ why: `The user kept the deletion of page ${slug} although the read-only mirror's upstream edited ${record.path}, so the hold is decided and carried (mirror_keep_deleted) and needs nothing: sync leaves the page deleted and gbrain never writes this mirror's files. A new upstream edit of the file, or restoring the page, asks again. Only if the user changes their mind, this preview (writes nothing) shows --prefer file: ${fileDriftActionVerb('deleted', state, 'file')}; its apply needs the user's consent.`,+ verify };+ }const uncommitted = state === 'file_gone' && (record.meta.reason === 'never_committed' || record.meta.reason === 'ignored');const what = state === 'file_gone' && record.meta.reason === 'origin_unknown' ? `${record.path} is gone, and Git could not show whether a commit held it (its history read did not finish), so sync kept page ${slug} instead of deleting it (#7130). The --held preview reads the whole history and names the file's provenance. `: uncommitted ? `${record.path} is gone, but Git never committed it${record.meta.reason === 'ignored' ? ' (.gitignore excludes it)' : ''}, so its absence is no evidence of a deletion and sync kept page ${slug} instead of deleting it (#7130). Put the file back and commit it (un-ignore it first) to keep the page file-backed. `@@ -827,10 +829,12 @@ function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'met// GST-2584: a file that moved left its page behind; the --held preview lists it moved_to and names the fold.const moved = state === 'file_gone' ? `If the file moved, the preview lists the page moved_to <slug> and names ${shellQuote(movedPagesPreviewArgv(source, record.slug))}, which folds it into the moved page. ` : '';const readOnly = record.read_only_checkout === true;- const options = readOnly ? `${moved}The source is a read-only mirror, so gbrain never rewrites its files and keeping the database copy needs no repair; this preview (writes nothing) shows --prefer file: ${fileDriftActionVerb('deleted', state, 'file')}. `+ const keepOnMirror = readOnly && state === 'tombstone_edited';+ const options = keepOnMirror ? `The source is a read-only mirror, so its files are never written: this preview (writes nothing) shows --prefer database, which keeps the deletion and records it on the hold (mirror_keep_deleted; no file is removed, and a new upstream edit asks again); ${preview('file').join(' ')} previews --prefer file: ${fileDriftActionVerb('deleted', state, 'file')}. `+ : readOnly ? `${moved}The source is a read-only mirror, so gbrain never rewrites its files and keeping the database copy needs no repair; this preview (writes nothing) shows --prefer file: ${fileDriftActionVerb('deleted', state, 'file')}. `: `${moved}This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `+ `${fileDriftActionVerb('deleted', state, 'file')}. `;- return { argv: preview(readOnly ? 'file' : 'database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',+ return { argv: preview(readOnly && !keepOnMirror ? 'file' : 'database'), consent: [], actor: 'agent', requires_exclusive: false, docs: keepOnMirror ? 'docs/guides/repair.md#mirror-keep-deleted' : 'docs/guides/repair.md#deleted-canonical-files',why: `${what}${options}Decide with the user. ${FILE_DRIFT_APPLY_STEP} Then sync again. The rest of the source is not blocked.`,then: { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Re-screens ${record.path} after the repair (a changed file or page revision re-screens it by itself).` },@@ -1130,6 +1134,7 @@ export function gitHoldItem(record: GitHoldRecord, auto?: FenceAutoRepair): GitH...(record.code === 'frontmatter_slug_conflict' && record.meta.content_repair ? { content_repair: record.meta.content_repair } : {}),...(record.code === 'file_drift' && fileDriftSide(record.meta) ? { side: fileDriftSide(record.meta) } : {}),...(record.code === 'file_drift' && record.meta.side === 'deleted' && record.meta.state ? { state: record.meta.state } : {}),+ ...(record.code === 'file_drift' && record.meta.keep_deleted ? { keep_deleted: record.meta.keep_deleted } : {}),message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,fix: gitHoldFix(record, auto), docs: gitHoldDocs(record.code, record.meta.reason, record.meta) };}diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex 177a6cffe0..6d1c5dbeda 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -89,6 +89,8 @@ const RESCREEN_PAGE = 500;* GST-2869: nor is a rewrite marked `retry_only` (re-checked only because `sync unblock` or `sources retry-held` asked, with* nothing due), nor one that brought a transient hold to its attempt cap: both leave the path where it was, waiting on a person.* A `retry_only` rewrite that changed the hold's code or bytes restarted `held_at`, so the first branch still counts it once.+ * Nor is a rewrite that carries a mirror's kept deletion (`meta.keep_deleted`): the page stays as the user decided, so passes+ * whose only work is carrying those paths build the streak too.*/export async function passBanked(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string, telemetry: { pass_id: string; started_at: string }): Promise<boolean> {const [row] = await engine.executeRaw<{ banked: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_source_bindings b ON b.worktree_id=r.worktree_id@@ -103,7 +105,7 @@ export async function passBanked(engine: Pick<BrainEngine, 'executeRaw'>, sourceFROM op_checkpoints h LEFT JOIN pages p ON p.source_id=$1 AND p.id=(h.completed_keys->0->>'page_id')::bigintWHERE h.op=$2 AND left(h.fingerprint, length($3))=$3 AND h.completed_keys->0->>'run_id'=$4 AND (h.completed_keys->0->>'updated_at')::timestamptz >= $5::timestamptzAND NOT (h.completed_keys->0->>'code' = ANY($6::text[])) AND h.completed_keys->0->'meta'->'basis_moved' IS NULL- AND h.completed_keys->0->'meta'->'retry_only' IS NULL AND h.fingerprint > $7 ORDER BY h.fingerprint LIMIT $8`,+ AND h.completed_keys->0->'meta'->'retry_only' IS NULL AND h.completed_keys->0->'meta'->'keep_deleted' IS NULL AND h.fingerprint > $7 ORDER BY h.fingerprint LIMIT $8`,[sourceId, GIT_HOLD_OP, `${sourceId}:${incarnation}:`, telemetry.pass_id, telemetry.started_at, [...EVERY_PASS_RESCREEN_CODES], after, RESCREEN_PAGE]);if (rewritten.some(({ record, revision }) => !holdRescreenDue(record, false) && !reachedAttemptCap(record)&& (record.code !== 'file_drift' || record.page_id == null || (record.meta.page_revision ?? null) === revision))) return true;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 22b084c016..72e23cfe3b 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -27,7 +27,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { readManagedSyncFailures, type ManagedSyncFailure } from './sync-failures.ts';-import { carriedHolds, type CarriedHolds, outOfAttemptsHold, fenceAutoRepairFor, fileDriftSide, gitHoldFix, mirrorDatabaseOnlyHold, holdEscalation, noteHoldEdit, readGitSourceHolds, recordHoldAttempt, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';+import { carriedHolds, type CarriedHolds, outOfAttemptsHold, fenceAutoRepairFor, fileDriftSide, gitHoldFix, mirrorDatabaseOnlyHold, mirrorKeepDeletedHold, holdEscalation, noteHoldEdit, readGitSourceHolds, recordHoldAttempt, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';import type { FenceAutoRepair } from '../fence-repair/hold-fix.ts';import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, PAGE_BODY_FAULT_CODES, type SyncFaultVerdict } from './sync-fault-class.ts';import { CONTENT_REPAIR_KINDS, contentHoldDisposition, runContentLane, type ContentHoldDisposition } from '../repair/content-lane.ts';@@ -320,6 +320,7 @@ export function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefif (record.code === 'page_identity_changed') return classifySyncFault({ code: record.code, detail: 'page_identity_decision', ...escalation });if (record.code === 'file_drift' && fileDriftSide(record.meta) === 'unknown') return classifySyncFault({ code: record.code, detail: 'file_drift_unknown', ...escalation });if (mirrorDatabaseOnlyHold(record)) return classifySyncFault({ code: record.code, detail: 'file_drift_mirror_database_only' });+ if (mirrorKeepDeletedHold(record)) return classifySyncFault({ code: record.code, detail: 'mirror_keep_deleted' });const bodyFault = record.code === 'page_write_failed' ? record.meta.write_failure?.code : undefined;if (bodyFault && PAGE_BODY_FAULT_CODES.has(bodyFault)) return classifySyncFault({ code: record.code, detail: `freeze_${bodyFault}`, ...escalation });const disposition = contentHoldDisposition(record, auto);diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 9a2e98f4de..888e1f0b14 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -77,7 +77,7 @@ import { fileWinsContent } from '../persistence/file-wins-content.ts';import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readCanonicalFileText, readDeletedDriftTarget, readReconcileState, assertReconcileRevision, validateReconcileArtifact, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';import { sourceDbOnlyVerdict } from '../persistence/source-storage.ts';import { readMovedPage } from '../persistence/moved-pages.ts';-import { clearGitHold, movedPagesPreviewArgv, readGitHold, 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 { clearGitHold, movedPagesPreviewArgv, readGitHold, recordKeepDeleted, 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';import type { PreparedMutation } from '../persistence/coordinator.ts';@@ -93,7 +93,7 @@ import { DATABASE_AHEAD_CODE, databaseAheadDetail, ghostFileBacked, GHOST_PURGE_import { prepareReconcileResult } from '../persistence/reconcile-prepare.ts';import { canonicalOriginPage, originConflictMessage, originTwinsFix } from '../persistence/origin-guard.ts';import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';-import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';+import { authorizeReconcile, authorizeReconcileGrant, runReconcileApply } from '../persistence/reconcile.ts';import { discardedFilePaths, unimportedFile, unimportedFileText, type UnimportedFile } from '../persistence/unimported-file.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';@@ -142,7 +142,12 @@ export interface DetachPage { slug: string; prefer: 'database'; exceptions: Drif*/export interface ReleasePin { path: string; incarnation: string; revision: string; file_hash: string | null; observed_at: string }export interface ReleasePage { slug: string; prefer: DriftSide; exceptions: DriftException[]; release_hold: ReleasePin }-type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage | DetachPage | ReleasePage;+/**+ * `--prefer database` on a read-only mirror's `tombstone_edited` hold: gbrain never writes the mirror, so instead of removing+ * the file the apply records the decision on the hold (`meta.keep_deleted`), bound to the same pin; nothing else is written.+ */+export interface KeepDeletedPage { slug: string; prefer: 'database'; exceptions: DriftException[]; keep_deleted: DeletedDriftPin }+type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage | DetachPage | ReleasePage | KeepDeletedPage;/** #6712 PR 4b: one held `file_drift` page a `--held` selection resolves. */interface HeldTarget { hold: GitHoldRecord; side: FileDriftSide; state?: FileDriftDeletedState; provenance?: DeletionProvenance }@@ -601,15 +606,19 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,* deletion and removes the file through a coordinated publication; `--prefer file` imports the file's bytes through the* managed file repair, which restores the tombstone or creates a new page and leaves the marker for sync to retire.*/-async function deletedPage(engine: BrainEngine, sourceId: string, target: HeldTarget & { state: 'tombstone_edited' | 'purged_differs' }, prefer: DriftSide):+async function deletedPage(engine: BrainEngine, sourceId: string, target: HeldTarget & { state: 'tombstone_edited' | 'purged_differs' }, prefer: DriftSide, mirror: boolean):Promise<{ page: PlannedPage; detail: string } | { skip: string; detail: string }> {const { hold, state } = target;+ if (mirror && prefer === 'database' && hold.meta.keep_deleted) return { skip: 'mirror_keep_deleted',+ detail: `the user already kept this deletion (${hold.meta.keep_deleted.decided_at}); the hold is carried (mirror_keep_deleted) until the upstream edits ${hold.path} again` };const live = await readDeletedDriftTarget(engine, sourceId, { path: hold.path, sourcePath: hold.source_path, pageId: hold.page_id });if ('changed' in live) return { skip: `resolved_${live.changed}`, detail: DELETED_CHANGES[live.changed] };if (live.state !== state) return { skip: 'state_changed', detail: `it is ${live.state} now; preview it with ${shellQuote(heldDriftPreviewArgv(sourceId, 'deleted', live.state, prefer, hold.path))}` };const slug = live.tombstone?.slug ?? hold.slug ?? resolveSlugForPath(hold.source_path);const pin: DeletedDriftPin = { state, path: hold.path, source_path: hold.source_path, raw_file_hash: live.raw_file_hash, page_id: live.tombstone?.page_id ?? null,revision: live.tombstone?.revision ?? null, marker_digest: live.marker_digest, observed_at: hold.observed_at };+ if (mirror && prefer === 'database' && state === 'tombstone_edited') return { page: { slug, prefer, exceptions: [], keep_deleted: pin },+ detail: `${KEEP_DELETED_VERB}: ${hold.path}` };const detail = `${fileDriftActionVerb('deleted', state, prefer)}: ${hold.path}`;if (prefer === 'database') return { page: { slug, prefer, exceptions: [], remove_file: pin }, detail };const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });@@ -625,6 +634,31 @@ async function deletedPage(engine: BrainEngine, sourceId: string, target: HeldTareturn { page: { slug, prefer, exceptions: [], import_file: { ...pin, result_digest: publication.digest } }, detail };}+const KEEP_DELETED_VERB = 'keep the deletion and record it on the hold (the read-only mirror keeps its file)';++/**+ * Records a mirror's kept deletion on its hold, bound to the previewed pin: the file's bytes, the tombstone's id and revision+ * and the hold the preview observed. Writes no file and no page; a source that is no longer a read-only mirror is refused, and+ * the caller's CLI grant must cover the page as it does for every other file-drift page.+ */+async function applyKeepDeleted(ctx: OperationContext, page: ApprovedPage, artifact: KeepDeletedPage, requestId: string): Promise<RepairItemOutcome> {+ const pin = artifact.keep_deleted;+ const changed = (why: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason: 'changed_since_preview',+ detail: { request_id: requestId, action: 'keep_deleted', message: `${pin.path} changed since its keep-the-deletion was previewed: ${why}.`,+ fix: repreviewFix(page, heldDriftPreviewArgv(page.source_id, 'deleted', pin.state, 'database', pin.path)) } });+ if (!await sourceMirrorReadOnly(ctx.engine, page.source_id)) return changed('the source is no longer a read-only mirror');+ await asLocalCli(ctx.engine, () => authorizeReconcileGrant(ctx.engine, page.source_id, page.slug));+ try { await assertDeletedPin(ctx.engine, page.source_id, pin); } catch (error) {+ if (error instanceof OperationError && error.code === 'changed_since_preview') return changed(error.message);+ throw error;+ }+ const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [page.source_id]);+ const recorded = await ctx.engine.transaction(tx => recordKeepDeleted(tx, { sourceId: page.source_id, incarnation: source!.incarnation, path: pin.path, observedAt: pin.observed_at,+ state: pin.state, decision: { request_id: requestId, decided_at: new Date().toISOString(), page_id: pin.page_id, revision: pin.revision } }));+ if (!recorded) return changed('its hold was re-checked or cleared');+ return { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: 'database', action: 'keep_deleted', state: pin.state } };+}+/** #6712 PR 4b: the deleted-side pin as the preview hash and the publication read it again. */async function assertDeletedPin(engine: BrainEngine, sourceId: string, pin: DeletedDriftPin): Promise<DeletedDriftTarget> {const live = await readDeletedDriftTarget(engine, sourceId, { path: pin.path, sourcePath: pin.source_path, pageId: pin.page_id });@@ -834,8 +868,12 @@ export function fileDriftConsentText(hash: string, sourceId: string | undefined)let discards: UnimportedFile[] = [];let removals: string[] = [];let losing: number[] = [];+ let kept: string[] = [];+ let total = 0;try {const pages = [...readArtifact(hash, `gbrain repair file-drift --source ${sourceId ?? '<source>'}`).values()];+ total = pages.length;+ kept = pages.flatMap(page => 'keep_deleted' in page ? [page.keep_deleted.path] : []);discards = pages.flatMap(page => 'discards' in page && page.discards ? [page.discards] : []);removals = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);losing = pages.flatMap(page => 'lost_lines' in page && page.lost_lines ? [page.lost_lines] : []);@@ -844,6 +882,12 @@ export function fileDriftConsentText(hash: string, sourceId: string | undefined)const named = list(discards.map(unimportedFileText));const lost = losing.reduce((sum, lines) => sum + lines, 0);const dropping = lost ? ` It drops ${lost} line(s) that the copies it overwrites hold and the result does not carry, across ${losing.length} page(s).` : '';+ if (kept.length && kept.length === total) return {+ what: 'Record that the user keeps the deletion of each listed page on the read-only mirror.',+ why: `The preview ${hash} listed each deleted page whose file the mirror's upstream edited (${kept.length}).`,+ risk: 'Each hold stays and reads as decided (mirror_keep_deleted); no file, page or tombstone changes. A new upstream edit of a file or a restore asks again; a page that changed since the preview is skipped.',+ user_message: `Keep the deletion of ${kept.length} page(s) on the read-only mirror? Each hold records the decision and stops asking; nothing is deleted, restored or written: ${list(kept)}.`,+ };const removing = removals.length ? ` It also removes ${removals.length} file(s) that changed after their page was deleted, and the page does not hold what they say: ${list(removals)}.` : '';return {what: 'Apply the previewed file-drift resolutions: each listed page takes the preferred side, so either the canonical file is rewritten from the database copy or the page is replaced from the file.',@@ -891,6 +935,7 @@ export const fileDriftRepair: RepairHandler = {return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };}const held = opts.held ? await selectHeld(engine, sourceId, opts) : null;+ const mirror = held ? await sourceMirrorReadOnly(engine, sourceId) : false;const { slugs, classes, notSelected, unknown } = held? { slugs: [], classes: new Map<string, DriftClass>(), notSelected: held.notSelected, unknown: [] as UnknownDrift[] } : await selectSlugs(engine, sourceId, opts);const assessmentAt = new Date().toISOString();@@ -922,9 +967,9 @@ export const fileDriftRepair: RepairHandler = {const label = targetSlug ?? target?.hold.path ?? '';try {if (target?.state === 'tombstone_edited' || target?.state === 'purged_differs') {- const resolved = await deletedPage(engine, sourceId, { ...target, state: target.state }, opts.prefer);+ const resolved = await deletedPage(engine, sourceId, { ...target, state: target.state }, opts.prefer, mirror);if ('skip' in resolved) { count(resolved.skip); listing.push({ item: `${sourceId}:${label}`, class: resolved.skip, detail: resolved.detail }); continue; }- await authorizeReconcile(engine, sourceId, resolved.page.slug);+ await ('keep_deleted' in resolved.page ? authorizeReconcileGrant : authorizeReconcile)(engine, sourceId, resolved.page.slug);pages.push(resolved.page);listing.push({ item: `${sourceId}:${resolved.page.slug}`, class: `prefer_${opts.prefer}`, detail: resolved.detail });continue;@@ -1010,6 +1055,7 @@ export const fileDriftRepair: RepairHandler = {: 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']: 'detach_page' in page ? [page.slug, page.detach_page.revision, ABSENT_FILE_HASH, 'detach_page', page.detach_page.page_id, page.detach_page.observed_at]: 'remove_file' in page ? [page.slug, page.remove_file.revision, page.remove_file.raw_file_hash, 'remove_file', page.remove_file.state, page.remove_file.marker_digest]+ : 'keep_deleted' in page ? [page.slug, page.keep_deleted.revision, page.keep_deleted.raw_file_hash, 'keep_deleted', page.keep_deleted.state, page.keep_deleted.page_id, page.keep_deleted.observed_at]: 'import_file' in page ? [page.slug, page.import_file.revision, page.import_file.raw_file_hash, page.import_file.result_digest, page.import_file.state, page.import_file.marker_digest]: [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });// #6712 wave: a recreated file stays only once committed; without Git durability the next sync imports the committed deletion again.@@ -1063,6 +1109,7 @@ export const fileDriftRepair: RepairHandler = {pages: pages.map(page => ({ ...('release_hold' in page ? { slug: page.slug, action: 'release_hold', path: page.release_hold.path, verb: 're-screen the held file (the page and the file agree)', exceptions: page.exceptions }: 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }: 'detach_page' in page ? { slug: page.slug, action: 'detach_page', path: page.detach_page.path, verb: 'keep the page database-only (no file)', exceptions: page.exceptions }+ : 'keep_deleted' in page ? { slug: page.slug, action: 'keep_deleted', state: page.keep_deleted.state, path: page.keep_deleted.path, verb: KEEP_DELETED_VERB, exceptions: page.exceptions }: 'remove_file' in page ? { slug: page.slug, action: 'remove_file', state: page.remove_file.state, path: page.remove_file.path, verb: fileDriftActionVerb('deleted', page.remove_file.state, 'database'), exceptions: page.exceptions }: 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }: { slug: page.slug, ...(page.file_gone ? { action: 'recreate_file' } : {}), ...(page.class ? { class: page.class } : {}),@@ -1079,6 +1126,7 @@ export const fileDriftRepair: RepairHandler = {const requestId = requestIdFor(hash, page);let outcome: RepairItemOutcome;if ('release_hold' in artifact) outcome = await releaseAgreedHold(ctx.engine, page, artifact.release_hold, requestId);+ else if ('keep_deleted' in artifact) outcome = await applyKeepDeleted(ctx, page, artifact, requestId);else if ('remove_file' in artifact || 'import_file' in artifact || 'detach_page' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);else if ('soft_delete' in artifact) {const retired = await retireGhost(ctx, artifact.soft_delete.ghost, artifact.soft_delete.owner, async () => requestId);diff --git a/test/mirror-keep-deleted.test.ts b/test/mirror-keep-deleted.test.tsnew file mode 100644index 0000000000..d91adb101d--- /dev/null+++ b/test/mirror-keep-deleted.test.ts@@ -0,0 +1,259 @@+/**+ * Keep it deleted on a read-only mirror: gbrain repair file-drift --held --side deleted --state tombstone_edited --prefer database+ * records the decision on the hold (meta.keep_deleted) instead of removing a file gbrain never writes. The hold stays,+ * reads as carried (mirror_keep_deleted) and needs nobody; it is carried across a re-check of the same bytes, voided by a+ * new upstream edit or a restore, and rebound to the deletion marker when the tombstone is purged. A pass whose only work is+ * re-checking such a hold is not saved work. The mirror's checkout is never written.+ * PGLite always; Postgres when DATABASE_URL is set (managedBrain). Synthetic content only.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { 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/ops/contract.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { digest } from '../src/core/persistence/digest.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { gitHoldItem, readGitSourceHolds, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';+import { readPassRow, SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass-row.ts';+import { passBanked } from '../src/core/persistence/sync-pass-status.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { resolveRepairScope, type RepairPlanOptions } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++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 OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const logger = { info() {}, warn() {}, error() {} };+const SLUG = 'notes/page-x';+const PATH = SLUG + '.md';+const doc = (body: string) => '---\ntype: concept\ntitle: Page X\n---\n\n' + body + '\n';+const commitFile = (root: string, body: string, message: string) => { writeFileSync(join(root, PATH), doc(body)); git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const setup = ({ root }: { root: string }) => { git(root, 'init', '-q'); mkdirSync(join(root, 'notes'), { recursive: true }); commitFile(root, 'The first upstream body.', 'pages'); };+const mirror = (engine: BrainEngine) => engine.executeRaw("UPDATE sources SET config = config || '{\"mirror_read_only\": true}'::jsonb WHERE id='default'");+const incarnation = async (engine: BrainEngine) => (await engine.executeRaw<{ i: string }>("SELECT incarnation::text AS i FROM sources WHERE id='default'"))[0]!.i;+const holdOf = async (engine: BrainEngine): Promise<GitHoldRecord | undefined> => (await engine.executeRaw<{ r: GitHoldRecord }>(+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' AND completed_keys->0->>'path'=$1", [PATH]))[0]?.r;+const oldRecoveryVersion = (engine: BrainEngine) => engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,meta,recovery_version}',$2::text::jsonb) "+ + "WHERE op='sync-hold' AND completed_keys->0->>'path'=$1", [PATH, JSON.stringify(RECOVERY_VERSION - 1)]);+const snapshot = (engine: BrainEngine) => engine.readPageSnapshot(SLUG, { sourceId: 'default', includeDeleted: true });+/** The checkout as Git and the disk see it. */+const checkout = (root: string) => ({ head: git(root, 'rev-parse', 'HEAD'), status: git(root, 'status', '--porcelain', '--untracked-files=all'),+ file: readFileSync(join(root, PATH), 'utf8') });++async function repair(engine: BrainEngine, opts: Partial<RepairPlanOptions>): Promise<any> {+ return withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),+ { explicit: true, sourceFlag: 'default', held: true, side: 'deleted', state: 'tombstone_edited', ...opts } as never));+}++/** A page deleted in the database of a mirror whose upstream then edited its file: the tombstone_edited hold. */+async function tombstoneEdited(engine: BrainEngine, ctx: OperationContext, root: string): Promise<void> {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await mirror(engine);+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: SLUG, request_id: randomUUID(), expected_revision: (await snapshot(engine))!.revision } });+ expect((await snapshot(engine))!.page.deleted_at).toBeTruthy();+ commitFile(root, 'The upstream edited this file after the page was deleted.', 'upstream edit');+ await performManagedSync(engine, OPTS);+ expect((await holdOf(engine))?.meta).toMatchObject({ side: 'deleted', state: 'tombstone_edited' });+}++/** Previews and applies keep-the-deletion on the mirror; the checkout is byte-identical before and after. */+async function keepDeleted(engine: BrainEngine, root: string): Promise<void> {+ const before = checkout(root);+ const preview = await repair(engine, { prefer: 'database' });+ expect(preview.details.pages).toEqual([expect.objectContaining({ slug: SLUG, action: 'keep_deleted', state: 'tombstone_edited', path: PATH })]);+ expect(JSON.stringify(preview.details.pages)).not.toContain('remove_file');+ const applied = await repair(engine, { prefer: 'database', expect: preview.preview_hash });+ expect(applied.applied).toBe(1);+ expect(checkout(root)).toEqual(before);+ const tombstone = (await snapshot(engine))!;+ expect(tombstone.page.deleted_at).toBeTruthy();+ expect(tombstone.page.compiled_truth).not.toContain('upstream edited');+ const hold = (await holdOf(engine))!;+ expect(hold.meta.keep_deleted).toMatchObject({ page_id: Number(tombstone.page.id), revision: tombstone.revision });+ expect(typeof hold.meta.keep_deleted!.request_id).toBe('string');+ expect(Number.isNaN(Date.parse(hold.meta.keep_deleted!.decided_at))).toBe(false);+}++describe.each(testBackends())('keep it deleted on a read-only mirror (%s)', backend => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('the apply keeps the hold, marks it decided and carried (mirror_keep_deleted), and writes nothing into the mirror', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await keepDeleted(engine, root);+ const status: any = await readSyncStatus(engine, 'default');+ expect(status.carried).toEqual([expect.objectContaining({ class: 'mirror_keep_deleted', count: 1, sample: [PATH] })]);+ expect(status.needs_human).toBe(false);+ expect(status.holds).toEqual([expect.objectContaining({ path: PATH, needs_human: false })]);+ const item = gitHoldItem((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]!.holds.find(hold => hold.path === PATH)!);+ expect(item.keep_deleted).toBeTruthy();+ expect(item.fix.why).toContain('mirror_keep_deleted');+ expect((await repair(engine, { prefer: 'database' })).details.pages).toEqual([]);+ // A source that is writable again behaves as before: the decision no longer counts and --prefer database removes the file.+ await engine.executeRaw("UPDATE sources SET config = config - 'mirror_read_only' WHERE id='default'");+ const writable: any = await readSyncStatus(engine, 'default');+ expect(writable.carried ?? []).toEqual([]);+ expect(writable.holds).toEqual([expect.objectContaining({ path: PATH, needs_human: true })]);+ expect((await repair(engine, { prefer: 'database' })).details.pages).toEqual([expect.objectContaining({ action: 'remove_file' })]);+ }, { databaseUrl, setup }), 600_000);++ test('6: a re-check of the same bytes after a recovery-version bump carries the decision, and status shows it carried', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await keepDeleted(engine, root);+ const decided = (await holdOf(engine))!.meta.keep_deleted;+ await oldRecoveryVersion(engine);+ const before = checkout(root);+ const synced: any = await performManagedSync(engine, OPTS);+ expect(checkout(root)).toEqual(before);+ const hold = (await holdOf(engine))!;+ expect(hold.meta.recovery_version).toBe(RECOVERY_VERSION);+ expect(hold.meta.keep_deleted).toEqual(decided);+ expect(synced.carried).toEqual([expect.objectContaining({ class: 'mirror_keep_deleted', count: 1 })]);+ const status: any = await readSyncStatus(engine, 'default');+ expect(status.carried).toEqual([expect.objectContaining({ class: 'mirror_keep_deleted', count: 1 })]);+ expect(status.needs_human).toBe(false);+ }, { databaseUrl, setup }), 600_000);++ test('6b: in working-tree mode a re-check of the same bytes carries the decision too', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.include_working_tree', 'true');+ await tombstoneEdited(engine, ctx, root);+ expect((await holdOf(engine))!.meta).toMatchObject({ working: true });+ expect((await holdOf(engine))!.meta.blob_oid).toBeUndefined();+ await keepDeleted(engine, root);+ const decided = (await holdOf(engine))!.meta.keep_deleted;+ await oldRecoveryVersion(engine);+ await performManagedSync(engine, OPTS);+ const hold = (await holdOf(engine))!;+ expect(hold.meta.recovery_version).toBe(RECOVERY_VERSION);+ expect(hold.meta.keep_deleted).toEqual(decided);+ expect((await readSyncStatus(engine, 'default') as any).needs_human).toBe(false);+ }, { databaseUrl, setup }), 600_000);++ test('7a: a new upstream edit voids the decision: the hold asks again', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await keepDeleted(engine, root);+ commitFile(root, 'The upstream edited the file once more.', 'second upstream edit');+ await performManagedSync(engine, OPTS);+ const hold = (await holdOf(engine))!;+ expect(hold.meta).toMatchObject({ side: 'deleted', state: 'tombstone_edited' });+ expect(hold.meta.keep_deleted).toBeUndefined();+ const status: any = await readSyncStatus(engine, 'default');+ expect(status.carried ?? []).toEqual([]);+ expect(status.holds).toEqual([expect.objectContaining({ path: PATH, needs_human: true })]);+ const asked = gitHoldItem((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]!.holds.find(held => held.path === PATH)!);+ expect(asked.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'default', '--held', '--side', 'deleted', '--state', 'tombstone_edited', '--only', PATH, '--prefer', 'database']);+ expect(asked.fix.why).toContain('records it on the hold (mirror_keep_deleted; no file is removed');+ expect((await repair(engine, { prefer: 'database' })).details.pages).toEqual([expect.objectContaining({ action: 'keep_deleted' })]);+ }, { databaseUrl, setup }), 600_000);++ test('7b: gbrain restore voids the decision', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await keepDeleted(engine, root);+ await submitPageMutation(ctx, { operation: 'restore_page', params: { slug: SLUG, request_id: randomUUID(), expected_revision: (await snapshot(engine))!.revision } });+ expect((await snapshot(engine))!.page.deleted_at).toBeFalsy();+ await performManagedSync(engine, OPTS);+ expect((await holdOf(engine))?.meta.keep_deleted).toBeUndefined();+ const status: any = await readSyncStatus(engine, 'default');+ expect((status.carried ?? []).filter((carried: { class: string }) => carried.class === 'mirror_keep_deleted')).toEqual([]);+ }, { databaseUrl, setup }), 600_000);++ test('8: a purged tombstone carries the decision to purged_differs, bound to the deletion marker', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await keepDeleted(engine, root);+ const decided = (await holdOf(engine))!.meta.keep_deleted!;+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: SLUG, request_id: randomUUID(), expected_revision: (await snapshot(engine))!.revision, purge: true } });+ expect(await snapshot(engine)).toBeNull();+ await performManagedSync(engine, OPTS);+ const [marker] = await engine.executeRaw<{ value: unknown }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',+ [SYNC_ORIGIN_DELETED_OP, 'default:' + await incarnation(engine) + ':' + PATH]);+ expect(marker?.value).toBeTruthy();+ const hold = (await holdOf(engine))!;+ expect(hold.meta).toMatchObject({ side: 'deleted', state: 'purged_differs' });+ expect(hold.meta.keep_deleted).toMatchObject({ request_id: decided.request_id, decided_at: decided.decided_at, marker_digest: digest(marker!.value) });+ const status: any = await readSyncStatus(engine, 'default');+ expect(status.carried).toEqual([expect.objectContaining({ class: 'mirror_keep_deleted', count: 1 })]);+ expect(status.needs_human).toBe(false);+ }, { databaseUrl, setup }), 600_000);++ test('10a: the apply refuses with changed_since_preview when the source stops being a read-only mirror after the preview', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ const preview = await repair(engine, { prefer: 'database' });+ await engine.executeRaw("UPDATE sources SET config = config - 'mirror_read_only' WHERE id='default'");+ const before = checkout(root);+ const applied = await repair(engine, { prefer: 'database', expect: preview.preview_hash });+ expect(applied.applied).toBe(0);+ expect(JSON.stringify(applied)).toContain('changed_since_preview');+ expect((await holdOf(engine))!.meta.keep_deleted).toBeUndefined();+ expect(checkout(root)).toEqual(before);+ }, { databaseUrl, setup }), 600_000);++ test('10b: the apply refuses with changed_since_preview when the hold was re-checked after the preview', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ const preview = await repair(engine, { prefer: 'database' });+ await oldRecoveryVersion(engine);+ await performManagedSync(engine, OPTS);+ const before = checkout(root);+ const applied = await repair(engine, { prefer: 'database', expect: preview.preview_hash });+ expect(applied.applied).toBe(0);+ expect(JSON.stringify(applied)).toContain('changed_since_preview');+ expect((await holdOf(engine))!.meta.keep_deleted).toBeUndefined();+ expect(checkout(root)).toEqual(before);+ }, { databaseUrl, setup }), 600_000);++ test('10c: a CLI writer whose grant does not cover the page can neither preview nor apply keep-the-deletion', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ await repair(engine, { prefer: 'file' });+ const [{ ceiling }] = await engine.executeRaw<{ ceiling: unknown }>("SELECT grant_ceiling AS ceiling FROM persistence_local_writers WHERE lane='cli' AND revoked_at IS NULL");+ const narrow = () => engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling = grant_ceiling || '{\"slugPrefixes\": [\"elsewhere\"]}'::jsonb WHERE lane='cli'");+ await narrow();+ const refused = await repair(engine, { prefer: 'database' });+ expect(refused.details.pages).toEqual([]);+ expect(JSON.stringify(refused)).toContain('permission_denied');+ await engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling = $1::text::jsonb WHERE lane='cli'", [JSON.stringify(ceiling)]);+ const preview = await repair(engine, { prefer: 'database' });+ expect(preview.details.pages).toEqual([expect.objectContaining({ action: 'keep_deleted' })]);+ await narrow();+ const applied = await repair(engine, { prefer: 'database', expect: preview.preview_hash }).catch((error: unknown) => error);+ expect(JSON.stringify(applied, Object.getOwnPropertyNames(applied ?? {}))).toContain('permission_denied');+ expect((await holdOf(engine))!.meta.keep_deleted).toBeUndefined();+ }, { databaseUrl, setup }), 600_000);++ test('9: a pass whose only work is re-checking a kept deletion is not saved work, so it still builds the abandoned streak', () => managedBrain(async ({ engine, ctx, root }) => {+ await tombstoneEdited(engine, ctx, root);+ const inc = await incarnation(engine);+ const recheck = async () => {+ await oldRecoveryVersion(engine);+ await performManagedSync(engine, OPTS);+ const telemetry = (await readPassRow(engine, 'default', inc))!.value.telemetry;+ expect((await holdOf(engine))!.run_id).toBe(telemetry.pass_id);+ return passBanked(engine, 'default', inc, telemetry);+ };+ // Control: the same re-check of an undecided hold settles an older gbrain's hold, which is saved work.+ expect(await recheck()).toBe(true);+ await keepDeleted(engine, root);+ expect(await recheck()).toBe(false);+ }, { databaseUrl, setup }), 600_000);+});++describe('11: a repo-less brain', () => {+ test('the keep-the-deletion preview finds no held pages and does not refuse', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-keep-deleted-repoless-'));+ try {+ const env = { ...process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' };+ const cli = (...args: string[]) => execFileSync('bun', ['run', join(import.meta.dir, '..', 'src', 'cli.ts'), ...args], { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ cli('init', '--pglite', '--no-embedding');+ const out = JSON.parse(cli('repair', 'file-drift', '--source', 'default', '--held', '--side', 'deleted', '--state', 'tombstone_edited', '--prefer', 'database', '--json'));+ const [result] = out.results;+ expect(result).toMatchObject({ kind: 'file-drift', affected: 0, failed: [], complete: true, listing: [] });+ expect(result.details.pages).toEqual([]);+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 120_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 7cbe615d13..f8f2ec5191 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -378,6 +378,7 @@ test/migration-0-53-host-move-7900.test.tstest/migration-persistence-foreground-committed-index.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.ts+test/mirror-keep-deleted.test.tstest/mirror-readonly-write-through-7098.test.tstest/moved-pages-gst2584.test.tstest/notifier-passed-freshness-marker-7941.test.ts