Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/capy/fix-wave-5 (lane B-atoms) into lane B-facts; reuse the approval-keyed repair cursor

garrytan657ec6d9c4c6
diff --cc docs/architecture/canonical-writers.tsv
index 897e829049,2dfbb9cedd..73c2d6304f
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@@ -192,4 -192,5 +192,6 @@@ src/core/schema-migrations/v142-takes-e
src/core/schema-migrations/v144-open-loops.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/persistence/connector-path.ts 1 coordinator Connector path clear locks the source row, refuses filesystem sources and bound connectors, and runs as a coordinated write on managed brains.
src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.
+src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.
+ src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.
+ src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.
diff --cc docs/architecture/key-files/core-utilities-2.md
index 4709712110,6c13f8b18d..91b8fc79e3
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@@ -3,9 -3,8 +3,9 @@@
[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`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. 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()`.
+- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.
diff --cc src/core/persistence/prepared-maintenance.ts
index bf9d8f4bfa,b93318cc85..a26909dbbe
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@@ -118,20 -118,10 +118,20 @@@ export async function publishMaintenanc
/** A maintenance request with its own intent kind, keyed by the intent (a retry replays its receipt). */
export async function submitMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
- intent: Record<string, unknown> & { kind: string; expected_revision: string | null }): Promise<Record<string, unknown>> {
- return submitMaintenance(engine, authority, slug, intent, maintenanceRequestId({ authority: authority.writer, slug, intent }));
+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }, requestId?: string): Promise<Record<string, unknown>> {
+ return submitMaintenance(engine, authority, slug, intent, requestId ?? maintenanceRequestId({ authority: authority.writer, slug, intent }));
}
+/**
+ * A database-only maintenance request under a caller-chosen request id: a
+ * preview-approved item (`gbrain repair extractor-facts`) replays its own id
+ * after a crash. No worktree is bound, so no file is staged.
+ */
+export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }, requestId: string): Promise<Record<string, unknown>> {
+ return submitMaintenance(engine, authority, slug, intent, requestId, false);
+}
+
export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
cycleDate: string, rawSource?: string): Promise<void> {
const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId });
diff --cc src/core/repair/extractor-facts.ts
index 0235acdfa8,148468b78f..9b0be57960
--- a/src/core/repair/extractor-facts.ts
+++ b/src/core/repair/extractor-facts.ts
@@@ -1,402 -1,19 +1,400 @@@
/**
- * `gbrain repair extractor-facts` (#5731): 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 extractor-facts` (#5731, CEO-A9, ENG-O8, DX-O4, DX-T1):
+ * restore conversation-extractor facts that the pre-fix canonical projection
+ * expired.
+ *
+ * Before v0.60.11.0 every managed write to a fenceless conversation page ran
+ * the canonical facts projection with an empty fence, which expired every
+ * extractor fact of that page and cleared its `row_num` in the publication
+ * transaction. The fix stopped new expiries; this kind restores the old ones.
+ *
+ * Candidates: `source` starts with `cli:extract-conversation-facts`,
+ * `expired_at` set, `row_num` NULL (the projection's signature). Each is
+ * classified, in this order:
+ * - excluded (listed, never restored): the page is missing or deleted; the
+ * fact was superseded (`superseded_by`, E-T5); its claim was withdrawn
+ * (`fact_withdrawals`); an active fact with the same text and entity already
+ * sits on the page (a fence row or another extractor row); or an earlier
+ * candidate of the page carries the same text and entity.
+ * - ambiguous (restored only with `--include-ambiguous` and the hash of that
+ * preview): an unmanaged brain (no receipts); no committed write receipt of
+ * the page completed at the exact expiry instant (`completed_at =
+ * expired_at`, which holds only when both happened in one transaction); the
+ * receipt's consumer is v0.60.11.0 or newer (a fence takeover, not the
+ * defect); or the page ever carried fence-projected facts (a fence row may
+ * have taken the fact's row number).
+ * - evidenced: everything else, restored by `--apply --expect <hash>`.
+ *
+ * `writer_version_cutoff` marks when consumers began stamping their version,
+ * so a receipt with no `consumer_version` was published by a binary older
+ * than the stamps, which shipped together with the fix.
+ *
+ * The preview lists every candidate with its class and evidence, prints a
+ * hash over them, and saves the restorable set (one item per page, each with
+ * its request id) through `persistence/preview-approval.ts`. The apply replays
+ * exactly that set: a managed brain publishes one database-only
+ * `managed_maintenance_restore_extractor_facts` request per page; an unmanaged
+ * brain writes directly under the page lock. Each fact is reclassified under
+ * the lock and restored only when its class, evidence and expiry are
+ * unchanged (`changed_since_preview` otherwise). A restored fact gets a fresh
+ * `row_num` above every row of its page, so it never looks like an unfenced
+ * legacy row. A resumed apply skips pages whose request already committed (or
+ * whose facts are already active), so a crash after publication restores no
- * new candidate. A page already passed by this set's cursor is not retried,
++ * new candidate. A page already passed by this set's cursor (keyed by its
++ * approval hash) is not retried,
+ * whatever its outcome, so a `--limit` run always advances.
*/
-import { catalogueError } from '../error-catalogue.ts';
-import type { RepairHandler } from './core.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { VERSION } from '../../version.ts';
+import { OperationError } from '../ops/contract.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { digest } from '../persistence/digest.ts';
+import { isTerminal } from '../persistence/model.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { waitForWrite, writeResponse } from '../persistence/service.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { compareWriterVersions, recentWriterVersions, writerVersionLabel } from '../persistence/writer-versions.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
- import type { RepairHandler, RepairItem, RepairItemOutcome, RepairListing, RepairPlan, RepairScope } from './core.ts';
++import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
-function notBuilt(): never {
- throw catalogueError('repair_kind_unavailable', 'gbrain repair extractor-facts is not implemented in this build.',
- 'Upgrade on the brain host, then preview again: gbrain upgrade && gbrain repair extractor-facts');
+export const EXTRACTOR_FACTS_INTENT = 'managed_maintenance_restore_extractor_facts';
+export const EXTRACTOR_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';
+/** The first release whose canonical projection leaves fenceless extractor facts alone. */
+export const EXTRACTOR_FACTS_FIX_VERSION = '0.60.11.0';
+
+export type ExtractorFactClass = 'evidenced' | 'ambiguous' | 'excluded';
+
+/**
+ * The exact expiry instant as text (UTC, microseconds). Compared as text in
+ * SQL: a bound timestamp parameter can lose its microseconds on the way in.
+ */
+const EXPIRY_TEXT = (column: string) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+/** One candidate as the preview showed it; the apply rechecks every field. */
+export interface ExtractorFactCandidate {
+ id: number;
+ source_id: string;
+ slug: string;
+ class: ExtractorFactClass;
+ reason: string;
+ /** UTC, microseconds: the exact instant the projection expired it. */
+ expired_at: string;
+ /** The committed request whose publication expired it, if any. */
+ receipt: string | null;
+ receipt_consumer: string | null;
+ /** Digest of the row's claim, visibility and entity, so an edited row is not restored. */
+ fact_hash: string;
+}
+
+/** One approved page: its restorable facts and the request id its managed restore uses. */
+export interface ExtractorFactsPage {
+ source_id: string;
+ slug: string;
+ page_id: number;
+ request_id: string;
+ include_ambiguous: boolean;
+ /** The preview's source scope; an apply under another scope refuses. */
+ scope: string[];
+ facts: ExtractorFactCandidate[];
+}
+
+interface PageItem extends RepairItem { page: ExtractorFactsPage; hash: string; last: boolean }
+
+interface CandidateRow {
+ id: number | string; source_id: string; slug: string; fact: string; visibility: string; entity_slug: string | null;
+ superseded: boolean; expired_at: string; page_id: number | string | null; page_deleted: boolean | null;
+ withdrawn: boolean; active_duplicate: boolean; fence_history: boolean; fingerprint: string;
+ receipt: string | null; receipt_consumer: string | null;
+}
+
+/**
+ * Every candidate of these sources (or of one page), classified, in (source,
+ * page, id) order. Read-only; `managed` is the brain's persistence mode.
+ */
+export async function classifyExtractorFacts(db: BrainEngine, sourceIds: string[], opts: { managed: boolean; slug?: string }): Promise<ExtractorFactCandidate[]> {
+ const rows = await db.executeRaw<CandidateRow>(`
+ WITH cand AS (
+ SELECT f.id, f.source_id, f.source_markdown_slug AS slug, f.fact, f.visibility, f.entity_slug, f.expired_at AS expired,
+ f.superseded_by IS NOT NULL AS superseded, gbrain_fact_fingerprint(f.fact) AS fingerprint
+ FROM facts f
+ WHERE f.source_id=ANY($1::text[]) AND f.source LIKE '${EXTRACTOR_FACTS_SOURCE_PREFIX}%'
+ AND f.expired_at IS NOT NULL AND f.row_num IS NULL AND f.source_markdown_slug IS NOT NULL
+ AND ($2::text IS NULL OR f.source_markdown_slug=$2::text)
+ ), receipts AS (
+ SELECT DISTINCT ON (r.source_id, r.slug, r.completed_at) r.source_id, r.slug, r.completed_at,
+ r.request_id::text AS request_id, r.consumer_version
+ FROM persistence_requests r
+ JOIN (SELECT DISTINCT source_id, slug, expired FROM cand) k
+ ON k.source_id=r.source_id AND k.slug=r.slug AND k.expired=r.completed_at
+ WHERE r.state='committed'
+ ORDER BY r.source_id, r.slug, r.completed_at, r.sequence
+ ), fenced AS (
+ SELECT DISTINCT g.source_id, g.source_markdown_slug AS slug FROM facts g
+ JOIN (SELECT DISTINCT source_id, slug FROM cand) k ON k.source_id=g.source_id AND k.slug=g.source_markdown_slug
+ WHERE COALESCE(g.source,'') NOT LIKE '${EXTRACTOR_FACTS_SOURCE_PREFIX}%'
+ )
+ SELECT c.id, c.source_id, c.slug, c.fact, c.visibility, c.entity_slug, c.superseded, c.fingerprint,
+ ${EXPIRY_TEXT('c.expired')} AS expired_at,
+ p.id AS page_id, p.deleted_at IS NOT NULL AS page_deleted,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=c.source_id AND w.visibility=c.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(c.fact), gbrain_fact_fingerprint_v1(c.fact))
+ AND (w.subject='*' OR w.subject=c.entity_slug)) AS withdrawn,
+ EXISTS (SELECT 1 FROM facts a WHERE a.source_id=c.source_id AND a.visibility=c.visibility
+ AND gbrain_fact_fingerprint(a.fact)=c.fingerprint AND a.source_markdown_slug=c.slug AND a.expired_at IS NULL
+ AND a.entity_slug IS NOT DISTINCT FROM c.entity_slug) AS active_duplicate,
+ fenced.slug IS NOT NULL AS fence_history,
+ r.request_id AS receipt, r.consumer_version AS receipt_consumer
+ FROM cand c
+ LEFT JOIN pages p ON p.source_id=c.source_id AND p.slug=c.slug
+ LEFT JOIN receipts r ON r.source_id=c.source_id AND r.slug=c.slug AND r.completed_at=c.expired
+ LEFT JOIN fenced ON fenced.source_id=c.source_id AND fenced.slug=c.slug
+ ORDER BY c.source_id, c.slug, c.id`, [sourceIds, opts.slug ?? null]);
+ const seen = new Set<string>();
+ return rows.map(row => {
+ const id = Number(row.id);
+ const key = JSON.stringify([row.source_id, row.slug, row.visibility, row.entity_slug, row.fingerprint]);
+ const [klass, reason] = classify(row, seen.has(key), opts.managed);
+ if (klass !== 'excluded') seen.add(key);
+ return { id, source_id: row.source_id, slug: row.slug, class: klass, reason, expired_at: row.expired_at,
+ receipt: row.receipt, receipt_consumer: row.receipt === null ? null : row.receipt_consumer,
+ fact_hash: digest([row.fact, row.visibility, row.entity_slug]) };
+ });
+}
+
+function classify(row: CandidateRow, duplicate: boolean, managed: boolean): [ExtractorFactClass, string] {
+ if (row.page_id === null || row.page_deleted) return ['excluded', 'page_missing'];
+ if (row.superseded) return ['excluded', 'superseded'];
+ if (row.withdrawn) return ['excluded', 'withdrawn'];
+ if (row.active_duplicate) return ['excluded', 'active_duplicate'];
+ if (duplicate) return ['excluded', 'duplicate_candidate'];
+ if (!managed) return ['ambiguous', 'unmanaged_brain'];
+ if (row.receipt === null) return ['ambiguous', 'no_same_transaction_receipt'];
+ const order = row.receipt_consumer === null ? -1 : compareWriterVersions(row.receipt_consumer, EXTRACTOR_FACTS_FIX_VERSION);
+ if (order === null || order >= 0) return ['ambiguous', 'post_fix_consumer'];
+ if (row.fence_history) return ['ambiguous', 'fence_takeover_possible'];
+ return ['evidenced', 'pre_fix_projection'];
+}
+
+const DETAILS: Record<string, string> = {
+ page_missing: 'its conversation page is missing or deleted',
+ superseded: 'a newer fact superseded it',
+ withdrawn: 'its claim was withdrawn (forget)',
+ active_duplicate: 'an active fact with the same text and entity is already on the page',
+ duplicate_candidate: 'an earlier candidate of the page has the same text and entity',
+ unmanaged_brain: 'unmanaged brain: no write receipt can prove the expiry',
+ no_same_transaction_receipt: 'no committed write of the page completed at the exact expiry instant',
+ post_fix_consumer: 'expired by a write published by a fixed consumer (a fence row may have taken its position)',
+ fence_takeover_possible: 'the page has carried fence facts, so a fence row may have taken its position',
+};
+
+function detail(fact: ExtractorFactCandidate): string {
+ if (fact.class !== 'evidenced') return DETAILS[fact.reason] ?? fact.reason;
+ return `expired at ${fact.expired_at} by the pre-fix projection in write ${fact.receipt}, published by ${writerVersionLabel(fact.receipt_consumer)}`;
+}
+
+/** The preview command for this scope: `--source` only when the scope is one source of several (what the operator passed). */
+async function previewCommand(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean): Promise<string> {
+ const [{ n }] = await engine.executeRaw<{ n: number | string }>('SELECT count(*)::int AS n FROM sources WHERE archived IS NOT TRUE');
+ const narrowed = scope.source_ids.length === 1 && Number(n) > 1;
+ return `gbrain repair extractor-facts${narrowed ? ` --source ${scope.source_ids[0]}` : ''}${includeAmbiguous ? ' --include-ambiguous' : ''}`;
+}
+
+function requestIdFor(hash: string, page: Pick<ExtractorFactsPage, 'source_id' | 'slug'>, attempt: number): string {
+ const h = digest(['extractor-facts-request-v1', hash, page.source_id, page.slug, attempt]);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+/**
+ * Hosts whose latest consumer since `writer_version_cutoff` is older than this
+ * release: a pre-fix consumer there can expire restored facts again.
+ */
+async function mixedVersionWarnings(engine: BrainEngine): Promise<string[]> {
+ const rows = await recentWriterVersions(engine, 30).catch(() => []);
+ const latest = new Map<string, (typeof rows)[number]>();
+ for (const row of rows.filter(r => r.role === 'consumer')) {
+ const key = `${row.host_id}|${row.principal}`;
+ const prior = latest.get(key);
+ if (!prior || (row.last_seen ?? '') > (prior.last_seen ?? '')) latest.set(key, row);
+ }
+ const hosts = new Map<string, string>();
+ for (const row of latest.values()) {
+ const order = row.version === null ? -1 : compareWriterVersions(row.version, VERSION);
+ if (order !== null && order >= 0) continue;
+ const host = row.host_id ?? 'unknown (not recorded)';
+ if (!hosts.has(host)) hosts.set(host, `${row.version_label}, last seen ${row.last_seen}`);
+ }
+ return [...hosts].map(([host, seen]) => `host ${host} still published writes with a consumer older than this release (${seen}); `
+ + `a consumer older than v${EXTRACTOR_FACTS_FIX_VERSION} expires restored extractor facts again. Upgrade and restart gbrain on that host before applying.`);
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean, facts: ExtractorFactCandidate[]) {
+ 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: 'extractor-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous }, facts };
+}
+
- /** Cursor phase naming one approved set, so a cursor left by another preview never skips this set's pages. */
- const hashPhase = (hash: string) => Number.parseInt(hash.slice(0, 12), 16) || 0;
-
+function pageItem(page: ExtractorFactsPage, hash: string, index: number, last: boolean): PageItem {
- return { cursor: { phase: hashPhase(hash), id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,
++ return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: `restore ${page.facts.length} extractor fact(s)`, page, hash, last };
+}
+
+/** Pages of an approved set whose restore already finished (a committed request, or every fact active again). */
+async function finishedPages(engine: BrainEngine, hash: string, pages: ExtractorFactsPage[]): Promise<Set<string>> {
+ if (!pages.length) return new Set();
+ const committed = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT DISTINCT source_id, slug FROM persistence_requests
+ WHERE state='committed' AND operation='submit_job' AND source_id=ANY($1::text[]) AND slug=ANY($2::text[])
+ AND (intent->>'preview_hash'=$3 OR request_id=ANY($4::uuid[]))`,
+ [[...new Set(pages.map(p => p.source_id))], [...new Set(pages.map(p => p.slug))], hash, pages.map(p => p.request_id)]);
+ const active = await engine.executeRaw<{ id: number | string }>(
+ 'SELECT id FROM facts WHERE id=ANY($1::bigint[]) AND expired_at IS NULL AND row_num IS NOT NULL', [pages.flatMap(p => p.facts.map(f => f.id))]);
+ const restored = new Set(active.map(row => Number(row.id)));
+ const done = new Set(committed.map(row => `${row.source_id}\u0000${row.slug}`));
+ for (const page of pages) if (page.facts.every(f => restored.has(f.id))) done.add(`${page.source_id}\u0000${page.slug}`);
+ return done;
}
export const extractorFactsRepair: RepairHandler = {
kind: 'extractor-facts',
- plan: async () => notBuilt(),
- apply: async () => notBuilt(),
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeAmbiguous = opts?.includeAmbiguous === true;
+ if (!opts?.apply) {
+ const managed = await managedPersistenceEnabled(engine);
+ const facts = await classifyExtractorFacts(engine, scope.source_ids, { managed });
+ const hash = previewHash(await hashParts(engine, scope, includeAmbiguous, facts));
+ const pageIds = new Map((await engine.executeRaw<{ id: number | string; source_id: string; slug: string }>(
+ 'SELECT id, source_id, slug FROM pages WHERE source_id=ANY($1::text[]) AND slug=ANY($2::text[]) AND deleted_at IS NULL',
+ [scope.source_ids, [...new Set(facts.map(f => f.slug))]])).map(row => [`${row.source_id}\u0000${row.slug}`, Number(row.id)]));
+ const pages = new Map<string, ExtractorFactsPage>();
+ for (const fact of facts) {
+ if (fact.class === 'excluded' || fact.class === 'ambiguous' && !includeAmbiguous) continue;
+ const key = `${fact.source_id}\u0000${fact.slug}`;
+ const page = pages.get(key) ?? { source_id: fact.source_id, slug: fact.slug, page_id: pageIds.get(key)!,
+ request_id: requestIdFor(hash, fact, 0), include_ambiguous: includeAmbiguous, scope: scope.source_ids, facts: [] };
+ page.facts.push(fact);
+ pages.set(key, page);
+ }
+ const approved = [...pages.values()];
+ if (approved.length) await saveApprovedSet(engine, { command: 'extractor-facts', hash }, approved);
+ const count = (klass: ExtractorFactClass) => facts.filter(f => f.class === klass).length;
+ const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,
+ class: fact.class === 'excluded' ? `excluded:${fact.reason}` : fact.class, detail: detail(fact) }));
+ return { items: approved.map((page, index) => pageItem(page, hash, index, index === approved.length - 1)), preview_hash: hash,
+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded') },
+ listing, warnings: await mixedVersionWarnings(engine) };
+ }
+ const command = await previewCommand(engine, scope, includeAmbiguous);
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair extractor-facts --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<ExtractorFactsPage>(engine, { command: 'extractor-facts', hash: opts.expect, previewCommand: command });
+ const scopeKey = JSON.stringify(scope.source_ids);
+ if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {
+ throw previewChangedError(opts.expect, command);
+ }
- // Resume: skip pages this set's cursor already passed (any outcome) and pages whose restore already finished.
++ // Resume: skip pages the set's cursor (keyed by its approval hash in runRepair) already passed,
++ // whatever their outcome, and pages whose restore already finished.
+ const done = await finishedPages(engine, opts.expect, approved.items);
- const passed = after && after.phase === hashPhase(opts.expect) ? after.id : 0;
+ const items = approved.items.map((page, index) => pageItem(page, opts.expect!, index, index === approved.items.length - 1))
- .filter(item => item.cursor.id > passed && !done.has(`${item.source_id}\u0000${item.slug}`));
++ .filter(item => afterCursor(item.cursor, after) && !done.has(`${item.source_id}\u0000${item.slug}`));
+ if (!items.length) await clearApprovedSet(engine, { command: 'extractor-facts', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: { already_restored_pages: approved.items.length - items.length } };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, last } = entry as PageItem;
+ const result = await managedPersistenceEnabled(ctx.engine)
+ ? await restoreManaged(ctx.engine, ctx.config, page, hash)
+ : await ctx.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ return restorePageFacts(tx, page, false);
+ });
+ if (last) await clearApprovedSet(ctx.engine, { command: 'extractor-facts', hash });
+ const changed = page.facts.length - result.restored.length;
+ return { applied: result.restored.length > 0, outcome: !changed ? 'restored' : result.restored.length ? 'partially_restored' : 'changed_since_preview',
+ ...(changed ? { reason: `${result.restored.length} of ${page.facts.length} restored; changed since the preview: ${result.changed.join(', ')}` } : {}) };
+ },
};
+
+interface RestoreResult { restored: number[]; changed: number[] }
+
+async function restoreManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: ExtractorFactsPage, hash: string): Promise<RestoreResult> {
+ const unchanged: RestoreResult = { restored: [], changed: page.facts.map(f => f.id) };
+ const authority = (await maintenancePreflight(engine, page.source_id))!;
+ for (let attempt = 0; ; attempt++) {
+ const requestId = attempt === 0 ? page.request_id : requestIdFor(hash, page, attempt);
+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;
+ try {
+ let receipt: Record<string, unknown>;
+ if (prior) {
+ await authorizeStoredRequest(engine, prior);
+ receipt = writeResponse(await waitForWrite(engine, prior, config));
+ } else {
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot || snapshot.page.id !== page.page_id) return unchanged;
+ receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,
+ { kind: EXTRACTOR_FACTS_INTENT, expected_revision: snapshot.revision, preview_hash: hash, page }, requestId);
+ }
+ return { restored: (receipt.restored as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [] };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return unchanged;
+ throw error;
+ }
+ }
+}
+
+/**
+ * Restores the page's approved facts that are still exactly as previewed,
+ * under the page lock: each gets a fresh row number above every fact and
+ * fence row of the page. Runs inside the managed publication or the unmanaged
+ * transaction.
+ */
+async function restorePageFacts(tx: BrainEngine, page: ExtractorFactsPage, managed: boolean): Promise<RestoreResult> {
+ const ids = page.facts.map(f => f.id);
+ await tx.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) FOR UPDATE', [page.source_id, ids]);
+ const live = new Map((await classifyExtractorFacts(tx, [page.source_id], { managed, slug: page.slug })).map(f => [f.id, f]));
+ const [snapshot] = await tx.executeRaw<{ compiled_truth: string | null; max_row: number | string | null }>(
+ `SELECT p.compiled_truth, (SELECT MAX(row_num) FROM facts WHERE source_id=$1 AND source_markdown_slug=$2) AS max_row
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL`, [page.source_id, page.slug]);
+ const fenceRows = parseFactsFence(snapshot?.compiled_truth ?? '').facts.map(f => f.rowNum);
+ let next = Math.max(Number(snapshot?.max_row ?? 0), ...fenceRows, 0) + 1;
+ const result: RestoreResult = { restored: [], changed: [] };
+ for (const approved of page.facts) {
+ const current = live.get(approved.id);
+ const same = !!snapshot && !!current && (['class', 'reason', 'expired_at', 'receipt', 'receipt_consumer', 'fact_hash'] as const)
+ .every(field => current[field] === approved[field]);
+ const updated = same ? await tx.executeRaw(`UPDATE facts SET expired_at=NULL, row_num=$3
+ WHERE source_id=$1 AND id=$2 AND row_num IS NULL AND superseded_by IS NULL AND ${EXPIRY_TEXT('expired_at')}=$4 RETURNING id`,
+ [page.source_id, approved.id, next, approved.expired_at]) : [];
+ if (updated.length) { result.restored.push(approved.id); next++; } else result.changed.push(approved.id);
+ }
+ return result;
+}
+
+/**
+ * Preparer for `managed_maintenance_restore_extractor_facts`: a database-only
+ * publication on the page key that reclassifies and restores the approved
+ * facts of one page, reporting the rest as `changed_since_preview`.
+ */
+export async function prepareExtractorFactsRestore(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const intent = row.intent as { page?: ExtractorFactsPage; preview_hash?: unknown } | null;
+ const page = intent?.page;
+ if (!page || page.source_id !== row.source_id || page.slug !== row.slug || typeof intent?.preview_hash !== 'string' || !Array.isArray(page.facts)) {
+ throw new OperationError('invalid_params', 'The extractor facts restore intent does not name its page.');
+ }
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw new OperationError('page_identity_changed', 'The conversation page was deleted or replaced before its facts were restored.');
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const result = await restorePageFacts(tx, page, true);
+ return { status: 'completed', preview_hash: intent!.preview_hash, restored: result.restored, changed_since_preview: result.changed };
+ } };
+}
diff --cc src/core/repair/registry.ts
index ac85e5c32f,ced5831865..f85c51f811
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@@ -96,15 -96,14 +96,17 @@@ const SPECS: Record<RepairKind, Omit<Re
+ '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,
- summary: 'Restore extractor facts expired by the pre-fix re-extraction (#5731). Not implemented in this build.',
+ 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 '
+ + '(a committed write of the page completed in the same transaction, by an older consumer); --include-ambiguous widens the hashed set to facts '
+ + 'without that evidence. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a fact that changed since reports '
+ + 'changed_since_preview and stays expired. Superseded, withdrawn and duplicated facts are never restored. Database-only; no page is rewritten.',
},
};