Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair segmented-mirror re-mirrors files older binaries left holding withdrawn rows (LPH a)

garrytan0f5e146d60ab
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index b1c474b854..91dc583440 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -24,3 +24,5 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete, after the belief-ledger expiry of recorded sources' tombstones: each is its own transaction and item (ItemRun site `purge.recorded_tombstones`), a run-scoped failure or a systemic run stops the purge, and any other failure lists the tombstone in `blocked` with its classified code, counts it in `failed` (no `error`, so the phase warns) and keeps it out of the bulk delete (`purgeDeletedPages` `excludeIds`); a content failure counts toward the same park as the managed purge, a transient one is retried next run, and parked tombstones are skipped as `purge_parked` unless `retryParked` (the unmanaged preview excludes them too). A managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run); #6884: the run submits only while the writer has outstanding-request room (`readOutstandingRoom` in `journal.ts`, at `persistence.capacity.background_pause_pct` of the cap for a background run); the rest, and the rest after a `queue_capacity` refusal, is `blocked` as `write_capacity_deferred` and counted in `capacity_deferred`, never a failure or a park. `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`; warn on `writer_not_active`, parked, capacity-deferred or an unmanaged `failed` tombstone). The engine bulk delete (`engine-sql/pages.ts` `purgeDeletedPages`) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced. Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`, `test/purge-deleted-capacity-6884.test.ts`, `test/pathological/a49-unmanaged-purge-tombstones.test.ts`.
- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. Tests: `test/purge-deleted-parks.test.ts`.
+
+- `src/core/repair/segmented-mirror.ts` — `gbrain repair segmented-mirror` (LPH a), explicit-only, preview-bound, destructive consent, `checks: []` (no doctor scan: detection reads every segmented file). `scanSegmentedMirrors` (read-only, owner host; a non-owner source is held `not_owner_host`) walks live `body_storage='segmented'` pages of sources with a worktree binding whose snapshot ledger applies (`ledgerApplies`), runs `prepareFileTarget(..., null, { allowMissing })` (the mirror's own drift check; `file_database_drift` or any other `OperationError` is held, never rewritten), then lists the page only when overlaying the ledger on the file's facts fences changes its region digests (`fileBodyDigests` vs `overlaidFileBodyDigests` over `FileBytes`, bounded memory) and the streamed render (`unreadPageFile`) hashes differently. The hash (`segmented-mirror-v1`) binds source selection, slug, page id, revision, path and both SHA-256s; the approved set lives in `op_checkpoints`. Apply re-checks revision and file hash of every page not yet admitted (`preview_changed`), then per page admits and commits, in one transaction like a withdrawal, a `repair_segmented_mirror` request (request id derived from the hash; its receipt) that inserts a version-2 targeted `withdrawal-mirror` + `git` effect (no embedding); it wakes this process's consumer and waits up to the write wait for them (`mirrored` / `mirror_queued` / `held` / `failed`; a replay is `replayed`). Test: `test/pathological/lp-a-segmented-mirror.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 513326228d..6e3c3ceb5d 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -9,7 +9,7 @@ fixes those and the other kinds listed in
[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless
you pass `--apply`.
The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `extractor-facts`,
-`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `stuck-recovery`, `aliases` and `rename-identity`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
+`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget
(see [Run repairs through doctor](#run-repairs-through-doctor)).
@@ -150,6 +150,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different content, with no later revision holding the edit again. The preview diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |
| `missing-tables` | `schema_missing_tables` | Explicit-only, preview-bound. Recreates, empty, a rebuildable cache table (`query_cache`, `code_traversal_cache`) that the applied migrations created but the brain no longer has, on a brain whose schema version already covers its creating migration, so `apply-migrations` never recreates it (#6911). DDL only (`IF NOT EXISTS`), no journal admission, brain-wide. See [missing tables](#missing-tables). | `user_data_tables`: a missing table that holds user data; this repair never recreates it, so restore its rows from a backup first. `other_tables`: a missing table that holds no user data; `gbrain init --migrate-only` recreates it if the base schema defines it. |
+| `segmented-mirror` | none (doctor does not read segmented files; run the preview once if the brain ran a version before v0.60.299.0) | Explicit-only, preview-bound, destructive consent. Rewrites the canonical file of a page stored in segments that an older binary's withdrawal mirror passed by (`page_body_segmented`), so the file still holds a row `forget`, `forget_fact` or `purge_fact` removed from the database. The file becomes the page's canonical render (`gbrain export`'s bytes), written by the withdrawal mirror and committed by its Git effect. See [segmented mirror](#segmented-mirror). | `file_database_drift`: the file also differs from the database for another reason; it is listed held and never rewritten. `not_owner_host`: the preview ran off the source's owner host and read none of its files. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -315,6 +316,66 @@ one table.
The repair runs only when named and never on upgrade, `apply-migrations`,
`db-repair` or the maintenance cycle.
+<a id="segmented-mirror"></a>
+### Segmented mirror
+
+Before v0.60.299.0, a withdrawal (`forget`, `forget_fact` or `purge_fact`) of
+a row in a page stored in segments struck the row in the database, but the
+withdrawal mirror and Git walk skipped the page (`skipped` reason
+`page_body_segmented`). Its canonical file kept the withdrawn or purged row.
+Current versions mirror such a page, but upgrading rewrites nothing, so a file
+an older binary left behind keeps the row until this repair runs. Doctor does
+not look for these files, because finding one means reading every segmented
+page file in full. Run the preview once on each source's owner host if the
+brain ever ran an older version with `pages.segmented_storage` on.
+
+**Say to your agent:** *"We forgot facts on big pages before upgrading. Make
+sure the files don't still have them."*
+
+```bash
+gbrain repair segmented-mirror --source notes # read-only: each stale file, its hash and size, the render's, and a hash
+gbrain repair segmented-mirror --source notes --apply --expect <preview-hash> --yes
+```
+
+The preview reads each live, file-backed segmented page of a source that has
+withdrawals. Files are hashed in pieces and never held whole. A page is listed
+when its file is an older render the repair can explain:
+
+- the file passes the check the withdrawal mirror itself runs before it
+ rewrites a file: with the withdrawals applied to its facts fences, the file
+ matches the stored page; and
+- applying the withdrawals changes the file, so it still holds a withdrawn or
+ purged row.
+
+Each listed page shows its path, the file's SHA-256 and size, and the SHA-256
+and size of the page's canonical render: the bytes `gbrain export` writes for
+it. A file that differs from the database for any other reason, such as a
+local edit, is listed as held with `file_database_drift` and the
+`gbrain sources reconcile ... --preview` command. It is never overwritten:
+reconcile it, then preview again. A clean segmented file and an inline page are
+never listed.
+
+The apply re-checks every listed page first. If a page's revision or its file's
+hash changed since the preview, the apply refuses with `preview_changed` and
+writes nothing. Run the preview again and use the new hash. Each page then gets
+one write request (`operation: repair_segmented_mirror`, its request id derived
+from the hash). That request is the page's receipt; read it with
+`gbrain write-request <request id>`. It commits a withdrawal-mirror effect and
+a Git effect for the page, and the existing mirror does the rewrite. The mirror
+keeps its recovery record, streamed staging file, owner and lock checks, and its
+own file/database check. The Git effect commits the file. Outcomes are
+`mirrored`, `mirror_queued` (the owner's consumer has not run it yet; preview
+again later), `held` (the mirror's own check refused the file) or `failed`
+(the mirror's error code). Replaying an apply with the same hash finds each
+receipt and writes nothing (`replayed`).
+
+The rewrite replaces the file with the page's canonical render, so any other
+formatting differences in it are normalized as well. The old bytes stay in
+earlier Git commits; this repair does not rewrite history.
+
+The repair runs only when named and never on upgrade, `apply-migrations` or the
+maintenance cycle.
+
<a id="request-growth"></a>
### Request-table growth
@@ -2759,7 +2820,7 @@ Each heading below is the `docs` anchor a refusal carries.
### Explicit-only repair kinds
`google-file-modes`, `stale-atoms`, `extractor-facts`, `captured-facts`,
-`loop-facts`, `ontology-facts`, `file-drift` and `missing-tables` run only when named: `gbrain repair <kind>` previews, and
+`loop-facts`, `ontology-facts`, `file-drift`, `missing-tables` and `segmented-mirror` run only when named: `gbrain repair <kind>` previews, and
`gbrain repair <kind> --apply` applies (every kind but `google-file-modes`
also needs `--expect <hash>`, so it applies exactly the previewed set; `google-file-modes` re-checks each file's owner,
type and mode at apply time). They are excluded everywhere else:
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 79c501e37e..e8578d4d72 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -478,6 +478,7 @@ src/core/repair/overwritten-edits.ts versionMarkdown call:serializePageToMarkdow
src/core/repair/overwritten-edits.ts versionMarkdown field SEGW inline versions only: overwriteContent returns null for a segmented version, which answers version_changed
src/core/repair/overwritten-edits.ts versionMarkdown sql SEGW selects body_storage; a segmented version answers version_changed
src/core/repair/safe-chunks.ts safeChunksRepair sql META
+src/core/repair/segmented-mirror.ts fileHoldsWithdrawnRows field NONE the overlay result of one file fragment (a facts fence block) for the region digests (body-digests.ts); no page body is read
src/core/repair/slug-conflicts.ts pageContent call:serializePageToMarkdown SEGW
src/core/repair/split-facts.ts mergeOne call:serializePageToMarkdown SEGW
src/core/repair/split-facts.ts mergeSplitFacts call:serializePageToMarkdown SEGW
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3d3753be42..29bb8dcc77 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -903,6 +903,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
+ { since: 'TBD', text: 'New `gbrain repair segmented-mirror [--source <id>]` for brains that ran a gbrain older than v0.60.299.0 with `pages.segmented_storage` on: on those versions a withdrawal (`forget`, `forget_fact`, `purge_fact`) of a row in a page stored in segments struck it in the database but left the page\'s canonical file holding it (the mirror skipped the page with `page_body_segmented`). Upgrading does not rewrite those files. Run the preview on the source\'s owner host: it lists each file-backed segmented page whose file still holds a withdrawn or purged row and otherwise matches the database, with the file\'s SHA-256 and size and those of the page\'s canonical render (`gbrain export`\'s bytes), and prints a hash; a file that also differs from the database for another reason is listed held (`file_database_drift`) and never rewritten. `--apply --expect <hash> --yes` rewrites each listed file to that render through the withdrawal mirror (one receipted write request per page, `operation: repair_segmented_mirror`) and its Git effect commits it; a file or page that changed since the preview refuses the apply with `preview_changed`. Doctor does not scan for these files (that needs every segmented file read), so run the preview once if this brain ever ran such a version.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 469cfa3cec..461a866486 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' | 'facts-rehome' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables' | 'segmented-mirror';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 93748d0278..3a7e34e627 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.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', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] 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', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'segmented-mirror'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 4ed6334402..427e5b6974 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -73,6 +73,7 @@ import { aliasesRepair } from './aliases.ts';
import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';
import { overwrittenEditsRepair } from './overwritten-edits.ts';
import { missingTablesRepair } from './missing-tables.ts';
+import { segmentedMirrorRepair } from './segmented-mirror.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -405,6 +406,22 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'recreated. DDL only (IF NOT EXISTS), no journal admission. The preview prints a hash; --apply --expect <hash> recreates exactly that set. '
+ 'Runs only when named; never on upgrade. Brain-wide.',
},
+ 'segmented-mirror': {
+ handler: segmentedMirrorRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Rewrite the previewed canonical files of pages stored in segments without their withdrawn or purged rows',
+ why: 'The preview listed each file an older binary left holding a row a withdrawal or purge removed from the database; the apply rewrites each one to the page\'s canonical render through the withdrawal mirror.',
+ risk: 'Each listed file is replaced by the bytes gbrain export writes for its page (other formatting differences in it are normalized the same way). A file that changed since the preview refuses the apply (preview_changed), and one that differs from the database for any other reason is never rewritten. The Git effect commits the change; the old bytes stay in earlier commits.',
+ user_message: 'Rewrite the previewed page files without their withdrawn rows? Each becomes the page\'s canonical render',
+ },
+ summary: 'Re-mirror the canonical files of pages stored in segments whose withdrawal mirror an older binary (before v0.60.299.0) passed by '
+ + '(skipped page_body_segmented), so the file still holds a row forget, forget_fact or purge_fact removed from the database. The preview, '
+ + 'on the source\'s owner host and in bounded memory, lists each file-backed segmented page whose file is an older render: it passes the '
+ + 'mirror\'s own file/database check and still holds a withdrawn or purged row; it prints the path, the file\'s SHA-256 and size and those '
+ + 'of the canonical render (gbrain export\'s bytes). A file that differs from the database for another reason is listed held '
+ + '(file_database_drift) and never rewritten. Preview-bound and destructive: --apply --expect <hash> --yes re-checks each page and commits, per '
+ + 'page, one receipted request whose withdrawal-mirror and Git effects rewrite and commit the file. Runs only when named; never on upgrade.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/src/core/repair/segmented-mirror.ts b/src/core/repair/segmented-mirror.ts
new file mode 100644
index 0000000000..ca616f7b83
--- /dev/null
+++ b/src/core/repair/segmented-mirror.ts
@@ -0,0 +1,269 @@
+/**
+ * `gbrain repair segmented-mirror [--source <id>]`: re-mirror the canonical files of pages stored in segments that an
+ * older binary's withdrawal mirror passed by. Before v0.60.299.0 a withdrawal (`forget`, `forget_fact`, `purge_fact`)
+ * struck the row in the page's segments but skipped its file (`skipped` reason `page_body_segmented`), so the file can
+ * still hold the withdrawn or purged row.
+ *
+ * Preview (read-only, on the source's owner host): every live, file-backed segmented page of a source with a withdrawal
+ * ledger is checked in bounded memory. A page is listed when its file is an older render the repair can explain: the
+ * file passes the same file/database check the withdrawal mirror runs (the ledger overlaid on the file's facts fences
+ * matches the stored body), and overlaying the ledger changes the file (it still holds a withdrawn or purged row). Each
+ * listed page names its file's SHA-256 and size and those of the canonical render (`gbrain export`'s bytes, streamed
+ * from the segments). A file that differs from the database for any other reason (`file_database_drift`) is listed as
+ * held with the reconcile preview and is never overwritten. The hash binds the listed pages, their revisions and both
+ * file hashes.
+ *
+ * `--apply --expect <hash> --yes` re-checks every listed page (revision and file hash, else `preview_changed`) and admits,
+ * per page, one journal request (its receipt, request id derived from the hash) that commits a targeted
+ * `withdrawal-mirror` and `git` effect for that page: the existing mirror (recovery record, staged stream, owner checks,
+ * native lock, drift check) rewrites the file and the Git effect commits it. An apply replayed with the same hash is a
+ * no-op. Explicit-only: never from `--all`, a remediation plan or an upgrade.
+ */
+import { existsSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { fileBodyDigests, overlaidFileBodyDigests } from '../page-body/body-digests.ts';
+import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
+import { fenceTooLargeError } from '../page-body/read-range.ts';
+import { FileBytes } from '../persistence/large-file.ts';
+import { getWorktreeBinding } from '../persistence/ownership.ts';
+import { localHostId } from '../persistence/identity.ts';
+import { prepareFileTarget, unreadPageFile } from '../persistence/page-prepare.ts';
+import { loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { admitWriteInTransaction, completeWrite, getWriteRequest } from '../persistence/journal.ts';
+import { submissionAuthority } from '../persistence/authority.ts';
+import { declareDurablePersistence } from '../persistence/protocol.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { requestAttribution } from '../persistence/attribution.ts';
+import { retryWriteAdmission } from '../persistence/admission-retry.ts';
+import { isTerminal, type WriteRequest } from '../persistence/model.ts';
+import { digest } from '../persistence/digest.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+export const SEGMENTED_MIRROR_OPERATION = 'repair_segmented_mirror';
+const DOCS = 'docs/guides/repair.md#segmented-mirror';
+
+/** One listed page: its identity at preview time and the two file versions the preview compared. */
+export interface StaleMirror {
+ source_id: string; slug: string; page_id: number; revision: string; path: string;
+ file_sha256: string; file_bytes: number; expected_sha256: string; expected_bytes: number;
+}
+/** A page (or, with slug '*', a source) the preview does not rewrite, with why and the read-only command that shows it. */
+export interface HeldMirror { source_id: string; slug: string; reason: string; message: string; fix?: string[] }
+
+type Selection = { sources: string[] };
+type MirrorItem = RepairItem & { stale: StaleMirror; hash: string };
+
+const previewCommand = (scope: Pick<RepairScope, 'source_ids'>) => `gbrain repair segmented-mirror${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
+const toItem = (stale: StaleMirror, index: number, hash: string): MirrorItem => ({ cursor: { phase: 0, id: index + 1 }, source_id: stale.source_id, slug: stale.slug,
+ chars: 0, action: 'remirror_file', change: { from: stale.file_sha256, to: stale.expected_sha256 }, stale, hash });
+const hashOf = (scope: RepairScope, selection: Selection, items: StaleMirror[]) => previewHash({ kind: 'segmented-mirror-v1', brain_id: scope.brain_id, selection,
+ items: items.map(({ source_id, slug, page_id, revision, path, file_sha256, expected_sha256 }) => ({ source_id, slug, page_id, revision, path, file_sha256, expected_sha256 })) });
+
+/** The request id an apply admits for one page under one approved hash: a replay finds its receipt instead of admitting again. */
+function remirrorRequestId(hash: string, stale: Pick<StaleMirror, 'source_id' | 'slug' | 'page_id'>): string {
+ const h = digest(['segmented-mirror-request-v1', hash, stale.source_id, stale.slug, stale.page_id]);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+const ledgerOf = (snapshot: PageSnapshot): BodyLedger => ({ withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) });
+
+/**
+ * Whether the withdrawal ledger changes the file: the digest of each body region as the file holds it against the same
+ * region with the ledger overlaid on its facts fences, both streamed over the file in pieces (body-digests.ts).
+ */
+async function fileHoldsWithdrawnRows(engine: BrainEngine, snapshot: PageSnapshot, bytes: FileBytes): Promise<boolean> {
+ const reading = { prefix: new Uint8Array(0), skip: 0 };
+ const file = fileBodyDigests(bytes, reading, snapshot.page.slug, {});
+ if (file.kind !== 'ok' || !file.factsFence) return false;
+ const ledger = ledgerOf(snapshot);
+ const overlaid = await overlaidFileBodyDigests(bytes, reading, file.regions, async text => (await overlayCanonicalBodies(engine.executeRaw.bind(engine), text, '',
+ ledger.withdrawals, { sourceId: snapshot.page.source_id, marker: ledger.globalPurges })).compiled_truth,
+ fence => fenceTooLargeError(snapshot.page.slug, snapshot.page.source_id, fence));
+ return overlaid.truth !== file.digests.truth || overlaid.timeline !== file.digests.timeline;
+}
+
+const heldFrom = (sourceId: string, slug: string, error: OperationError): HeldMirror => {
+ const drift = error.code === 'source_changed' && error.detail === 'file_database_drift';
+ return { source_id: sourceId, slug, reason: drift ? 'file_database_drift' : error.code, message: error.message, ...(error.fix?.argv ? { fix: [...error.fix.argv] } : {}) };
+};
+
+/** Every listed and held page of the sources, in (source, slug) order, read on this host one page at a time. */
+export async function scanSegmentedMirrors(engine: BrainEngine, sourceIds: readonly string[]): Promise<{ items: StaleMirror[]; held: HeldMirror[]; residuals: Record<string, number> }> {
+ const hostId = localHostId();
+ const items: StaleMirror[] = [], held: HeldMirror[] = [];
+ const residuals: Record<string, number> = {};
+ const hold = (entry: HeldMirror) => { held.push(entry); residuals[entry.reason] = (residuals[entry.reason] ?? 0) + 1; };
+ for (const sourceId of sourceIds) {
+ const binding = await getWorktreeBinding(engine, sourceId, hostId);
+ if (!binding) continue;
+ const slugs = (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND body_storage='segmented' AND deleted_at IS NULL ORDER BY slug", [sourceId]))
+ .map(row => row.slug);
+ if (!slugs.length) continue;
+ if (binding.owner_host_id !== hostId || !binding.local_path) {
+ hold({ source_id: sourceId, slug: '*', reason: 'not_owner_host',
+ message: `This host does not hold source ${sourceId}'s canonical worktree, so the files of its ${slugs.length} segmented page(s) were not read. Run the preview on the owner host.`,
+ fix: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+ continue;
+ }
+ const root = binding.local_path;
+ for (const slug of slugs) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot || !isSegmentedPage(snapshot.page) || !ledgerApplies(ledgerOf(snapshot))) continue;
+ try {
+ const target = await prepareFileTarget(engine, { source_id: sourceId, worktree_id: binding.worktree_id, slug }, snapshot, null, hostId, { allowMissing: true });
+ if (!target || !existsSync(target.path)) continue;
+ const bytes = FileBytes.open(target.path);
+ let holds: boolean, file: { sha256: string; bytes: number };
+ try { holds = await fileHoldsWithdrawnRows(engine, snapshot, bytes); file = { sha256: bytes.hash(), bytes: bytes.length }; } finally { bytes.close(); }
+ if (!holds) continue;
+ const expected = await unreadPageFile(engine, snapshot);
+ if (expected.hash === file.sha256) continue;
+ items.push({ source_id: sourceId, slug, page_id: Number(snapshot.page.id), revision: snapshot.revision, path: relative(root, target.path).split(sep).join('/'),
+ file_sha256: file.sha256, file_bytes: file.bytes, expected_sha256: expected.hash, expected_bytes: expected.bytes });
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ hold(heldFrom(sourceId, slug, error));
+ }
+ }
+ }
+ return { items, held, residuals };
+}
+
+/** The listed page as it is now: its live revision and id, and its file's streamed SHA-256, read on this host. */
+async function currentState(engine: BrainEngine, stale: StaleMirror): Promise<{ revision: string | null; page_id: number | null; file_sha256: string | null }> {
+ const snapshot = await engine.readPageSnapshot(stale.slug, { sourceId: stale.source_id });
+ const binding = await getWorktreeBinding(engine, stale.source_id, localHostId());
+ const path = binding?.local_path ? join(binding.local_path, ...stale.path.split('/')) : null;
+ let file_sha256: string | null = null;
+ if (path && existsSync(path)) {
+ const bytes = FileBytes.open(path);
+ try { file_sha256 = bytes.hash(); } finally { bytes.close(); }
+ }
+ return { revision: snapshot?.revision ?? null, page_id: snapshot ? Number(snapshot.page.id) : null, file_sha256 };
+}
+
+/** One page's receipt and its mirror and Git effects, admitted and committed in one transaction as a withdrawal's are. */
+async function admitRemirror(ctx: OperationContext, stale: StaleMirror, hash: string, requestId: string): Promise<WriteRequest> {
+ const engine = ctx.engine;
+ const { requestPrincipalForContext } = await import('../persistence/page-mutations.ts');
+ const principal = await requestPrincipalForContext(ctx);
+ const callerIntent = { kind: 'segmented_mirror', slug: stale.slug, page_id: stale.page_id, preview_hash: hash, file_sha256: stale.file_sha256, expected_sha256: stale.expected_sha256 };
+ return retryWriteAdmission(requestId, remaining => engine.transaction(async tx => {
+ await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
+ const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [stale.source_id]);
+ if (!source || source.archived) throw opError('source_changed', 'The source is missing or archived.',
+ `Source ${stale.source_id} is archived or missing, so ${stale.slug} was not re-mirrored. Run ${previewCommand({ source_ids: [stale.source_id] })} again.`);
+ const prior = await getWriteRequest(tx, principal, requestId);
+ if (prior) return prior;
+ const authority = await submissionAuthority({ ...ctx, engine: tx }, SEGMENTED_MIRROR_OPERATION, stale.source_id, source.incarnation, stale.slug);
+ const row = await admitWriteInTransaction(tx, { principal, operation: SEGMENTED_MIRROR_OPERATION, sourceId: stale.source_id, sourceIncarnation: source.incarnation,
+ slug: stale.slug, pageId: stale.page_id, requestId, callerIntent, intent: callerIntent, authority });
+ if (isTerminal(row)) return row;
+ return withCoordinatedWrite(tx, [stale.source_id], async () => {
+ await tx.lockPageKeys([{ sourceId: stale.source_id, slug: stale.slug }]);
+ const snapshot = await tx.readPageSnapshot(stale.slug, { sourceId: stale.source_id });
+ if (snapshot?.revision !== stale.revision || Number(snapshot.page.id) !== stale.page_id) throw previewChangedError(hash, previewCommand({ source_ids: [stale.source_id] }));
+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
+ SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
+ FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
+ CROSS JOIN (VALUES ('withdrawal-mirror'),('git')) AS k(kind)
+ WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [row.id, stale.source_id, JSON.stringify({ version: 2,
+ commit_subject: `gbrain: re-mirror segmented page ${stale.slug}`, commit_line: `re-mirror ${stale.slug} without withdrawn rows`,
+ targets: [{ slug: stale.slug, page_id: stale.page_id, revision: stale.revision }] })]);
+ return completeWrite(tx, row, 'committed', { segmented_mirror: { ...callerIntent, revision: stale.revision, path: stale.path, effects: ['withdrawal-mirror', 'git'] } });
+ }, requestAttribution(row));
+ }), undefined, error => engine.reconnect({ error }));
+}
+
+interface EffectState { kind: string; state: string; error_code: string | null; recovering: boolean; parked: boolean; skipped: Array<{ slug?: string; reason?: string }> }
+async function readEffects(engine: BrainEngine, requestRowId: string): Promise<EffectState[]> {
+ const rows = await engine.executeRaw<EffectState>(`SELECT kind,state,error_code,recovery IS NOT NULL AS recovering,data ? 'parked' AS parked,
+ COALESCE(data->'skipped','[]'::jsonb) AS skipped FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind`, [requestRowId]);
+ return rows.map(row => ({ ...row, skipped: typeof row.skipped === 'string' ? JSON.parse(row.skipped) : row.skipped }));
+}
+const effectSettled = (effect: EffectState) => !effect.recovering && (effect.state === 'committed' || effect.state === 'failed' || effect.parked);
+
+/** Wakes this process's consumer and waits up to `waitMs` for the request's mirror and Git effects to settle. */
+async function awaitEffects(ctx: OperationContext, requestRowId: string, waitMs: number): Promise<EffectState[]> {
+ const { startPersistenceConsumer } = await import('../persistence/service.ts');
+ startPersistenceConsumer(ctx.engine, ctx.config ?? { engine: ctx.engine.kind }).wake(true);
+ const deadline = Date.now() + waitMs;
+ for (let delay = 50; ; delay = Math.min(500, delay * 2)) {
+ const effects = await readEffects(ctx.engine, requestRowId);
+ if (effects.every(effectSettled) || Date.now() >= deadline) return effects;
+ await new Promise(resolve => setTimeout(resolve, Math.min(delay, Math.max(1, deadline - Date.now()))));
+ }
+}
+
+function outcomeOf(stale: StaleMirror, row: WriteRequest, effects: EffectState[], replayed: boolean): RepairItemOutcome {
+ const detail = { request_id: row.request_id, path: stale.path, file_sha256_before: stale.file_sha256, expected_sha256: stale.expected_sha256,
+ effects: effects.map(effect => ({ kind: effect.kind, state: effect.state, ...(effect.error_code ? { error: effect.error_code } : {}) })) };
+ if (replayed) return { applied: false, outcome: 'replayed', detail };
+ const mirror = effects.find(effect => effect.kind === 'withdrawal-mirror');
+ const skip = mirror?.skipped.find(entry => entry.slug === stale.slug);
+ if (skip) return { applied: false, outcome: 'held', reason: skip.reason ?? 'skipped', detail };
+ if (mirror?.state === 'committed' && !mirror.recovering) return { applied: true, outcome: 'mirrored', detail };
+ if (mirror && (mirror.state === 'failed' || mirror.parked)) return { applied: false, outcome: 'failed', reason: mirror.error_code ?? 'mirror_failed', detail };
+ return { applied: true, outcome: 'mirror_queued', detail };
+}
+
+export const segmentedMirrorRepair: RepairHandler = {
+ kind: 'segmented-mirror',
+ embeds: false,
+ outcomeItemsLimit: 1000,
+ async plan(engine, scope, after, opts = { apply: false }): Promise<RepairPlan> {
+ const selection: Selection = { sources: scope.source_ids };
+ const command = previewCommand(scope);
+ if (!opts.apply) {
+ const scan = await scanSegmentedMirrors(engine, scope.source_ids);
+ const hash = hashOf(scope, selection, scan.items);
+ if (scan.items.length) await saveApprovedSet<StaleMirror & { selection: Selection }>(engine, { command: 'segmented-mirror', hash }, scan.items.map(stale => ({ ...stale, selection })));
+ return { items: scan.items.map((stale, index) => toItem(stale, index, hash)), preview_hash: hash, residuals: scan.residuals,
+ listing: scan.items.map(stale => ({ item: `${stale.source_id}:${stale.slug}`, class: 'stale_render',
+ detail: `${stale.path}: file sha256 ${stale.file_sha256} (${stale.file_bytes} bytes), canonical render sha256 ${stale.expected_sha256} (${stale.expected_bytes} bytes)` })),
+ details: { stale: scan.items, held: scan.held } };
+ }
+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair segmented-mirror --apply needs the preview hash.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, DOCS);
+ const expect = opts.expect;
+ const approved = (await loadApprovedSet<StaleMirror & { selection: Selection }>(engine, { command: 'segmented-mirror', hash: expect, previewCommand: command,
+ emptyHash: async () => hashOf(scope, selection, (await scanSegmentedMirrors(engine, scope.source_ids)).items) })).items;
+ if (approved.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(selection))) throw previewChangedError(expect, command);
+ const stale = approved.map(({ selection: _selection, ...entry }) => entry);
+ const admitted = new Set((await engine.executeRaw<{ request_id: string }>('SELECT request_id::text AS request_id FROM persistence_requests WHERE request_id=ANY($1::uuid[])',
+ [stale.map(entry => remirrorRequestId(expect, entry))])).map(row => row.request_id));
+ // Every page not yet admitted under this hash still has the revision and file bytes the user saw, or nothing is written.
+ for (const entry of stale) {
+ if (admitted.has(remirrorRequestId(expect, entry))) continue;
+ const now = await currentState(engine, entry);
+ if (now.revision !== entry.revision || now.page_id !== entry.page_id || now.file_sha256 !== entry.file_sha256) throw previewChangedError(expect, command);
+ }
+ return { items: stale.map((entry, index) => toItem(entry, index, expect)).filter(item => afterCursor(item.cursor, after)), preview_hash: expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { stale, hash } = entry as MirrorItem;
+ const { initializeLocalPersistence, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');
+ await initializeLocalPersistence(ctx);
+ const requestId = remirrorRequestId(hash, stale);
+ const prior = await getWriteRequest(ctx.engine, await requestPrincipalForContext(ctx), requestId);
+ const row = prior ?? await admitRemirror(ctx, stale, hash, requestId);
+ if (row.state !== 'committed') return { applied: false, outcome: 'failed', reason: row.error_code ?? row.state, detail: { request_id: row.request_id } };
+ const effects = prior ? await readEffects(ctx.engine, row.id) : await awaitEffects(ctx, row.id, ctx.writeWaitMs ?? 5_000);
+ return outcomeOf(stale, row, effects, prior !== null);
+ },
+ render(details) {
+ const stale = (details.stale ?? []) as StaleMirror[];
+ const held = (details.held ?? []) as HeldMirror[];
+ return [
+ ...stale.map(entry => ` re-mirror ${entry.source_id}:${entry.slug} (${entry.path}): file sha256 ${entry.file_sha256.slice(0, 16)}… ${entry.file_bytes} bytes, `
+ + `canonical render sha256 ${entry.expected_sha256.slice(0, 16)}… ${entry.expected_bytes} bytes; the file still holds a withdrawn or purged row`),
+ ...held.map(entry => ` held ${entry.source_id}:${entry.slug} (${entry.reason}): not rewritten. ${entry.message}${entry.fix ? ` Read-only next step: ${entry.fix.join(' ')}` : ''}`),
+ ];
+ },
+};
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 9236d4b3a3..d8fba1046b 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -197,7 +197,7 @@ for (const backend of testBackends()) {
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', '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', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
- 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables' };
+ 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables', 'segmented-mirror': 'gbrain repair segmented-mirror' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/pathological/lp-a-segmented-mirror.test.ts b/test/pathological/lp-a-segmented-mirror.test.ts
new file mode 100644
index 0000000000..7e44e47176
--- /dev/null
+++ b/test/pathological/lp-a-segmented-mirror.test.ts
@@ -0,0 +1,168 @@
+/**
+ * LPH (a): `gbrain repair segmented-mirror` re-mirrors the canonical file of a page stored in segments that an older
+ * binary's withdrawal mirror passed by.
+ *
+ * 1. Protects: before v0.60.299.0 a purge or forget struck the row in a segmented page's segments but skipped its file
+ * (`page_body_segmented`), so the file kept the withdrawn row. The preview lists exactly the file-backed segmented
+ * pages whose file is such an older render (the mirror's own file/database check passes and the ledger still changes
+ * the file), with each file's SHA-256 and size beside the canonical render's, and a hash. It never lists a clean
+ * segmented page or an inline page, and it holds (never rewrites) a segmented file that also differs from the
+ * database for another reason (`file_database_drift`). `--apply --expect <hash>` rewrites each listed file through
+ * a withdrawal-mirror effect of its own receipted request: the file loses the row, is byte-identical to the page's
+ * `gbrain export` render, and the Git effect commits it. A second preview lists nothing; a second apply (the new
+ * hash, or the old one replayed) writes nothing. A hash no preview saved, or one whose file changed since, refuses
+ * with `preview_changed` before anything is admitted.
+ * 2. Fails when: the kind does not exist (red before), the preview misses a stale file or lists a clean, inline or
+ * drifted one, the apply writes anything other than the export render, overwrites the drifted file, or a stale hash
+ * applies.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set. The older binary's on-disk state is modelled by writing each
+ * file's pre-withdrawal bytes back after the withdrawal committed and committing them to Git, which is exactly what
+ * the skipped mirror and Git walk left behind.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';
+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { durableGitRepo, git, gitAsync } from '../helpers/git-publication.ts';
+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';
+import { exported, fileOf, purge, settle } from '../helpers/segmented-withdrawal.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+const STALE_PURGE = 'people/stale-purge-example';
+const STALE_FORGET = 'people/stale-forget-example';
+const CLEAN = 'people/clean-example';
+const DRIFT = 'people/drift-example';
+const INLINE = 'people/inline-example';
+const SEGMENTED = [STALE_PURGE, STALE_FORGET, CLEAN, DRIFT];
+const CLAIM: Record<string, string> = {
+ [STALE_PURGE]: 'Mirror Example locker code is 4411', [STALE_FORGET]: 'Mirror Example bike lock is 4412', [CLEAN]: 'Mirror Example vault code is 4413',
+ [DRIFT]: 'Mirror Example safe code is 4414', [INLINE]: 'Mirror Example gate code is 4415',
+};
+const KEPT = 'Mirror Example adopted a narwhalbot';
+const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
+const quiet = { info() {}, warn() {}, error() {} };
+
+async function extract(brain: TwinBrain, slug: string, facts: string[]) {
+ brain.setChatReply(JSON.stringify({ facts: facts.map(fact => ({ fact, kind: 'fact', entity: slug, confidence: 1, notability: 'high' })) }));
+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + facts.join('. ') + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, slug))
+ .toMatchObject({ inserted: facts.length });
+}
+
+for (const { backend: kind } of pathologicalArms()) {
+ describe(kind + ': gbrain repair segmented-mirror re-mirrors files an older binary left holding withdrawn rows', () => {
+ let brain: TwinBrain;
+ const before: Record<string, Buffer> = {};
+
+ const run = (apply: boolean, expectHash?: string): Promise<RepairResult> => withEnv(brain.env(), () => withVerifiedLocalRegistration(brain.engine, brain.cli, async () => {
+ const scope = await resolveRepairScope(brain.engine, brain.sourceId);
+ const runner = await repairRunner(brain.engine, { apply, logger: quiet });
+ return runner.run('segmented-mirror', scope, { explicit: true, sourceFlag: brain.sourceId, ...(expectHash ? { expect: expectHash } : {}) });
+ }));
+ const remirrorRequests = async () => (await brain.engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND operation='repair_segmented_mirror'", [brain.sourceId]))[0]!.n;
+ const files = () => Object.fromEntries([...SEGMENTED, INLINE].map(slug => [slug, readFileSync(fileOf(brain, slug))]));
+
+ beforeAll(async () => {
+ brain = await openTwinBrain(kind, [INLINE], async seed => {
+ await seed.setSwitch(false);
+ await seed.put(INLINE, 1_100_000);
+ await seed.setSwitch(true);
+ for (const slug of SEGMENTED) await seed.put(slug, 1_100_000);
+ });
+ for (const slug of [...SEGMENTED, INLINE]) await extract(brain, slug, [CLAIM[slug]!, KEPT]);
+ await settle(brain, kind);
+ expect(await Promise.all([...SEGMENTED, INLINE].map(slug => brain.storageOf(slug)))).toEqual(['segmented', 'segmented', 'segmented', 'segmented', 'inline']);
+ durableGitRepo(brain.root, [...SEGMENTED, INLINE].map(slug => slug + '.md'));
+
+ // The older binary: each withdrawal committed in the database, and its file (and Git) kept the pre-withdrawal bytes.
+ for (const slug of [...SEGMENTED, INLINE]) before[slug] = readFileSync(fileOf(brain, slug));
+ for (const slug of [STALE_PURGE, CLEAN, DRIFT, INLINE]) await purge(brain, kind, slug, CLAIM[slug]!);
+ const [forgotten] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3',
+ [brain.sourceId, STALE_FORGET, CLAIM[STALE_FORGET]]);
+ expect(await brain.call('forget_fact', { id: Number(forgotten!.id), request_id: randomUUID() }, STALE_FORGET)).toMatchObject({ state: 'committed' });
+ await settle(brain, kind);
+ for (const slug of [STALE_PURGE, STALE_FORGET, INLINE]) writeFileSync(fileOf(brain, slug), before[slug]!);
+ // The drifted file also carries a local edit the database never saw.
+ writeFileSync(fileOf(brain, DRIFT), before[DRIFT]!.toString('utf8').replace('00000007 acme-example journal line', '00000007 acme-example journal LINE edited by hand'));
+ git(brain.root, 'add', '-A'); git(brain.root, 'commit', '-q', '-m', 'older binary state');
+ }, 900_000);
+
+ afterAll(() => brain.close(), 120_000);
+
+ test('the seeded files are the older binary\'s: the withdrawn rows are still on disk though the database withdrew them', async () => {
+ for (const slug of [STALE_PURGE, DRIFT, INLINE]) {
+ expect(readFileSync(fileOf(brain, slug), 'utf8')).toContain(CLAIM[slug]!);
+ expect(await brain.engine.executeRaw('SELECT 1 FROM facts WHERE source_id=$1 AND fact=$2', [brain.sourceId, CLAIM[slug]])).toEqual([]);
+ }
+ expect(readFileSync(fileOf(brain, STALE_FORGET)).equals(before[STALE_FORGET]!)).toBe(true);
+ for (const slug of [STALE_PURGE, STALE_FORGET]) expect(readFileSync(fileOf(brain, slug)).equals(await exported(brain, slug))).toBe(false);
+ expect(readFileSync(fileOf(brain, CLEAN), 'utf8')).not.toContain(CLAIM[CLEAN]!);
+ expect(readFileSync(fileOf(brain, CLEAN)).equals(await exported(brain, CLEAN))).toBe(true);
+ }, 300_000);
+
+ test('preview lists exactly the stale segmented files, holds the drifted one and refuses a stale hash', async () => {
+ const preview = await run(false);
+ expect(preview.mode).toBe('dry_run');
+ expect(preview.listing?.map(entry => entry.item)).toEqual([STALE_FORGET, STALE_PURGE].map(slug => `${brain.sourceId}:${slug}`));
+ const stale = preview.details!.stale as Array<{ slug: string; path: string; file_sha256: string; file_bytes: number; expected_sha256: string; expected_bytes: number }>;
+ for (const entry of stale) {
+ const file = readFileSync(fileOf(brain, entry.slug)), render = await exported(brain, entry.slug);
+ expect(entry).toMatchObject({ path: entry.slug + '.md', file_sha256: sha(file), file_bytes: file.length, expected_sha256: sha(render), expected_bytes: render.length });
+ }
+ expect((preview.details!.held as Array<{ slug: string; reason: string }>).map(entry => [entry.slug, entry.reason])).toEqual([[DRIFT, 'file_database_drift']]);
+ expect(preview.preview_hash).toMatch(/^[0-9a-f]{64}$/);
+ expect(preview.apply_command).toContain(`--apply --expect ${preview.preview_hash} --yes`);
+
+ // A hash no preview saved refuses before anything is admitted.
+ const unknown = await run(true, 'f'.repeat(64)).then(() => null, error => error);
+ expect(unknown).toBeInstanceOf(OperationError);
+ expect((unknown as OperationError).code).toBe('preview_changed');
+ // So does the previewed hash once a listed file changed since the preview.
+ const snapshot = files();
+ writeFileSync(fileOf(brain, STALE_PURGE), Buffer.concat([snapshot[STALE_PURGE]!, Buffer.from('\n')]));
+ const changed = await run(true, preview.preview_hash).then(() => null, error => error);
+ writeFileSync(fileOf(brain, STALE_PURGE), snapshot[STALE_PURGE]!);
+ expect(changed).toBeInstanceOf(OperationError);
+ expect((changed as OperationError).code).toBe('preview_changed');
+ expect(await remirrorRequests()).toBe(0);
+ for (const [slug, bytes] of Object.entries(files())) expect({ slug, same: bytes.equals(snapshot[slug]!) }).toEqual({ slug, same: true });
+ }, 600_000);
+
+ test('apply rewrites each listed file to its export render through the mirror, commits it, and is idempotent', async () => {
+ const preview = await run(false);
+ const untouched = { [DRIFT]: readFileSync(fileOf(brain, DRIFT)), [INLINE]: readFileSync(fileOf(brain, INLINE)), [CLEAN]: readFileSync(fileOf(brain, CLEAN)) };
+ const applied = await run(true, preview.preview_hash);
+ expect(applied.outcomes).toEqual({ mirrored: 2 });
+ expect(applied.applied).toBe(2);
+ expect(await remirrorRequests()).toBe(2);
+ await settle(brain, kind);
+ for (const slug of [STALE_PURGE, STALE_FORGET]) {
+ const file = readFileSync(fileOf(brain, slug));
+ expect(file.equals(await exported(brain, slug))).toBe(true);
+ expect(file.toString('utf8')).toContain(KEPT);
+ expect((await gitAsync(brain.root, 'log', '-1', '--format=%s', '--', slug + '.md')).trim()).toBe(`gbrain: re-mirror segmented page ${slug}`);
+ expect(await gitAsync(brain.root, 'status', '--porcelain', '--', slug + '.md')).toBe('');
+ }
+ expect(readFileSync(fileOf(brain, STALE_PURGE), 'utf8')).not.toContain(CLAIM[STALE_PURGE]!);
+ for (const [slug, bytes] of Object.entries(untouched)) expect({ slug, same: readFileSync(fileOf(brain, slug)).equals(bytes) }).toEqual({ slug, same: true });
+
+ // A second preview lists nothing; applying its hash, or replaying the first one, writes nothing.
+ const again = await run(false);
+ expect(again.listing).toEqual([]);
+ expect((again.details!.held as Array<{ slug: string }>).map(entry => entry.slug)).toEqual([DRIFT]);
+ const snapshot = files();
+ const empty = await run(true, again.preview_hash);
+ expect(empty.applied).toBe(0);
+ const replay = await run(true, preview.preview_hash);
+ expect(replay.applied).toBe(0);
+ expect(replay.outcomes).toEqual({ replayed: 2 });
+ expect(await remirrorRequests()).toBe(2);
+ for (const [slug, bytes] of Object.entries(files())) expect({ slug, same: bytes.equals(snapshot[slug]!) }).toEqual({ slug, same: true });
+ }, 600_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 36e1413f6a..d6d9f8bebe 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -254,6 +254,7 @@ test/pathological/b-9-enrich-retired-alias.test.ts
test/pathological/b6-triage-verdict-surrogate.test.ts
test/pathological/c-23-override-and-doctor-fixes.test.ts
test/pathological/c-9-facts-absorb-dead.test.ts
+test/pathological/lp-a-segmented-mirror.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 306a687409..f4e1501ef2 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', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'segmented-mirror'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));