Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6643 PR B: conflict audit, maintenance drift refusal, repair file-drift, doctor maintenance_write_drift
garrytana1ffa3a1d125
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 322c7a9c7f..a27b7b1c19 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Pages whose writes keep refusing `source_changed` can now be listed, resolved and measured, and maintenance stops adding to the pile (#6643).** A page whose canonical file differs from its database copy refuses every coordinated write with `source_changed` (`file_database_drift`) until someone reconciles it. Nothing listed those pages, nothing resolved them in bulk, and `synthesize_concepts` paid for a new narrative for each drifted concept on every cycle and left another conflict receipt each time. Now the audit groups the receipts by page, maintenance checks the file before it spends or admits anything, `gbrain repair file-drift` resolves the pages through canonical reconciliation, and doctor counts what is left.++### Itemized changes++- `gbrain sources reconcile <source> --audit --conflicts [--window <n>]` (read-only) lists conflict receipts grouped by slug: receipt and drift-receipt counts, first and last seen, producers, the last committed write, whether the file still differs (checked live on the canonical owner host), the source path, git tracked/committed state and the drift class. It reads a bounded window of request sequences (100,000 by default, at most 1,000,000), paginates by slug and says whether the window covered all history.+- MCP `list_write_conflicts` (read scope) returns the database-derived part of the same audit to remote callers, filtered by source grant, slug fence and page visibility in the SQL that counts. No paths, hashes, revisions or live checks leave the host.+- `synthesize_concepts` skips a drifted concept before any provider call or admission, on every cycle, records the skip in `dream.concepts.drift_skips` (a separate key from the retry bound) and releases it when the file and database agree. The phase reports `warn` with `skipped_file_drift` and the commands to run.+- A prepared maintenance write to a drifted page refuses `source_changed` / `file_database_drift` before admission, without a request row. A replay of an earlier request id still returns its receipt.+- `gbrain repair file-drift --source <id> (--slug <s>... | --request <id>... | --all-drifted [--class <name>]) --prefer file|database` is explicit-only and preview-bound. The preferred side wins inside reconcile's protections (protected metadata, the tag union, protected takes and private fact rows), and each page's preview lists its `exceptions`. `--all-drifted` refuses a selection that mixes drift classes unless `--class` keeps one. `--apply --expect <hash>` applies exactly the previewed set under derived request ids, resumes an interrupted apply, and reports `repaired`, `refused` or `changed_since_preview` per page.+- Doctor `maintenance_write_drift` (ops) counts drifted pages behind the newest 20,000 request sequences and the recorded concept skips, and names the audit and the repair preview.+- Docs: [file drift](docs/guides/repair.md#file-drift), the troubleshooting row and [maintenance write drift](docs/guides/troubleshooting.md#maintenance-write-drift), and `list_write_conflicts` in the MCP tool reference.+## [0.60.212.0] - 2026-10-13**CI test shards are packed from fresh timings again.** CI splits each test lane across several machines using the recorded run time of every test file. Test files added since the last refresh had no recorded time, so shards were packed from guesses for them. This release re-measures all three lanes from green master runs. No product behaviour changes.diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex cb8439c80f..f22f6a86b6 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -4,7 +4,7 @@<!-- Regenerate: bun run scripts/generate-tool-catalog.ts --><!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->-Every non-localOnly operation on the MCP surface: 149 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.+Every non-localOnly operation on the MCP surface: 150 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.## admin@@ -179,6 +179,7 @@ Every non-localOnly operation on the MCP surface: 149 tools across 25 areas. **S| `get_write_request` | Your write's receipt by request_id (after write_pending or a lost reply). | write | yes | || `list_page_purges` | Owner-only (`gbrain pages purges list`). | admin | | || `list_pages` | List pages with filters. | read | yes | |+| `list_write_conflicts` | Pages whose writes keep ending in a source_changed conflict, grouped by slug. | read | | || `list_write_requests` | Your write receipts in one source, newest first (for a lost request_id). | write | yes | || `put_page` | Complete content REPLACES the whole page: read get_page include_content:true; send its revision as expected_revision. | write | yes | || `put_pages` | Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. | write | | |diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 7878db72e7..48a04975f1 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -17,3 +17,5 @@- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesSql` (the paged same-name query, 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain sync --source <id> --no-pull --full` that imports the kept file into the survivor), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.+- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).+- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 9097f22910..db05270cb9 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -141,6 +141,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `orphan-children` | `child_table_orphans` (also a `storage_corrupt` error) | Explicit-only. Deletes rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page row no longer exists, and clears dangling `links.origin_page_id` and `files.page_id` references, each in one statement that rechecks the orphan condition. See [orphan children](#orphan-children). | `torn_pages`: page rows whose stored body cannot be read (torn TOAST). The preview names them; the repair never changes them. || `planner-stats` | `planner_stats_stale` | Runs `ANALYZE` on the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale, so search and graph reads stop planning as slow nested loops. PGLite also resets each table's pending row count; Postgres runs each `ANALYZE` with a 60 s statement timeout and a 2 s lock timeout. No journal admission, no user data changes, brain-wide. | none || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |+| `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -870,6 +871,65 @@ request). Attribution names the original writer. A replay thebrain refuses reports `refused` with the code. The failed receipts stay ashistory.+<a id="file-drift"></a>+### File drift++A page whose canonical file differs from its database copy refuses every+coordinated write with `source_changed` (detail `file_database_drift`) until+someone resolves it. Before #6643 nothing resolved them in bulk, and+`synthesize_concepts` paid for a new narrative for each drifted concept on+every cycle, then left another conflict receipt behind. Now maintenance checks+the file before it spends or admits anything: a drifted concept is skipped+(recorded in `dream.concepts.drift_skips`, released once the file and database+agree), and a maintenance write to a drifted page refuses before admission+without a request row. Doctor's `maintenance_write_drift` counts the drifted+pages and the skips.++`gbrain repair file-drift` resolves them through the same canonical+reconciliation as `gbrain sources reconcile`, preferring one side. It is+explicit-only, preview-bound and runs only from the trusted local CLI on the+canonical owner host.++**Say to your agent:** *"List the pages whose writes keep refusing+source_changed, preview resolving them with the file winning, show me the+exceptions, then apply after I agree."*++```bash+gbrain sources reconcile <id> --brain host --audit --conflicts # read-only: receipts per slug, still drifted?, class+gbrain repair file-drift --source <id> --slug notes/a --prefer file # preview one page+gbrain repair file-drift --source <id> --all-drifted --class structurally_additive --prefer file+gbrain repair file-drift --source <id> --all-drifted --class structurally_additive --prefer file --apply --expect <hash>+```++Select pages with `--slug` (repeatable), `--request <id>` (a conflict receipt,+repeatable) or `--all-drifted` (every page the conflict audit still finds+drifted, up to 1,000). `--prefer file` takes the canonical file, `--prefer+database` the database copy. The preferred side wins the title, type, body,+timeline and ordinary frontmatter (a key only the other side has is dropped)+inside reconcile's existing protections: protected metadata (provenance,+trust, source and scan fields) stays as the database holds it, tags are the+union of both sides, and protected takes and private fact rows are kept as+stored. Each page's preview lists `exceptions`, the places where the result+differs from the preferred side and why (`protected_metadata`, `scan_state`,+`tags_union`, `protected_takes_or_private_facts`).++The audit gives every drifted page one class: `structurally_additive`,+`additive_with_suggestions`, `review_required`, `formatting_only` or `error`.+`--all-drifted` refuses a selection that mixes classes (the message counts+each one) unless `--class <name>` keeps exactly one, so a single `--prefer`+never resolves differently shaped drift in bulk. Review `review_required`+pages one at a time with `--slug`.++The preview writes each page's resolved result to a private artifact under+the gbrain config directory (`repair-previews/file-drift/<hash>.json`,+outside every checkout) and prints the hash. `--apply --expect <hash>`+applies exactly that set through the reconcile apply, with its preimage+checks and retained backups, under request ids derived from the hash, so an+interrupted apply resumes and never writes a page twice. Each page reports+`repaired`, `refused` (with the code) or `changed_since_preview` (the file or+the page changed after the preview; preview again). A changed set refuses+with `preview_changed`.+<a id="held-files"></a>### Held files@@ -1847,7 +1907,7 @@ Each heading below is the `docs` anchor a refusal carries.### Explicit-only repair kinds`google-file-modes`, `stale-atoms`, `extractor-facts`, `captured-facts`,-`loop-facts` and `ontology-facts` run only when named: `gbrain repair <kind>` previews, and+`loop-facts`, `ontology-facts` and `file-drift` run only when named: `gbrain repair <kind>` previews, and`gbrain repair <kind> --apply` applies (every kind but `google-file-modes`also needs `--expect <hash>`, so it applies exactly the previewed set; `google-file-modes` re-checks each file's owner,type and mode at apply time). They are excluded everywhere else:diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 0055588806..dd1107c3e1 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -61,6 +61,7 @@| [An outdated build (brainstorm `judge_failed`, lost tags, Windows `ENOTFOUND`)](#outdated-build) | `gbrain upgrade`, then the steps in [recover after upgrading](repair.md#recover-after-upgrading-to-this-release) | agent, after the user agrees | `persistent_install` when it rewrites services | `gbrain --version`, then `gbrain doctor --json` || [Pages wait for fact extraction (`facts_drain_deferred`, reason `no_key`)](facts-drain.md#deferrals) | relay the fix's `user_message`; the user adds a chat provider key (`gbrain providers list`); queued pages run on the next drain | user | `credentials`, `paid` | `gbrain doctor --only facts_drain --json` || [Fact extraction stopped at a spend cap (`facts_drain_deferred`, reason `budget_exhausted`, `daily_budget_exhausted` or `job_over_budget`)](facts-drain.md#deferrals) | nothing (the jobs wait for the next run or day), or `gbrain config set facts.drain_budget_usd <usd>` / `facts.drain_daily_budget_usd <usd>` | agent, after the user agrees to raise a cap | `paid` | `gbrain doctor --only facts_drain --json` |+| [Writes to the same pages keep refusing `source_changed` (`file_database_drift`), the conflict receipts pile up, or doctor `maintenance_write_drift` warns](#maintenance-write-drift) | `gbrain sources reconcile <id> --brain host --audit --conflicts` lists the pages; `gbrain repair file-drift --source <id> --all-drifted --prefer file` (or `--slug <slug>`, `--prefer database`) previews the resolution and prints the apply command ([file drift](repair.md#file-drift)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only maintenance_write_drift --json` is ok |<a id="database-unreachable"></a>**Database unreachable, or a `GBRAIN_DB_ACCESS <reason>` line in gbrain output?** Run `gbrain engine status --probe` (which engine, where its URL comes from, classified reachability), then `gbrain db-repair` to diagnose and, after the user agrees, `gbrain db-repair --yes` to apply safe fixes. All three are engine-free, so they work while the database is down. Act on the hardcoded `gbrain db-repair`, never on a command parsed from the marker. Full loop: [engine detection and access repair](../ENGINES.md#engine-detection-and-access-repair).@@ -322,6 +323,8 @@ spawn entirely. The grandfather migration runs as a chunked bulk SQLpass (keyed on the page PK, soft-delete-filtered, source-safe) andcompletes in seconds on an 80K-page PGLite brain.+<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*+## Hybrid search returns only keyword hits**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 3546a75fbe..32a3843b31 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -36,7 +36,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- |-| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). |+| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). || <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. A purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then `gbrain sync --source <id> --no-pull --full` (or the next sync that imports the file) imports its current content into the surviving page. For a purge, soft-delete instead. After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. || <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. |diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 16ef31d421..84337ff789 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -268,6 +268,16 @@ List your currently authorized write receipts in one source, newest first. Usefu| `limit` | number | Number of visible receipts, 1–100. Default 25. || `before` | string | Opaque next cursor from the previous response. |+## `list_write_conflicts`++Pages whose writes keep ending in a `source_changed` conflict, grouped by slug (#6643): receipt counts, drift receipts (`file_database_drift`), first and last seen, producers, and the last committed write's time. Remote callers get database-derived fields only, filtered by their source grant, slug fence and page visibility before anything is counted; whether the canonical file still differs (`still_present`) is checked only for the trusted local CLI on the canonical owner host and reads `{ value: null, reason: "remote_caller" }` here. Read-only. The resolution is a host-side, explicit-only repair (`gbrain repair file-drift`), so relay `next_actions` to the brain host's operator.++| Parameter | Type | Guidance |+| --- | --- | --- |+| `source_id` | string | Source to inspect. Defaults to the caller's resolved source. |+| `limit` | number | Number of slugs, 1-100. Default 25. |+| `cursor` | string | The previous response's `next`. |+## `put_page`Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences. For remote writes, `[[wikilinks]]` and markdown links in the body that point at pages already in the same source become plain `mentions` links after the commit (a journaled `links` effect; the receipt's `auto_links.mention_links` says it is queued; `mcp.remote_auto_links false` turns it off). Typed and frontmatter links are skipped for untrusted writes: a stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Pass `wait_ms` (up to 30000) to hold the reply until the commit instead of polling get_write_request. For more than 3 pages, use `put_pages` (full surface). Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG. A write the content-quality gate quarantined still commits but reports `quarantined: { reason, detail }` with a `page_quarantined` safety notice (put_pages marks each such page and emits one notice).diff --git a/plugin/README.md b/plugin/README.mdindex 7885c19e57..044aedd0b8 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -8,7 +8,7 @@ addition/exclusion).## MCP surface note (read once)-The plugin's MCP server runs `gbrain serve --surface full` — 170+The plugin's MCP server runs `gbrain serve --surface full` — 171operations, the same surface every stdio registration gbrain writes pins.Every gbrain operation the bundled skills name is on it. A harness that capsits tool count can narrow this machine's plugin surface withdiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 8454fa3857..3f80e006a2 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -35,7 +35,7 @@ src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refasrc/core/cycle/extract-facts.ts runExtractFacts 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts; +1 #5575 I2 (L1a-taint): the run result sums the write-gate tally each page reconcile returnssrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 490 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts)+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift detailssrc/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/import-file.ts importFromContent 666 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDispositiondiff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 3cb102df2c..d7a24708cc 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -328,6 +328,7 @@ export const timelineHistoryEntry: DoctorEntry = {'loop_facts_drift','ontology_facts_fenced','stale_frontmatter_keys',+ 'maintenance_write_drift',],run: runTimelineHistory,};diff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.tsnew file mode 100644index 0000000000..c411f4bc14--- /dev/null+++ b/src/commands/doctor/checks/maintenance-drift.ts@@ -0,0 +1,62 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { auditConflictsCommand, FILE_DRIFT_MESSAGE, fileDriftRepairCommand, liveFileDrift, readDriftSkips } from '../../../core/persistence/drift-conflicts.ts';++/** Newest request sequences scanned for drift conflicts (one range read of the unique sequence index). */+const WINDOW = 20_000;+/** Distinct slugs checked live per source; the rest are reported as unchecked. */+const LIVE_LIMIT = 100;++/**+ * #6643 (B3): pages whose canonical file differs from the database right now,+ * found from the drift conflict receipts of the newest 20,000 request sequences+ * and checked live on the canonical owner host (at most 100 slugs per source),+ * plus the concept synthesis skips recorded in `dream.concepts.drift_skips`.+ * It measures the drift itself, not conflict-row growth: producers back off+ * before admission, so a drifted page stops adding receipts. Names the+ * read-only audit and the explicit-only `gbrain repair file-drift` preview.+ */+export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const docs = 'docs/guides/troubleshooting.md#maintenance-write-drift';+ try {+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');+ const floor = String(Math.max(0, Number(bounds?.top ?? 0) - WINDOW));+ const skips = await readDriftSkips(engine);+ const rows = [];+ for (const sourceId of sources) {+ const candidates = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r+ WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3+ ORDER BY r.slug LIMIT ${LIVE_LIMIT + 1}`, [sourceId, floor, FILE_DRIFT_MESSAGE]);+ const skipped = Object.keys(skips).filter(key => key.startsWith(`${sourceId}:`)).map(key => key.slice(sourceId.length + 1));+ const drifted = new Set<string>();+ let unknown = 0;+ for (const slug of [...new Set([...candidates.slice(0, LIVE_LIMIT).map(row => row.slug), ...skipped])].slice(0, LIVE_LIMIT)) {+ const live = await liveFileDrift(engine, sourceId, slug);+ if (live.still_present === true) drifted.add(slug);+ else if (live.still_present === null) unknown++;+ }+ if (drifted.size || skipped.length || unknown) rows.push({ source_id: sourceId, drifted: drifted.size, sample: [...drifted].slice(0, 5),+ concept_skips: skipped.length, unknown, unchecked: Math.max(0, candidates.length - LIVE_LIMIT) });+ }+ const count = rows.reduce((sum, row) => sum + row.drifted, 0);+ const skipCount = rows.reduce((sum, row) => sum + row.concept_skips, 0);+ const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs };+ if (!count && !skipCount) {+ const unknown = rows.reduce((sum, row) => sum + row.unknown, 0);+ return { name: 'maintenance_write_drift', status: 'ok', details,+ message: unknown ? `No page checked on this host has a canonical file that differs from the database; ${unknown} could not be checked here (run doctor on the canonical owner host).`+ : 'No page whose writes refuse source_changed still has a canonical file that differs from the database.' };+ }+ const first = rows.find(row => row.drifted || row.concept_skips)!.source_id;+ return { name: 'maintenance_write_drift', status: 'warn', details,+ message: `${count} page(s) have a canonical file that differs from the database, so every coordinated write to them refuses source_changed `+ + `(${rows.filter(row => row.drifted || row.concept_skips).map(row => `${row.source_id}: ${row.drifted} drifted, ${row.concept_skips} concept skip(s)`).join('; ')}). `+ + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.`,+ fix: agentFix(['gbrain', 'sources', 'reconcile', first, '--brain', 'host', '--audit', '--conflicts', '--json'],+ 'Read-only: lists the conflict receipts grouped by slug, whether each file still differs, its drift class and producer.', 'maintenance_write_drift', { docs }) };+ } catch (error) {+ return checkError('maintenance_write_drift', 'check file/database drift behind conflict receipts', error, { details: { count: 'unknown', docs } });+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex c1af746673..6e16c023b2 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -312,6 +312,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some pages store a parser-reserved frontmatter key (type, title, tags, slug) left by an older import; writes compare around it, the sweep is hygiene',run: async (engine, scope) => (await import('./checks/frontmatter-keys.ts')).staleFrontmatterKeysCheck(engine, scope.sourceIds),},+ {+ id: 'maintenance_write_drift', resolution: 'repair', registration: 'wave',+ hostOnly: 'The live file check reads the canonical checkout on the brain host; resolving drift is a host-side, explicit-only repair.',+ count: d => Number(d.count ?? 0) + Number(d.concept_skips ?? 0),+ impact: 'Some pages have a canonical file that differs from the database, so every coordinated write to them refuses source_changed until someone resolves them',+ run: async (engine, scope) => (await import('./checks/maintenance-drift.ts')).maintenanceWriteDriftCheck(engine, scope.sourceIds),+ },];/** A check that could not run reports unknown, never ok. */diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex eb2616abe7..3c6891ef51 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -63,6 +63,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--apply --expect <preview-hash> --yes] [--json]gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff][--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]+ gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>])+ --prefer file|database [--apply --expect <preview-hash>] [--json]${REPAIR_CONTENT_HELP}Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -88,7 +90,10 @@ Options:Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).--only <path>, --skip <path>frontmatter, fences, slug-conflicts, content: select source-relative files (repeatable); the hash covers the selection.- --slug <slug> fences: select a database page by slug (repeatable); the hash covers the selection.+ --slug <slug> fences, file-drift: select a database page by slug (repeatable); the hash covers the selection.+ --prefer file|database, --request <id>, --all-drifted, --class <name>+ file-drift: the side that wins; select conflict receipts by request id (repeatable), or every page+ still drifted (refused across mixed drift classes unless --class keeps one).--diff frontmatter, fences, slug-conflicts, content: print every per-file diff, not one sample per class or tier.--no-llm Kinds that may call a paid model (${llmKinds}) and the content lane: use only the free tiers;model-tier items stay held with llm_disabled.@@ -105,21 +110,22 @@ With no kind, previews every kind. Run it on the brain host.Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.`;-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm']);-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels'],- '--slug': ['fences'],+ '--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',- '--slug': 'notes/a', '--max-usd': '0.50' };+ '--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required' };/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;- noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[] }+ noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];+ allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -131,7 +137,8 @@ function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | und/** Strict parse: every flag is known, value flags carry a value, at most one kind. */export function parseRepairArgs(args: string[]): RepairArgs {- const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [] };+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],+ allDrifted: false, requests: [] };const used = new Set<string>();const positional: string[] = [];let maxUsdText: string | undefined;@@ -156,6 +163,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--diff') parsed.diff = true;else if (flag === '--yes') parsed.yes = true;else if (flag === '--no-llm') parsed.noLlm = true;+ else if (flag === '--all-drifted') parsed.allDrifted = true;else parsed.noEmbed = true;continue;}@@ -168,6 +176,13 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--skip') parsed.skip.push(value);else if (flag === '--slug') parsed.slugs.push(value);else if (flag === '--max-usd') { maxUsdText = value; maxUsdFlag = flag; }+ else if (flag === '--prefer') {+ if (value !== 'file' && value !== 'database') throw invalid('--prefer takes file or database.', 'Pass --prefer file (the canonical file wins) or --prefer database (the database copy wins).',+ ['gbrain', 'repair', 'file-drift', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);+ parsed.prefer = value;+ }+ else if (flag === '--request') parsed.requests.push(value);+ else if (flag === '--class') parsed.driftClass = value;else parsed.limit = value;}if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,@@ -245,7 +260,8 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }- const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText } = parseRepairArgs(args);+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,+ prefer, requests, allDrifted, driftClass } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');if (kind === CONTENT_LANE) {@@ -282,7 +298,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Profor (const k of kinds) {const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),- ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}) });+ ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass } : {}) });results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsindex 1471e49d13..bf782000dd 100644--- a/src/commands/source-reconcile.ts+++ b/src/commands/source-reconcile.ts@@ -29,6 +29,7 @@ export const RECONCILE_HELP = `Usage:gbrain sources reconcile <source> <slug> --brain <id> --apply <resolved-preview-file>--request-id <uuid> [--json]gbrain sources reconcile <source> --brain <id> --audit [--classify] [--limit <1-100>] [--after <slug>] [--json]+ gbrain sources reconcile <source> --brain <id> --audit --conflicts [--window <n>] [--limit <1-100>] [--after <cursor>] [--json]gbrain sources reconcile <source> <slug> --brain <id> --backups [--limit <1-100>] [--after <request-uuid>] [--json]gbrain sources reconcile <source> <slug> --brain <id> --remove-backup <exact-reference> [--json]@@ -65,6 +66,12 @@ many applies at once only queues them (commits coalesce); reconcile a large setfrom one client, one or two at a time.Audit is bounded and read-only; its cursor is not a sync checkpoint. --classifyadds each drifted page's structural classification and counts, never values.+--conflicts lists the source_changed conflict receipts grouped by slug instead+(what keeps refusing, which producer wrote it, the last committed request, and on+the owner host whether the file still differs and its drift class), scanning the+newest --window request sequences (default 100000, at most 1000000); --after takes+the previous page's next cursor and complete is true only when the window reached+the oldest receipt. Resolve the listed pages with gbrain repair file-drift.Backups persist until explicitly removed. Removal deletes that private history,not the page or immutable receipt, and refuses nonterminal/recovering requests.`;@@ -81,8 +88,8 @@ export interface ReconcileCliArgs {export function parseReconcileArgs(args: string[]): ReconcileCliArgs {const flags = new Map<string, string | true>();const positional: string[] = [];- const boolean = new Set(['--preview', '--audit', '--backups', '--json', '--auto-additive', '--accept-suggested', '--classify', '--adopt-slug-path']);- const values = new Set(['--brain', '--out', '--from', '--decisions', '--apply', '--request-id', '--limit', '--after', '--remove-backup']);+ const boolean = new Set(['--preview', '--audit', '--backups', '--json', '--auto-additive', '--accept-suggested', '--classify', '--adopt-slug-path', '--conflicts']);+ const values = new Set(['--brain', '--out', '--from', '--decisions', '--apply', '--request-id', '--limit', '--after', '--remove-backup', '--window']);for (let i = 0; i < args.length; i++) {const token = args[i];if (!token.startsWith('-')) { positional.push(token); continue; }@@ -95,7 +102,7 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {continue;}if (!values.has(flag)) throw opError('invalid_params', `Unknown reconciliation option: ${flag}.`,- 'Reconciliation accepts --brain, --preview, --adopt-slug-path, --out, --from, --decisions, --apply, --request-id, --audit, --backups, --remove-backup, --limit, --after and --json; the help in fix shows which forms combine.',+ 'Reconciliation accepts --brain, --preview, --adopt-slug-path, --out, --from, --decisions, --apply, --request-id, --audit, --conflicts, --window, --classify, --backups, --remove-backup, --limit, --after and --json; the help in fix shows which forms combine.',{ fix: readFix('Lists every reconciliation form and its options.', { argv: ['gbrain', 'sources', 'reconcile', '--help'] }) });const value = equal >= 0 ? token.slice(equal + 1) : args[++i];if (!value || value.startsWith('-') || value.includes('\0')) throw opError('invalid_params', `${flag} requires a value.`,@@ -136,6 +143,12 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {'Run the audit without --preview, --out, --from, --decisions, --auto-additive or --accept-suggested, then preview a page it lists in a separate command.');if (flags.has('--classify') && !audit) throw opError('invalid_params', '--classify is only valid with --audit.','Add --audit (with --source), or drop --classify.');+ if (flags.has('--conflicts') && !audit) throw opError('invalid_params', '--conflicts is only valid with --audit.',+ `Add --audit: gbrain sources reconcile ${source} --brain host --audit --conflicts.`);+ if (flags.has('--conflicts') && flags.has('--classify')) throw opError('invalid_params', '--conflicts and --classify are separate audits.',+ 'Run --audit --conflicts for the conflict receipts grouped by slug (it classifies pages whose file still differs), or --audit --classify for the page-by-page drift scan.');+ if (flags.has('--window') && !flags.has('--conflicts')) throw opError('invalid_params', '--window is only valid with --audit --conflicts.',+ 'Add --audit --conflicts, or drop --window.');if ((applying || backups || audit) && flags.has('--adopt-slug-path')) throw opError('invalid_params', '--adopt-slug-path only shapes a preview.','Use --adopt-slug-path with --preview; apply adopts the file the written preview pinned.');if ((applying || backups) && (flags.has('--auto-additive') || flags.has('--accept-suggested'))) throw opError('invalid_params', '--auto-additive and --accept-suggested only shape a preview.',@@ -164,6 +177,13 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {if (flags.has('--adopt-slug-path')) params.adopt_slug_path = true;if (flags.has('--accept-suggested')) params.accept_suggested = true;if (flags.has('--classify')) params.classify = true;+ if (flags.has('--conflicts')) params.conflicts = true;+ if (flags.has('--window')) {+ const window = Number(flags.get('--window'));+ if (!Number.isInteger(window) || window < 1 || window > 1_000_000) throw opError('invalid_params', 'The conflict window must be an integer from 1 to 1000000.',+ 'Pass --window as the number of newest request sequences to scan (default 100000), or omit it.');+ params.window = window;+ }if (flags.has('--limit')) {const limit = Number(flags.get('--limit'));if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw opError('invalid_params', 'Audit limit must be an integer from 1 to 100.',diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex af6a92d5ff..f01ae3d44b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -541,6 +541,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6574 (publication round trips). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.209.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },{ since: '0.60.209.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },+ // #6643 PR B (conflict pile). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.212.0', text: '`synthesize_concepts` now checks each concept page against its canonical file before it calls a model or admits a write. A concept whose file differs from the database (`file_database_drift`) is skipped on every cycle, recorded in `dream.concepts.drift_skips` and released once the file and database agree, and the phase reports `warn` naming `gbrain sources reconcile <source> --brain host --audit --conflicts` and `gbrain repair file-drift`. Before, it paid for a narrative per drifted concept every cycle and left another `source_changed` conflict receipt.' },+ { since: '0.60.212.0', text: 'A maintenance write (a dream-cycle page publication) to a page whose canonical file differs from the database now refuses `source_changed` with detail `file_database_drift` before admission and leaves no request row, instead of being admitted and ending as a conflict receipt. A replay of an earlier request with the same id still returns its receipt.' },+ { since: '0.60.212.0', text: 'Doctor has a new `maintenance_write_drift` check: it warns when pages behind recent `file_database_drift` conflict receipts (or recorded concept skips) still have a canonical file that differs from the database, and names the read-only `--audit --conflicts` listing and the explicit-only `gbrain repair file-drift` preview. New: `gbrain sources reconcile <source> --audit --conflicts`, MCP `list_write_conflicts` (read scope; database-derived fields only for remote callers) and `gbrain repair file-drift --prefer file|database`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex bd69138a31..7bcbeaebd0 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,14 +47,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--group', '--harness', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],- 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],+ 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],@@ -73,14 +73,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--full', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],+ 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--full', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -101,16 +101,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],- 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],+ 'repair': ['--all', '--all-drifted', '--apply', '--brain', '--class', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -124,11 +124,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 930e9d486e..8220096847 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -49,6 +49,7 @@ import {} from './concept-publication.ts';import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts';import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts';+import { ConceptDriftSkips } from '../persistence/drift-conflicts.ts';// Miss policy for the shared resolver (`priceFor`: operator overrides, the// claude-cli → Anthropic sibling, canonical rows): assume Sonnet-tier@@ -340,6 +341,8 @@ export async function runPhaseSynthesizeConcepts(const pricingFallbackModels = new Set<string>();const retries = await ConceptRetryBound.load(engine); // #6260: bounded paid retries per member hashconst skippedRetryBound: string[] = [];+ const driftSkips = await ConceptDriftSkips.load(engine, opts.sourceId ?? 'default', !!maintenance?.binding, !!opts.dryRun);+ const skippedFileDrift = driftSkips.skipped;for (const group of atomGroups) {const conceptSlug = `concepts/${group.conceptSlug}`;// A concept page this phase did not write belongs to a human (or another@@ -369,6 +372,8 @@ export async function runPhaseSynthesizeConcepts(skippedUnchanged.push(conceptSlug);continue;}+ // #6643 (B1): a drifted concept would only add a conflict receipt per publication; checked live before any spend.+ if (await driftSkips.skip(conceptSlug, existingSnapshot)) continue;// A page hashed by the pre-D-N3 formula (full atom bodies) whose inputs are// provably unchanged keeps its narrative: only the hash is rewritten, no spend.const grandfathered = realNarrative && existing?.frontmatter?.member_hash === hashOf(synthModel, group.atomBodies);@@ -575,6 +580,7 @@ export async function runPhaseSynthesizeConcepts(// survives only as the fallback for legacy unscoped callers. Receipt only// fires when concepts were actually written; rollup always fires so doctor// sees the phase ran.+ const driftActions = await driftSkips.finish();const warnings = budgetWarnings(budget.warning, budgetCapped, budgetCap);if (!opts.dryRun) await retries.save(engine);// Managed brains skip the receipt page (a legacy putPage), like extract_atoms;@@ -613,7 +619,7 @@ export async function runPhaseSynthesizeConcepts(return {phase: 'synthesize_concepts',- status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 ? 'warn' : 'ok',+ status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0 ? 'warn' : 'ok',duration_ms: 0,summary:`synthesize_concepts: ${conceptsWritten} concepts ` +@@ -627,7 +633,8 @@ export async function runPhaseSynthesizeConcepts((keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : '') +(skippedRetryBound.length > 0 ? ` (${skippedRetryBound.length} skipped after ${MAX_CONCEPT_ATTEMPTS} failed attempts on unchanged members)` : '') +(publicationDeferred.length > 0 ? ` (${publicationDeferred.length} publication(s) deferred: page changed, retried next run)` : '') +- (publicationHeld.length > 0 ? ` (${publicationHeld.length} publication(s) held: existing page needs import/repair)` : ''),+ (publicationHeld.length > 0 ? ` (${publicationHeld.length} publication(s) held: existing page needs import/repair)` : '') ++ (skippedFileDrift.length > 0 ? ` (${skippedFileDrift.length} skipped before synthesis: canonical file differs from the database; ${driftActions.join('; ')})` : ''),details: {concepts_written: conceptsWritten,tier_counts: tierCounts,@@ -643,6 +650,8 @@ export async function runPhaseSynthesizeConcepts(rehashed,kept_existing_narrative: keptExistingNarrative,skipped_retry_bound: skippedRetryBound,+ skipped_file_drift: skippedFileDrift,+ ...(driftActions.length ? { file_drift_next_actions: driftActions } : {}),folded_spellings: foldedSpellings,publication_deferred: publicationDeferred,publication_held: publicationHeld,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 9b03e6847b..ccacea956c 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -265,6 +265,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['persistence_write_stall','lost_caller_writes','stale_frontmatter_keys',+ 'maintenance_write_drift','managed_sync_not_moving','persistence_session_timeouts',// #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).diff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.tsindex 5b6cb57740..c8c333e5aa 100644--- a/src/core/eligibility/registry.ts+++ b/src/core/eligibility/registry.ts@@ -50,6 +50,7 @@ export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {sources_inspect: 'text_free', request_tools: 'text_free', connectors_status: 'text_free',get_active_schema_pack: 'text_free', list_schema_packs: 'text_free', schema_stats: 'text_free', schema_lint: 'text_free',schema_graph: 'text_free', schema_explain_type: 'text_free',+ list_write_conflicts: 'text_free',};/** The class an op resolves to; an unlisted read op is held to the strictest (`labeled`) rule. */diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.tsindex 7c51ce8d8b..4f5e648de8 100644--- a/src/core/operation-loaders.generated.ts+++ b/src/core/operation-loaders.generated.ts@@ -69,6 +69,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st"put_pages": [load_page_batch, "pageBatchOperations"],"get_write_request": [load_persistence, "persistenceOperations"],"list_write_requests": [load_persistence, "persistenceOperations"],+ "list_write_conflicts": [load_persistence, "persistenceOperations"],"cancel_write_request": [load_persistence, "persistenceOperations"],"search": [load_search, "searchOperations"],"query": [load_search, "searchOperations"],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex e1f3a5b73e..899ae59575 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -836,6 +836,33 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "write-requests"}},+ {+ "name": "list_write_conflicts",+ "idempotent": true,+ "outputRedaction": "no_stored_text",+ "description": "Pages whose writes keep ending in a source_changed conflict, grouped by slug.",+ "params": {+ "source_id": {+ "type": "string",+ "description": "Default: yours."+ },+ "limit": {+ "type": "number",+ "default": 25,+ "description": "1-100 slugs (default 25)."+ },+ "cursor": {+ "type": "string",+ "description": "Previous page's next."+ }+ },+ "scope": "read",+ "mutating": false,+ "area": "pages",+ "cliHints": {+ "name": "write-conflicts"+ }+ },{"name": "cancel_write_request","idempotent": true,diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 4d762d85e9..ce5cb8f5e1 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -2,7 +2,7 @@import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';import { invalidParam, readFix } from './op-fix.ts';import { isValidSourceId } from '../source-id.ts';-import { enforceBoundClientOpAllowList, enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam } from './context.ts';+import { enforceBoundClientOpAllowList, enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam, readPolicyOpts } from './context.ts';import { hasScope } from '../scope.ts';import { normalizeTokenScopes } from '../legacy-token-scope.ts';import { parseWriteRequestId } from '../persistence/preconditions.ts';@@ -186,6 +186,38 @@ export const persistenceOperations: Operation[] = [return { requests: await Promise.all(result.requests.map(row => publicReceipt(ctx, row, facts.get(row.id)))), next: result.next };},},+ {+ // #6643 (B0): the conflict pile grouped by slug. Database-derived fields only for remote callers, filtered by source grant, slug fence+ // and page visibility in the aggregating SQL; the live file check runs only for the trusted local CLI on the canonical owner host.+ name: 'list_write_conflicts',+ idempotent: true,+ outputRedaction: 'no_stored_text',+ description: 'Pages whose writes keep ending in a source_changed conflict, grouped by slug.',+ params: {+ source_id: { type: 'string', description: 'Default: yours.' },+ limit: { type: 'number', default: 25, description: '1-100 slugs (default 25).' },+ cursor: { type: 'string', description: "Previous page's next." },+ },+ scope: 'read', mutating: false, area: 'pages',+ cliHints: { name: 'write-conflicts' },+ handler: async (ctx, params) => {+ const sourceId = parseSourceIdParam(params.source_id ?? ctx.sourceId, 'list_write_conflicts') ?? 'default';+ const limit = params.limit ?? 25;+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParam(ctx, 'list_write_conflicts', 'limit', 'limit must be an integer from 1 to 100.', { example: 25 });+ if (params.cursor !== undefined && typeof params.cursor !== 'string') throw opError('invalid_params', 'Invalid conflict cursor.', "Pass `cursor` exactly as the previous response's `next` value.");+ const policy = await readPolicyOpts(ctx);+ const trusted = ctx.remote === false;+ const sourceIds = policy.sourceIds ?? (!trusted && policy.sourceId ? [policy.sourceId] : undefined);+ const subagent = ctx.viaSubagent !== true ? undefined : ctx.allowedSlugPrefixes?.length ? ctx.allowedSlugPrefixes+ : typeof ctx.subagentId === 'number' ? [`wiki/agents/${ctx.subagentId}/`] : [];+ const bound = ctx.auth?.boundSlugPrefixes?.map(normalizeSlugPrefix);+ // Both fences apply: a slug must sit under each confinement this caller carries.+ const slugPrefixes = bound && subagent ? intersectPrefixes(bound, subagent) : bound ?? subagent?.map(normalizeSlugPrefix);+ const { auditDriftConflicts } = await import('../persistence/drift-conflicts.ts');+ return auditDriftConflicts(ctx.engine, sourceId, { trusted, sourceIds, slugPrefixes, excludePrivate: policy.excludePrivate === true },+ { limit, cursor: params.cursor as string | undefined });+ },+ },{name: 'cancel_write_request',idempotent: true,diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.tsnew file mode 100644index 0000000000..675ee963e8--- /dev/null+++ b/src/core/persistence/drift-conflicts.ts@@ -0,0 +1,365 @@+/**+ * #6643: the `source_changed` conflict pile, made visible and kept from growing.+ *+ * A canonical file that diverged from its database row refuses every+ * coordinated write to it (`page-prepare.ts` `prepareFileTarget`, detail+ * `file_database_drift`) until someone reconciles it. Three readers share this+ * module:+ *+ * - the audit (`gbrain sources reconcile <source> --audit --conflicts`, MCP+ * `list_write_conflicts`): conflict receipts grouped by slug, read through a+ * bounded window of request sequences (the request table's unique sequence+ * index), paginated by slug with a completeness flag. Remote callers get+ * database-derived fields only, filtered by source grant, slug fence and page+ * visibility in the SQL that aggregates; the live file check runs only for a+ * trusted local caller on the source's canonical owner host;+ * - the maintenance producers (`prepared-maintenance.ts`, `synthesize_concepts`),+ * which check `liveFileDrift` before admission or spend; the concept phase+ * records each skip in `dream.concepts.drift_skips` with per-entry atomic+ * updates and releases it once the file and database agree again;+ * - doctor `maintenance_write_drift` and `gbrain repair file-drift`.+ */+import { readFileSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { normalizeSlugPrefix } from '../ops/context.ts';+import { resolveSourceLocalFilePath } from '../markdown.ts';+import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';+import { hardenedGitSync, hardenedPathDirty } from '../hardened-git.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { isValidSourceId } from '../source-id.ts';+import { validateSlug } from '../utils.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { sha256 } from './digest.ts';+import { existingLocalHostId } from './identity.ts';+import { getWorktreeBinding } from './ownership.ts';+import { prepareFileTarget } from './page-prepare.ts';+import { readReconcileState } from './reconcile-state.ts';+import { reconcileCanonical } from './reconcile-merge.ts';+import { classifyDrift } from './reconcile-additive.ts';++/** The refusal message `prepareFileTarget` stores on a drift conflict receipt (the detail is not kept on the row). */+export const FILE_DRIFT_MESSAGE = 'The canonical file contains an uncoordinated local edit.';+/** Separate from `dream.concepts.failed_attempts` (#6260): `{ "<source>:<slug>": { file_hash, db_revision, at } }`. */+export const DRIFT_SKIPS_KEY = 'dream.concepts.drift_skips';+export const CONFLICT_WINDOW_DEFAULT = 100_000;+export const CONFLICT_WINDOW_MAX = 1_000_000;++export const auditConflictsCommand = (sourceId: string) => `gbrain sources reconcile ${sourceId} --brain host --audit --conflicts`;+export const fileDriftRepairCommand = (sourceId: string) => `gbrain repair file-drift --source ${sourceId} --all-drifted --prefer file`;++/** The drift classes `--all-drifted` groups by (reconcile-additive.ts verdicts; `no_drift` reads as formatting only). */+export const DRIFT_CLASSES = ['structurally_additive', 'additive_with_suggestions', 'review_required', 'formatting_only', 'error'] as const;+export type DriftClass = typeof DRIFT_CLASSES[number];++/**+ * `still_present`: true when the canonical file still differs from the database+ * row, false when they agree (or the page publishes database-only), null when+ * this caller or host cannot tell; `reason` says which.+ */+export interface LiveDrift {+ still_present: boolean | null;+ reason: string;+ file_hash?: string;+ db_revision?: string;+ /** Source-relative path of the canonical file the check compared (trusted callers only). */+ path?: string;+}++/**+ * The live file/database comparison `prepareFileTarget` runs before a write,+ * without writing: a trusted local check on the source's active canonical owner+ * host. Honors database-only and read-only mirror policies (no file target: the+ * page cannot drift).+ */+export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug: string, snapshot?: PageSnapshot | null): Promise<LiveDrift> {+ const hostId = existingLocalHostId();+ const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;+ if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { still_present: null, reason: 'not_owner_host' };+ const page = snapshot === undefined ? await engine.readPageSnapshot(slug, { sourceId }) : snapshot;+ if (!page || page.page.deleted_at) return { still_present: null, reason: 'page_missing' };+ const root = join(binding.local_path, binding.relative_path);+ try {+ const file = await prepareFileTarget(engine, { source_id: sourceId, worktree_id: binding.worktree_id, slug }, page, null, hostId!);+ if (!file) return { still_present: false, reason: 'database_only', db_revision: page.revision };+ return { still_present: false, reason: 'agrees', db_revision: page.revision, path: relative(root, file.path).split(sep).join('/'),+ ...(file.expectedBeforeHash ? { file_hash: file.expectedBeforeHash } : {}) };+ } catch (error) {+ if (!(error instanceof OperationError)) return { still_present: null, reason: 'error' };+ if (error.detail !== 'file_database_drift') {+ return { still_present: null, reason: error.code === 'source_changed' ? 'file_missing' : error.code };+ }+ const path = await canonicalFilePath(engine, sourceId, root, page, slug);+ let file_hash: string | undefined;+ try { file_hash = sha256(readFileSync(path)); } catch { /* the hash is advisory */ }+ return { still_present: true, reason: 'file_database_drift', db_revision: page.revision, path: relative(root, path).split(sep).join('/'),+ ...(file_hash ? { file_hash } : {}) };+ }+}++/** The path `prepareFileTarget` compares, resolved the same way (recorded source path, captured file URI, then the slug path). */+async function canonicalFilePath(engine: BrainEngine, sourceId: string, root: string, snapshot: PageSnapshot, slug: string): Promise<string> {+ const mode = snapshot.page.source_path ? await scannerSlugRootMode(engine, sourceId, root) : undefined;+ const captured = recordedPathFromFileUri(snapshot.page.source_uri, root);+ return resolveSourceLocalFilePath(root, snapshot.page.source_path, slug, mode) ?? (captured ? join(root, captured) : join(root, `${slug}.md`));+}++/** Whether Git tracks the canonical file and whether its bytes equal the last commit (null: Git cannot say). */+function gitState(root: string, rel: string): { tracked: boolean | null; committed: boolean | null } {+ const listed = hardenedGitSync(root, ['ls-files', '-z', '--', `:(literal)${rel}`], { timeoutMs: 10_000, maxBytes: 1024 * 1024 });+ if (!listed.ok) return { tracked: null, committed: null };+ const tracked = listed.stdout.length > 0;+ if (!tracked) return { tracked, committed: false };+ const dirty = hardenedPathDirty(root, rel);+ return { tracked, committed: dirty === null ? null : !dirty };+}++/** The B0 class of one drifted page: its structural drift verdict, never values. */+export async function driftClass(engine: BrainEngine, sourceId: string, slug: string, adoptSlugPath = false): Promise<DriftClass> {+ try {+ const state = await readReconcileState(engine, sourceId, slug, undefined, { adoptSlugPath });+ const verdict = classifyDrift(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags)).verdict;+ return verdict === 'no_drift' ? 'formatting_only' : verdict;+ } catch { return 'error'; }+}++export interface ConflictAuditAccess {+ /** `ctx.remote === false`: the live file check and local paths are allowed. */+ trusted: boolean;+ /** Sources this caller may read (undefined: every source). */+ sourceIds?: string[];+ /** Slug prefixes this caller is fenced to (undefined: unfenced). */+ slugPrefixes?: string[];+ /** Hide pages private to this caller. */+ excludePrivate: boolean;+}++export interface ConflictRow extends Record<string, unknown> {+ slug: string;+ receipts: number;+ drift_receipts: number;+ first_seen: string;+ last_seen: string;+ producers: string[];+ last_conflict_request_id?: string;+ last_committed: { request_id?: string; completed_at: string } | null;+ source_path?: string | null;+ git?: { tracked: boolean | null; committed: boolean | null };+ file_hash?: string;+ db_revision?: string;+ still_present: { value: boolean | null; reason: string };+ class?: DriftClass;+}++export interface ConflictAuditReport extends Record<string, unknown> {+ source_id: string;+ group_by: 'slug';+ window: { from_sequence: string; through_sequence: string; covers_history: boolean };+ conflicts: ConflictRow[];+ next: string | null;+ complete: boolean;+ totals: { slugs: number; receipts: number; still_present: number; checked: number };+ next_actions: string[];+}++const cursorPattern = /^(\d{1,19}):([A-Za-z0-9_-]*)$/;+function parseCursor(value: unknown): { through: bigint; after: string } | null {+ if (value === undefined) return null;+ const match = typeof value === 'string' ? cursorPattern.exec(value) : null;+ const after = match ? Buffer.from(match[2], 'base64url').toString('utf8') : '';+ if (!match || BigInt(match[1]) > 9_223_372_036_854_775_807n || (after && !validSlug(after))) {+ throw opError('invalid_params', 'Invalid conflict audit cursor.',+ "Pass the cursor exactly as the previous page's `next` value, or omit it to start from the first slug.");+ }+ return { through: BigInt(match[1]), after };+}+function validSlug(slug: string): boolean { try { validateSlug(slug); return true; } catch { return false; } }+const likeEscape = (value: string) => value.replace(/[\\%_]/g, char => `\\${char}`);++/**+ * Conflict receipts of one source grouped by slug. The rows scanned are the+ * newest `window` request sequences (through the first page's high-water mark,+ * which the cursor carries so later pages read the same window); `complete` is+ * true only when the window reaches the oldest receipt and no slug is left.+ */+export async function auditDriftConflicts(engine: BrainEngine, sourceId: string, access: ConflictAuditAccess,+ options: { limit?: number; cursor?: string; window?: number } = {}): Promise<ConflictAuditReport> {+ const limit = options.limit ?? 25;+ const window = options.window ?? CONFLICT_WINDOW_DEFAULT;+ if (!isValidSourceId(sourceId) || !Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(window) || window < 1 || window > CONFLICT_WINDOW_MAX) {+ throw opError('invalid_params', 'The conflict audit needs one source, a limit from 1 to 100 and a window from 1 to 1,000,000 request sequences.',+ `Pass a registered source id, limit 1-100 (default 25) and window 1-${CONFLICT_WINDOW_MAX} (default ${CONFLICT_WINDOW_DEFAULT}).`,+ { fix: readFix('Lists the registered sources and their IDs.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });+ }+ const cursor = parseCursor(options.cursor);+ const [bounds] = await engine.executeRaw<{ top: string | null; bottom: string | null }>(+ 'SELECT (SELECT max(sequence) FROM persistence_requests)::text AS top, (SELECT min(sequence) FROM persistence_requests)::text AS bottom');+ const through = cursor?.through ?? BigInt(bounds?.top ?? '0');+ const floor = through - BigInt(window);+ const coversHistory = bounds?.bottom == null || BigInt(bounds.bottom) > floor;+ const report: ConflictAuditReport = { source_id: sourceId, group_by: 'slug',+ window: { from_sequence: String(floor > 0n ? floor + 1n : 1n), through_sequence: String(through), covers_history: coversHistory },+ conflicts: [], next: null, complete: false, totals: { slugs: 0, receipts: 0, still_present: 0, checked: 0 }, next_actions: [] };+ if (access.sourceIds && !access.sourceIds.includes(sourceId)) { report.complete = true; return report; }+ const params: unknown[] = [sourceId, String(floor), String(through)];+ const where = [`r.source_id=$1`, `r.sequence > $2::bigint`, `r.sequence <= $3::bigint`, `r.state='conflict'`, `r.error_code='source_changed'`];+ const prefixes = access.slugPrefixes?.map(normalizeSlugPrefix).filter(Boolean);+ if (prefixes) {+ if (!prefixes.length) { report.complete = true; return report; }+ const alternatives = prefixes.map(base => {+ params.push(base.endsWith('/') ? `${likeEscape(base)}%` : likeEscape(base));+ const at = params.length;+ return base.endsWith('/') ? `lower(r.slug) LIKE $${at}` : `(lower(r.slug) = $${at} OR lower(r.slug) LIKE $${at} || '/%')`;+ });+ where.push(`(${alternatives.join(' OR ')})`);+ }+ if (!access.trusted || access.excludePrivate) {+ where.push(`EXISTS (SELECT 1 FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug AND p.deleted_at IS NULL${access.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : ''})`);+ }+ const filtered = where.join(' AND ');+ const [totals] = await engine.executeRaw<{ slugs: number; receipts: number }>(+ `SELECT count(DISTINCT r.slug)::int AS slugs, count(*)::int AS receipts FROM persistence_requests r WHERE ${filtered}`, params);+ report.totals.slugs = Number(totals?.slugs ?? 0);+ report.totals.receipts = Number(totals?.receipts ?? 0);+ params.push(cursor?.after ?? '', limit + 1, FILE_DRIFT_MESSAGE);+ const rows = await engine.executeRaw<{ slug: string; receipts: number; drift_receipts: number; first_seen: string; last_seen: string; producers: string[]; last_request_id: string }>(+ `SELECT r.slug, count(*)::int AS receipts, count(*) FILTER (WHERE r.error_message=$${params.length})::int AS drift_receipts,+ to_char(min(r.created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS first_seen,+ to_char(max(r.created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS last_seen,+ array_agg(DISTINCT r.operation || COALESCE(':' || (r.intent->>'kind'), '') ORDER BY r.operation || COALESCE(':' || (r.intent->>'kind'), '')) AS producers,+ (array_agg(r.request_id::text ORDER BY r.sequence DESC))[1] AS last_request_id+ FROM persistence_requests r WHERE ${filtered} AND r.slug > $${params.length - 2}+ GROUP BY r.slug ORDER BY r.slug LIMIT $${params.length - 1}`, params);+ const page = rows.slice(0, limit);+ const slugs = page.map(row => row.slug);+ // The newest committed receipt per slug, read through the slug intent index (receipts within retention).+ const committed = slugs.length ? await engine.executeRaw<{ slug: string; request_id: string; completed_at: string }>(+ `SELECT DISTINCT ON (r.slug) r.slug, r.request_id::text, to_char(r.completed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS completed_at+ FROM persistence_requests r WHERE r.source_id=$1 AND r.slug=ANY($2::text[]) AND r.intent IS NOT NULL AND NOT r.compacted AND r.state='committed'+ ORDER BY r.slug, r.sequence DESC`, [sourceId, slugs]) : [];+ const recorded = access.trusted && slugs.length ? await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null }>(+ 'SELECT slug, source_path, source_uri FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL', [sourceId, slugs]) : [];+ const hostId = access.trusted ? existingLocalHostId() : null;+ const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;+ const owner = !!binding?.local_path && binding.owner_host_id === hostId && binding.state === 'active';+ const root = owner ? join(binding!.local_path!, binding!.relative_path) : null;+ for (const row of page) {+ const last = committed.find(entry => entry.slug === row.slug);+ const result: ConflictRow = { slug: row.slug, receipts: Number(row.receipts), drift_receipts: Number(row.drift_receipts),+ first_seen: row.first_seen, last_seen: row.last_seen, producers: row.producers ?? [],+ last_committed: last ? { ...(access.trusted ? { request_id: last.request_id } : {}), completed_at: last.completed_at } : null,+ still_present: { value: null, reason: access.trusted ? 'not_owner_host' : 'remote_caller' } };+ if (access.trusted) {+ const page = recorded.find(entry => entry.slug === row.slug);+ result.last_conflict_request_id = row.last_request_id;+ result.source_path = page?.source_path ?? null;+ if (root) {+ const live = await liveFileDrift(engine, sourceId, row.slug);+ report.totals.checked++;+ result.still_present = { value: live.still_present, reason: live.reason };+ if (live.file_hash) result.file_hash = live.file_hash;+ if (live.db_revision) result.db_revision = live.db_revision;+ if (live.path) result.git = gitState(root, live.path);+ if (live.still_present) {+ report.totals.still_present++;+ result.class = await driftClass(engine, sourceId, row.slug, !page?.source_path && !page?.source_uri);+ }+ }+ }+ report.conflicts.push(result);+ }+ const more = rows.length > limit;+ report.next = more ? `${through}:${Buffer.from(page[page.length - 1].slug, 'utf8').toString('base64url')}` : null;+ report.complete = !more && coversHistory;+ if (report.totals.slugs) {+ report.next_actions.push(access.trusted+ ? `Preview the resolution of every drifted page with ${fileDriftRepairCommand(sourceId)} (or --prefer database); it previews by default and writes nothing.`+ : 'The brain host operator resolves drifted pages with gbrain repair file-drift on the brain host; relay the slugs to the user.');+ }+ if (!coversHistory) report.next_actions.push(`Older receipts lie outside the ${window}-sequence window; widen it with --window (at most ${CONFLICT_WINDOW_MAX}).`);+ return report;+}++/** One drift skip entry: the file bytes and database revision the skip was recorded against. */+export interface DriftSkip { file_hash: string | null; db_revision: string | null; at: string }++/**+ * Records one skip with a single-statement update of its own key inside the JSON+ * object, so concurrent cycles never overwrite each other's entries. A stored+ * value that is not a JSON object is replaced.+ */+export async function recordDriftSkip(engine: BrainEngine, sourceId: string, slug: string, entry: Omit<DriftSkip, 'at'>): Promise<void> {+ const key = `${sourceId}:${slug}`;+ const value = JSON.stringify({ ...entry, at: new Date().toISOString() });+ try {+ await engine.executeRaw(`INSERT INTO config(key,value) VALUES($1, jsonb_build_object($2::text, $3::text::jsonb)::text)+ ON CONFLICT (key) DO UPDATE SET value = ((CASE WHEN jsonb_typeof(config.value::jsonb)='object' THEN config.value::jsonb ELSE '{}'::jsonb END)+ || jsonb_build_object($2::text, $3::text::jsonb))::text`, [DRIFT_SKIPS_KEY, key, value]);+ } catch {+ await engine.setConfig(DRIFT_SKIPS_KEY, JSON.stringify({ [key]: JSON.parse(value) }));+ }+}++/** Releases one skip (the file and database agree again, or the page left the phase); a no-op when absent. */+export async function releaseDriftSkip(engine: BrainEngine, sourceId: string, slug: string): Promise<void> {+ try {+ await engine.executeRaw(`UPDATE config SET value = (value::jsonb - $2::text)::text+ WHERE key=$1 AND jsonb_typeof(value::jsonb)='object' AND value::jsonb ? $2::text`, [DRIFT_SKIPS_KEY, `${sourceId}:${slug}`]);+ } catch { await engine.unsetConfig(DRIFT_SKIPS_KEY); }+}++/** Every recorded skip, keyed `<source>:<slug>`; a malformed value reads as none. */+export async function readDriftSkips(engine: BrainEngine): Promise<Record<string, DriftSkip>> {+ try {+ const parsed = JSON.parse(await engine.getConfig(DRIFT_SKIPS_KEY) ?? '{}') as unknown;+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed as Record<string, Partial<DriftSkip>>).filter(([, entry]) => entry && typeof entry === 'object')+ .map(([key, entry]) => [key, { file_hash: entry.file_hash ?? null, db_revision: entry.db_revision ?? null, at: String(entry.at ?? '') }]));+ } catch { return {}; }+}++/**+ * One `synthesize_concepts` run's view of the drift skips (B1): `skip` checks a+ * concept live before any spend and records or releases its entry; `finish`+ * re-checks recorded skips this run did not reach and returns the next actions.+ * Inactive (never skips) without a managed binding.+ */+export class ConceptDriftSkips {+ readonly skipped: string[] = [];+ private constructor(private engine: BrainEngine, private sourceId: string, private active: boolean, private dryRun: boolean,+ private recorded: Record<string, DriftSkip>) {}++ static async load(engine: BrainEngine, sourceId: string, active: boolean, dryRun: boolean): Promise<ConceptDriftSkips> {+ return new ConceptDriftSkips(engine, sourceId, active, dryRun, active ? await readDriftSkips(engine) : {});+ }++ async skip(slug: string, snapshot: PageSnapshot | null | undefined): Promise<boolean> {+ if (!this.active || !snapshot) return false;+ const drift = await liveFileDrift(this.engine, this.sourceId, slug, snapshot);+ if (drift.still_present === true) {+ this.skipped.push(slug);+ if (!this.dryRun) await recordDriftSkip(this.engine, this.sourceId, slug, { file_hash: drift.file_hash ?? null, db_revision: drift.db_revision ?? null });+ return true;+ }+ const key = `${this.sourceId}:${slug}`;+ if (this.recorded[key] && drift.still_present === false) {+ delete this.recorded[key];+ if (!this.dryRun) await releaseDriftSkip(this.engine, this.sourceId, slug);+ }+ return false;+ }++ async finish(): Promise<string[]> {+ if (this.active && !this.dryRun) {+ for (const key of Object.keys(this.recorded)) {+ const slug = key.startsWith(`${this.sourceId}:`) ? key.slice(this.sourceId.length + 1) : null;+ if (!slug || this.skipped.includes(slug)) continue;+ if ((await liveFileDrift(this.engine, this.sourceId, slug)).still_present !== true) await releaseDriftSkip(this.engine, this.sourceId, slug);+ }+ }+ return this.skipped.length ? [`List them: ${auditConflictsCommand(this.sourceId)}`,+ `Preview the resolution: ${fileDriftRepairCommand(this.sourceId)} (or --prefer database); apply with the --expect hash it prints.`] : [];+ }+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 0a56a6a7e8..ed1b2b78fe 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -4,7 +4,7 @@ import { boundedReads } from './bounded-reads.ts';import { join } from 'node:path';import type { BrainEngine, FactRow } from '../engine.ts';import { loadConfig, type GBrainConfig } from '../config.ts';-import { opError, type OperationContext } from '../ops/contract.ts';+import { opError, type OperationContext, type OperationError } from '../ops/contract.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';@@ -27,6 +27,7 @@ import { nativeLockCapability } from './native-lock.ts';import { assertPhysicalRoot } from './physical-root.ts';import { isConnectorSourceKind } from './connector-identity.ts';import { MaintenanceWriteWait } from './maintenance-wait.ts';+import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drift-conflicts.ts';import { declaredWriteTrust, lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';export interface MaintenanceAuthority {@@ -168,6 +169,12 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthconst scan = scanCanonicalFences(parseMarkdown(intent.content, slug));if (scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, authority.writer.sourceId);}+ // #6643 (B1): a canonical file that already differs from the database refuses at publication; refuse before a request+ // exists, so a producer that runs every cycle stops adding a conflict receipt per cycle. A replay above still returns its receipt.+ if (file && authority.binding && snapshot && !snapshot.page.deleted_at+ && (await liveFileDrift(engine, authority.writer.sourceId, slug, snapshot)).still_present === true) {+ throw maintenanceDriftRefusal(authority.writer.sourceId, slug);+ }const row = await admitWrite(engine, { principal: authority.writer.principal, requestId, operation: 'submit_job',sourceId: authority.writer.sourceId, sourceIncarnation: authority.writer.sourceIncarnation, slug,pageId: snapshot?.page.id ?? null, authority: authority.writer, callerIntent: intent, intent,@@ -175,6 +182,15 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthreturn writeResponse(wait.observe(await waitForWrite(engine, row, loadConfig() ?? { engine: engine.kind }, wait.ms())));}+/** #6643: `source_changed` / `file_database_drift` before admission: the audit and repair commands, never a new request. */+export function maintenanceDriftRefusal(sourceId: string, slug: string): OperationError {+ return opError('source_changed', FILE_DRIFT_MESSAGE,+ `Maintenance submitted nothing for ${slug} in '${sourceId}': its canonical file differs from the database copy, so the write would only add another conflict receipt. `+ + `List every such page with ${auditConflictsCommand(sourceId)}, then preview the resolution with gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer file (or --prefer database). Neither copy was changed.`,+ { detail: 'file_database_drift', fix: readFix(`Lists the pages of source ${sourceId} whose writes keep refusing source_changed, grouped by slug; read-only.`,+ { argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });+}+/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex b2d64a16a3..70fb6fe5b2 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex eeab55837d..c83d28caf5 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -17,6 +17,7 @@ import { readReconcileState } from './reconcile-state.ts';import { reconcileCanonical } from './reconcile-merge.ts';import { classifyDrift } from './reconcile-additive.ts';import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';+import { auditDriftConflicts, type ConflictAuditReport } from './drift-conflicts.ts';export interface ReconcileAuditReport extends Record<string, unknown> {source_id: string;@@ -138,11 +139,14 @@ async function classifyFinding(engine: BrainEngine, sourceId: string, slug: stri}}-export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport> {- if (Object.keys(params).some(key => !['source_id', 'limit', 'after', 'classify'].includes(key)) || !isValidSourceId(params.source_id)- || params.classify !== undefined && typeof params.classify !== 'boolean') {- throw opError('invalid_params', 'Audit accepts only source_id, limit, after, and classify.',- 'Pass a registered source_id, and optionally limit (1 to 100), after (the previous next_after slug) and classify (true or false), with no other fields.');+export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown> & { conflicts: true }): Promise<ConflictAuditReport>;+export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport>;+export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport | ConflictAuditReport> {+ if (Object.keys(params).some(key => !['source_id', 'limit', 'after', 'classify', 'conflicts', 'window'].includes(key)) || !isValidSourceId(params.source_id)+ || params.classify !== undefined && typeof params.classify !== 'boolean' || params.conflicts !== undefined && typeof params.conflicts !== 'boolean'+ || params.window !== undefined && params.conflicts !== true || params.classify === true && params.conflicts === true) {+ throw opError('invalid_params', 'Audit accepts only source_id, limit, after, classify, conflicts and window.',+ 'Pass a registered source_id, and optionally limit (1 to 100), after (the previous next_after slug, or with conflicts the previous next cursor), classify (true or false) or conflicts (true, with an optional window), with no other fields.');}const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {@@ -159,8 +163,12 @@ export async function runReconcileAudit(engine: BrainEngine, params: Record<stri{ fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');- const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined,- classify: params.classify === true });+ // #6643 (B0): the conflict pile, grouped by slug; the live file check runs only on the canonical owner host.+ const report = params.conflicts === true+ ? await auditDriftConflicts(engine, params.source_id, { trusted: true, excludePrivate: false },+ { limit: params.limit as number | undefined, cursor: params.after as string | undefined, window: params.window as number | undefined })+ : await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined,+ classify: params.classify === true });await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');return report;diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 87ae0c618c..bc2fb97c0c 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -137,7 +137,10 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteReassertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);const prepared = await prepareReconcileResult(engine, state, artifact.decisions);if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('canonical policy result changed');- const content = serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);+ // #6643: a request that asks to keep the file's bytes (repair file-drift --prefer file) leaves a file that already parses to the+ // reviewed result as it is; any other difference (a protected key, a tag union, a kept private row) renders the result.+ const keep = row.intent.keep_file_bytes === true && digest(reconcileCanonical(state.file, state.file.tags)) === artifact.result_digest;+ const content = keep ? state.raw.toString('utf8') : serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);const ready = prepared.ready;return {observedRevision: state.snapshot.revision, trust: await ownerImportTrust(engine, row, prepared.result.frontmatter, state.path),diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex 12947db038..02e8358a6b 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -28,7 +28,8 @@ export type { ReconcileArtifact } from './reconcile-state.ts';function grantFix(): Action {return readFix('Shows the CLI writer registration and its sources, operations and slug-prefix grant.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] });}-async function authorize(engine: BrainEngine, sourceId: unknown, slug: unknown) {+/** The trusted CLI grant check every reconcile entry point (and `gbrain repair file-drift`'s preview) runs per page. */+export async function authorizeReconcile(engine: BrainEngine, sourceId: unknown, slug: unknown) {const verified = currentVerifiedLocalWriter();if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Reconciliation requires a verified trusted local CLI caller.');if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw opError('invalid_params', 'One explicit source ID and page slug are required.',@@ -99,7 +100,7 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<st}if (auto && params.decisions !== undefined) throw opError('invalid_params', 'auto_additive computes its own decisions; omit decisions, or resolve manually without auto_additive.','Drop decisions, or drop auto_additive and resolve the preview with decisions.');- const { sourceId, slug } = await authorize(engine, params.source_id, params.slug);+ const { sourceId, slug } = await authorizeReconcile(engine, params.source_id, params.slug);if (params.output_path !== undefined) {if (typeof params.output_path !== 'string') throw opError('invalid_params', 'output_path must be an absolute private file path.','Pass output_path (CLI: --out) as an absolute path to a new file outside every source checkout.');@@ -143,8 +144,10 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<stresult_digest: preview.result_digest, preview };}export async function runReconcileApply(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {- strictReconcileKeys(params, ['source_id', 'slug', 'preview', 'request_id']);- const { sourceId, slug, authority } = await authorize(engine, params.source_id, params.slug);+ strictReconcileKeys(params, ['source_id', 'slug', 'preview', 'request_id', 'keep_file_bytes'], ['source_id', 'slug', 'preview', 'request_id']);+ if (params.keep_file_bytes !== undefined && params.keep_file_bytes !== true) throw opError('invalid_params', 'keep_file_bytes is true or absent.',+ 'Pass keep_file_bytes: true to leave a canonical file that already holds the resolved result byte for byte, or omit it.');+ const { sourceId, slug, authority } = await authorizeReconcile(engine, params.source_id, params.slug);const artifact = validateReconcileArtifact(params.preview);artifact.decisions = reconcileDecisions(artifact.decisions);const requestId = requireUuid(params.request_id as string);@@ -152,7 +155,8 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<strithrow opError('invalid_params', 'Apply requires a ready preview for this exact source and page.',`Nothing was submitted. Resolve every conflict first (preview with --from and --decisions until status is ready), then apply that resolved preview for ${slug} in '${sourceId}'.`);}- const callerIntent = { kind: 'canonical_reconcile', preview: artifact };+ // #6643: `gbrain repair file-drift --prefer file` keeps the file's own bytes when they already parse to the resolved result.+ const callerIntent = { kind: 'canonical_reconcile', preview: artifact, ...(params.keep_file_bytes === true ? { keep_file_bytes: true } : {}) };const expectedDigest = intentDigest({ operation: 'put_page', sourceId, slug, callerIntent });await assertPageRequestIdentity(engine, authority.principal, requestId);const replay = async () => {@@ -195,7 +199,7 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striexport async function runReconcileBackups(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {strictReconcileKeys(params, ['source_id', 'slug', 'action', 'backup_reference', 'after', 'limit'], ['source_id', 'slug', 'action']);- const { slug, authority } = await authorize(engine, params.source_id, params.slug);+ const { slug, authority } = await authorizeReconcile(engine, params.source_id, params.slug);if (!['list', 'remove'].includes(String(params.action)) || params.action === 'remove' &&(typeof params.backup_reference !== 'string' || params.after !== undefined || params.limit !== undefined) ||params.action === 'list' && params.backup_reference !== undefined || params.limit !== undefined &&diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 80d121fd1e..372f093901 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -35,7 +35,7 @@ import type { RepairKindSpec } from './registry.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -86,7 +86,9 @@ export interface RepairListing { item: string; class: string; detail?: string }export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[];noLlm?: boolean; maxLlmUsd?: number; deadline?: number;/** `ctx.remote !== false` of the run: a remote caller's plan never names a local path (unset reads as remote). */- remote?: boolean }+ remote?: boolean;+ /** `file-drift` (#6643): the side that wins, conflict receipt ids, every still-drifted page, and the one drift class kept. */+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string }export interface RepairHandler {kind: RepairKind;@@ -266,6 +268,7 @@ function writerHeld(error: unknown): error is OperationError {export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {@@ -277,7 +280,9 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst now = opts.now ?? Date.now;const planOpts: RepairPlanOptions = { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip,...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),- ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false };+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,+ ...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),+ ...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);@@ -299,7 +304,9 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sresumed_from: resumed, applied: 0, skipped: 0, failed: [], complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),- ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug])].map(arg => ` ${shellQuote([arg])}`).join('')}`+ ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.requests ?? []).flatMap(id => ['--request', id]),+ ...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []),+ ...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,...(plan.scan ? { scan: plan.scan } : {}),diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsnew file mode 100644index 0000000000..a3e28389f6--- /dev/null+++ b/src/core/repair/file-drift.ts@@ -0,0 +1,335 @@+/**+ * `gbrain repair file-drift --source <id> (--slug <s>... | --request <id>... | --all-drifted [--class <c>]) --prefer file|database`+ * (#6643 B2): resolve pages whose canonical file differs from their database row+ * (the `source_changed` / `file_database_drift` refusal) through canonical+ * reconciliation, preferring one side.+ *+ * The preferred side wins every ordinary field (title, type, body, timeline and+ * unprotected frontmatter; a key only the other side has is dropped) WITHIN+ * reconcile's existing protections: protected metadata (provenance, trust,+ * source and scan fields) stays as the database holds it, tags are the union of+ * both sides, and protected takes and private fact rows are kept as stored.+ * Each page's preview lists where its result differs from the preferred side+ * (`exceptions`) and why.+ *+ * Explicit-only and preview-bound: the preview checks each page live on the+ * canonical owner, preflights the CLI writer grant, prepares the reconcile+ * result, writes every page's resolved result and exceptions to a private+ * artifact under the gbrain config directory (`repair-previews/file-drift/+ * <hash>.json`, outside every canonical worktree) and saves the set under the+ * plan hash. `--apply --expect <hash>` applies exactly that set: each page goes+ * through the reconcile apply (its preimage checks and retained backups) under+ * a request id derived from the plan hash and slug, so an interrupted apply+ * resumes from the saved plan and replays the same requests. Outcomes per page:+ * `repaired`, `refused` (with the refusal code) or `changed_since_preview`.+ *+ * `--all-drifted` takes every page the conflict audit finds still drifted. It+ * refuses a selection that mixes drift classes unless `--class <name>` keeps+ * exactly one, so one `--prefer` never resolves differently shaped drift in bulk.+ * Trusted local CLI only.+ */+import { randomUUID } from 'node:crypto';+import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { configDir } from '../config.ts';+import { flushDirectory } from '../fs-durable.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';+import { validateSlug } from '../utils.ts';+import type { ParsedPage } from '../import-file.ts';+import { digest, stableJson } from '../persistence/digest.ts';+import { currentVerifiedLocalWriter, readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { canonicalFilesystemPath } from '../persistence/root-registry.ts';+import { auditDriftConflicts, DRIFT_CLASSES, driftClass, liveFileDrift, type DriftClass } from '../persistence/drift-conflicts.ts';+import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type ReconcileDecision } from '../persistence/reconcile-merge.ts';+import { readReconcileState, type ReconcileArtifact } from '../persistence/reconcile-state.ts';+import { prepareReconcileResult } from '../persistence/reconcile-prepare.ts';+import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';+import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';++export type DriftSide = 'file' | 'database';+/** Where a page's resolved result differs from the preferred side, and why. */+export interface DriftException { path: string; reason: 'protected_metadata' | 'scan_state' | 'tags_union' | 'protected_takes_or_private_facts' | 'canonical_import' }+interface ApprovedPage { source_id: string; slug: string; artifact_digest: string; selection: string }+interface DriftItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean }+interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact }++const ALL_DRIFTED_LIMIT = 1000;+const TOP_FIELDS = ['title', 'type', 'compiled_truth', 'timeline'] as const;+const artifactDirectory = () => join(canonicalFilesystemPath(configDir()), 'repair-previews', 'file-drift');+const escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');++function previewCommand(sourceId: string, opts: RepairPlanOptions): string {+ const select = opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}`+ : [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');+ return `gbrain repair file-drift --source ${sourceId}${select} --prefer ${opts.prefer ?? '<file|database>'}`;+}++/** The reconcile decisions that make the preferred side win every field reconcile lets a decision choose. */+export function preferSideDecisions(file: ParsedPage, database: ParsedPage, prefer: DriftSide): ReconcileDecision[] {+ const take = prefer === 'file' ? 'take_file' : 'take_database';+ const [preferred, other] = prefer === 'file' ? [file, database] : [database, file];+ const decisions: ReconcileDecision[] = TOP_FIELDS.filter(key => digest(file[key] ?? '') !== digest(database[key] ?? '')).map(key => ({ path: `/${key}`, action: take }));+ const extraction = file.frontmatter.provenance === 'auto-extracted' || database.frontmatter.provenance === 'auto-extracted';+ for (const key of [...new Set([...Object.keys(preferred.frontmatter), ...Object.keys(other.frontmatter)])].sort()) {+ if (protectedReconcileKey(key) || extraction && key === 'status') continue;+ const has = Object.hasOwn(preferred.frontmatter, key);+ if (has && Object.hasOwn(other.frontmatter, key) && digest(preferred.frontmatter[key]) === digest(other.frontmatter[key])) continue;+ decisions.push({ path: `/frontmatter/${escapePointer(key)}`, action: has ? take : 'delete' });+ }+ return decisions;+}++/** Every path where the resolved result is not the preferred side, with the protection that kept it. */+export function driftExceptions(result: ParsedPage, preferred: ParsedPage): DriftException[] {+ const exceptions: DriftException[] = [];+ for (const key of TOP_FIELDS) {+ if (digest(result[key] ?? '') === digest(preferred[key] ?? '')) continue;+ exceptions.push({ path: `/${key}`, reason: key === 'compiled_truth' || key === 'timeline' ? 'protected_takes_or_private_facts' : 'canonical_import' });+ }+ if (digest([...result.tags].sort()) !== digest([...preferred.tags].sort())) exceptions.push({ path: '/tags', reason: 'tags_union' });+ for (const key of [...new Set([...Object.keys(result.frontmatter), ...Object.keys(preferred.frontmatter)])].sort()) {+ if (digest(result.frontmatter[key] ?? null) === digest(preferred.frontmatter[key] ?? null)) continue;+ exceptions.push({ path: `/frontmatter/${escapePointer(key)}`, reason: RECONCILE_SCAN_KEYS.includes(key) ? 'scan_state'+ : protectedReconcileKey(key) || key === 'status' ? 'protected_metadata' : 'canonical_import' });+ }+ return exceptions;+}++async function asLocalCli<T>(engine: BrainEngine, run: () => Promise<T>): Promise<T> {+ const verified = currentVerifiedLocalWriter();+ if (verified) {+ if (verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI.');+ return run();+ }+ return withVerifiedLocalRegistration(engine, await readLocalWriter(engine, 'cli'), run);+}++function requestIdFor(hash: string, page: Pick<ApprovedPage, 'source_id' | 'slug'>): string {+ const h = digest(['file-drift-request-v1', hash, page.source_id, page.slug]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+}++function writeArtifact(hash: string, value: unknown): string {+ const directory = artifactDirectory();+ if (!existsSync(directory)) mkdirSync(directory, { recursive: true, mode: 0o700 });+ const stat = lstatSync(directory);+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw opError('permission_denied', 'The file-drift preview directory must be a private real directory.',+ `Nothing was written. Make ${directory} a real directory owned by the user with mode 0700 (not a symlink), then preview again.`);+ const path = join(directory, `${hash}.json`);+ const temporary = join(directory, `.${hash}.${randomUUID()}.tmp`);+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);+ try { writeFileSync(fd, stableJson(value)); fsyncSync(fd); } finally { closeSync(fd); }+ renameSync(temporary, path);+ flushDirectory(directory);+ return path;+}++function readArtifact(hash: string, command: string): Map<string, ArtifactPage> {+ const path = join(artifactDirectory(), `${hash}.json`);+ try {+ const stat = lstatSync(path);+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('not a regular file');+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { pages?: ArtifactPage[] };+ return new Map((parsed.pages ?? []).map(page => [page.slug, page]));+ } catch { throw previewChangedError(hash, command); }+}++/** The slugs the selection names: exact slugs, the slugs of named conflict receipts, or every page the audit finds still drifted. */+async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions): Promise<{ slugs: string[]; classes: Map<string, DriftClass> }> {+ const classes = new Map<string, DriftClass>();+ if (opts.allDrifted) {+ const drifted: string[] = [];+ let cursor: string | undefined;+ do {+ const page = await auditDriftConflicts(engine, sourceId, { trusted: true, excludePrivate: false }, { limit: 100, cursor });+ for (const row of page.conflicts) if (row.still_present.value === true) { drifted.push(row.slug); classes.set(row.slug, row.class ?? 'error'); }+ cursor = page.next ?? undefined;+ } 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) {+ 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.`,+ { fix: readFix('Lists the drifted pages with their drift class, read-only.', { argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });+ }+ return { slugs: drifted.filter(slug => !opts.driftClass || classes.get(slug) === opts.driftClass), classes };+ }+ const slugs = new Set(opts.slugs ?? []);+ if (opts.requests?.length) {+ const rows = await engine.executeRaw<{ request_id: string; slug: string }>(+ "SELECT request_id::text, slug FROM persistence_requests WHERE source_id=$1 AND request_id=ANY($2::uuid[]) AND state='conflict' AND error_code='source_changed'",+ [sourceId, opts.requests]);+ const missing = opts.requests.filter(id => !rows.some(row => row.request_id === id));+ if (missing.length) throw opError('invalid_params', `Request ${missing[0]} is not a source_changed conflict of source '${sourceId}'.`,+ `Pass the request id of a conflict receipt the audit lists (last_conflict_request_id), or select the page with --slug.`,+ { fix: readFix('Lists the conflict receipts of this source grouped by slug, read-only.', { argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });+ for (const row of rows) slugs.add(row.slug);+ }+ return { slugs: [...slugs].sort(), classes };+}++function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {+ 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>]) --prefer file|database';+ 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].reduce((a, b) => a + b, 0);+ if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request or --all-drifted.', `Pick one selection: ${usage}`);+ if (opts.driftClass && !opts.allDrifted) throw opError('invalid_params', '--class only narrows --all-drifted.', `Drop --class, or use it with --all-drifted: ${usage}`);+ if (opts.driftClass && !(DRIFT_CLASSES as readonly string[]).includes(opts.driftClass)) throw opError('invalid_params', `Unknown drift class '${opts.driftClass}'.`,+ `Pass one of ${DRIFT_CLASSES.join(', ')}; the conflict audit lists each drifted page's class.`);+ for (const slug of opts.slugs ?? []) {+ try { validateSlug(slug); } catch { throw opError('invalid_params', `Invalid page slug '${slug}'.`, 'Pass each page by its exact stored slug.'); }+ }+ if (opts.requests?.some(id => !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))) {+ throw opError('invalid_params', '--request takes a conflict receipt request UUID.', 'Pass the request id the conflict audit lists (last_conflict_request_id).');+ }+}++/**+ * The bare `gbrain repair file-drift` (the explicit-only preview command doctor and `repair --all` print): a read-only+ * survey of the drifted pages per source with their drift class and the preview command for each class. Nothing to apply.+ */+async function survey(engine: BrainEngine, scope: RepairScope): Promise<RepairPlan> {+ const listing: NonNullable<RepairPlan['listing']> = [];+ const residuals: Record<string, number> = {};+ const next: string[] = [];+ for (const sourceId of scope.source_ids) {+ const counts = new Map<DriftClass, number>();+ let cursor: string | undefined;+ let seen = 0;+ do {+ const page = await auditDriftConflicts(engine, sourceId, { trusted: true, excludePrivate: false }, { limit: 100, cursor });+ for (const row of page.conflicts) {+ if (row.still_present.value !== true) continue;+ const kind = row.class ?? 'error';+ counts.set(kind, (counts.get(kind) ?? 0) + 1);+ residuals[`drifted_${kind}`] = (residuals[`drifted_${kind}`] ?? 0) + 1;+ listing.push({ item: `${sourceId}:${row.slug}`, class: kind, detail: `${row.drift_receipts} conflict receipt(s)` });+ }+ seen += page.conflicts.length;+ cursor = page.next ?? undefined;+ } while (cursor && seen < ALL_DRIFTED_LIMIT);+ for (const kind of counts.keys()) next.push(previewCommand(sourceId, { apply: false, allDrifted: true, driftClass: kind, prefer: 'file' }));+ }+ return { items: [], residuals, listing, details: { survey: true,+ next_actions: next.length ? [...next.map(command => `Preview: ${command} (or --prefer database)`), 'Or preview single pages with --slug <slug>.'] : [] } };+}++function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {+ return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };+}++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) return survey(engine, scope);+ validateOptions(scope, opts);+ const sourceId = scope.source_ids[0]!;+ const command = previewCommand(sourceId, opts);+ const selection = digest({ prefer: opts.prefer, slugs: opts.slugs ?? [], requests: opts.requests ?? [], all: opts.allDrifted === true, class: opts.driftClass ?? null });+ if (opts.apply) {+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair file-drift --apply applies only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints with --expect <preview-hash>.`, 'docs/guides/repair.md#explicit-only-repair-kinds');+ const approved = await loadApprovedSet<ApprovedPage>(engine, { command: 'file-drift', hash: opts.expect, previewCommand: command });+ if (approved.items.some(page => page.selection !== selection || page.source_id !== sourceId)) throw previewChangedError(opts.expect, command);+ const items = approved.items.map((page, index) => item(page, index, opts.expect!, index === approved.items.length - 1, opts.prefer));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ }+ const { slugs, classes } = await selectSlugs(engine, sourceId, opts);+ const assessmentAt = new Date().toISOString();+ const pages: ArtifactPage[] = [];+ const listing: NonNullable<RepairPlan['listing']> = [];+ const residuals: Record<string, number> = {};+ const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };+ await asLocalCli(engine, async () => {+ for (const slug of slugs) {+ try {+ await authorizeReconcile(engine, sourceId, slug);+ const live = await liveFileDrift(engine, sourceId, slug);+ if (live.still_present !== true) {+ count(live.still_present === false ? 'no_drift' : `unknown_${live.reason}`);+ listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });+ continue;+ }+ const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });+ const adopt = !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;+ const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt });+ const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);+ const file = reconcileCanonical(state.file, state.file.tags);+ const decisions = preferSideDecisions(state.file, database, opts.prefer);+ const prepared = await prepareReconcileResult(engine, state, decisions);+ if (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',+ `Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);+ const preview: ReconcileArtifact = { format_version: 1, preview_id: randomUUID(), preconditions: state.pins,+ preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),+ decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };+ await assertReconcileSize(engine, preview);+ const exceptions = driftExceptions(prepared.result, opts.prefer === 'file' ? file : database);+ pages.push({ slug, prefer: opts.prefer, ...(classes.has(slug) ? { class: classes.get(slug) } : {}), adopt_slug_path: adopt, exceptions, result: prepared.result, preview });+ listing.push({ item: `${sourceId}:${slug}`, class: `prefer_${opts.prefer}`,+ detail: `${exceptions.length ? `kept: ${[...new Set(exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${adopt ? '; adopts the file at its slug path' : ''}` });+ } catch (error) {+ if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;+ count(`refused_${error.code}`);+ listing.push({ item: `${sourceId}:${slug}`, class: 'refused', detail: `${error.code}: ${error.message}` });+ }+ }+ });+ const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,+ pages: pages.map(page => [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });+ let artifact: string | undefined;+ if (pages.length) {+ await assertReconcileOutputPath(engine, sourceId, artifactDirectory());+ artifact = writeArtifact(hash, { format_version: 1, kind: 'file-drift', hash, source_id: sourceId, prefer: opts.prefer, pages });+ await saveApprovedSet<ApprovedPage>(engine, { command: 'file-drift', hash }, pages.map(page => ({ source_id: sourceId, slug: page.slug,+ artifact_digest: digest(page), selection })));+ }+ return { items: pages.map((page, index) => item({ source_id: sourceId, slug: page.slug, artifact_digest: digest(page), selection }, index, hash, index === pages.length - 1, opts.prefer)),+ preview_hash: hash, residuals, listing,+ details: { prefer: opts.prefer, ...(artifact ? { artifact } : {}),+ pages: pages.map(page => ({ slug: page.slug, ...(page.class ? { class: page.class } : {}), adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest })),+ protections: 'Protected metadata stays as the database holds it, tags are the union of both sides, and protected takes and private fact rows are kept; exceptions lists each page\'s.' } };+ },+ async apply(ctx, entry, opts): Promise<RepairItemOutcome> {+ const { page, hash, last } = entry as DriftItem;+ const command = `gbrain repair file-drift --source ${page.source_id}`;+ const artifact = readArtifact(hash, command).get(page.slug);+ if (!artifact || digest(artifact) !== page.artifact_digest) throw previewChangedError(opts?.expect ?? hash, command);+ const requestId = requestIdFor(hash, page);+ let outcome: RepairItemOutcome;+ try {+ await asLocalCli(ctx.engine, () => runReconcileApply(ctx.engine, { source_id: page.source_id, slug: page.slug, preview: artifact.preview, request_id: requestId,+ ...(artifact.prefer === 'file' ? { keep_file_bytes: true } : {}) }));+ outcome = { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: artifact.prefer } };+ } catch (error) {+ if (acceptedPendingReceipt(error) || !(error instanceof OperationError) || ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'write_pending'].includes(error.code)) throw error;+ const changed = error.code === 'revision_conflict' || error.code === 'page_identity_changed' || error.code === 'page_not_found'+ || error.code === 'source_changed' && error.message.startsWith('Reconciliation preview is stale');+ outcome = { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code, detail: { request_id: requestId, message: error.message } };+ }+ if (last) {+ await clearApprovedSet(ctx.engine, { command: 'file-drift', hash });+ try { unlinkSync(join(artifactDirectory(), `${hash}.json`)); } catch { /* already gone */ }+ }+ return outcome;+ },+ render(details) {+ const lines: string[] = [];+ for (const action of (details.next_actions ?? []) as string[]) lines.push(` ${action}`);+ if (typeof details.artifact === 'string') lines.push(` private artifact (each page's resolved result and exceptions): ${details.artifact}`);+ if (typeof details.protections === 'string') lines.push(` ${details.protections}`);+ for (const page of (details.pages ?? []) as Array<{ slug: string; exceptions: DriftException[] }>) {+ for (const exception of page.exceptions) lines.push(` kept ${page.slug} ${exception.path}: ${exception.reason}`);+ }+ return lines;+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 3b4b0bcb84..91a7860a6f 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -61,6 +61,7 @@ import { plannerStatsRepair } from './planner-stats.ts';import { fencesRepair } from './fences.ts';import { slugConflictsRepair } from './slug-conflicts.ts';import { frontmatterKeysRepair } from './frontmatter-keys.ts';+import { fileDriftRepair } from './file-drift.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -267,6 +268,15 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'to 1,000 pages, no file, body or embedding change. Each swept page advances its knowledge_revision once (a client holding an older revision '+ 'gets one revision_conflict). Preview-bound: --apply --expect <hash> sweeps exactly the previewed set; runs only when named.',},+ 'file-drift': {+ handler: fileDriftRepair, embeds: 'effect', checks: ['maintenance_write_drift'], explicit_only: true, preview_bound: true,+ summary: 'Resolve pages whose canonical file differs from the database (source_changed / file_database_drift, #6643) through canonical reconciliation: '+ + '--prefer file or --prefer database wins every ordinary field, within reconcile\'s protections (protected metadata stays as stored, tags are '+ + 'the union, protected takes and private fact rows are kept; the preview lists each page\'s exceptions). Select with --slug <slug>, --request '+ + '<conflict request id> or --all-drifted (refused across mixed drift classes unless --class <name> keeps one). Needs --source. The preview '+ + 'writes each resolved result to a private artifact; --apply --expect <hash> applies exactly that set with request ids derived from the hash, '+ + 'resumable, per page repaired, refused or changed_since_preview. Backups are reconcile\'s own. Trusted local CLI only; runs only when named.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));@@ -349,13 +359,14 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;* `maxLlmUsd`: what this run may spend on a paid chat model (`spends: 'llm'` kinds; undefined = no run cap).*/async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];- slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number } = {}): Promise<RepairResult> {+ slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,- maxLlmUsd: run.maxLlmUsd, deadline: run.deadline });+ maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass });},};}diff --git a/test/e2e/maintenance-file-drift-6643-postgres.test.ts b/test/e2e/maintenance-file-drift-6643-postgres.test.tsnew file mode 100644index 0000000000..8cd54f9842--- /dev/null+++ b/test/e2e/maintenance-file-drift-6643-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../maintenance-file-drift-6643.test.ts'));diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex c21d99a241..e14e843565 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -195,7 +195,7 @@ for (const backend of testBackends()) {const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts','conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys' };+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 18813dc1f2..ef1c3f7b8a 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 231878,- "stdoutSha256": "483f72a8533acf46fd7ff62602c053a1d78c6b77b872d60e56b3982d63df1ed9",+ "stdoutBytes": 232698,+ "stdoutSha256": "efcd4e38b964afc730f5c34369c4f9f3d8cec4ad1e885a6df5186b69830924e8","toolNames": ["remember","entity",@@ -21,6 +21,7 @@"put_pages","get_write_request","list_write_requests",+ "list_write_conflicts","cancel_write_request","search","query",@@ -1087,6 +1088,39 @@},"scope": "write"},+ {+ "description": "Pages whose writes keep ending in a source_changed conflict, grouped by slug.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "list_write_conflicts",+ "parameters": {+ "cursor": "string?",+ "limit": "number?",+ "source_id": "string?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "cursor": {+ "description": "Previous page's next.",+ "type": "string"+ },+ "limit": {+ "default": 25,+ "description": "1-100 slugs (default 25).",+ "type": "number"+ },+ "source_id": {+ "description": "Default: yours.",+ "type": "string"+ }+ },+ "required": [],+ "type": "object"+ },+ "scope": "read"+ },{"description": "Cancel your accepted write before it publishes; returns the receipt.","idempotent": true,diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 962cbb350a..b77763a633 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -111,6 +111,7 @@" [OK] loop_facts_drift: Every closed commitment loop has its fact retired."," [OK] ontology_facts_fenced: No ontology observation is held by a page's Facts table."," [OK] stale_frontmatter_keys: No stored frontmatter carries a parser-reserved key (type, title, tags, slug).",+ " [OK] maintenance_write_drift: No page whose writes refuse source_changed still has a canonical file that differs from the database."," [OK] extraction_date_grounding: Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it)."," [OK] integrity: Sampled 5 pages; no bare-tweet phrases or external links."," [OK] jsonb_integrity: All JSONB columns store objects/arrays",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 2f3cb72821..2ea64ab407 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1188,6 +1188,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 2d4192a540..e8f83f1838 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1298,6 +1298,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",@@ -4403,6 +4417,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex faaabbf893..afd658ef4a 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1294,6 +1294,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",@@ -4391,6 +4405,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 8dfaee3626..323674a4ed 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1128,6 +1128,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 8703fc099b..7171de6cc5 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1147,6 +1147,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 7900113e9f..3a15322f5c 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1143,6 +1143,20 @@"name": "stale_frontmatter_keys","status": "ok"},+ {+ "category": "ops",+ "details": {+ "concept_skips": 0,+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#maintenance-write-drift",+ "repair": "file-drift",+ "sources": [],+ "window_sequences": 20000+ },+ "message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.",+ "name": "maintenance_write_drift",+ "status": "ok"+ },{"category": "brain","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 440ff87b8d..353fd65f0b 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -485,6 +485,10 @@"category": "ops","name": "stale_frontmatter_keys"},+ {+ "category": "ops",+ "name": "maintenance_write_drift"+ },{"category": "brain","name": "extraction_date_grounding"diff --git a/test/maintenance-file-drift-6643.test.ts b/test/maintenance-file-drift-6643.test.tsnew file mode 100644index 0000000000..c9450fe6dc--- /dev/null+++ b/test/maintenance-file-drift-6643.test.ts@@ -0,0 +1,330 @@+/**+ * #6643: the source_changed conflict pile becomes visible (B0), stops growing (B1),+ * resolvable (B2) and measured (B3).+ *+ * A canonical file that diverged from its database row refuses every coordinated+ * write. Before #6643 `synthesize_concepts` paid for a narrative per drifted+ * concept on every cycle and left a conflict receipt for each publication, and no+ * command resolved the pile. These cases pin:+ * - B1: a drifted concept is skipped before any provider call or admission, on+ * every cycle (restart-safe: the check is live), the skip is recorded in+ * `dream.concepts.drift_skips` and released once the file and database agree;+ * a maintenance submit refuses `source_changed` / `file_database_drift`+ * without a request row, while a replay of an earlier request returns its receipt;+ * - B0: the conflict audit groups receipts by slug with the live check for the+ * trusted CLI and database-derived fields only for scoped MCP readers;+ * - B2: `gbrain repair file-drift` previews, refuses mixed drift classes under+ * --all-drifted unless --class keeps one, applies exactly the previewed set+ * with per-page outcomes and resumes an interrupted apply; --prefer keeps+ * one-sided metadata, tags and protected metadata as reconcile protects them;+ * - B3: doctor `maintenance_write_drift` counts drifted pages and skips.+ *+ * Runs on PGLite, and on Postgres when DATABASE_URL is set+ * (test/e2e/maintenance-file-drift-6643-postgres.test.ts).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { maintenancePreflight, publishMaintenancePage } from '../src/core/persistence/prepared-maintenance.ts';+import { DRIFT_SKIPS_KEY, liveFileDrift, readDriftSkips, recordDriftSkip, releaseDriftSkip } from '../src/core/persistence/drift-conflicts.ts';+import { runReconcileAudit } from '../src/core/persistence/reconcile-audit.ts';+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';+import { persistenceOperations } from '../src/core/ops/persistence.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { preferSideDecisions, driftExceptions } from '../src/core/repair/file-drift.ts';+import { maintenanceWriteDriftCheck } from '../src/commands/doctor/checks/maintenance-drift.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const logger = { info() {}, warn() {}, error() {} };+const CONCEPT = 'concepts/example-topic';+const listConflicts = persistenceOperations.find(op => op.name === 'list_write_conflicts')!;++function conceptMarkdown(narrative: string, hash: string): string {+ return `---\ntype: concept\ntitle: example topic\nsynthesized_by: synthesize_concepts-v0.41\nsynthesis_mode: llm\nmember_hash: ${hash}\nvisibility: world\ntier: T2\n---\n\n${narrative}\n`;+}+const atoms = (variant: string) => Array.from({ length: 5 }, (_, i) => ({ slug: `atoms/example-${i}`, title: `Example ${i}`,+ body: `Observation ${i} ${variant}.`, concept_refs: ['example-topic'], visibility: 'world' as const }));++for (const backend of testBackends()) describe(`#6643 maintenance file drift (${backend})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-6643-db-'));++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({ database_path: dataDir }); await pglite.initSchema(); engine = pglite;+ } else {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (closePostgres) await closePostgres(); else await engine.disconnect();+ resetGateway(); rmSync(dataDir, { recursive: true, force: true });+ });++ async function fixture(run: (input: { root: string; sourceId: string; ctx: OperationContext }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6643-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `d6643-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await run({ root, sourceId, ctx });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.unsetConfig(DRIFT_SKIPS_KEY);+ rmSync(dir, { recursive: true, force: true });+ }+ }++ const put = (ctx: OperationContext, slug: string, content: string) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+ const requests = async (sourceId: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [sourceId]))[0].n);++ test('a drifted concept is skipped before spend and admission on every cycle, and released after --prefer file', () => fixture(async ({ root, sourceId, ctx }) => {+ for (const atom of atoms('one')) await put(ctx, atom.slug, `---\ntype: atom\ntitle: ${atom.title}\n---\n${atom.body}\n`);+ await put(ctx, CONCEPT, conceptMarkdown('The first narrative.', 'stale-hash'));+ const file = join(root, 'concepts', 'example-topic.md');+ expect(existsSync(file)).toBe(true);+ writeFileSync(file, readFileSync(file, 'utf8').replace('The first narrative.', 'The first narrative.\n\nA paragraph added in the file only.'));+ const drifted = readFileSync(file, 'utf8');+ expect((await liveFileDrift(engine, sourceId, CONCEPT)).still_present).toBe(true);++ let calls = 0;+ const chat = (async () => { calls++; return { text: 'A paid narrative.', usage: { input_tokens: 10, output_tokens: 10 }, model: 'anthropic:claude-sonnet-4-6', stopReason: 'end' }; }) as never;+ const before = await requests(sourceId);+ for (const cycle of [1, 2]) {+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(`cycle-${cycle}`), sourceId, brainDir: root, _chat: chat });+ const details = result.details as Record<string, unknown>;+ expect(details.skipped_file_drift).toEqual([CONCEPT]);+ expect(result.status).toBe('warn');+ expect(result.summary).toContain('gbrain repair file-drift');+ expect(result.summary).toContain('--audit --conflicts');+ }+ expect(calls).toBe(0);+ expect(await requests(sourceId)).toBe(before);+ const skips = await readDriftSkips(engine);+ expect(skips[`${sourceId}:${CONCEPT}`]).toMatchObject({ db_revision: expect.any(String), file_hash: expect.any(String) });++ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);+ expect(doctor).toMatchObject({ name: 'maintenance_write_drift', status: 'warn', details: { count: 1, concept_skips: 1 } });+ expect(doctor.fix?.argv).toEqual(['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json']);++ const scope = await resolveRepairScope(engine, sourceId);+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('file-drift', scope,+ { explicit: true, sourceFlag: sourceId, slugs: [CONCEPT], prefer: 'file' });+ const hash = preview.preview_hash!;+ expect(hash).toMatch(/^[0-9a-f]{64}$/);+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });+ expect(preview.apply_command).toContain(`--slug ${CONCEPT}`);+ expect(preview.apply_command).toContain('--prefer file');+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('file-drift', scope,+ { explicit: true, sourceFlag: sourceId, slugs: [CONCEPT], prefer: 'file', expect: hash });+ expect(applied.outcomes).toEqual({ repaired: 1 });+ expect(readFileSync(file, 'utf8')).toBe(drifted);+ expect((await liveFileDrift(engine, sourceId, CONCEPT)).still_present).toBe(false);+ expect((await engine.getPage(CONCEPT, { sourceId }))!.compiled_truth).toContain('A paragraph added in the file only.');++ const released = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms('cycle-3'), sourceId, brainDir: root, _chat: chat });+ expect((released.details as Record<string, unknown>).skipped_file_drift).toEqual([]);+ expect(calls).toBe(1);+ expect((await readDriftSkips(engine))[`${sourceId}:${CONCEPT}`]).toBeUndefined();+ expect((await maintenanceWriteDriftCheck(engine, [sourceId])).status).toBe('ok');+ }), 240_000);++ const drift = (root: string, slug: string, edit: (text: string) => string) => {+ const file = join(root, `${slug}.md`);+ writeFileSync(file, edit(readFileSync(file, 'utf8')));+ return file;+ };+ /** A caller write refused source_changed: one conflict receipt for the slug. */+ const refusedWrite = async (ctx: OperationContext, slug: string, body: string) => {+ const expected_revision = (await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId! }))!.revision;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: `---\ntype: note\ntitle: Refused\n---\n${body}\n`, expected_revision, request_id: randomUUID() } })+ .then(() => { throw new Error(`write to ${slug} committed`); }, (error: { code?: string }) => expect(error.code).toBe('source_changed'));+ };++ test('a maintenance submit refuses drift before admission, and a replay of an earlier request still returns its receipt', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, CONCEPT, conceptMarkdown('The first narrative.', 'h1'));+ const authority = (await maintenancePreflight(engine, sourceId, root))!;+ const snapshot = (await engine.readPageSnapshot(CONCEPT, { sourceId }))!;+ const content = conceptMarkdown('A maintenance narrative.', 'h2');+ const first = await publishMaintenancePage(engine, authority, CONCEPT, content, { expectedRevision: snapshot.revision });+ expect(first.state).toBe('committed');+ drift(root, CONCEPT, text => `${text}\nA hand edit.\n`);+ const before = await requests(sourceId);+ const replay = await publishMaintenancePage(engine, authority, CONCEPT, content, { expectedRevision: snapshot.revision });+ expect(replay.request_id).toBe(first.request_id);+ const current = (await engine.readPageSnapshot(CONCEPT, { sourceId }))!;+ const refused = await publishMaintenancePage(engine, authority, CONCEPT, conceptMarkdown('Another narrative.', 'h3'), { expectedRevision: current.revision })+ .then(() => null, (error: { code?: string; detail?: string; suggestion?: string }) => error);+ expect(refused).toMatchObject({ code: 'source_changed', detail: 'file_database_drift' });+ expect(refused!.suggestion).toContain('--audit --conflicts');+ expect(refused!.suggestion).toContain('gbrain repair file-drift');+ expect(await requests(sourceId)).toBe(before);+ }), 240_000);++ test('the conflict audit groups receipts by slug; scoped MCP readers get database-derived fields within their grant', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, 'notes/alpha', '---\ntype: note\ntitle: Alpha\n---\nAlpha.\n');+ await put(ctx, 'notes/secret', '---\ntype: note\ntitle: Secret\nvisibility: private\n---\nSecret.\n');+ await put(ctx, 'people/alice-example', '---\ntype: person\ntitle: Alice Example\n---\nAlice.\n');+ for (const slug of ['notes/alpha', 'notes/secret', 'people/alice-example']) drift(root, slug, text => `${text}\nEdited in the file only.\n`);+ await refusedWrite(ctx, 'notes/alpha', 'One.');+ await refusedWrite(ctx, 'notes/alpha', 'Two.');+ await refusedWrite(ctx, 'notes/secret', 'Three.');+ await refusedWrite(ctx, 'people/alice-example', 'Four.');++ const report = await runReconcileAudit(engine, { source_id: sourceId, conflicts: true });+ expect(report).toMatchObject({ source_id: sourceId, group_by: 'slug', complete: true, next: null, totals: { slugs: 3, receipts: 4, still_present: 3, checked: 3 } });+ expect(report.conflicts.map(row => [row.slug, row.receipts, row.drift_receipts])).toEqual([['notes/alpha', 2, 2], ['notes/secret', 1, 1], ['people/alice-example', 1, 1]]);+ const alpha = report.conflicts[0];+ expect(alpha).toMatchObject({ producers: ['put_page'], still_present: { value: true, reason: 'file_database_drift' }, source_path: 'notes/alpha.md',+ git: { tracked: false, committed: false }, class: 'additive_with_suggestions', last_committed: { request_id: expect.any(String) },+ last_conflict_request_id: expect.any(String), file_hash: expect.any(String), db_revision: expect.any(String) });+ const paged = await runReconcileAudit(engine, { source_id: sourceId, conflicts: true, limit: 1 });+ expect(paged).toMatchObject({ complete: false });+ expect(paged.conflicts.map(row => row.slug)).toEqual(['notes/alpha']);+ const next = await runReconcileAudit(engine, { source_id: sourceId, conflicts: true, limit: 1, after: paged.next! });+ expect(next.conflicts.map(row => row.slug)).toEqual(['notes/secret']);++ const remote = (auth: Record<string, unknown>) => ({ engine, remote: true, sourceId, logger, config: { engine: engine.kind } as never,+ auth: { token: 't', clientId: 'reader-example', scopes: ['read'], ...auth } } as unknown as OperationContext);+ const reader = await listConflicts.handler(remote({}), { source_id: sourceId }) as { conflicts: Array<Record<string, unknown>>; totals: Record<string, number> };+ expect(reader.conflicts.map(row => row.slug)).toEqual(['notes/alpha', 'people/alice-example']);+ expect(reader.totals).toMatchObject({ slugs: 2, receipts: 3, checked: 0 });+ for (const row of reader.conflicts) {+ expect(row.still_present).toEqual({ value: null, reason: 'remote_caller' });+ for (const key of ['source_path', 'git', 'file_hash', 'db_revision', 'class', 'last_conflict_request_id']) expect(row).not.toHaveProperty(key);+ expect(row.last_committed).not.toHaveProperty('request_id');+ }+ expect(JSON.stringify(reader)).not.toContain(root);+ const fenced = await listConflicts.handler(remote({ boundSlugPrefixes: ['people/'] }), { source_id: sourceId }) as { conflicts: Array<{ slug: string }> };+ expect(fenced.conflicts.map(row => row.slug)).toEqual(['people/alice-example']);+ const elsewhere = await listConflicts.handler(remote({ allowedSources: ['other-source'] }), { source_id: sourceId }) as { conflicts: unknown[]; totals: { slugs: number } };+ expect(elsewhere).toMatchObject({ conflicts: [], totals: { slugs: 0 } });+ }), 240_000);++ test('--all-drifted refuses mixed drift classes unless --class keeps one', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, 'notes/additive', '---\ntype: note\ntitle: Additive\n---\nAdditive.\n');+ await put(ctx, 'notes/rewritten', '---\ntype: note\ntitle: Rewritten\n---\nOriginal sentence.\n');+ drift(root, 'notes/additive', text => `${text}\nAn appended line.\n`);+ drift(root, 'notes/rewritten', text => text.replace('Original sentence.', 'A different sentence.'));+ await refusedWrite(ctx, 'notes/additive', 'One.');+ await refusedWrite(ctx, 'notes/rewritten', 'Two.');+ const scope = await resolveRepairScope(engine, sourceId);+ const runner = await repairRunner(engine, { apply: false, logger });+ const surveyed = await runner.run('file-drift', await resolveRepairScope(engine, undefined), { explicit: true });+ expect(surveyed.affected).toBe(0);+ expect(surveyed.preview_hash).toBeUndefined();+ expect(surveyed.listing!.filter(row => row.item.startsWith(`${sourceId}:`)).map(row => [row.item, row.class]))+ .toEqual([[`${sourceId}:notes/additive`, 'additive_with_suggestions'], [`${sourceId}:notes/rewritten`, 'review_required']]);+ expect(surveyed.details!.next_actions).toContain(`Preview: gbrain repair file-drift --source ${sourceId} --all-drifted --class review_required --prefer file (or --prefer database)`);+ const mixed = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'file' }).then(() => null, error => error);+ expect(mixed).toMatchObject({ code: 'invalid_params' });+ expect(mixed.message).toContain('2 drift classes');+ expect(mixed.message).toContain('review_required=1');+ expect(mixed.message).toContain('additive_with_suggestions=1');+ const one = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, driftClass: 'review_required', prefer: 'file' });+ expect(one.affected).toBe(1);+ expect(one.sample).toEqual([`${sourceId}:notes/rewritten`]);+ expect(one.apply_command).toContain('--all-drifted --class review_required --prefer file');+ }), 240_000);++ test('--prefer keeps protected metadata and unions tags; an interrupted apply resumes, and a page edited after the preview is changed_since_preview', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, 'notes/one', '---\ntype: note\ntitle: One\nreviewed: true\ntags: [alpha]\n---\nStored one.\n');+ await put(ctx, 'notes/two', '---\ntype: note\ntitle: Two\n---\nStored two.\n');+ await put(ctx, 'notes/three', '---\ntype: note\ntitle: Three\n---\nStored three.\n');+ const stored = (await engine.readPageSnapshot('notes/one', { sourceId }))!;+ drift(root, 'notes/one', text => text.replace('reviewed: true\n', 'owner: alice-example\n').replace('Stored one.', 'File one.')+ .replace(/ingested_via: [^\n]+/, 'ingested_via: hand-edit').replace(' - alpha', ' - alpha\n - beta'));+ drift(root, 'notes/two', text => text.replace('Stored two.', 'File two.'));+ drift(root, 'notes/three', text => text.replace('Stored three.', 'File three.'));+ const scope = await resolveRepairScope(engine, sourceId);+ const slugs = ['notes/one', 'notes/two', 'notes/three'];+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('file-drift', scope, { explicit: true, sourceFlag: sourceId, slugs, prefer: 'database' });+ const hash = preview.preview_hash!;+ expect(preview.affected).toBe(3);+ const pages = (preview.details!.pages as Array<{ slug: string; exceptions: Array<{ path: string; reason: string }> }>);+ expect(pages.find(page => page.slug === 'notes/one')!.exceptions).toEqual([{ path: '/tags', reason: 'tags_union' }]);+ const artifact = JSON.parse(readFileSync(String(preview.details!.artifact), 'utf8'));+ const one = artifact.pages.find((page: { slug: string }) => page.slug === 'notes/one');+ expect(one.result.frontmatter).toMatchObject({ reviewed: true, ingested_via: stored.page.frontmatter.ingested_via ?? 'put_page' });+ expect(one.result.frontmatter).not.toHaveProperty('owner');+ expect(one.result.tags).toEqual(['alpha', 'beta']);+ expect(one.result.compiled_truth).toBe('Stored one.');++ const apply = (limit?: number) => repairRunner(engine, { apply: true, logger }).then(runner => runner.run('file-drift', scope,+ { explicit: true, sourceFlag: sourceId, slugs, prefer: 'database', expect: hash, ...(limit ? { limit } : {}) }));+ const firstRun = await apply(1);+ expect(firstRun).toMatchObject({ applied: 1, complete: false, outcomes: { repaired: 1 } });+ drift(root, 'notes/two', text => text.replace('File two.', 'File two, edited again.'));+ const resumed = await apply();+ expect(resumed.resumed_from).not.toBeNull();+ expect(resumed.outcomes).toEqual({ changed_since_preview: 1, repaired: 1 });+ expect(resumed.outcome_items!.map(item => [item.item, item.outcome])).toEqual([[`${sourceId}:notes/three`, 'repaired'], [`${sourceId}:notes/two`, 'changed_since_preview']]);+ const page = (await engine.getPage('notes/one', { sourceId }))!;+ expect(page.compiled_truth).toBe('Stored one.');+ expect(page.frontmatter).toMatchObject({ reviewed: true });+ expect(await engine.getTags('notes/one', { sourceId })).toEqual(['alpha', 'beta']);+ expect(readFileSync(join(root, 'notes/one.md'), 'utf8')).not.toContain('owner: alice-example');+ expect((await liveFileDrift(engine, sourceId, 'notes/two')).still_present).toBe(true);+ await expect(apply()).rejects.toMatchObject({ code: 'preview_changed' });+ }), 240_000);+});++describe('#6643 file-drift pure rules', () => {+ const page = (fields: Partial<{ title: string; compiled_truth: string; frontmatter: Record<string, unknown>; tags: string[] }>) =>+ ({ type: 'note', title: 'T', compiled_truth: 'Body.', timeline: '', frontmatter: {}, tags: [], ...fields }) as never;+ test('prefer decisions take the preferred side, drop its missing keys and never decide protected keys or tags', () => {+ const file = page({ compiled_truth: 'File.', frontmatter: { owner: 'alice-example', provenance: 'hand', shared: 1 }, tags: ['b'] });+ const database = page({ frontmatter: { reviewed: true, provenance: 'extracted', shared: 1 }, tags: ['a'] });+ expect(preferSideDecisions(file, database, 'file')).toEqual([{ path: '/compiled_truth', action: 'take_file' },+ { path: '/frontmatter/owner', action: 'take_file' }, { path: '/frontmatter/reviewed', action: 'delete' }]);+ expect(preferSideDecisions(file, database, 'database')).toEqual([{ path: '/compiled_truth', action: 'take_database' },+ { path: '/frontmatter/owner', action: 'delete' }, { path: '/frontmatter/reviewed', action: 'take_database' }]);+ });+ test('exceptions name the protection that kept each difference', () => {+ const preferred = page({ compiled_truth: 'File.', frontmatter: { provenance: 'hand', atoms_scan_hash: 'x' }, tags: ['b'] });+ const result = page({ compiled_truth: 'File.\n\nkept private row', frontmatter: { provenance: 'extracted' }, tags: ['a', 'b'] });+ expect(driftExceptions(result, preferred)).toEqual([{ path: '/compiled_truth', reason: 'protected_takes_or_private_facts' },+ { path: '/tags', reason: 'tags_union' }, { path: '/frontmatter/atoms_scan_hash', reason: 'scan_state' }, { path: '/frontmatter/provenance', reason: 'protected_metadata' }]);+ });+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ test('drift skip entries update one key at a time and a malformed value is replaced', async () => {+ await Promise.all([recordDriftSkip(engine, 's', 'concepts/a', { file_hash: 'f1', db_revision: 'r1' }),+ recordDriftSkip(engine, 's', 'concepts/b', { file_hash: 'f2', db_revision: 'r2' })]);+ expect(Object.keys(await readDriftSkips(engine)).sort()).toEqual(['s:concepts/a', 's:concepts/b']);+ await releaseDriftSkip(engine, 's', 'concepts/a');+ expect(Object.keys(await readDriftSkips(engine))).toEqual(['s:concepts/b']);+ await engine.setConfig(DRIFT_SKIPS_KEY, 'not json');+ await recordDriftSkip(engine, 's', 'concepts/c', { file_hash: null, db_revision: 'r3' });+ expect(Object.keys(await readDriftSkips(engine))).toEqual(['s:concepts/c']);+ });+});diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 7065b2381a..50a1072063 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -49,6 +49,7 @@ const LEDGER: Record<string, string> = {get_write_request: 'test/persistence-receipt-operations.test.ts',list_write_requests: 'test/persistence-receipt-operations.test.ts',cancel_write_request: 'test/persistence-receipt-operations.test.ts',+ list_write_conflicts: 'test/maintenance-file-drift-6643.test.ts',search: 'test/cli-search-dispatch.test.ts',query: 'test/query-image-flag.serial.test.ts',search_stats: 'test/search-introspection-ops.test.ts',diff --git a/test/operations-source-isolation-matrix.test.ts b/test/operations-source-isolation-matrix.test.tsindex 8e6476c7c8..e6ab34508a 100644--- a/test/operations-source-isolation-matrix.test.ts+++ b/test/operations-source-isolation-matrix.test.ts@@ -105,6 +105,7 @@ const MATRIX: Row[] = [{ name: 'entity', mode: 'skip', reason: 'MEMORY_VERBS conformance suite owns it; LLM-shaped output' },{ name: 'synthesize', mode: 'skip', reason: 'LLM-dependent; keyless envs cannot run it — verbs conformance owns the error path' },{ name: 'think', mode: 'skip', reason: 'LLM-dependent; think-source-isolation-pglite e2e owns its scoping' },+ { name: 'list_write_conflicts', mode: 'skip', reason: 'needs source_changed conflict receipts from a bound canonical checkout; test/maintenance-file-drift-6643.test.ts owns its source-grant and slug-fence filtering' },{ name: 'search_by_image', mode: 'skip', reason: 'needs image-embedding infra; cross-modal suites own it' },{ name: 'volunteer_context', mode: 'skip', reason: 'session/reflex machinery; volunteer-context suites own scoping' },{ name: 'context_pack', mode: 'skip', reason: 'verbs conformance owns it; budget-packed composite of scoped reads' },diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex 2c2309d16c..47fdfc2f65 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -356,6 +356,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {add_timeline_entry: 'ok',get_write_request: 'error',list_write_requests: 'ok',+ list_write_conflicts: 'ok',cancel_write_request: 'error',revert_version: 'error',edit_page: 'error',diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex fc9e344573..7c027d0faa 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.tsindex 91f9800590..b84daa7816 100644--- a/test/retrieval-op-redaction.test.ts+++ b/test/retrieval-op-redaction.test.ts@@ -208,6 +208,7 @@ const SWEEP: Record<string, Row> = {schema_graph: { args: {} },schema_explain_type: { args: { type: 'note' } },schema_review_orphans: { args: { limit: 50 } },+ list_write_conflicts: { args: {} },// no_stored_text — write receipts (the planted content is the caller's own// input here; the receipt must not echo it)remember: { args: { fact: planted('remembered'), provenance: 'test:sweep', request_id: randomUUID() } },