Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep a newer file change from being overwritten by a database-wins repair (GST-2579)
garrytane9114493971b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e07e59362c..be51574d88 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++### A database-wins file-drift repair no longer discards a newer file edit++**`gbrain repair file-drift --prefer database` and `gbrain sources reconcile --apply` could overwrite a change to a page's file that sync had not imported yet, or bring back a file another writer had just deleted, with nothing in the preview saying so.** gbrain's own hold messages pointed agents at that command, so the loss was easy to walk into. A repair now checks each page's file against sync's import record before it takes the database copy.++- `src/core/persistence/unimported-file.ts` (new): the database copy may win only when the database itself held the version the file records: the bytes sync's import record names, or gbrain's own write of a revision the page has held (live or in its version history). Anything else is newer, whoever committed it, including gbrain's own writer commit of a revision whose database row never landed and a page with no import record at all; a wrong "keep" costs a hold and a wrong "take" costs an edit. A database edit made after the file's last commit still wins. The preview names the last commit that touched the file (sha, author, date).+- `gbrain repair file-drift --prefer database` with `--held` or `--all-drifted` leaves such pages held and lists them `kept_newer_file`; a file that another writer's delete commit removed is `kept_newer_delete` instead of being recreated. Naming one page with `--slug` still previews it, and the preview and the consent text name what it would discard.+- Every `gbrain repair file-drift` apply now asks for the user's consent (`consent: 'destructive'` in the repair registry), and the consent text lists the changes it would discard. A script that applied without `--yes` now exits 3.+- `gbrain sources reconcile` (preview and `--apply`, and the `writer_reconcile_preview` / `writer_reconcile_apply` operations) refuses `source_changed` when its result takes the database copy over such a file.+- Hold texts, `fix` steps and the docs that print a database-wins repair now give the preview as the step and say the apply needs the user's consent.+- `docs/guides/repair.md` explains the new behaviour and how to find edits an earlier repair overwrote, from the reconcile backups it kept.+- Tests: `test/db-wins-unimported-gst2579.test.ts` on PGLite and Postgres.+## [0.60.702.0] - 2026-11-12**A member can now be kept to pages labelled for it.** A group chat bot or a shared assistant bound to a member read every unlabelled page its source grant opened, and every summary, atom and fact made from them. `gbrain access member labelled-only <id> on` (off by default, unchanged on upgrade) keeps every credential of that member to pages that name it: the member or one of its groups in `readable_by`, or a folder or page rule listing them. Unlabelled pages, and derived pages and facts that name nobody, are hidden on every read path; with `access.members_read_lineage` on, a derived page passes only when every origin names the member. Writes follow the same rule. Only the operator on the brain host sets it, and never on the owner. It works the same on a repo-less brain and with rules in `access.yml`.diff --git a/docs/architecture/key-files/canonical-reconciliation-continued.md b/docs/architecture/key-files/canonical-reconciliation-continued.mdindex bda6b7f80a..0bef6982e6 100644--- a/docs/architecture/key-files/canonical-reconciliation-continued.md+++ b/docs/architecture/key-files/canonical-reconciliation-continued.md@@ -7,3 +7,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/rows-behind.ts` — doctor `sync_rows_behind_checkpoint` (BRAIN, after `sync_overwritten_db_edits`): per source counts and first slugs from `scanRowsBehind`; `warn` on `behind` rows with the read-only `gbrain repair rows-behind --source <id> --json` preview as the fix; `unknown` (info) when the `GBRAIN_DOCTOR_ROWS_BEHIND_TIMEOUT_MS` budget (default 10 s) stopped a scan or a checkout is unreadable; not applicable (ok) off the owner host and on repo-less brains.- `src/core/repair/rows-behind.ts` — `gbrain repair rows-behind --source <id>`: explicit-only, preview-bound (`--apply --expect <hash>`, `--include-ambiguous` adds rows with no import record). `reimport` submits the committed bytes through `submitManagedFileRepair`; `hold:<code>` writes the hold sync would have written (`writeGitHold`). Refused off the owner host (`not_owner_host`). Never runs on upgrade. Tests: `test/rows-behind-checkpoint-8071.test.ts` (PGLite and Postgres via `test/e2e/rows-behind-checkpoint-8071-postgres.test.ts`).- GST-2201, a file that comes back after sync deleted its page: `readShadowLevel` (`sync-pass.ts`) reads whether a tombstone is sync-made (`syncDeleteOrigin`, `sync-delete-tombstones.ts`) into `page.syncDeleted`, and `sync-classify.ts` classifies such a path `import` ahead of `deleted_same` / `deleted_edited` (uncommitted bytes take `dirty`; an old hold on it re-runs). The selection fingerprint carries `sync_deleted_restore`, so the first pass after the upgrade reads the whole level once. `originCommitted` (`sync-markers.ts`) says whether a page's file is in the tree at the source's `last_commit` or at HEAD (false off a managed checkout or for a company-brain source; an unreadable checkout counts as committed). A retention purge (`page-prepare.ts`) of a tombstone whose file is committed defers a sync-made tombstone (`revision_conflict`) and purges any other database-only (`databaseOnlyReason: committed_file`), so the file stays. Tests: `test/sync-restored-file-purge.test.ts` (PGLite and Postgres), `test/sync-classify-6712.test.ts`.+- `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`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex cbda3abddb..58e0a16b68 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1868,7 +1868,7 @@ More: [docs/guides/write-refusals.md#file_database_drift](../../docs/guides/writ| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version. | Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database. | Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file), decide with the user, then apply it with the plan hash; the next gbrain sync --source <source> --no-pull re-screens the hold. | agent | `repeat the read that failed` | 1 | no |+| A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version. | Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database. | Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file); the preview writes nothing and names any file edit or deletion sync never imported that the database copy would overwrite. Decide with the user: the apply needs their consent (run it without --yes to get the consent message, exit 3, and add --yes only after they agree). The next gbrain sync --source <source> --no-pull re-screens the hold. | agent | `repeat the read that failed` | 1 | no |More: [docs/guides/write-refusals.md#file_drift](../../docs/guides/write-refusals.md#file_drift)diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 84f44af5f2..540453a801 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -872,7 +872,7 @@ file holds the restored edit:```bashgbrain repair file-drift --source <id> --slug <slug> --prefer database # preview-gbrain repair file-drift --source <id> --slug <slug> --prefer database --apply --expect <preview-hash>+gbrain repair file-drift --source <id> --slug <slug> --prefer database --apply --expect <preview-hash> --yes # after the user agrees```A restored page is not listed again.@@ -3307,6 +3307,60 @@ and `gbrain agent logs --since`.equivalent: `--prefer database` keeps the database copy, `--prefer file`keeps the file.+<a id="file-drift-newer"></a>**A database-wins repair never silently discards a newer file change** (GST-2579).+Before this release, `--prefer database` (by `--held`, `--all-drifted` or+`--slug`) and a `gbrain sources reconcile` apply that took the database copy+wrote the page over its file even when the file held another writer's commit+that sync had not imported yet, and the preview said "exactly the preferred+side". Now a database-wins write goes ahead only when the database itself held+the version the file's bytes record: the bytes the page's last import read or left+on disk (sync's import record), or bytes a Git effect of one of the page's own+writes put in the file for a revision the page has held (its live revision or one+in its version history). So a database edit made after the file's last commit+still wins, shorter or not. Anything else is a change the database never held,+whoever committed it: another writer's commit, an uncommitted edit, gbrain's own+writer commit of a revision whose database row never landed, or a page with no+import record and no write of its own.++| Selection | A newer file edit | A commit that deleted the file (`file_gone`) |+|---|---|---|+| `--held`, `--all-drifted`, `--request` | listed `kept_newer_file`, nothing written, the hold stays | listed `kept_newer_delete`, nothing written, the hold stays |+| `--slug <slug>` | approved; the listing, `details.pages[].discards`, the warnings and the consent name the commit (sha, author, date), or say the edit is uncommitted | approved; the same places name the deleting commit |++Every `gbrain repair file-drift` apply now needs the user's consent: run the+printed apply without `--yes` and it exits 3 with the consent message, which+lists each newer change the database copy overwrites; add `--yes` only after+the user agrees. `gbrain sources reconcile` (and MCP+`writer_reconcile_preview` / `writer_reconcile_apply`) refuses+`source_changed` (detail `unimported_file_edit`) when a decision takes the+database copy over what such a file says (`take_database`, `delete` or+`set_value`); decide `take_file` for those paths, or preview the page alone with+`--slug` as above. A `never_committed` `file_gone` page resolved+`--prefer database` writes no file, so it is unaffected. The keep_db policy is+unchanged.++<a id="file-drift-past-losses"></a>**Finding earlier overwrites (read-only).** Every reconcile apply, a+file-drift page included, first keeps a private backup of both sides at+`~/.gbrain/reconciliation-previews/<request_id>.<digest>.json`+(`$GBRAIN_HOME/.gbrain/…` when `GBRAIN_HOME` is set), mode 0600, with+`retention: pre_admission_or_terminal`. Nothing prunes it: it stays until+`gbrain sources reconcile <source> <slug> --remove-backup <ref>` removes it once+its request has finished (`--backups` lists a page's). `preview.preimages.file_base64`+holds the file bytes the apply replaced. To list database-wins applies and check+whether the replaced bytes came from a commit gbrain never imported:++```bash+dir="${GBRAIN_HOME:-$HOME}/.gbrain/reconciliation-previews"+jq -r 'select(any(.preview.decisions[]; .action != "take_file"))+ | [.request_id, .preview.preconditions.source_id, .preview.preconditions.slug, .preview.preconditions.relative_path, .preview.preconditions.assessment_at] | @tsv' "$dir"/*.json+# For one listed backup: the blob of the bytes it replaced, and the commit that introduced that blob.+jq -r .preview.preimages.file_base64 "$dir/<backup>.json" | base64 -d | git -C <checkout> hash-object --no-filters --stdin+git -C <checkout> log --all --find-object=<blob> --format='%H %an %aI %s'+```++A commit there that gbrain did not write is an edit the repair overwrote;+`git -C <checkout> show <commit>:<path>` (or the decoded backup) recovers it.+<a id="deleted-canonical-files"></a>**A page whose canonical file is gone** (#6712). A page selected with`--slug` or `--request` whose recorded canonical file is missing is resolvedby where the deletion stands in Git:@@ -3400,7 +3454,7 @@ preview command with `--cursor <next_cursor>` (JSON: `details.window`):```bashgbrain repair file-drift --source <id> --held --side deleted --state file_gone --prefer database # window 1-gbrain repair file-drift --source <id> --held --side deleted --state file_gone --prefer database --apply --expect <hash>+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --prefer database --apply --expect <hash> --yes # after the user agreesgbrain repair file-drift --source <id> --held --side deleted --state file_gone --cursor <next_cursor> --prefer database # window 2```diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex eea1be4c97..2e03f5e91b 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -435,7 +435,8 @@ it, and a `--full` continues until every path it covers is settled.file is unchanged; a page sync deleted because its file was gone is an `import` once the file is back), and `db_ahead` (the page changed in the database and the filedid not; the sub-labels `pending`, `db_only` and `unproven` areinformational, and `gbrain repair file-drift --prefer database` writes one- back to its file if the owner wants it).+ back to its file if the owner wants it: its preview names any file change+ sync never imported, and its apply asks for the owner's consent).- `owner`, sync finishes it by itself: `in_flight` (admitted, not yetpublished), `import`, `reparse` (an unchanged file whose page is importedagain because its parser or schema pack changed, its origin moved, or andiff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 52f553f07a..bbd98479f7 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -413,7 +413,7 @@ records completion and leaves every page as it was.<a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*-<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*+<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions` (and, for `--prefer database`, any `kept_newer_file` page: a file edit sync never imported, which bulk keeps), and after they agree run the printed `--apply --expect <hash> --yes` command exactly as printed; without `--yes` it exits 3 with the consent message ([newer file changes](repair.md#file-drift-newer)). For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count, the exceptions and any `kept_newer_file` page, and after they agree run the apply command it prints (it ends in `--yes`), which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width when it holds vectors and prints the key to set; a fresh keyless install, a keyless brain with no vectors and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 32a3c75147..59c5334843 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -51,7 +51,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- |-| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. The receipt records the cause as `error_detail.origin: file_database_drift` (GST-1601). A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. Drift only in ordinary frontmatter keys (not a policy, privacy, lineage or trust key such as `readable_by`, `derived_from` or `trust_tier`, nor title, type or tags) does not refuse a write that leaves the frontmatter unchanged, such as `remember`: the write lands and the file keeps its own frontmatter, so that drift is left for reconcile (#8109). With `gbrain config set persistence.adopt_local_edits.source.<source> true` (off by default), a `remember`, `capture` or `add_timeline_entry` that meets a one-sided local edit (Git `HEAD` still holds the database copy; on a repo-less brain, any edit) is not refused: once the file has been unchanged for `persistence.adopt_quiet_ms` (default 5000), the owner commits that file on its own (`gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`; page history reason `adopted_local_edit`), then applies the write on top, and the receipt names `adopted`. A two-sided edit, a file that does not import, an edit to the title, type or a protected key, `put_page` and every other verb still refuse; doctor `local_edit_adoptions` lists adoptions of the last 24 h (GST-1601). The refusal also stays for a file over the page size limit or a page stored in segments, an unmerged path or a merge, cherry-pick, revert, rebase, `git bisect` (`BISECT_LOG`) or uncommitted `git merge --squash` (`SQUASH_MSG`) in progress, and a stale editor save (a file equal to an earlier stored revision, or missing a Facts or timeline row the last write added); the quiet wait never passes 30 s, since writes behind it on the same checkout wait meanwhile (#8755). It also stays when `git rev-parse --absolute-git-dir` answers with anything but one absolute, existing directory in valid UTF-8; a `git cherry-pick -n` leaves no marker, and its staged paths stay out of the adoption's commit (#8826). An adoption whose commit landed before its publication failed is published on its replay even after the write it was made for ended, and one that ends without committing after that commit names it on its receipt (`outcome.persistence.git_commit`, `landed_before_row: true`; #8824, #8767). | The receipt's fix (`gbrain sources writer failures <source>`, `gbrain write-request <request_id> --json`) previews keeping the database copy for that one page with `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (`--prefer file` previews importing the file instead); a person picks the side, then the agent runs the apply command the preview prints. A group of such receipts gets `--all-drifted --since <instant>` with the oldest receipt's time, so only pages that drifted since then are selected. For a hand merge: `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |+| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. The receipt records the cause as `error_detail.origin: file_database_drift` (GST-1601). A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. Drift only in ordinary frontmatter keys (not a policy, privacy, lineage or trust key such as `readable_by`, `derived_from` or `trust_tier`, nor title, type or tags) does not refuse a write that leaves the frontmatter unchanged, such as `remember`: the write lands and the file keeps its own frontmatter, so that drift is left for reconcile (#8109). With `gbrain config set persistence.adopt_local_edits.source.<source> true` (off by default), a `remember`, `capture` or `add_timeline_entry` that meets a one-sided local edit (Git `HEAD` still holds the database copy; on a repo-less brain, any edit) is not refused: once the file has been unchanged for `persistence.adopt_quiet_ms` (default 5000), the owner commits that file on its own (`gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`; page history reason `adopted_local_edit`), then applies the write on top, and the receipt names `adopted`. A two-sided edit, a file that does not import, an edit to the title, type or a protected key, `put_page` and every other verb still refuse; doctor `local_edit_adoptions` lists adoptions of the last 24 h (GST-1601). The refusal also stays for a file over the page size limit or a page stored in segments, an unmerged path or a merge, cherry-pick, revert, rebase, `git bisect` (`BISECT_LOG`) or uncommitted `git merge --squash` (`SQUASH_MSG`) in progress, and a stale editor save (a file equal to an earlier stored revision, or missing a Facts or timeline row the last write added); the quiet wait never passes 30 s, since writes behind it on the same checkout wait meanwhile (#8755). It also stays when `git rev-parse --absolute-git-dir` answers with anything but one absolute, existing directory in valid UTF-8; a `git cherry-pick -n` leaves no marker, and its staged paths stay out of the adoption's commit (#8826). An adoption whose commit landed before its publication failed is published on its replay even after the write it was made for ended, and one that ends without committing after that commit names it on its receipt (`outcome.persistence.git_commit`, `landed_before_row: true`; #8824, #8767). | The receipt's fix (`gbrain sources writer failures <source>`, `gbrain write-request <request_id> --json`) previews keeping the database copy for that one page with `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (`--prefer file` previews importing the file instead); the preview names any file edit or deletion sync never imported that the database copy would overwrite (in bulk such pages are kept, `kept_newer_file` / `kept_newer_delete`); a person picks the side, and the apply the preview prints asks for their consent (exit 3), taking `--yes` only after they agree ([newer file changes](repair.md#file-drift-newer)). A group of such receipts gets `--all-drifted --since <instant>` with the oldest receipt's time, so only pages that drifted since then are selected. For a hand merge: `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). || <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. A visibility edit cannot publish while the file is gone, so to keep the page and only narrow who reads it, add a page rule on the brain host: `gbrain access rule add --slug <slug> --readers <member> --source <source>` (it previews; `--yes` applies; list the owner's member to keep the owner reading; removing the rule undoes it; upgrade every gbrain host that shares the brain first). No file is written for the page. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). || <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. || <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |@@ -276,7 +276,7 @@ with each file and fix the ones that need no guessing."*| <a id="rename_identity_unreadable"></a>`rename_identity_unreadable` | Classic sync (GBRA-133 S-51): a file added in the same sync that removed or renamed another has a title or frontmatter `id` the database refused to compare (SQLSTATE 22021 or 22P05), so sync could not tell whether it is that page renamed. The new file is held and the old page keeps its id, links, facts and timeline; the rest of the source keeps syncing. A NUL byte or an unpaired surrogate in a title or id never reaches the database: sync treats such a value as absent and the pair takes the ordinary unconfirmed-rename path. | Remove the characters the database cannot store from the file title and `id`, commit, then `gbrain sync --source <source> --no-pull`. The pair is decided again when the file changes or on `gbrain sources retry-held <source>`. || <a id="rename_reconcile_failed"></a>`rename_reconcile_failed` | Classic sync (GBRA-133 S-67): a rename fell back to importing the new file, and removing the page of the old name then failed with an unexpected error (the hold records its class and code, never its message). The old page was kept and may duplicate the new one; the rest of the source keeps syncing. A transient database error and the reconcile's own "staleness unprovable" verdict still record the `<rename:…>` marker, which a later run converges. | Ask the user before `gbrain sync --source <source> --full --no-pull`: the full walk removes pages whose file is gone after checking each one (it re-reads the whole source). Or remove the old page with `gbrain delete --source <source> -- <slug>` (recoverable for 72 h). || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |-| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. |+| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file); the preview names any file edit sync never imported that the database copy would overwrite. Decide with the user; the apply asks for their consent (exit 3) and takes `--yes` only after they agree ([newer file changes](repair.md#file-drift-newer)), then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. || <a id="file_wins_rewrite"></a>`file_wins_rewrite` | `gbrain repair file-drift --prefer file` keeps the canonical file's bytes and adds only the protected parts reconcile keeps from the database: protected frontmatter keys the file lacks (inserted before the closing `---`) and database-only timeline rows (appended to the file's timeline, with a `<!-- timeline -->` line above a bare `## Timeline` heading so they stay in it). When the resolved page also differs in anything else (a value, a tag, the title, the body), keeping the file would mean re-rendering all of it, so the preview refuses the page and nothing is written. A database-only timeline row dated before the file's own rows sorts in among them rather than after them, so it refuses too. A file-wins apply accepted before this rule existed refuses the same way when it is prepared, and writes nothing. | Show the user the page's differences. Commit them into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win. || <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. || <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880); `gbrain repair url-clone-fences` lists a clone file whose HEAD asks for it this way under this code; apply restores the file from HEAD with its fence rows kept database-only, so the clone can pull, but does not import HEAD and reports `held` (#7897). `put_page`, `edit_page`, `capture`, `ingest_capture`, `brainstorm --save` and `sources reconcile` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |diff --git a/llms-full.txt b/llms-full.txtindex 17bc03954f..9e3ccd9c0d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9702,7 +9702,7 @@ records completion and leaves every page as it was.<a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*-<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*+<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions` (and, for `--prefer database`, any `kept_newer_file` page: a file edit sync never imported, which bulk keeps), and after they agree run the printed `--apply --expect <hash> --yes` command exactly as printed; without `--yes` it exits 3 with the consent message ([newer file changes](repair.md#file-drift-newer)). For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count, the exceptions and any `kept_newer_file` page, and after they agree run the apply command it prints (it ends in `--yes`), which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width when it holds vectors and prints the key to set; a fresh keyless install, a keyless brain with no vectors and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e96340ecf6..813b2d5e8c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -49,6 +49,6 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1761 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3+src/core/behavior-change-notice.ts 1762 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +1 GST-2579 db_wins_unimported_gst2579 row (since is the current VERSION until the merge slot; rows are data and cannot move)src/core/git/commit-push.ts 1658 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.tsindex 3072336f59..a0381837ed 100644--- a/src/commands/doctor/checks/maintenance-drift.ts+++ b/src/commands/doctor/checks/maintenance-drift.ts@@ -119,7 +119,7 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?return { name: 'maintenance_write_drift', status: 'warn', details,message: `${bounded ? 'At least ' : ''}${count} page(s) have a canonical file that differs from the database, so every coordinated write to them refuses source_changed `+ `(${rows.filter(row => row.drifted || row.concept_skips).map(row => `${row.source_id}: ${row.drifted} drifted, ${row.concept_skips} concept skip(s)`).join('; ')}). `- + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.${policyNote}${boundNote}`,+ + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database); its apply needs the user's consent (it asks; add --yes only after they agree).${policyNote}${boundNote}`,fix: agentFix(['gbrain', 'sources', 'reconcile', first, '--brain', 'host', '--audit', '--conflicts', '--json'],'Read-only: lists the conflict receipts grouped by slug, whether each file still differs, its drift class and producer.', 'maintenance_write_drift', { docs }) };} catch (error) {diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 06a9792cad..284942b0ff 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -38,6 +38,7 @@ import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts'import { resolveSecretRules } from '../core/secret-spans.ts';import { normalizeSeatLabel } from '../core/context/seat.ts';import { agentSessionFlagArgs } from '../core/repair/agent-session-facts.ts';+import { fileDriftConsentText } from '../core/repair/file-drift.ts';import { privateLabelsLedger } from './repair-private-labels.ts';import { isAbsolute } from 'node:path';import { readFileSync } from 'node:fs';@@ -546,8 +547,12 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),...(kind === 'origin-twins' || kind === 'timeline-order' || kind === 'contact-rows' || kind === 'provenance' ? slugs.flatMap(slug => ['--slug', slug]) : []),...(generations ? generationsSelectionArgv(generations) : []),- ...(kind === 'agent-session-facts' ? agentSessionFlagArgs({ cwdPrefixes, sessions, principal }) : [])];- const custom = repairSpec(kind as RepairKind).consentText;+ ...(kind === 'agent-session-facts' ? agentSessionFlagArgs({ cwdPrefixes, sessions, principal }) : []),+ ...(kind === 'file-drift' ? [...slugs.flatMap(slug => ['--slug', slug]), ...requests.flatMap(id => ['--request', id]), ...(allDrifted ? ['--all-drifted'] : []),+ ...(driftClass ? ['--class', driftClass] : []), ...(since ? ['--since', since] : []), ...(held ? ['--held'] : []), ...(side ? ['--side', side] : []),+ ...(state ? ['--state', state] : []), ...(provenance ? ['--provenance', provenance] : []), ...(cursor ? ['--cursor', cursor] : []), ...(prefer ? ['--prefer', prefer] : [])] : [])];+ // GST-2579: a file-drift consent names the unimported file edits its database-wins pages overwrite.+ const custom = kind === 'file-drift' ? fileDriftConsentText(expect, source) : repairSpec(kind as RepairKind).consentText;const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {what: `Rewrite the previewed ${kind} changes on disk and import them`,why: `The preview ${expect} listed each file change; applying it rewrites those files in place and publishes them.`,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 590ab065e6..eed7c82021 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1563,6 +1563,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.693.0', id: 'member_save_withdrawn_scope_gst2346', text: 'A remote `remember` onto a member\'s own page (`memory/members/<id>`) is refused `fact_withdrawn` only when that member could read what was withdrawn: a fact on its own page, its own copy withdrawn by the brain host, or for the brain owner a fact it reads. A claim withdrawn by the brain host or the owner that the member never read no longer refuses its save: the fact saves as the member\'s own active row with the same reply as a new claim. A schema migration makes the database insert guards mark a row on a member page only by that page\'s own withdrawals; a withdrawal still expires matching rows on member pages when it is made, and strikes them in the page\'s file, so an import of a member page\'s file no longer marks a row withdrawn by a withdrawal of another subject. The same holds for each item of a `remember` batch (`items`), a replay with the same `request_id`, a `replaces` and the write receipt (`get_write_request`). Trusted local saves keep the check they had.' },{ since: '0.60.694.0', id: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },{ since: '0.60.694.0', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ { since: '0.60.702.0', id: 'db_wins_unimported_gst2579', text: 'A database-wins file-drift repair no longer overwrites a newer change to the file that sync has not imported. `gbrain repair file-drift --prefer database` by `--held` or `--all-drifted` now lists such a page `kept_newer_file` (a file edited since the last import) or `kept_newer_delete` (a file another writer deleted) and leaves it held; naming the page with `--slug` previews it and names the commit it would discard (sha, author, date). Every file-drift apply now asks for the user\'s consent, so a script that applies without `--yes` exits 3. `gbrain sources reconcile --apply` refuses `source_changed` when its result takes the database copy over such an edit. A database copy newer than the file (the file still holds what sync imported, or gbrain\'s own write of a revision the page has since moved past) repairs as before; gbrain\'s own writer commit of a revision the database never took counts as newer. The keep_db policy is unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cca0fb7231..552215c69b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--code', '--concurrency', '--confirm-destructive', '--content-root', '--cursor', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--hold-state', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],- 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2a76592151..ff2cfd1baf 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -348,7 +348,7 @@ export const CODES = {fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },file_database_drift: { class: 'caller', summary: "A page's checkout file and its database copy differ, so the writer left both as they are instead of replacing one with the other; the item is held and the rest of the batch continues.", why: "Replacing the file with the database copy (or the database copy with the file) would destroy an edit only the replaced copy holds: a hand edit sync has not imported, an unindexed file at the page's path, or a database edit the file never received (#6982). The file is replaceable only when it equals the live page or one of its recent page_versions rows.", docs: 'docs/guides/write-refusals.md#file_database_drift', suggestion: 'If the file holds the newer edit, run gbrain sync --source <source> to import it; if the database copy is newer, re-save the page with write-through on; when both changed, ask the user which version to keep before retrying.' },fix_not_writable: { class: 'host_only', summary: "A gbrain lint fix was not applied because the file refused the write (EACCES, EPERM or EROFS); the file was left unchanged.", why: "Lint repairs files in place, and this file's permissions or a read-only mount stopped the write; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#fix-not-writable', suggestion: "Make the file writable by the user running gbrain, or pass its directory or file name to gbrain lint --exclude, then lint again." },- file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file), decide with the user, then apply it with the plan hash; the next gbrain sync --source <source> --no-pull re-screens the hold.' },+ file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file); the preview writes nothing and names any file edit or deletion sync never imported that the database copy would overwrite. Decide with the user: the apply needs their consent (run it without --yes to get the consent message, exit 3, and add --yes only after they agree). The next gbrain sync --source <source> --no-pull re-screens the hold.' },file_drift_mixed_selection: { class: 'caller', summary: "gbrain repair file-drift --held selected held pages of more than one Decision (side, or deleted state), so nothing was previewed: one --prefer must not resolve differently shaped drift in bulk.", why: "Each side and deleted state is its own Decision with its own meaning of --prefer file and --prefer database; resolving them together would apply one choice to questions the user answered differently, or not at all.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Preview one Decision at a time with the narrower commands the message names (--held --side <side>, plus --state <state> for --side deleted), or narrow with --only / --skip.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },file_drift_state_required: { class: 'caller', summary: "gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed.", why: "In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.tsindex 7307f35f2d..7fd87564bb 100644--- a/src/core/persistence/drift-conflicts.ts+++ b/src/core/persistence/drift-conflicts.ts@@ -464,6 +464,6 @@ export class ConceptDriftSkips {}}return this.skipped.length ? [`List them: ${auditConflictsCommand(this.sourceId)}`,- `Preview the resolution: ${fileDriftRepairCommand(this.sourceId)} (or --prefer database); apply with the --expect hash it prints.`] : [];+ `Preview the resolution: ${fileDriftRepairCommand(this.sourceId)} (or --prefer database); its apply needs the user's consent (it asks; add --yes only after they agree).`] : [];}}diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex b37b590c5a..346167d42c 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -149,7 +149,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout+ `to see each one's state and repair the rest now, run ${fences.join(', ')} on the brain host (a read-only preview that prints the apply command).`] : []),...(concurrent.length ? [`Some notes changed in their files while an agent saved a different version to the brain, so both were kept: on the brain host run ${concurrent.map(id => `'gbrain sources status ${id}'`).join(', ')} and reconcile each named note with 'gbrain sources reconcile <source> <slug> --preview'.`] : []),...(stalled.length ? [`Some files are held because the brain's write owner could not finish preparing them (the files themselves are fine): on the brain host run ${stalled.map(id => `'gbrain sources writer status --source ${id} --json'`).join(', ')} to see what the owner was stuck on, fix that or upgrade gbrain, then 'gbrain sources retry-held <source>' and the same sync.`] : []),- ...(drift.length ? [`Some notes were edited in the brain after their files were last imported, so sync kept the brain's version instead of overwriting it: on the brain host run ${drift.map(id => `'gbrain sources status ${id}'`).join(', ')} and resolve each named note with 'gbrain repair file-drift --source <source> --slug <slug> --prefer database' (or '--prefer file').`] : []),+ ...(drift.length ? [`Some notes were edited in the brain after their files were last imported, so sync kept the brain's version instead of overwriting it: on the brain host run ${drift.map(id => `'gbrain sources status ${id}'`).join(', ')} and preview each named note with 'gbrain repair file-drift --source <source> --slug <slug> --prefer database' (or '--prefer file'), which names what it would overwrite; the apply asks for the user's consent.`] : []),...(dirty.length ? [`Some files have uncommitted edits in the brain's checkout that sync would not overwrite: on the brain host commit them, then run ${dirty.map(id => `'gbrain sync unblock --source ${id} --apply'`).join(', ')} (or 'gbrain sources retry-held <source>') and the same sync.`] : []),];return { argv: holdRepairSteps(first.source_id, first.route ?? { fences: 0, others: 1 }).argv, consent: [], actor: 'host_admin', requires_exclusive: false, why,diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.tsindex 325e91a1cb..e0e36947ac 100644--- a/src/core/persistence/pending-import.ts+++ b/src/core/persistence/pending-import.ts@@ -158,6 +158,13 @@ export async function commitMessage(root: string, commit: string): Promise<strinreturn gitRead(root, ['log', '-1', '--format=%B', commit]).catch(() => null);}+/** GST-2579: the newest commit (from HEAD) that touched `path`, with its author and author date; null when none did or Git cannot read it. */+export async function lastCommitOf(root: string, path: string): Promise<{ sha: string; author: string; date: string } | null> {+ const out = await quiet(gitRead(root, ['log', '-1', '--no-show-signature', '--format=%H%x00%an%x00%aI', 'HEAD', '--', `:(literal)${relative(root, path).split(sep).join('/')}`]));+ const [sha = '', author = '', date = ''] = (out ?? '').split('\0');+ return /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(sha) ? { sha, author, date } : null;+}+/** #8824: the first parent of `commit` in `root`'s repository, or null when it has none or Git cannot read it. */export async function commitParent(root: string, commit: string): Promise<string | null> {return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `${commit}^`]));diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex 4b9805d062..eb1e4640ed 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -21,6 +21,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { serializePageToMarkdown } from '../markdown.ts';import { liveFileDrift } from './drift-conflicts.ts';import { clearGitHold, GIT_HOLD_OP, gitHoldFingerprint, outOfAttemptsHold, readGitHold } from './sync-holds.ts';+import { discardedFilePaths, unimportedFile, unimportedFileRefusal } from './unimported-file.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';@@ -127,6 +128,7 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<stautoDecisions = chosen.auto;}if (autoDecisions.length) assertAutoDecisions(autoDecisions, state.file, database, decisions);+ await refuseUnimportedDiscard(engine, state, decisions, autoDecisions);const prepared = await prepareReconcileResult(engine, state, decisions);const reviewRequired = classification?.verdict === 'review_required';const preview: ReconcileArtifact = { format_version: autoDecisions.length ? 2 : 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,@@ -146,13 +148,26 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<stsha256(serializePageToMarkdown(state.snapshot.page, state.snapshot.tags)) !== state.pins.raw_file_hash,result_digest: preview.result_digest, preview };}+/**+ * GST-2579: refuses a resolution that writes the database copy over a file edit gbrain never imported or wrote+ * (unimported-file.ts), unless `discard` is that file's exact hash: `repair file-drift --prefer database` passes it for a+ * page whose preview named the edit and whose apply the user consented to.+ */+async function refuseUnimportedDiscard(engine: BrainEngine, state: ReconcileState, decisions: ReconcileArtifact['decisions'], auto: AutoDecision[], discard?: string): Promise<void> {+ const paths = discardedFilePaths(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), decisions, auto);+ if (!paths.length || discard === state.pins.raw_file_hash) return;+ const newer = await unimportedFile(engine, state);+ if (newer) throw unimportedFileRefusal(state.pins.source_id, state.pins.slug, newer, paths);+}/*** Applies one reconcile preview under its request id. `keep_file_bytes` (`repair file-drift --prefer file`) keeps the canonical* file's bytes plus the protected parts the result keeps from the database (`fileWinsContent`), and refuses `file_wins_rewrite`* at prepare when the result needs any other change. #7974: a pending request accepted before that rule prepares under it, so* it refuses `file_wins_rewrite` instead of rendering the result, writes nothing, and the page is previewed again.+ * GST-2579: a resolution that takes the database copy over an unimported file edit refuses (`refuseUnimportedDiscard`) unless+ * `opts.discardFileHash` names that file's exact bytes, which only `repair file-drift`'s consented apply passes.*/-export async function runReconcileApply(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {+export async function runReconcileApply(engine: BrainEngine, params: Record<string, unknown>, opts: { discardFileHash?: string } = {}): Promise<Record<string, unknown>> {strictReconcileKeys(params, ['source_id', 'slug', 'preview', 'request_id', 'keep_file_bytes'], ['source_id', 'slug', 'preview', 'request_id']);if (params.keep_file_bytes !== undefined && params.keep_file_bytes !== true) throw opError('invalid_params', 'keep_file_bytes is true or absent.','Pass keep_file_bytes: true to keep the canonical file\'s bytes and add only the protected parts the result keeps from the database (any other change refuses file_wins_rewrite), or omit it.');@@ -160,7 +175,8 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striconst artifact = validateReconcileArtifact(params.preview);artifact.decisions = reconcileDecisions(artifact.decisions);const requestId = requireUuid(params.request_id as string);- return admitReconcileArtifact(engine, { sourceId, slug, authority, artifact, requestId, keepFileBytes: params.keep_file_bytes === true }, async (row, replayed) => {+ return admitReconcileArtifact(engine, { sourceId, slug, authority, artifact, requestId, keepFileBytes: params.keep_file_bytes === true,+ guard: state => refuseUnimportedDiscard(engine, state, artifact.decisions, artifact.auto_decisions ?? [], opts.discardFileHash) }, async (row, replayed) => {const settled = replayed && isTerminal(row) ? row : await waitForWrite(engine, row, await config(engine));const cleared = settled.state === 'committed' ? await clearAgreedStallHold(engine, sourceId, slug) : null;return { ...writeResponse(settled), ...(cleared ? { cleared_hold: cleared } : {}) };@@ -187,10 +203,11 @@ async function clearAgreedStallHold(engine: BrainEngine, sourceId: string, slug:* the preimages, retains the backup and admits the request, replaying a prior request under the same id. `settle` runs on* the admitted or replayed row inside the same refusal handling. `intentExtra` rides the stored intent without entering the* digest; `transaction` wraps the admission transaction (`admitWrite`). #6712 PR 4b: the sync pass's keep_db admission- * (repair/keep-db-policy.ts) uses both and settles without waiting for publication.+ * (repair/keep-db-policy.ts) uses both and settles without waiting for publication. `guard` runs on the re-read state+ * before anything is retained or admitted (GST-2579: `runReconcileApply`'s unimported-edit refusal; keep_db passes none).*/export async function admitReconcileArtifact<T>(engine: BrainEngine, input: { sourceId: string; slug: string; authority: Awaited<ReturnType<typeof authorizeReconcile>>['authority'];- artifact: ReconcileArtifact; requestId: string; keepFileBytes?: boolean; intentExtra?: Record<string, unknown>;+ artifact: ReconcileArtifact; requestId: string; keepFileBytes?: boolean; intentExtra?: Record<string, unknown>; guard?: (state: ReconcileState) => Promise<void>;transaction?: <U>(fn: (tx: BrainEngine) => Promise<U>) => Promise<U> }, settle: (row: WriteRequest, replayed: boolean) => Promise<T>): Promise<T> {const { sourceId, slug, authority, artifact, requestId } = input;if (artifact.preconditions.source_id !== sourceId || artifact.preconditions.slug !== slug || artifact.status !== 'ready' || artifact.conflicts.length) {@@ -216,6 +233,7 @@ export async function admitReconcileArtifact<T>(engine: BrainEngine, input: { soconst adopt = reconcileReadOptions(artifact);const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at, adopt);assertPreimages(artifact, state);+ await input.guard?.(state);assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);const prepared = await prepareReconcileResult(engine, state, artifact.decisions);if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('resolved content or canonical policy changed');diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 413d384140..acc88193ec 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -683,7 +683,7 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:const dirtyText = `the ${route.dirty ?? 0} worktree-dirty hold(s) are uncommitted edits in the checkout that sync would not overwrite: commit them (gbrain sources status ${sourceId} names each file), `+ `then run ${unblock.join(' ')}, which re-screens every held file that is now committed, and the same sync`;const driftText = `for each file-drift hold, preview the resolution with gbrain repair file-drift --source ${sourceId} --slug <slug> --prefer database (or --prefer file) `- + `(gbrain sources status ${sourceId} names each slug and the database write sync did not overwrite), decide with the user, apply it with the plan hash, then run gbrain sync --source ${sourceId} --no-pull`;+ + `(gbrain sources status ${sourceId} names each slug and the database write sync did not overwrite) and decide with the user. ${FILE_DRIFT_APPLY_STEP} Then run gbrain sync --source ${sourceId} --no-pull`;if (route.stalled && !route.others && !content && !route.concurrent && !route.dirty && !route.drift) {return { argv: stalled.status, commands: [stalled.status.join(' '), stalled.retry.join(' '), stalled.sync.join(' ')], text: stalledText };}@@ -747,12 +747,20 @@ function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'metconst options = `This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `+ `${fileDriftActionVerb('deleted', state, 'file')}. `;return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',- why: `${what}${options}Decide with the user, run the apply command the preview prints, then sync again. The rest of the source is not blocked.`,+ 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).` },verify };}+/**+ * GST-2579: what every printed file-drift fix says about the step after its read-only preview. A database-wins apply+ * replaces the file, so it is the user's decision (ask_user): the CLI asks for consent and the apply takes --yes only after they agree.+ */+export const FILE_DRIFT_APPLY_STEP = 'The preview writes nothing and names what the winning side overwrites: in bulk, --prefer database keeps every file edit or deletion sync never imported '+ + '(kept_newer_file, kept_newer_delete), and a page named with --slug lists the commit it would discard. The apply it prints replaces the other copy and needs the user\'s consent: '+ + 'show them what the preview names, run the apply without --yes to get its consent message (exit 3), and add --yes only after they agree.';+/*** The exact next step for one hold: the repair preview for frontmatter, the* split or exclude for size, and for a fence hold the step its state calls@@ -820,7 +828,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cconst verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',why: `${record.path} was deleted in Git while ${by}, so sync held the deletion instead of removing a page that changed. This preview (writes nothing) keeps the page and recreates its file; `- + `${preview('file').join(' ')} previews the deletion instead (soft-deletes exactly that page). Decide with the user, run the apply command the preview prints, then sync again. The rest of the source is not blocked.`,+ + `${preview('file').join(' ')} previews the deletion instead (soft-deletes exactly that page). 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).` },verify };@@ -844,7 +852,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c? `Page ${slug} differs from ${record.path} and has no import record to tell whether the file or the database changed, so sync held the file instead of overwriting the database version. `: `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' && !record.meta.side ? 'the file did not change in Git': side === 'both' ? 'the file changed too' : 'no import record says whether the file changed too'}). `;- const decide = 'Decide with the user which version wins, run the apply command the preview prints, then sync again. The rest of the source is not blocked.';+ const decide = `Decide with the user which version wins. ${FILE_DRIFT_APPLY_STEP} Then sync again. The rest of the source is not blocked.`;// #6517: a shared-origin delete kept the file for this surviving page, and its receipt names importing the file.const shared = record.meta.shared_origin === true;return { argv: preview(shared ? 'file' : 'database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#file_drift',diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex b57bb8a0c1..2f8f837d90 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -26,6 +26,7 @@ import { isSyncKnockOn, knockOnRoot, SYNC_CURSOR_FENCE_ORIGIN, SYNC_KNOCK_ON_ORIimport { writeFailureDiagnostic } from './verb-errors.ts';import { publicCategory, type PublicCategory } from './public-category.ts';import { ownerMarkerRestoreFix } from './owner-marker.ts';+import { FILE_DRIFT_APPLY_STEP } from './sync-holds.ts';export type TerminalCategory =| 'recovery_pending' | 'recovery_blocked'@@ -127,7 +128,7 @@ function inspect(sourceId: string, why: string, userMessage?: string): Action {*/export function driftSinceAction(sourceId: string, since: string): Action {return { argv: ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--all-drifted', '--since', since, '--prefer', 'database'], consent: [], actor: 'agent', requires_exclusive: false,- why: `Previews keeping the database copy of every page still drifted since ${since} and writes nothing (it refuses a mix of drift classes and names --class for each); --prefer file previews importing the files instead. Decide with the user, then apply with the printed plan hash.`,+ why: `Previews keeping the database copy of every page still drifted since ${since} and writes nothing (it refuses a mix of drift classes and names --class for each); --prefer file previews importing the files instead. Decide with the user. ${FILE_DRIFT_APPLY_STEP}`,verify: { argv: failuresArgv(sourceId) }, docs: 'docs/guides/write-refusals.md#file_database_drift' };}@@ -260,7 +261,7 @@ function route(input: TerminalInput): Partial_ {if (known === 'file_database_drift' || known === 'canonical_path_occupied' || known === 'unbound_source') {return { category: 'file_conflict', code, origin: origin ?? known, ...row('file_database_drift'),action: { argv: ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', input.slug, '--prefer', 'database'], consent: [], actor: 'agent', requires_exclusive: false,- why: `Previews keeping the database copy of ${input.slug} and rewriting its file, and writes nothing; --prefer file previews importing the file instead. Decide with the user, apply with the printed plan hash, then resubmit the write with a new request id.`,+ why: `Previews keeping the database copy of ${input.slug} and rewriting its file, and writes nothing; --prefer file previews importing the file instead. Decide with the user. ${FILE_DRIFT_APPLY_STEP} Then resubmit the write with a new request id.`,verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#file_database_drift' } };}if (known === 'canonical_file_missing') {diff --git a/src/core/persistence/unimported-file.ts b/src/core/persistence/unimported-file.tsnew file mode 100644index 0000000000..a05a059616--- /dev/null+++ b/src/core/persistence/unimported-file.ts@@ -0,0 +1,110 @@+/**+ * GST-2579: a database-wins repair must not silently discard a file edit sync never imported. A reconcile result that+ * takes the database copy over the file's own value at a path (take_database, delete or set_value on what the file+ * says) overwrites the canonical file; when the file's bytes are not ones gbrain imported or wrote, that overwrite+ * drops an edit nobody saw: another writer's commit that sync has not imported yet, or an uncommitted edit.+ *+ * The bytes count as known only when the database itself held the version they render: the bytes the page's last+ * recorded import read or left on disk (sync's import record: raw_sha256, disk_sha256, written in the publication that+ * stored them), or bytes a Git effect of one of the page's own writes put in that file (expected_hash) for a revision the+ * page has held, live or in its version history. gbrain's own writer commit over a database row that never took that+ * revision (the Git commit landed and the row did not) is newer, as is anything else, including a page with no import+ * record and no write of its own: a wrong "newer" keeps a hold, a wrong "known" loses an edit. Git only describes the+ * newer bytes (the commit that holds them, or that they are uncommitted); it never decides that they are known, and+ * neither does who made the commit.+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { digest, gitBlobOid } from './digest.ts';+import type { ReconcileDecision } from './reconcile-merge.ts';+import type { AutoDecision } from './reconcile-additive.ts';+import { ABSENT_FILE_HASH, type ReconcileState } from './reconcile-state.ts';+import { readSyncImportProvenance } from './sync-holds.ts';+import { headBlob, lastCommitOf } from './pending-import.ts';++/** A canonical file whose bytes gbrain never imported or wrote, and what Git says about them. */+export interface UnimportedFile {+ path: string;+ /**+ * unimported_commit: HEAD holds the bytes and sync imported other bytes. uncommitted_edit: HEAD holds other bytes.+ * no_import_record: sync recorded no import of the page and gbrain never wrote the file. unknown: Git could not say+ * whether the bytes are committed. unimported_delete: a commit deleted the file and its live page still holds the+ * content (a held file_gone deletion); recreating the file from the page undoes that commit.+ */+ reason: 'unimported_commit' | 'uncommitted_edit' | 'no_import_record' | 'unknown' | 'unimported_delete';+ /** The newest commit that touched the file, when HEAD holds exactly these bytes; for unimported_delete the deleting commit (null when Git could not name it). */+ commit: { sha: string; author: string; date: string } | null;+}++function valueAt(page: unknown, path: string): { has: boolean; value?: unknown } {+ let node = page;+ for (const key of path.slice(1).split('/').map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'))) {+ if (node === null || typeof node !== 'object' || Array.isArray(node) || !Object.hasOwn(node, key)) return { has: false };+ node = (node as Record<string, unknown>)[key];+ }+ return { has: true, value: node };+}++/** The decided paths (automatic additive ones excepted) whose result drops what the file says there. */+export function discardedFilePaths(file: unknown, database: unknown, decisions: readonly ReconcileDecision[], auto: readonly AutoDecision[] = []): string[] {+ const automatic = new Set(auto.map(decision => decision.path));+ return decisions.filter(decision => {+ if (automatic.has(decision.path) || decision.action === 'take_file') return false;+ const own = valueAt(file, decision.path);+ if (decision.action === 'delete') return own.has;+ const kept = decision.action === 'take_database' ? valueAt(database, decision.path) : { has: true, value: decision.value };+ return own.has !== kept.has || digest(own.value ?? null) !== digest(kept.value ?? null);+ }).map(decision => decision.path);+}++/**+ * Whether a Git effect of one of the page's own writes put exactly these bytes in its file for a revision the page has+ * held: its live revision, or one its version history keeps.+ */+async function gbrainWroteHeldBytes(engine: BrainEngine, pins: ReconcileState['pins']): Promise<boolean> {+ const rows = await engine.executeRaw<{ found: number }>(`SELECT 1 AS found FROM persistence_requests r+ JOIN persistence_effects e ON e.request_id=r.id AND e.kind='git' AND e.revision IS NOT NULL+ JOIN pages p ON p.id=$4 AND p.source_id=r.source_id+ WHERE r.source_id=$1 AND r.slug=$2 AND e.data->>'expected_hash'=$3+ AND (e.revision=p.knowledge_revision OR EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id=p.id AND v.knowledge_revision=e.revision))+ LIMIT 1`, [pins.source_id, pins.slug, pins.raw_file_hash, Number(pins.page_id)]);+ return rows.length > 0;+}++/** The canonical file of a reconcile state when its bytes are not ones gbrain imported or wrote; null when they are, or when the file is absent. */+export async function unimportedFile(engine: BrainEngine, state: Pick<ReconcileState, 'root' | 'path' | 'raw' | 'pins'>): Promise<UnimportedFile | null> {+ const { pins } = state;+ if (pins.raw_file_hash === ABSENT_FILE_HASH) return null;+ const record = await readSyncImportProvenance(engine, pins.source_id, pins.source_incarnation, Number(pins.page_id));+ if (record && (record.raw_sha256 === pins.raw_file_hash || record.disk_sha256 === pins.raw_file_hash)) return null;+ if (await gbrainWroteHeldBytes(engine, pins)) return null;+ const path = pins.relative_path.split('\\').join('/');+ const head = await headBlob(state.root, state.path);+ const committed = head !== null && gitBlobOid(state.raw, head.length === 64 ? 'sha256' : 'sha1') === head;+ const commit = committed ? await lastCommitOf(state.root, state.path) : null;+ if (!record) return { path, reason: 'no_import_record', commit };+ return { path, reason: committed ? 'unimported_commit' : head === null ? 'unknown' : 'uncommitted_edit', commit };+}++/** What a database-wins write over the file would discard, in words. */+export function unimportedFileText(file: UnimportedFile): string {+ if (file.reason === 'uncommitted_edit') return `an uncommitted edit of ${file.path}`;+ if (file.reason === 'unimported_delete') return file.commit ? `the delete of ${file.path} in commit ${file.commit.sha.slice(0, 12)} by ${file.commit.author} on ${file.commit.date}, which sync has not applied to the page`+ : `the delete of ${file.path} (Git could not name the deleting commit), which sync has not applied to the page`;+ if (file.reason === 'unknown') return `the current bytes of ${file.path}, which no import or gbrain write recorded`;+ const commit = file.commit ? `commit ${file.commit.sha.slice(0, 12)} by ${file.commit.author} on ${file.commit.date}` : 'the newest edit';+ return `${commit} to ${file.path}, which sync ${file.reason === 'no_import_record' ? 'never recorded importing' : 'has not imported'}`;+}++/**+ * The refusal of a reconcile that would write the database copy over an unimported file edit (sources reconcile,+ * writer_reconcile_preview and writer_reconcile_apply). Nothing was written.+ */+export function unimportedFileRefusal(sourceId: string, slug: string, file: UnimportedFile, paths: readonly string[]) {+ return opError('source_changed', `Reconciling ${slug} would overwrite ${unimportedFileText(file)}.`,+ `Nothing was written. The resolution takes the database copy over what the file says at ${paths.join(', ')}. Decide take_file for those paths to keep the file's edit; `+ + `if the user decides the edit should be discarded, preview gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database, which names the edit and needs their consent before it overwrites the file.`,+ { detail: 'unimported_file_edit', fix: readFix(`Previews the database-wins repair of ${slug}, read-only: it names the edit it would discard.`,+ { argv: ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--slug', slug, '--prefer', 'database'] }) });+}diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 51ddf597fa..b526f9a8af 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -91,6 +91,7 @@ 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 { discardedFilePaths, unimportedFile, unimportedFileText, type UnimportedFile } from '../persistence/unimported-file.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';@@ -105,7 +106,9 @@ export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftCl/** #6712 wave: the canonical file is gone from the last commit and the apply recreates it from the page. */file_gone?: true;/** GBRA-133: file wins appends protected keys or timeline rows to the canonical file (`fileWinsContent`). */- file_appended?: true }+ file_appended?: true;+ /** GST-2579: database wins writes over a file edit gbrain never imported or wrote; only an exact --slug selection keeps such a page, and its apply needs consent. */+ discards?: UnimportedFile }/** #6712 wave: a page whose canonical file is gone from the last commit, resolved `--prefer file`: soft-delete exactly that page. */export interface SoftDeletePage { slug: string; prefer: 'file'; exceptions: DriftException[]; soft_delete: { ghost: GhostPage; owner: GhostOwner } }/**@@ -507,6 +510,7 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slconst file = reconcileCanonical(state.file, state.file.tags);const decisions = preferSideDecisions(state.file, database, prefer);await assertReconcileRevision(engine, state.snapshot, sourceId, slug);+ const discards = prefer === 'database' && discardedFilePaths(state.file, database, decisions).length ? await unimportedFile(engine, state) : null;const prepared = await prepareReconcileResult(engine, state, decisions);if (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',`Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);@@ -523,7 +527,7 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slthrow error;}return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview,- ...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}) };+ ...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}), ...(discards ? { discards } : {}) };}/**@@ -548,11 +552,18 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,if (opts.prefer === 'file' && !await ghostFileBacked(engine, now.ghost, now.owner)) return { skip: DATABASE_AHEAD_CODE, detail: databaseAheadDetail(now.ghost) };if (opts.prefer === 'file') return { page: { slug, prefer: 'file', exceptions: [], soft_delete: { ghost: now.ghost, owner: now.owner } },detail: `soft-deletes the page: its file ${now.ghost.path} is gone from the last commit (purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore ${slug} --force undoes it until then)` };+ // GST-2579: recreating the file undoes the commit that deleted it; in bulk the deletion is kept, an exact --slug names the commit and needs consent.+ const deletedBy = target?.provenance ?? (await readDeletionProvenance(root, [now.ghost.path])).get(now.ghost.path) ?? { kind: 'unknown' as const };+ const undone: UnimportedFile | null = deletedBy.kind === 'never_committed' ? null : { path: now.ghost.path, reason: 'unimported_delete',+ commit: deletedBy.kind === 'deleted_by_commit' ? { sha: deletedBy.commit, author: deletedBy.author, date: deletedBy.date } : null };+ if (undone && !opts.slugs?.length) return { skip: 'kept_newer_delete', detail: `kept the deletion, nothing is written for it: recreating the file would undo ${unimportedFileText(undone)}. `+ + `Delete the page with --prefer file, or, if the user decides to bring the file back, preview the page alone: gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database` };const page = await prepareDriftPage(engine, sourceId, slug, 'database', assessmentAt, { fileGone: true });if (page.preview.preconditions.revision !== now.ghost.revision || page.preview.preconditions.relative_path.split(sep).join('/') !== now.ghost.path) {throw opError('source_changed', 'The page or its canonical path changed during the preview.', `Nothing was written. Preview ${slug} in '${sourceId}' again.`);}- return { page, detail: `recreates its missing file ${now.ghost.path} from the page` };+ if (undone) page.discards = undone;+ return { page, detail: `${undone ? `undoes ${unimportedFileText(undone)}; ` : ''}recreates its missing file ${now.ghost.path} from the page` };}/**@@ -726,6 +737,25 @@ function item(page: ApprovedPage, index: number, hash: string, last: boolean, prreturn { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };}+/**+ * GST-2579: the consent wording of a file-drift apply, naming every file edit sync never imported that the previewed+ * database-wins resolutions overwrite (the artifact's `discards`).+ */+export function fileDriftConsentText(hash: string, sourceId: string | undefined): { what: string; why: string; risk: string; user_message: string } {+ let discards: UnimportedFile[] = [];+ try { discards = [...readArtifact(hash, `gbrain repair file-drift --source ${sourceId ?? '<source>'}`).values()].flatMap(page => 'discards' in page && page.discards ? [page.discards] : []); }+ catch { /* the apply itself refuses a missing or changed artifact */ }+ const named = discards.slice(0, 10).map(unimportedFileText).join('; ') + (discards.length > 10 ? `; and ${discards.length - 10} more (listed in the preview)` : '');+ 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.',+ why: `The preview ${hash} listed each page and the side that wins it${discards.length ? `, and the file edits sync never imported that the database copy overwrites (${discards.length})` : ''}.`,+ risk: 'The losing side is replaced: a file rewrite is a new commit (git revert brings the edit back) and reconcile keeps a private backup of the replaced copy; a page that changed since the preview is skipped.',+ user_message: discards.length+ ? `Apply the previewed file-drift repair? It overwrites file edits sync never imported with the database copy: ${named}.`+ : 'Apply the previewed file-drift repair? Each listed page takes the side the preview showed, and the other copy is replaced.',+ };+}+export const fileDriftRepair: RepairHandler = {kind: 'file-drift',outcomeItemsLimit: 1000,@@ -840,9 +870,16 @@ export const fileDriftRepair: RepairHandler = {}const page = await prepareDriftPage(engine, sourceId, slug, opts.prefer, assessmentAt);if (classes.has(slug)) page.class = classes.get(slug);+ // GST-2579: in bulk a newer file is kept (its hold stays); only an exact --slug selection may discard it, named here and in the consent.+ if (page.discards && !opts.slugs?.length) {+ count('kept_newer_file');+ listing.push({ item: `${sourceId}:${slug}`, class: 'kept_newer_file', detail: `kept the file, nothing is written for it: it holds ${unimportedFileText(page.discards)}. `+ + `Import it with --prefer file, or, if the user decides to discard that edit, preview the page alone: gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database` });+ continue;+ }pages.push(page);listing.push({ item: `${sourceId}:${slug}`, class: `prefer_${opts.prefer}`,- detail: `${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}` });+ detail: `${page.discards ? `discards ${unimportedFileText(page.discards)}; ` : ''}${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}` });} catch (error) {if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;count(`refused_${error.code}`);@@ -869,6 +906,9 @@ export const fileDriftRepair: RepairHandler = {const removed = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);let warnings: string[] = nextCommand ? [`This preview covered ${previewed} of the ${held!.targets.length} selected held pages${opts.cursor ? ' after its cursor' : ''} (one window stops at ${HELD_WINDOW_PAGES} pages or ${HELD_WINDOW_BUDGET_MS / 1000} s); its hash and apply command cover only these. `+ `After applying this window (or deciding not to), preview the next one: ${nextCommand}`] : [];+ const discarded = pages.flatMap(page => 'preview' in page && page.discards ? [page.discards] : []);+ if (discarded.length) warnings.unshift(`This apply writes the database copy over ${discarded.length} file change(s) sync never imported, and needs the user's consent: ${discarded.map(unimportedFileText).join('; ')}. `+ + 'Each write is a new commit, so git revert brings the change back; reconcile also keeps the replaced bytes in its private backup.');const releases = pages.filter(page => 'release_hold' in page).length;if (releases) warnings.push(`The apply only schedules a re-screen of ${releases} held file(s) whose page and file agree; the next sync (gbrain sync --source ${sourceId}) releases each that still agrees.`);let undoneBySync: { recreated: number; removed: number } | null = null;@@ -907,7 +947,7 @@ export const fileDriftRepair: RepairHandler = {: '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 } : {}),verb: page.file_gone ? fileDriftActionVerb('deleted', 'file_gone', 'database') : fileDriftActionVerb('both', undefined, page.prefer),- adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest }),+ adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest, ...(page.discards ? { discards: page.discards } : {}) }),...(provenanceOf.get(page.slug) ? { provenance: provenanceOf.get(page.slug) } : {}) })),protections: 'Protected metadata stays as the database holds it, tags are the union of both sides, and protected takes and private fact rows are kept; exceptions lists each page\'s.' } };},@@ -926,7 +966,7 @@ export const fileDriftRepair: RepairHandler = {: { applied: false, outcome: 'changed_since_preview', reason: retired.outcome === 'file_restored' ? 'file_restored' : 'revision_conflict', detail: { request_id: requestId, message: retired.reason } };} else try {await asLocalCli(ctx.engine, () => runReconcileApply(ctx.engine, { source_id: page.source_id, slug: page.slug, preview: artifact.preview, request_id: requestId,- ...(artifact.prefer === 'file' ? { keep_file_bytes: true } : {}) }));+ ...(artifact.prefer === 'file' ? { keep_file_bytes: true } : {}) }, artifact.discards ? { discardFileHash: artifact.preview.preconditions.raw_file_hash } : {}));outcome = { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: artifact.prefer } };} catch (error) {if (acceptedPendingReceipt(error) || !(error instanceof OperationError) || ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'write_pending'].includes(error.code)) throw error;diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 96fd1e7d8d..78fce2ce41 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -454,7 +454,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'gets one revision_conflict). Preview-bound: --apply --expect <hash> sweeps exactly the previewed set; runs only when named.',},'file-drift': {- handler: fileDriftRepair, embeds: 'effect', checks: ['maintenance_write_drift'], explicit_only: true, preview_bound: true,+ handler: fileDriftRepair, embeds: 'effect', checks: ['maintenance_write_drift'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Apply the previewed file-drift resolutions: each listed page takes the preferred side, and the other copy is replaced.',+ why: 'The preview listed each page and the side that wins it.',+ risk: 'A file rewrite is a new commit (git revert brings the edit back) and reconcile keeps a private backup of the replaced copy; a page that changed since the preview is skipped.',+ user_message: 'Apply the previewed file-drift repair? Each listed page takes the side the preview showed, and the other copy is replaced.',+ },summary: 'Resolve pages whose canonical file differs from the database (source_changed / file_database_drift, #6643) through canonical reconciliation: '+ '--prefer file or --prefer database wins every ordinary field, within reconcile\'s protections (protected metadata stays as stored, tags are '+ 'the union, protected takes and private fact rows are kept; the preview lists each page\'s exceptions). Select with --slug <slug>, --request '@@ -466,7 +472,9 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'deleted only in the worktree is listed deletion_uncommitted and routed to committing the deletion or repair ghost-pages. --held [--side both|unknown|deleted '+ '[--state tombstone_edited|purged_differs|file_gone]] selects the source\'s held file_drift pages of one Decision (several sides or states are refused; '+ '--side deleted needs --state): a deleted page whose file changed is restored and imported (--prefer file) or keeps its deletion while the file is '- + 'removed by a coordinated commit (--prefer database); a purged page\'s file is imported as a new page or removed. Trusted local CLI only; runs only when named.',+ + 'removed by a coordinated commit (--prefer database); a purged page\'s file is imported as a new page or removed. --prefer database never overwrites a file '+ + 'edit sync never imported in bulk: such a page is listed kept_newer_file and skipped, and an exact --slug selection names the commit it discards (GST-2579). '+ + 'The apply needs the user\'s consent (--yes), which names those edits. Trusted local CLI only; runs only when named.',},'stuck-recovery': {handler: stuckRecoveryRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',diff --git a/test/db-wins-unimported-gst2579.test.ts b/test/db-wins-unimported-gst2579.test.tsnew file mode 100644index 0000000000..a1c4cbc75b--- /dev/null+++ b/test/db-wins-unimported-gst2579.test.ts@@ -0,0 +1,324 @@+/**+ * GST-2579: a database-wins drift repair silently discarded a newer file commit sync had not imported. Another writer+ * commits an edit to a page's file; before the next sync imports it, `repair file-drift --prefer database` (by --held,+ * --all-drifted or --slug) or a `sources reconcile` apply that takes the database copy wrote the page over the file, and+ * nothing said a commit was being thrown away.+ * - bulk selections (--held, --all-drifted) list such a page kept_newer_file and write nothing for it;+ * - an exact --slug selection names the commit (sha, author, date) in the preview and in the consent, and its apply+ * needs the user's consent (--yes);+ * - `sources reconcile`'s preview and apply refuse a resolution that takes the database copy over such a file;+ * - gbrain's own writer commit counts the same as anyone's: a file holding gbrain's write of a revision the database+ * never took (the Git commit landed, the row fell back) is kept_newer_file in bulk and named with --slug;+ * - a database copy that is provably newer still wins: the file holds the bytes sync imported, or gbrain's write of a+ * revision the page has since moved past (a later, shorter database edit included, --all-drifted --only), and the+ * repair is listed and applied as before.+ * Real PGLite (and Postgres when DATABASE_URL is set), a managed worktree with real Git commits; no seams.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { prepareDriftPage } from '../src/core/repair/file-drift.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { testBackends } from './helpers/test-backends.ts';++const SYNC = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const logger = { info() {}, warn() {}, error() {} };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Other Writer', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const FIRST = '---\ntype: concept\ntitle: A\n---\n\nThe first body.\n';+const EDIT = '---\ntype: concept\ntitle: A\n---\n\nAn edit by another writer.\n';+const WRITER_LINE = 'A line only gbrain\'s own writer committed.';+const WRITER = `---\ntype: concept\ntitle: A\n---\n\nThe first body.\n\n${WRITER_LINE}\n`;+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, 'notes/a.md'), FIRST); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'first');+};+const backendOpts = (backend: string) => ({ ...(backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {}), setup });++interface Brain { engine: BrainEngine; ctx: OperationContext; root: string; commit: string }+/** A synced managed brain whose notes/a.md then gets another writer's commit that no sync imported. */+const brain = (backend: string, run: (b: Brain) => Promise<void>) => managedBrain(async ({ engine, ctx, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/a.md'), EDIT);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'other writer edit');+ await run({ engine, ctx, root, commit: git(root, 'rev-parse', 'HEAD') });+}, backendOpts(backend));++const cli = async <T>(engine: BrainEngine, run: () => Promise<T>) => withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), run);+const runner = async (engine: BrainEngine, opts: Record<string, unknown>) => cli(engine, async () =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', ...opts }));+const fileHasEdit = (root: string) => readFileSync(join(root, 'notes/a.md'), 'utf8').includes('another writer');+const settle = () => Bun.sleep(1500);+/** A file_drift hold on notes/a.md, as sync writes it for a page whose page and file both moved. */+async function holdBoth(engine: BrainEngine): Promise<void> {+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const page = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: source!.incarnation, path: 'notes/a.md', source_path: 'notes/a.md', slug: 'notes/a',+ page_id: Number(page.page.id), code: 'file_drift', message: 'notes/a.md is held: file drift (both)', upstream_version: null, observed_at: new Date().toISOString(),+ run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION, side: 'both', page_revision: page.revision } }));+}++/** A file_drift hold for a live page whose file is gone (the file_gone Decision), as sync writes it. */+async function holdDeleted(engine: BrainEngine, slug: string, path: string): Promise<void> {+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: source!.incarnation, path, source_path: path, slug,+ page_id: Number(page.page.id), code: 'file_drift', message: `${path} is held: file drift (deleted file_gone)`, upstream_version: null, observed_at: new Date().toISOString(),+ run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'file_gone', page_revision: page.revision } }));+}++/** The CLI's JSON output and exit code for one file-drift invocation. */+async function repairCli(engine: BrainEngine, args: string[]): Promise<{ out: string; exitCode: number | string | undefined }> {+ const lines: string[] = [];+ const { log, error } = console;+ const stdout = process.stdout.write.bind(process.stdout);+ const previous = process.exitCode;+ process.exitCode = 0;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ console.error = () => {};+ process.stdout.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stdout.write;+ try { await runRepairCommand(engine, ['file-drift', ...args, '--json']); return { out: lines.join('\n'), exitCode: process.exitCode }; }+ finally { console.log = log; console.error = error; process.stdout.write = stdout; process.exitCode = previous ?? 0; _resetCliExitVerdictForTests(); }+}++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++for (const backend of testBackends()) {+ test(`${backend}: --held --prefer database keeps a newer unimported file (kept_newer_file) and writes nothing`, () => brain(backend, async ({ engine, root }) => {+ await holdBoth(engine);+ const preview = await runner(engine, { held: true, side: 'both', prefer: 'database' });+ expect(preview.affected).toBe(0);+ expect(preview.residuals).toMatchObject({ kept_newer_file: 1 });+ const listed = preview.listing!.find(entry => entry.item === 'default:notes/a')!;+ expect(listed.class).toBe('kept_newer_file');+ expect(listed.detail).toContain('has not imported');+ expect(listed.detail).toContain('--slug notes/a --prefer database');+ await runner(engine, { held: true, side: 'both', prefer: 'database', expect: preview.preview_hash });+ await settle();+ expect(fileHasEdit(root)).toBe(true);+ }), 240_000);++ test(`${backend}: --all-drifted --prefer database keeps a newer unimported file a refused write recorded`, () => brain(backend, async ({ engine, ctx, root }) => {+ const revision = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!.revision;+ expect((await refusal(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: '---\ntype: concept\ntitle: A\n---\n\nA database edit.\n',+ request_id: randomUUID(), expected_revision: revision } }))).code).toBe('source_changed');+ const preview = await runner(engine, { allDrifted: true, prefer: 'database' });+ expect(preview.affected).toBe(0);+ expect(preview.listing!.find(entry => entry.item === 'default:notes/a')?.class).toBe('kept_newer_file');+ await runner(engine, { allDrifted: true, prefer: 'database', expect: preview.preview_hash });+ await settle();+ expect(fileHasEdit(root)).toBe(true);+ }), 240_000);++ test(`${backend}: --slug --prefer database names the commit it discards and applies only with the user's consent`, () => brain(backend, async ({ engine, root, commit }) => {+ const preview = JSON.parse((await repairCli(engine, ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database'])).out).results[0];+ expect(preview.affected).toBe(1);+ const listed = preview.listing.find((entry: { item: string }) => entry.item === 'default:notes/a');+ expect(listed.detail).toContain(`discards commit ${commit.slice(0, 12)} by Other Writer`);+ expect(preview.details.pages[0].discards).toMatchObject({ reason: 'unimported_commit', path: 'notes/a.md', commit: { sha: commit, author: 'Other Writer' } });+ expect(preview.warnings.join(' ')).toContain(commit.slice(0, 12));+ expect(preview.apply_command).toEndWith(' --yes');+ const apply = ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database', '--apply', '--expect', preview.preview_hash];+ const unconsented = await repairCli(engine, apply);+ expect(unconsented.exitCode).toBe(3);+ expect(unconsented.out).toContain(commit.slice(0, 12));+ await settle();+ expect(fileHasEdit(root)).toBe(true);+ const consented = JSON.parse((await repairCli(engine, [...apply, '--yes'])).out).results[0];+ expect(consented.outcomes).toEqual({ repaired: 1 });+ await settle();+ expect(fileHasEdit(root)).toBe(false);+ // The overwritten bytes stay in reconcile's private backup (mode 0600), which nothing prunes on its own.+ const backups = join(process.env.GBRAIN_HOME!, '.gbrain', 'reconciliation-previews');+ const [backup] = readdirSync(backups).filter(name => name.endsWith('.json'));+ expect(statSync(join(backups, backup!)).mode & 0o777).toBe(0o600);+ const kept = JSON.parse(readFileSync(join(backups, backup!), 'utf8'));+ expect(kept).toMatchObject({ format_version: 1, retention: 'pre_admission_or_terminal' });+ expect(Buffer.from(kept.preview.preimages.file_base64, 'base64').toString('utf8')).toBe(EDIT);+ expect(kept.preview.decisions).toContainEqual({ path: '/compiled_truth', action: 'take_database' });+ }), 240_000);++ test(`${backend}: sources reconcile refuses to take the database copy over the unimported commit, in its preview and its apply`, () => brain(backend, async ({ engine, root, commit }) => {+ await cli(engine, async () => {+ const fresh = await runReconcilePreview(engine, { source_id: 'default', slug: 'notes/a' });+ const decided = await refusal(() => runReconcilePreview(engine, { source_id: 'default', slug: 'notes/a', from: fresh.preview,+ decisions: [{ path: '/compiled_truth', action: 'take_database' }] }));+ expect(decided.code).toBe('source_changed');+ expect(decided.message).toContain(`commit ${commit.slice(0, 12)} by Other Writer`);+ const kept = await runReconcilePreview(engine, { source_id: 'default', slug: 'notes/a', from: fresh.preview, decisions: [{ path: '/compiled_truth', action: 'take_file' }] });+ expect(kept.status).toBe('ready');+ const ready = await prepareDriftPage(engine, 'default', 'notes/a', 'database', new Date().toISOString());+ const applied = await refusal(() => runReconcileApply(engine, { source_id: 'default', slug: 'notes/a', preview: ready.preview, request_id: randomUUID() }));+ expect(applied.code).toBe('source_changed');+ expect(applied.message).toContain(commit.slice(0, 12));+ });+ await settle();+ expect(fileHasEdit(root)).toBe(true);+ }), 240_000);++ test(`${backend}: an ordinary database-wins repair (the file still holds the imported bytes) is listed and applied in bulk as before`, () => managedBrain(async ({ engine, ctx, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ // The page takes a database edit (written through to the file), then the file goes back to the bytes sync imported: nothing in it is new.+ const revision = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!.revision;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: '---\ntype: concept\ntitle: A\n---\n\nA database-only edit.\n',+ request_id: randomUUID(), expected_revision: revision } });+ await settleManagedGitEffects(engine);+ writeFileSync(join(root, 'notes/a.md'), FIRST);+ git(root, 'add', '-A'); git(root, 'commit', '-q', '--allow-empty', '-m', 'back to the imported bytes');+ await holdBoth(engine);+ const preview = await runner(engine, { held: true, side: 'both', prefer: 'database' });+ expect(preview.affected).toBe(1);+ expect(preview.residuals.kept_newer_file).toBeUndefined();+ expect(preview.listing!.find(entry => entry.item === 'default:notes/a')).toMatchObject({ class: 'prefer_database', detail: 'exactly the preferred side' });+ expect((await runner(engine, { held: true, side: 'both', prefer: 'database', expect: preview.preview_hash })).outcomes).toEqual({ repaired: 1 });+ await settle();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('A database-only edit.');+ }, backendOpts(backend)), 240_000);+ test(`${backend}: a file whose newest commit is gbrain's own write, over a database copy that fell behind it, is kept_newer_file in bulk and named with --slug`, () => managedBrain(async ({ engine, ctx, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ const older = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ // gbrain's own writer commits a longer page (Git durability on); then the database row falls back to the older copy,+ // as when the Git commit lands and the row does not.+ await engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: WRITER, request_id: randomUUID(), expected_revision: older.revision } });+ await settleManagedGitEffects(engine);+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(WRITER_LINE);+ expect(git(root, 'log', '-1', '--format=%an', '--', 'notes/a.md')).not.toBe('Other Writer');+ expect(git(root, 'status', '--porcelain')).toBe('');+ const commit = git(root, 'log', '-1', '--format=%H', '--', 'notes/a.md');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ "UPDATE pages SET compiled_truth=$1, knowledge_revision=$2::uuid WHERE source_id='default' AND slug='notes/a'", [older.page.compiled_truth, randomUUID()]), TEST_WRITE_ATTRIBUTION));+ const behind = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ expect(behind.page.compiled_truth).not.toContain(WRITER_LINE);+ // A refused write records the drift conflict --all-drifted selects.+ expect((await refusal(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: '---\ntype: concept\ntitle: A\n---\n\nA database edit.\n',+ request_id: randomUUID(), expected_revision: behind.revision } }))).code).toBe('source_changed');++ const bulk = await runner(engine, { allDrifted: true, only: ['notes/**'], prefer: 'database' });+ expect(bulk.affected).toBe(0);+ expect(bulk.listing!.find(entry => entry.item === 'default:notes/a')).toMatchObject({ class: 'kept_newer_file', detail: expect.stringContaining(commit.slice(0, 12)) });+ await runner(engine, { allDrifted: true, only: ['notes/**'], prefer: 'database', expect: bulk.preview_hash });+ await settle();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(WRITER_LINE);++ const named = JSON.parse((await repairCli(engine, ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database'])).out).results[0];+ expect(named.listing.find((entry: { item: string }) => entry.item === 'default:notes/a').detail).toStartWith(`discards commit ${commit.slice(0, 12)}`);+ const unconsented = await repairCli(engine, ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database', '--apply', '--expect', named.preview_hash]);+ expect(unconsented.exitCode).toBe(3);+ await settle();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(WRITER_LINE);+ }, backendOpts(backend)), 240_000);+ test(`${backend}: a file holding gbrain's own committed write of a revision the database has since moved past repairs in bulk as before`, () => managedBrain(async ({ engine, ctx, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ await engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");+ const first = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: WRITER, request_id: randomUUID(), expected_revision: first.revision } });+ await settleManagedGitEffects(engine);+ const written = readFileSync(join(root, 'notes/a.md'));+ const second = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: '---\ntype: concept\ntitle: A\n---\n\nA later database edit.\n',+ request_id: randomUUID(), expected_revision: second.revision } });+ await settleManagedGitEffects(engine);+ // The file goes back to gbrain's earlier write, a revision the page's version history keeps: the database copy is newer.+ writeFileSync(join(root, 'notes/a.md'), written);+ git(root, 'commit', '-qam', "back to gbrain's earlier write");+ await holdBoth(engine);+ const preview = await runner(engine, { held: true, side: 'both', prefer: 'database' });+ expect(preview.affected).toBe(1);+ expect(preview.residuals.kept_newer_file).toBeUndefined();+ expect((await runner(engine, { held: true, side: 'both', prefer: 'database', expect: preview.preview_hash })).outcomes).toEqual({ repaired: 1 });+ await settle();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('A later database edit.');+ }, backendOpts(backend)), 240_000);+ test(`${backend}: a database edit made after gbrain's own last commit of the file, shorter than the file, still wins an --all-drifted --only repair`, () => managedBrain(async ({ engine, ctx, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ await engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");+ const first = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: WRITER, request_id: randomUUID(), expected_revision: first.revision } });+ await settleManagedGitEffects(engine);+ const commit = git(root, 'log', '-1', '--format=%H', '--', 'notes/a.md');+ expect(git(root, 'status', '--porcelain')).toBe('');+ // The database then takes a shorter edit that never reaches the file (write-through off): the database copy is newer.+ await engine.setConfig('sync.write_through', 'false');+ const written = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: FIRST, request_id: randomUUID(), expected_revision: written.revision } });+ await engine.setConfig('sync.write_through', 'true');+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(WRITER_LINE);+ expect(git(root, 'log', '-1', '--format=%H', '--', 'notes/a.md')).toBe(commit);+ const newer = (await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!;+ expect(newer.page.compiled_truth).not.toContain(WRITER_LINE);+ expect((await refusal(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', content: '---\ntype: concept\ntitle: A\n---\n\nA refused edit.\n',+ request_id: randomUUID(), expected_revision: newer.revision } }))).code).toBe('source_changed');++ const preview = await runner(engine, { allDrifted: true, only: ['notes/**'], prefer: 'database' });+ expect(preview.affected).toBe(1);+ expect(preview.residuals.kept_newer_file).toBeUndefined();+ expect(preview.listing!.find(entry => entry.item === 'default:notes/a')!.class).toBe('prefer_database');+ expect((await runner(engine, { allDrifted: true, only: ['notes/**'], prefer: 'database', expect: preview.preview_hash })).outcomes).toEqual({ repaired: 1 });+ await settleManagedGitEffects(engine);+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).not.toContain(WRITER_LINE);+ }, backendOpts(backend)), 240_000);+ test(`${backend}: --held --side deleted --state file_gone --prefer database keeps another writer's unimported delete (kept_newer_delete)`, () => brain(backend, async ({ engine, root }) => {+ git(root, 'rm', '-q', '--', 'notes/a.md'); git(root, 'commit', '-qm', 'other writer delete');+ const deleteCommit = git(root, 'rev-parse', 'HEAD');+ await holdDeleted(engine, 'notes/a', 'notes/a.md');+ const preview = await runner(engine, { held: true, side: 'deleted', state: 'file_gone', prefer: 'database' });+ expect(preview.affected).toBe(0);+ expect(preview.residuals).toMatchObject({ kept_newer_delete: 1 });+ const listed = preview.listing!.find(entry => entry.item === 'default:notes/a')!;+ expect(listed.class).toBe('kept_newer_delete');+ expect(listed.detail).toContain(`commit ${deleteCommit.slice(0, 12)} by Other Writer`);+ await runner(engine, { held: true, side: 'deleted', state: 'file_gone', prefer: 'database', expect: preview.preview_hash });+ await settle();+ expect(existsSync(join(root, 'notes/a.md'))).toBe(false);+ const named = JSON.parse((await repairCli(engine, ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database'])).out).results[0];+ expect(named.details.pages[0]).toMatchObject({ action: 'recreate_file', discards: { reason: 'unimported_delete', commit: { sha: deleteCommit } } });+ const unconsented = await repairCli(engine, ['--source', 'default', '--slug', 'notes/a', '--prefer', 'database', '--apply', '--expect', named.preview_hash]);+ expect(unconsented.exitCode).toBe(3);+ expect(unconsented.out).toContain(deleteCommit.slice(0, 12));+ await settle();+ expect(existsSync(join(root, 'notes/a.md'))).toBe(false);+ }), 240_000);++ test(`${backend}: --held --state file_gone --provenance never_committed --prefer database keeps the page database-only and writes no file`, () => brain(backend, async ({ engine, ctx, root }) => {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/b', content: '---\ntype: concept\ntitle: B\n---\n\nOnly ever in the working tree.\n', request_id: randomUUID() } });+ await settleManagedGitEffects(engine);+ expect(git(root, 'log', '--oneline', '--', 'notes/b.md')).toBe('');+ const imported = await engine.readPageSnapshot('notes/b', { sourceId: 'default' });+ expect(imported?.page.compiled_truth).toContain('Only ever in the working tree.');+ rmSync(join(root, 'notes/b.md'));+ await holdDeleted(engine, 'notes/b', 'notes/b.md');+ const preview = await runner(engine, { held: true, side: 'deleted', state: 'file_gone', provenance: 'never_committed', prefer: 'database' });+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/b', action: 'detach_page' })]);+ expect((await runner(engine, { held: true, side: 'deleted', state: 'file_gone', provenance: 'never_committed', prefer: 'database', expect: preview.preview_hash })).outcomes).toEqual({ repaired: 1 });+ await settle();+ expect(existsSync(join(root, 'notes/b.md'))).toBe(false);+ expect((await engine.readPageSnapshot('notes/b', { sourceId: 'default' }))?.page.compiled_truth).toContain('Only ever in the working tree.');+ expect(fileHasEdit(root)).toBe(true);+ }), 240_000);+}diff --git a/test/file-drift-bulk-reconcile.test.ts b/test/file-drift-bulk-reconcile.test.tsindex 46081dc91b..b65ae2f5bd 100644--- a/test/file-drift-bulk-reconcile.test.ts+++ b/test/file-drift-bulk-reconcile.test.ts@@ -151,10 +151,6 @@ for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${const put = (ctx: OperationContext, slug: string, content: string) =>submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });- const drift = (root: string, slug: string, edit: (text: string) => string) => {- const file = join(root, `${slug}.md`);- writeFileSync(file, edit(readFileSync(file, 'utf8')));- };/** A caller write refused source_changed: one conflict receipt for the slug. */const refusedWrite = async (ctx: OperationContext, slug: string) => {const expected_revision = (await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId! }))!.revision;@@ -168,12 +164,25 @@ for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${for (const slug of slugs) if ((await liveFileDrift(engine, sourceId, slug)).still_present === true) drifted.push(slug);return drifted;};- /** Three concepts drifted by an appended line, one person rewritten (another drift class); each with a conflict receipt. */+ /**+ * Three concepts drifted by an appended line, one person rewritten (another drift class); each with a conflict receipt.+ * Each file goes back to bytes gbrain wrote for it earlier, so the database copy is the newer side and a database-wins+ * repair discards nothing (a file edit sync never imported is kept_newer_file instead, GST-2579).+ */async function driftedPages(root: string, ctx: OperationContext): Promise<void> {- for (const slug of CONCEPTS) await put(ctx, slug, `---\ntype: concept\ntitle: ${slug.slice(9)}\n---\nStored ${slug}.\n`);- await put(ctx, PERSON, '---\ntype: person\ntitle: Alice Example\n---\nOriginal sentence.\n');- for (const slug of CONCEPTS) drift(root, slug, text => `${text}\nA line added in the file only.\n`);- drift(root, PERSON, text => text.replace('Original sentence.', 'A different sentence.'));+ const earlier = new Map<string, string>();+ const stage = async (slug: string, older: string, newer: string) => {+ await put(ctx, slug, older);+ earlier.set(slug, readFileSync(join(root, `${slug}.md`), 'utf8'));+ const expected_revision = (await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId! }))!.revision;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: newer, expected_revision, request_id: randomUUID() } });+ };+ for (const slug of CONCEPTS) {+ const head = `---\ntype: concept\ntitle: ${slug.slice(9)}\n---\nStored ${slug}.\n`;+ await stage(slug, `${head}\nA line added in the file only.\n`, head);+ }+ await stage(PERSON, '---\ntype: person\ntitle: Alice Example\n---\nA different sentence.\n', '---\ntype: person\ntitle: Alice Example\n---\nOriginal sentence.\n');+ for (const [slug, bytes] of earlier) writeFileSync(join(root, `${slug}.md`), bytes);for (const slug of [...CONCEPTS, PERSON]) await refusedWrite(ctx, slug);expect(await stillDrifted(ctx.sourceId!, [...CONCEPTS, PERSON])).toEqual([...CONCEPTS, PERSON]);}@@ -313,7 +322,9 @@ for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${expect(await pass.freeze(PERSON)).toEqual({ refused: 'outside_keep_db' });expect(await requests(sourceId)).toBe(before);- const ids = (await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key LIKE 'principal:%' ORDER BY lifetime_ids DESC LIMIT 1"))[0]!;+ // The principal that wrote this source's pages (earlier tests' principals share the engine and may hold more ids).+ const ids = (await engine.executeRaw<{ lifetime_ids: string }>(`SELECT lifetime_ids::text FROM persistence_counters WHERE key IN+ (SELECT DISTINCT 'principal:' || principal_kind || ':' || principal_id FROM persistence_requests WHERE source_id=$1) ORDER BY lifetime_ids DESC LIMIT 1`, [sourceId]))[0]!;await engine.setConfig('persistence.limits.principal_lifetime_ids', ids.lifetime_ids);expect(await pass.admit(CONCEPTS[0]!)).toEqual({ refused: 'capacity' });expect(await requests(sourceId)).toBe(before);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 23f6769146..e9f2353fb7 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -80,6 +80,7 @@ test/cycle/dream-reverse-write-commit.test.tstest/cycle/synthesize-concepts-merge.test.tstest/db-lock-reconnect.test.tstest/db-only-labels-gst2519.test.ts+test/db-wins-unimported-gst2579.test.tstest/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.tsdiff --git a/test/reconcile-unbound-collision.test.ts b/test/reconcile-unbound-collision.test.tsindex 88530bd2aa..71bc2b2c75 100644--- a/test/reconcile-unbound-collision.test.ts+++ b/test/reconcile-unbound-collision.test.ts@@ -80,15 +80,22 @@ test('preview accepts a database-only page colliding with a canonical file, chanexpect(readFileSync(f.file, 'utf8')).toBe(fileSide);expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!.revision).toBe(before.revision);+ // GST-2579: sync never imported the file, so taking the database copy over its body is refused and writes nothing.+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_database' })) }))+ .rejects.toMatchObject({ code: 'source_changed', detail: 'unimported_file_edit' });+ expect(readFileSync(f.file, 'utf8')).toBe(fileSide);+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!.revision).toBe(before.revision);const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,- decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_database' })) });+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_file' })) });expect(resolved.status).toBe('ready');const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });expect(receipt.state).toBe('committed');const current = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;- expect(current.page.compiled_truth).toContain('no canonical owner');+ expect(current.page.compiled_truth).toContain('on another host');expect(current.page.frontmatter).toMatchObject({ db_only_field: 'kept', file_field: 'kept' });- expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).compiled_truth).toContain('no canonical owner');+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).compiled_truth).toContain('on another host');+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).frontmatter).toMatchObject({ db_only_field: 'kept' });const [page] = await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null }>('SELECT source_path,database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);// The page now has a canonical origin, so the unbound_source doctor count no longer reports it.@@ -233,12 +240,12 @@ test('a marked page adopts a file whose name differs from its slug only by case,const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });expect(preview.relative_path).toBe('notes/Example.md');const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,- decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_database' })) });+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_file' })) });const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });expect(receipt.state).toBe('committed');const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);expect(page!.source_path).toBe('notes/Example.md');- expect(readFileSync(cased, 'utf8')).toContain('no canonical owner');+ expect(readFileSync(cased, 'utf8')).toContain('db_only_field: kept');});}});diff --git a/test/repair-file-drift-deleted-6712.test.ts b/test/repair-file-drift-deleted-6712.test.tsindex 5eb76151f9..9480901f4b 100644--- a/test/repair-file-drift-deleted-6712.test.ts+++ b/test/repair-file-drift-deleted-6712.test.ts@@ -111,7 +111,7 @@ for (const backend of testBackends()) describe(`#6712 wave: deleted-file repairconst preview = await run(sourceId, { slugs: ['notes/keep'], prefer: 'database' });expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/keep', action: 'recreate_file' })]);- expect(preview.warnings).toEqual([expect.stringContaining('Git durability is off')]);+ expect(preview.warnings).toEqual([expect.stringContaining('Git durability is off'), expect.stringContaining('the delete of notes/keep.md in commit ')]);expect(existsSync(file)).toBe(false);const applied = await run(sourceId, { slugs: ['notes/keep'], prefer: 'database', expect: preview.preview_hash! });diff --git a/test/repair-file-drift-deleted-side-d5.test.ts b/test/repair-file-drift-deleted-side-d5.test.tsindex 5432f27c16..bf400344a1 100644--- a/test/repair-file-drift-deleted-side-d5.test.ts+++ b/test/repair-file-drift-deleted-side-d5.test.ts@@ -67,9 +67,9 @@ for (const backend of testBackends()) describe(`[${backend}] PR A item 5: repairfor (const name of NAMES) writeFileSync(join(root, `notes/${name}-example.md`), note(`notes/${name}-example`, `The committed body of notes/${name}-example.`));commit(root, 'notes');};- const run = async (engine: BrainEngine, opts: { state: string; prefer: 'file' | 'database'; provenance?: string; only?: string[]; expect?: string }) =>+ const run = async (engine: BrainEngine, opts: { state?: string; slugs?: string[]; prefer: 'file' | 'database'; provenance?: string; only?: string[]; expect?: string }) =>(await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),- { explicit: true, sourceFlag: 'default', held: true, side: 'deleted', state: opts.state, prefer: opts.prefer,+ { explicit: true, sourceFlag: 'default', ...(opts.slugs ? { slugs: opts.slugs } : { held: true, side: 'deleted', state: opts.state }), prefer: opts.prefer,...(opts.provenance ? { provenance: opts.provenance } : {}), ...(opts.only ? { only: opts.only } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });type Page = { slug: string; action?: string; verb?: string; state?: string; path?: string; provenance?: { kind: string; subject?: string } };const pages = (result: Awaited<ReturnType<typeof run>>) => (result.details?.pages ?? []) as Page[];@@ -86,18 +86,25 @@ for (const backend of testBackends()) describe(`[${backend}] PR A item 5: repairconst before = await state(engine, root);const page = (await engine.readPageSnapshot('notes/alpha-example', { sourceId: 'default' }))!;- const preview = await run(engine, { state: 'file_gone', prefer: 'database', provenance: 'deleted_by_commit' });+ // GST-2579: the delete is newer than what sync imported, so the bulk database-wins run keeps it and writes nothing;+ // naming the page previews the recreate, and its detail and warning name the delete it undoes.+ const bulk = await run(engine, { state: 'file_gone', prefer: 'database', provenance: 'deleted_by_commit' });+ expect(bulk).toMatchObject({ mode: 'dry_run', affected: 0, residuals: { kept_newer_delete: 1 } });+ expect(listed(bulk)).toEqual([['default:notes/alpha-example', 'kept_newer_delete']]);+ expect(bulk.listing![0]!.detail).toContain(`commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);+ expect(await state(engine, root)).toEqual(before);+ const preview = await run(engine, { slugs: ['notes/alpha-example'], prefer: 'database' });expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });expect(pages(preview)).toEqual([expect.objectContaining({ slug: 'notes/alpha-example', action: 'recreate_file', verb: 'recreate the file',- provenance: expect.objectContaining({ kind: 'deleted_by_commit', subject: 'cull alpha' }) })]);+ discards: { path, reason: 'unimported_delete', commit: expect.objectContaining({ sha: git(root, 'rev-parse', 'HEAD'), author: 'Example' }) } })]);expect(listed(preview)).toEqual([['default:notes/alpha-example', 'prefer_database']]);expect(preview.listing![0]!.detail).toContain(`recreates its missing file ${path} from the page`);- expect(preview.listing![0]!.detail).toContain(`deleted by commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);- expect(preview.apply_command).toContain('--provenance deleted_by_commit --prefer database --apply --expect');+ expect(preview.listing![0]!.detail).toContain(`undoes the delete of ${path} in commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);+ expect(preview.apply_command).toContain('--slug notes/alpha-example --prefer database --apply --expect');expect(await state(engine, root)).toEqual(before);expect(existsSync(join(root, path))).toBe(false);- const applied = await run(engine, { state: 'file_gone', prefer: 'database', provenance: 'deleted_by_commit', expect: preview.preview_hash! });+ const applied = await run(engine, { slugs: ['notes/alpha-example'], prefer: 'database', expect: preview.preview_hash! });expect(applied.outcomes).toEqual({ repaired: 1 });const parsed = parseMarkdown(readFileSync(join(root, path), 'utf8'), path);const after = (await engine.readPageSnapshot('notes/alpha-example', { sourceId: 'default' }))!;@@ -109,7 +116,7 @@ for (const backend of testBackends()) describe(`[${backend}] PR A item 5: repairexpect(parsed.type).toBe(page.page.type);// The apply recreates the file uncommitted (Git durability is off here, as the preview warns) and leaves the hold to the// sync that re-screens it: an uncommitted file keeps the hold and the page; committing it and syncing clears the hold.- expect(preview.warnings).toEqual([expect.stringContaining('unless the recreated files are committed')]);+ expect(preview.warnings).toEqual([expect.stringContaining('unless the recreated files are committed'), expect.stringContaining(`the delete of ${path} in commit `)]);expect(preview.details!.undone_by_next_sync_unless_committed).toEqual({ recreated: 1, removed: 0 });expect(git(root, 'status', '--porcelain')).toBe(`?? ${path}`);expect((await holds(engine))[path]).toMatchObject({ code: 'file_drift', meta: { state: 'file_gone' } });diff --git a/test/repair-file-drift-held-6712.test.ts b/test/repair-file-drift-held-6712.test.tsindex da8dad57a2..e449ddaf55 100644--- a/test/repair-file-drift-held-6712.test.ts+++ b/test/repair-file-drift-held-6712.test.ts@@ -98,6 +98,9 @@ for (const backend of testBackends()) describe(`#6712 PR 4b: repair file-drift -(await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, sourceId),{ explicit: true, sourceFlag: sourceId, held: true, prefer: opts.prefer, ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),...(opts.only ? { only: opts.only } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });+ const runDatabaseSlug = async (sourceId: string, slug: string, expectHash?: string) =>+ (await repairRunner(engine, { apply: expectHash !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, sourceId),+ { explicit: true, sourceFlag: sourceId, slugs: [slug], prefer: 'database', ...(expectHash ? { expect: expectHash } : {}) });const runSlug = async (sourceId: string, slug: string, expectHash?: string) =>(await repairRunner(engine, { apply: expectHash !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, sourceId),{ explicit: true, sourceFlag: sourceId, slugs: [slug], prefer: 'file', ...(expectHash ? { expect: expectHash } : {}) });@@ -283,11 +286,14 @@ for (const backend of testBackends()) describe(`#6712 PR 4b: repair file-drift -test('file_gone: --prefer database recreates the file, --prefer file soft-deletes the page', () => fixture(async f => {const { path } = await fileGone(f, 'notes/gone');- const recreate = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'database' });+ // GST-2579: the delete commit is newer than what sync imported, so the held database-wins run keeps it; naming the page recreates.+ const kept = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'database' });+ expect(kept).toMatchObject({ affected: 0, residuals: { kept_newer_delete: 1 } });+ const recreate = await runDatabaseSlug(f.sourceId, 'notes/gone');expect(recreate.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/gone', action: 'recreate_file', verb: 'recreate the file' })]);const soft = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'file' });expect(soft.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/gone', action: 'soft_delete', verb: 'soft-delete the page' })]);- const applied = await run(f.sourceId, { side: 'deleted', state: 'file_gone', prefer: 'database', expect: recreate.preview_hash! });+ const applied = await runDatabaseSlug(f.sourceId, 'notes/gone', recreate.preview_hash!);expect(applied.outcomes).toEqual({ repaired: 1 });expect(readFileSync(join(f.root, path), 'utf8')).toContain('The page.');diff --git a/test/repair-file-drift-held-window-gbra133.test.ts b/test/repair-file-drift-held-window-gbra133.test.tsindex 53fa77cced..0751566d51 100644--- a/test/repair-file-drift-held-window-gbra133.test.ts+++ b/test/repair-file-drift-held-window-gbra133.test.ts@@ -99,12 +99,20 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prev...(opts.cursor ? { cursor: opts.cursor } : {}), ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.expect ? { expect: opts.expect } : {}),...(opts.progress ? { progress: opts.progress } : {}) });const refusal = async (promise: Promise<unknown>) => { try { await promise; } catch (error) { return error as OperationError; } throw new Error('expected a refusal'); };- /** `count` live pages whose committed files are then removed in one commit, each held as the file_gone Decision. */- async function fileGone(f: Fixture, count: number): Promise<string[]> {+ /**+ * `count` live pages whose committed files are then removed in one commit, each held as the file_gone Decision. With+ * `committed: false` no commit ever held the files (never_committed), so recreating one undoes no commit; a committed+ * delete newer than what sync imported is kept_newer_delete in a held window instead (GST-2579).+ */+ async function fileGone(f: Fixture, count: number, opts: { committed?: boolean } = {}): Promise<string[]> {const slugs = Array.from({ length: count }, (_, i) => `notes/gone-${String(i).padStart(4, '0')}`);+ const committed = opts.committed !== false;+ if (!committed) git(f.root, 'commit', '-q', '--allow-empty', '-m', 'base');for (const slug of slugs) await put(f.ctx, slug, `The page ${slug}.`);- commitAll(f.root, 'pages');- git(f.root, 'rm', '-q', '--', ...slugs.map(slug => `${slug}.md`)); git(f.root, 'commit', '-q', '-m', 'remove');+ if (committed) {+ commitAll(f.root, 'pages');+ git(f.root, 'rm', '-q', '--', ...slugs.map(slug => `${slug}.md`)); git(f.root, 'commit', '-q', '-m', 'remove');+ } else for (const slug of slugs) rmSync(join(f.root, `${slug}.md`));for (const slug of slugs) {const live = (await snapshot(f.sourceId, slug))!;await hold(f, { path: `${slug}.md`, slug, pageId: Number(live.page.id), side: 'deleted', state: 'file_gone', revision: live.revision });@@ -115,7 +123,7 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prevconst slugsOf = (result: Awaited<ReturnType<typeof run>>) => (result.details!.pages as Array<{ slug: string }>).map(page => page.slug);test('past its time budget a window previews one page; the cursors walk the held set once, and an apply covers only its window', () => fixture(async f => {- const slugs = await fileGone(f, 3);+ const slugs = await fileGone(f, 3, { committed: false });const ticks: string[] = [];const progress = { start: (phase: string, total?: number) => ticks.push(`start ${phase} ${total}`), tick: (_n?: number, note?: string) => ticks.push(`tick ${note}`),heartbeat() {}, finish: () => ticks.push('finish'), child: () => progress } as unknown as ProgressReporter;@@ -148,8 +156,9 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prev}), 240_000);test('an apply parses the preview artifact once while it is unchanged, and reports each item to its progress reporter', () => fixture(async f => {+ // Named pages: a committed delete is recreated only when the page is named (GST-2579).const slugs = await fileGone(f, 3);- const preview = await run(f.sourceId, {});+ const preview = await run(f.sourceId, { held: false, slugs });const hash = preview.preview_hash!;// Git durability is off in this fixture: the preview leads with what the next sync does to an uncommitted recreate.expect(preview.warnings![0]).toStartWith('The next sync undoes this repair unless the recreated files are committed');@@ -162,14 +171,14 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prevconst ticks: string[] = [];const progress = { start: (phase: string, total?: number) => ticks.push(`start ${phase} ${total}`), tick: (_n?: number, note?: string) => ticks.push(`tick ${note}`),heartbeat() {}, finish: () => ticks.push('finish'), child: () => progress } as unknown as ProgressReporter;- const applied = await run(f.sourceId, { expect: hash, progress });+ const applied = await run(f.sourceId, { held: false, slugs, expect: hash, progress });expect(applied.outcomes).toEqual({ repaired: 3 });expect(ticks).toEqual(['start repair.file-drift.apply 3', ...slugs.map(slug => `tick ${f.sourceId}:${slug}`), 'finish']);for (const slug of slugs) expect(existsSync(join(f.root, `${slug}.md`))).toBe(true);}), 240_000);test('a window stops at 200 pages and the next one previews the rest', () => fixture(async f => {- const slugs = await fileGone(f, 203);+ const slugs = await fileGone(f, 203, { committed: false });const first = await run(f.sourceId, {});expect(slugsOf(first)).toEqual(slugs.slice(0, 200));expect(window(first)).toMatchObject({ previewed: 200, remaining: 3, complete: false });diff --git a/test/repair-file-drift-origin-twin-gbra108.test.ts b/test/repair-file-drift-origin-twin-gbra108.test.tsindex a3b271e478..da8d9e47a9 100644--- a/test/repair-file-drift-origin-twin-gbra108.test.ts+++ b/test/repair-file-drift-origin-twin-gbra108.test.ts@@ -77,7 +77,9 @@ test('a held origin twin is listed by the preview with an apply command, and --pconst planned = await preview(engine, 'database');expect(planned.residuals).toEqual({});expect(planned.affected).toBe(1);- expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'prefer_database', detail: 'exactly the preferred side; adopts the file at its slug path' }]);+ // GST-2579: the external commit was never imported, so the listing names the commit the repair discards.+ expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'prefer_database',+ detail: expect.stringMatching(new RegExp(`^discards commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)} by Example on \\S+ to ${PATH}, which sync never recorded importing; exactly the preferred side; adopts the file at its slug path$`)) }]);expect((await preview(engine, 'database', planned.preview_hash!)).outcomes).toEqual({ repaired: 1 });await settleManagedGitEffects(engine);git(root, 'commit', '-qam', 'commit the repaired file');diff --git a/test/repair-file-drift-provenance-gbra133.test.ts b/test/repair-file-drift-provenance-gbra133.test.tsindex 839d87796f..b736e5078a 100644--- a/test/repair-file-drift-provenance-gbra133.test.ts+++ b/test/repair-file-drift-provenance-gbra133.test.ts@@ -109,9 +109,10 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: held goneconst all = await run({ prefer: 'database' });expect(all.preview_hash).toBeTruthy();expect(all.details!.provenance).toEqual({ deleted_by_commit: 1, deletion_uncommitted: 0, never_committed: 1, unknown: 0 });- expect(pages(all).map(page => [page.slug, page.provenance?.kind, page.provenance?.subject])).toEqual([['notes/b', 'deleted_by_commit', 'cull b'], ['notes/w', 'never_committed', undefined]]);- expect(pages(all).find(page => page.slug === 'notes/b')!.provenance!.commit).toBe(git(root, 'rev-parse', 'HEAD'));- expect(all.listing!.find(entry => entry.item === 'default:notes/b')!.detail).toContain(`deleted by commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);+ // GST-2579: a database-wins run keeps notes/b's delete, newer than what sync imported, and names its commit.+ expect(pages(all).map(page => [page.slug, page.provenance?.kind, page.provenance?.subject])).toEqual([['notes/w', 'never_committed', undefined]]);+ expect(all.listing!.find(entry => entry.item === 'default:notes/b')).toMatchObject({ class: 'kept_newer_delete',+ detail: expect.stringContaining(`commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`) });expect(all.listing!.find(entry => entry.item === 'default:notes/w')!.detail).toContain('never committed');const unsafe = await refusal(run({ prefer: 'file', provenance: 'never_committed' }));@@ -122,6 +123,8 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: held goneconst accept = await run({ prefer: 'file', provenance: 'deleted_by_commit' });expect(pages(accept).map(page => [page.slug, page.action])).toEqual([['notes/b', 'soft_delete']]);+ expect(pages(accept).map(page => [page.provenance?.kind, page.provenance?.subject, page.provenance?.commit])).toEqual([['deleted_by_commit', 'cull b', git(root, 'rev-parse', 'HEAD')]]);+ expect(accept.listing!.find(entry => entry.item === 'default:notes/b')!.detail).toContain(`deleted by commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);expect(accept.residuals).toMatchObject({ other_provenance: 1 });const accepted = await run({ prefer: 'file', provenance: 'deleted_by_commit', expect: accept.preview_hash! });expect(accepted.outcomes).toEqual({ repaired: 1 });diff --git a/test/sync-holds-wave-gbra133.test.ts b/test/sync-holds-wave-gbra133.test.tsindex 4218e963ee..0949afa0b6 100644--- a/test/sync-holds-wave-gbra133.test.ts+++ b/test/sync-holds-wave-gbra133.test.ts@@ -51,10 +51,10 @@ const origin = async (engine: BrainEngine, slug: string) => (await engine.execut"SELECT source_path, source_uri FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };-async function heldPreview(engine: BrainEngine, prefer: 'file' | 'database', expectHash?: string) {+async function heldPreview(engine: BrainEngine, prefer: 'file' | 'database', expectHash?: string, slugs?: string[]) {return withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>(await repairRunner(engine, { apply: expectHash !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),- { explicit: true, sourceFlag: 'default', held: true, side: 'unknown', prefer, ...(expectHash ? { expect: expectHash } : {}) }));+ { explicit: true, sourceFlag: 'default', ...(slugs ? { slugs } : { held: true, side: 'unknown' }), prefer, ...(expectHash ? { expect: expectHash } : {}) }));}const listing = (plan: Awaited<ReturnType<typeof heldPreview>>) => (plan as { listing?: Array<{ item: string; class: string }> }).listing?.map(row => `${row.item} ${row.class}`);@@ -116,7 +116,8 @@ for (const backend of testBackends()) {writeFileSync(join(root, 'people/alice-example.md'), note('people/alice-example', 'The full page of people/alice-example.')); commitAll(root, 'add alice');await performManagedSync(engine, OPTS);expect(await holds(engine)).toEqual(['people/alice-example.md file_drift unknown']);- expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:people/alice-example prefer_database']);+ // GST-2579: sync never imported the file, so a held database-wins run keeps it.+ expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:people/alice-example kept_newer_file']);const preview = await heldPreview(engine, 'file');expect(listing(preview)).toEqual(['default:people/alice-example prefer_file']);expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'people/alice-example', adopt_slug_path: true })]);@@ -133,7 +134,7 @@ for (const backend of testBackends()) {writeFileSync(join(root, 'projects/README.md'), note('Projects', 'The projects index.')); commitAll(root, 'add readme');await performManagedSync(engine, OPTS);expect(await holds(engine)).toEqual(['projects/README.md file_drift unknown']);- expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:projects/readme prefer_database']);+ expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:projects/readme kept_newer_file']);const preview = await heldPreview(engine, 'file');expect(listing(preview)).toEqual(['default:projects/readme prefer_file']);expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });@@ -226,9 +227,11 @@ for (const backend of testBackends()) {await engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only": true}'::jsonb WHERE id='default'`);expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:notes/mirror-page no_drift']);await engine.executeRaw(`UPDATE sources SET config = config - 'mirror_read_only' WHERE id='default'`);- const preview = await heldPreview(engine, 'database');+ // GST-2579: the upstream file was never imported, so the held run keeps it and only naming the page takes the database copy.+ expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:notes/mirror-page kept_newer_file']);+ const preview = await heldPreview(engine, 'database', undefined, ['notes/mirror-page']);expect(listing(preview)).toEqual(['default:notes/mirror-page prefer_database']);- expect((await heldPreview(engine, 'database', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });+ expect((await heldPreview(engine, 'database', preview.preview_hash!, ['notes/mirror-page'])).outcomes).toEqual({ repaired: 1 });expect(readFileSync(join(root, 'notes/mirror-page.md'), 'utf8')).toContain('The database copy, written while the source was a mirror.');expect(await engine.executeRaw("SELECT source_path, database_only_reason FROM pages WHERE source_id='default' AND slug='notes/mirror-page'")).toEqual([{ source_path: 'notes/mirror-page.md', database_only_reason: null }]);