Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Clear purged change reasons that already leaked into page history, with a preview-first repair (GST-2886) (#9584)
Garry Tanb6528b40f58d
diff --git a/behavior-changes.d/purged_change_reasons_repair_gst2886.md b/behavior-changes.d/purged_change_reasons_repair_gst2886.mdnew file mode 100644index 0000000000..490d6650d2--- /dev/null+++ b/behavior-changes.d/purged_change_reasons_repair_gst2886.md@@ -0,0 +1,4 @@+---+kind: add+---+New command gbrain repair purged-change-reasons. If you purged a fact before upgrading, a page's history could still show a change reason quoting it (#8635). Run gbrain repair purged-change-reasons on the brain host to see how many such reasons this brain holds; nothing runs it for you. If it finds any, the preview prints the apply command, which sets exactly those reasons to [purged] after you agree. Pages, files and Git history are not changed.diff --git a/changelog.d/fix-repair-purged-change-reasons-gst2886.md b/changelog.d/fix-repair-purged-change-reasons-gst2886.mdnew file mode 100644index 0000000000..51d717fe0c--- /dev/null+++ b/changelog.d/fix-repair-purged-change-reasons-gst2886.md@@ -0,0 +1,6 @@+**New `gbrain repair purged-change-reasons` finds page-history change reasons that still quote a claim you purged before the #8635 fix, and redacts them after you agree.**++### Added+- Before #8635 was fixed, a sync that read a page's `gbrain-reason` trailer just before a fact purge could still store the purged text as that page version's change reason. `gbrain repair purged-change-reasons` re-reads each reason the purge recorded from the source's Git checkout, counts the page versions that still hold it (for the whole brain and for each source, never printing the text), and with `--apply --expect <hash> --yes` sets exactly those to `[purged]`, the value a purge writes. The same text under another file, or from a commit that gives the file two reasons, is kept unless you pass `--include-ambiguous`. It runs only when you name it, and never on upgrade, sync or doctor. Repo-less sources have nothing to check and the preview still succeeds. Pages, files and Git history are not changed (GST-2886, follow-up to #8635).++<!-- behavior-change: purged_change_reasons_repair_gst2886 -->diff --git a/docs/architecture/key-files/page-history.md b/docs/architecture/key-files/page-history.mdindex 2b1d1c56a5..ebfdf9d4e8 100644--- a/docs/architecture/key-files/page-history.md+++ b/docs/architecture/key-files/page-history.md@@ -8,3 +8,4 @@ Page-write reasons: admission, the snapshot column, the Git trailer and the remo- `src/core/reason-trailers.ts` — GBRA-217 reasons read back from Git ([reasons from Git](../../guides/page-history.md#reasons-from-git)). `readReasonTrailers` streams one `git log` through `hardenedGitStream` with `REASON_LOG_OPTIONS` (`hardened-git.ts`: `-z --first-parent --diff-merges=first-parent --root --name-only --no-renames` and a `%x00%H%x00%(trailers:key=gbrain-reason,valueonly,unfold)` format; no pathspec, no grep), parses records as they stream and stops at a commit cap. `scanSyncReasons` maps each repository path to its newest first-parent commit's trailer (canonicalised by `canonicalChangeReason`, over-long ones counted as malformed, secrets via `scanTextSpans` reported by commit and path, `reason_purge_tombstones` pairs skipped) and counts touches per path; `importHistoryFor` turns that into the `VersionHistory` an import passes to `createVersion` (more than one commit, or a failed or capped scan, sets `historyGap`), with the deciding commit and path as `reasonSource`, so the snapshot insert rechecks that pair's tombstone under the page guard (#8635). `gitTopLevel` returns null outside a repository, so a repo-less or plain-folder source runs no scan. `reasonScanNotices` builds `reason_scan_failed` / `reason_scan_capped` / `reason_trailer_secret`. `cachedSyncReasonScan` shares one scan per (source, root, range) for managed preparations; purge clears it. `scanTrailersCarrying` is purge's read (cap 200,000, or the user's `--reason-scan-limit`). Caps 10,000 (sync) and 200,000 (purge), 120 s timeout. Seams: `__setReasonScanCapsForTests`, `__setReasonGitStreamForTests`. Test: `test/reason-trailers-gbra217.test.ts` (both engines).- `src/commands/sync/reasons.ts` + `src/core/persistence/sync-reasons.ts` — the sync wiring. Classic: `incremental.ts` scans `last_commit..pin` once per pass when it imports or renames files (not for a company brain), `full.ts` scans the whole history only when the source already has pages, and `imports.ts` / `renames.ts` / `runImport` pass each file's `history` to `importFile`; `withReasonNotices` puts the notices and `reason_trailers_malformed` on the `SyncResult` (`sync/run.ts` renders them). Managed: `sync-prepare.ts` calls `managedFileHistory` (claim step `reason_scan`) only when the page exists, and `performManagedPass` adds the pass's notices through `withManagedReasonNotices`. Content never waits on the scan.- `src/core/facts/purge-reasons.ts` — A7 ([purge and reasons](../../guides/page-history.md#purge-and-reasons)). `scanPurgeTrailers` runs before the purge transaction (no checkout: nothing to scan; a failed read refuses `reason_purge_scan_failed`, `fix.next = wait`; over the cap `reason_purge_scan_capped`, ask_user with `--reason-scan-limit`). Inside the transaction `redactGitEffectReasons` rewrites `commit_line` / `commit_trailers` / legacy `commit_trailer` on queued, failed and committed git effects (a running one refuses `purge_blocked_pending_recovery`) and `recordReasonTombstones` rechecks `head..HEAD` and inserts text-free `reason_purge_tombstones` rows. `purge.ts` `redactPageVersions` sets a quoting `change_reason` to `[purged]`; `purge-verify.ts` checks it and reports pushed commits as the `git_commit_messages` residual.+- `src/core/repair/purged-change-reasons.ts` — `gbrain repair purged-change-reasons` (GST-2886, #8635 follow-up), explicit-only, preview-bound, destructive. `findLeakedChangeReasons` (read-only) re-reads the trailers of each `reason_purge_tombstones` row's `<commit>^!` from the source's checkout (`gitTopLevel`, `readReasonTrailers`, `trailerTexts` with `pathForms`, `canonicalChangeReason`) and returns the source's `page_versions` whose `change_reason` equals that text: `evidenced` when `source_path` is a form of the tombstoned path, else, or when the commit gives that path more than one reason, `path_mismatch` (only with `--include-ambiguous`); unreadable commits and repo-less sources are residuals. The approved set holds version ids and classes, never the text or a digest of it; the apply reads the candidates from Git again, takes `sources FOR UPDATE` and sets each approved row still of its class to `[purged]` only while it holds exactly that text, one `maintenanceTransaction` per batch (`changed_since_preview` otherwise). Tests: `test/purged-change-reasons-repair-gst2886.test.ts` (PGLite and Postgres).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex bb05f8d84b..38fd808595 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -312,6 +312,7 @@ or a physical projection that leaves attribution untouched):- `src/core/repair/duplicate-facts.ts` (2): `gbrain repair duplicate-facts` supersedes duplicate fact copies onto the kept row (the fenced copy, else the oldest) inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per group on unmanaged brains; a fenced copy is struck through a revision-bound `put_page` first.- `src/core/repair/conversation-labels.ts` (4): a request on managed brains; the unmanaged label retirement runs in `maintenanceTransaction`.- `src/core/repair/purged-page-facts.ts` (1): a request on managed brains; the unmanaged expiry runs in `maintenanceTransaction`.+- `src/core/repair/purged-change-reasons.ts` (1): `gbrain repair purged-change-reasons` sets preview-approved `page_versions.change_reason` rows to `[purged]` in `maintenanceTransaction`; database-only, no page, file or commit changes.- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.- `src/core/repair/fact-claim-dates.ts` (1): `gbrain repair fact-claim-dates` updates database-only facts' `valid_from` in one `maintenanceTransaction` on unmanaged brains only; fence rows move through revision-bound `put_page`, and a managed brain never takes the direct update.- `src/core/repair/facts-rehome.ts` (1): `gbrain repair facts-rehome` moves facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per slug on unmanaged brains.diff --git a/docs/guides/page-history.md b/docs/guides/page-history.mdindex f398804058..624f3ac0d1 100644--- a/docs/guides/page-history.md+++ b/docs/guides/page-history.md@@ -199,6 +199,11 @@ reaches every copy of a reason that quotes the claim:The receipt counts these in `removed.reason_purge_tombstones` and lists thecommits under the `git_commit_messages` residual.+Before #8635 was fixed, a sync that read a reason just before a purge could+still save it afterwards. `gbrain repair purged-change-reasons` finds those+versions and, after you agree, sets them to `[purged]`+([purged change reasons](repair.md#purged-change-reasons)).+Purge refuses before it changes anything when it cannot read that history:- `reason_purge_scan_failed`: reading the trailers failed: the source's folderdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex fbbb08166b..6425a8b02c 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -8,7 +8,7 @@ can load, and Google source files other local users can read. `gbrain repair`fixes those and the other kinds listed in[What each kind fixes](#what-each-kind-fixes). Every run is a preview unlessyou pass `--apply`.-The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `atom-fence-rows`, `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`,+The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `atom-fence-rows`, `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`, `purged-change-reasons`,`captured-facts`, `agent-session-facts`, `redacted-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `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@@ -228,8 +228,8 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. || `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |-| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `atoms-restore`, `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`, `captured-facts`, `redacted-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |-| `--include-ambiguous` | `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`, `captured-facts` and `agent-session-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). |+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `atoms-restore`, `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`, `purged-change-reasons`, `captured-facts`, `redacted-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |+| `--include-ambiguous` | `extractor-facts`, `unwithdrawn-facts`, `purged-page-facts`, `captured-facts` and `agent-session-facts`: widen the hashed set to `ambiguous` facts. `purged-change-reasons`: add the `path_mismatch` rows. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). || `--only <path>`, `--skip <path>` | `frontmatter` only: select source-relative files (repeatable). The hash covers the selection, so pass the same flags to the apply. || `--diff` | `frontmatter` only: print every per-file diff instead of one sample per class (`--json` always carries all of them). || `--yes` | `frontmatter --apply` only: the user agreed to the previewed file changes (destructive consent). Without it a terminal asks, and a run without a terminal exits 3 with the consent payload. |@@ -2713,6 +2713,50 @@ managed brain each batch of up to 200 facts is one database-only`managed_maintenance_expire_purged_page_facts` request. It works the same ona repo-less brain: no page or file is written.+<a id="purged-change-reasons"></a>+### Purged change reasons++Before #8635 was fixed, a sync could read a page's `gbrain-reason` trailer+from Git, a fact purge could then run, and the sync would still save that+reason as the page version's change reason. So `gbrain history` could show a+reason quoting a claim you had purged. Syncs no longer do this;+`gbrain repair purged-change-reasons` finds and redacts the reasons saved+before the fix. Nothing runs it for you: not an upgrade, a sync or doctor.++```bash+gbrain repair purged-change-reasons # preview: a count for the brain and for each source+gbrain repair purged-change-reasons --apply --expect <hash> --yes+gbrain repair purged-change-reasons --include-ambiguous # also the same text under another path+```++When a purge finds a reason quoting the claim in a commit already in Git, it+records that commit and file (with no text). For each such record, the repair+reads the commit's reason for that file from the source's checkout again,+exactly as sync reads it, and looks for page versions in that source whose+change reason is that same text:++- **evidenced**: the version's file is that file. Redacted by default.+- **path_mismatch**: the same text on a version of another file, or on a+ version with no file recorded, or a commit that gives the file more than one+ reason (the purge may have matched the other one). Kept, and redacted only+ with `--include-ambiguous` on both the preview and the apply.++The preview never prints the reason text, only counts and items such as+`source-a:notes/a@v42`. It also counts `unreadable_commit` (the checkout is+gone or the commit can no longer be read; nothing is found for those) and+`sources_without_checkout`. A preview that finds 0 is only complete when+`unreadable_commit` is 0 too: run it on the brain host, where the checkouts+are. A repo-less source never stored a reason from Git, so it has nothing to+check and the preview still succeeds.++The apply needs the preview's hash and your consent (`--yes`, or a terminal+prompt). It reads the reasons from Git again, locks the source as a purge+does and sets exactly the previewed versions whose reason is still the same+text to `[purged]`, the value a purge+writes; anything else is reported as `changed_since_preview` and kept. Pages,+files and Git history are not changed; a commit message keeps its text, as+after any purge. Running the preview again after the apply finds nothing.+<a id="conversation-labels"></a>### Conversation labels@@ -4836,6 +4880,7 @@ Then recover what doctor names, in this order (skip a step whose check is ok):| `The OpenAI embedding provider rejected its key (HTTP 401)` | [`embedding_auth_failed`](write-refusals.md#embedding_auth_failed) | `gbrain doctor` (`embedding_key_source`, `embedding_provider`) | the printed fix for the key source in effect, then `gbrain embed --stale` | `gbrain doctor` shows `embedding_provider` ok | user (owns the key) | `credentials`; `paid` for `embed --stale` || Conversation facts missing from recall after managed writes | `extractor_facts_expired` | `gbrain repair extractor-facts` | `gbrain repair extractor-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` | brain host, after the user agrees | `destructive` (rewrites expired facts) || Recall still returns claims from a page you purged; doctor `purged_page_facts` warns | `purged_page_facts` ([purged page facts](#purged-page-facts)) | `gbrain repair purged-page-facts` | `gbrain repair purged-page-facts --apply --expect <hash> --yes` (no purge record: add `--include-ambiguous` to both) | `gbrain doctor` | brain host, after the user agrees | destructive (`--yes`) |+| Page history still shows a change reason quoting a claim you purged before upgrading | none (run the preview; [purged change reasons](#purged-change-reasons)) | `gbrain repair purged-change-reasons` | `gbrain repair purged-change-reasons --apply --expect <hash> --yes` (same text under another path: add `--include-ambiguous` to both) | the preview again finds 0, with `unreadable_commit` 0 | brain host, after the user agrees | destructive (`--yes`) || Facts missing from recall after a page write or `extract_facts` run, although no fence of their page held them; doctor `unwithdrawn_facts` warns | `unwithdrawn_facts` ([unwithdrawn facts](#unwithdrawn-facts)) | `gbrain repair unwithdrawn-facts` | `gbrain repair unwithdrawn-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` | brain host, after the user agrees | none || Recall returns conversation facts such as "Date said …" or "Attendees said …", or facts dated 1970-01-01; doctor `conversation_label_facts` warns; the upgrade banner prints `conversation_label_facts: N (explicit_kind_required; …)` | `gbrain repair conversation-labels` (ambiguous: add `--include-ambiguous`) | `gbrain repair conversation-labels --apply --expect <hash> --yes`, then the printed `gbrain extract-conversation-facts --slugs … --dry-run` | `gbrain doctor --only conversation_label_facts --json` | brain host, after the user agrees | `destructive` (retires facts; no model calls) |diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex bade3a9a4c..d40561ec02 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -505,6 +505,7 @@"test/purge-root-metafile-7613.test.ts": 13254,"test/purge-scrub-followups-9068.test.ts": 9315,"test/purge-sync-tombstone-hold-7130.test.ts": 50265,+ "test/purged-change-reasons-repair-gst2886.test.ts": 15032,"test/qm-attest-write-boundary.test.ts": 7200,"test/qm-memory-propose.test.ts": 19584,"test/qm-memory-tools.test.ts": 32903,diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 3ea659ba7a..a03d76e043 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' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'purged-page-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'moved-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows' | 'open-facts';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'purged-page-facts' | 'purged-change-reasons' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'moved-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows' | 'open-facts';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex d2ed388aac..de6cdd5d1b 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -55,7 +55,7 @@ import type { PrivateLabelsLedger } from './private-labels.ts';import type { OpenFactsRequest } from './open-facts.ts';import type { ReadersRequest } from './readers.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', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels', 'open-facts'] 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', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'purged-change-reasons', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels', 'open-facts'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/purged-change-reasons.ts b/src/core/repair/purged-change-reasons.tsnew file mode 100644index 0000000000..e3fabcb438--- /dev/null+++ b/src/core/repair/purged-change-reasons.ts@@ -0,0 +1,198 @@+/**+ * `gbrain repair purged-change-reasons` (GST-2886, #8635 follow-up): clear change reasons that a sync stored after a fact+ * purge had tombstoned them.+ *+ * Before #8635, a sync could read a page's `gbrain-reason` trailer, a fact purge could then commit and tombstone that+ * (source, commit, path), and the import would still store the purged text as the snapshot's `page_versions.change_reason`.+ * The fix stops new leaks; this repair finds the rows already stored. The purged claim is gone, so the match never uses it:+ * for each `reason_purge_tombstones` row the commit's trailers are read again from the source's checkout, with the same+ * functions sync uses, to get the exact text T the import stored. A version of a page in that source whose+ * `change_reason` equals T is a candidate:+ * - evidenced: its `source_path` is a spelling of the tombstoned path;+ * - path_mismatch (kept): another or no `source_path`, or the commit holds more than one reason for that path (the+ * purge may have matched the other one); cleared only with `--include-ambiguous` and that preview's hash.+ * A tombstone whose commit or trailer can no longer be read counts `unreadable_commit`; a source with no checkout (a+ * repo-less source) never stored a Git reason and counts `sources_without_checkout`. Neither refuses.+ *+ * The preview prints a per-brain count, a count per source and a few `<source>:<slug>@v<id>` items, never the reason+ * text, and saves the approved set (row ids and classes, never the text or a digest of it). The apply, bound to that hash+ * and the user's consent, reads the source's candidates from Git again, then takes the source `FOR UPDATE` as a purge+ * does and sets each approved row that is still a candidate of its class and still holds exactly that text to '[purged]',+ * the value the purge's own redaction writes; any other row is reported changed_since_preview and kept. Git history is+ * never rewritten. Never automatic.+ */+import { isAbsolute } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { canonicalChangeReason } from '../persistence/change-reason.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { gitTopLevel, pathForms, readReasonTrailers, trailerTexts, type TrailerCommit } from '../reason-trailers.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan } from './core.ts';++const COMMAND = 'purged-change-reasons' as const;+const DOCS = 'docs/guides/repair.md#purged-change-reasons';+const BATCH_ROWS = 500;+const SAMPLES = 5;+const PURGED_REASON = '[purged]';++export type LeakedReasonClass = 'evidenced' | 'path_mismatch';++export interface LeakedReason { id: number; source_id: string; slug: string; class: LeakedReasonClass }++/** `text` is the stored reason; it stays in memory and never reaches the approved set or the output. */+export interface LeakedReasonScan { rows: Array<LeakedReason & { text: string }>; unreadable_commit: number; without_checkout: boolean }++interface Approved { source_id: string; include_ambiguous: boolean; scope: string[]; rows: LeakedReason[] }+interface BatchItem extends RepairItem { batch: Approved; hash: string; last: boolean }+interface Details { brain_total: number; by_source: Record<string, number>; samples: Record<string, string[]>; sources_without_checkout: number }++/** The source's checkout, found the way the purge's trailer scan finds it; null for a repo-less source. */+async function checkoutRoot(engine: BrainEngine, sourceId: string): Promise<string | null> {+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [sourceId]);+ const root = source?.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);+ return root && isAbsolute(root) ? root : null;+}++async function readCommit(gitRoot: string, sha: string): Promise<TrailerCommit | null> {+ let found: TrailerCommit | null = null;+ const read = await readReasonTrailers(gitRoot, `${sha}^!`, 1, commit => { if (commit.sha === sha) found = commit; });+ return read.status === 'complete' ? found : null;+}++/** Every stored change reason of the source that is the trailer text of one of its tombstoned (commit, path) pairs. Read-only. */+export async function findLeakedChangeReasons(engine: BrainEngine, sourceId: string): Promise<LeakedReasonScan> {+ const tombstones = await engine.executeRaw<{ commit_sha: string; path: string }>(+ 'SELECT commit_sha, path FROM reason_purge_tombstones WHERE source_id = $1 ORDER BY commit_sha, path', [sourceId]);+ const root = await checkoutRoot(engine, sourceId);+ if (!root) return { rows: [], unreadable_commit: tombstones.length, without_checkout: true };+ const repo = tombstones.length ? gitTopLevel(root) : null;+ if (!repo) return { rows: [], unreadable_commit: tombstones.length, without_checkout: false };+ const forms = pathForms(repo.scopePrefix);+ const commits = new Map<string, TrailerCommit | null>();+ const pathsByText = new Map<string, Set<string>>();+ const sharedTexts = new Set<string>();+ let unreadable = 0;+ for (const tombstone of tombstones) {+ if (!commits.has(tombstone.commit_sha)) commits.set(tombstone.commit_sha, await readCommit(repo.gitRoot, tombstone.commit_sha));+ const commit = commits.get(tombstone.commit_sha);+ const raw = commit ? trailerTexts(commit, forms).byPath.get(tombstone.path) : undefined;+ const text = raw === undefined ? null : canonicalChangeReason(raw);+ if (text === null) { unreadable++; continue; }+ if (commit!.values.filter(value => trailerTexts({ ...commit!, values: [value] }, forms).byPath.has(tombstone.path)).length > 1) sharedTexts.add(text);+ const paths = pathsByText.get(text) ?? new Set<string>();+ for (const form of forms(tombstone.path)) paths.add(form);+ pathsByText.set(text, paths);+ }+ if (!pathsByText.size) return { rows: [], unreadable_commit: unreadable, without_checkout: false };+ const rows = await engine.executeRaw<{ id: number | string; slug: string; source_path: string | null; reason: string }>(+ `SELECT v.id, p.slug, v.source_path, v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND v.change_reason = ANY($2::text[]) ORDER BY v.id`, [sourceId, [...pathsByText.keys()]]);+ return {+ rows: rows.map(row => ({ id: Number(row.id), source_id: sourceId, slug: row.slug, text: row.reason,+ class: row.source_path !== null && !sharedTexts.has(row.reason) && pathsByText.get(row.reason)!.has(row.source_path) ? 'evidenced' : 'path_mismatch' })),+ unreadable_commit: unreadable, without_checkout: false,+ };+}++async function previewCommand(engine: BrainEngine, sourceIds: string[], includeAmbiguous: boolean): Promise<string> {+ const [{ n }] = await engine.executeRaw<{ n: number | string }>('SELECT count(*)::int AS n FROM sources WHERE archived IS NOT TRUE');+ return `gbrain repair ${COMMAND}${sourceIds.length === 1 && Number(n) > 1 ? ` --source ${sourceIds[0]}` : ''}${includeAmbiguous ? ' --include-ambiguous' : ''}`;+}++function batchItems(batches: Approved[], hash: string): BatchItem[] {+ return batches.map((batch, index) => ({ cursor: { phase: 0, id: index + 1 }, source_id: batch.source_id, slug: batch.rows[0]!.slug, chars: 0,+ action: `set ${batch.rows.length} leaked change reason(s) to '${PURGED_REASON}'`, batch, hash, last: index === batches.length - 1 }));+}++const sourcesOf = (engine: BrainEngine, ids: string[]) => engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [ids]);++const itemName = (row: LeakedReason) => `${row.source_id}:${row.slug}@v${row.id}`;++export const purgedChangeReasonsRepair: RepairHandler = {+ kind: COMMAND,+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const includeAmbiguous = opts?.includeAmbiguous === true;+ const command = await previewCommand(engine, scope.source_ids, includeAmbiguous);+ const hashOf = async (rows: LeakedReason[]) => previewHash({ kind: 'purged-change-reasons-v1', brain_id: scope.brain_id, sources: await sourcesOf(engine, scope.source_ids),+ selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous }, rows });+ if (opts?.apply) {+ if (!opts.expect) {+ throw new OperationError('invalid_params', `gbrain repair ${COMMAND} --apply clears only the set a preview printed.`,+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, DOCS);+ }+ const approved = await loadApprovedSet<Approved>(engine, { command: COMMAND, hash: opts.expect, previewCommand: command, emptyHash: () => hashOf([]) });+ const scopeKey = JSON.stringify(scope.source_ids);+ if (approved.items.some(batch => batch.include_ambiguous !== includeAmbiguous || JSON.stringify(batch.scope) !== scopeKey)) throw previewChangedError(opts.expect, command);+ const items = batchItems(approved.items, opts.expect).filter(item => afterCursor(item.cursor, after));+ if (!items.length) await clearApprovedSet(engine, { command: COMMAND, hash: opts.expect });+ return { items, preview_hash: opts.expect, residuals: {} };+ }+ const rows: LeakedReason[] = [];+ let unreadable = 0;+ let withoutCheckout = 0;+ for (const sourceId of scope.source_ids) {+ const scan = await findLeakedChangeReasons(engine, sourceId);+ rows.push(...scan.rows.map(({ text: _text, ...row }) => row));+ unreadable += scan.unreadable_commit;+ if (scan.without_checkout) withoutCheckout++;+ }+ const batches: Approved[] = [];+ for (const row of rows.filter(r => r.class === 'evidenced' || includeAmbiguous)) {+ const open = batches.at(-1);+ if (open && open.source_id === row.source_id && open.rows.length < BATCH_ROWS) open.rows.push(row);+ else batches.push({ source_id: row.source_id, include_ambiguous: includeAmbiguous, scope: scope.source_ids, rows: [row] });+ }+ const hash = await hashOf(batches.length ? rows : []);+ if (batches.length) await saveApprovedSet(engine, { command: COMMAND, hash }, batches);+ const bySource = new Map<string, number>();+ const samples = new Map<string, string[]>();+ for (const row of batches.flatMap(batch => batch.rows)) {+ bySource.set(row.source_id, (bySource.get(row.source_id) ?? 0) + 1);+ const items = samples.get(row.source_id) ?? [];+ if (items.length < SAMPLES) samples.set(row.source_id, [...items, itemName(row)]);+ }+ const details: Details = { brain_total: [...bySource.values()].reduce((sum, n) => sum + n, 0), by_source: Object.fromEntries(bySource),+ samples: Object.fromEntries(samples), sources_without_checkout: withoutCheckout };+ const kept = includeAmbiguous ? 0 : rows.filter(r => r.class === 'path_mismatch').length;+ return { items: batchItems(batches, hash), preview_hash: hash, details: details as unknown as Record<string, unknown>,+ residuals: { path_mismatch: kept, unreadable_commit: unreadable, sources_without_checkout: withoutCheckout } };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const item = entry as BatchItem;+ const current = new Map((await findLeakedChangeReasons(ctx.engine, item.source_id)).rows.map(row => [row.id, row]));+ const still = item.batch.rows.flatMap(row => { const now = current.get(row.id); return now && now.class === row.class ? [{ id: row.id, text: now.text }] : []; });+ const result = await maintenanceTransaction(ctx.engine, tx => clearBatch(tx, item.batch, still));+ if (item.last) await clearApprovedSet(ctx.engine, { command: COMMAND, hash: item.hash });+ if (!result.cleared.length) return { applied: false, outcome: 'changed_since_preview', reason: 'every approved row changed since the preview' };+ return { applied: true, outcome: 'cleared', detail: { cleared: result.cleared.length, ...(result.changed.length ? { changed_since_preview: result.changed } : {}) } };+ },+ render(raw): string[] {+ const details = raw as unknown as Details;+ const lines = [` ${details.brain_total} leaked change reason(s) in ${Object.keys(details.by_source).length} source(s) of this brain`];+ for (const [sourceId, count] of Object.entries(details.by_source)) {+ const samples = Object.hasOwn(details.samples, sourceId) ? details.samples[sourceId]! : [];+ lines.push(` ${sourceId}: ${count}`, ...samples.map(item => ` ${item}`));+ if (count > samples.length) lines.push(` and ${count - samples.length} more`);+ }+ if (details.sources_without_checkout) lines.push(` ${details.sources_without_checkout} source(s) without a Git checkout: nothing to check there`);+ return lines;+ },+};++/**+ * Under the source lock a purge takes: set each approved row that the apply's own Git read still finds (`still`, with the+ * text it found) to '[purged]' only while it holds exactly that text. Nothing outside the approved ids is written.+ */+async function clearBatch(tx: BrainEngine, batch: Approved, still: Array<{ id: number; text: string }>): Promise<{ cleared: number[]; changed: number[] }> {+ await tx.executeRaw('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [batch.source_id]);+ const ids = batch.rows.map(row => row.id);+ const cleared = still.length ? (await tx.executeRaw<{ id: number | string }>(+ `UPDATE page_versions v SET change_reason = $1 FROM pages p, unnest($3::bigint[], $4::text[]) AS t(id, reason)+ WHERE p.id = v.page_id AND p.source_id = $2 AND v.id = t.id AND v.change_reason = t.reason RETURNING v.id`,+ [PURGED_REASON, batch.source_id, still.map(row => row.id), still.map(row => row.text)])).map(row => Number(row.id)) : [];+ const done = new Set(cleared);+ return { cleared: cleared.sort((a, b) => a - b), changed: ids.filter(id => !done.has(id)) };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 1c2e0c1788..42008d61f5 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -58,6 +58,7 @@ import { atomFenceRowsRepair } from './atom-fence-rows.ts';import { extractorFactsRepair } from './extractor-facts.ts';import { unwithdrawnFactsRepair } from './unwithdrawn-facts.ts';import { purgedPageFactsRepair } from './purged-page-facts.ts';+import { purgedChangeReasonsRepair } from './purged-change-reasons.ts';import { conversationLabelsRepair } from './conversation-labels.ts';import { capturedFactsRepair } from './captured-facts.ts';import { agentSessionFactsRepair, agentSessionFlagArgs } from './agent-session-facts.ts';@@ -273,6 +274,20 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'not carry its facts) are retired only with --include-ambiguous; withdrawn, superseded and referenced rows are never touched. Preview-bound: '+ '--apply --expect <hash> --yes expires exactly the previewed rows; a row that changed since reports changed_since_preview. Database-only; runs only when named.',},+ 'purged-change-reasons': {+ handler: purgedChangeReasonsRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: "Set the previewed page-history change reasons that quote a purged claim to '[purged]'",+ why: 'The preview listed each stored change reason whose text is the Git reason of a (commit, path) a fact purge tombstoned; applying it redacts exactly those rows.',+ risk: "Database rows only: page_versions.change_reason becomes '[purged]', as the purge itself writes; no page, file or Git commit changes. "+ + 'A row whose reason changed since the preview is kept. The old text is not kept anywhere by this repair.',+ user_message: "Redact the previewed page-history change reasons that still quote a purged claim? They become '[purged]'; pages, files and Git history are unchanged.",+ },+ summary: 'Redact change reasons that a sync stored after a fact purge tombstoned them (before the #8635 fix): a page version in a source whose '+ + 'change_reason equals the Git reason trailer of a tombstoned (commit, path), re-read from the checkout. Rows whose source_path is that path are '+ + 'evidenced; the same text under another path is kept unless --include-ambiguous. Preview-bound: --apply --expect <hash> --yes sets exactly the '+ + "previewed rows to '[purged]'; a row that changed since reports changed_since_preview. Repo-less sources have nothing to check. Database-only; runs only when named.",+ },'conversation-labels': {handler: conversationLabelsRepair, embeds: 'none', checks: ['conversation_label_facts'], explicit_only: true, consent: 'destructive',consentText: {diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 7da067e6ea..f6c012eba3 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -193,7 +193,7 @@ for (const backend of testBackends()) {const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };- const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'atom-fence-rows': 'gbrain repair atom-fence-rows', 'extractor-facts': 'gbrain repair extractor-facts', 'unwithdrawn-facts': 'gbrain repair unwithdrawn-facts', 'purged-page-facts': 'gbrain repair purged-page-facts',+ const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'atom-fence-rows': 'gbrain repair atom-fence-rows', 'extractor-facts': 'gbrain repair extractor-facts', 'unwithdrawn-facts': 'gbrain repair unwithdrawn-facts', 'purged-page-facts': 'gbrain repair purged-page-facts', 'purged-change-reasons': 'gbrain repair purged-change-reasons','conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'agent-session-facts': 'gbrain repair agent-session-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-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', 'timeline-order': 'gbrain repair timeline-order', 'contact-rows': 'gbrain repair contact-rows', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', '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', 'moved-pages': 'gbrain repair moved-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d4c1e7b953..c952d75481 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -563,6 +563,7 @@ test/purge-scrub-followups-9068.test.tstest/purge-slug-stores-9146.test.tstest/purge-sync-tombstone-hold-7130.test.tstest/purged-change-reason-8635.test.ts+test/purged-change-reasons-repair-gst2886.test.tstest/qm-attest-write-boundary.test.tstest/qm-memory-propose.test.tstest/qm-memory-tools.test.tsdiff --git a/test/purged-change-reasons-repair-gst2886.test.ts b/test/purged-change-reasons-repair-gst2886.test.tsnew file mode 100644index 0000000000..2a7c8a4484--- /dev/null+++ b/test/purged-change-reasons-repair-gst2886.test.ts@@ -0,0 +1,352 @@+/**+ * GST-2886: change reasons leaked before the #8635 fix stay leaked until `gbrain repair purged-change-reasons` clears them.+ *+ * 1. Protects: before #8635 a sync could read a page's `gbrain-reason` trailer, a fact purge could commit and tombstone+ * that (commit, path), and the import could then store the purged text as the snapshot's `change_reason`. Brains+ * upgraded past the fix keep those rows. `gbrain repair purged-change-reasons` (explicit-only, preview-bound,+ * destructive) lists every stored reason whose text is the trailer of a tombstoned (source, commit, path), with a+ * per-brain count, and `--apply --expect <hash> --yes` sets exactly those to '[purged]'.+ * 2. Fails when: the leaked row is not listed, the count is wrong, the apply clears anything else (the sibling reason from+ * the same commit, a reason already '[purged]'), a second apply changes anything, or a repo-less brain refuses.+ * 3. Real temp Git repositories, the real classic and managed sync racing the real purge_fact handler (which writes the+ * real tombstone and version row; since #8635 that row stores NULL, so the test writes back the text a brain from+ * before the fix holds), and the real `gbrain repair` command; PGLite, plus Postgres when DATABASE_URL is set.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync } from '../src/commands/sync.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { hardenedGitStream } from '../src/core/hardened-git.ts';+import { __setReasonGitStreamForTests, clearReasonScanCache } from '../src/core/reason-trailers.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-purged-reason-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let serial = 0;++const page = (body: string) => `---\ntitle: Note\ntype: note\n---\n\n${body}\n`;+const SIBLING = 'Routine tidy-up.';++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function write(root: string, files: Record<string, string>): void {+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+}+function commit(root: string, message: string, reasons: string[] = []): string {+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '-m', message,+ ...reasons.flatMap(reason => ['--trailer', `gbrain-reason: ${reason}`]));+ return git(root, 'rev-parse', 'HEAD');+}+function newRepo(files: Record<string, string>): string {+ const root = join(home, `repo-${++serial}`);+ mkdirSync(root);+ git(root, 'init', '-q', '-b', 'main');+ write(root, files);+ commit(root, 'initial content');+ return root;+}++const ctx = (engine: BrainEngine, sourceId: string): OperationContext => ({ engine, sourceId, remote: false, dryRun: false,+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);+const run = (engine: BrainEngine, sourceId: string, name: string, params: Record<string, unknown>) =>+ operations.find(o => o.name === name)!.handler(ctx(engine, sourceId), params) as Promise<Record<string, any>>;++const factFence = (claim: string) => `<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |+<!--- gbrain:facts:end -->`;+/** A database-only page holding the claim as a fact, so purge_fact has a target in the source. */+async function seedFact(engine: BrainEngine, sourceId: string, slug: string, claim: string): Promise<number> {+ await importFromContent(engine, slug, `---\ntitle: Holder\ntype: person\n---\n# Holder\n\nProse.\n\n## Facts\n\n${factFence(claim)}\n`, { noEmbed: true, sourceId });+ await runExtractFacts(engine, { slugs: [slug], sourceId });+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact = $1 AND entity_slug = $2', [claim, slug]);+ return Number(row!.id);+}+async function purge(engine: BrainEngine, sourceId: string, id: number): Promise<Record<string, any>> {+ const dry = await run(engine, sourceId, 'purge_fact', { id, source_id: sourceId, dry_run: true });+ return run(engine, sourceId, 'purge_fact', { id, source_id: sourceId, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });+}++/** Classic: the next reason scan reads Git, then the purge runs to its commit before the scan's result reaches the pass. */+function purgeAfterNextScan(purgeNow: () => Promise<Record<string, any>>): () => Promise<Record<string, any>> {+ let started: Promise<Record<string, any>> | null = null;+ __setReasonGitStreamForTests(async (root, args, opts) => {+ const result = await hardenedGitStream(root, args, opts);+ if (!started) { started = purgeNow(); await started; }+ return result;+ });+ return () => started ?? Promise.reject(new Error('no reason scan ran'));+}+/** Managed: the purge runs to its commit once the request for `slug` is prepared, before its publication starts. */+function purgeOncePrepared(engine: BrainEngine, slug: string, purgeNow: () => Promise<Record<string, any>>): () => Promise<Record<string, any>> {+ let started: Promise<Record<string, any>> | null = null;+ installFaultHook(async (point, detail) => {+ if (started || point !== 'consumer:prepared' || !detail.requestId) return;+ const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id = $1::uuid', [detail.requestId]);+ if (row?.slug !== slug) return;+ started = purgeNow();+ await started;+ });+ return () => started ?? Promise.reject(new Error(`no request for ${slug} was prepared`));+}+++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);++async function leakedRows(engine: BrainEngine, sourceId: string, claim: string): Promise<Array<{ id: number; reason: string }>> {+ return (await engine.executeRaw<{ id: number; reason: string }>(`SELECT v.id, v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND strpos(lower(v.change_reason), $2) > 0 ORDER BY v.id`, [sourceId, claim.toLowerCase()])).map(row => ({ id: Number(row.id), reason: row.reason }));+}+async function siblingReason(engine: BrainEngine, sourceId: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ reason: string | null }>(`SELECT v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = 'notes/b' ORDER BY v.id DESC LIMIT 1`, [sourceId]);+ return rows[0]?.reason ?? null;+}+async function repairCli(engine: BrainEngine, args: string[]): Promise<{ out: string; error?: OperationError }> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await inHome(() => runRepairCommand(engine, args)); return { out: lines.join('\n') }; }+ catch (error) { if (error instanceof OperationError) return { out: lines.join('\n'), error }; throw error; }+ finally { console.log = original; }+}+const lastJson = (out: string) => JSON.parse(out.slice(out.lastIndexOf('\n{') + 1 || 0)).results[0];+const leakedText = (claim: string) => `Changed after ${claim} was rotated.`;+async function latestVersion(engine: BrainEngine, sourceId: string, slug: string): Promise<{ id: number; reason: string | null }> {+ const [row] = await engine.executeRaw<{ id: number; reason: string | null }>(`SELECT v.id, v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id DESC LIMIT 1`, [sourceId, slug]);+ return { id: Number(row!.id), reason: row!.reason };+}+/** Since #8635 the race stores NULL; a brain that ran the race before the fix holds the trailer text in that same row. */+async function asBeforeTheFix(engine: BrainEngine, leak: Leak): Promise<void> {+ const row = await latestVersion(engine, leak.sourceId, 'notes/a');+ expect(row.reason).toBeNull();+ await engine.executeRaw('UPDATE page_versions SET change_reason = $1 WHERE id = $2', [leakedText(leak.claim), row.id]);+}+const reasonOf = async (engine: BrainEngine, id: number) => (await engine.executeRaw<{ reason: string | null }>('SELECT change_reason AS reason FROM page_versions WHERE id = $1', [id]))[0]!.reason;++interface Leak { sourceId: string; claim: string; fact: number; pushed: string; root: string }++/** Classic sync, as master runs it today: the pass reads the trailers, the purge commits, the import stores the reason. */+async function classicLeak(engine: BrainEngine, sourceId = `leak-classic-${serial + 1}`, firstReason?: string): Promise<Leak> {+ const n = ++serial;+ const claim = `Vault code is ${7100 + n}`;+ const root = newRepo({ 'notes/a.md': page('A one.'), 'notes/b.md': page('B one.') });+ await runSources(engine, ['add', sourceId, '--path', root, '--no-federated']);+ const sync = () => performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });+ await sync();+ write(root, { 'notes/a.md': page('A two.'), 'notes/b.md': page('B two.') });+ const pushed = commit(root, 'edit', [...(firstReason ? [`notes/a.md: ${firstReason}`] : []), `notes/a.md: Changed after ${claim} was rotated.`, `notes/b.md: ${SIBLING}`]);+ const fact = await seedFact(engine, sourceId, `people/vault-example-${n}`, claim);+ const purged = purgeAfterNextScan(() => purge(engine, sourceId, fact));+ await sync();+ expect((await purged()).state).toBe('committed');+ __setReasonGitStreamForTests();+ return { sourceId, claim, fact, pushed, root };+}++/** Managed sync, as master runs it today: the request was prepared from the pass's scan, the purge commits, then it publishes. */+async function managedLeak(engine: BrainEngine): Promise<Leak> {+ const n = ++serial;+ const claim = `Alarm phrase is ${8200 + n}`;+ const sourceId = `leak-managed-${n}`;+ const root = newRepo({ 'notes/a.md': page('A one.'), 'notes/b.md': page('B one.') });+ 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]);+ const fact = await seedFact(engine, sourceId, `people/alarm-example-${n}`, claim);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1');+ try {+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('first_sync');+ write(root, { 'notes/a.md': page('A two.'), 'notes/b.md': page('B two.') });+ const pushed = commit(root, 'edit', [`notes/a.md: Changed after ${claim} was rotated.`, `notes/b.md: ${SIBLING}`]);+ const purged = purgeOncePrepared(engine, 'notes/a', () => purge(engine, sourceId, fact));+ await performManagedSync(engine, { sourceId, noPull: true });+ expect((await purged()).state).toBe('committed');+ return { sourceId, claim, fact, pushed, root };+ } finally {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await engine.executeRaw('UPDATE persistence_brain SET enabled = false WHERE singleton = 1');+ }+}++beforeAll(async () => inHome(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) await registerLocalWriter(engine, 'cli');+}), 180_000);+afterEach(() => { __setReasonGitStreamForTests(); installFaultHook(undefined); clearReasonScanCache(); });+afterAll(async () => {+ await inHome(async () => { for (const engine of engines) await disposePersistenceConsumer(engine).catch(() => undefined); });+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++for (const backend of ['pglite', 'postgres'] as const) {+ const engineOf = () => engines.find(engine => engine.kind === backend)!;+ describe(`[${backend}] GST-2886: change reasons leaked before #8635`, () => {+ const leaks: Leak[] = [];+ const skip = backend === 'postgres' && !process.env.DATABASE_URL;++ test.skipIf(skip)('a brain from before #8635 holds the purged reason under a tombstoned (commit, path), after classic and managed syncs', async () => inHome(async () => {+ const engine = engineOf();+ leaks.push(await classicLeak(engine), await managedLeak(engine));+ for (const leak of leaks) {+ await asBeforeTheFix(engine, leak);+ expect(await engine.executeRaw('SELECT commit_sha, path FROM reason_purge_tombstones WHERE source_id = $1', [leak.sourceId]))+ .toEqual([{ commit_sha: leak.pushed, path: 'notes/a.md' }]);+ expect((await leakedRows(engine, leak.sourceId, leak.claim)).map(row => row.reason)).toEqual([`Changed after ${leak.claim} was rotated.`]);+ expect(await siblingReason(engine, leak.sourceId)).toBe(SIBLING);+ }+ }), 300_000);++ test.skipIf(skip)('no other command clears it: repair --all (preview and apply) and a second purge', async () => inHome(async () => {+ const engine = engineOf();+ expect(leaks).toHaveLength(2);+ const preview = await repairCli(engine, ['--all', '--json']);+ for (const leak of leaks) expect(preview.out.toLowerCase()).not.toContain(leak.claim.toLowerCase());+ await repairCli(engine, ['--all', '--apply', '--json']);+ for (const leak of leaks) {+ expect(await leakedRows(engine, leak.sourceId, leak.claim)).toHaveLength(1);+ const again = await run(engine, leak.sourceId, 'purge_fact', { id: leak.fact, source_id: leak.sourceId, dry_run: true }).then(() => null, (error: unknown) => error);+ expect(again).toBeInstanceOf(OperationError);+ expect(await leakedRows(engine, leak.sourceId, leak.claim)).toHaveLength(1);+ }+ }), 300_000);++ test.skipIf(skip)('repair purged-change-reasons: preview counts the leaked rows per brain, apply clears exactly them, a rerun changes nothing', async () => inHome(async () => {+ const engine = engineOf();+ expect(leaks).toHaveLength(2);+ const human = await repairCli(engine, ['purged-change-reasons']);+ expect(human.error?.message).toBeUndefined();+ expect(human.out).toContain('2 leaked change reason(s) in 2 source(s) of this brain');+ for (const leak of leaks) expect(human.out).toContain(`${leak.sourceId}:notes/a@v`);+ for (const leak of leaks) expect(human.out.toLowerCase()).not.toContain(leak.claim.toLowerCase());+ const preview = await repairCli(engine, ['purged-change-reasons', '--json']);+ expect(preview.error?.message).toBeUndefined();+ const planned = lastJson(preview.out);+ expect(planned.mode).toBe('dry_run');+ expect(planned.details.brain_total).toBe(2);+ for (const leak of leaks) expect(planned.details.by_source[leak.sourceId]).toBe(1);+ expect(planned.residuals).toMatchObject({ path_mismatch: 0, unreadable_commit: 0 });+ for (const leak of leaks) expect(preview.out.toLowerCase()).not.toContain(leak.claim.toLowerCase());+ expect(typeof planned.preview_hash).toBe('string');++ const applied = lastJson((await repairCli(engine, ['purged-change-reasons', '--apply', '--expect', planned.preview_hash, '--yes', '--json'])).out);+ expect(applied.outcome_items.reduce((sum: number, item: { detail: { cleared: number } }) => sum + item.detail.cleared, 0)).toBe(2);+ for (const leak of leaks) {+ expect(await leakedRows(engine, leak.sourceId, leak.claim)).toEqual([]);+ const [cleared] = await engine.executeRaw<{ reason: string | null }>(`SELECT v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = 'notes/a' ORDER BY v.id DESC LIMIT 1`, [leak.sourceId]);+ expect(cleared?.reason).toBe('[purged]');+ expect(await siblingReason(engine, leak.sourceId)).toBe(SIBLING);+ }+ const rerun = lastJson((await repairCli(engine, ['purged-change-reasons', '--json'])).out);+ expect(rerun.affected).toBe(0);+ expect(rerun.details.brain_total).toBe(0);+ }), 300_000);++ // The source id is one an object prototype holds, so a per-source tally kept in a plain object would break.+ test.skipIf(skip)('consent, a stale hash, a row changed since the preview, the same text under another path, a missing checkout, and a source named constructor', async () => inHome(async () => {+ const engine = engineOf();+ const leak = await classicLeak(engine, 'constructor');+ await asBeforeTheFix(engine, leak);+ const leaked = await latestVersion(engine, leak.sourceId, 'notes/a');+ const elsewhere = await latestVersion(engine, leak.sourceId, 'notes/b');+ expect(elsewhere.reason).toBe(SIBLING);+ await engine.executeRaw('UPDATE page_versions SET change_reason = $1 WHERE id = $2', [leakedText(leak.claim), elsewhere.id]);+ const cli = (...args: string[]) => repairCli(engine, ['purged-change-reasons', '--source', leak.sourceId, ...args, '--json']);++ const gone = `${leak.root}.moved`;+ renameSync(leak.root, gone);+ const blind = await cli();+ renameSync(gone, leak.root);+ expect(blind.error?.message).toBeUndefined();+ expect(lastJson(blind.out).residuals).toMatchObject({ unreadable_commit: 1 });+ expect(lastJson(blind.out).details.brain_total).toBe(0);++ const human = await repairCli(engine, ['purged-change-reasons', '--source', leak.sourceId]);+ expect(human.out).toContain('1 leaked change reason(s) in 1 source(s) of this brain');+ expect(human.out).toContain('constructor:notes/a@v');+ const planned = lastJson((await cli()).out);+ expect(planned.details.brain_total).toBe(1);+ expect(planned.details.by_source).toEqual({ constructor: 1 });+ expect(planned.residuals).toMatchObject({ path_mismatch: 1, unreadable_commit: 0, sources_without_checkout: 0 });++ const previous = process.exitCode;+ const unconsented = await cli('--apply', '--expect', planned.preview_hash);+ const exitCode = process.exitCode;+ process.exitCode = previous ?? 0;+ expect(unconsented.error?.message).toBeUndefined();+ expect(exitCode).toBe(3);+ expect(await reasonOf(engine, leaked.id)).toBe(leakedText(leak.claim));+ expect((await cli('--apply', '--expect', 'f'.repeat(64), '--yes')).error?.code).toBe('preview_changed');++ await engine.executeRaw('UPDATE page_versions SET change_reason = $1 WHERE id = $2', ['Rewritten by hand.', leaked.id]);+ const changed = lastJson((await cli('--apply', '--expect', planned.preview_hash, '--yes')).out);+ expect(changed.outcomes).toMatchObject({ changed_since_preview: 1 });+ expect(await reasonOf(engine, leaked.id)).toBe('Rewritten by hand.');+ expect(await reasonOf(engine, elsewhere.id)).toBe(leakedText(leak.claim));++ await engine.executeRaw('UPDATE page_versions SET change_reason = $1 WHERE id = $2', [leakedText(leak.claim), leaked.id]);+ const widened = lastJson((await cli('--include-ambiguous')).out);+ expect(widened.details.brain_total).toBe(2);+ await cli('--include-ambiguous', '--apply', '--expect', widened.preview_hash, '--yes');+ expect(await reasonOf(engine, leaked.id)).toBe('[purged]');+ expect(await reasonOf(engine, elsewhere.id)).toBe('[purged]');+ expect(lastJson((await cli('--include-ambiguous')).out).details.brain_total).toBe(0);+ }), 300_000);++ // Sync stores the first reason a commit gives a file; when the commit gives that file two, the purge may have matched the other one.+ test.skipIf(skip)('a commit with two reasons for one file: the stored first reason is kept as path_mismatch, not redacted', async () => inHome(async () => {+ const engine = engineOf();+ const leak = await classicLeak(engine, undefined, 'Benign first note.');+ const row = await latestVersion(engine, leak.sourceId, 'notes/a');+ expect(row.reason).toBeNull();+ await engine.executeRaw('UPDATE page_versions SET change_reason = $1 WHERE id = $2', ['Benign first note.', row.id]);+ const planned = lastJson((await repairCli(engine, ['purged-change-reasons', '--source', leak.sourceId, '--json'])).out);+ expect(planned.details.brain_total).toBe(0);+ expect(planned.residuals).toMatchObject({ path_mismatch: 1, unreadable_commit: 0 });+ }), 300_000);++ // A repo-less source has no trailers and no tombstones; the preview says so and exits clean.+ test.skipIf(skip)('repo-less source: the preview lists nothing and does not refuse', async () => inHome(async () => {+ const engine = engineOf();+ const sourceId = `repo-less-${++serial}`;+ await engine.executeRaw(`INSERT INTO sources(id, name, config) VALUES ($1, $1, '{}')`, [sourceId]);+ await importFromContent(engine, 'notes/plain', page('Plain.'), { noEmbed: true, sourceId });+ const preview = await repairCli(engine, ['purged-change-reasons', '--source', sourceId, '--json']);+ expect(preview.error?.message).toBeUndefined();+ const planned = lastJson(preview.out);+ expect(planned.affected).toBe(0);+ expect(planned.details.sources_without_checkout).toBe(1);+ expect(planned.residuals).toMatchObject({ sources_without_checkout: 1, unreadable_commit: 0 });+ }), 120_000);+ });+}diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 7a220630b1..27f399ad32 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', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels', 'open-facts'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'purged-change-reasons', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels', 'open-facts'];// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.// open-facts (#8194) needs --source and --created-before, which only the operator can name, so no surface lists it.const LISTED = EXPLICIT.filter(kind => kind !== 'open-facts');@@ -113,7 +113,7 @@ describe('surfaces that list instead of run', () => {expect(out.explicit_kinds).toEqual(LISTED.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));}- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair atom-fence-rows; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair purged-page-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair atom-fence-rows; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair purged-page-facts; gbrain repair purged-change-reasons; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');});test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex 77c6341239..0200523c58 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -60,6 +60,7 @@ const EXEMPT: Record<string, string> = {'src/core/repair/fact-claim-dates.ts': 'owner repair moving the valid_from of existing database-only facts to the date their claim states (lifecycle)','src/core/repair/extractor-facts.ts': 'owner repair of existing rows','src/core/repair/purged-page-facts.ts': 'owner repair behind a preview hash: only sets expired_at and clears row_num on existing fact rows (lifecycle); writes no new text',+ 'src/core/repair/purged-change-reasons.ts': 'owner repair behind a preview hash: only sets matched page_versions.change_reason values to [purged] (redaction); writes no new text','src/core/repair/unwithdrawn-facts.ts': 'owner repair behind a preview hash: puts back an existing fact row\'s own ledger before-state (lifecycle and row number); no new text','src/core/generations/fence-evidence.ts': 'renumbers a kept existing fact row inside the gated fence projection or reconcile; no new text','src/core/repair/secret-spans.ts': 'owner repair behind a preview hash: replaces only the credential spans the secret scanner finds in a page\'s stored copies with <REDACTED:rule> markers (no new text)',