Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
repair atoms-restore: revert to the archived live version; docs, key files and guard allowlist (#7013)
garrytan4f7431bcf452
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 9669644346..601620e1cc 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -14,6 +14,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` and no recorded origin (blank `source_path` and `source_uri`) per source, via `databaseOnlyPageSql` (`persistence/unbound-pages.ts`), the SQL form of `isDatabaseOnlyPage` (#6536). A managed sync that records a page's origin, and a reconcile apply, clear the marker. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Tests: `e2e/unbound-source-postgres`, `unbound-source-6536`.- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.+- `src/commands/doctor/checks/atom-retirements.ts` — `atom_retirements_restorable` (#7013, BRAIN, a `WAVE_CHECKS` entry with `resolution: 'repair'`, host-only, cleared by the explicit-only `atoms-restore`, so remediation classifies it `explicit_kind_required`): counts atoms `restorableAtomRetirementSql` selects per source; `warn` names the count, origins, oldest and newest `retired_at`, the end of the earliest purge hold (`hold_until`) and the read-only preview `gbrain repair atoms-restore --source <id> --json` as an agent `fix`; the apply is the user's call.- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_label_facts` (wave check, host-only, resolution `repair`): bounded count (capped at 1000, reported as at least N) of the default set `gbrain repair conversation-labels` would retire; names the preview, never the apply. `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.- `src/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex b1c474b854..a9b711f0b4 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -22,5 +22,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.- `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/atom-retirement-hold.ts` — #7013: the one SQL rule for atoms `gbrain repair atoms-restore` restores (`restorableAtomRetirementSql`: a non-imported atom soft-deleted with `retired_by: managed-reextract`, whose origin is a live page of its source or a transcript, that no live atom of the same origin with another stripped source hash replaced, and whose hash is the hash of the origin's latest `managed-reextract` retirement), its parts (used for the preview residuals) and `atomRetirementPurgeHold`, which keeps such an atom out of every batch purge selection (engine `purgeDeletedPages` preview and delete, the belief-ledger expiry, `selectPurgeCandidates`) for `ATOM_RESTORE_HOLD_DAYS` (30) after `deleted_at`, next to the #6729 `identityDowngradePurgeHold`. An explicit `delete --purge` is not held. Static strings only, so `engine-sql/pages.ts` imports it.+- `src/core/repair/atoms-restore.ts` — `gbrain repair atoms-restore` (#7013), explicit-only and preview-bound: lists atoms an empty managed re-extraction retired (`retired_by: managed-reextract`) that `restorableAtomRetirementSql` (`persistence/atom-retirement-hold.ts`) selects, each with origin, stripped source hash and `retired_at`, and residuals `restorable`, `origins`, `origin_gone`, `replaced`, `older_generation`; `--apply --expect <hash>` restores the approved set, rechecking each atom (id, incarnation, revision, origin, hash, `retired_at`, rule match) and reporting `changed_since_preview` otherwise. Managed: one `managed_maintenance_restore_reextract_atom` request per atom (`deleted_page: true`, bound to the deleted revision, request id in the outcome detail); `prepareAtomRestore` (dispatched from `prepared-maintenance.ts`) rechecks the rule under the atom and origin page locks and publishes a revision-bound `revert_version` to `version_id`, the newest live version of the atom at its source hash without `retired_by` (the one the coordinated delete archived; file written back, `allowMissingFile`); none is `no_version`, lowered to the `derive:atoms` tier of its origin with taint edges. Unmanaged: `createVersion`, `restorePage` and the two keys dropped in one `maintenanceTransaction`. Extraction state is not touched. Test: `test/pathological/d24-atoms-restore.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`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 5627788632..df780aa5c4 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`, `extractor-facts`,+The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `extractor-facts`,`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases` and `rename-identity`, 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@@ -108,7 +108,7 @@ 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`, `extractor-facts`, `captured-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |+| `--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`, `captured-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. || `--include-ambiguous` | `extractor-facts` and `captured-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). || `--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). |@@ -1229,6 +1229,58 @@ than the preview also refuses with `preview_changed`. Doctor`atom_provenance_drift` names this command when drift crosses its warnthreshold.+### Atoms restore++A managed atom re-extraction whose model returned no atoms for a page or+transcript (#7013) retired every earlier atom of that origin: each one was+soft-deleted and stamped `retired_by: managed-reextract`, and the purge then+removed it for good. `gbrain repair atoms-restore` brings them back. It is+explicit-only and preview-bound, and nothing runs on upgrade.++```bash+gbrain repair atoms-restore --source <id> --json # preview: each atom with its origin, hash and retirement time, and a hash+gbrain repair atoms-restore --source <id> --apply --expect <hash>+```++The preview lists a retired atom only when all of these hold:++- it is not imported (`imported_from`) and carries `retired_by: managed-reextract`+ (a `stale-atoms` retirement is never listed);+- its origin is still there: a live page of the same source (`source_slug`), or+ a transcript (`source_path`);+- no live atom of the same origin carries a different source hash, so no later+ extraction replaced it;+- it belongs to the origin's most recently retired generation (its source hash+ is the hash of the origin's latest `managed-reextract` retirement), so an older+ generation that a later non-empty extraction replaced is never revived.++The residuals count what it keeps: `origin_gone`, `replaced` and+`older_generation`, next to `restorable` and the number of `origins`.++The apply restores exactly the previewed set and checks each atom again first;+one whose revision or rule match changed since the preview (for example a new+extraction replaced it) reports `changed_since_preview` and stays deleted. On a+managed brain each atom is one coordinated request bound to the deleted atom's+revision: it reverts the atom to the live version its retirement archived+(same source hash, no `retired_by`/`retired_at`), writes its canonical file+back, keeps the derived trust tier an extraction gives it, and the outcome names+the request id (`gbrain write-request -- <id>` reads its receipt). An atom with+no such version reports `no_version` and stays deleted. A file that differs from the database at the atom's path reports+`file_conflict` and is left as it is. On an unmanaged brain the atom is+versioned, restored and has the two keys removed in one transaction. Neither+changes the origin's extraction state. `--apply` without `--expect` refuses with+the preview and apply commands; a stale hash or another `--source` refuses with+[`preview_changed`](#preview-changed).++The batch purge (the maintenance cycle, `gbrain pages purge-deleted` and the+unmanaged bulk delete) holds every atom the preview would list for 30 days+after its deletion instead of the usual 72 hours, so an operator who upgrades+late can still restore it. An explicit `gbrain delete <slug> --purge` is not+held. Doctor `atom_retirements_restorable` warns while such atoms exist, with+their count, origins, oldest and newest retirement and the date the first hold+ends; its fix is the read-only preview. Show the user the preview before+running the apply.+### Extractor factsA managed write by a gbrain older than v0.60.11.0 to a conversation pagediff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 4441a04f29..ffaba3ccf9 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -74,6 +74,7 @@ const VETTED_BUILDERS: Record<string, string> = {rederiveHiddenSql: 'src/core/eligibility/sql.ts: constant needs_rederive NOT EXISTS predicate over a literal table name and caller alias; no values',privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',+ atomRetirementPurgeHold: 'src/core/persistence/atom-retirement-hold.ts: constant #7013 restorable-atom purge-hold predicate over a caller pages alias; no values',rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex f5ec01e770..bd8255e6d9 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -157,7 +157,8 @@ export interface PurgeCandidate { source_id: string; slug: string; cutoff: strin* #6741 C: what a purge with these options would do, read-only. The one eligibility selector behind the* `pages purge-deleted` dry-run preview, its consent request, the `purge_deleted_pages` op and the real purge (the* CLI, the cycle phase and the Minion job), so the preview, the consent and the run cannot disagree. The- * `--older-than` cutoff and the #6729 rename-recovery hold (identityDowngradePurgeHold) apply to every page, parked+ * `--older-than` cutoff, the #6729 rename-recovery hold (identityDowngradePurgeHold) and the #7013 restorable-atom hold+ * (atomRetirementPurgeHold) apply to every page, parked* or not, so `retryParked` retries only parked pages the cutoff selects and never a held page.*/export interface PurgeSelection {diff --git a/src/core/repair/atoms-restore.ts b/src/core/repair/atoms-restore.tsindex 5d52b84d58..0150b3f96c 100644--- a/src/core/repair/atoms-restore.ts+++ b/src/core/repair/atoms-restore.ts@@ -13,9 +13,9 @@* is rechecked when it is restored; one whose revision or rule match changed reports `changed_since_preview` and* stays deleted. A managed brain restores one atom per `managed_maintenance_restore_reextract_atom` request bound to* the atom's deleted revision: its preparer rechecks the rule under the atom's and its origin's page locks and- * publishes the atom live through a revision-bound `put_page` of its stored body without `retired_by`/`retired_at`- * (the canonical file is written back, at the derived tier an extraction gives it), and the outcome names the- * request id. An unmanaged brain versions the atom, clears `deleted_at` and drops the two keys in one+ * publishes the atom live through a revision-bound `revert_version` to the live version its retirement archived (same+ * source hash, no `retired_by`/`retired_at`; the canonical file is written back, at the derived tier an extraction+ * gives it), and the outcome names the request id; an atom with no such version reports `no_version`. An unmanaged brain versions the atom, clears `deleted_at` and drops the two keys in one* maintenance transaction. Neither changes the origin's extraction state.*/import type { BrainEngine } from '../engine.ts';@@ -24,7 +24,6 @@ import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';import { opError, OperationError, type OperationContext } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';-import { serializePageToMarkdown } from '../markdown.ts';import { authorizeWrite } from '../persistence/authority.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';@@ -54,6 +53,8 @@ export interface RestorableAtom {/** The atom's source hash with a `pending:` prefix stripped. */hash: string;retired_at: string | null;+ /** The newest live version of the atom (the one its retirement archived) at the same hash and unstamped; a managed restore reverts to it. */+ version_id: number | null;}interface RestoreItem extends RepairItem { atom: RestorableAtom; hash: string; last: boolean }@@ -70,11 +71,15 @@ async function restorableAtoms(db: BrainEngine, sourceIds: string[], atomId?: nuCOALESCE(NULLIF(a.frontmatter->>'source_slug',''), a.frontmatter->>'source_path') AS origin,(SELECT o.id FROM pages o WHERE o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug' AND o.deleted_at IS NULL) AS origin_page_id,regexp_replace(COALESCE(a.frontmatter->>'source_hash',''),'^pending:','') AS hash,- a.frontmatter->>'retired_at' AS retired_at+ a.frontmatter->>'retired_at' AS retired_at,+ (SELECT v.id FROM page_versions v WHERE v.page_id=a.id AND v.is_deleted=false AND v.frontmatter->>'retired_by' IS NULL+ AND regexp_replace(COALESCE(v.frontmatter->>'source_hash',''),'^pending:','')=regexp_replace(COALESCE(a.frontmatter->>'source_hash',''),'^pending:','')+ ORDER BY v.id DESC LIMIT 1) AS version_idFROM pages aWHERE a.source_id=ANY($1::text[]) AND ($2::int IS NULL OR a.id=$2::int) AND ${restorableAtomRetirementSql('a')}ORDER BY a.id`, [sourceIds, atomId ?? null]);- return rows.map(row => ({ ...row, id: Number(row.id), origin_page_id: row.origin_page_id === null ? null : Number(row.origin_page_id) }));+ return rows.map(row => ({ ...row, id: Number(row.id), origin_page_id: row.origin_page_id === null ? null : Number(row.origin_page_id),+ version_id: row.version_id === null ? null : Number(row.version_id) }));}/** The re-extraction retirements of these sources the rule keeps, by reason. */@@ -90,7 +95,7 @@ async function keptCounts(db: BrainEngine, sourceIds: string[]): Promise<{ origi}function sameAtom(live: RestorableAtom | undefined, approved: RestorableAtom): boolean {- return !!live && (['id', 'source_id', 'incarnation', 'slug', 'revision', 'origin_kind', 'origin', 'origin_page_id', 'hash', 'retired_at'] as const)+ return !!live && (['id', 'source_id', 'incarnation', 'slug', 'revision', 'origin_kind', 'origin', 'origin_page_id', 'hash', 'retired_at', 'version_id'] as const).every(field => live[field] === approved[field]);}@@ -148,6 +153,8 @@ async function restoreAtom(ctx: OperationContext, atom: RestorableAtom): Promiseconst changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });if (!sameAtom((await restorableAtoms(engine, [atom.source_id], atom.id))[0], atom)) return changed('the atom, its origin or a later generation changed');if (await managedPersistenceEnabled(engine)) {+ if (atom.version_id === null) return { applied: false, outcome: 'no_version',+ reason: 'the atom has no archived live version at its source hash to revert to, so a managed restore cannot rebuild it' };const authority = (await maintenancePreflight(engine, atom.source_id))!;const requestId = await repairRequestId(ctx, 'atoms-restore', atom, atom.revision);try {@@ -177,7 +184,7 @@ const previewFix = (sourceId: string) => readFix('Previews the atoms-restore rep/** Preparer for `managed_maintenance_restore_reextract_atom`: rechecks the rule under the atom's and its origin's page locks, then publishes the atom live. */export async function prepareAtomRestore(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const atom = row.intent!.atom as RestorableAtom;- if (!atom || atom.slug !== row.slug || atom.source_id !== row.source_id || atom.id !== Number(row.page_id)) {+ if (!atom || atom.slug !== row.slug || atom.source_id !== row.source_id || atom.id !== Number(row.page_id) || atom.version_id === null) {throw opError('invalid_params', 'The atom restore intent does not name its atom.',`Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the atom it restores, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,{ fix: previewFix(row.source_id) });@@ -190,17 +197,14 @@ export async function prepareAtomRestore(engine: BrainEngine, row: WriteRequest,}};await unchanged(engine);- await authorizeWrite(engine, row.authority, 'put_page', row.slug);- const snapshot = (await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true }))!;- const { retired_by: _retiredBy, retired_at: _retiredAt, ...frontmatter } = snapshot.page.frontmatter;+ await authorizeWrite(engine, row.authority, 'revert_version', row.slug);const derivation = await deriveTrust(engine, atom.origin_page_id !== null ? [{ table: 'pages', id: atom.origin_page_id }] : [],{ channel: 'derive:atoms', requestId: row.id });- const page = await preparePageMutation(engine, { ...row, operation: 'put_page', intent: { kind: ATOMS_RESTORE_INTENT, expected_revision: atom.revision,- content: serializePageToMarkdown({ ...snapshot.page, frontmatter }, snapshot.tags), derivation: declareDerivation(derivation.trust, derivation.inputs) } },- config, undefined, undefined, { allowMissingFile: true });+ const page = await preparePageMutation(engine, { ...row, operation: 'revert_version', intent: { kind: ATOMS_RESTORE_INTENT, expected_revision: atom.revision,+ version_id: atom.version_id, derivation: declareDerivation(derivation.trust, derivation.inputs) } }, config, undefined, undefined, { allowMissingFile: true });return { ...page, trust: derivation.trust,additionalPageKeys: [...(page.additionalPageKeys ?? []), ...(atom.origin_kind === 'page' ? [{ sourceId: row.source_id, slug: atom.origin }] : [])],- validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await unchanged(tx); },+ validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'revert_version', row.slug); await unchanged(tx); },apply: async tx => {const outcome = await page.apply(tx);const [live] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [row.source_id, row.slug]);