Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair stale-atoms retires drifted atoms preview-bound (#5770)

garrytane508db62f58d
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 4195089a98..d3ed1fc40d 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; stubs in `stale-atoms.ts` and `extractor-facts.ts` that refuse with `unavailable` until their fix wave 5 lanes land) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command. Tests: `test/repair-explicit-only.test.ts`. Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.
+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired` or `changed_since_preview`. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 88f8e6d678..09fa913cd5 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -71,7 +71,6 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },
{ path: 'src/core/chronicle/backstop.ts', reason: 'held: the put_page chronicle backstop was dropped in v0.51.0.0, so the documented auto_chronicle setting does nothing; restore-or-retract is a product decision' },
{ path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },
- { path: 'src/core/persistence/preview-approval.ts', reason: 'held: fix wave 5 shared commit (ENG-O1); its callers (jobs authorize-legacy/cancel --select, repair stale-atoms/extractor-facts) land in the wave 5 lanes, which remove this entry' },
{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },
{ path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
{ path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 871f745869..f2dcca05c8 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -95,7 +95,7 @@ test/destructive-guard.test.ts purgeExpiredSources — clone cleanup containment
test/detached-stderr.test.ts jobs.ts detach branch (source pin, #4418) 2 source-surface-helper
test/docs-mcp-deploy.test.ts DEPLOY.md documents the owner magic-link flow (#5007) 1 readFileSync,source-surface-helper
test/docs-navigation.test.ts primary documentation navigation 1 readFileSync
-test/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 18 doctor-source-helper
+test/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 19 doctor-source-helper
test/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helper
test/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync
test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helper
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 8a75c0cbf2..3ae83cbdbc 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -840,7 +840,10 @@ export async function computeAtomProvenanceDriftCheck(
// metric omitted, verdict untouched).
`WITH atom AS (
SELECT a.source_id,
- a.frontmatter->>'source_hash' AS sh,
+ -- managed atoms keep their provisional prefix for good (#5770)
+ CASE WHEN a.frontmatter->>'managed_extraction' = 'true'
+ THEN regexp_replace(a.frontmatter->>'source_hash', '^pending:', '')
+ ELSE a.frontmatter->>'source_hash' END AS sh,
-- NULL = slug-unbound: transcript-minted (source_path only) or
-- pre-binding-era. \`ss IS NULL\` is THE predicate for that
-- population everywhere below (#4799 / #4806).
@@ -851,8 +854,8 @@ export async function computeAtomProvenanceDriftCheck(
WHERE a.type = 'atom'
AND a.deleted_at IS NULL
AND a.frontmatter->>'source_hash' IS NOT NULL
- -- in-flight marker written before the extraction commits
- AND a.frontmatter->>'source_hash' NOT LIKE 'pending:%'
+ -- in-flight marker written before an unmanaged extraction commits
+ AND (a.frontmatter->>'source_hash' NOT LIKE 'pending:%' OR a.frontmatter->>'managed_extraction' = 'true')
-- Lookup sets are built ONCE and joined (#4937). A correlated EXISTS in
-- the SELECT list is not rewritten to a semi-join — Postgres re-runs it
-- per atom over substring(content_hash), which no index serves, so the
@@ -922,11 +925,9 @@ export async function computeAtomProvenanceDriftCheck(
if (drifted >= MIN_DRIFTED && ratio > WARN_RATIO) {
const fix =
- "review before acting — most drift is an edited source, not a dead one. " +
- "List them with: SELECT slug, frontmatter->>'source_slug' FROM pages a WHERE a.type='atom' " +
- "AND a.deleted_at IS NULL AND NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL " +
- "AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id " +
- "AND p.deleted_at IS NULL AND substring(p.content_hash from 1 for 16)=a.frontmatter->>'source_hash')";
+ "preview the atoms that are safe to retire with gbrain repair stale-atoms (source gone, or source edited and " +
+ "already re-extracted), then apply with the --expect hash it prints. Atoms of an edited page that was not " +
+ "re-extracted yet are the extract_atoms backlog, not stale";
return {
name, status: 'warn',
message:
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 7c774f0cd8..116ae57467 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -114,6 +114,8 @@ function human(result: RepairResult): string {
if (result.resumed_from) lines.push(` resuming after item ${result.resumed_from.phase}:${result.resumed_from.id}`);
if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);
if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);
+ for (const entry of result.listing ?? []) lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);
+ if (result.mode === 'apply' && result.outcomes) lines.push(` outcomes: ${Object.entries(result.outcomes).map(([k, v]) => `${k}=${v}`).join(', ')}`);
if (result.mode === 'dry_run' && result.affected) lines.push(` apply: ${result.apply_command}`);
return lines.join('\n');
}
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 33ad970a99..16ac3026f6 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -394,9 +394,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
} };
}
+/** The completed, failure-free `managed-atoms` checkpoint `ac` for one page at its current content hash. */
+export function managedAtomCompletedSql(page: { sourceId: string; slug: string; pageId: string; contentHash: string }): string {
+ return `ac.op='managed-atoms' AND ac.completed_keys->0->>'sourceId'=${page.sourceId}
+ AND ac.completed_keys->0->>'incarnation'=(SELECT incarnation::text FROM sources WHERE id=${page.sourceId})
+ AND ac.completed_keys->0->>'kind'='page' AND ac.completed_keys->0->>'locator'=${page.slug}
+ AND ac.completed_keys->0->>'pageId'=${page.pageId}::text AND ac.completed_keys->0->>'contentHash'=${page.contentHash}
+ AND ac.completed_keys->0->>'failure' IS NULL`;
+}
+
export const MANAGED_ATOM_DISCOVERY_SQL = `AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac
- WHERE ac.op='managed-atoms' AND ac.completed_keys->0->>'sourceId'=p.source_id
- AND ac.completed_keys->0->>'incarnation'=(SELECT incarnation::text FROM sources WHERE id=p.source_id)
- AND ac.completed_keys->0->>'kind'='page' AND ac.completed_keys->0->>'locator'=p.slug
- AND ac.completed_keys->0->>'pageId'=p.id::text AND ac.completed_keys->0->>'contentHash'=p.content_hash
- AND ac.completed_keys->0->>'failure' IS NULL)`;
+ WHERE ${managedAtomCompletedSql({ sourceId: 'p.source_id', slug: 'p.slug', pageId: 'p.id', contentHash: 'p.content_hash' })})`;
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index d720d1e718..29e8a40eeb 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -282,6 +282,7 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Write
if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(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_consolidate') throw new OperationError('invalid_params', 'Unsupported maintenance request.');
const p = row.intent;
const facts = p.facts as FactSnapshot[];
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index f3a59bb01e..397ea72e18 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -43,8 +43,12 @@ export interface RepairPlan {
residuals: Record<string, number>;
/** Preview-bound kinds: the `previewHash` an apply must pass back with `--expect`. */
preview_hash?: string;
+ /** Preview-bound kinds: every previewed item with its class, all of which the hash covers. */
+ listing?: RepairListing[];
}
+export interface RepairListing { item: string; class: string; detail?: string }
+
/** What the run was asked to do; preview-bound (explicit-only) kinds read `expect` and `includeAmbiguous`. */
export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean }
@@ -82,6 +86,8 @@ export interface RepairResult {
complete: boolean;
stopped?: { reason: string; message: string };
apply_command: string;
+ /** Preview-bound kinds' dry run: every item the preview hash covers. */
+ listing?: RepairListing[];
/** Per-outcome counts and the first items, for kinds that name outcomes. */
outcomes?: Record<string, number>;
outcome_items?: Array<{ item: string; outcome: string; reason?: string }>;
@@ -191,6 +197,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''} --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}`,
};
if (!opts.apply) {
+ if (plan.listing) result.listing = plan.listing;
result.complete = pending.length === plan.items.length;
return result;
}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 6e899c8313..ced5831865 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -96,8 +96,10 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'retry_queued for its owner (paid; a consumed retry allowance gets one new bounded cycle per explicit run) or blocked with the reason. Never drops an obligation.',
},
'stale-atoms': {
- handler: staleAtomsRepair, embeds: 'none', checks: [], explicit_only: true,
- summary: 'Retire managed atoms whose source page changed or was deleted (#5770). Not implemented in this build.',
+ handler: staleAtomsRepair, embeds: 'none', checks: ['atom_provenance_drift'], explicit_only: true,
+ summary: 'Retire, by soft delete, page-bound atoms whose source page is gone, or whose source page changed after its current text was already extracted (#5770). '
+ + '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.',
},
'extractor-facts': {
handler: extractorFactsRepair, embeds: 'none', checks: [], explicit_only: true,
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
index 431b26cf4a..f68c4e10a1 100644
--- a/src/core/repair/stale-atoms.ts
+++ b/src/core/repair/stale-atoms.ts
@@ -1,19 +1,207 @@
/**
- * `gbrain repair stale-atoms` (#5770): registry stub from the fix wave 5 shared
- * commit. The kind is explicit-only (never run by `--all` or a remediation
- * step) and preview-bound through `persistence/preview-approval.ts`. Until its
- * lane replaces this handler, every preview and apply refuses.
+ * `gbrain repair stale-atoms` (#5770, CEO-A7, ENG-O7, DX-O4): the one-time
+ * cleanup of atoms that drifted before managed re-extraction retired them.
+ *
+ * Two classes of live, page-bound (`source_slug`) atoms, never one with
+ * `imported_from` and never a file-bound (`source_path`-only) atom:
+ * (a) `origin_gone`: the source page is missing or soft-deleted;
+ * (b) `origin_changed`: the atom's 16-character source hash (a managed
+ * `pending:` prefix stripped) differs from its live source page's
+ * current hash, and that page already completed an extraction at its
+ * current hash (managed: the completed `managed-atoms` checkpoint;
+ * unmanaged: a non-managed atom of that page carrying the hash).
+ *
+ * The kind is explicit-only and preview-bound: the preview lists every atom
+ * with its class and saves the set under its hash; `--apply --expect <hash>`
+ * retires exactly that set. Each atom is rechecked when it is retired; one
+ * whose revision, class, origin or completion evidence changed reports
+ * `changed_since_preview` and is kept. A managed brain retires one atom per
+ * `managed_maintenance_retire_stale_atoms` request bound to the atom's
+ * revision (no live origin is required); an unmanaged brain soft-deletes it
+ * directly. Both stamp `retired_by: stale-atoms`, so a later extraction that
+ * produces the atom again restores it, and both invalidate the origin page's
+ * earlier completed extractions so a restored page is extracted again.
*/
-import { catalogueError } from '../error-catalogue.ts';
-import type { RepairHandler } from './core.ts';
+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 { OperationError } from '../ops/contract.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { preparePageMutation } from '../persistence/page-prepare.ts';
+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { bumpAtomGeneration, managedAtomCompletedSql } from '../persistence/atom-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
-function notBuilt(): never {
- throw catalogueError('repair_kind_unavailable', 'gbrain repair stale-atoms is not implemented in this build.',
- 'Upgrade on the brain host, then preview again: gbrain upgrade && gbrain repair stale-atoms');
+export const STALE_ATOMS_RETIRED_BY = 'stale-atoms';
+export const STALE_ATOMS_INTENT = 'managed_maintenance_retire_stale_atoms';
+
+export type StaleAtomClass = 'origin_gone' | 'origin_changed';
+
+/** Everything the preview showed for one atom; the apply rechecks each field. */
+export interface StaleAtom {
+ id: number;
+ source_id: string;
+ slug: string;
+ revision: string;
+ class: StaleAtomClass;
+ managed: boolean;
+ origin_slug: string;
+ origin_page_id: number | null;
+ origin_hash: string | null;
+ /** Class (b): the completed-extraction evidence at the origin's current hash. */
+ evidence: string | null;
+}
+
+interface StaleAtomItem extends RepairItem { atom: StaleAtom; hash: string; last: boolean }
+
+/** Live stale atoms of these sources, in (class, id) order; `atomId` narrows to one atom for the apply recheck. */
+async function staleAtoms(db: BrainEngine, sourceIds: string[], atomId?: number): Promise<Array<StaleAtom & { chars: number }>> {
+ const rows = await db.executeRaw<StaleAtom & { chars: number }>(`
+ WITH atom AS (
+ SELECT a.id, a.source_id, a.slug, a.knowledge_revision::text AS revision,
+ a.frontmatter->>'source_slug' AS origin_slug,
+ COALESCE(a.frontmatter->>'managed_extraction','')='true' AS managed,
+ regexp_replace(COALESCE(a.frontmatter->>'source_hash',''),'^pending:','') AS atom_hash,
+ length(COALESCE(a.compiled_truth,'')) AS chars,
+ o.id AS origin_page_id, o.slug AS origin_live_slug, o.source_id AS origin_source_id,
+ o.content_hash AS origin_hash, o.deleted_at IS NOT NULL AS origin_deleted
+ FROM pages a
+ LEFT JOIN pages o ON o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug'
+ WHERE a.source_id=ANY($1::text[]) AND a.type='atom' AND a.deleted_at IS NULL
+ AND NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL
+ AND NULLIF(a.frontmatter->>'imported_from','') IS NULL
+ AND ($2::int IS NULL OR a.id=$2::int)
+ ), classified AS (
+ SELECT atom.*, CASE
+ WHEN origin_page_id IS NULL OR origin_deleted THEN 'origin_gone'
+ WHEN origin_hash IS NOT NULL AND atom_hash<>substring(origin_hash from 1 for 16) THEN 'origin_changed'
+ END AS class,
+ CASE WHEN managed THEN (SELECT ac.fingerprint FROM op_checkpoints ac WHERE ${managedAtomCompletedSql({ sourceId: 'atom.origin_source_id',
+ slug: 'atom.origin_live_slug', pageId: 'atom.origin_page_id', contentHash: 'atom.origin_hash' })} ORDER BY ac.fingerprint LIMIT 1)
+ ELSE (SELECT 'unmanaged:'||e.id FROM pages e WHERE e.source_id=atom.source_id AND e.type='atom' AND e.deleted_at IS NULL
+ AND COALESCE(e.frontmatter->>'managed_extraction','')<>'true' AND e.frontmatter->>'source_slug'=atom.origin_slug
+ AND e.frontmatter->>'source_hash'=substring(atom.origin_hash from 1 for 16) ORDER BY e.id LIMIT 1)
+ END AS completion
+ FROM atom
+ )
+ SELECT id, source_id, slug, revision, class, managed, origin_slug,
+ origin_page_id,
+ CASE WHEN class='origin_gone' THEN NULL ELSE origin_hash END AS origin_hash,
+ CASE WHEN class='origin_gone' THEN NULL ELSE completion END AS evidence, chars
+ FROM classified
+ WHERE class='origin_gone' OR (class='origin_changed' AND completion IS NOT NULL)
+ ORDER BY CASE class WHEN 'origin_gone' THEN 1 ELSE 2 END, id`, [sourceIds, atomId ?? null]);
+ return rows.map(row => ({ ...row, id: Number(row.id), managed: row.managed === true,
+ origin_page_id: row.origin_page_id === null ? null : Number(row.origin_page_id), chars: Number(row.chars) }));
+}
+
+function sameAtom(live: StaleAtom | undefined, approved: StaleAtom): boolean {
+ return !!live && (['id', 'source_id', 'slug', 'revision', 'class', 'managed', 'origin_slug', 'origin_page_id', 'origin_hash', 'evidence'] as const)
+ .every(field => live[field] === approved[field]);
+}
+
+function previewCommand(scope: RepairScope): string {
+ return `gbrain repair stale-atoms${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
+}
+
+function item(atom: StaleAtom, hash: string, last: boolean): StaleAtomItem {
+ return { cursor: { phase: atom.class === 'origin_gone' ? 1 : 2, id: atom.id }, source_id: atom.source_id, slug: atom.slug,
+ chars: 0, action: `retire:${atom.class}`, atom, hash, last };
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, atoms: StaleAtom[]) {
+ 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: 'stale-atoms-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, atoms };
}
export const staleAtomsRepair: RepairHandler = {
kind: 'stale-atoms',
- plan: async () => notBuilt(),
- apply: async () => notBuilt(),
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = previewCommand(scope);
+ if (!opts?.apply) {
+ const atoms = (await staleAtoms(engine, scope.source_ids)).map(({ chars: _chars, ...atom }) => atom);
+ const hash = previewHash(await hashParts(engine, scope, atoms));
+ if (atoms.length) await saveApprovedSet(engine, { command: 'stale-atoms', hash }, atoms);
+ return { items: atoms.map((atom, index) => item(atom, hash, index === atoms.length - 1)), preview_hash: hash,
+ residuals: { origin_gone: atoms.filter(atom => atom.class === 'origin_gone').length,
+ origin_changed: atoms.filter(atom => atom.class === 'origin_changed').length },
+ listing: atoms.map(atom => ({ item: `${atom.source_id}:${atom.slug}`, class: atom.class,
+ detail: atom.class === 'origin_gone' ? `source page ${atom.origin_slug} is gone`
+ : `source page ${atom.origin_slug} now at ${atom.origin_hash!.slice(0, 16)}` })) };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair stale-atoms --apply retires 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<StaleAtom>(engine, { command: 'stale-atoms', hash: opts.expect, previewCommand: command });
+ const items = approved.items.map((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 StaleAtomItem;
+ const outcome = await retireStaleAtom(ctx.engine, atom);
+ if (last) await clearApprovedSet(ctx.engine, { command: 'stale-atoms', hash });
+ return outcome;
+ },
};
+
+async function retireStaleAtom(engine: BrainEngine, atom: StaleAtom): Promise<RepairItemOutcome> {
+ const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
+ if (!sameAtom((await staleAtoms(engine, [atom.source_id], atom.id))[0], atom)) return changed('the atom or its source page changed');
+ if (await managedPersistenceEnabled(engine)) {
+ const authority = (await maintenancePreflight(engine, atom.source_id))!;
+ try {
+ await submitMaintenanceIntent(engine, authority, atom.slug, { kind: STALE_ATOMS_INTENT, expected_revision: atom.revision, atom });
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);
+ throw error;
+ }
+ return { applied: true, outcome: 'retired' };
+ }
+ const retired = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: atom.source_id, slug: atom.slug }, { sourceId: atom.source_id, slug: atom.origin_slug }]);
+ if (!sameAtom((await staleAtoms(tx, [atom.source_id], atom.id))[0], atom)) return false;
+ await tx.createVersion(atom.slug, { sourceId: atom.source_id });
+ await tx.softDeletePage(atom.slug, { sourceId: atom.source_id });
+ await stampRetirement(tx, atom);
+ return true;
+ });
+ return retired ? { applied: true, outcome: 'retired' } : changed('the atom or its source page changed');
+}
+
+async function stampRetirement(tx: BrainEngine, atom: StaleAtom): Promise<void> {
+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [STALE_ATOMS_RETIRED_BY, new Date().toISOString(), atom.id, atom.source_id]);
+ if (atom.origin_page_id === null) return;
+ const [{ incarnation }] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [atom.source_id]);
+ await bumpAtomGeneration(tx, atom.source_id, incarnation, atom.origin_page_id, atom.class === 'origin_changed' ? atom.origin_hash : null);
+}
+
+/** Preparer for `managed_maintenance_retire_stale_atoms`: rechecks the atom's class under its and its origin's page locks, then retires it. */
+export async function prepareStaleAtomRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+ const atom = row.intent!.atom as StaleAtom;
+ if (!atom || atom.slug !== row.slug || atom.source_id !== row.source_id || atom.id !== Number(row.page_id)) {
+ throw new OperationError('invalid_params', 'The stale atom retirement intent does not name its atom.');
+ }
+ const unchanged = async (db: BrainEngine) => {
+ if (!sameAtom((await staleAtoms(db, [row.source_id], atom.id))[0], atom)) {
+ throw new OperationError('revision_conflict', 'The stale atom or its source page changed since the preview.');
+ }
+ };
+ await unchanged(engine);
+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
+ const page = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
+ return { ...page, additionalPageKeys: [...(page.additionalPageKeys ?? []), { sourceId: row.source_id, slug: atom.origin_slug }],
+ validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); await unchanged(tx); },
+ apply: async tx => {
+ const outcome = await page.apply(tx);
+ await stampRetirement(tx, atom);
+ return { ...outcome, retired_by: STALE_ATOMS_RETIRED_BY };
+ } };
+}
diff --git a/test/doctor-atom-provenance-drift.test.ts b/test/doctor-atom-provenance-drift.test.ts
index b02a7cc1da..8d01e87474 100644
--- a/test/doctor-atom-provenance-drift.test.ts
+++ b/test/doctor-atom-provenance-drift.test.ts
@@ -360,4 +360,20 @@ describe('computeAtomProvenanceDriftCheck', () => {
expect(c.message).toContain('0 whose source page is gone');
expect(c.message).toContain('30 slug-unbound');
}, 60_000);
+
+ it('counts a managed atom by its stripped provisional hash and names the stale-atoms repair (#5770)', async () => {
+ await seedSource('src-managed', 'original body');
+ const original = await hashOf('src-managed');
+ for (let i = 0; i < 30; i++) {
+ await engine.putPage(`atoms/2026-01-01/managed-${String(i).padStart(6, '0')}`, { type: 'atom', title: `managed ${i}`, compiled_truth: 'claim body',
+ frontmatter: { type: 'atom', source_slug: 'src-managed', source_hash: `pending:${original}`, managed_extraction: true, extracted_at: new Date().toISOString() } });
+ }
+ const healthy = await computeAtomProvenanceDriftCheck(engine);
+ expect(healthy.details).toMatchObject({ total_atoms: 30, drifted: 0 });
+ await seedSource('src-managed', 'edited body');
+ const c = await computeAtomProvenanceDriftCheck(engine);
+ expect(c.status).toBe('warn');
+ expect(c.details).toMatchObject({ drifted: 30, source_changed: 30 });
+ expect(c.message).toContain('gbrain repair stale-atoms');
+ }, 60_000);
});
diff --git a/test/e2e/journey-atoms-sync-race-postgres.test.ts b/test/e2e/journey-atoms-sync-race-postgres.test.ts
new file mode 100644
index 0000000000..da00c46637
--- /dev/null
+++ b/test/e2e/journey-atoms-sync-race-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../journey-atoms-sync-race.test.ts'));
diff --git a/test/e2e/repair-stale-atoms-postgres.test.ts b/test/e2e/repair-stale-atoms-postgres.test.ts
new file mode 100644
index 0000000000..f2c34ae578
--- /dev/null
+++ b/test/e2e/repair-stale-atoms-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-stale-atoms.test.ts'));
diff --git a/test/journey-atoms-sync-race.test.ts b/test/journey-atoms-sync-race.test.ts
new file mode 100644
index 0000000000..e56e14b8f4
--- /dev/null
+++ b/test/journey-atoms-sync-race.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Cross-lane journey (ENG-O14): #5770 together with #5777, on PGLite and, with
+ * a safe DATABASE_URL, Postgres (test/e2e/journey-atoms-sync-race-postgres.test.ts).
+ *
+ * A managed source page is synced and extracted, edited through sync, caught
+ * in the trailing-commit window of a queued publication (#5777: skipped, not a
+ * sticky source_changed), re-extracted (#5774 retires the stale atom), deleted
+ * and cleaned up by `gbrain repair stale-atoms`, then restored: discovery
+ * offers it again and extraction restores every atom of its current text.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { runPhaseExtractAtoms, discoverExtractablePages } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const note = (text: string) => `---\ntitle: Example note\ntype: source\n---\n${`${text} `.repeat(40).trim()}\n`;
+
+for (const kind of testBackends()) {
+ describe(`#5770 with #5777 (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-journey-atoms-sync-'));
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));
+ if (close) await close(); else await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('queued publication, stale-atom preview, source change, retirement, restoration and rediscovery', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const sourceId = `journey-${randomUUID().replace(/-/g, '').slice(0, 12)}`;
+ const root = join(home, sourceId);
+ const slug = 'notes/example';
+ const path = join(root, 'notes/example.md');
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const commit = (message: string) => { git('add', 'notes/example.md'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git('rev-parse', 'HEAD'); };
+ mkdirSync(join(root, 'notes'), { recursive: true }); git('init', '-q');
+ writeFileSync(path, note('The first project record.')); commit('first');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ let titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const extract = async () => {
+ const page = (await engine.getPage(slug, { sourceId }))!;
+ return runPhaseExtractAtoms(engine, { sourceId, _transcripts: [], _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+ };
+ const atoms = async () => Object.fromEntries((await engine.executeRaw<{ slug: string; deleted: boolean; retired_by: string | null }>(
+ "SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]))
+ .map(row => [row.slug.replace(/^atoms\/[^/]+\//, '').replace(/-[0-9a-f]+$/, ''), { deleted: row.deleted, retired_by: row.retired_by }]));
+ const repair = async (args: string[]) => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, [...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')).results[0] as { apply_command: string; listing: Array<{ class: string }>; outcomes?: Record<string, number> };
+ };
+ const failures = () => loadSyncFailures().filter(row => row.source_id === sourceId);
+
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('first_sync');
+ expect((await extract()).status).toBe('ok');
+ expect(await atoms()).toEqual({ 'patience-compounds': { deleted: false, retired_by: null }, 'hire-slowly': { deleted: false, retired_by: null } });
+
+ writeFileSync(path, note('The edited project record.')); commit('edit');
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).not.toBe('blocked_by_failures');
+ writeFileSync(path, note('An older record a trailing commit still carries.')); const trailing = commit('trailing'); writeFileSync(path, note('The edited project record.'));
+ const raced = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(raced.status).not.toBe('blocked_by_failures');
+ expect(raced.managedWrite).toBeUndefined();
+ expect(raced.toCommit).toBe(trailing);
+ expect(failures()).toEqual([]);
+ expect((await engine.getPage(slug, { sourceId }))?.compiled_truth).toContain('The edited project record.');
+
+ titles = ['Patience compounds over years', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect(await atoms()).toMatchObject({ 'patience-compounds': { deleted: true, retired_by: 'managed-reextract' },
+ 'patience-compounds-over-years': { deleted: false }, 'hire-slowly': { deleted: false } });
+
+ await unmanaged(() => engine.softDeletePage(slug, { sourceId }));
+ const preview = await repair(['stale-atoms', '--source', sourceId]);
+ expect(preview.listing.map(entry => entry.class)).toEqual(['origin_gone', 'origin_gone']);
+ expect(preview.apply_command).toMatch(/^gbrain repair stale-atoms --source \S+ --apply --expect [0-9a-f]{64}$/);
+ expect((await repair(preview.apply_command.split(' ').slice(2))).outcomes).toEqual({ retired: 2 });
+ expect(await atoms()).toMatchObject({ 'patience-compounds-over-years': { deleted: true, retired_by: 'stale-atoms' },
+ 'hire-slowly': { deleted: true, retired_by: 'stale-atoms' } });
+
+ await unmanaged(() => engine.restorePage(slug, { sourceId }));
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ titles = ['Patience compounds', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(3);
+ expect(await atoms()).toEqual({ 'patience-compounds': { deleted: false, retired_by: null }, 'hire-slowly': { deleted: false, retired_by: null },
+ 'patience-compounds-over-years': { deleted: true, retired_by: 'stale-atoms' } });
+ expect(await discoverExtractablePages(engine, sourceId)).toEqual([]);
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).not.toBe('blocked_by_failures');
+ expect(failures()).toEqual([]);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }), 120_000);
+ });
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 0b52300deb..54f383ebb7 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -71,14 +71,14 @@ describe('registry', () => {
});
describe('execution-time enforcement', () => {
- test('runRepair refuses an explicit-only handler that was not named, then reaches the stub refusal when named', async () => {
+ test('runRepair refuses an explicit-only handler that was not named, then previews it when named', async () => {
const scope = await resolveRepairScope(engine);
const ctx = { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: true, remote: false } as unknown as OperationContext;
const unnamed = await refusal(() => runRepair(ctx, staleAtomsRepair, scope, { apply: false }));
expect(unnamed.toJSON()).toMatchObject({ error: 'explicit_kind_required', suggestion: 'Preview it on the brain host: gbrain repair stale-atoms',
docs: 'docs/guides/repair.md#explicit-only-repair-kinds' });
- const named = await refusal(() => runRepair(ctx, staleAtomsRepair, scope, { apply: false, explicit: true }));
- expect(named.toJSON()).toMatchObject({ error: 'unavailable', message: 'gbrain repair stale-atoms is not implemented in this build.' });
+ const named = await runRepair(ctx, staleAtomsRepair, scope, { apply: false, explicit: true });
+ expect(named).toMatchObject({ kind: 'stale-atoms', mode: 'dry_run', affected: 0 });
});
test('the shared runner refuses an unnamed explicit-only kind', async () => {
diff --git a/test/repair-stale-atoms.test.ts b/test/repair-stale-atoms.test.ts
new file mode 100644
index 0000000000..4d00ab170e
--- /dev/null
+++ b/test/repair-stale-atoms.test.ts
@@ -0,0 +1,252 @@
+/**
+ * `gbrain repair stale-atoms` (#5770, CEO-A7, ENG-O7, DX-O4), on PGLite and,
+ * with a safe DATABASE_URL, Postgres (test/e2e/repair-stale-atoms-postgres.test.ts).
+ *
+ * Unmanaged and managed brains: the preview lists both classes and changes
+ * nothing; the apply needs the preview hash and retires exactly the previewed
+ * set; an atom that changed since the preview is kept as changed_since_preview;
+ * imported and file-bound atoms survive; on a managed brain a deleted page's
+ * atoms come back when the page is restored and extracted again.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { runPhaseExtractAtoms, discoverExtractablePages } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operations } from '../src/core/operations.ts';
+import { computeAtomProvenanceDriftCheck } from '../src/commands/doctor.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
+ listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number>; outcome_items?: Array<{ item: string; outcome: string }> }> }
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+test('stale-atoms is CLI-only: no operation exposes it over MCP (ENG-O13)', () => {
+ expect(operations.map(op => op.name).filter(name => /stale|repair/.test(name))).toEqual([]);
+});
+
+for (const kind of testBackends()) {
+ describe(`gbrain repair stale-atoms (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-stale-atoms-'));
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ if (close) await close(); else await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const repair = async (args: string[]): Promise<RepairJson> => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['stale-atoms', ...args, '--json'])); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ };
+ const hashOf = (json: RepairJson) => json.results[0].apply_command.match(/--expect ([0-9a-f]+)/)![1];
+ const atom = async (sourceId: string, slug: string) => (await engine.executeRaw<{ deleted: boolean; frontmatter: Record<string, unknown> }>(
+ 'SELECT deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];
+ const putAtom = (sourceId: string, slug: string, frontmatter: Record<string, unknown>) =>
+ engine.putPage(slug, { type: 'atom', title: slug, compiled_truth: `Claim ${slug}.`, frontmatter: { type: 'atom', ...frontmatter } }, { sourceId });
+
+ async function unmanagedFixture() {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `stale-u-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const edited = await engine.putPage('notes/edited', { type: 'note', title: 'Edited', compiled_truth: 'The current text of the edited page.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/edited-old', { source_slug: 'notes/edited', source_hash: 'aaaaaaaaaaaaaaaa' });
+ await putAtom(sourceId, 'atoms/2026-01-01/edited-current', { source_slug: 'notes/edited', source_hash: edited.content_hash!.slice(0, 16) });
+ await engine.putPage('notes/unextracted', { type: 'note', title: 'Unextracted', compiled_truth: 'Edited but not extracted again.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/unextracted-old', { source_slug: 'notes/unextracted', source_hash: 'bbbbbbbbbbbbbbbb' });
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'A page the user deleted.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/gone', { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc' });
+ await putAtom(sourceId, 'atoms/2026-01-01/imported', { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc', imported_from: 'brain-export' });
+ await putAtom(sourceId, 'atoms/2026-01-01/file-bound', { source_path: '/transcripts/meeting.txt', source_hash: 'dddddddddddddddd' });
+ await engine.softDeletePage('notes/gone', { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/orphan', { source_slug: 'notes/never-existed', source_hash: 'eeeeeeeeeeeeeeee' });
+ return sourceId;
+ }
+
+ test('unmanaged: the preview lists both classes and changes nothing; the apply needs its hash and retires exactly them', async () => {
+ const sourceId = await unmanagedFixture();
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing).toEqual([
+ { item: `${sourceId}:atoms/2026-01-01/gone`, class: 'origin_gone', detail: 'source page notes/gone is gone' },
+ { item: `${sourceId}:atoms/2026-01-01/orphan`, class: 'origin_gone', detail: 'source page notes/never-existed is gone' },
+ { item: `${sourceId}:atoms/2026-01-01/edited-old`, class: 'origin_changed', detail: expect.stringContaining('source page notes/edited now at') },
+ ]);
+ expect(preview.results[0].residuals).toEqual({ origin_gone: 2, origin_changed: 1 });
+ const hash = hashOf(preview);
+ expect(preview.results[0].apply_command).toBe(`gbrain repair stale-atoms --source ${sourceId} --apply --expect ${hash}`);
+ for (const slug of ['gone', 'orphan', 'edited-old']) expect((await atom(sourceId, `atoms/2026-01-01/${slug}`)).deleted).toBe(false);
+
+ const unbound = await refusal(() => repair(['--source', sourceId, '--apply']));
+ expect(unbound.toJSON()).toMatchObject({ error: 'invalid_params', docs: 'docs/guides/repair.md#explicit-only-repair-kinds',
+ suggestion: `Preview first: gbrain repair stale-atoms --source ${sourceId} — then run the apply command it prints: gbrain repair stale-atoms --source ${sourceId} --apply --expect <preview-hash>` });
+ const stale = await refusal(() => repair(['--source', sourceId, '--apply', '--expect', 'f'.repeat(64)]));
+ expect(stale.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed',
+ message: `The preview changed since ${'f'.repeat(64)}; re-run gbrain repair stale-atoms --source ${sourceId} and use the new hash.` });
+
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hash]);
+ expect(applied.results[0]).toMatchObject({ applied: 3, skipped: 0, outcomes: { retired: 3 } });
+ for (const slug of ['gone', 'orphan', 'edited-old']) {
+ const row = await atom(sourceId, `atoms/2026-01-01/${slug}`);
+ expect(row.deleted).toBe(true);
+ expect(row.frontmatter.retired_by).toBe('stale-atoms');
+ }
+ for (const slug of ['edited-current', 'unextracted-old', 'imported', 'file-bound']) expect((await atom(sourceId, `atoms/2026-01-01/${slug}`)).deleted).toBe(false);
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair-approval' AND fingerprint=$1", [`stale-atoms:${hash}`])).toEqual([]);
+ expect((await repair(['--source', sourceId])).results[0].affected).toBe(0);
+ }, 60_000);
+
+ test('unmanaged: an atom edited between preview and apply reports changed_since_preview and is kept', async () => {
+ const sourceId = await unmanagedFixture();
+ const hash = hashOf(await repair(['--source', sourceId]));
+ await putAtom(sourceId, 'atoms/2026-01-01/orphan', { source_slug: 'notes/never-existed', source_hash: 'eeeeeeeeeeeeeeee', note: 'edited after the preview' });
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hash]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, skipped: 1, outcomes: { retired: 2, changed_since_preview: 1 } });
+ expect(applied.results[0].outcome_items).toContainEqual(expect.objectContaining({ item: `${sourceId}:atoms/2026-01-01/orphan`, outcome: 'changed_since_preview' }));
+ expect((await atom(sourceId, 'atoms/2026-01-01/orphan')).deleted).toBe(false);
+ }, 60_000);
+
+ test('recovery journey: doctor, preview, apply, doctor, running the printed commands verbatim (DX-O15c)', async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `stale-j-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'A page the user deleted.' }, { sourceId });
+ for (let i = 0; i < 30; i++) await putAtom(sourceId, `atoms/2026-01-01/gone-${i}`, { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc' });
+ await engine.softDeletePage('notes/gone', { sourceId });
+ const before = await computeAtomProvenanceDriftCheck(engine);
+ expect(before.status).toBe('warn');
+ const printed = before.message.match(/gbrain repair stale-atoms/)![0];
+ const preview = await withEnv({ GBRAIN_HOME: home }, async () => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, [...printed.split(' ').slice(2), '--source', sourceId, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ });
+ expect(preview.results[0].residuals).toEqual({ origin_gone: 30, origin_changed: 0 });
+ const applied = await repair(preview.results[0].apply_command.split(' ').slice(3));
+ expect(applied.results[0].outcomes).toEqual({ retired: 30 });
+ const after = await computeAtomProvenanceDriftCheck(engine);
+ expect(Number((before.details as Record<string, number>).source_gone) - Number((after.details as Record<string, number>).source_gone)).toBe(30);
+ }, 60_000);
+
+ async function managedFixture(sourceId: string) {
+ const root = join(home, sourceId);
+ const slug = 'notes/example';
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (body: string) => {
+ const written = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: body }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(written, []));
+ return written;
+ };
+ let page = await writeSource('A careful project record at revision one. '.repeat(40));
+ await withEnv({ GBRAIN_HOME: home }, async () => { await registerLocalWriter(engine, 'cli'); await claimWorktree(engine, sourceId, root); });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ return {
+ root, slug, unmanaged, calls: () => calls,
+ extract: () => withEnv({ GBRAIN_HOME: home }, () => runPhaseExtractAtoms(engine, { sourceId, _transcripts: [],
+ _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat })),
+ edit: async (body: string) => { page = await unmanaged(() => writeSource(body)); return page; },
+ atoms: () => engine.executeRaw<{ slug: string; deleted: boolean; frontmatter: Record<string, unknown> }>(
+ "SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND type='atom' ORDER BY slug", [sourceId]),
+ };
+ }
+
+ test('managed: delete the page, repair, restore the page, and extraction re-creates its atoms', async () => {
+ const sourceId = `stale-m-${randomUUID().slice(0, 8)}`;
+ const f = await managedFixture(sourceId);
+ try {
+ expect((await f.extract()).status).toBe('ok');
+ const before = await f.atoms();
+ expect(before.map(row => row.deleted)).toEqual([false, false]);
+ await f.unmanaged(() => engine.softDeletePage(f.slug, { sourceId }));
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing!.map(entry => entry.class)).toEqual(['origin_gone', 'origin_gone']);
+ expect((await f.atoms()).map(row => row.deleted)).toEqual([false, false]);
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, outcomes: { retired: 2 } });
+ for (const row of await f.atoms()) {
+ expect(row).toMatchObject({ deleted: true, frontmatter: { retired_by: 'stale-atoms' } });
+ expect(existsSync(join(f.root, `${row.slug}.md`))).toBe(false);
+ }
+ await f.unmanaged(() => engine.restorePage(f.slug, { sourceId }));
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([f.slug]);
+ expect((await f.extract()).status).toBe('ok');
+ expect(f.calls()).toBe(2);
+ const after = await f.atoms();
+ expect(after.map(row => row.slug)).toEqual(before.map(row => row.slug));
+ for (const row of after) {
+ expect(row.deleted).toBe(false);
+ expect(row.frontmatter).not.toHaveProperty('retired_by');
+ expect(existsSync(join(f.root, `${row.slug}.md`))).toBe(true);
+ }
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 60_000);
+
+ test('managed: atoms of an edited page are stale only once its current text completed an extraction', async () => {
+ const sourceId = `stale-c-${randomUUID().slice(0, 8)}`;
+ const f = await managedFixture(sourceId);
+ try {
+ expect((await f.extract()).status).toBe('ok');
+ const edited = await f.edit('A careful project record at revision two. '.repeat(40));
+ expect((await repair(['--source', sourceId])).results[0].affected).toBe(0);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-atoms',$1,$2::text::jsonb)`,
+ [`pre-fix-${sourceId}`, JSON.stringify([{ sourceId, incarnation, requestId: randomUUID(), kind: 'page', locator: f.slug, pageId: edited.id, contentHash: edited.content_hash }])]);
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing!.map(entry => entry.class)).toEqual(['origin_changed', 'origin_changed']);
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, outcomes: { retired: 2 } });
+ expect((await f.atoms()).every(row => row.deleted && row.frontmatter.retired_by === 'stale-atoms')).toBe(true);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 60_000);
+ });
+}