Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): captured-facts repair and captured_facts_active doctor check

garrytan0ada8e7827c9
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 1b5debf2f2..e4dfa9b49a 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -10,6 +10,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set), origins (`mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`, and the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
- `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.md
index 6031af254a..94c1b409dc 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -6,6 +6,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. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `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`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `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/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows in one (coordinated, owner-checked on a managed brain) transaction, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.
diff --git a/src/commands/doctor/checks/captured-facts.ts b/src/commands/doctor/checks/captured-facts.ts
new file mode 100644
index 0000000000..d03a1c1880
--- /dev/null
+++ b/src/commands/doctor/checks/captured-facts.ts
@@ -0,0 +1,34 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { classifyCapturedFacts } from '../../../core/repair/captured-facts.ts';
+
+/**
+ * `captured_facts_active`: active facts the capture lanes extracted from
+ * gbrain's own claude-cli sessions (evidenced) or, by heuristic, from pasted
+ * text (ambiguous), before v0.60.30.0 stopped both. Counts them and names the
+ * explicit-only `gbrain repair captured-facts` preview. It reports facts in
+ * the database; the `self_capture` check reports corpus files. Read-only;
+ * reads the brain host's harness transcripts and session corpus.
+ */
+export async function capturedFactsCheck(engine: BrainEngine, sourceIds?: string[], opts: { projectsRoot?: string; corpusDir?: string | null } = {}): Promise<Check> {
+ const name = 'captured_facts_active';
+ 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 { candidates, unclassifiable } = await classifyCapturedFacts(engine, sources, opts);
+ const count = (klass: string) => candidates.filter(c => c.class === klass).length;
+ const details = { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'), unclassifiable,
+ repair: 'captured-facts', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' };
+ const differs = 'This counts facts in the database; the self_capture check counts corpus files.';
+ if (!details.evidenced && !details.ambiguous) {
+ return { name, status: 'ok', details, message: `No active fact from a gbrain self-capture or paste candidate remains. ${differs}` };
+ }
+ return { name, status: 'warn', details,
+ message: `${details.evidenced + details.ambiguous} active fact(s) were captured before v0.60.30.0 from gbrain's own claude-cli sessions `
+ + `(${details.evidenced} with evidence) or from pasted text (${details.ambiguous} paste candidate(s), heuristic); recall still returns them. ${differs} `
+ + 'Preview the cleanup on the brain host: gbrain repair captured-facts — then run the apply command it prints after the user agrees '
+ + '(paste candidates only with gbrain repair captured-facts --include-ambiguous).' };
+ } catch (error) {
+ return { name, status: 'warn', message: `Captured facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { count: 'unknown' } };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 461e66de21..a126e6dbfc 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -282,6 +282,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'stale_embedding_effects',
'google_file_modes',
'extractor_facts_expired',
+ 'captured_facts_active',
],
run: runTimelineHistory,
};
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 9812aef570..845856b880 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -183,6 +183,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some conversation-extractor facts were expired by the pre-v0.60.11.0 canonical projection and recall no longer returns them',
run: async (engine, scope) => (await import('./checks/extractor-facts.ts')).extractorFactsCheck(engine, scope.sourceIds),
},
+ {
+ id: 'captured_facts_active', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Classifying captured facts reads harness transcripts and the session corpus on the brain host; the repair is explicit-only.',
+ count: d => Number(d.evidenced ?? 0) + Number(d.ambiguous ?? 0),
+ impact: 'Some active facts were captured from gbrain\'s own model sessions or from pasted text before v0.60.30.0',
+ run: async (engine, scope) => (await import('./checks/captured-facts.ts')).capturedFactsCheck(engine, scope.sourceIds),
+ },
];
/** A check that could not run reports unknown, never ok. */
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 331e55f8ba..90aa4e3a18 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -57,6 +57,7 @@ export type CheckCategory = 'brain' | 'skill' | 'ops' | 'meta';
export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'abandoned_threads',
'atom_provenance_drift',
+ 'captured_facts_active',
'connector_checkpoints',
'connector_held_items',
'credential_projection_pending',
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 582278a2e2..0aee5673f3 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.ts
new file mode 100644
index 0000000000..95f3cdc4c9
--- /dev/null
+++ b/src/core/repair/captured-facts.ts
@@ -0,0 +1,338 @@
+/**
+ * `gbrain repair captured-facts`: expire facts that the capture lanes
+ * (`hook:writeback`, `hook:compact`, `sweep:corpus`) extracted, before
+ * v0.60.30.0, from gbrain's own claude-cli sessions (#5413, #5820) or from
+ * pasted text (#5812). Those releases stopped new extraction; this kind
+ * cleans up the facts already stored.
+ *
+ * Candidates are active capture-lane facts of the scoped sources. Each is
+ * classified from its session (`source_session`; corpus rows carry
+ * `sweep:corpus:<file>`, resolved with `corpusFileSessionId`):
+ * - evidenced (self-capture): the session id names a harness transcript
+ * under a gbrain claude-cli scratch project, or its corpus file sits in
+ * doctor's `<corpus>.quarantine/` directory.
+ * - ambiguous (paste candidate): a still-retained corpus file of the session
+ * holds a paste block, and at least 60% of the fact's content words occur
+ * in that file only inside paste blocks (not in the session's own text).
+ * Heuristic: listed in every preview, expired only with
+ * `--include-ambiguous` and the hash of that preview.
+ * - excluded: an evidenced or ambiguous row whose claim and entity also have
+ * an active row that is not suspect (another lane, or a capture row from a
+ * session that is neither); the self-capture prompts ran over real pages,
+ * so such a claim is legitimate and is kept.
+ * Rows of sessions that cannot be classified on this host (harness transcript
+ * pruned, corpus file gone) are counted as `unclassifiable`, never expired.
+ *
+ * The apply expires rows; it never records a withdrawal, so a later
+ * `remember` of the same claim is not blocked. A fenced row (`row_num` on its
+ * entity page) is struck in the page's `## Facts` fence by one revision-bound
+ * `put_page` per page, so the canonical projection expires it and a later
+ * write of the page cannot reactivate it; a row with no fence row is expired
+ * in a coordinated database write. Each fact is rechecked before it is
+ * touched; a fact that changed since the preview is reported as
+ * `changed_since_preview` and kept.
+ */
+import { existsSync, readdirSync, readFileSync, type Dirent } from 'node:fs';
+import { basename, dirname, join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { parseFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { strikeFenceRow } from '../facts/forget.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { digest } from '../persistence/digest.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';
+import { claudeProjectsDir } from '../bootstrap/host-specs.ts';
+import { corpusFileSessionId, corpusTextForExtraction } from '../context/corpus-segments.ts';
+import { pruneDir } from '../sync.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+export const CAPTURE_LANES = ['hook:writeback', 'hook:compact', 'sweep:corpus'] as const;
+const CORPUS_KEY = 'dream.synthesize.session_corpus_dir';
+const PASTE_SHARE = 0.6;
+const EXPIRY_CONTEXT = 'expired: captured-facts repair';
+
+export type CapturedFactClass = 'evidenced' | 'ambiguous' | 'excluded';
+
+export interface CapturedFactCandidate {
+ id: number;
+ source_id: string;
+ /** The page the fact lives on (fenced rows) or its entity key (database-only rows). */
+ slug: string;
+ row_num: number | null;
+ class: CapturedFactClass;
+ /** `self_capture_transcript`, `self_capture_quarantined`, `paste_heuristic`, or `excluded:legitimate_duplicate`. */
+ reason: string;
+ session: string;
+ evidence: string;
+ /** Digest of the row's claim, visibility, entity and fence position, so an edited row is not expired. */
+ fact_hash: string;
+}
+
+export interface CapturedFactsClassification {
+ candidates: CapturedFactCandidate[];
+ unclassifiable: number;
+ not_suspect: number;
+}
+
+export interface CapturedFactsPage {
+ source_id: string;
+ slug: string;
+ include_ambiguous: boolean;
+ scope: string[];
+ facts: CapturedFactCandidate[];
+}
+
+interface PageItem extends RepairItem { page: CapturedFactsPage; hash: string; last: boolean }
+
+interface FactRow {
+ id: number | string; source_id: string; source: string; source_session: string | null; fact: string; visibility: string;
+ entity_slug: string | null; row_num: number | null; source_markdown_slug: string | null; fingerprint: string; legit_twin: boolean;
+}
+
+export interface ClassifyOptions { projectsRoot?: string; corpusDir?: string | null; ids?: number[] }
+
+const STOPWORDS = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'are', 'was', 'were', 'has', 'have', 'had', 'not', 'but', 'his', 'her',
+ 'their', 'they', 'them', 'its', 'our', 'you', 'your', 'who', 'what', 'when', 'which', 'will', 'would', 'should', 'can', 'could', 'into', 'about']);
+
+function words(text: string): Set<string> {
+ return new Set((text.toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) ?? []).filter(w => !STOPWORDS.has(w)));
+}
+
+/** Every `.txt` under `root` (dream discovery's pruning), keyed by its session id. */
+function sessionFiles(root: string | null | undefined): Map<string, string[]> {
+ const bySession = new Map<string, string[]>();
+ if (!root || !existsSync(root)) return bySession;
+ const walk = (dir: string) => {
+ let entries: Dirent[];
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) { if (pruneDir(entry.name, dir)) walk(full); }
+ else if (entry.isFile() && entry.name.endsWith('.txt')) {
+ const session = corpusFileSessionId(entry.name);
+ bySession.set(session, [...(bySession.get(session) ?? []), full]);
+ }
+ }
+ };
+ walk(root);
+ return bySession;
+}
+
+function harnessSessionIds(projectsRoot: string): Set<string> {
+ const ids = new Set<string>();
+ let projects: string[];
+ try { projects = readdirSync(projectsRoot); } catch { return ids; }
+ for (const project of projects) {
+ let files: string[];
+ try { files = readdirSync(join(projectsRoot, project)); } catch { continue; }
+ for (const file of files) if (file.endsWith('.jsonl')) ids.add(file.slice(0, -'.jsonl'.length));
+ }
+ return ids;
+}
+
+/** The capture session a fact row came from (`sweep:corpus:<file>` names the corpus file). */
+export function captureSessionId(sourceSession: string | null): string | null {
+ if (!sourceSession) return null;
+ return sourceSession.startsWith('sweep:corpus:') ? corpusFileSessionId(basename(sourceSession.slice('sweep:corpus:'.length))) : sourceSession;
+}
+
+const factHash = (row: FactRow) => digest(['captured-fact-v1', row.fact, row.visibility, row.entity_slug, row.row_num, row.source_markdown_slug]);
+const targetSlug = (row: Pick<FactRow, 'row_num' | 'source_markdown_slug' | 'entity_slug'>) =>
+ row.row_num !== null && row.source_markdown_slug ? row.source_markdown_slug : row.source_markdown_slug ?? row.entity_slug ?? 'memory/unattributed';
+
+/** Read-only: every suspect capture-lane fact of these sources, classified, in (source, page, id) order. */
+export async function classifyCapturedFacts(db: BrainEngine, sourceIds: string[], opts: ClassifyOptions = {}): Promise<CapturedFactsClassification> {
+ const rows = await db.executeRaw<FactRow>(`
+ SELECT f.id, f.source_id, f.source, f.source_session, f.fact, f.visibility, f.entity_slug, f.row_num, f.source_markdown_slug,
+ gbrain_fact_fingerprint(f.fact) AS fingerprint,
+ EXISTS (SELECT 1 FROM facts a WHERE a.source_id=f.source_id AND a.id<>f.id AND a.expired_at IS NULL
+ AND a.visibility=f.visibility AND a.entity_slug IS NOT DISTINCT FROM f.entity_slug
+ AND gbrain_fact_fingerprint(a.fact)=gbrain_fact_fingerprint(f.fact)
+ AND COALESCE(a.source,'') <> ALL($2::text[])) AS legit_twin
+ FROM facts f
+ WHERE f.source_id=ANY($1::text[]) AND f.source=ANY($2::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL
+ AND ($3::bigint[] IS NULL OR f.id=ANY($3::bigint[]))
+ ORDER BY f.source_id, f.id`, [sourceIds, [...CAPTURE_LANES], opts.ids ?? null]);
+ if (!rows.length) return { candidates: [], unclassifiable: 0, not_suspect: 0 };
+ const projectsRoot = opts.projectsRoot ?? claudeProjectsDir();
+ const selfDirs = claudeCliSelfProjectDirs(projectsRoot);
+ const known = harnessSessionIds(projectsRoot);
+ const corpusDir = opts.corpusDir === undefined ? await db.getConfig(CORPUS_KEY) : opts.corpusDir;
+ const corpus = sessionFiles(corpusDir);
+ const quarantine = sessionFiles(corpusDir ? join(dirname(corpusDir), `${basename(corpusDir)}.quarantine`) : null);
+ const pasteWords = new Map<string, { file: string; paste: Set<string> } | null>();
+ const pasteOnlyWords = (session: string) => {
+ if (pasteWords.has(session)) return pasteWords.get(session)!;
+ let found: { file: string; paste: Set<string> } | null = null;
+ for (const file of corpus.get(session) ?? []) {
+ let raw: string;
+ try { raw = readFileSync(file, 'utf8'); } catch { continue; }
+ if (!raw.includes('<pasted_content')) continue;
+ const own = words(corpusTextForExtraction(file, raw));
+ const paste = new Set([...words(raw)].filter(w => !own.has(w)));
+ found = found ? { file: found.file, paste: new Set([...found.paste, ...paste]) } : { file, paste };
+ }
+ pasteWords.set(session, found);
+ return found;
+ };
+
+ type Hit = { klass: 'evidenced' | 'ambiguous'; reason: string; session: string; evidence: string };
+ const classified: Array<Hit | 'unclassifiable' | 'not_suspect'> = rows.map(row => {
+ const session = captureSessionId(row.source_session);
+ if (!session) return 'unclassifiable';
+ if (isClaudeCliSelfSessionId(session, selfDirs)) {
+ const dir = selfDirs.find(d => existsSync(join(d, `${session}.jsonl`)))!;
+ return { klass: 'evidenced', reason: 'self_capture_transcript', session, evidence: join(basename(dir), `${session}.jsonl`) };
+ }
+ const quarantined = quarantine.get(session);
+ if (quarantined?.length) return { klass: 'evidenced', reason: 'self_capture_quarantined', session, evidence: basename(quarantined[0]!) };
+ const paste = pasteOnlyWords(session);
+ if (paste) {
+ const claim = [...words(row.fact)];
+ const covered = claim.filter(w => paste.paste.has(w)).length;
+ if (claim.length >= 2 && covered / claim.length >= PASTE_SHARE) {
+ return { klass: 'ambiguous', reason: 'paste_heuristic', session, evidence: `${basename(paste.file)}: ${covered}/${claim.length} words only in paste blocks` };
+ }
+ }
+ return corpus.has(session) || known.has(session) ? 'not_suspect' : 'unclassifiable';
+ });
+ // A suspect claim that also has an active copy not proven suspect (another lane, or any other capture row) is kept.
+ const twinKey = (row: FactRow) => JSON.stringify([row.source_id, row.visibility, row.entity_slug, row.fingerprint]);
+ const unproven = new Set(rows.filter((_, i) => typeof classified[i] === 'string').map(twinKey));
+ const candidates: CapturedFactCandidate[] = [];
+ rows.forEach((row, i) => {
+ const hit = classified[i];
+ if (typeof hit === 'string') return;
+ const legit = row.legit_twin || unproven.has(twinKey(row));
+ candidates.push({ id: Number(row.id), source_id: row.source_id, slug: targetSlug(row), row_num: row.row_num === null ? null : Number(row.row_num),
+ class: legit ? 'excluded' : hit.klass, reason: legit ? 'excluded:legitimate_duplicate' : hit.reason, session: hit.session,
+ evidence: hit.evidence, fact_hash: factHash(row) });
+ });
+ candidates.sort((a, b) => a.source_id.localeCompare(b.source_id) || a.slug.localeCompare(b.slug) || a.id - b.id);
+ return { candidates, unclassifiable: classified.filter(c => c === 'unclassifiable').length, not_suspect: classified.filter(c => c === 'not_suspect').length };
+}
+
+function previewCommand(scope: RepairScope, all: string[], includeAmbiguous: boolean): string {
+ const source = scope.source_ids.length === 1 && all.length > 1 ? ` --source ${scope.source_ids[0]}` : '';
+ return `gbrain repair captured-facts${source}${includeAmbiguous ? ' --include-ambiguous' : ''}`;
+}
+
+async function activeSources(engine: BrainEngine): Promise<string[]> {
+ return (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+}
+
+function pageItem(page: CapturedFactsPage, hash: string, index: number, last: boolean): PageItem {
+ return { cursor: { phase: 0, id: index }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: `expire ${page.facts.length} captured fact(s)`, page, hash, last };
+}
+
+export const capturedFactsRepair: RepairHandler = {
+ kind: 'captured-facts',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeAmbiguous = opts?.includeAmbiguous === true;
+ const command = previewCommand(scope, await activeSources(engine), includeAmbiguous);
+ if (!opts?.apply) {
+ const { candidates, unclassifiable, not_suspect } = await classifyCapturedFacts(engine, scope.source_ids);
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);
+ const hash = previewHash(['captured-facts-v1', brain?.brain_id ?? 'host', scope.source_ids, includeAmbiguous,
+ candidates.map(c => [c.id, c.class, c.reason, c.fact_hash])]);
+ const pages = new Map<string, CapturedFactsPage>();
+ for (const fact of candidates) {
+ 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, 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: 'captured-facts', hash }, approved);
+ const count = (klass: CapturedFactClass) => candidates.filter(c => c.class === klass).length;
+ const listing: RepairListing[] = candidates.map(c => ({ item: `${c.source_id}:${c.slug}#${c.id}`,
+ class: c.class === 'excluded' ? c.reason : c.class, detail: `${c.reason === 'paste_heuristic' ? 'paste candidate' : c.reason}; session ${c.session}; ${c.evidence}` }));
+ return { items: approved.map((page, i) => pageItem(page, hash, i, i === approved.length - 1)), preview_hash: hash, listing,
+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'), unclassifiable, not_suspect } };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair captured-facts --apply expires 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<CapturedFactsPage>(engine, { command: 'captured-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);
+ }
+ const items = approved.items.map((page, i) => pageItem(page, opts.expect!, i, i === approved.items.length - 1))
+ .filter(item => afterCursor(item.cursor, after));
+ if (!items.length) await clearApprovedSet(engine, { command: 'captured-facts', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: { approved_pages: approved.items.length, pending_pages: items.length } };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, last } = entry as PageItem;
+ const engine = ctx.engine;
+ // Recheck each approved fact against its live row: same class, evidence and row.
+ const live = new Map((await classifyCapturedFacts(engine, [page.source_id], { ids: page.facts.map(f => f.id) })).candidates.map(c => [c.id, c]));
+ const unchanged = page.facts.filter(f => {
+ const current = live.get(f.id);
+ return !!current && (['class', 'reason', 'fact_hash', 'slug', 'row_num'] as const).every(field => current[field] === f[field]);
+ });
+ const expired: number[] = [];
+ const dbOnly = unchanged.filter(f => f.row_num === null);
+ if (dbOnly.length) expired.push(...await expireDatabaseRows(engine, page.source_id, dbOnly.map(f => f.id)));
+ const fenced = unchanged.filter(f => f.row_num !== null);
+ if (fenced.length) expired.push(...await strikeFencedRows(ctx, entry, page, fenced));
+ if (last) await clearApprovedSet(engine, { command: 'captured-facts', hash });
+ const changed = page.facts.filter(f => !expired.includes(f.id)).map(f => f.id);
+ return { applied: expired.length > 0, outcome: !changed.length ? 'expired' : expired.length ? 'partially_expired' : 'changed_since_preview',
+ ...(changed.length ? { reason: `${expired.length} of ${page.facts.length} expired; changed since the preview: ${changed.join(', ')}` } : {}) };
+ },
+};
+
+/** Database-only rows: expired with a reason in one transaction (coordinated on a managed brain, whose source needs its owner). */
+async function expireDatabaseRows(engine: BrainEngine, sourceId: string, ids: number[]): Promise<number[]> {
+ const managed = await managedPersistenceEnabled(engine);
+ if (managed) await maintenancePreflight(engine, sourceId);
+ const expire = (tx: BrainEngine) => tx.executeRaw<{ id: number | string }>(`UPDATE facts
+ SET expired_at=now(), valid_until=LEAST(COALESCE(valid_until, now()), now()), context=concat_ws(' | ', $3::text, NULLIF(context,''))
+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL AND row_num IS NULL RETURNING id`, [sourceId, ids, EXPIRY_CONTEXT]);
+ const rows = await engine.transaction(tx => managed ? withCoordinatedWrite(tx, [sourceId], () => expire(tx)) : expire(tx));
+ return rows.map(row => Number(row.id));
+}
+
+/**
+ * Fenced rows: strike each still-matching fence row (no withdrawal marker) and
+ * publish the page once, bound to the revision read; the canonical projection
+ * expires the struck rows. Returns the facts that ended expired.
+ */
+async function strikeFencedRows(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: CapturedFactsPage, facts: CapturedFactCandidate[]): Promise<number[]> {
+ const engine = ctx.engine;
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot) return [];
+ const rows = await engine.executeRaw<{ id: number | string; fact: string; row_num: number }>(
+ 'SELECT id, fact, row_num FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL', [page.source_id, facts.map(f => f.id)]);
+ const today = new Date().toISOString().slice(0, 10);
+ const strike = (fact: ParsedFact): ParsedFact => ({ ...fact, active: false, forgotten: false, validUntil: fact.validUntil && fact.validUntil < today ? fact.validUntil : today,
+ context: [EXPIRY_CONTEXT, fact.context?.trim()].filter(Boolean).join(' | ') });
+ let body = snapshot.page.compiled_truth ?? '';
+ const struck: number[] = [];
+ for (const row of rows) {
+ const fenceRow = parseFactsFence(body).facts.find(f => f.rowNum === Number(row.row_num));
+ if (!fenceRow?.active || fenceRow.claim.trim() !== row.fact.trim()) continue;
+ const next = strikeFenceRow(body, Number(row.row_num), strike);
+ if (next === null) continue;
+ body = next;
+ struck.push(Number(row.id));
+ }
+ if (!struck.length) return [];
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id,
+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'captured-facts', item, snapshot.revision) } });
+ return (await engine.executeRaw<{ id: number | string }>('SELECT id FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NOT NULL',
+ [page.source_id, struck])).map(row => Number(row.id));
+}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 79ec677b0a..5e947953d2 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';
import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 0db950fd6c..4ae3e59905 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -34,6 +34,7 @@ import { embeddingEffectsRepair } from './embedding-effects.ts';
import { googleFileModesRepair } from './google-file-modes.ts';
import { staleAtomsRepair } from './stale-atoms.ts';
import { extractorFactsRepair } from './extractor-facts.ts';
+import { capturedFactsRepair } from './captured-facts.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -115,6 +116,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ '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.',
},
+ 'captured-facts': {
+ handler: capturedFactsRepair, embeds: 'effect', checks: ['captured_facts_active'], explicit_only: true,
+ summary: 'Expire facts the capture lanes (writeback, compact, corpus sweep) extracted before v0.60.30.0 from gbrain\'s own claude-cli sessions '
+ + '(evidence: a scratch-project harness transcript or a quarantined corpus file). Paste-derived facts are found by a heuristic over the retained '
+ + 'corpus file and expire only with --include-ambiguous. A claim that also has an active copy from another lane is kept. Preview-bound: --apply '
+ + '--expect <hash> expires exactly the previewed set; a fact that changed since reports changed_since_preview. Rows are expired, never withdrawn, '
+ + 'so remember can save the same claim again; fenced rows are struck in their page, which is re-embedded by its publication.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/test/e2e/repair-captured-facts-postgres.test.ts b/test/e2e/repair-captured-facts-postgres.test.ts
new file mode 100644
index 0000000000..3c1023353e
--- /dev/null
+++ b/test/e2e/repair-captured-facts-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-captured-facts.test.ts'));
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 6552fe9a2b..c763506ed3 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -191,7 +191,8 @@ for (const backend of testBackends()) {
const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;
const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
- const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts' };
+ const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
+ 'captured-facts': 'gbrain repair captured-facts' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 060c614c93..c1c7808556 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -720,6 +720,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "captured-facts",
+ "unclassifiable": 0
+ },
+ "message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",
+ "name": "captured_facts_active",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 43c6ad0cad..85416ba416 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -720,6 +720,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "captured-facts",
+ "unclassifiable": 0
+ },
+ "message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",
+ "name": "captured_facts_active",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index b40fae8128..b18cc57d25 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -389,6 +389,10 @@
"category": "brain",
"name": "extractor_facts_expired"
},
+ {
+ "category": "brain",
+ "name": "captured_facts_active"
+ },
{
"category": "brain",
"name": "integrity"
diff --git a/test/repair-captured-facts.test.ts b/test/repair-captured-facts.test.ts
new file mode 100644
index 0000000000..288bf338b6
--- /dev/null
+++ b/test/repair-captured-facts.test.ts
@@ -0,0 +1,192 @@
+/**
+ * `gbrain repair captured-facts` and doctor `captured_facts_active`, on PGLite
+ * and, with a safe DATABASE_URL, Postgres (test/e2e/repair-captured-facts-postgres.test.ts).
+ *
+ * Protects: capture-lane facts from gbrain's own claude-cli sessions are
+ * expired by a hash-bound apply (fenced rows struck in their page so a later
+ * write cannot reactivate them); paste candidates are listed but kept unless
+ * --include-ambiguous; a claim with a legitimate active copy, a normal
+ * session's fact and an unclassifiable session's fact are kept; nothing is
+ * withdrawn, so remember can save the same claim again; the finding clears.
+ * Seams: harness transcripts and the session corpus are files under a temp
+ * CLAUDE_CONFIG_DIR and corpus dir; the legitimate copy is a raw coordinated
+ * insert (the managed writer dedups a same-entity duplicate).
+ */
+import { afterAll, 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 { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { capturedFactsCheck } from '../src/commands/doctor/checks/captured-facts.ts';
+import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.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 ALICE = 'people/alice-example';
+const ACME = 'companies/acme-example';
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
+ listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number> }> }
+
+/** Harness transcripts (one gbrain scratch project, one normal project) and a session corpus with a paste. */
+function hostFiles(base: string) {
+ const claude = join(base, 'claude');
+ const scratch = join(claude, 'projects', '-tmp-gbrain-claude-cli-cwd-4242');
+ const normal = join(claude, 'projects', '-home-user-work');
+ mkdirSync(scratch, { recursive: true }); mkdirSync(normal, { recursive: true });
+ writeFileSync(join(scratch, 'sess-self.jsonl'), '{}\n');
+ writeFileSync(join(normal, 'sess-normal.jsonl'), '{}\n');
+ writeFileSync(join(normal, 'sess-paste.jsonl'), '{}\n');
+ const corpus = join(base, 'corpus');
+ mkdirSync(corpus, { recursive: true });
+ writeFileSync(join(corpus, 'sess-paste.txt'), '[user]\nCan you summarize this email?\n<pasted_content id="7">\n'
+ + 'Acme Example raised a Series B round led by Fund Alpha at a forty million valuation.\n</pasted_content id="7">\n\n[assistant]\nSure.');
+ writeFileSync(join(corpus, 'sess-normal.txt'), '[user]\nAlice joined Acme in 2024.\n\n[assistant]\nNoted.');
+ return { claude, corpus };
+}
+
+async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, ['captured-facts', ...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+}
+const applyArgs = (json: RepairJson) => json.results[0].apply_command.split(' ').slice(3);
+
+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');
+}
+
+const active = async (engine: BrainEngine, id: number) =>
+ (await engine.executeRaw<{ active: boolean }>('SELECT expired_at IS NULL AS active FROM facts WHERE id=$1', [id]))[0]?.active;
+
+async function seedEntity(engine: BrainEngine, root: string, slug: string, title: string, type: string) {
+ const page = await engine.putPage(slug, { type: type as 'person', title, compiled_truth: `# ${title}` }, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${slug}.md`, page.id]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ mkdirSync(join(root, slug.split('/')[0]!), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const base = mkdtempSync(join(tmpdir(), 'gbrain-captured-facts-'));
+ afterAll(() => rmSync(base, { recursive: true, force: true }));
+ const { claude, corpus } = hostFiles(base);
+
+ describe(`gbrain repair captured-facts, managed (${backend})`, () => {
+ test('doctor finding, preview, hash-bound apply, paste kept until --include-ambiguous, remember still works', async () => {
+ await withEnv({ CLAUDE_CONFIG_DIR: claude }, () => managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);
+ const write = (fact: string, entity: string | null, provenance: string, sessionId: string) =>
+ writeSingleFact(engine, 'default', { fact, entity, provenance, sessionId }).then(r => r.id);
+ const self = await write('Alice Example prefers Rust for systems work', ALICE, 'hook:writeback', 'sess-self');
+ const selfCompact = await write('Acme Example ships quarterly', ACME, 'hook:compact', 'sess-self');
+ const paste = await write('Acme Example raised a Series B round led by Fund Alpha', ACME, 'sweep:corpus', 'sweep:corpus:sess-paste.txt');
+ const pasteOwn = await write('Acme Example wants a summary of an email', ACME, 'sweep:corpus', 'sweep:corpus:sess-paste.txt');
+ const twinned = await write('Alice Example lives in Lisbon', ALICE, 'hook:writeback', 'sess-self');
+ const normal = await write('Alice Example joined Acme Example in 2024', ALICE, 'hook:writeback', 'sess-normal');
+ const gone = await write('Alice Example likes long walks', ALICE, 'hook:writeback', 'sess-gone');
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source)
+ VALUES ('default', $1, 'Alice Example lives in Lisbon', 'fact', 'private', 'cli:remember')`, [ALICE])));
+
+ const finding = await capturedFactsCheck(engine);
+ expect(finding.status).toBe('warn');
+ expect(finding.details).toMatchObject({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1 });
+ expect(finding.message).toContain('gbrain repair captured-facts');
+ expect(finding.message).toContain('the self_capture check counts corpus files');
+ const wave = (await runWaveChecks(engine, { only: 'wave' })).find(f => f.spec.id === 'captured_facts_active')!;
+ expect(wave.state).toBe('finding');
+ expect(wave.spec.count(wave.check.details!)).toBe(3);
+
+ const preview = await repair(engine, []);
+ expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1, not_suspect: 2 });
+ const classes = Object.fromEntries(preview.results[0].listing!.map(l => [Number(l.item.split('#')[1]), l.class]));
+ expect(classes).toEqual({ [self]: 'evidenced', [selfCompact]: 'evidenced', [paste]: 'ambiguous', [twinned]: 'excluded:legitimate_duplicate' });
+ expect(preview.results[0].apply_command).toMatch(/^gbrain repair captured-facts --apply --expect [0-9a-f]+$/);
+ for (const id of [self, selfCompact, paste, pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
+
+ expect((await refusal(() => repair(engine, ['--apply']))).code).toBe('invalid_params');
+ const applied = await repair(engine, applyArgs(preview));
+ expect(applied.results[0].outcomes).toEqual({ expired: 2 });
+ expect(await active(engine, self)).toBe(false);
+ expect(await active(engine, selfCompact)).toBe(false);
+ for (const id of [paste, pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals'))[0].n).toBe(0);
+
+ // The fenced row is struck in the page, so a later write of the page keeps it expired.
+ const alice = (await engine.readPageSnapshot(ALICE, { sourceId: 'default' }))!;
+ expect(alice.page.compiled_truth).toContain('~~Alice Example prefers Rust for systems work~~');
+ await submitPageMutation(ctx, { operation: 'add_timeline_entry',
+ params: { request_id: randomUUID(), slug: ALICE, date: '2026-03-01', summary: 'met for coffee', source: 'operator' } });
+ expect(await active(engine, self)).toBe(false);
+
+ expect((await capturedFactsCheck(engine)).details).toMatchObject({ evidenced: 0, ambiguous: 1 });
+ const widened = await repair(engine, ['--include-ambiguous']);
+ expect(widened.results[0].apply_command).toContain('--include-ambiguous --apply --expect');
+ expect((await repair(engine, applyArgs(widened))).results[0].outcomes).toEqual({ expired: 1 });
+ expect(await active(engine, paste)).toBe(false);
+ for (const id of [pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
+ expect((await capturedFactsCheck(engine)).status).toBe('ok');
+
+ // Expired, not withdrawn: the same claim can be remembered again.
+ const again = await writeSingleFact(engine, 'default', { fact: 'Alice Example prefers Rust for systems work', entity: ALICE, provenance: 'cli:remember' });
+ expect(again.status).toBe('inserted');
+ expect(await active(engine, again.id)).toBe(true);
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ await seedEntity(engine, root, ALICE, 'Alice Example', 'person');
+ await seedEntity(engine, root, ACME, 'Acme Example', 'company');
+ } }));
+ }, 180_000);
+
+ test('a fact edited after the preview reports changed_since_preview and stays active', async () => {
+ await withEnv({ CLAUDE_CONFIG_DIR: claude }, () => managedBrain(async ({ engine }) => {
+ const id = (await writeSingleFact(engine, 'default', { fact: 'Alice Example prefers tea', entity: ALICE, provenance: 'hook:writeback', sessionId: 'sess-self' })).id;
+ const preview = await repair(engine, []);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>
+ tx.executeRaw("UPDATE facts SET visibility='world' WHERE id=$1", [id])));
+ const applied = await repair(engine, applyArgs(preview));
+ expect(applied.results[0].outcomes).toEqual({ changed_since_preview: 1 });
+ expect(await active(engine, id)).toBe(true);
+ }, { databaseUrl, setup: async ({ engine, root }) => { await seedEntity(engine, root, ALICE, 'Alice Example', 'person'); } }));
+ }, 180_000);
+ });
+
+ describe(`gbrain repair captured-facts, unmanaged (${backend})`, () => {
+ test('database-only self-capture rows expire; the rest stay', async () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const insert = async (fact: string, session: string) => Number((await engine.executeRaw<{ id: number }>(`INSERT INTO facts
+ (source_id, entity_slug, fact, kind, visibility, source, source_session) VALUES ('default', $1, $2, 'fact', 'private', 'hook:writeback', $3) RETURNING id`,
+ [ALICE, fact, session]))[0].id);
+ const self = await insert('Alice Example drinks oat milk', 'sess-self');
+ const normal = await insert('Alice Example runs marathons', 'sess-normal');
+ await withEnv({ CLAUDE_CONFIG_DIR: claude }, async () => {
+ const preview = await repair(engine, []);
+ expect(preview.results[0].residuals).toMatchObject({ evidenced: 1, not_suspect: 1 });
+ expect((await repair(engine, applyArgs(preview))).results[0].outcomes).toEqual({ expired: 1 });
+ });
+ expect(await active(engine, self)).toBe(false);
+ expect(await active(engine, normal)).toBe(true);
+ const [row] = await engine.executeRaw<{ context: string }>('SELECT context FROM facts WHERE id=$1', [self]);
+ expect(row.context).toContain('expired: captured-facts repair');
+ } finally { if (close) await close(); else await engine.disconnect(); }
+ }, 120_000);
+ });
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index a42e5f6229..12e94c9aab 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));