Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Sync stops holding pages over gbrain's own frontmatter stamps, and file-drift repairs can compare first (GST-2568)
garrytan423dcc57f307
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 927b2836bc..11d2a838ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ 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]++### Sync no longer holds pages over gbrain's own frontmatter stamps, and file-drift repairs can compare before you pick a side++**A page that differs from its file only by what gbrain itself wrote is no longer held as file drift.** A schema-pack retype changes a page's type in the database and keeps the old type as `legacy_type` (plus an optional `subtype`) without touching the file. A file that still named the old type then read as a different page, and a later mass rewrite of the files, or a page imported before import records existed, turned that into a `file_drift` hold that needed a person. Sync now reads such a file with the stored retype stamp kept, so nothing differs. A real database edit (a label, a body change) is still held.++- **Existing holds of that kind release by themselves.** The next sync after upgrading re-screens each held `file_drift` page that is not a deletion once, releases the ones that now agree with no page write and no commit, and says how many (`Released N held file(s) that no longer need a decision.`, JSON `holds_released`). On a seeded source of 3,000 holds, 99% of them normalisation-only, one sync released 2,970 and left the 30 real differences held, in about 27 s on PGLite and 61 s on Postgres; the next sync took about 0.1 s.+- **A later commit over a page that only gained derived keys imports.** When the page side changed only by keys gbrain derives (a stored reserved `type` key or a `validate: false` stamp) and someone commits a body edit to the file, sync imports the file instead of holding it.+- **A page whose file is gone under a `gbrain.yml` `db_only` folder is no drift.** An existing deleted-side hold there now releases.+- **`gbrain repair file-drift` compares without a winner.** Any selection without `--prefer` lists, per page, what differs, which side is newer (the file's last commit against the page's `updated_at`) and what a repair would do, and writes nothing. A `--prefer` preview with no side names that comparison as its fix.+- **`--prefer file` never drops a newer page in bulk.** A `--held`, `--all-drifted` or `--request` preview lists a page edited after its file's last commit as `kept_newer_page` and leaves it held; naming the page with `--slug` still resolves it, with a warning naming the edit it drops. A page whose file is gone is never deleted by a comparison (GST-2568).+## [0.60.699.0] - 2026-11-12### The Ubicloud gate VMs run a current gitdiff --git a/docs/architecture/key-files/canonical-reconciliation-continued.md b/docs/architecture/key-files/canonical-reconciliation-continued.mdindex bda6b7f80a..498887f381 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/repair/file-drift-compare.ts` — GST-2568: `gbrain repair file-drift` with a selection and no `--prefer` (`compareSelection` in file-drift.ts) compares each page with its file through `comparePage` and writes nothing: `driftDifference` over the `reconcileCanonical` readings names what differs, `newerSide` compares the file's last commit at HEAD (`fileCommitEvidence`) with the page's `updated_at` (unknown with uncommitted bytes, a missing time or the same second), and the verdict is `release_hold`, `no_drift`, `prefer_file`, `needs_human` (a newer page, a page whose file is gone, a deleted page whose file differs) or `unknown`. A `--prefer file` preview reads `readDriftEvidence` first and lists a page newer than its file `kept_newer_page` (`newerPageParagraph`) unless `--slug` names it, which adds a warning instead. Test: `test/file-drift-normalisation-gst2568.test.ts`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 84f44af5f2..aa2c82d3db 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -3356,9 +3356,37 @@ One preview resolves one Decision, so a selection that spans several sides ordeleted states refuses [`file_drift_mixed_selection`](error-codes.md#file_drift_mixed_selection),and a deleted side refuses without `--state`([`file_drift_state_required`](error-codes.md#file_drift_state_required)):-the two `--prefer` values do opposite things in each state. `--held`, `--side`,-`--state`, `--cursor` and `--provenance` always need `--prefer`: without it-the command refuses with the usage line instead of running the bare survey.+the two `--prefer` values do opposite things in each state. Those two refusals+apply to a `--prefer` preview only.++<a id="file-drift-compare"></a>**Compare before you pick a side** (GST-2568). Any selection (`--slug`,+`--request`, `--all-drifted` or `--held`, with its narrowing flags) without+`--prefer` compares each page with its file and writes nothing. Each page+lists what differs (`frontmatter` with the keys, `body`, `both`, or `none`+once gbrain's own normalisation is read), which side is newer (the file's last+commit time at HEAD against the page's `updated_at`; `unknown` when the file+has uncommitted bytes or a time is missing) and what a repair would do:+`release_hold` or `no_drift` (they agree), `prefer_file` (the file was+committed after the page last changed, so the file side is the repair),+`needs_human` (the page is newer, a page whose file is gone, or a deleted page+whose file differs) or `unknown`. A held comparison may span several sides and+states, and is windowed like a held preview. The comparison prints no apply+command; its `next_actions` names the `--prefer file` preview when some files+are newer. A `--prefer` preview without a side names this comparison as its+`fix`.++```bash+gbrain repair file-drift --source <id> --held --json # compare every held page, no winner named+```++<a id="file-drift-kept-newer"></a>`--prefer file` never drops a page edited after its file's last commit in+bulk. A `--held`, `--all-drifted` or `--request` preview lists such a page+`kept_newer_page`, with the edit's time, the file's commit time and the two ways+to settle it (`--prefer database` for that page, or carry the edit into the+file, commit it and sync), and leaves its hold in place. Naming the page with+`--slug` still resolves it file-wins, and the preview's warning says which+database edit the apply drops. A page whose file is gone is never deleted by a+comparison or by `--prefer file` unless you select its deleted state.| State | `--prefer database` | `--prefer file` ||---|---|---|@@ -3380,13 +3408,18 @@ hold the preview observed, and answers `changed_since_preview` when any ofthem changed. A preview that finds nothing still prints an apply command; itapplies nothing. Page andfile agree when they differ only in formatting sync does not import (frontmatter-key order or quoting). An apply refused before it published reserves no request+key order or quoting, or a retype's database-only `legacy_type` stamp on a file that+still names the old type). An apply refused before it published reserves no requestid, so the apply a fresh preview prints goes through. A page withno recorded file origin (no source path, and a source URI that is not a`file:` URI) is compared with, and adopts, the file at its slug path, spelledas sync imports it (`README.md` for slug `readme`); the apply records thatpath. A sync re-screens a held page that changed since it was held even when-Git did not move. A page a read-only mirror stored database-only (`mirror_read_only`)+Git did not move. A gbrain that compares file drift differently (GST-2568) has+the next sync re-screen every held `file_drift` page that is not a deletion+once: a page that now agrees with its file is released with no write and no+commit, and the sync prints `Released N held file(s) that no longer need a+decision.` (JSON `holds_released`). A page a read-only mirror stored database-only (`mirror_read_only`)is compared with the file at its slug path once its source is writable again;the apply records that path and clears the stamp.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 32a3c75147..7da441e67d 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -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. [Compare it first](repair.md#file-drift-compare) with `gbrain repair file-drift --source <source> --slug <slug>` (no `--prefer`: it names the newer side and writes nothing). Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. || <a id="file_wins_rewrite"></a>`file_wins_rewrite` | `gbrain repair file-drift --prefer file` keeps the canonical file's bytes and adds only the protected parts reconcile keeps from the database: protected frontmatter keys the file lacks (inserted before the closing `---`) and database-only timeline rows (appended to the file's timeline, with a `<!-- timeline -->` line above a bare `## Timeline` heading so they stay in it). When the resolved page also differs in anything else (a value, a tag, the title, the body), keeping the file would mean re-rendering all of it, so the preview refuses the page and nothing is written. 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/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex dd2ea888de..2fbfecb804 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -871,6 +871,7 @@ src/core/remote-token-cache.ts fs_import 1 W7: filesystem boundary moves to thesrc/core/repair/agent-session-facts.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/repair/captured-facts.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/repair/fences.ts process_env 2 W6: settings plane out of the core+src/core/repair/file-drift-compare.ts spawn_import 1 W7: process-wide effects move to src/clisrc/core/repair/file-drift.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/repair/frontmatter.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/repair/frontmatter.ts spawn_import 1 W7: process-wide effects move to src/clidiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b1efc2ba87..0fa1a0c87e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -38,7 +38,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1997 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt names; +1 GBRA-377 PR B: the GBRAIN_HOOK_LANE=skill-resolver dispatch line (logic in core/skills/resolver/hook-lane.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 2027 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +2 GBRA-377 PR B: loadConfig reads a config.json of file-plane settings alone (skills.resolver) as no brain, plus its comment; +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts); re-summed at the #8797 merge (2026 measured); +1 GST-2250: the sources.auto_reconcile.source. KNOWN_CONFIG_KEY_PREFIXES row (prefix rows are data and cannot move)-src/core/persistence/sync-run.ts 1710 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals); +10 GBRA-133: freezeEntry takes a timer turn between its synchronous Git reads and re-checks the run there (loopYield lives in sync-yield.ts; the turns sit between reads of freezeEntry locals)+src/core/persistence/sync-run.ts 1714 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals); +10 GBRA-133: freezeEntry takes a timer turn between its synchronous Git reads and re-checks the run there (loopYield lives in sync-yield.ts; the turns sit between reads of freezeEntry locals); +4 GST-2568: the freeze drift screen accepts a page that holds its file's baseline when only derived keys differ (onlyDerivedKeysAdded lives in sync-screen.ts; the condition reads freezeEntry locals), and performManagedPass counts the holds a pass released (sourceHoldFingerprints and releasedHoldCount live in sync-holds.ts)src/core/persistence/worktree-refresh.ts 1554 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside itsrc/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mintdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex c484306067..2b032015f9 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -570,6 +570,7 @@ src/core/repair/extractor-facts.ts restorePageFacts sql STREAMsrc/core/repair/fact-claim-dates.ts movePage call:serializePageToMarkdown SEGW refuses a segmented page: the plan lists it segmented_page and movePage keeps one as changed_since_previewsrc/core/repair/fences.ts afterBytes field STREAMsrc/core/repair/fences.ts fencesRepair field STREAM+src/core/repair/file-drift-compare.ts driftDifference field NONE compares the compiled_truth and timeline of the reconcile reading (readReconcileState materializes a segmented page), never a stored body stringsrc/core/repair/frontmatter.ts analyzeFile field LEADsrc/core/repair/frontmatter.ts pagesByOrigin sql LEADsrc/core/repair/lost-fence-rows.ts lostIn field NONE walks the history scanLostFenceRows built (inline page_versions bodies and a materialized snapshot); no stored page body is read herediff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 06a9792cad..545819a008 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -86,7 +86,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>]| --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone[--provenance never_committed|deleted_by_commit|deletion_uncommitted]]] [--cursor <next_cursor>])- [--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]+ [--only <glob>]... [--skip <glob>]... [--prefer file|database [--apply --expect <preview-hash>]] [--json]gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>][--keep prior|disk|withdrawn --apply --expect <preview-hash> --yes] [--json]gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]@@ -157,7 +157,8 @@ Options:--prefer file|database, --request <id>, --all-drifted, --class <name>file-drift: the side that wins; select conflict receipts by request id (repeatable), or every pagestill drifted (refused across mixed drift classes unless --class keeps one). --keep is refused here:- --prefer database keeps the database copy, --prefer file keeps the file.+ --prefer database keeps the database copy, --prefer file keeps the file. A selection without --prefer+ compares each page with its file, names the newer side and the next step, and writes nothing.--held [--side both|unknown|deleted] [--state tombstone_edited|purged_differs|file_gone]file-drift: select the source's held file_drift pages of one Decision. --side deleted needs --state,because --prefer file and --prefer database do opposite things in each state (tombstone_edited: restorediff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsindex 03c12ca446..e02ba12300 100644--- a/src/commands/sync-diagnostics.ts+++ b/src/commands/sync-diagnostics.ts@@ -31,6 +31,7 @@ export function printHoldNotes(result: SyncResult, write: (line: string) => void// #7199: the source synced, and files held this run wait on a person; the hold fix's verify step names the source.const source = result.holds_fix?.verify?.argv?.[3];if (result.reason === 'held_needs_human' && source) write(`Synced; ${result.held_needs_human} file(s) held for a person (gbrain sync status --source ${source}).`);+ if (result.holds_released) write(` Released ${result.holds_released} held file(s) that no longer need a decision.`);for (const item of (result.held ?? []).slice(0, HOLD_LINES)) write(holdLine(item, 'Held'));const shown = Math.min(result.held?.length ?? 0, HOLD_LINES);if ((result.held_count ?? 0) > shown) write(` ... and ${(result.held_count ?? 0) - shown} more held this run (--json lists ${result.holds_truncated ? 'the first ones' : 'them all'}).`);diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex e84c7a98e0..2a7b3b081c 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -148,7 +148,7 @@ export interface SyncResult {*/held?: import('../core/persistence/sync-holds.ts').GitHoldItem[];held_count?: number; held_needs_human?: number;- holds_outstanding?: number;+ holds_outstanding?: number; holds_released?: number;holds_escalated?: boolean;holds_truncated?: boolean;/** A sliced run (`writer_yield`) has not screened every entry yet. */diff --git a/src/core/persistence/align-stored.ts b/src/core/persistence/align-stored.tsindex dddc1ddc5b..9117c8cd2f 100644--- a/src/core/persistence/align-stored.ts+++ b/src/core/persistence/align-stored.ts@@ -5,13 +5,37 @@ import { resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';* `type:` (or whose type was only inferred from its path, #6605) keeps the stored type, and the subtype is resolved* against that type, so the stored subtype is kept too, and so is the grandfather stamp (#6429). Import over an existing* page (import-file.ts), the write guard (page-prepare.ts) and reconcile (reconcile-state.ts, reconcile-prepare.ts) share it.+ * A file that still names the type a schema-pack retype replaced keeps the retyped page's type and stamp (`keepRetypeStamp`).*/export function alignWithStored(parsed: ParsedMarkdown, stored: { type: string; frontmatter?: Record<string, unknown> | null }, inferred: boolean): void {- if (inferred || !parsed.typeExplicit) parsed.type = stored.type as ParsedMarkdown['type'];+ if (!keepRetypeStamp(parsed, stored) && (inferred || !parsed.typeExplicit)) parsed.type = stored.type as ParsedMarkdown['type'];resolveParsedSubtype(parsed, stored);keepGrandfatherStamp(parsed.frontmatter, stored);}+/** Sync's reading of a file over the stored page (sync-prepare.ts): the retype stamp, the subtype and the grandfather stamp kept as `alignWithStored` keeps them; an explicit file type is otherwise read as written. */+export function keepStoredStamps(parsed: ParsedMarkdown, stored?: { type: string; frontmatter?: Record<string, unknown> | null } | null): void {+ keepRetypeStamp(parsed, stored);+ resolveParsedSubtype(parsed, stored);+ keepGrandfatherStamp(parsed.frontmatter, stored);+}++/**+ * GST-2568: a schema-pack retype (schema-pack/retype.ts, run by unify-types) changes `pages.type` from `from_type` to+ * `to_type` and stamps `legacy_type: <from_type>` (D8, its per-page rollback record), and optionally a `subtype`, in the+ * database only; it never writes the file. A file that still names `from_type` and carries no `legacy_type` of its own+ * is that page as retyped, so it keeps the stored type and stamp; the stored subtype then follows through+ * `resolveParsedSubtype` (the types now agree). A file that names any other type, or writes `legacy_type` itself, is+ * read as written. Returns whether the stamp was kept.+ */+export function keepRetypeStamp(parsed: ParsedMarkdown, stored?: { type: string; frontmatter?: Record<string, unknown> | null } | null): boolean {+ const legacy = stored?.frontmatter?.legacy_type;+ if (!stored || typeof legacy !== 'string' || Object.hasOwn(parsed.frontmatter, 'legacy_type') || parsed.type !== legacy) return false;+ parsed.type = stored.type as ParsedMarkdown['type'];+ parsed.frontmatter.legacy_type = legacy;+ return true;+}+/*** #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path never wrote* the file, so the file lacks a key the database carries. The mechanical stamp authors nothing (grandfather.ts): a filediff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 413d384140..02fef8bfc3 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -473,6 +473,19 @@ export async function settledDeletionHolds(tx: Exec, sourceId: string, candidatereturn candidates.filter(c => (c.page_id === null || !ids.has(String(c.page_id))) && (c.slug === null || !slugs.has(c.slug))).map(c => c.path);}+/** GST-2568: the fingerprints of a source's holds; a managed pass reads them before it runs to count the holds it released (`releasedHoldCount`). */+export async function sourceHoldFingerprints(engine: Exec, sourceId: string): Promise<Set<string>> {+ const rows = await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'=$2", [GIT_HOLD_OP, sourceId]);+ return new Set(rows.map(row => row.fingerprint));+}++/** GST-2568: how many of the holds read before a pass (`sourceHoldFingerprints`) are gone after it. */+export async function releasedHoldCount(engine: Exec, sourceId: string, before: Set<string> | null): Promise<number> {+ if (!before?.size) return 0;+ const after = await sourceHoldFingerprints(engine, sourceId);+ return [...before].filter(fingerprint => !after.has(fingerprint)).length;+}+/** #5984: which of these paths have a hold row (one indexed read), so a batched waiver run clears only those. */export async function heldGitPaths(tx: Exec, sourceId: string, incarnation: string, paths: readonly string[]): Promise<Set<string>> {if (!paths.length) return new Set();@@ -612,8 +625,9 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so/*** GBRA-133: the `file_drift` screen version; 1 is #7340's rule (a page with no import record compares its file at the baseline commit),* 2 adds the path's earlier committed versions (`driftHistory`), which landed after version 1 without re-screening its holds.+ * GST-2568: 3 reads a schema-pack retype's database-only stamp as the file's own type (align-stored.ts `keepRetypeStamp`).*/-export const FILE_DRIFT_VERSION = 2;+export const FILE_DRIFT_VERSION = 3;export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || (record.code === 'file_too_large' && record.meta.streamed?.gbrain_version !== VERSION) || ['frontmatter_slug_conflict', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict', 'page_identity_changed', 'git_object_missing'].includes(record.code)@@ -626,6 +640,8 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re// GBRA-133: an unknown-side drift held before #7340's baseline rule (a Git edit to a page with no import record) imports// now when the page still holds its file at the baseline commit, so it is screened once more.|| (record.code === 'file_drift' && fileDriftSide(record.meta) === 'unknown' && (record.meta.drift_version ?? 0) < FILE_DRIFT_VERSION)+ // GST-2568: a live page's drift held before version 3 may differ from its file only by a schema-pack retype's stamp, so it is screened once more.+ || (record.code === 'file_drift' && fileDriftSide(record.meta) !== 'deleted' && (record.meta.drift_version ?? 0) < 3)// #8007: a deletion held while gbrain.yml's storage section was invalid is decided again by every sync, so a fixed file settles it.|| (record.code === 'file_drift' && record.meta.reason === 'storage_invalid')|| (outOfAttemptsHold(record.code) && record.meta.stall?.gbrain_version !== VERSION)@@ -1387,7 +1403,7 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; i/** The hold fields as the sync JSON envelopes carry them (snake_case already). */export function syncHoldJsonFields(result: object): Record<string, unknown> {const fields = result as Record<string, unknown>;- return Object.fromEntries(['held', 'held_count', 'held_needs_human', 'holds_outstanding', 'holds_escalated', 'holds_truncated', 'holds_pending_screen', 'holds_fix',+ return Object.fromEntries(['held', 'held_count', 'held_needs_human', 'holds_outstanding', 'holds_released', 'holds_escalated', 'holds_truncated', 'holds_pending_screen', 'holds_fix','converted_from_failed', 'recovered_frontmatter', 'fences_normalized', 'fence_issues', 'dry_run', 'would_hold', 'would_hold_count', 'would_normalize', 'would_normalize_count', 'screen_skipped', 'breaker', 'slug_lines_removed'].filter(key => fields[key] !== undefined).map(key => [key, fields[key]]));}diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex fc51875bcc..ad39658039 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -635,6 +635,18 @@ async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | u* GBRA-133: the deleted-side `file_drift` holds and the `concurrent_write` holds (#8751) whose file is gone (`gone`, on the* Git path); the stamp releases those whose page is no longer live, where both sides agree the path is deleted.*/+/**+ * Whether the pass releases a held path: one outside the sync domain, a `storage_invalid` hold once gbrain.yml's storage+ * loads and resolves its folder (#8007), and (GST-2568) a live page whose file is gone once gbrain.yml declares its folder+ * database-only, which is no drift.+ */+function releasableHold(hold: GitHoldRecord, inDomain: boolean, dbOnlyUnknown: boolean, storage: Parameters<typeof dbOnlyVerdict>[1]): boolean {+ if (!inDomain) return true;+ if (dbOnlyUnknown || hold.code !== 'file_drift') return false;+ if (hold.meta.reason === 'storage_invalid') return !hold.slug || dbOnlyVerdict(hold.slug, storage) !== 'unknown';+ return hold.meta.state === 'file_gone' && !!hold.slug && dbOnlyVerdict(hold.slug, storage) === true;+}+function deletionCandidates(holds: readonly GitHoldRecord[], gone: (path: string) => boolean, toGit: (path: string) => string): DeletionCandidate[] {return holds.filter(hold => (hold.code === 'concurrent_write' || hold.code === 'file_drift' && fileDriftSide(hold.meta) === 'deleted') && gone(toGit(hold.path))).map(hold => ({ path: hold.path, page_id: hold.page_id ?? null, slug: hold.slug ?? null }));@@ -936,7 +948,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, strict, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),- releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path)) || (!dbOnlyUnknown && hold.code === 'file_drift' && hold.meta.reason === 'storage_invalid' && (!hold.slug || dbOnlyVerdict(hold.slug, storage) !== 'unknown'))).map(hold => hold.path),+ releasableHolds: holds.filter(hold => releasableHold(hold, domain.has(toGit(hold.path)), dbOnlyUnknown, storage)).map(hold => hold.path),deletionCandidates: deletionCandidates(holds, path => domain.has(path) && !tree.has(path)&& !(mode === 'working' && (untracked.has(path) || index.has(path))) && !readPresent(root, path, scope), toGit),paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3,diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex b4e91bf148..f7023ce5c2 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -19,7 +19,7 @@ import type { VersionHistory } from '../page-state/versions.ts';import { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';-import { keepGrandfatherStamp } from './align-stored.ts';+import { keepStoredStamps } from './align-stored.ts';import { resolveSlugForPath, slugifyPath, isCodeFilePath, isImageFilePath } from '../sync.ts';import { prepareManagedSyncImage } from './sync-image.ts';import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';@@ -913,8 +913,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c`Page ${ready.slug} already holds the content identity of ${renamed?.slug ?? row.slug}; resolve the duplicate pages first.`);}const parsed = parseMarkdown(keepDbOnlyLabels(root, row.slug, base, p.content, parsedInput.frontmatter), `${row.slug}.md`, { activePack });- resolveParsedSubtype(parsed, base?.page);- keepGrandfatherStamp(parsed.frontmatter, base?.page);+ keepStoredStamps(parsed, base?.page);const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();const renderedPage = { ...(base ? withoutBody(base.page) : { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex d3ad21e4c2..ea7490a03a 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -48,7 +48,7 @@ import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { readDryRunWriterState } from './sync-dry-run-writer.ts';import { fileMatchesSnapshot } from './page-prepare.ts';-import { pageHoldsDriftBaseline, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedFilterDriver, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, unreadableFileHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';+import { onlyDerivedKeysAdded, pageHoldsDriftBaseline, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedFilterDriver, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, unreadableFileHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';import { frozenImageIntent, sameImageBytes } from './sync-image.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';@@ -64,7 +64,7 @@ import { withManagedReasonNotices } from './sync-reasons.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';-import { outOfAttemptsHold, addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';+import { outOfAttemptsHold, addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, releasedHoldCount, sourceHoldFingerprints, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';import { withScreeningPaths } from './screening-paths.ts';import { withBoundedReadSession } from './bounded-reads.ts';import { receiptClass, recordedStop, replaysContentRefusal, resumableStop, stopRecorded, unrecordedStop } from './sync-stop-class.ts';@@ -480,10 +480,12 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,}}// #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).- // #7931: a file that holds the page as prepareFileTarget and repair file-drift read it (format-insensitive) is one too.+ // #7931: a file that holds the page as prepareFileTarget and repair file-drift read it (format-insensitive) is one too;+ // GST-2568: and so is a page that holds its file's baseline (or an earlier committed version) in that same reading.if (entry.drift && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page): await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal)- || await fileMatchesSnapshot(engine, slug, content, snapshot, entry.sourcePath).catch(() => false) || await pageHoldsDriftBaseline(cursor.gitRoot, entry, baseline => sameContentAtOrigin(engine, cursor, entry, key, snapshot, baseline, null, false, run.signal, true)))) {+ || await fileMatchesSnapshot(engine, slug, content, snapshot, entry.sourcePath).catch(() => false) || await pageHoldsDriftBaseline(cursor.gitRoot, entry, async baseline => await sameContentAtOrigin(engine, cursor, entry, key, snapshot, baseline, null, false, run.signal, true)+ || baseline !== null && onlyDerivedKeysAdded(baseline, snapshot.page.frontmatter) && await fileMatchesSnapshot(engine, slug, baseline, snapshot, entry.sourcePath).catch(() => false)))) {if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} ${entry.drift === 'unknown' ? `differs from ${entry.path} and has no import record to tell whether the file or the database changed` : `changed in the database since ${entry.path} was last imported, and the file differs from it`}, so the run stopped before admitting it (sync.holds=fail).`);const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null }); assertActive();return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof, sharedOrigin: await sharedOriginSurvivor(engine, cursor.sourceId, entry.sourcePath), baseline: entry.driftBaseline ?? null }) };@@ -1294,6 +1296,7 @@ async function performLeasedPass(engine: BrainEngine, opts: SyncOpts, slice?: {}async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {const state: HoldRunState = {};+ const holdsBefore = opts.dryRun ? null : await sourceHoldFingerprints(engine, opts.sourceId ?? 'default').catch(() => null);// #6729: every managed entry point (CLI, drain, owner slice, worktree refresh) records the renames whose identity it did not keep.const synced = await withManagedReasonNotices(engine, opts.sourceId ?? 'default', await noteIdentityDowngrades(engine, opts.sourceId ?? 'default', await runManagedSync(engine, opts, slice, state), serr));if (!state.sourceId || !state.incarnation || synced.status === 'dry_run' || currentDrainLease(state.sourceId)?.idleClear) return synced;@@ -1306,7 +1309,8 @@ async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: {const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);// #7199: a pass that synced but held files a person must decide does not read as plain synced.const humanHeld = report.held_needs_human && !synced.reason && ['synced', 'first_sync', 'up_to_date'].includes(synced.status);- return { ...synced, ...report, ...(humanHeld ? { reason: 'held_needs_human' as const } : {}), ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),+ const released = await releasedHoldCount(engine, state.sourceId, holdsBefore);+ return { ...synced, ...report, ...(released ? { holds_released: released } : {}), ...(humanHeld ? { reason: 'held_needs_human' as const } : {}), ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),...(recovered ? { recovered_frontmatter: recovered } : {}), ...(fences ? { fences_normalized: fences } : {}) };} catch {return synced;diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex a6ef867210..299eb67115 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -30,7 +30,7 @@ import { slugConflictHoldMessage } from '../import-file.ts';import { isImageFilePath, isMultimodalEnabled, resolveSlugForPath } from '../sync.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { VERSION } from '../../version.ts';-import { sha256 } from './digest.ts';+import { digest, sha256 } from './digest.ts';import { readPageBodyPolicy, type PageBodyPolicy } from '../page-body/limits.ts';import { materializedSnapshot } from './segmented-apply.ts';import { readPagePurgeTombstones } from './page-purge.ts';@@ -123,6 +123,18 @@ export function driftBaselineContent(gitRoot: string, entry: Pick<SyncEntry, 'drtry { return readBlobContents(gitRoot, [{ oid: entry.driftBaseline, size: SYNC_READ_BOUND }]).get(entry.driftBaseline) ?? null; } catch { return null; }}+/**+ * GST-2568: whether the stored frontmatter differs from a file's only by keys gbrain itself wrote to the database: a copy of+ * the reserved `type` key (older imports) and the grandfather's `validate: false` (#6429), each absent from the file. A+ * page with any other difference (a protected key, a label) is not treated as unchanged since that file.+ */+export function onlyDerivedKeysAdded(content: string, stored: Record<string, unknown> | null | undefined): boolean {+ const file = parseMarkdown(content, 'derived-keys.md').frontmatter;+ const page = stored ?? {};+ return [...new Set([...Object.keys(file), ...Object.keys(page)])].every(key => digest(file[key] ?? null) === digest(page[key] ?? null)+ || !Object.hasOwn(file, key) && (key === 'type' || key === 'validate' && page[key] === false));+}+/** #7199: whether the page still holds what the entry's baseline or one of its earlier committed versions (`driftHistory`) imports, tried in order. */export async function pageHoldsDriftBaseline(gitRoot: string, entry: Pick<SyncEntry, 'drift' | 'driftBaseline' | 'driftHistory'>, same: (content: string | null) => Promise<boolean>): Promise<boolean> {if (await same(driftBaselineContent(gitRoot, entry))) return true;diff --git a/src/core/repair/file-drift-compare.ts b/src/core/repair/file-drift-compare.tsnew file mode 100644index 0000000000..af16150383--- /dev/null+++ b/src/core/repair/file-drift-compare.ts@@ -0,0 +1,121 @@+/**+ * GST-2568: `gbrain repair file-drift` with a selection and no `--prefer`: a read-only comparison of each selected page+ * with its file that needs no winner. Per page it reports what differs (frontmatter, body, both, or nothing once gbrain's+ * own normalisation is read: `none`), which side is newer by the evidence gbrain has (the file's last commit time at HEAD,+ * the page's `updated_at`), and what a repair would do. It writes nothing: no artifact, no approved set, no hold change.+ *+ * Git is the parent, so a newer file is the side a repair takes (`--prefer file`). A page that changed after its file's+ * last commit and differs from it is never resolved file-wins in bulk (`newerPageParagraph`): `--prefer file` lists+ * it `kept_newer_page` and leaves its hold for a person, and a page whose file is gone is never resolved by deleting it+ * here either; both are `needs_human` with the reason.+ */+import { execFileSync } from '../spawn.ts';+import { gitChildEnv } from '../git-env.ts';+import { relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import type { ParsedPage } from '../import-file.ts';+import { digest } from '../persistence/digest.ts';+import { liveFileDrift } from '../persistence/drift-conflicts.ts';+import { reconcileCanonical } from '../persistence/reconcile-merge.ts';+import { readReconcileState } from '../persistence/reconcile-state.ts';+import { fileDriftActionVerb, fileDriftSide, holdRescreenDue, type GitHoldRecord } from '../persistence/sync-holds.ts';+import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';+import { OperationError } from '../ops/contract.ts';+import type { RepairListing } from './core.ts';++export type DriftDifference = 'none' | 'frontmatter' | 'body' | 'both';+export type NewerSide = 'file' | 'database' | 'unknown';+export interface DriftEvidence { path: string; differs: DriftDifference; keys: string[]; file_committed_at: string | null; file_uncommitted: boolean;+ page_updated_at: string | null; newer: NewerSide }+export type CompareVerdict = 'release_hold' | 'no_drift' | 'prefer_file' | 'needs_human' | 'unknown';+export interface ComparedPage { item: string; slug: string | null; path?: string; would: CompareVerdict; why: string; evidence?: Omit<DriftEvidence, 'path'>; side?: string; state?: string }++/** What differs between the file's page (as an import over the stored page reads it) and the database page: the body, and the frontmatter keys (title, type and tags included). */+export function driftDifference(file: ParsedPage, database: ParsedPage): { differs: DriftDifference; keys: string[] } {+ const body = (file.compiled_truth ?? '') !== (database.compiled_truth ?? '') || (file.timeline ?? '') !== (database.timeline ?? '');+ const keys = (['title', 'type'] as const).filter(key => file[key] !== database[key]) as string[];+ if (digest([...file.tags].sort()) !== digest([...database.tags].sort())) keys.push('tags');+ for (const key of [...new Set([...Object.keys(file.frontmatter), ...Object.keys(database.frontmatter)])].sort()) {+ if (digest(file.frontmatter[key] ?? null) !== digest(database.frontmatter[key] ?? null)) keys.push(key);+ }+ return { differs: body ? (keys.length ? 'both' : 'body') : keys.length ? 'frontmatter' : 'none', keys };+}++/** The file's last commit time at HEAD and whether its working-tree bytes differ from HEAD; a Git failure reads as no evidence. */+export function fileCommitEvidence(root: string, path: string): { committed_at: string | null; uncommitted: boolean } {+ const git = (args: string[]) => execFileSync('git', ['-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ try {+ return { committed_at: git(['log', '-1', '--format=%cI', 'HEAD', '--', path]) || null, uncommitted: git(['status', '--porcelain', '--', path]) !== '' };+ } catch { return { committed_at: null, uncommitted: false }; }+}++/**+ * The newer side: the page when it was updated after the file's last commit, the file when it was committed after the+ * page's update; unknown without a commit time, with uncommitted bytes, without an update time, or within the same second+ * (a commit time has whole seconds, so an update in that second may come before or after it).+ */+export function newerSide(file: { committed_at: string | null; uncommitted: boolean }, pageUpdatedAt: string | null): NewerSide {+ if (!file.committed_at || file.uncommitted || !pageUpdatedAt) return 'unknown';+ const page = Math.floor(Date.parse(pageUpdatedAt) / 1000), committed = Math.floor(Date.parse(file.committed_at) / 1000);+ return page > committed ? 'database' : page < committed ? 'file' : 'unknown';+}++/** One live page's comparison with its canonical file (read as reconcile and `repair file-drift` read it). */+export async function readDriftEvidence(engine: BrainEngine, sourceId: string, slug: string, assessmentAt: string): Promise<DriftEvidence> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: !!snapshot && recordsNoFileOrigin(snapshot.page) });+ const { differs, keys } = driftDifference(reconcileCanonical(state.file, state.file.tags), reconcileCanonical(state.snapshot.page, state.snapshot.tags));+ const path = relative(state.root, state.path).split(sep).join('/');+ const file = fileCommitEvidence(state.root, path);+ const updated = state.snapshot.page.updated_at ? new Date(state.snapshot.page.updated_at).toISOString() : null;+ return { path, differs, keys, file_committed_at: file.committed_at, file_uncommitted: file.uncommitted, page_updated_at: updated, newer: newerSide(file, updated) };+}++/** Why a page newer than its file is not resolved file-wins: the paragraph a held page carries in every preview. */+export function newerPageParagraph(sourceId: string, slug: string, evidence: DriftEvidence): string {+ const what = evidence.differs === 'both' ? 'body and frontmatter' : evidence.differs === 'body' ? 'body' : `frontmatter (${evidence.keys.join(', ')})`;+ return `page ${slug} changed after its file was last committed (page updated ${evidence.page_updated_at}, ${evidence.path} committed ${evidence.file_committed_at}) and its ${what} differs, `+ + `so letting the file win would drop that database edit; it stays held for a person. Keep the page with gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database `+ + `(rewrites the file from the page), or carry the edit into the file, commit it and run gbrain sync --source ${sourceId}.`;+}++/** One selected page, compared: a held page by its hold, any other by its slug. Never writes. */+export async function comparePage(engine: BrainEngine, sourceId: string, target: { slug: string | null; hold?: GitHoldRecord }, assessmentAt: string): Promise<ComparedPage> {+ const { slug, hold } = target;+ const item = `${sourceId}:${slug ?? hold?.path ?? ''}`;+ const side = hold ? fileDriftSide(hold.meta) : undefined;+ const held = { ...(side ? { side } : {}), ...(hold?.meta.state ? { state: hold.meta.state } : {}), ...(hold ? { path: hold.path } : {}) };+ if (side === 'deleted' && hold?.meta.state && hold.meta.state !== 'file_gone') {+ const state = hold.meta.state;+ return { item, slug, ...held, would: 'needs_human', why: `the page at ${hold.path} is deleted and the file differs (${state}); --prefer database would ${fileDriftActionVerb('deleted', state, 'database')} and --prefer file would ${fileDriftActionVerb('deleted', state, 'file')}, so a person decides` };+ }+ if (slug === null) return { item, slug, ...held, would: 'unknown', why: 'the hold names no page; the next sync re-classifies it' };+ try {+ const live = await liveFileDrift(engine, sourceId, slug);+ if (live.reason === 'canonical_file_missing') return { item, slug, ...held, would: 'needs_human',+ why: `the page has no file at the last commit, so letting the file win would delete the page; that is never the default here. Keep it with --prefer database (recreates the file), or preview --held --side deleted --state file_gone --prefer file for a deletion you intend` };+ if (live.reason === 'agrees') {+ const due = hold ? holdRescreenDue(hold, false) : false;+ return { item, slug, ...held, ...(live.path ? { path: live.path } : {}), would: hold ? 'release_hold' : 'no_drift',+ why: !hold ? 'the page and its file agree' : due ? 'the page and its file agree once gbrain\'s own normalisation is read; the next sync releases the hold with no write'+ : `the page and its file agree; gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer file previews the release` };+ }+ if (live.still_present !== true) return { item, slug, ...held, would: live.still_present === false ? 'no_drift' : 'unknown', why: live.reason };+ const { path, ...evidence } = await readDriftEvidence(engine, sourceId, slug, assessmentAt);+ const base = { item, slug, ...held, path, evidence };+ if (evidence.differs === 'none') return { ...base, would: hold ? 'release_hold' : 'no_drift', why: 'nothing differs once gbrain\'s own normalisation is read' };+ if (evidence.newer === 'file') return { ...base, would: 'prefer_file', why: `${path} was committed after the page last changed, so the file wins (Git is the parent): gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer file` };+ if (evidence.newer === 'database') return { ...base, would: 'needs_human', why: newerPageParagraph(sourceId, slug, { path, ...evidence }) };+ return { ...base, would: 'needs_human', why: evidence.file_uncommitted ? `${path} has uncommitted bytes, so which side is newer is unknown; commit or restore the file, then compare again`+ : `which side is newer is unknown (${evidence.file_committed_at ? 'the page has no update time' : `no commit holds ${path}`}); a person decides` };+ } catch (error) {+ if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;+ return { item, slug, ...held, would: 'unknown', why: `${error.code}: ${error.message}` };+ }+}++/** The listing row of a compared page. */+export function comparedListing(page: ComparedPage): RepairListing {+ const evidence = page.evidence ? `differs: ${page.evidence.differs}${page.evidence.keys.length ? ` (${page.evidence.keys.join(', ')})` : ''}; newer: ${page.evidence.newer}; ` : '';+ return { item: page.item, class: page.would, detail: `${evidence}${page.why}` };+}diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 51ddf597fa..d83d09af74 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -93,6 +93,7 @@ import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/rimport { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';+import { comparedListing, comparePage, newerPageParagraph, readDriftEvidence, type ComparedPage } from './file-drift-compare.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';export type DriftSide = 'file' | 'database';@@ -293,7 +294,7 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl} while (cursor && drifted.length < ALL_DRIFTED_LIMIT);const counts = new Map<DriftClass, number>();for (const value of classes.values()) counts.set(value, (counts.get(value) ?? 0) + 1);- if (!opts.driftClass && counts.size > 1) {+ if (opts.prefer && !opts.driftClass && counts.size > 1) {const listed = [...counts].map(([name, count]) => `${name}=${count}`).join(', ');throw opError('invalid_params', `The drifted pages of '${sourceId}' fall into ${counts.size} drift classes (${listed}); one --prefer must not resolve them in bulk.`,`Preview one class at a time: ${previewCommand(sourceId, { ...opts, driftClass: [...counts.keys()][0] })}, and so on for each class; or name pages with --slug.`,@@ -334,7 +335,7 @@ function unknownDriftDetail(sourceId: string, { slug, reason }: UnknownDrift): s* (`file_drift_state_required`): its two actions are opposite. Holds an older gbrain wrote with `sides: database` have* no side and are listed with their single-page route.*/-async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions & { prefer: DriftSide }):+async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions):Promise<{ targets: HeldTarget[]; before: number; notSelected: number; legacy: GitHoldRecord[]; otherProvenance: number; provenance?: Record<string, number> }> {const after = opts.cursor ? heldCursorPath(sourceId, opts.cursor) : null;const rows = await engine.executeRaw<{ record: GitHoldRecord; in_window: boolean }>(`SELECT h.completed_keys->0 AS record,@@ -355,14 +356,15 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlaconst group = groups.get(key(target)) ?? { side: target.side, ...(target.state ? { state: target.state } : {}), count: 0 };group.count++; groups.set(key(target), group);}- const narrower = (group: { side: FileDriftSide; state?: FileDriftDeletedState }) => heldCommand(sourceId, group.side, group.state, opts.prefer, opts);+ const narrower = (group: { side: FileDriftSide; state?: FileDriftDeletedState }) => heldCommand(sourceId, group.side, group.state, opts.prefer!, opts);const statusFix = readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] });- if (!opts.side && groups.size > 1) {+ // GST-2568: a comparison without --prefer resolves nothing, so several Decisions may be compared together.+ if (opts.prefer && !opts.side && groups.size > 1) {const listed = [...groups.entries()].map(([name, group]) => `${name}=${group.count}`).join(', ');throw opError('file_drift_mixed_selection', `The held file-drift pages of '${sourceId}' are ${groups.size} different Decisions (${listed}); one --prefer must not resolve them in bulk.`,`Nothing was previewed. Preview one Decision at a time: ${[...groups.values()].map(narrower).join('; ')}.`, { fix: statusFix });}- const only = !opts.side && groups.size === 1 ? [...groups.values()][0]! : null;+ const only = opts.prefer && !opts.side && groups.size === 1 ? [...groups.values()][0]! : null;if (only?.side === 'deleted') throw stateRequired(sourceId, opts, [only.state!]);const selected = targets.filter(target => !opts.side || target.side === opts.side && (!opts.state || target.state === opts.state));let window = selected.filter(target => target.inWindow).map(({ inWindow: _inWindow, ...target }) => target);@@ -403,12 +405,28 @@ function stateRequired(sourceId: string, opts: RepairPlanOptions, states: readon{ fix: readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) });}+const USAGE = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone [--provenance never_committed|deleted_by_commit|deletion_uncommitted]]] [--cursor <next_cursor>]) [--only <glob>]... [--skip <glob>]... [--prefer file|database]';++/** GST-2568: the selection's winner-free comparison (no --prefer), as argv: read-only, it names each page's newer side. */+function compareArgv(sourceId: string, opts: RepairPlanOptions): string[] {+ const select = opts.held ? ['--held', ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []), ...(opts.provenance ? ['--provenance', opts.provenance] : []), ...(opts.cursor ? ['--cursor', opts.cursor] : [])]+ : opts.allDrifted ? ['--all-drifted', ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : [])]+ : [...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.requests ?? []).flatMap(id => ['--request', id])];+ return ['gbrain', 'repair', 'file-drift', '--source', sourceId, ...select, ...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob]), '--json'];+}+function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {+ validateSelection(scope, opts);+ if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database to resolve pages.',+ `Nothing was written. Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way); the comparison in fix shows each page's newer side first: ${USAGE}`,+ { fix: readFix('Compares each selected page with its file and names the newer side and what a repair would do, writing nothing.', { argv: compareArgv(scope.source_ids[0]!, opts) }) });+ if (opts.side === 'deleted' && !opts.state) throw stateRequired(scope.source_ids[0]!, opts, FILE_DRIFT_DELETED_STATES);+}++function validateSelection(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions {if (opts?.remote !== false) throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI on the brain host.');- const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone [--provenance never_committed|deleted_by_commit|deletion_uncommitted]]] [--cursor <next_cursor>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';+ const usage = USAGE;if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair file-drift needs exactly one --source.', `Name the source: ${usage}`);- if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database.',- `Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way): ${usage}`);const modes = [opts.slugs?.length ? 1 : 0, opts.requests?.length ? 1 : 0, opts.allDrifted ? 1 : 0, opts.held ? 1 : 0].reduce((a, b) => a + b, 0);if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request, --all-drifted or --held.', `Pick one selection: ${usage}`);if ((opts.side || opts.state) && !opts.held) throw opError('invalid_params', '--side and --state only narrow --held.', `Drop them, or select the held pages with --held: ${usage}`);@@ -418,7 +436,6 @@ function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefinedif (opts.state && !(FILE_DRIFT_DELETED_STATES as readonly string[]).includes(opts.state)) throw opError('invalid_params', `Unknown deleted-side state '${opts.state}'.`,`Pass --state ${FILE_DRIFT_DELETED_STATES.join(', --state ')} with --side deleted; gbrain sources status ${scope.source_ids[0]} --json lists each held file's state.`);if (opts.state && opts.side !== 'deleted') throw opError('invalid_params', '--state only narrows --side deleted.', `Drop --state, or pass --side deleted with it: ${usage}`);- if (opts.side === 'deleted' && !opts.state) throw stateRequired(scope.source_ids[0]!, opts, FILE_DRIFT_DELETED_STATES);if (opts.provenance && !(DELETION_PROVENANCES as readonly string[]).includes(opts.provenance)) throw opError('invalid_params', `Unknown deletion provenance '${opts.provenance}'.`,`Pass --provenance ${DELETION_PROVENANCES.join(', --provenance ')}; each page of a --held --side deleted --state file_gone preview names its provenance.`);if (opts.provenance && opts.state !== 'file_gone') throw opError('invalid_params', '--provenance only narrows --held --side deleted --state file_gone.',@@ -726,11 +743,53 @@ 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-2568: the selection compared with no winner named (file-drift-compare.ts): per page what differs, which side is newer+ * and what a repair would do. Reads only; it prints no apply command, and a held selection is windowed as a preview is.+ */+async function compareSelection(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions): Promise<RepairPlan> {+ const held = opts.held ? await selectHeld(engine, sourceId, opts) : null;+ const selected = held ? null : await selectSlugs(engine, sourceId, opts);+ const targets: { slug: string | null; hold?: GitHoldRecord }[] = held ? [...held.legacy.map(hold => ({ slug: hold.slug, hold })), ...held.targets.slice(0, HELD_WINDOW_PAGES).map(target => ({ slug: target.hold.slug, hold: target.hold }))]+ : selected!.slugs.map(slug => ({ slug }));+ const residuals: Record<string, number> = { ...(held?.notSelected || selected?.notSelected ? { not_selected: held?.notSelected ?? selected!.notSelected } : {}), ...(held?.before ? { before_cursor: held.before } : {}) };+ const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };+ const listing: NonNullable<RepairPlan['listing']> = [];+ for (const row of selected?.unknown ?? []) { count(`unknown_${row.reason}`); listing.push({ item: `${sourceId}:${row.slug}`, class: 'unknown', detail: unknownDriftDetail(sourceId, row) }); }+ const assessmentAt = new Date().toISOString();+ const windowEnd = Math.min(Date.now() + HELD_WINDOW_BUDGET_MS, opts.deadline ?? Infinity);+ const pages: ComparedPage[] = [];+ let windowed = 0;+ opts.progress?.start('repair.file_drift.compare', targets.length);+ if (targets.length) await asLocalCli(engine, async () => {+ for (const target of targets) {+ if (held && pages.length && Date.now() >= windowEnd) break;+ opts.progress?.tick(1, target.slug ?? target.hold?.path);+ if (target.hold && fileDriftSide(target.hold.meta)) windowed++;+ pages.push(await comparePage(engine, sourceId, target, assessmentAt));+ }+ });+ opts.progress?.finish();+ for (const page of pages) { count(page.would); listing.push(comparedListing(page)); }+ const remaining = held ? held.targets.length - windowed : 0;+ const nextCursor = remaining > 0 && windowed > 0 ? heldCursor(held!.targets[windowed - 1]!.hold.path) : undefined;+ if (remaining > 0) residuals.after_window = remaining;+ const filesNewer = pages.filter(page => page.would === 'prefer_file').length;+ const next = [...(filesNewer ? [`Preview the file side for the ${filesNewer} page(s) whose file is newer: ${previewCommand(sourceId, { ...opts, prefer: 'file' })} (pages newer than their file are left held, kept_newer_page)`] : []),+ ...(nextCursor ? [`Compare the next window: ${shellQuote(compareArgv(sourceId, { ...opts, cursor: nextCursor }).slice(0, -1))}`] : [])];+ return { items: [], residuals, listing, details: { compare: true, writes: 'none',+ pages: pages.map(({ item: _item, ...page }) => page), ...(next.length ? { next_actions: next } : {}),+ ...(held ? { window: { previewed: windowed, remaining, complete: remaining === 0, ...(nextCursor ? { next_cursor: nextCursor } : {}) } } : {}),+ evidence: 'newer compares the file\'s last commit time at HEAD with the page\'s updated_at; unknown when the file has uncommitted bytes or either time is missing.' } };+}+export const fileDriftRepair: RepairHandler = {kind: 'file-drift',outcomeItemsLimit: 1000,async plan(engine, scope, after, opts): Promise<RepairPlan> {if (opts?.remote === false && !opts.apply && !opts.prefer && !opts.slugs?.length && !opts.requests?.length && !opts.allDrifted && !opts.driftClass && !opts.held && !opts.side && !opts.state && !opts.cursor && !opts.provenance) return survey(engine, scope, opts);+ validateSelection(scope, opts);+ if (!opts.apply && !opts.prefer) return compareSelection(engine, scope.source_ids[0]!, opts);validateOptions(scope, opts);const sourceId = scope.source_ids[0]!;const command = previewCommand(sourceId, opts);@@ -781,6 +840,7 @@ export const fileDriftRepair: RepairHandler = {const windowEnd = Math.min(Date.now() + HELD_WINDOW_BUDGET_MS, opts.deadline ?? Infinity);let previewed = 0;const [source] = held ? [] : await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const newerPages: string[] = [];opts.progress?.start('repair.file_drift.preview', targets.length);await asLocalCli(engine, async () => {for (const { slug: targetSlug, held: target } of targets) {@@ -838,6 +898,15 @@ export const fileDriftRepair: RepairHandler = {listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });continue;}+ // GST-2568: Git stays the parent, but a page edited after its file's last commit is never dropped file-wins in bulk;+ // an explicit --slug still resolves it, with the warning naming the edit it drops.+ if (opts.prefer === 'file') {+ const evidence = await readDriftEvidence(engine, sourceId, slug, assessmentAt);+ if (evidence.newer === 'database' && evidence.differs !== 'none') {+ if (!opts.slugs?.length) { count('kept_newer_page'); listing.push({ item: `${sourceId}:${slug}`, class: 'kept_newer_page', detail: newerPageParagraph(sourceId, slug, evidence) }); continue; }+ newerPages.push(`${slug}: ${newerPageParagraph(sourceId, slug, evidence).replace('it stays held for a person', '--prefer file named for it drops that edit')}`);+ }+ }const page = await prepareDriftPage(engine, sourceId, slug, opts.prefer, assessmentAt);if (classes.has(slug)) page.class = classes.get(slug);pages.push(page);@@ -869,6 +938,7 @@ 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}`] : [];+ if (newerPages.length) warnings.unshift(`The apply drops a database edit newer than its file for ${newerPages.length} page(s): ${newerPages.join(' ')}`);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;diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex a3fdf414c5..9a360524bf 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -419,6 +419,7 @@ describe('#7619 split rules', () => {'src/core/persistence/topology-filesystem.ts': 'git child argv','src/core/persistence/worktree-refresh.ts': 'git child argv','src/core/reason-trailers.ts': 'git child argv (the reason scan and its notice fix)',+ 'src/core/repair/file-drift-compare.ts': 'git child argv','src/core/skillpack/bundle.ts': 'git child argv','src/core/skillpack/tarball.ts': 'tar child argv','src/core/source-health.ts': 'git child argv',diff --git a/test/file-drift-normalisation-gst2568.test.ts b/test/file-drift-normalisation-gst2568.test.tsnew file mode 100644index 0000000000..aab6c7eb5b--- /dev/null+++ b/test/file-drift-normalisation-gst2568.test.ts@@ -0,0 +1,215 @@+/**+ * GST-2568: `file_drift` holds raised by gbrain's own frontmatter normalisation, and a repair preview that needs no winner.+ *+ * A schema-pack retype (schema-pack/retype.ts) rewrites `pages.type` and stamps `legacy_type` (and optionally `subtype`)+ * in the database only, never in the file. A page with no import record whose file still names the old type then read as+ * drift on every sync, though nothing but that stamp differed.+ *+ * Protects:+ * - item 1: a page that differs from its file only by a retype's stamp (`legacy_type`, `legacy_type` plus `subtype`) is no+ * drift: a commit to the file imports as a no-op, writes no page revision and no file; a database-only label still holds;+ * a file that names a new type imports it;+ * - item 2: such holds an older screen wrote release on the next sync with no content write and no commit, counted in+ * `holds_released`; a real difference is screened again and stays held;+ * - a later deliberate commit over a page that changed only by derived keys (a retype's stamp, a stored reserved key, the+ * grandfather `validate: false`) imports; a page whose body also changed in the database stays held;+ * - a live page whose file is gone under a gbrain.yml `db_only` folder or a `sync.exclude` path is no drift: no hold, an+ * existing hold releases, and the page stays;+ * - item 3: `repair file-drift --held` without `--prefer` compares each hold (what differs, which side is newer, what a+ * repair would do) and writes nothing; an apply without `--prefer` refuses with a `fix` naming that comparison;+ * - item 4: `--prefer file` never drops a page edited after its file's last commit in bulk (`kept_newer_page`, the hold+ * stays), names the drop in a warning when one `--slug` asks for it, and the comparison never proposes deleting a page+ * whose file is gone.+ * PGLite always; Postgres too when DATABASE_URL is set. Holds exist only where sync imports a Git checkout, so there is no+ * repo-less arm.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { FILE_DRIFT_VERSION, writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { resolveRepairScope, type RepairPlanOptions } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const logger = { info() {}, warn() {}, error() {} };+const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const doc = (type: string, title: string, body: string, extra = '') => `---\ntype: ${type}\ntitle: ${title}\n${extra}---\n\n${body}\n`;+const coordinated = (engine: BrainEngine, sql: string, params: unknown[] = []) =>+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; meta: { side?: string; drift_version?: number } } }>(+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code} ${r.meta.side ?? ''}`.trim());+const row = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ type: string; frontmatter: Record<string, unknown>; body: string; revision: string; deleted: boolean }>(+ "SELECT type, frontmatter, compiled_truth AS body, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!;++/** Pages as an older gbrain left them: no import record, and a revision no import or write request produced. */+async function legacy(engine: BrainEngine, slugs?: string[]): Promise<void> {+ await coordinated(engine, "DELETE FROM op_checkpoints WHERE op='sync-import-provenance'");+ await coordinated(engine, `UPDATE pages SET knowledge_revision=gen_random_uuid(), revision_write_request_id=NULL WHERE source_id='default'${slugs ? ' AND slug=ANY($1::text[])' : ''}`, slugs ? [slugs] : []);+}+/** What retype.ts's apply writes for a rule from `from` to `to`: the type column and the stamp, in the database only. */+const retype = (engine: BrainEngine, slug: string, from: string, to: string, subtype?: string) => coordinated(engine,+ `UPDATE pages SET type=$2, frontmatter = frontmatter || jsonb_build_object('legacy_type', $3::text) || $4::text::jsonb WHERE source_id='default' AND slug=$1`,+ [slug, to, from, JSON.stringify(subtype ? { subtype } : {})]);+/** The `file_drift` hold an older screen wrote for a page, at its current revision. */+async function seedHold(engine: BrainEngine, slug: string, meta: Record<string, unknown>): Promise<void> {+ const [page] = await engine.executeRaw<{ id: string; revision: string; incarnation: string }>(`SELECT p.id::text AS id, p.knowledge_revision::text AS revision,+ s.incarnation::text AS incarnation FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id='default' AND p.slug=$1`, [slug]);+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: page!.incarnation, path: `${slug}.md`, source_path: `${slug}.md`, slug,+ page_id: Number(page!.id), code: 'file_drift', message: `${slug}.md is held: file drift`, upstream_version: null, observed_at: new Date().toISOString(),+ run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION, page_revision: page!.revision, ...meta } as never }));+}+async function repair(engine: BrainEngine, opts: Partial<RepairPlanOptions> & { expect?: string }) {+ return withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),+ { explicit: true, sourceFlag: 'default', ...opts } as never));+}+type Plan = { listing?: Array<{ item: string; class: string; detail?: string }>; preview_hash?: string; warnings?: string[]; outcomes?: Record<string, number>; details?: Record<string, any> };+const classes = (plan: unknown) => Object.fromEntries(((plan as Plan).listing ?? []).map(entry => [entry.item.replace('default:', ''), entry.class]));++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const files = (root: string, entries: Record<string, string>) => {+ for (const [slug, content] of Object.entries(entries)) { mkdirSync(join(root, slug, '..'), { recursive: true }); writeFileSync(join(root, `${slug}.md`), content); }+ };+ const setupWith = (entries: Record<string, string>) => ({ root }: { root: string }) => { git(root, 'init', '-q'); files(root, entries); commitAll(root, 'pages'); };++ test(`GST-2568 item 1 [${backend}]: a page that differs from its file only by a retype's stamp is no drift; a database label still holds`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await retype(engine, 'notes/alpha', 'civic', 'note');+ await retype(engine, 'notes/beta', 'civic', 'note', 'ward');+ await retype(engine, 'notes/delta', 'civic', 'note');+ await coordinated(engine, "UPDATE pages SET frontmatter = frontmatter || '{\"label\": \"x\"}'::jsonb WHERE source_id='default' AND slug='notes/gamma'");+ await legacy(engine);+ const before = { alpha: (await row(engine, 'notes/alpha')).revision, beta: (await row(engine, 'notes/beta')).revision };+ // A commit that only quotes the title touches every file; delta's also names a new type.+ for (const slug of ['notes/alpha', 'notes/beta', 'notes/gamma']) files(root, { [slug]: doc('civic', `'${slug}'`, `Body of ${slug}.`) });+ files(root, { 'notes/delta': doc('event', `'notes/delta'`, 'Body of notes/delta.') });+ commitAll(root, 'quote titles');+ const head = git(root, 'rev-parse', 'HEAD');+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual(['notes/gamma.md file_drift unknown']);+ const alpha = await row(engine, 'notes/alpha'), beta = await row(engine, 'notes/beta'), delta = await row(engine, 'notes/delta');+ expect([alpha.type, alpha.frontmatter, alpha.revision]).toEqual(['note', { legacy_type: 'civic' }, before.alpha]);+ expect([beta.type, beta.frontmatter, beta.revision]).toEqual(['note', { legacy_type: 'civic', subtype: 'ward' }, before.beta]);+ expect([delta.type, delta.frontmatter.legacy_type]).toEqual(['event', undefined]);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(root, 'status', '--porcelain')).toBe('');+ }, { databaseUrl, setup: setupWith(Object.fromEntries(['alpha', 'beta', 'gamma', 'delta'].map(name => [`notes/${name}`, doc('civic', `notes/${name}`, `Body of notes/${name}.`)]))) }), 180_000);++ test(`GST-2568 item 2 [${backend}]: existing normalisation-only holds release on the next sync, counted, with no write and no commit`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await retype(engine, 'notes/alpha', 'civic', 'note');+ await retype(engine, 'notes/beta', 'civic', 'note', 'ward');+ await coordinated(engine, "UPDATE pages SET frontmatter = frontmatter || '{\"label\": \"x\"}'::jsonb WHERE source_id='default' AND slug='notes/gamma'");+ await legacy(engine);+ for (const slug of ['notes/alpha', 'notes/beta', 'notes/gamma']) await seedHold(engine, slug, { sides: 'unknown', side: 'unknown', drift_version: 2 });+ const revisions = async () => (await engine.executeRaw<{ r: string }>("SELECT string_agg(knowledge_revision::text, ',' ORDER BY slug) AS r FROM pages WHERE source_id='default'"))[0]!.r;+ const [before, head] = [await revisions(), git(root, 'rev-parse', 'HEAD')];+ const result = await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual(['notes/gamma.md file_drift unknown']);+ expect(result.holds_released).toBe(2);+ const [gamma] = await engine.executeRaw<{ v: number }>("SELECT (completed_keys->0->'meta'->>'drift_version')::int AS v FROM op_checkpoints WHERE op='sync-hold'");+ expect(gamma!.v).toBe(FILE_DRIFT_VERSION);+ expect(await revisions()).toBe(before);+ expect([git(root, 'rev-parse', 'HEAD'), git(root, 'status', '--porcelain')]).toEqual([head, '']);+ expect((await performManagedSync(engine, OPTS)).holds_released).toBeUndefined();+ }, { databaseUrl, setup: setupWith(Object.fromEntries(['alpha', 'beta', 'gamma'].map(name => [`notes/${name}`, doc('civic', `notes/${name}`, `Body of notes/${name}.`)]))) }), 180_000);++ test(`GST-2568 [${backend}]: a later commit over a page that changed only by derived keys imports; a page edited in the database too stays held`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await retype(engine, 'notes/retyped', 'civic', 'note');+ // Older imports kept a copy of the reserved `type` key, and the v0.13.1 grandfather stamped `validate: false` in the database only.+ await coordinated(engine, "UPDATE pages SET frontmatter = frontmatter || '{\"type\": \"concept\", \"validate\": false}'::jsonb WHERE source_id='default' AND slug IN ('notes/job','notes/both')");+ await coordinated(engine, "UPDATE pages SET compiled_truth='A database edit of notes/both.' WHERE source_id='default' AND slug='notes/both'");+ await legacy(engine);+ files(root, { 'notes/retyped': doc('civic', 'notes/retyped', 'See [the new link](notes/target).'),+ 'notes/job': doc('concept', 'notes/job', 'A body an external job rewrote.', 'source_kind: external-job\nsynced_at: run-1\n'),+ 'notes/both': doc('concept', 'notes/both', 'A body an external job rewrote.', 'source_kind: external-job\n') });+ commitAll(root, 'rewrite links and sync the job');+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual(['notes/both.md file_drift unknown']);+ const retyped = await row(engine, 'notes/retyped'), job = await row(engine, 'notes/job');+ expect([retyped.type, retyped.frontmatter, retyped.body]).toEqual(['note', { legacy_type: 'civic' }, 'See [the new link](notes/target).']);+ expect([job.body, job.frontmatter.source_kind, job.frontmatter.validate]).toEqual(['A body an external job rewrote.', 'external-job', false]);+ expect((await row(engine, 'notes/both')).body).toBe('A database edit of notes/both.');+ }, { databaseUrl, setup: setupWith({ 'notes/retyped': doc('civic', 'notes/retyped', 'See [the old link](notes/old).'),+ 'notes/job': doc('concept', 'notes/job', 'The first body.'), 'notes/both': doc('concept', 'notes/both', 'The first body.') }) }), 180_000);++ test(`GST-2568 [${backend}]: a live page whose file is gone under a db_only folder or a sync.exclude path is no drift`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await engine.setConfig('sync.exclude', 'excluded/');+ await legacy(engine);+ rmSync(join(root, 'private/kept.md')); rmSync(join(root, 'excluded/kept.md'));+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - private/\n');+ commitAll(root, 'move private pages to the database');+ // The holds an older gbrain wrote for these pages before the folders were declared.+ for (const slug of ['private/kept', 'excluded/kept']) await seedHold(engine, slug, { side: 'deleted', state: 'file_gone' });+ const result = await performManagedSync(engine, OPTS);+ expect([await holds(engine), result.holds_released]).toEqual([[], 2]);+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual([]);+ for (const slug of ['private/kept', 'excluded/kept']) expect((await row(engine, slug)).deleted).toBe(false);+ }, { databaseUrl, setup: setupWith({ 'private/kept': doc('concept', 'private/kept', 'A private body.'), 'excluded/kept': doc('concept', 'excluded/kept', 'An excluded body.') }) }), 180_000);++ /** Four held pages: same (a retype's stamp only), newer-file, newer-page (each differs in body), gone (its file left Git). */+ async function heldPages(engine: BrainEngine, root: string): Promise<void> {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await retype(engine, 'notes/same', 'civic', 'note');+ // newer-file: the database body changed two hours ago, then a commit changed the file; newer-page: the database changed after the last commit.+ await coordinated(engine, "UPDATE pages SET compiled_truth='An old database body.', updated_at=now() - interval '2 hours' WHERE source_id='default' AND slug='notes/newer-file'");+ files(root, { 'notes/newer-file': doc('civic', 'notes/newer-file', 'A newer file body.') });+ git(root, 'rm', '-q', '--', 'notes/gone.md');+ commitAll(root, 'edit and remove');+ await coordinated(engine, "UPDATE pages SET compiled_truth='A newer database body.', updated_at=now() + interval '1 minute' WHERE source_id='default' AND slug='notes/newer-page'");+ await legacy(engine);+ for (const slug of ['notes/same', 'notes/newer-file', 'notes/newer-page']) await seedHold(engine, slug, { sides: 'unknown', side: 'unknown', drift_version: FILE_DRIFT_VERSION });+ await seedHold(engine, 'notes/gone', { side: 'deleted', state: 'file_gone' });+ }+ const heldSetup = setupWith(Object.fromEntries(['same', 'newer-file', 'newer-page', 'gone'].map(name => [`notes/${name}`, doc('civic', `notes/${name}`, `The committed body of notes/${name}.`)])));++ test(`GST-2568 item 3 [${backend}]: the held comparison needs no winner, names each page's newer side and writes nothing`, () => managedBrain(async ({ engine, root }) => {+ await heldPages(engine, root);+ const state = async () => JSON.stringify(await engine.executeRaw("SELECT op, fingerprint, completed_keys FROM op_checkpoints WHERE op NOT LIKE '%writer%' ORDER BY op, fingerprint"))+ + JSON.stringify(await engine.executeRaw("SELECT slug, knowledge_revision FROM pages ORDER BY slug"));+ const before = await state();+ const compared = await repair(engine, { held: true }) as Plan;+ expect(classes(compared)).toEqual({ 'notes/gone': 'needs_human', 'notes/newer-file': 'prefer_file', 'notes/newer-page': 'needs_human', 'notes/same': 'release_hold' });+ const pages = Object.fromEntries((compared.details!.pages as Array<{ slug: string; evidence?: { differs: string; newer: string } }>).map(page => [page.slug, page.evidence]));+ expect([pages['notes/newer-file'], pages['notes/newer-page']].map(found => [found!.differs, found!.newer])).toEqual([['body', 'file'], ['body', 'database']]);+ expect(compared.preview_hash).toBeUndefined();+ expect(compared.listing!.find(entry => entry.item === 'default:notes/gone')!.detail).toContain('would delete the page');+ expect(await state()).toBe(before);+ // An apply still names a winner; its refusal carries the comparison as its fix.+ const refusal = await repair(engine, { held: true, expect: 'abc' }).then(() => null, error => error as OperationError);+ expect(refusal?.code).toBe('invalid_params');+ expect(refusal?.fix?.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'default', '--held', '--json']);+ }, { databaseUrl, setup: heldSetup }), 240_000);++ test(`GST-2568 item 4 [${backend}]: --prefer file never drops a page edited after its file's last commit in bulk, and says so for one --slug`, () => managedBrain(async ({ engine, root }) => {+ await heldPages(engine, root);+ // --prefer file in bulk keeps the newer page held; the file-newer page imports its file.+ const bulk = await repair(engine, { held: true, side: 'unknown', prefer: 'file' }) as Plan;+ expect(classes(bulk)['notes/newer-page']).toBe('kept_newer_page');+ expect(classes(bulk)['notes/newer-file']).toBe('prefer_file');+ expect((await repair(engine, { held: true, side: 'unknown', prefer: 'file', expect: bulk.preview_hash! }) as Plan).outcomes?.repaired).toBeGreaterThanOrEqual(1);+ expect((await row(engine, 'notes/newer-file')).body).toBe('A newer file body.');+ expect((await row(engine, 'notes/newer-page')).body).toBe('A newer database body.');+ expect(await holds(engine)).toContain('notes/newer-page.md file_drift unknown');+ // One --slug may still ask for it, and the preview says what it drops.+ const single = await repair(engine, { slugs: ['notes/newer-page'], prefer: 'file' }) as Plan;+ expect(classes(single)['notes/newer-page']).toBe('prefer_file');+ expect(single.warnings?.join(' ')).toContain('drops a database edit newer than its file');+ }, { databaseUrl, setup: heldSetup }), 240_000);+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 8844966e9f..2c6e1d2de2 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -122,6 +122,7 @@ test/fence-fact-append.test.tstest/fence-first-generation-8819.test.tstest/fence-repair-receipts.test.tstest/fenced-embed-reuse-6961.test.ts+test/file-drift-normalisation-gst2568.test.tstest/file-drift-soft-delete-hold-release-gbra133.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tsdiff --git a/test/repair-file-drift-options-8615.test.ts b/test/repair-file-drift-options-8615.test.tsindex bc53553e50..6f54f96d6d 100644--- a/test/repair-file-drift-options-8615.test.ts+++ b/test/repair-file-drift-options-8615.test.ts@@ -1,7 +1,8 @@/*** #8615: `gbrain repair file-drift` with a held-selection option (--held, --side, --state, --cursor, --provenance) and no- * --prefer is refused with the usage line instead of silently running the all-drifted survey, which counts a different- * set of pages (drift conflicts, not held files) with nothing saying the options were ignored.+ * --prefer never silently runs the all-drifted survey, which counts a different set of pages (drift conflicts, not held+ * files) with nothing saying the options were ignored. GST-2568: a valid held selection without --prefer compares the+ * selected holds and writes nothing; a narrowing option without --held is still refused.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { OperationError } from '../src/core/ops/contract.ts';@@ -23,21 +24,16 @@ afterAll(async () => {const scope = { brain_id: 'host', source_ids: ['source-a'] };-test('held-selection options without --prefer are refused, never surveyed', async () => {- const selections = [- { held: true, side: 'deleted' },- { held: true },- { side: 'deleted' },- { state: 'file_gone' },- { cursor: 'next' },- { provenance: 'never_committed' },- ];- for (const selection of selections) {+test('held-selection options without --prefer compare the held selection or are refused, never surveyed', async () => {+ for (const selection of [{ held: true, side: 'deleted' }, { held: true }]) {+ const plan = await fileDriftRepair.plan(engine, scope, null, { apply: false, remote: false, ...selection });+ expect([plan.items, plan.details?.compare, plan.details?.writes, plan.details?.window]).toEqual([[], true, 'none', { previewed: 0, remaining: 0, complete: true }]);+ }+ for (const selection of [{ side: 'deleted' }, { state: 'file_gone' }, { cursor: 'next' }, { provenance: 'never_committed' }]) {const outcome = await fileDriftRepair.plan(engine, scope, null, { apply: false, remote: false, ...selection }).then(plan => ({ selection, surveyed: plan.listing }), (error: unknown) => error);expect(outcome).toBeInstanceOf(OperationError);- expect((outcome as OperationError).code).toBe('invalid_params');- expect((outcome as OperationError).message).toBe('gbrain repair file-drift needs --prefer file or --prefer database.');+ expect([(outcome as OperationError).code, (outcome as OperationError).message]).toEqual(['invalid_params', 'Select pages one way: --slug, --request, --all-drifted or --held.']);}});