Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): gbrain repair extractor-facts restores facts the pre-fix projection expired (#5731)
garrytancb394d18a737
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 95b29a9ae4..897e829049 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -192,3 +192,4 @@ src/core/schema-migrations/v142-takes-embedding-dimension-matches-config.ts 1 scsrc/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.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 5503266a3a..4a28ef1425 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -8,6 +8,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.+- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 4195089a98..4709712110 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -5,6 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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/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 --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 88f8e6d678..1405cf0814 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -71,7 +71,7 @@ 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/commands/doctor/checks/extractor-facts.ts', reason: 'held: fix wave 5 lane B-facts (#5731); the integrator registers extractor_facts_expired in WAVE_CHECKS (src/commands/doctor/wave-checks.ts) with the doctor goldens and removes 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/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 26527e0240..161031a465 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -31,6 +31,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/persistence/orphan-bindings.ts": ["test/e2e/sources-remove-bindings.test.ts"],// Fix wave 5 shared commit: preview-bound approved sets in op_checkpoints."src/core/persistence/preview-approval.ts": ["test/e2e/preview-approval-postgres.test.ts"],+ // Fix wave 5 (#5731): the extractor-facts restore and its doctor check.+ "src/core/repair/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts"],+ "src/commands/doctor/checks/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts"],"src/core/persistence/deactivation.ts": ["test/e2e/persistence-deactivate-race.test.ts", "test/e2e/fix-wave-4-integration.test.ts"],// SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger."src/core/skillopt/**": [diff --git a/src/commands/doctor/checks/extractor-facts.ts b/src/commands/doctor/checks/extractor-facts.tsnew file mode 100644index 0000000000..57cf87f820--- /dev/null+++ b/src/commands/doctor/checks/extractor-facts.ts@@ -0,0 +1,34 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';+import { classifyExtractorFacts } from '../../../core/repair/extractor-facts.ts';++/**+ * #5731: conversation-extractor facts the pre-fix canonical projection+ * expired (expired, row number cleared). Counts the restorable ones by class+ * (evidenced, ambiguous) and names the explicit-only repair's preview; the+ * excluded ones (superseded, withdrawn, duplicated, page gone) are reported+ * but never count as a finding. Read-only.+ */+export async function extractorFactsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const facts = await classifyExtractorFacts(engine, sources, { managed: await managedPersistenceEnabled(engine) });+ const count = (klass: string) => facts.filter(f => f.class === klass).length;+ const details = { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),+ repair: 'extractor-facts', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' };+ if (!details.evidenced && !details.ambiguous) {+ return { name: 'extractor_facts_expired', status: 'ok', details,+ message: `No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection${details.excluded ? ` (${details.excluded} expired candidate(s) are excluded and stay expired)` : ''}.` };+ }+ return { name: 'extractor_facts_expired', status: 'warn', details,+ message: `${details.evidenced + details.ambiguous} conversation-extractor fact(s) were expired by the pre-v0.60.11.0 canonical projection `+ + `(${details.evidenced} with receipt evidence, ${details.ambiguous} ambiguous); recall no longer returns them. `+ + 'Preview the restore on the brain host: gbrain repair extractor-facts — then run the apply command it prints after the user agrees '+ + '(ambiguous rows only with gbrain repair extractor-facts --include-ambiguous).' };+ } catch (error) {+ return { name: 'extractor_facts_expired', status: 'warn',+ message: `Expired extractor facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown' } };+ }+}diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 7c774f0cd8..eef9a876f9 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -105,6 +105,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {function human(result: RepairResult): string {const lines = [`${result.kind}: ${result.affected} item(s) ${result.mode === 'apply' ? 'pending before this run' : 'to repair'}`];+ for (const warning of result.warnings ?? []) lines.push(` WARNING: ${warning}`);if (result.sample.length) lines.push(` e.g. ${result.sample.join(', ')}`);const residuals = Object.entries(result.residuals).map(([k, v]) => `${k}=${v}`).join(', ');if (residuals) lines.push(` ${residuals}`);@@ -114,6 +115,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/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex d720d1e718..bf9d8f4bfa 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -122,6 +122,16 @@ export async function submitMaintenanceIntent(engine: BrainEngine, authority: Mareturn submitMaintenance(engine, authority, slug, intent, 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 });@@ -263,6 +273,7 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');+ if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_page') {const prepared = await preparePageMutation(engine, row.intent.expected_revision === null? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex f3a59bb01e..2747cd1341 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -38,13 +38,19 @@ export interface RepairItem {}export interface RepairPlan {+ /** Operator warnings the preview prints before its items (for example an older writer that can undo the repair). */+ warnings?: string[];items: RepairItem[];/** Counts of rows the kind keeps and reports instead of repairing. */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 }@@ -70,6 +76,7 @@ export interface RepairItemOutcome { applied: boolean; outcome: string; reason?:export interface RepairResult {kind: RepairKind;mode: 'dry_run' | 'apply';+ warnings?: string[];scope: RepairScope;affected: number;sample: string[];@@ -82,6 +89,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 }>;@@ -186,11 +195,12 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, scost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: handler.embeds === false ? 0 : pending.length,embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel) },capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),- resumed_from: resumed, applied: 0, skipped: 0, complete: false,+ resumed_from: resumed, applied: 0, skipped: 0, complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`+ `${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/extractor-facts.ts b/src/core/repair/extractor-facts.tsindex 148468b78f..e8a8e9f92c 100644--- a/src/core/repair/extractor-facts.ts+++ b/src/core/repair/extractor-facts.ts@@ -1,19 +1,390 @@/**- * `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 already sits on+ * the page (a fence row or another extractor row); or an earlier candidate+ * of the page carries the same text.+ * - 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.*/-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';-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;+ 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) 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.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 is already on the page',+ duplicate_candidate: 'an earlier candidate of the page has the same text',+ 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 };+}++function pageItem(page: ExtractorFactsPage, hash: string, last: boolean): PageItem {+ return { cursor: { phase: 0, id: page.page_id }, 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, 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 === 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 });+ if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous)) throw previewChangedError(opts.expect, command);+ const done = await finishedPages(engine, opts.expect, approved.items);+ const pending = approved.items.filter(page => !done.has(`${page.source_id}\u0000${page.slug}`));+ if (!pending.length) await clearApprovedSet(engine, { command: 'extractor-facts', hash: opts.expect });+ return { items: pending.map((page, index) => pageItem(page, opts.expect!, index === pending.length - 1)), preview_hash: opts.expect,+ residuals: { already_restored_pages: approved.items.length - pending.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 --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 6e899c8313..ac85e5c32f 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -100,8 +100,11 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {summary: 'Retire managed atoms whose source page changed or was deleted (#5770). Not implemented in this build.',},'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.',},};diff --git a/test/e2e/repair-extractor-facts-postgres.test.ts b/test/e2e/repair-extractor-facts-postgres.test.tsnew file mode 100644index 0000000000..7ea3840231--- /dev/null+++ b/test/e2e/repair-extractor-facts-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-extractor-facts.test.ts'));diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 0b52300deb..2f6dc59e99 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -120,10 +120,10 @@ describe('surfaces that list instead of run', () => {expect(currentExitCode()).toBe(0);});- test('naming an explicit kind runs it (here: the stub refusal) instead of explicit_kind_required', async () => {- const error = await refusal(() => withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['extractor-facts'])));- expect(error.code).toBe('unavailable');- expect(error.suggestion).toContain('gbrain repair extractor-facts');+ test('naming an explicit kind runs it (here: the extractor-facts preview) instead of explicit_kind_required', async () => {+ const out = JSON.parse(await captured(['extractor-facts', '--json'])) as { results: Array<{ kind: string; mode: string; affected: number }>; explicit_kinds?: unknown };+ expect(out.results).toMatchObject([{ kind: 'extractor-facts', mode: 'dry_run', affected: 0 }]);+ expect(out.explicit_kinds).toBeUndefined();});test('help marks explicit kinds with their preview and keeps them out of the --all list; --expect is accepted only for them', () => {diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.tsnew file mode 100644index 0000000000..1f7b073027--- /dev/null+++ b/test/repair-extractor-facts.test.ts@@ -0,0 +1,352 @@+/**+ * `gbrain repair extractor-facts` (#5731, CEO-A9, ENG-O8, DX-O4, DX-T1), on+ * PGLite and, with a safe DATABASE_URL, Postgres+ * (test/e2e/repair-extractor-facts-postgres.test.ts).+ *+ * Protects: facts the pre-fix canonical projection expired come back only+ * with receipt evidence (a committed write of the page completed in the same+ * transaction, by a consumer older than v0.60.11.0); compacted receipts still+ * count; separate-transaction, post-fix, fence-history and unmanaged rows are+ * ambiguous and need --include-ambiguous with that preview's hash;+ * superseded, withdrawn and duplicated rows are never restored; the apply+ * restores exactly the previewed set, rechecks each fact, and a resumed apply+ * restores no new candidate.+ * Seams: the pre-fix projection's expiry is reproduced by its SQL effect (a+ * real committed page write, then `expired_at` and the receipt's completion+ * set in one transaction); the crash replaces the handler's apply for one run.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { VERSION } from '../src/version.ts';+import { operations } from '../src/core/operations.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { extractorFactsRepair, EXTRACTOR_FACTS_INTENT } from '../src/core/repair/extractor-facts.ts';+import { extractorFactsCheck } from '../src/commands/doctor/checks/extractor-facts.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { compactWriteReceipts } from '../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const EXTRACTOR = 'cli:extract-conversation-facts:sess';+const ENTITY = 'people/alice-example';++interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;+ warnings?: string[]; listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number>;+ outcome_items?: Array<{ item: string; outcome: string; reason?: 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');+}++/** `home` only outside a managed brain, whose helper already set GBRAIN_HOME (the owner's host identity). */+async function repair(engine: BrainEngine, home: string | null, args: string[]): Promise<RepairJson> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ const run = () => runRepairCommand(engine, ['extractor-facts', ...args, '--json']);+ try { await (home ? withEnv({ GBRAIN_HOME: home }, run) : run()); } 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];++/** A conversation page with extractor facts at row numbers 1..n, as `extract-conversation-facts` leaves it. */+async function conversation(engine: BrainEngine, slug: string, facts: string[], root?: string, sourceId = 'default'): Promise<number[]> {+ const page = await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Alice: I will send the deck on Friday.\nBob: Thanks.' }, { sourceId });+ if (root) {+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${slug}.md`, page.id]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ mkdirSync(dirname(join(root, `${slug}.md`)), { recursive: true });+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+ }+ const ids: number[] = [];+ for (const [i, fact] of facts.entries()) {+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session,+ row_num, source_markdown_slug) VALUES ($1, $2, $3, 'commitment', 'private', $4, 'sess', $5, $6) RETURNING id`, [sourceId, ENTITY, fact, EXTRACTOR, i + 1, slug]);+ ids.push(Number(row.id));+ }+ return ids;+}++async function factState(engine: BrainEngine, ids: number[]) {+ return engine.executeRaw<{ id: number; active: boolean; row_num: number | null }>(+ 'SELECT id::int AS id, expired_at IS NULL AS active, row_num FROM facts WHERE id=ANY($1::bigint[]) ORDER BY id', [ids]);+}+const activeIds = async (engine: BrainEngine, ids: number[]) => (await factState(engine, ids)).filter(row => row.active).map(row => row.id);++describe('extractor-facts is CLI-only (ENG-O13)', () => {+ test('no operation exposes it over MCP', () => {+ expect(operations.map(op => op.name).filter(name => /repair|extractor/.test(name))).toEqual([]);+ });+});++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-extractor-facts-'));+ afterAll(() => rmSync(home, { recursive: true, force: true }));++ /** A real managed write of the page, then the pre-fix projection's effect on its extractor facts. */+ async function prefixExpire(engine: BrainEngine, ctx: OperationContext, slug: string,+ opts: { transaction?: 'same' | 'separate'; consumer?: string | null; ids?: number[] } = {}): Promise<string> {+ const receipt = await submitPageMutation(ctx, { operation: 'add_timeline_entry',+ params: { request_id: randomUUID(), slug, date: '2026-03-01', summary: `note ${randomUUID().slice(0, 8)}`, source: 'operator' } }) as { request_id: string };+ const [row] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [receipt.request_id]);+ const expire = (tx: BrainEngine) => tx.executeRaw(`UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id='default'+ AND source_markdown_slug=$1 AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL ${opts.ids ? 'AND id=ANY($2::bigint[])' : ''}`,+ opts.ids ? [slug, opts.ids] : [slug]);+ const complete = async (tx: BrainEngine) => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw('UPDATE persistence_requests SET completed_at=now(), consumer_version=$2 WHERE id=$1::uuid', [row.id, opts.consumer === undefined ? null : opts.consumer]);+ };+ if ((opts.transaction ?? 'same') === 'same') {+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => { await complete(tx); await expire(tx); }));+ } else {+ await engine.transaction(tx => complete(tx));+ // PGLite's now() has millisecond resolution: a later transaction is at least one tick later.+ await new Promise(resolve => setTimeout(resolve, 5));+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => expire(tx)));+ }+ return row.id;+ }++ describe(`gbrain repair extractor-facts, managed (${backend})`, () => {+ test('the fix holds: a managed write to a conversation page leaves its extractor facts active', async () => {+ let ids: number[] = [];+ await managedBrain(async ({ engine, ctx }) => {+ await submitPageMutation(ctx, { operation: 'add_timeline_entry',+ params: { request_id: randomUUID(), slug: 'conversations/fixed', date: '2026-03-01', summary: 'after the fix', source: 'operator' } });+ expect(await activeIds(engine, ids)).toEqual(ids);+ expect((await repair(engine, null, [])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 0 });+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/fixed', ['Alice sends the deck'], root); } });+ }, 120_000);++ test('retained, compacted and ambiguous histories: preview, hash-bound apply, recall, then --include-ambiguous', async () => {+ const seeded: Record<string, number[]> = {};+ await managedBrain(async ({ engine, ctx }) => {+ const [retainedA, retainedB, superseded, withdrawn, duplicated] = seeded.retained;+ // An active copy of one claim and a withdrawal of another, then one pre-fix publication expires the page.+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)+ VALUES ('default', $1, 'Alice sends the deck on Friday', 'commitment', 'private', $2, 9, 'conversations/retained')`, [ENTITY, EXTRACTOR]);+ await tx.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint('Alice withdrew this claim'))");+ }));+ await prefixExpire(engine, ctx, 'conversations/retained', { ids: [retainedA, retainedB, superseded, withdrawn, duplicated] });+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [retainedA, superseded])));+ const compacted = await prefixExpire(engine, ctx, 'conversations/compacted');+ // Older than the 30-day receipt retention, so compaction drops its intent but keeps its completion.+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=$1::uuid", [compacted]);+ await tx.executeRaw("UPDATE persistence_requests SET completed_at=completed_at-interval '40 days' WHERE id=$1::uuid", [compacted]);+ });+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw("UPDATE facts SET expired_at=expired_at-interval '40 days' WHERE source_markdown_slug='conversations/compacted'")));+ expect(await compactWriteReceipts(engine, 30)).toBeGreaterThanOrEqual(1);+ expect((await engine.executeRaw<{ compacted: boolean }>('SELECT compacted FROM persistence_requests WHERE id=$1::uuid', [compacted]))[0].compacted).toBe(true);+ await prefixExpire(engine, ctx, 'conversations/separate', { transaction: 'separate' });+ await prefixExpire(engine, ctx, 'conversations/post-fix', { consumer: VERSION });+ await prefixExpire(engine, ctx, 'conversations/fenced');++ const preview = await repair(engine, null, []);+ const classes = Object.fromEntries(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.class]));+ expect(classes).toEqual({+ [retainedA]: 'evidenced', [retainedB]: 'evidenced', [superseded]: 'excluded:superseded', [withdrawn]: 'excluded:withdrawn',+ [duplicated]: 'excluded:active_duplicate', [seeded.compacted[0]]: 'evidenced',+ [seeded.separate[0]]: 'ambiguous', [seeded['post-fix'][0]]: 'ambiguous', [seeded.fenced[0]]: 'ambiguous',+ });+ const details = Object.fromEntries(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.detail]));+ expect(details[seeded.separate[0]]).toContain('no committed write of the page completed at the exact expiry instant');+ expect(details[seeded['post-fix'][0]]).toContain('fixed consumer');+ expect(details[seeded.fenced[0]]).toContain('fence facts');+ expect(details[retainedA]).toContain('unstamped');+ expect(preview.results[0].residuals).toEqual({ evidenced: 3, ambiguous: 3, excluded: 3 });+ expect(preview.results[0].affected).toBe(2);+ const hash = hashOf(preview);+ expect(preview.results[0].apply_command).toBe(`gbrain repair extractor-facts --apply --expect ${hash}`);+ const everything = Object.values(seeded).flat();+ const activeBefore = await activeIds(engine, everything);++ const unbound = await refusal(() => repair(engine, null, ['--apply']));+ expect(unbound.toJSON()).toMatchObject({ error: 'invalid_params', docs: 'docs/guides/repair.md#explicit-only-repair-kinds',+ suggestion: 'Preview first: gbrain repair extractor-facts — then run the apply command it prints: gbrain repair extractor-facts --apply --expect <preview-hash>' });+ const stale = await refusal(() => repair(engine, null, ['--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 extractor-facts and use the new hash.` });+ expect(await activeIds(engine, everything)).toEqual(activeBefore);++ const applied = await repair(engine, null, ['--apply', '--expect', hash]);+ expect(applied.results[0]).toMatchObject({ applied: 2, skipped: 0, outcomes: { restored: 2 } });+ const restored = [retainedA, retainedB, seeded.compacted[0]];+ expect(await activeIds(engine, everything)).toEqual([...activeBefore, ...restored].sort((a, b) => a - b));+ // Per-history counts (CEO-A9 completion criteria): restored, ambiguous (left for --include-ambiguous), excluded, unresolved.+ const activeNow = new Set(await activeIds(engine, everything));+ const report = Object.fromEntries(Object.entries(seeded).map(([history, ids]) => {+ const mine = ids.filter(id => classes[id] !== undefined);+ const restoredHere = mine.filter(id => activeNow.has(id)).length;+ return [history, { restored: restoredHere, ambiguous: mine.filter(id => classes[id] === 'ambiguous').length,+ excluded: mine.filter(id => classes[id].startsWith('excluded')).length,+ unresolved: mine.filter(id => classes[id] === 'evidenced' && !activeNow.has(id)).length }];+ }));+ expect(report).toEqual({+ retained: { restored: 2, ambiguous: 0, excluded: 3, unresolved: 0 },+ compacted: { restored: 1, ambiguous: 0, excluded: 0, unresolved: 0 },+ separate: { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },+ 'post-fix': { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },+ fenced: { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },+ });+ const rows = await factState(engine, [retainedA, retainedB]);+ expect(rows.map(row => row.row_num)).toEqual([10, 11]);+ const requests = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent->>'kind'=$1 AND state='committed'", [EXTRACTOR_FACTS_INTENT]);+ expect(requests[0].n).toBe(2);+ const recall = operations.find(op => op.name === 'recall')!;+ const recalled = await recall.handler({ ...ctx, remote: false }, { entity: ENTITY }) as { facts: Array<{ fact_id: string }> };+ for (const id of restored) expect(recalled.facts.map(fact => Number(fact.fact_id))).toContain(id);+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair-approval' AND fingerprint=$1", [`extractor-facts:${hash}`])).toEqual([]);++ const wide = await repair(engine, null, ['--include-ambiguous']);+ expect(wide.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 3, excluded: 3 });+ const wideHash = hashOf(wide);+ expect(wide.results[0].apply_command).toBe(`gbrain repair extractor-facts --include-ambiguous --apply --expect ${wideHash}`);+ expect((await refusal(() => repair(engine, null, ['--apply', '--expect', wideHash]))).code).toBe('preview_changed');+ const wideApplied = await repair(engine, null, ['--include-ambiguous', '--apply', '--expect', wideHash]);+ expect(wideApplied.results[0].outcomes).toEqual({ restored: 3 });+ expect(await activeIds(engine, [superseded, withdrawn])).toEqual([]);+ const after = await repair(engine, null, []);+ expect(after.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 3 });+ }, { databaseUrl, setup: async ({ engine, root }) => {+ seeded.retained = await conversation(engine, 'conversations/retained', ['Alice sends the deck', 'Alice books the venue',+ 'Alice hires a designer', 'Alice withdrew this claim', 'Alice sends the deck on Friday'], root);+ seeded.compacted = await conversation(engine, 'conversations/compacted', ['Alice reviews the budget'], root);+ seeded.separate = await conversation(engine, 'conversations/separate', ['Alice calls the bank'], root);+ seeded['post-fix'] = await conversation(engine, 'conversations/post-fix', ['Alice drafts the memo'], root);+ seeded.fenced = await conversation(engine, 'conversations/fenced', ['Alice signs the lease'], root);+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug, expired_at)+ VALUES ('default', 'conversations/fenced', 'A fence row on this page', 'fact', 'private', 'fence', 7, 'conversations/fenced', now())`);+ } });+ }, 180_000);++ test('a fact edited between preview and apply reports changed_since_preview and stays expired; the rest restore', async () => {+ let ids: number[] = [];+ await managedBrain(async ({ engine, ctx }) => {+ await prefixExpire(engine, ctx, 'conversations/edited');+ const preview = await repair(engine, null, []);+ expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 0, excluded: 0 });+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw("UPDATE facts SET fact='Alice sends the revised deck' WHERE id=$1", [ids[1]])));+ const applied = await repair(engine, null, ['--apply', '--expect', hashOf(preview)]);+ expect(applied.results[0]).toMatchObject({ applied: 1, outcomes: { partially_restored: 1 } });+ expect(applied.results[0].outcome_items![0].reason).toBe(`1 of 2 restored; changed since the preview: ${ids[1]}`);+ expect(await activeIds(engine, ids)).toEqual([ids[0]]);+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/edited', ['Alice sends the deck', 'Alice books the venue'], root); } });+ }, 120_000);++ test('crash after a publication, before the cursor: the resumed apply replays its receipt and restores no new candidate (ENG-O8)', async () => {+ const seeded: Record<string, number[]> = {};+ await managedBrain(async ({ engine, ctx }) => {+ await prefixExpire(engine, ctx, 'conversations/a', { ids: [seeded.a[0]] });+ await prefixExpire(engine, ctx, 'conversations/b');+ const preview = await repair(engine, null, []);+ const hash = hashOf(preview);+ expect(preview.results[0].affected).toBe(2);+ const original = extractorFactsRepair.apply;+ extractorFactsRepair.apply = async (...args) => { await original(...args); throw new Error('simulated crash after publication'); };+ try { await expect(repair(engine, null, ['--apply', '--expect', hash])).rejects.toThrow('simulated crash after publication'); }+ finally { extractorFactsRepair.apply = original; }+ expect(await activeIds(engine, [...seeded.a, ...seeded.b])).toEqual(seeded.a);+ // A new defect-evidenced candidate appears on the half-applied page after the preview.+ await prefixExpire(engine, ctx, 'conversations/a', { ids: [seeded.a[1]] });+ const resumed = await repair(engine, null, ['--apply', '--expect', hash]);+ expect(resumed.results[0]).toMatchObject({ affected: 1, applied: 1, residuals: { already_restored_pages: 1 }, outcomes: { restored: 1 } });+ expect(await activeIds(engine, [...seeded.a, ...seeded.b])).toEqual([seeded.a[0], ...seeded.b]);+ const requests = await engine.executeRaw<{ slug: string; n: number }>(`SELECT slug, count(*)::int AS n FROM persistence_requests+ WHERE intent->>'kind'=$1 AND state='committed' GROUP BY slug ORDER BY slug`, [EXTRACTOR_FACTS_INTENT]);+ expect(requests).toEqual([{ slug: 'conversations/a', n: 1 }, { slug: 'conversations/b', n: 1 }]);+ expect((await refusal(() => repair(engine, null, ['--apply', '--expect', hash]))).code).toBe('preview_changed');+ expect((await repair(engine, null, [])).results[0].residuals).toEqual({ evidenced: 1, ambiguous: 0, excluded: 0 });+ }, { databaseUrl, setup: async ({ engine, root }) => {+ seeded.a = await conversation(engine, 'conversations/a', ['Alice sends the deck', 'Alice books the venue'], root);+ seeded.b = await conversation(engine, 'conversations/b', ['Bob reviews the budget'], root);+ } });+ }, 120_000);++ test('the preview warns, naming the host, when a consumer older than this release published after the cutoff', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ const request = await prefixExpire(engine, ctx, 'conversations/mixed');+ // The host upgraded after the pre-fix write: writer-version observation starts here.+ await new Promise(resolve => setTimeout(resolve, 5));+ await engine.executeRaw('UPDATE persistence_brain SET writer_version_cutoff=now() WHERE singleton=1');+ const quiet = await repair(engine, null, []);+ expect(quiet.results[0].warnings ?? []).toEqual([]);+ const host = randomUUID();+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ // A host still running v0.60.10.0 publishes after the upgrade cutoff.+ await tx.executeRaw(`UPDATE persistence_requests SET consumer_version='0.60.10.0', consumer_host_id=$2::uuid, published_at=now()+ WHERE id=$1::uuid`, [request, host]);+ });+ const warned = await repair(engine, null, []);+ expect(warned.results[0].warnings).toEqual([expect.stringContaining(`host ${host} still published writes with a consumer older than this release (0.60.10.0`)]);+ }, { databaseUrl, setup: async ({ engine, root }) => { await conversation(engine, 'conversations/mixed', ['Alice sends the deck'], root); } });+ }, 120_000);++ test('recovery journey: doctor, preview, apply, doctor, running the printed commands verbatim (DX-O15d)', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await prefixExpire(engine, ctx, 'conversations/journey');+ const before = await extractorFactsCheck(engine);+ expect(before).toMatchObject({ name: 'extractor_facts_expired', status: 'warn', details: { evidenced: 3, ambiguous: 0 } });+ const printed = before.message.match(/gbrain repair extractor-facts(?= )/)![0];+ const preview = await repair(engine, null, printed.split(' ').slice(3));+ const applied = await repair(engine, null, preview.results[0].apply_command.split(' ').slice(3));+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });+ expect(await extractorFactsCheck(engine)).toMatchObject({ status: 'ok', details: { evidenced: 0, ambiguous: 0 } });+ }, { databaseUrl, setup: async ({ engine, root }) => {+ await conversation(engine, 'conversations/journey', ['Alice sends the deck', 'Alice books the venue', 'Alice hires a designer'], root);+ } });+ }, 120_000);+ });++ describe(`gbrain repair extractor-facts, unmanaged (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!));+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ test('every candidate is ambiguous; only --include-ambiguous with its own hash restores them', async () => {+ const sourceId = `ef-u-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const ids = await conversation(engine, 'conversations/unmanaged', ['Alice sends the deck', 'Alice books the venue'], undefined, sourceId);+ const superseded = (await conversation(engine, 'conversations/unmanaged-2', ['Alice hires a designer'], undefined, sourceId))[0];+ await engine.executeRaw("UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id=$1", [sourceId]);+ await engine.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [ids[0], superseded]);+ const preview = await repair(engine, home, ['--source', sourceId]);+ expect(preview.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 2, excluded: 1 });+ expect(preview.results[0].affected).toBe(0);+ expect(preview.results[0].listing!.map(entry => entry.detail)).toContain('unmanaged brain: no write receipt can prove the expiry');+ expect((await refusal(() => repair(engine, home, ['--source', sourceId, '--apply', '--expect', hashOf(preview)]))).code).toBe('preview_changed');+ const wide = await repair(engine, home, ['--source', sourceId, '--include-ambiguous']);+ expect(wide.results[0].affected).toBe(1);+ const applied = await repair(engine, home, ['--source', sourceId, '--include-ambiguous', '--apply', '--expect', hashOf(wide)]);+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });+ expect(await factState(engine, [...ids, superseded])).toEqual([+ { id: ids[0], active: true, row_num: 1 }, { id: ids[1], active: true, row_num: 2 }, { id: superseded, active: false, row_num: null }]);+ expect((await repair(engine, home, ['--source', sourceId])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 1 });+ }, 60_000);+ });+}