Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP: atoms-restore repair, purge hold and doctor check (#7013)
garrytan408a1d456617
diff --git a/src/commands/doctor/checks/atom-retirements.ts b/src/commands/doctor/checks/atom-retirements.tsnew file mode 100644index 0000000000..d402659c51--- /dev/null+++ b/src/commands/doctor/checks/atom-retirements.ts@@ -0,0 +1,51 @@+/**+ * #7013 `atom_retirements_restorable`: atoms a managed re-extraction retired (`retired_by: managed-reextract`) that+ * `gbrain repair atoms-restore` can bring back, by the one rule the repair and the purge hold share+ * (`restorableAtomRetirementSql`). A `WAVE_CHECKS` entry: `ok` when none; `warn` with the count, the origins, the+ * oldest and newest retirement, the date the purge hold of the earliest one ends, and the read-only preview as fix.+ * The apply needs the user's agreement on the previewed set. Read-only.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';+import { ATOM_RESTORE_HOLD_DAYS, restorableAtomRetirementSql } from '../../../core/persistence/atom-retirement-hold.ts';++const DOCS = 'docs/guides/repair.md#atoms-restore';++export async function atomRetirementsRestorableCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const rows = await engine.executeRaw<{ source_id: string; count: number; origins: number; oldest: string | null; newest: string | null; hold_until: string }>(`+ SELECT p.source_id, count(*)::int AS count,+ count(DISTINCT COALESCE(NULLIF(p.frontmatter->>'source_slug',''), 'path:'||(p.frontmatter->>'source_path')))::int AS origins,+ min(p.frontmatter->>'retired_at') AS oldest, max(p.frontmatter->>'retired_at') AS newest,+ to_char((min(p.deleted_at) + interval '${ATOM_RESTORE_HOLD_DAYS} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS hold_until+ FROM pages p WHERE p.source_id=ANY($1::text[]) AND ${restorableAtomRetirementSql('p')}+ GROUP BY p.source_id ORDER BY p.source_id`, [sources]);+ const bySource = rows.map(row => ({ ...row, count: Number(row.count), origins: Number(row.origins) }));+ const count = bySource.reduce((sum, row) => sum + row.count, 0);+ const details = { count, origins: bySource.reduce((sum, row) => sum + row.origins, 0),+ oldest_retired_at: bySource.map(row => row.oldest).filter(Boolean).sort()[0] ?? null,+ newest_retired_at: bySource.map(row => row.newest).filter(Boolean).sort().at(-1) ?? null,+ hold_until: bySource.map(row => row.hold_until).sort()[0] ?? null,+ source_ids: bySource.map(row => row.source_id), by_source: bySource, repair: 'atoms-restore', docs: DOCS };+ if (!count) {+ return { name: 'atom_retirements_restorable', status: 'ok', details,+ message: 'No atom retired by an empty re-extraction is waiting to be restored.' };+ }+ const first = bySource[0]!;+ const preview = ['gbrain', 'repair', 'atoms-restore', '--source', first.source_id, '--json'];+ return { name: 'atom_retirements_restorable', status: 'warn', details,+ message: `${count} atom(s) from ${details.origins} origin(s) were retired when a re-extraction returned no atoms (#7013), between `+ + `${details.oldest_retired_at ?? 'an unrecorded time'} and ${details.newest_retired_at ?? 'an unrecorded time'} `+ + `(${bySource.map(row => `${row.source_id}: ${row.count} from ${row.origins} origin(s)`).join('; ')}). `+ + `The purge holds them for ${ATOM_RESTORE_HOLD_DAYS} days after deletion; the first hold ends ${details.hold_until}. `+ + `Preview the restore with ${preview.join(' ')} (read-only); apply the previewed set only after the user agrees.`,+ fix: agentFix(preview, 'Lists each restorable atom with its origin, source hash and retirement time and prints the apply command bound to that set; '+ + 'it writes nothing. Restoring is the user\'s call: show them the preview before running the apply.', 'atom_retirements_restorable', { docs: DOCS }) };+ } catch (error) {+ return { name: 'atom_retirements_restorable', status: 'warn',+ message: `Restorable atom retirements could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown' } };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 53deeaa450..f0c0ed32c9 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -307,6 +307,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some atoms reference a source page that is gone or was edited, and still surface in search with a quote no current page contains',run: async engine => (await import('./checks/extraction-sync.ts')).computeAtomProvenanceDriftCheck(engine),},+ {+ id: 'atom_retirements_restorable', resolution: 'repair', registration: 'wave',+ hostOnly: 'Restoring atoms an empty re-extraction retired is a host-side, explicit-only repair.',+ count: d => Number(d.count ?? 0),+ impact: 'Some atoms were retired when a re-extraction returned no atoms, and the purge removes them once their hold ends',+ run: async (engine, scope) => (await import('./checks/atom-retirements.ts')).atomRetirementsRestorableCheck(engine, scope.sourceIds),+ },{id: 'extractor_facts_expired', resolution: 'repair', registration: 'wave',hostOnly: 'Restoring expired extractor facts is a host-side, explicit-only repair.',diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex de9d46fab4..eb73aeff5b 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -57,6 +57,8 @@ export type CheckCategory = 'brain' | 'skill' | 'ops' | 'meta';export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['abandoned_threads','atom_provenance_drift',+ // #7013: atoms an empty managed re-extraction retired that atoms-restore can bring back (doctor/checks/atom-retirements.ts).+ 'atom_retirements_restorable','captured_facts_active','conversation_label_facts','conversation_outcomes_stale',diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 01a3f6ef46..6e2b250551 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -32,6 +32,7 @@ import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';import type { ScopedReadRunner } from './cjk-search.ts';import { compileRowNormalizer } from './normalize.ts';import { stagingNeedsTextSql } from '../page-body/schema.ts';+import { atomRetirementPurgeHold } from '../persistence/atom-retirement-hold.ts';import { createPageVersion } from '../page-state/versions.ts';import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';@@ -320,7 +321,8 @@ export async function purgeDeletedPages(WHERE deleted_at IS NOT NULLAND deleted_at < now() - (${hours} || ' hours')::intervalAND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text- AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)${excluded}+ AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)+ AND ${trustedSql(atomRetirementPurgeHold('pages'))}${excluded}ORDER BY deleted_at ASC, slug ASC`);const pages = rows.map((r) => ({@@ -340,7 +342,9 @@ export async function purgeDeletedPages(AND deleted_at < now() - (${hours} || ' hours')::interval-- #6729: the old page of an open rename-identity downgrade waits for its disposition (identityDowngradePurgeHold).AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text- AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)${excluded}+ AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)+ -- #7013: a restorable re-extraction retirement waits out its hold (atomRetirementPurgeHold).+ AND ${trustedSql(atomRetirementPurgeHold('pages'))}${excluded}RETURNING slug, source_id`);if (rows.length) await tx.run(sqlFragment`DELETE FROM page_body_stagings s USING unnest(${rows.map(r => r.source_id)}::text[], ${rows.map(r => r.slug)}::text[]) AS d(source_id, slug)diff --git a/src/core/persistence/atom-retirement-hold.ts b/src/core/persistence/atom-retirement-hold.tsnew file mode 100644index 0000000000..108fdc9a02--- /dev/null+++ b/src/core/persistence/atom-retirement-hold.ts@@ -0,0 +1,67 @@+/**+ * #7013: atoms a managed re-extraction retired that `gbrain repair atoms-restore` can bring back, as one SQL+ * predicate shared by the repair (preview, apply recheck and coordinated preparer), the+ * `atom_retirements_restorable` doctor check and the purge hold. Static strings over a `pages` alias only, so+ * `engine-sql/pages.ts` may import it.+ *+ * A page `a` is restorable when every part holds:+ * - `reextractRetiredAtomSql`: a soft-deleted, non-imported atom stamped `retired_by: managed-reextract`;+ * - `atomOriginLiveSql`: its origin is a live page of the same source (`source_slug`), or a transcript+ * (`source_path`, whose file SQL cannot check);+ * - `atomReplacedSql` is false: no live, non-imported atom of the same source and origin carries a different+ * source hash (a `pending:` prefix stripped), so no later generation replaced it;+ * - `atomLatestGenerationSql`: its hash is the hash of the origin's most recently retired `managed-reextract`+ * atom, so an older generation that a later extraction replaced is never revived.+ *+ * The purge (engine bulk delete and preview, the belief-ledger expiry, the managed selection) holds a restorable+ * atom for `ATOM_RESTORE_HOLD_DAYS` after its `deleted_at`; an explicit `gbrain delete --purge` is not held.+ */++/** The stamp `prepareManagedAtomMutation` writes on a re-extraction retirement (`ATOM_RETIRED_BY_REEXTRACT`). */+export const ATOM_REEXTRACT_RETIRED_BY = 'managed-reextract';++/** Days after `deleted_at` that the purge keeps a restorable atom. */+export const ATOM_RESTORE_HOLD_DAYS = 30;++const strippedHash = (alias: string) => `regexp_replace(COALESCE(${alias}.frontmatter->>'source_hash',''),'^pending:','')`;++/** `other` is bound to the same origin as `alias`: the same `source_slug`, or for a transcript atom the same `source_path`. */+const sameOrigin = (other: string, alias: string) => `((NULLIF(${alias}.frontmatter->>'source_slug','') IS NOT NULL+ AND ${other}.frontmatter @> jsonb_build_object('source_slug',${alias}.frontmatter->'source_slug'))+ OR (NULLIF(${alias}.frontmatter->>'source_slug','') IS NULL+ AND ${other}.frontmatter @> jsonb_build_object('source_path',${alias}.frontmatter->'source_path')))`;++export function reextractRetiredAtomSql(alias: string): string {+ return `(${alias}.type='atom' AND ${alias}.deleted_at IS NOT NULL+ AND ${alias}.frontmatter->>'retired_by'='${ATOM_REEXTRACT_RETIRED_BY}'+ AND NULLIF(${alias}.frontmatter->>'imported_from','') IS NULL)`;+}++export function atomOriginLiveSql(alias: string): string {+ return `((NULLIF(${alias}.frontmatter->>'source_slug','') IS NOT NULL AND EXISTS (SELECT 1 FROM pages ao+ WHERE ao.source_id=${alias}.source_id AND ao.slug=${alias}.frontmatter->>'source_slug' AND ao.deleted_at IS NULL))+ OR (NULLIF(${alias}.frontmatter->>'source_slug','') IS NULL AND NULLIF(${alias}.frontmatter->>'source_path','') IS NOT NULL))`;+}++export function atomReplacedSql(alias: string): string {+ return `EXISTS (SELECT 1 FROM pages ar WHERE ar.source_id=${alias}.source_id AND ar.type='atom' AND ar.deleted_at IS NULL+ AND NULLIF(ar.frontmatter->>'imported_from','') IS NULL AND ${sameOrigin('ar', alias)}+ AND ${strippedHash('ar')}<>${strippedHash(alias)})`;+}++export function atomLatestGenerationSql(alias: string): string {+ return `${strippedHash(alias)}=(SELECT ${strippedHash('ag')} FROM pages ag WHERE ag.source_id=${alias}.source_id AND ag.type='atom'+ AND ag.deleted_at IS NOT NULL AND ag.frontmatter @> jsonb_build_object('retired_by','${ATOM_REEXTRACT_RETIRED_BY}')+ AND NULLIF(ag.frontmatter->>'imported_from','') IS NULL AND ${sameOrigin('ag', alias)}+ ORDER BY ag.frontmatter->>'retired_at' DESC NULLS LAST, ag.id DESC LIMIT 1)`;+}++/** SQL: the page aliased `alias` is an atom `gbrain repair atoms-restore` restores. */+export function restorableAtomRetirementSql(alias: string): string {+ return `(${reextractRetiredAtomSql(alias)} AND ${atomOriginLiveSql(alias)} AND NOT ${atomReplacedSql(alias)} AND ${atomLatestGenerationSql(alias)})`;+}++/** SQL predicate for a purge scan over `pages` aliased `alias`: the page is not a restorable atom inside its hold. */+export function atomRetirementPurgeHold(alias: string): string {+ return `NOT (${alias}.deleted_at > now() - interval '${ATOM_RESTORE_HOLD_DAYS} days' AND ${restorableAtomRetirementSql(alias)})`;+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 3545ca7209..1ef505282c 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -532,6 +532,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coreturn (await import('../chronicle/publish.ts')).prepareChronicleMutation(engine, row, config);}if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_restore_reextract_atom') return (await import('../repair/atoms-restore.ts')).prepareAtomRestore(engine, row, config);if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(engine, row, config);if (row.intent?.kind === 'managed_maintenance_resolve_origin_twin') return (await import('../repair/origin-twins.ts')).prepareOriginTwinResolve(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 469cfa3cec..6a1be58b00 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex 387bee46fc..f5ec01e770 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -12,6 +12,7 @@ import { withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';import { linkStreamSlugs } from './page-purge.ts';import { identityDowngradePurgeHold } from '../sync-identity-downgrades.ts';+import { atomRetirementPurgeHold } from './atom-retirement-hold.ts';import { writerOnboardingPreflight } from './onboarding.ts';import { clearPurgePark, notePurgeSourceWriter, PURGE_PARK_LIMIT, purgeParkKey, prunePurgeParks, readPurgeParks, recordPurgeFailure, type PurgePark } from './purge-parks.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';@@ -78,7 +79,7 @@ interface RecordedTombstone { id: number; source_id: string; slug: string; deletasync function recordedTombstones(engine: BrainEngine, hours: string): Promise<RecordedTombstone[]> {const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; deleted_us: string }>(`SELECT p.id, p.source_id, p.slug,floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text AS deleted_us FROM pages p- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND ${identityDowngradePurgeHold('p')}+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')}AND EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = p.source_id AND e.subject_kind = 'coverage')ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [hours]);const parks = rows.length ? await readPurgeParks(engine) : new Map<string, PurgePark>();@@ -123,7 +124,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: numconst slugs = [...new Set([row.slug, ...await linkStreamSlugs(tx, row.source_id, row.id)])].sort();await tx.lockPageKeys(slugs.map(slug => ({ sourceId: row.source_id, slug })));return withBeliefBatch(tx, { sourceId: row.source_id, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report },- async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} RETURNING id`,+ async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} AND ${atomRetirementPurgeHold('pages')} RETURNING id`,[row.id, hours])).length > 0);});run.succeed();@@ -189,7 +190,7 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:const rows = await engine.executeRaw<{ source_id: string; slug: string; cutoff: string; deleted_us: string }>(`SELECT p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff,floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text AS deleted_us FROM pages p JOIN sources s ON s.id = p.source_id- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')}+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')}ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(hours)]);const states = new Map<string, { state: string; physical_error?: string }>();if (rows.length) for (const source of (await writerOnboardingPreflight(engine)).sources) states.set(source.source_id, source);diff --git a/src/core/repair/atoms-restore.ts b/src/core/repair/atoms-restore.tsnew file mode 100644index 0000000000..5d52b84d58--- /dev/null+++ b/src/core/repair/atoms-restore.ts@@ -0,0 +1,213 @@+/**+ * `gbrain repair atoms-restore` (#7013): bring back atoms a managed re-extraction retired when its model+ * returned no atoms for their origin. An empty extraction retired every earlier atom of the origin by soft delete+ * stamped `retired_by: managed-reextract`, and the purge then removed them for good.+ *+ * The candidate rule is one SQL predicate (`restorableAtomRetirementSql`, persistence/atom-retirement-hold.ts):+ * the latest retired generation of a live origin (a page in the same source, or a transcript) that no later+ * generation replaced. Imported atoms, `stale-atoms` retirements and older generations are never listed; the+ * preview counts what it keeps (`origin_gone`, `replaced`, `older_generation`).+ *+ * The kind is explicit-only and preview-bound: the preview lists every atom with its origin, source hash and+ * retirement time and saves the set under its hash; `--apply --expect <hash>` restores exactly that set. Each atom+ * 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+ * maintenance transaction. Neither changes the origin's extraction state.+ */+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix } 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';+import { preparePageMutation } from '../persistence/page-prepare.ts';+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { atomLatestGenerationSql, atomOriginLiveSql, atomReplacedSql, reextractRetiredAtomSql, restorableAtomRetirementSql,+ ATOM_REEXTRACT_RETIRED_BY } from '../persistence/atom-retirement-hold.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { declareDerivation, deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++export const ATOMS_RESTORE_INTENT = 'managed_maintenance_restore_reextract_atom';++/** Everything the preview showed for one atom; the apply rechecks each field. */+export interface RestorableAtom {+ id: number;+ source_id: string;+ /** The source incarnation the preview saw; a re-created source is a different atom. */+ incarnation: string;+ slug: string;+ /** The deleted atom's revision; the managed request is bound to it. */+ revision: string;+ origin_kind: 'page' | 'transcript';+ /** The origin page slug, or the transcript path. */+ origin: string;+ origin_page_id: number | null;+ /** The atom's source hash with a `pending:` prefix stripped. */+ hash: string;+ retired_at: string | null;+}++interface RestoreItem extends RepairItem { atom: RestorableAtom; hash: string; last: boolean }++/** An approved atom carries the preview's source selection, so an apply under another `--source` refuses. */+interface ApprovedAtom extends RestorableAtom { selection: string[] }++/** Restorable atoms of these sources in id order; `atomId` narrows to one atom for the apply recheck. */+async function restorableAtoms(db: BrainEngine, sourceIds: string[], atomId?: number): Promise<RestorableAtom[]> {+ const rows = await db.executeRaw<RestorableAtom>(`+ SELECT a.id, a.source_id, (SELECT s.incarnation::text FROM sources s WHERE s.id=a.source_id) AS incarnation,+ a.slug, a.knowledge_revision::text AS revision,+ CASE WHEN NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL THEN 'page' ELSE 'transcript' END AS origin_kind,+ COALESCE(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+ FROM pages a+ WHERE 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) }));+}++/** The re-extraction retirements of these sources the rule keeps, by reason. */+async function keptCounts(db: BrainEngine, sourceIds: string[]): Promise<{ origin_gone: number; replaced: number; older_generation: number }> {+ const [row] = await db.executeRaw<{ origin_gone: number; replaced: number; older_generation: number }>(`+ SELECT count(*) FILTER (WHERE NOT live)::int AS origin_gone,+ count(*) FILTER (WHERE live AND replaced)::int AS replaced,+ count(*) FILTER (WHERE live AND NOT replaced AND NOT latest)::int AS older_generation+ FROM (SELECT ${atomOriginLiveSql('a')} AS live, ${atomReplacedSql('a')} AS replaced,+ COALESCE(${atomLatestGenerationSql('a')}, false) AS latest+ FROM pages a WHERE a.source_id=ANY($1::text[]) AND ${reextractRetiredAtomSql('a')}) kept`, [sourceIds]);+ return { origin_gone: Number(row?.origin_gone ?? 0), replaced: Number(row?.replaced ?? 0), older_generation: Number(row?.older_generation ?? 0) };+}++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)+ .every(field => live[field] === approved[field]);+}++function previewCommand(scope: RepairScope): string {+ return `gbrain repair atoms-restore${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++function item(atom: RestorableAtom, hash: string, last: boolean): RestoreItem {+ return { cursor: { phase: 1, id: atom.id }, source_id: atom.source_id, slug: atom.slug, chars: 0, action: 'restore', atom, hash, last };+}++async function hashParts(engine: BrainEngine, scope: RepairScope, atoms: RestorableAtom[]) {+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ return { kind: 'atoms-restore-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, atoms };+}++export const atomsRestoreRepair: RepairHandler = {+ kind: 'atoms-restore',+ embeds: true,+ outcomeItemsLimit: 1000,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const atoms = await restorableAtoms(engine, scope.source_ids);+ const hash = previewHash(await hashParts(engine, scope, atoms));+ if (atoms.length) await saveApprovedSet<ApprovedAtom>(engine, { command: 'atoms-restore', hash }, atoms.map(atom => ({ ...atom, selection: scope.source_ids })));+ return { items: atoms.map((atom, index) => item(atom, hash, index === atoms.length - 1)), preview_hash: hash,+ residuals: { restorable: atoms.length, origins: new Set(atoms.map(atom => `${atom.source_id}:${atom.origin_kind}:${atom.origin}`)).size,+ ...await keptCounts(engine, scope.source_ids) },+ listing: atoms.map(atom => ({ item: `${atom.source_id}:${atom.slug}`, class: 'restorable',+ detail: `origin ${atom.origin_kind} ${atom.origin}, hash ${atom.hash}, retired ${atom.retired_at ?? 'at an unrecorded time'}` })) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair atoms-restore --apply restores only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,+ 'docs/guides/repair.md#explicit-only-repair-kinds');+ }+ const approved = await loadApprovedSet<ApprovedAtom>(engine, { command: 'atoms-restore', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(await hashParts(engine, scope, [])) });+ if (approved.items.some(atom => JSON.stringify(atom.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, ...atom }, index) => item(atom, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { atom, hash, last } = entry as RestoreItem;+ const outcome = await restoreAtom(ctx, atom);+ if (last) await clearApprovedSet(ctx.engine, { command: 'atoms-restore', hash });+ return outcome;+ },+};++async function restoreAtom(ctx: OperationContext, atom: RestorableAtom): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const 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)) {+ const authority = (await maintenancePreflight(engine, atom.source_id))!;+ const requestId = await repairRequestId(ctx, 'atoms-restore', atom, atom.revision);+ try {+ await submitMaintenanceIntent(engine, authority, atom.slug, { kind: ATOMS_RESTORE_INTENT, expected_revision: atom.revision, deleted_page: true, atom }, requestId);+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);+ if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'file_conflict', reason: error.message, detail: { request_id: requestId } };+ throw error;+ }+ return { applied: true, outcome: 'restored', detail: { request_id: requestId } };+ }+ const restored = await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: atom.source_id, slug: atom.slug }, ...(atom.origin_kind === 'page' ? [{ sourceId: atom.source_id, slug: atom.origin }] : [])]);+ if (!sameAtom((await restorableAtoms(tx, [atom.source_id], atom.id))[0], atom)) return false;+ await tx.createVersion(atom.slug, { sourceId: atom.source_id });+ await tx.restorePage(atom.slug, { sourceId: atom.source_id });+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter-'retired_by'-'retired_at' WHERE id=$1 AND source_id=$2 AND deleted_at IS NULL`,+ [atom.id, atom.source_id]);+ return true;+ });+ return restored ? { applied: true, outcome: 'restored' } : changed('the atom, its origin or a later generation changed');+}++const previewFix = (sourceId: string) => readFix('Previews the atoms-restore repair without changing anything.',+ { argv: ['gbrain', 'repair', 'atoms-restore', '--source', sourceId, '--json'] });++/** 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)) {+ 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) });+ }+ const unchanged = async (db: BrainEngine) => {+ if (!sameAtom((await restorableAtoms(db, [row.source_id], atom.id))[0], atom)) {+ throw opError('revision_conflict', 'The retired atom, its origin or a later generation changed since the preview.',+ `Atom ${row.slug} in source ${row.source_id} no longer matches the restore preview (it changed, its origin is gone, or a later extraction replaced it), so request ${row.request_id} restored nothing. Preview the repair again and apply the new preview after the user approves.`,+ { fix: previewFix(row.source_id) });+ }+ };+ 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;+ 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 });+ 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); },+ 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]);+ if (live) {+ await lowerToDerivedTier(tx, 'pages', [Number(live.id)], derivation.trust);+ await recordTaintEdges(tx, { table: 'pages', id: Number(live.id), sourceId: row.source_id }, derivation.inputs);+ }+ return { ...outcome, restored_from: ATOM_REEXTRACT_RETIRED_BY };+ } };+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 0bd3765bcc..9a4b0d7b1f 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] 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', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 11e3a3ddfa..a1e313a4a1 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -50,6 +50,7 @@ import { contentReceiptRootRepair } from './content-receipt-root.ts';import { embeddingEffectsRepair } from './embedding-effects.ts';import { googleFileModesRepair } from './google-file-modes.ts';import { staleAtomsRepair } from './stale-atoms.ts';+import { atomsRestoreRepair } from './atoms-restore.ts';import { extractorFactsRepair } from './extractor-facts.ts';import { conversationLabelsRepair } from './conversation-labels.ts';import { capturedFactsRepair } from './captured-facts.ts';@@ -186,6 +187,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'Preview-bound: --apply --expect <hash> retires exactly the previewed set; an atom that changed since reports changed_since_preview and is kept. '+ 'A later extraction that produces a retired atom again restores it. Never touches imported or file-bound atoms.',},+ 'atoms-restore': {+ handler: atomsRestoreRepair, embeds: 'effect', checks: ['atom_retirements_restorable'], explicit_only: true, preview_bound: true,+ summary: 'Restore atoms a managed re-extraction retired when its model returned no atoms for their origin (#7013, retired_by: managed-reextract). '+ + 'Only the latest retired generation of a live origin that no later extraction replaced; imported atoms, stale-atoms retirements and older '+ + 'generations are kept. Preview-bound: --apply --expect <hash> restores exactly the previewed set (managed: one revision-bound request per atom '+ + 'that writes the canonical file back, its request id in the outcome); an atom that changed since reports changed_since_preview and stays deleted. '+ + 'The purge holds these atoms for 30 days after deletion. Runs only when named; never on upgrade.',+ },'extractor-facts': {handler: extractorFactsRepair, embeds: 'none', checks: ['extractor_facts_expired'], explicit_only: true,summary: 'Restore conversation-extractor facts that the pre-v0.60.11.0 canonical projection expired (#5731). Restores only facts with receipt evidence '