Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(#6712 PR 4b lane T): gbrain repair legacy-twins converges pre-#6857 forked page pairs (#6885)
garrytan8cda2764b3e7
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 94057b0f8f..ba1b612a46 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -219,6 +219,7 @@ src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversationsrc/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.src/core/repair/ghost-pages.ts 1 coordinator `gbrain repair ghost-pages` (#6696 B5) retires a preview-approved ghost page (its canonical file is gone): on a managed brain only through a managed_maintenance_retire_ghost_page request whose preparer reruns the classifier under the approved owner and prepares a delete_page with allowMissingFile that refuses unless the file target is the approved path with no bytes (a restored file refuses at preparation or at filesystem publication); only an unmanaged brain versions and soft-deletes directly, inside maintenanceTransaction under the page lock after the revision, page id and file-absence recheck.+src/core/repair/legacy-twins.ts 9 coordinator `gbrain repair legacy-twins` (#6885) merges a preview-approved legacy twin pair onto its legacy page: on a managed brain only through a managed_maintenance_merge_legacy_twin request on the twin, holding the legacy page's key, whose preparer re-checks both pages (ids, slugs, revisions, recorded path, same content, the file agreeing with the twin) under the approved owner and again under the publication locks, and publishes no file; only an unmanaged brain records the origin, moves the twin's references, versions and soft-deletes the twin directly, inside maintenanceTransaction under both page locks after the same recheck.src/core/repair/aliases.ts 2 coordinator `gbrain repair aliases` (#6619) deletes preview-approved page_aliases / slug_aliases rows whose target page no longer exists (soft-deleted targets are never touched), under the page key: inside withCoordinatedWrite with maintenance attribution on a managed brain, one transaction on an unmanaged brain.src/core/repair/frontmatter.ts 2 coordinator `gbrain repair frontmatter --apply` (#5988) publishes a managed source's repaired file only through submitManagedFileRepair (the managed_file_repair request, preview-hash bound). On an unmanaged (legacy) source it writes the previewed bytes after a backup, moves a renamed page with updateSlug and its source_path in one maintenanceTransaction, then imports the file through importFromFile; no canonical writer enforcement applies there.src/commands/sources-mirror.ts 1 engine_guard `gbrain sources mirror-readonly|mirror-writable` (#5409) updates only sources.config.mirror_read_only, exactly as `sources federate` updates sources.config.federated; the sources managed_writer_guard trigger governs the row and no page, fact or file is written.diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex b1d1113255..9a961f46df 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -28,6 +28,7 @@- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`.- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.+- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.- `src/core/persistence/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.- `src/core/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7), since #6712 PR 4b an admission of the managed sync pass (design v3.2 §4, d1b option C); the consumer's keep_db worker and its 10-minute timer are gone. `readKeepDbPolicy` reads a source's `keep_db` prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding; doctor `maintenance_write_drift` reads it and `keepDbReceiptCost`. `freezeKeepDbReconcile` builds the `--prefer database` artifact (`prepareDriftPage`) for a path the pass classified `keep_db` (row 18) or `db_ahead`/`db_only` under keep_db (row 15), committed mode with `Dp = clean`, under this host's policy on a source that is not mirror-read-only, and refuses (`{ refused }`) unless the artifact's own read matches the frozen page id, revision, file bytes (`sha256` = `preconditions.raw_file_hash`) and path. `admitKeepDbReconcile` (trusted local pass only, `remote: false`) admits it through `admitReconcileArtifact` (`persistence/reconcile.ts`, the core `runReconcileApply` shares) under this installation's own CLI writer registration as a background producer, without waiting for publication; inside the admission transaction it re-reads `sync.admission` (`admission_paused` when not `normal`) and runs the pass's `inTx` fence, whose error rolls back and is rethrown as is. The request id derives from the page revision and frozen bytes (one drift, one request), skipping an id whose request `sync.admission` cancelled or that holds a retained backup but no request; the intent carries `keepDb: { passId }`, and its publication re-reads `sync.admission` and completes `cancelled`/`admission_paused` with nothing written (`reconcile-prepare.ts`, `coordinator.ts` `failureState`). `releaseMatchedDriftSkips` releases the concept drift skips of pages the pass classified `matched`. Tests: `test/keep-db-pass-admission.test.ts` (probes 26, 27, 47, 51; Postgres via `test/e2e/keep-db-pass-admission-postgres.test.ts`), `test/keep-db-consumer-retired.test.ts`, `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 856076ef95..d337844e2a 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -288,6 +288,7 @@ or a physical projection that leaves attribution untouched):- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.- `src/core/repair/ghost-pages.ts` (2): `gbrain repair ghost-pages` retirement: a receipted `managed_maintenance_retire_ghost_page` request (a prepared `delete_page` with no file bytes) on managed brains; the unmanaged version and soft delete run in `maintenanceTransaction` after the same recheck.+- `src/core/repair/legacy-twins.ts` (5): `gbrain repair legacy-twins` merge: a receipted `managed_maintenance_merge_legacy_twin` request (on the twin, holding the legacy page's key, no file bytes) on managed brains; the unmanaged merge runs in `maintenanceTransaction` under both page locks after the same recheck.- `src/core/repair/ontology-facts.ts` (1): a coordinated database-only write (`coordinatedDatabaseWrite`, the `ontology_propose` path) on managed brains; the unmanaged ontology-facts restore runs in `maintenanceTransaction`.- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4c9dc95d22..837ce26a83 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2052,6 +2052,28 @@ More: [docs/guides/repair.md#legacy-job-selection-invalid](../../docs/guides/repMore: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#legacy-jobs-active)+### legacy_twin_mass_merge_refused++<a id="legacy_twin_mass_merge_refused"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain repair legacy-twins refused to merge legacy twin pairs that are more than half of a source's file-backed pages; nothing was changed. | The sync mass-delete valve (#2828) applied to legacy twins: each merge soft-deletes a file-backed twin, and that many twins at once almost always means a re-import under another slug fold or the wrong checkout, not a backlog of forked pairs. | Check the source and its checkout on the owner host first. If merging these pairs is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1. Run: gbrain sources writer status --source '{source_id}' --json | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#legacy-twins](../../docs/guides/repair.md#legacy-twins)++### legacy_twins_storage_unknown++<a id="legacy_twins_storage_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Legacy twin pairs of a source cannot be checked because its canonical root is missing or is not a readable directory; nothing was listed or changed. | Whether a twin's file is still there and agrees with it is only known from the checkout, so the repair fails closed rather than merge on a guess. | Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair legacy-twins --source <id> again. Run: gbrain sources writer status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |++Reasons: `storage_unavailable`.++More: [docs/guides/repair.md#legacy-twins](../../docs/guides/repair.md#legacy-twins)+### local_conflict<a id="local_conflict"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 1a9f5d4fe6..f989814727 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -791,6 +791,79 @@ database only and are never ghosts. Doctor `undeclared_db_only_pages` is aseparate audit. A preview lists at most 1,000 ghosts; apply them, then previewagain for the rest. Sync never removes ghost pages by itself.+<a id="legacy-twins"></a>+### Legacy twins++Before #6857, a managed sync could fork a second page for a file an older gbrain+had imported under its raw name: the **legacy page** (the original id, a slug+such as `notes/foo bar` that the current slug fold spells differently, no+recorded file, and the page's links, timeline and history) and its **twin**+(the folded slug `notes/foo-bar`, recording the file). Sync no longer forks+new pairs, but it leaves the existing ones as they are. Deleting the twin by+hand withdraws the file, because no other live page records it; deleting the+legacy page keeps the file but loses the id, links and history.+`gbrain repair legacy-twins` converges each pair onto the legacy page.++```bash+gbrain repair legacy-twins --source default # preview: each pair, decisions, and a hash+gbrain repair legacy-twins --source default --apply --expect <hash> --yes+```++The preview writes nothing. It lists every pair with both page ids, slugs and+revisions, the file the twin records and whether the two pages hold the same+content, and prints the apply command with its hash. A pair the repair never+merges on its own is listed as a decision (class `decision:<reason>`), with the+commands a person uses to decide it:++| Reason | What to decide |+|---|---|+| `content_differs` | The two pages hold different content. Compare them (`gbrain get --source <id> -- '<slug>'`); make them the same (edit the file and sync, or edit the legacy page) and preview again, or keep the twin and delete the legacy page. |+| `several_legacy` | More than one legacy page folds to the twin's slug. Keep one, soft-delete the others, preview again. |+| `file_missing`, `file_drift`, `file_unverified` | The twin's file is gone, differs from the twin, or cannot be checked. Resolve it with [ghost pages](#ghost-pages) or [file drift](#file-drift) first. |+| `twin_slug_path_occupied` | A file sits at the twin's own slug path (`<twin-slug>.md`), which the twin's purge would compare or remove. Rename or remove it, sync, preview again. |+| `twin_has_withdrawals` | Claims were forgotten on the twin. Forget the same claims on the legacy page first, or retire the twin by hand. |+| `legacy_records_file_uri` | The legacy page records a file URI of its own; reconcile it first. |++The apply needs the user's consent: without `--yes` a terminal asks, and a+non-interactive run exits 3 (`ask_user`) with the consent payload and changes+nothing. Each approved pair is one coordinated write (an unmanaged brain does+the same in one transaction):++1. The legacy page records the file. It keeps its id, slug, links, timeline,+ versions and aliases.+2. The twin's links (both directions, without duplicating the legacy page's+ own; links between the two pages stay on the twin), timeline rows, slug+ aliases, facts other pages assert about it, raw data and attachments move+ to the legacy page. The twin's slug becomes an alias of the legacy page, so+ `[[notes/foo-bar]]` and `gbrain get notes/foo-bar` keep resolving.+3. The twin's sync import record moves to the legacy page, so the next+ `gbrain sync --source <id>` finds the file and the page unchanged: no new+ page, no hold, no file write.+4. The twin is soft-deleted as a shared origin: the file is not touched. Its+ tombstone forgets the file, so the autopilot purge removes it from the+ database 72 h later without refusing it as a page whose file another page+ records.++The legacy page keeps its slug: that is also the slug sync gives a never-forked+file whose legacy page it takes over (#6727), and the folded slug resolves to it+through the alias. The twin's tags, chunks, versions and the facts and takes its+own body projects stay with the twin (the legacy page has the same ones, from+the same content). Restoring the twin brings back a page that records no file;+what moved stays on the legacy page.++Each pair is checked again before its request, in preparation and under the+publication locks (both page ids, slugs and revisions, the recorded path, the+owner, the content and the file); a pair that moved is skipped+`changed_since_preview`. It refuses off the canonical owner host+([`not_owner_host`](error-codes.md#not_owner_host)), when the checkout cannot+be read ([`legacy_twins_storage_unknown`](error-codes.md#legacy_twins_storage_unknown)),+and when the pairs are more than half of the source's file-backed pages on a+source with more than 20 of them+([`legacy_twin_mass_merge_refused`](error-codes.md#legacy_twin_mass_merge_refused);+rerun with `GBRAIN_ALLOW_MASS_RECONCILE=1` only after the user agrees). A+preview lists at most 1,000 pairs and decisions; apply them, then preview+again. Trusted local CLI only; it runs only when named.+### Stale atoms`gbrain repair stale-atoms` (explicit-only) retires atoms that drifted fromdiff --git a/src/commands/repair.ts b/src/commands/repair.tsindex a808f47d41..5657f6867e 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -73,6 +73,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair stuck-recovery [--source <id>] [--request-id <uuid>][--keep prior|disk --apply --expect <preview-hash> --yes] [--json]gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]${REPAIR_CONTENT_HELP}Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -124,8 +125,8 @@ Options:stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).--request-id <uuid>stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages --apply: the user agreed to the previewed changes (destructive- consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins --apply: the user agreed to the previewed+ changes (destructive consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).Any other option is refused. --max-usd caps only a paid-model kind's model spend; to cap@@ -141,7 +142,7 @@ const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--inconst VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--side', '--state', '--keep', '--request-id', '--older-than']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {- '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages'],+ '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins'],'--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e69f90edc7..906e3b2778 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -342,6 +342,8 @@ export const CODES = {invalid_token: { class: 'host_only', summary: "The bearer token is missing, invalid, or revoked." },invalid_write_wait: { class: 'caller', summary: "Invalid write wait." },ipc_path_too_long: { class: 'host_only', summary: "The brain's local IPC socket path is longer than the operating system allows, even after the per-user run-dir fallback, so hooks and local commands cannot reach gbrain serve.", why: 'A Unix-domain socket path must fit sockaddr_un (107 bytes on Windows afunix, 103 on macOS); on Windows a long PGLite data-dir path already moves to %USERPROFILE%\\.gbrain\\run, and only a profile path too long for that is reported.', docs: 'docs/guides/troubleshooting.md#ipc-path-too-long', suggestion: 'Stop gbrain serve, move the brain to a shorter path (`gbrain config set database_path <shorter path>` after moving the data directory), then restart serve.', fix: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the socket path, its byte count and the limit.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'] } } },+ legacy_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair legacy-twins refused to merge legacy twin pairs that are more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to legacy twins: each merge soft-deletes a file-backed twin, and that many twins at once almost always means a re-import under another slug fold or the wrong checkout, not a backlog of forked pairs.", docs: 'docs/guides/repair.md#legacy-twins', suggestion: 'Check the source and its checkout on the owner host first. If merging these pairs is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is merged.", requires_exclusive: false } },+ legacy_twins_storage_unknown: { class: 'unavailable', summary: "Legacy twin pairs of a source cannot be checked because its canonical root is missing or is not a readable directory; nothing was listed or changed.", why: "Whether a twin's file is still there and agrees with it is only known from the checkout, so the repair fails closed rather than merge on a guess.", reasons: ['storage_unavailable'], docs: 'docs/guides/repair.md#legacy-twins', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair legacy-twins --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex fa98e16a78..9465d36fb2 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -533,6 +533,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(engine, row, config);if (row.intent?.kind === 'managed_maintenance_file_drift_remove') return (await import('../repair/file-drift.ts')).prepareDriftFileRemoval(engine, row);+ if (row.intent?.kind === 'managed_maintenance_merge_legacy_twin') return (await import('../repair/legacy-twins.ts')).prepareLegacyTwinMerge(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',`Request ${row.request_id} for ${row.slug} in ${row.source_id} carries a maintenance kind this gbrain version does not publish (likely queued by a newer release); nothing changed. Upgrade gbrain on the brain host, and read the receipt before submitting anything new.`,{ fix: receiptFix(row) });diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex f4f2b3db63..b5a063b1fd 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' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'legacy-twins' | 'receipt-compaction' | 'accepted-takes';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex ea2667e5f3..7d213d1ba4 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'legacy-twins'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/legacy-twins.ts b/src/core/repair/legacy-twins.tsnew file mode 100644index 0000000000..1dcbf79cfb--- /dev/null+++ b/src/core/repair/legacy-twins.ts@@ -0,0 +1,423 @@+/**+ * `gbrain repair legacy-twins --source <id>` (#6885): converge the page pairs older syncs forked before #6857.+ *+ * A pair is a legacy page (live, no recorded origin, not database-only, a slug the current `slugifyPath` folds+ * differently: an older gbrain imported the file under its raw name) and its twin (live, the folded slug, recording+ * the file as its origin). Since #6727 sync imports a never-forked file into the legacy page; already forked pairs+ * stay forked, and soft-deleting the twin by hand withdraws the file because no other live page records it.+ *+ * Explicit-only, preview-bound and destructive. The preview (read-only, bounded like the ghost-page scan) lists+ * every pair with both ids, slugs and revisions, the recorded path and whether the two pages hold the same content,+ * bound to the canonical owner it ran under; a pair it does not merge on its own is listed as a decision with the+ * commands a person uses to decide (two-sided content, several legacy candidates for one twin, a twin whose file is+ * missing or differs from it, withdrawn claims on the twin, a file at the twin's slug path). `--apply --expect <hash>+ * --yes` merges exactly the approved pairs, one coordinated write per pair (`managed_maintenance_merge_legacy_twin`+ * on the twin, holding the legacy page's key too; an unmanaged brain does the same in one maintenance transaction):+ *+ * 1. the legacy page records the file as its origin, keeping its id, slug, links, timeline, versions and aliases;+ * 2. the twin's links (both directions and as origin, deduplicated against the legacy page's own; links between+ * the pair stay), timeline rows, slug aliases, facts other pages assert about it, raw data rows the legacy page+ * lacks and file attachments move to the legacy page, and the twin's slug becomes a `slug_aliases` row for it;+ * 3. the twin's sync import record moves to the legacy page with its post-write revision, so the next sync sees+ * the file and the page both unchanged (the classifier's `matched`) instead of an unproven drift;+ * 4. the twin is soft-deleted as a shared origin: the file is untouched. Its tombstone forgets the file+ * (`source_path` and `source_uri` cleared), so the 72 h retention purge removes it database-only instead of+ * refusing it forever as a page whose file another live page records; a pair whose twin slug path holds a+ * file is a decision, so that purge has no file to compare or remove.+ *+ * Kept on the twin (they go with it when it is purged, and come back if it is restored): its tags, chunks and+ * embeddings, page versions, the facts and takes its own body projects and its derived per-page state. Both pages+ * hold the same content, so the legacy page already has the same projections.+ *+ * Apply re-checks each pair against the approved one (ids, slugs, revisions, recorded path, owner, same content,+ * the file still agreeing with the twin) and skips a moved pair `changed_since_preview`. Refuses off the owner+ * host (`not_owner_host`), when the checkout cannot be read (`legacy_twins_storage_unknown`) and, under the sync+ * mass-delete valve, when the pairs are more than half of the source's file-backed pages+ * (`legacy_twin_mass_merge_refused` unless `GBRAIN_ALLOW_MASS_RECONCILE=1`). Trusted local CLI only.+ */+import { existsSync, statSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';+import { isOpPageSlug } from '../ops/context.ts';+import { resolveSourceLocalFilePath } from '../markdown.ts';+import { slugifyPath } from '../sync.ts';+import { noteBelief } from '../belief/ledger.ts';+import { recordRenameAlias } from '../page-state/rename-alias.ts';+import { authorizeWrite } from '../persistence/authority.ts';+import { existingLocalHostId } from '../persistence/identity.ts';+import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { liveFileDrift } from '../persistence/drift-conflicts.ts';+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { readSyncImportProvenance, recordSyncImportProvenance, SYNC_IMPORT_PROVENANCE_OP } from '../persistence/sync-holds.ts';+import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';+import type { GhostOwner } from '../ghost-pages.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++export const LEGACY_TWINS_INTENT = 'managed_maintenance_merge_legacy_twin';+/** Pairs and decisions one preview lists; a larger set is applied in rounds (preview, apply, preview again). */+export const LEGACY_TWINS_LIMIT = 1000;+/** Pages without a recorded origin the scan reads per source. */+export const LEGACY_TWINS_SCAN_LIMIT = 250_000;+export const LEGACY_TWINS_PURGE_FUSE_HOURS = 72;+const BATCH = 10_000;+const DOCS = 'docs/guides/repair.md#legacy-twins';++export interface TwinPage { page_id: number; slug: string; revision: string }+export interface LegacyTwinPair { source_id: string; legacy: TwinPage; twin: TwinPage; path: string; import_record: boolean }+export type TwinDecisionReason = 'content_differs' | 'several_legacy' | 'file_missing' | 'file_drift' | 'file_unverified' | 'twin_slug_path_occupied'+ | 'legacy_records_file_uri' | 'twin_has_withdrawals' | 'twin_slug_unwritable';+export interface LegacyTwinDecision { source_id: string; reason: TwinDecisionReason; twin: TwinPage; legacy: TwinPage[]; path: string; commands: string[] }++interface ApprovedPair extends LegacyTwinPair { owner: GhostOwner; selection: string[] }+interface PairItem extends RepairItem { pair: LegacyTwinPair; owner: GhostOwner; hash: string; last: boolean }+interface PageRow { id: number | string; slug: string; revision: string; content_hash: string | null; source_path: string | null; source_uri: string | null }+type OwnerContext = { ok: true; root: string; owner: GhostOwner } | { ok: false; status: 'unknown' | 'not_applicable'; reason: string };++export const legacyTwinsPreviewCommand = (sourceId: string) => `gbrain repair legacy-twins --source ${sourceId}`;+const previewFix = (sourceId: string) => readFix('Previews the legacy twin pairs of the source again; writes nothing.',+ { argv: ['gbrain', 'repair', 'legacy-twins', '--source', sourceId, '--json'] });+const writerStatusFix = (sourceId: string) => readFix('Shows the source\'s canonical binding and owner host, read-only.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });++/** The consent payload of `--apply --expect <hash>` (registry `consentText`). */+export const LEGACY_TWINS_CONSENT_TEXT = {+ what: 'Merge each previewed legacy twin pair onto its legacy page and soft-delete the twin',+ why: 'The preview listed each pair with both pages, their revisions and the file the twin records; both pages hold the same content, so the legacy page (its id, links, timeline and history) takes over the file and the twin stops duplicating it.',+ risk: `The legacy page records the file; the twin's links, timeline rows and aliases move to it and the twin's slug becomes an alias of it. The twin is soft-deleted (the file stays) and purged by the autopilot purge phase ${LEGACY_TWINS_PURGE_FUSE_HOURS} h later. Restoring the twin brings back a page that records no file; its moved rows stay on the legacy page.`,+ user_message: `Merge the previewed legacy twin pairs onto their legacy pages? Each twin is soft-deleted (its file stays) and purged after ${LEGACY_TWINS_PURGE_FUSE_HOURS} h`,+};++/** The sync valve (#2828) over a source's file-backed pages. */+export function massTwins(pairs: number, fileBacked: number): boolean {+ return fileBacked > MASS_RECONCILE_MIN_PAGES && pairs > fileBacked * MASS_RECONCILE_RATIO;+}++const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id === b.host_id && a.worktree_id === b.worktree_id+ && a.owner_epoch === b.owner_epoch && a.source_incarnation === b.source_incarnation;+const page = (row: PageRow): TwinPage => ({ page_id: Number(row.id), slug: row.slug, revision: String(row.revision) });++async function ownerContext(engine: BrainEngine, sourceId: string): Promise<OwnerContext> {+ const hostId = existingLocalHostId();+ const binding = await getWorktreeBinding(engine, sourceId, hostId);+ if (!binding) return { ok: false, status: 'not_applicable', reason: 'not_applicable' };+ if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { ok: false, status: 'not_applicable', reason: 'not_owner_host' };+ const root = join(binding.local_path, binding.relative_path);+ try {+ if (!statSync(root).isDirectory()) return { ok: false, status: 'unknown', reason: 'storage_unavailable' };+ } catch {+ return { ok: false, status: 'unknown', reason: 'storage_unavailable' };+ }+ return { ok: true, root, owner: { host_id: hostId, worktree_id: binding.worktree_id, owner_epoch: String(binding.owner_epoch), source_incarnation: binding.source_incarnation } };+}++function ownerRefusal(sourceId: string, context: Extract<OwnerContext, { ok: false }>): OperationError {+ if (context.status === 'unknown') return opError('legacy_twins_storage_unknown', `Legacy twin pairs of source ${sourceId} cannot be checked: its canonical root is missing or is not a readable directory.`,+ `Nothing was listed or changed: whether a twin's file is still there is only known from the checkout. Inspect the source's checkout on the owner host (writer status shows its root), fix it, then preview again: ${legacyTwinsPreviewCommand(sourceId)}`,+ { reason: context.reason, fix: writerStatusFix(sourceId), docs: DOCS });+ return opError('not_owner_host', `Legacy twin pairs of source ${sourceId} can only be checked and merged on its canonical owner host.`,+ context.reason === 'not_applicable'+ ? `Source ${sourceId} has no canonical checkout, so no page records a file a twin could share; nothing was listed or changed.`+ : `This host does not own source ${sourceId}'s active canonical worktree, so it cannot check the files the twins record; nothing was listed or changed. Run ${legacyTwinsPreviewCommand(sourceId)} in a terminal on the owner host (writer status names it).`,+ { reason: context.reason, fix: writerStatusFix(sourceId), docs: DOCS });+}++export function massRefusal(sourceId: string, pairs: number, fileBacked: number): OperationError {+ return opError('legacy_twin_mass_merge_refused', `Refusing to merge ${pairs} legacy twin pair(s) of source ${sourceId}: that soft-deletes more than ${Math.round(MASS_RECONCILE_RATIO * 100)}% of its ${fileBacked} file-backed page(s).`,+ 'That many twins at once almost always means the source was re-imported under another slug fold or the wrong checkout is bound, not a backlog of forked pairs; nothing was changed. Check the source and its checkout on the owner host first. If merging these pairs is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.',+ { fix: writerStatusFix(sourceId), docs: DOCS });+}++/** What a person runs to decide a pair the repair does not merge on its own. */+function decisionCommands(sourceId: string, reason: TwinDecisionReason, twin: TwinPage, legacy: TwinPage[]): string[] {+ const show = [twin, ...legacy].map(p => `gbrain get --source ${sourceId} -- '${p.slug}'`);+ const preview = legacyTwinsPreviewCommand(sourceId);+ switch (reason) {+ case 'content_differs': return [...show, `Keep the legacy page: make its content and the twin's the same (edit the file and sync, or edit the legacy page), then run ${preview}.`,+ `Keep the twin instead: gbrain delete '${legacy[0]!.slug}' --source-id ${sourceId} (its id, links and history go with it).`];+ case 'several_legacy': return [...show, `Keep one legacy page: soft-delete the others with gbrain delete '<slug>' --source-id ${sourceId}, then run ${preview}.`];+ case 'file_missing': return [`gbrain repair ghost-pages --source ${sourceId} (the twin's file is gone: restore it from Git and sync, or remove the twin), then run ${preview}.`];+ case 'file_drift': return [`gbrain repair file-drift --source ${sourceId} --slug ${twin.slug} --prefer file (or --prefer database), then run ${preview}.`];+ case 'file_unverified': return [`gbrain sources writer status --source ${sourceId} --json (check the checkout), then run ${preview}.`];+ case 'twin_slug_path_occupied': return [`A file exists at the twin's own slug path (${twin.slug}.md), which the twin's purge would compare or remove: rename or remove that file and commit, sync, then run ${preview}.`];+ case 'legacy_records_file_uri': return [...show, `The legacy page records a file URI of its own; decide which file it belongs to with gbrain sources reconcile ${sourceId} '${legacy[0]!.slug}' --brain host --preview.`];+ case 'twin_has_withdrawals': return [...show, `Claims were forgotten on ${twin.slug}: forget the same claims on '${legacy[0]!.slug}' (gbrain forget), or soft-delete the twin by hand, then run ${preview}.`];+ case 'twin_slug_unwritable': return show;+ }+}++/** One pair's verdict: null when it merges, else the decision that holds it. */+async function pairVerdict(engine: BrainEngine, root: string, sourceId: string, twin: PageRow, legacy: PageRow[]): Promise<TwinDecisionReason | null> {+ if (legacy.length > 1) return 'several_legacy';+ const only = legacy[0]!;+ if (!isOpPageSlug(twin.slug)) return 'twin_slug_unwritable';+ if (only.source_uri?.startsWith('file:')) return 'legacy_records_file_uri';+ if (!twin.content_hash || twin.content_hash !== only.content_hash) return 'content_differs';+ const drift = await liveFileDrift(engine, sourceId, twin.slug);+ if (drift.reason === 'canonical_file_missing') return 'file_missing';+ if (drift.reason === 'file_database_drift') return 'file_drift';+ if (drift.reason !== 'agrees') return 'file_unverified';+ if (existsSync(resolveSourceLocalFilePath(root, undefined, twin.slug, undefined) ?? join(root, `${twin.slug}.md`))) return 'twin_slug_path_occupied';+ const [withdrawn] = await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1 AND subject=$2 LIMIT 1', [sourceId, twin.slug]);+ return withdrawn ? 'twin_has_withdrawals' : null;+}++export interface LegacyTwinScan { owner: GhostOwner; root: string; pairs: LegacyTwinPair[]; decisions: LegacyTwinDecision[]; file_backed: number; inspected: number; truncated: boolean }++const PAGE_COLUMNS = 'id, slug, knowledge_revision::text AS revision, content_hash, source_path, source_uri';++/**+ * Every pair of one source, in legacy page id order: pages without a recorded origin (and no database-only stamp)+ * whose slug folds differently are read in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), and the live pages at+ * their folded slugs that record a file are their twins. At most `LEGACY_TWINS_LIMIT` pairs and decisions.+ */+export async function scanLegacyTwins(engine: BrainEngine, sourceId: string): Promise<LegacyTwinScan> {+ const context = await ownerContext(engine, sourceId);+ if (!context.ok) throw ownerRefusal(sourceId, context);+ const byFold = new Map<string, PageRow[]>();+ let inspected = 0, truncated = false, after = 0;+ for (;;) {+ const rows = await engine.executeRaw<PageRow>(`SELECT ${PAGE_COLUMNS} FROM pages+ WHERE source_id=$1 AND deleted_at IS NULL AND COALESCE(btrim(source_path), '')='' AND database_only_reason IS NULL AND id > $2 ORDER BY id LIMIT ${BATCH}`, [sourceId, after]);+ for (const row of rows) {+ if (inspected >= LEGACY_TWINS_SCAN_LIMIT) { truncated = true; break; }+ inspected++;+ const folded = slugifyPath(row.slug);+ if (folded !== row.slug) byFold.set(folded, [...byFold.get(folded) ?? [], row]);+ }+ if (rows.length < BATCH || truncated) break;+ after = Number(rows[rows.length - 1]!.id);+ }+ const pairs: LegacyTwinPair[] = [], decisions: LegacyTwinDecision[] = [];+ const folds = [...byFold.keys()];+ for (let i = 0; i < folds.length && !(pairs.length + decisions.length >= LEGACY_TWINS_LIMIT); i += BATCH) {+ const twins = await engine.executeRaw<PageRow>(`SELECT ${PAGE_COLUMNS} FROM pages+ WHERE source_id=$1 AND deleted_at IS NULL AND slug=ANY($2::text[]) AND COALESCE(btrim(source_path), '')<>'' ORDER BY id `, [sourceId, folds.slice(i, i + BATCH)]);+ for (const twin of twins) {+ if (pairs.length + decisions.length >= LEGACY_TWINS_LIMIT) { truncated = true; break; }+ const legacy = byFold.get(twin.slug)!;+ const reason = await pairVerdict(engine, context.root, sourceId, twin, legacy);+ if (reason) {+ decisions.push({ source_id: sourceId, reason, twin: page(twin), legacy: legacy.map(page), path: twin.source_path!, commands: decisionCommands(sourceId, reason, page(twin), legacy.map(page)) });+ continue;+ }+ const record = await readSyncImportProvenance(engine, sourceId, context.owner.source_incarnation, Number(twin.id));+ pairs.push({ source_id: sourceId, legacy: page(legacy[0]!), twin: page(twin), path: twin.source_path!, import_record: record !== null });+ }+ }+ pairs.sort((a, b) => a.legacy.page_id - b.legacy.page_id);+ const [counted] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND COALESCE(btrim(source_path), '')<>''`, [sourceId]);+ return { owner: context.owner, root: context.root, pairs, decisions, file_backed: Number(counted?.n ?? 0), inspected, truncated };+}++function hashParts(scope: RepairScope, owner: GhostOwner, pairs: LegacyTwinPair[], decisions: LegacyTwinDecision[]) {+ return { kind: 'legacy-twins-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids }, owner, pairs,+ decisions: decisions.map(({ commands: _commands, ...decision }) => decision) };+}++function item(pair: LegacyTwinPair, owner: GhostOwner, hash: string, last: boolean): PairItem {+ return { cursor: { phase: 1, id: pair.legacy.page_id }, source_id: pair.source_id, slug: pair.twin.slug, chars: 0, action: 'merge:legacy_twin', pair, owner, hash, last };+}++const pairLine = (p: LegacyTwinPair) => `legacy ${p.legacy.slug} (id ${p.legacy.page_id}, revision ${p.legacy.revision}) takes over ${p.path} from twin ${p.twin.slug} (id ${p.twin.page_id}, revision ${p.twin.revision}); content matches`+ + (p.import_record ? '' : '; the twin has no sync import record, so the next sync compares the file with the legacy page again');++export const legacyTwinsRepair: RepairHandler = {+ kind: 'legacy-twins',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ if (opts?.remote === true) throw trustedCliRequired('gbrain repair legacy-twins runs only from the trusted local CLI on the brain host.');+ if (scope.source_ids.length !== 1) {+ throw opError('invalid_params', 'gbrain repair legacy-twins needs --source <id>.',+ 'Legacy twin pairs are checked on each source\'s own canonical owner host; name one source, e.g. gbrain repair legacy-twins --source default.',+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: DOCS });+ }+ const sourceId = scope.source_ids[0]!;+ const command = legacyTwinsPreviewCommand(sourceId);+ const scan = await scanLegacyTwins(engine, sourceId);+ const mass = massTwins(scan.pairs.length, scan.file_backed);+ if (!opts?.apply) {+ const hash = previewHash(hashParts(scope, scan.owner, scan.pairs, scan.decisions));+ if (scan.pairs.length) await saveApprovedSet<ApprovedPair>(engine, { command: 'legacy-twins', hash },+ scan.pairs.map(pair => ({ ...pair, owner: scan.owner, selection: scope.source_ids })));+ const warnings = [+ ...(mass ? [`${scan.pairs.length} pair(s) against ${scan.file_backed} file-backed page(s) (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses (legacy_twin_mass_merge_refused) unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the source first.`] : []),+ ...(scan.truncated ? [`More pairs may exist past the first ${LEGACY_TWINS_LIMIT} listed; apply this set, then preview again.`] : []),+ ...(scan.decisions.length ? [`${scan.decisions.length} pair(s) need a person's decision and are never merged by the apply; each lists the commands to decide it.`] : []),+ ...(scan.pairs.length ? [LEGACY_TWINS_CONSENT_TEXT.risk] : []),+ ];+ return { warnings, items: scan.pairs.map((pair, index) => item(pair, scan.owner, hash, index === scan.pairs.length - 1)), preview_hash: hash,+ residuals: { pairs: scan.pairs.length, decisions: scan.decisions.length, file_backed: scan.file_backed, inspected: scan.inspected },+ listing: [...scan.pairs.map(pair => ({ item: `${pair.source_id}:${pair.legacy.slug}`, class: 'merge', detail: pairLine(pair) })),+ ...scan.decisions.map(decision => ({ item: `${decision.source_id}:${decision.twin.slug}`, class: `decision:${decision.reason}`,+ detail: `twin ${decision.twin.slug} (id ${decision.twin.page_id}) records ${decision.path}; legacy ${decision.legacy.map(p => `${p.slug} (id ${p.page_id})`).join(', ')}` }))],+ details: { decisions: scan.decisions, mass_merge: mass, truncated: scan.truncated, purge_fuse_hours: LEGACY_TWINS_PURGE_FUSE_HOURS, docs: DOCS } };+ }+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair legacy-twins --apply merges only the set a preview printed.',+ `Preview first: ${command} — then, after the user agrees, run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`,+ { fix: previewFix(sourceId), docs: DOCS });+ }+ const approved = await loadApprovedSet<ApprovedPair>(engine, { command: 'legacy-twins', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(hashParts(scope, scan.owner, [], scan.decisions)) });+ if (approved.items.some(pair => JSON.stringify(pair.selection) !== JSON.stringify(scope.source_ids) || !sameOwner(scan.owner, pair.owner))) {+ throw previewChangedError(opts.expect, command);+ }+ if (massTwins(approved.items.length, scan.file_backed) && !massReconcileAllowed()) throw massRefusal(sourceId, approved.items.length, scan.file_backed);+ const items = approved.items.map(({ selection: _selection, owner, ...pair }, index) => item(pair, owner, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { pair, owner, hash, last } = entry as PairItem;+ const outcome = await mergeLegacyTwin(ctx, pair, owner,+ () => repairRequestId(ctx, 'legacy-twins', { source_id: pair.source_id, slug: pair.twin.slug }, `${pair.legacy.revision}:${pair.twin.revision}`));+ if (last) await clearApprovedSet(ctx.engine, { command: 'legacy-twins', hash });+ return outcome;+ },+ render(details) {+ const decisions = (details.decisions as LegacyTwinDecision[] | undefined) ?? [];+ return [...decisions.flatMap(decision => [` decision ${decision.reason}: twin ${decision.twin.slug} records ${decision.path}; legacy ${decision.legacy.map(p => p.slug).join(', ')}`,+ ...decision.commands.map(command => ` ${command}`)]),+ ` each merged twin: soft-deleted (its file stays), purged after ${details.purge_fuse_hours} h; guide: ${details.docs}`];+ },+};++const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });++/** Whether the pair is still the approved one under the approved owner; otherwise why not. */+async function pairNow(engine: BrainEngine, pair: LegacyTwinPair, owner: GhostOwner): Promise<string | null> {+ const context = await ownerContext(engine, pair.source_id);+ if (!context.ok || !sameOwner(context.owner, owner)) return 'the source\'s canonical owner changed since the preview';+ const rows = await engine.executeRaw<PageRow>(`SELECT ${PAGE_COLUMNS} FROM pages+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND deleted_at IS NULL AND database_only_reason IS NULL`, [pair.source_id, [pair.legacy.page_id, pair.twin.page_id]]);+ const legacy = rows.find(row => Number(row.id) === pair.legacy.page_id), twin = rows.find(row => Number(row.id) === pair.twin.page_id);+ if (!legacy || !twin) return 'one of the two pages was deleted, purged or stamped database-only';+ if (legacy.slug !== pair.legacy.slug || twin.slug !== pair.twin.slug) return 'one of the two pages was renamed';+ if (String(legacy.revision) !== pair.legacy.revision || String(twin.revision) !== pair.twin.revision) return 'one of the two pages has a new revision';+ if ((legacy.source_path ?? '').trim() || twin.source_path !== pair.path) return 'a recorded origin changed';+ const reason = await pairVerdict(engine, context.root, pair.source_id, twin, [legacy]);+ return reason ? `the pair needs a decision now (${reason})` : null;+}++/** Merges one approved pair; a managed brain submits it under `requestId()`. */+export async function mergeLegacyTwin(ctx: OperationContext, pair: LegacyTwinPair, owner: GhostOwner, requestId: () => Promise<string>): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const moved = await pairNow(engine, pair, owner);+ if (moved) return changed(moved);+ if (await managedPersistenceEnabled(engine)) {+ const authority = (await maintenancePreflight(engine, pair.source_id))!;+ try {+ await submitMaintenanceIntent(engine, authority, pair.twin.slug, { kind: LEGACY_TWINS_INTENT, expected_revision: pair.twin.revision, pair, owner }, await requestId());+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'source_changed'].includes(error.code)) return changed(error.message);+ throw error;+ }+ return { applied: true, outcome: 'merged' };+ }+ const locked = await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: pair.source_id, slug: pair.legacy.slug }, { sourceId: pair.source_id, slug: pair.twin.slug }]);+ const reason = await pairLocked(tx, pair);+ if (reason) return reason;+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [pair.source_id]);+ await applyTwinMerge(tx, pair, source!.incarnation);+ return null;+ });+ return locked ? changed(locked) : { applied: true, outcome: 'merged' };+}++/** Under the page keys: why the locked pair is no longer the approved one, or null. */+async function pairLocked(tx: BrainEngine, pair: LegacyTwinPair): Promise<string | null> {+ const legacy = await tx.readPageSnapshot(pair.legacy.slug, { sourceId: pair.source_id });+ const twin = await tx.readPageSnapshot(pair.twin.slug, { sourceId: pair.source_id });+ if (!legacy || Number(legacy.page.id) !== pair.legacy.page_id || legacy.revision !== pair.legacy.revision || (legacy.page.source_path ?? '').trim()) return 'the legacy page changed';+ if (!twin || Number(twin.page.id) !== pair.twin.page_id || twin.revision !== pair.twin.revision || twin.page.source_path !== pair.path) return 'the twin changed';+ return null;+}++/**+ * The merge itself, inside the caller's transaction with both page keys held: the legacy page records the file,+ * the twin's references move to it, the twin is soft-deleted with its recorded origin cleared, and the twin's import+ * record follows with the legacy page's post-write revision.+ */+async function applyTwinMerge(tx: BrainEngine, pair: LegacyTwinPair, incarnation: string): Promise<Record<string, unknown>> {+ const { source_id: sourceId, legacy, twin } = pair;+ const [twinRow] = await tx.executeRaw<{ source_uri: string | null }>('SELECT source_uri FROM pages WHERE id=$1', [twin.page_id]);+ const record = await readSyncImportProvenance(tx, sourceId, incarnation, twin.page_id);+ await tx.executeRaw('UPDATE pages SET source_path=NULL, source_uri=NULL WHERE id=$1', [twin.page_id]);+ await tx.executeRaw('UPDATE pages SET source_path=$2, source_uri=COALESCE(source_uri, $3) WHERE id=$1', [legacy.page_id, pair.path, twinRow?.source_uri ?? null]);+ const linkIds = (await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE (from_page_id=$1 AND to_page_id<>$2) OR (to_page_id=$1 AND from_page_id<>$2)',+ [twin.page_id, legacy.page_id])).map(row => Number(row.id));+ const statements: Array<[string, unknown[]]> = [+ [`DELETE FROM links s WHERE s.from_page_id=$1 AND s.to_page_id<>$2 AND EXISTS (SELECT 1 FROM links o WHERE o.from_page_id=$2 AND o.to_page_id=s.to_page_id+ AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [twin.page_id, legacy.page_id]],+ ['UPDATE links SET from_page_id=$2 WHERE from_page_id=$1 AND to_page_id<>$2', [twin.page_id, legacy.page_id]],+ [`DELETE FROM links s WHERE s.to_page_id=$1 AND s.from_page_id<>$2 AND EXISTS (SELECT 1 FROM links o WHERE o.to_page_id=$2 AND o.from_page_id=s.from_page_id+ AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [twin.page_id, legacy.page_id]],+ ['UPDATE links SET to_page_id=$2 WHERE to_page_id=$1 AND from_page_id<>$2', [twin.page_id, legacy.page_id]],+ [`DELETE FROM links s WHERE s.origin_page_id=$1 AND s.from_page_id<>$1 AND s.to_page_id<>$1 AND EXISTS (SELECT 1 FROM links o WHERE o.origin_page_id=$2+ AND o.from_page_id=s.from_page_id AND o.to_page_id=s.to_page_id AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source)`, [twin.page_id, legacy.page_id]],+ ['UPDATE links SET origin_page_id=$2 WHERE origin_page_id=$1 AND from_page_id<>$1 AND to_page_id<>$1', [twin.page_id, legacy.page_id]],+ [`DELETE FROM timeline_entries s WHERE s.page_id=$1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.page_id=$2 AND o.date=s.date+ AND md5(o.summary)=md5(s.summary) AND o.source=s.source)`, [twin.page_id, legacy.page_id]],+ ['UPDATE timeline_entries SET page_id=$2 WHERE page_id=$1', [twin.page_id, legacy.page_id]],+ ['DELETE FROM timeline_entries s WHERE s.event_page_id=$1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.event_page_id=$2 AND o.date=s.date)', [twin.page_id, legacy.page_id]],+ ['UPDATE timeline_entries SET event_page_id=$2 WHERE event_page_id=$1', [twin.page_id, legacy.page_id]],+ ['UPDATE raw_data r SET page_id=$2 WHERE r.page_id=$1 AND NOT EXISTS (SELECT 1 FROM raw_data o WHERE o.page_id=$2 AND o.source=r.source)', [twin.page_id, legacy.page_id]],+ ['UPDATE files SET page_id=$2, page_slug=$3 WHERE page_id=$1', [twin.page_id, legacy.page_id, legacy.slug]],+ [`UPDATE page_aliases a SET slug=$3 WHERE a.source_id=$1 AND a.slug=$2+ AND NOT EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id=$1 AND o.slug=$3 AND o.alias_norm=a.alias_norm AND o.origin=a.origin)`, [sourceId, twin.slug, legacy.slug]],+ ];+ for (const [sql, params] of statements) await tx.executeRaw(sql, params);+ const factIds = (await tx.executeRaw<{ id: number }>(`UPDATE facts SET entity_slug=$3 WHERE source_id=$1 AND entity_slug=$2+ AND source_markdown_slug IS DISTINCT FROM $2 RETURNING id`, [sourceId, twin.slug, legacy.slug])).map(row => Number(row.id));+ await recordRenameAlias(tx, sourceId, twin.slug, legacy.slug);+ const movedLinks = (await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE id=ANY($1::int[]) AND (from_page_id=$2 OR to_page_id=$2)', [linkIds, legacy.page_id])).map(row => Number(row.id));+ noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'links', ids: movedLinks });+ noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'facts', ids: factIds });+ await tx.createVersion(twin.slug, { sourceId });+ await tx.softDeletePage(twin.slug, { sourceId });+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:${twin.page_id}`]);+ if (record) {+ const [now] = await tx.executeRaw<{ revision: string }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1', [legacy.page_id]);+ await recordSyncImportProvenance(tx, { ...record, page_id: legacy.page_id, revision: now!.revision });+ }+ return { status: 'merged', legacy_slug: legacy.slug, twin_slug: twin.slug, source_id: sourceId, links_moved: movedLinks.length, facts_moved: factIds.length,+ import_record_moved: record !== null };+}++/**+ * Preparer for `managed_maintenance_merge_legacy_twin`, a request on the twin that also holds the legacy page's key:+ * re-checks the pair under the approved owner, publishes no file (the file already holds both pages' content and+ * stays), and re-checks both pages under the publication locks before the merge.+ */+export async function prepareLegacyTwinMerge(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {+ const pair = row.intent!.pair as LegacyTwinPair | undefined;+ const owner = row.intent!.owner as GhostOwner | undefined;+ if (!pair || !owner || pair.twin.slug !== row.slug || pair.source_id !== row.source_id || pair.twin.page_id !== Number(row.page_id)) {+ throw opError('invalid_params', 'The legacy twin merge intent does not name its pages.',+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the pair it merges, so nothing changed. Preview the repair again and apply the new preview after the user agrees.`,+ { fix: previewFix(row.source_id) });+ }+ const refuse = (reason: string) => opError('revision_conflict', 'The legacy twin pair changed since the preview.',+ `Pages ${pair.legacy.slug} and ${row.slug} in source ${row.source_id} changed after the preview (${reason}), so request ${row.request_id} merged nothing. Preview the repair again and apply the new preview after the user agrees.`,+ { fix: previewFix(row.source_id) });+ const moved = await pairNow(engine, pair, owner);+ if (moved) throw refuse(moved);+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ const prepared: PreparedMutation = { observedRevision: pair.twin.revision, additionalPageKeys: [{ sourceId: row.source_id, slug: pair.legacy.slug }],+ databaseOnlyReason: 'shared_origin',+ validate: async tx => {+ await authorizeWrite(tx, row.authority, 'submit_job', row.slug);+ const locked = await pairLocked(tx, pair);+ if (locked) throw refuse(locked);+ prepared.databaseOnlyWarning = `Twin ${row.slug} is hidden; ${pair.path} is untouched and now recorded by ${pair.legacy.slug}, which keeps its id, links and history; ${row.slug} resolves to it as an alias.`;+ },+ apply: async tx => applyTwinMerge(tx, pair, row.source_incarnation) };+ return prepared;+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 330b28df99..6619dbc681 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -66,6 +66,7 @@ import { frontmatterKeysRepair } from './frontmatter-keys.ts';import { fileDriftRepair } from './file-drift.ts';import { stuckRecoveryRepair } from './stuck-recovery.ts';import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';+import { legacyTwinsRepair, LEGACY_TWINS_CONSENT_TEXT, LEGACY_TWINS_PURGE_FUSE_HOURS } from './legacy-twins.ts';import { receiptCompactionRepair } from './receipt-compaction.ts';import { aliasesRepair } from './aliases.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';@@ -357,6 +358,17 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'of a page that still exists is never touched. Each target slug is rechecked under its page lock; coordinated maintenance write on a managed '+ 'brain, no journal admission. Runs only when named.',},+ 'legacy-twins': {+ handler: legacyTwinsRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: LEGACY_TWINS_CONSENT_TEXT,+ summary: 'Merge page pairs older syncs forked before #6857 (#6885): a legacy page with no recorded origin whose slug the current slug fold spells '+ + 'differently, and its twin at the folded slug recording the file. Needs --source; refused off the canonical owner host (not_owner_host). The preview '+ + 'lists each pair (both ids, slugs and revisions, the path, whether the content matches) and, as decisions never merged automatically, pairs whose '+ + 'content differs, several legacy candidates for one twin, and twins whose file is missing or drifted. --apply --expect <hash> --yes merges exactly '+ + 'the approved pairs, one coordinated write each: the legacy page records the file and keeps its id, links and history; the twin\'s links, timeline '+ + 'rows and aliases move to it, its slug becomes an alias, its sync import record follows, and the twin is soft-deleted with its file untouched '+ + `(purged after ${LEGACY_TWINS_PURGE_FUSE_HOURS} h). Refused when the pairs are over half of the source\'s file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Runs only when named.`,+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/e2e/repair-legacy-twins-6885-postgres.test.ts b/test/e2e/repair-legacy-twins-6885-postgres.test.tsnew file mode 100644index 0000000000..4eb4fa9ef9--- /dev/null+++ b/test/e2e/repair-legacy-twins-6885-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-legacy-twins-6885.test.ts'));diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 1445adcc5b..b5794399d1 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -196,7 +196,7 @@ for (const backend of testBackends()) {const previews = { 'accepted-takes': 'gbrain repair accepted-takes', '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', 'split-facts': 'gbrain repair split-facts',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',- 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases' };+ 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'legacy-twins': 'gbrain repair legacy-twins' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 1e7a28fbd9..b7820e9e67 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[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'legacy-twins'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-legacy-twins-6885.test.ts b/test/repair-legacy-twins-6885.test.tsnew file mode 100644index 0000000000..8360a3fa95--- /dev/null+++ b/test/repair-legacy-twins-6885.test.ts@@ -0,0 +1,311 @@+/**+ * #6885: page pairs older syncs forked before #6857. A legacy page (live, no recorded origin, a slug the current fold+ * spells differently) holds the id, links and history; its twin (the folded slug) records the file. `gbrain repair+ * legacy-twins` previews every pair and, after consent, merges each onto the legacy page in one coordinated write:+ * the legacy page records the file, the twin's links, timeline rows and aliases move to it, its slug becomes an alias,+ * its sync import record follows, and the twin is soft-deleted as a shared origin (the file stays). Protects: the+ * merge, the following sync (no new page, no hold, no file write, the classifier's `matched`), the twin tombstone's+ * 72 h purge (database-only, never refused as a shared origin), a pair whose content differs (a decision, never+ * merged), a pair that moved after the preview (`changed_since_preview`), the owner-host refusal, the mass valve and+ * the unmanaged brain's one-transaction merge. PGLite always; Postgres through the E2E wrapper.+ */+import { afterAll, afterEach, beforeAll, beforeEach, 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 { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitSourceHolds, readSyncImportProvenance } from '../src/core/persistence/sync-holds.ts';+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';+import { resolveRepairScope, type RepairKind } from '../src/core/repair/core.ts';+import { EXPLICIT_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.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 KIND = 'legacy-twins' as RepairKind;+const FILE = 'notes/Foo Bar.md', LEGACY = 'notes/foo bar', TWIN = 'notes/foo-bar';+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+let engine: BrainEngine;++interface Fixture { root: string; home: string; sourceId: string; ids: { legacy: number; twin: number; other: number; second: number } }++/** Raw rows written as an older gbrain left them: managed persistence off around the write, as the #6727 fixture does. */+async function raw<T>(fn: () => Promise<T>): Promise<T> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+}++/**+ * A managed source whose file FILE an older gbrain forked: sync imported it as the twin TWIN (recording the file, with+ * its import record), and a legacy page LEGACY with the same content and no recorded origin holds the inbound link,+ * a timeline row and an old alias. Two more files back notes/other and notes/second, which link to the pair.+ */+async function fixture(run: (f: Fixture) => Promise<void>, opts: { managed?: boolean; extra?: Record<string, string>; legacyBody?: string } = {}): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6885-'));+ const root = join(dir, 'brain'), home = join(dir, 'home');+ mkdirSync(join(root, 'notes'), { recursive: true });+ const sourceId = `twins-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ git(root, 'init', '-q');+ for (const [path, content] of Object.entries({ [FILE]: note('Foo Bar'), 'notes/other.md': note('other'), 'notes/second.md': note('second'), ...opts.extra })) {+ mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content);+ }+ git(root, 'add', '.'); commit(root, 'content');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) 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');+ expect((await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');+ const id = async (slug: string) => Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id);+ const twin = await id(TWIN), other = await id('notes/other'), second = await id('notes/second');+ const legacy = await raw(async () => {+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash)+ SELECT source_id, $2, type, title, COALESCE($3, compiled_truth), timeline, frontmatter, CASE WHEN $3::text IS NULL THEN content_hash ELSE md5($3::text) END+ FROM pages WHERE id=$1 RETURNING id`, [twin, LEGACY, opts.legacyBody ?? null]);+ const legacyId = Number(row!.id);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type) VALUES ($1,$2,'mentions'), ($3,$4,'mentions'), ($4,$1,'mentions'), ($2,$1,'mentions'), ($4,$2,'mentions')",+ [other, legacyId, second, twin]);+ await engine.executeRaw("INSERT INTO timeline_entries(page_id, date, summary) VALUES ($1,'2020-01-02','legacy history row'), ($2,'2021-03-04','twin timeline row')", [legacyId, twin]);+ await engine.executeRaw("INSERT INTO slug_aliases(source_id, alias_slug, canonical_slug, notes) VALUES ($1,'notes/old-name',$2,'rename')", [sourceId, LEGACY]);+ if (opts.managed === false) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ return legacyId;+ });+ if (opts.managed === false) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await run({ root, home, sourceId, ids: { legacy, twin, other, second } });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);+ rmSync(dir, { recursive: true, force: true });+ }+}++async function capture(fn: () => Promise<void>): Promise<string> {+ let printed = '';+ const original = console.log, write = process.stdout.write;+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;+ try { await fn(); } finally { console.log = original; process.stdout.write = write; }+ return printed;+}++async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const repair = async (sourceId: string, opts: { apply?: boolean; expect?: string } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))+ .run(KIND, await resolveRepairScope(engine, sourceId), { explicit: true, sourceFlag: sourceId, expect: opts.expect });+const pageRow = async (sourceId: string, id: number) => (await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null; deleted: boolean; revision: string }>(+ 'SELECT slug, source_path, source_uri, deleted_at IS NOT NULL AS deleted, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=$2', [sourceId, id]))[0];+const livePages = async (sourceId: string) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [sourceId])).map(row => row.slug);+const links = async (pageId: number) => (await engine.executeRaw<{ from_page_id: number; to_page_id: number }>(+ 'SELECT from_page_id, to_page_id FROM links WHERE from_page_id=$1 OR to_page_id=$1 ORDER BY from_page_id, to_page_id', [pageId])).map(row => [Number(row.from_page_id), Number(row.to_page_id)]);+const timeline = async (pageId: number) => (await engine.executeRaw<{ summary: string }>('SELECT summary FROM timeline_entries WHERE page_id=$1 ORDER BY summary', [pageId])).map(row => row.summary);+const holds = async (sourceId: string) => ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).map(hold => ({ path: hold.path, code: hold.code }));+const incarnation = async (sourceId: string) => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]))[0]!.incarnation;++for (const backend of testBackends()) describe(`#6885 repair legacy-twins (${backend})`, () => {+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;+ } else {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (closePostgres) await closePostgres(); else await engine.disconnect();+ });+ beforeEach(() => _resetCliExitVerdictForTests());+ afterEach(() => _resetCliExitVerdictForTests());++ test('preview lists the pair; consent refusal changes nothing; apply merges it onto the legacy page and keeps the file', () => fixture(async f => {+ const bytes = readFileSync(join(f.root, FILE), 'utf8');+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toContain(KIND);+ const preview = JSON.parse(await capture(() => runRepairCommand(engine, ['legacy-twins', '--source', f.sourceId, '--json']))).results[0];+ expect(preview.listing).toEqual([{ item: `${f.sourceId}:${LEGACY}`, class: 'merge', detail: expect.stringContaining(`takes over ${FILE} from twin ${TWIN}`) }]);+ expect(preview.apply_command).toBe(`gbrain repair legacy-twins --source ${f.sourceId} --apply --expect ${preview.preview_hash} --yes`);++ const priorExitCode = process.exitCode;+ await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['legacy-twins', '--source', f.sourceId, '--apply', '--expect', preview.preview_hash, '--json'])));+ expect(currentExitCode()).toBe(3);+ process.exitCode = priorExitCode ?? 0;+ _resetCliExitVerdictForTests();+ expect((await pageRow(f.sourceId, f.ids.twin))!.deleted).toBe(false);+ expect((await pageRow(f.sourceId, f.ids.legacy))!.source_path).toBeNull();++ const legacyBefore = (await pageRow(f.sourceId, f.ids.legacy))!;+ const applied = JSON.parse(await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['legacy-twins', '--source', f.sourceId, '--apply', '--expect', preview.preview_hash, '--yes', '--json'])))).results[0];+ expect(applied).toMatchObject({ mode: 'apply', applied: 1, skipped: 0, failed: [], complete: true, outcomes: { merged: 1 } });++ expect(readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);+ expect(await pageRow(f.sourceId, f.ids.legacy)).toMatchObject({ slug: LEGACY, source_path: FILE, deleted: false });+ expect((await pageRow(f.sourceId, f.ids.legacy))!.revision).toBe(legacyBefore.revision);+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ slug: TWIN, source_path: null, source_uri: null, deleted: true });+ // Links: the inbound link to the twin moved; the twin's outbound duplicate of the legacy page's own link collapsed; the pair's own link stayed.+ expect(await links(f.ids.legacy)).toEqual([[f.ids.legacy, f.ids.other], [f.ids.other, f.ids.legacy], [f.ids.second, f.ids.legacy], [f.ids.twin, f.ids.legacy]].sort((a, b) => a[0]! - b[0]! || a[1]! - b[1]!));+ expect(await timeline(f.ids.legacy)).toEqual(['legacy history row', 'twin timeline row']);+ const alias = await engine.readPageSnapshot(TWIN, { sourceId: f.sourceId, resolveAlias: true });+ expect(Number(alias!.page.id)).toBe(f.ids.legacy);+ expect(Number((await engine.readPageSnapshot('notes/old-name', { sourceId: f.sourceId, resolveAlias: true }))!.page.id)).toBe(f.ids.legacy);+ const inc = await incarnation(f.sourceId);+ expect(await readSyncImportProvenance(engine, f.sourceId, inc, f.ids.twin)).toBeNull();+ expect(await readSyncImportProvenance(engine, f.sourceId, inc, f.ids.legacy)).toMatchObject({ page_id: f.ids.legacy, origin: FILE, revision: legacyBefore.revision });++ // The next managed sync is a no-op: no new page, no hold, no file write, and a full walk agrees.+ const pagesBefore = await livePages(f.sourceId);+ expect(['up_to_date', 'synced']).toContain((await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true })).status);+ await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true, full: true });+ expect(await livePages(f.sourceId)).toEqual(pagesBefore);+ expect(await holds(f.sourceId)).toEqual([]);+ expect(readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);+ expect(git(f.root, 'status', '--porcelain')).toBe('');+ expect(await pageRow(f.sourceId, f.ids.legacy)).toMatchObject({ slug: LEGACY, source_path: FILE, deleted: false });+ // The 4a classifier (a full round reparses every live page by obligation, so the shadow level is read without one): the file settles as `matched` on the legacy page, like an untouched file.+ const level = await readShadowLevel(engine, { sourceId: f.sourceId });+ const classified = (path: string) => { const p = level!.paths.find(entry => entry.path === path)!; return { cls: p.result.cls, pageId: p.pageId, slug: p.slug }; };+ expect(classified(FILE)).toEqual({ cls: 'matched', pageId: f.ids.legacy, slug: LEGACY });+ expect(classified('notes/other.md')).toEqual({ cls: 'matched', pageId: f.ids.other, slug: 'notes/other' });++ // The twin's tombstone is purged by the 72 h retention purge, database-only: never refused as a shared origin, and the file stays.+ await raw(() => engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '73 hours' WHERE id=$1", [f.ids.twin]));+ const purged = await purgeDeletedPagesCoordinated(engine, 72);+ expect({ count: purged.count, blocked: purged.blocked }).toEqual({ count: 1, blocked: [] });+ expect(await pageRow(f.sourceId, f.ids.twin)).toBeUndefined();+ expect(readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);+ expect(Number((await engine.readPageSnapshot(TWIN, { sourceId: f.sourceId, resolveAlias: true }))!.page.id)).toBe(f.ids.legacy);+ await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true, full: true });+ expect(await livePages(f.sourceId)).toEqual(pagesBefore);+ expect(await holds(f.sourceId)).toEqual([]);+ }), 180_000);++ test('a pair whose content differs is listed as a decision and never merged', () => fixture(async f => {+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBe(0);+ expect(preview.listing).toEqual([{ item: `${f.sourceId}:${TWIN}`, class: 'decision:content_differs', detail: expect.stringContaining(`legacy ${LEGACY}`) }]);+ const decision = (preview.details!.decisions as Array<{ commands: string[] }>)[0]!;+ expect(decision.commands.join('\n')).toContain(`gbrain get --source ${f.sourceId} -- '${LEGACY}'`);+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 0, failed: [] });+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ deleted: false, source_path: FILE });+ expect((await pageRow(f.sourceId, f.ids.legacy))!.source_path).toBeNull();+ }, { legacyBody: 'An edited legacy body that the file never had.\n' }), 180_000);++ test('a page that moved after the preview is skipped changed_since_preview; nothing changes', () => fixture(async f => {+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBe(1);+ await raw(() => engine.executeRaw("UPDATE pages SET title='Renamed after the preview' WHERE id=$1", [f.ids.legacy]));+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 0, skipped: 1, outcomes: { changed_since_preview: 1 } });+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ deleted: false, source_path: FILE });+ expect((await pageRow(f.sourceId, f.ids.legacy))!.source_path).toBeNull();+ expect(await links(f.ids.twin)).toContainEqual([f.ids.second, f.ids.twin]);+ }), 180_000);++ test('off the owner host the preview and the apply refuse not_owner_host', () => fixture(async f => {+ const hash = (await repair(f.sourceId)).preview_hash!;+ await withEnv({ GBRAIN_HOME: join(f.home, '..', 'other-host') }, async () => {+ expect((await refusal(() => repair(f.sourceId))).code).toBe('not_owner_host');+ expect((await refusal(() => repair(f.sourceId, { apply: true, expect: hash }))).code).toBe('not_owner_host');+ });+ expect((await pageRow(f.sourceId, f.ids.twin))!.deleted).toBe(false);+ }), 180_000);++ test('the mass valve refuses when the pairs are over half of the file-backed pages', () => fixture(async f => {+ const extra = Array.from({ length: 24 }, (_, i) => `notes/Extra ${String(i).padStart(2, '0')}.md`);+ await raw(async () => {+ for (const path of extra) {+ const twinSlug = `notes/extra-${path.slice(12, 14)}`;+ await engine.executeRaw(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash)+ SELECT source_id, $2, type, title, compiled_truth, timeline, frontmatter, content_hash FROM pages WHERE source_id=$1 AND slug=$3`,+ [f.sourceId, path.replace(/\.md$/, '').toLowerCase(), twinSlug]);+ }+ });+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBeGreaterThan(13);+ expect(preview.warnings?.[0]).toContain('legacy_twin_mass_merge_refused');+ expect((await refusal(() => repair(f.sourceId, { apply: true, expect: preview.preview_hash }))).code).toBe('legacy_twin_mass_merge_refused');+ expect((await pageRow(f.sourceId, f.ids.twin))!.deleted).toBe(false);+ }, { extra: Object.fromEntries(Array.from({ length: 24 }, (_, i) => [`notes/Extra ${String(i).padStart(2, '0')}.md`, note(`Extra ${i}`)])) }), 180_000);++ test('a pair moved while its request waits for preparation or publication is refused and nothing changes', async () => {+ for (const point of ['consumer:preparing', 'consumer:prepared'] as const) await fixture(async f => {+ const preview = await repair(f.sourceId);+ installFaultHook(async (at, detail) => {+ if (at === point && detail.operation === 'submit_job') await raw(() => engine.executeRaw("UPDATE pages SET title='Edited mid-flight' WHERE id=$1", [f.ids.legacy]));+ });+ try {+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect({ point, applied: applied.applied, skipped: applied.skipped, outcomes: applied.outcomes }).toEqual({ point, applied: 0, skipped: 1, outcomes: { changed_since_preview: 1 } });+ } finally { installFaultHook(undefined); }+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ deleted: false, source_path: FILE });+ expect((await pageRow(f.sourceId, f.ids.legacy))!.source_path).toBeNull();+ expect(await links(f.ids.twin)).toContainEqual([f.ids.second, f.ids.twin]);+ });+ }, 180_000);++ test('several legacy pages folding to one twin are one decision; nothing is merged', () => fixture(async f => {+ await raw(() => engine.executeRaw(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash)+ SELECT source_id, 'notes/foo bar', type, title, compiled_truth, timeline, frontmatter, content_hash FROM pages WHERE id=$1`, [f.ids.legacy]));+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBe(0);+ expect(preview.listing).toEqual([{ item: `${f.sourceId}:${TWIN}`, class: 'decision:several_legacy', detail: expect.stringContaining('notes/foo bar') }]);+ expect((await pageRow(f.sourceId, f.ids.twin))!.deleted).toBe(false);+ }), 180_000);++ test('why the repair exists: a hand delete of the twin withdraws the file, and a tombstone that keeps its origin is never purged', () => fixture(async f => {+ const bytes = readFileSync(join(f.root, FILE), 'utf8');+ const ctx = { engine, sourceId: f.sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ // The legacy page records nothing, so the twin's file has no other claimant: delete_page removes it (#6885).+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: TWIN, expected_revision: (await pageRow(f.sourceId, f.ids.twin))!.revision, request_id: randomUUID() } });+ expect(existsSync(join(f.root, FILE))).toBe(false);+ // Put the file back and let the legacy page record it, but leave the twin's tombstone recording it too: the retention purge refuses it as a shared origin, every run.+ writeFileSync(join(f.root, FILE), bytes);+ await raw(async () => {+ await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.ids.legacy, FILE]);+ await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.ids.twin, FILE]);+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '73 hours' WHERE id=$1", [f.ids.twin]);+ });+ const purged = await purgeDeletedPagesCoordinated(engine, 72);+ expect(purged.count).toBe(0);+ expect(purged.blocked.map(entry => ({ slug: entry.slug, code: entry.code }))).toEqual([{ slug: TWIN, code: 'source_changed' }]);+ expect(purged.blocked[0]!.reason).toContain('shared with another live page');+ expect(readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);+ }), 180_000);++ test('an unmanaged brain merges the pair in one maintenance transaction', () => fixture(async f => {+ const bytes = readFileSync(join(f.root, FILE), 'utf8');+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBe(1);+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 1, outcomes: { merged: 1 } });+ expect(await pageRow(f.sourceId, f.ids.legacy)).toMatchObject({ source_path: FILE, deleted: false });+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ source_path: null, deleted: true });+ expect(await timeline(f.ids.legacy)).toEqual(['legacy history row', 'twin timeline row']);+ expect(existsSync(join(f.root, FILE)) && readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);+ }, { managed: false }), 180_000);+});diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex 4dad52a54f..4e620745b9 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -68,6 +68,7 @@ const EXEMPT: Record<string, string> = {'src/core/trust/owner-actions.ts': 'owner release publishes a held row the owner confirmed (CEO-9); the gate already held it','src/core/trust/supersede-handlers.ts': 'owner accept/undo re-tiers existing rows inside the checked supersede','src/core/repair/conversation-labels.ts': 'owner repair of existing conversation labels',+ 'src/core/repair/legacy-twins.ts': 'owner repair moving existing rows of a twin page onto its legacy page; it writes no new content','src/commands/extract-conversation-facts.ts': 'extracted rows go through insertDerivedFacts (persistence/derived-facts.ts), which gates them; its direct writes are gbrain audit outcome rows','src/core/cycle/dream-taint.ts': 'the dream summary index page lists the run\'s output pages (gbrain-generated), stamped at their taint','src/core/facts/fence-write.ts': 'callers decide the gate (backstop, loops-extract) and pass the decision; it records the flag receipt on the new row',