Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair conversation-labels retires label-misattributed conversation facts

time-attacke1c0b28ecd02
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 3f53657dcd..73e63dab67 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -7,7 +7,7 @@ src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one
src/core/persistence/takes-prepare.ts 4 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation. takes_remove deletes the removed row inside the same coordinated apply (#5167).
src/commands/extract-timeline-db.ts 2 coordinator `gbrain extract timeline --source db` (#5904): on a managed brain the timeline retraction and insert run only inside the managed_maintenance_timeline_extract publication (prepareTimelineExtract; owner-checked by maintenancePreflight, page key locked, revision-bound); only an unmanaged brain retracts and batch-inserts directly, where no canonical writer enforcement applies.
src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain each page's fact rows and outcome row are frozen into one database-only managed_maintenance_conversation_facts request (facts/conversation-publication.ts) after a maintenance preflight before provider work; the coordinator's preparer revalidates page identity, revision and parser-input snapshot under the page key. Unmanaged calls keep their direct engine writes behind the SQL guard (writeDerivedFacts refuses on a managed brain).
-src/core/facts/conversation-publication.ts 2 coordinator The managed conversation-facts preparer deletes the page's extractor rows and inserts the frozen batch inside the coordinator publication of its admitted managed_maintenance_conversation_facts request, after rechecking authority, page identity, revision, version token and embedding signature under the page key; a lost insert rolls the publication back.
+src/core/facts/conversation-publication.ts 3 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) and inserts the frozen batch inside the coordinator publication of its admitted managed_maintenance_conversation_facts request, after rechecking authority, page identity, revision, version token and embedding signature under the page key; a lost insert rolls the publication back. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction.
src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.
src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair preflights every target before the first backup/write.
src/commands/import.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
@@ -204,6 +204,7 @@ src/core/persistence/connector-path.ts 1 coordinator Connector path clear locks
src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.
src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.
src/core/repair/captured-facts.ts 1 coordinator `gbrain repair captured-facts` expires preview-approved capture-lane facts that have no fence row. On a managed brain the UPDATE runs only inside the managed_maintenance_expire_captured_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one transaction. Fenced rows are never updated here: they are struck in the page and expired by the canonical projection of a revision-bound put_page.
+src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per page on a managed brain (the preparer reclassifies under the lock), one maintenanceTransaction on an unmanaged brain.
src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.
src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.
src/core/repair/frontmatter.ts 2 coordinator `gbrain repair frontmatter --apply` (#5988) publishes a managed source's repaired file only through submitManagedFileRepair (the managed_file_repair request, preview-hash bound). On an unmanaged (legacy) source it writes the previewed bytes after a backup, moves a renamed page with updateSlug and its source_path in one maintenanceTransaction, then imports the file through importFromFile; no canonical writer enforcement applies there.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index d79bce3d45..0e681529ee 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -14,7 +14,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.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/conversation-outcomes.ts` — `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
+- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_label_facts` (wave check, host-only, resolution `repair`): bounded count (capped at 1000, reported as at least N) of the default set `gbrain repair conversation-labels` would retire; names the preview, never the apply. `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
- `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/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query 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`.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index c9b6b593c1..43e913e9c3 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`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.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/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; one database-only `managed_maintenance_conversation_label_retire` request per page on a managed brain (`prepareConversationLabelRetirement`), one transaction otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
- `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 through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, 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/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 29afd0a1e1..d306a8326f 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -235,7 +235,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.
-- `src/core/facts/conversation-publication.ts` (1): the managed conversation-facts preparer inserts the frozen batch inside the coordinator publication of its admitted request.
+- `src/core/facts/conversation-publication.ts` (2): the managed conversation-facts preparer clears the prior batch and inserts the frozen one inside the coordinator publication of its admitted request; the unmanaged cleanup runs the same clear in `maintenanceTransaction`.
- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.
- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.
- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).
@@ -268,6 +268,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/persistence/sync-prepare.ts` (4): managed sync request preparer.
- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.
- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.
+- `src/core/repair/conversation-labels.ts` (4): a request on managed brains; the unmanaged label retirement runs in `maintenanceTransaction`.
- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.
- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.
- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 8136d0fe4f..3d28f6a019 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -472,6 +472,78 @@ The preview warns, naming the host, when a consumer older than v0.60.11.0
published writes after `writer_version_cutoff`: an old consumer expires
restored facts again. Upgrade and restart it first.
+<a id="conversation-labels"></a>
+### Conversation labels
+
+Before v0.60.69 the conversation parser read meeting-note labels such as
+`**Date:**`, `**Attendees:**` and `**Summary:**` as speakers, so
+`gbrain extract-conversation-facts` stored facts like "Date said the review is
+on Monday", dated at 1970-01-01 when the page had no date. The parser is
+fixed, but those pages stay marked complete, so an upgrade never re-extracts
+them. `gbrain repair conversation-labels` retires those facts. It is
+explicit-only, preview-bound and destructive (it needs the user's consent),
+and it makes no model calls.
+
+**Say to your agent:** *"Doctor says some conversation facts came from
+meeting-note labels. Show me which ones before removing anything."* The agent
+runs the preview, shows you the list and, after you agree, runs the printed
+apply command with `--yes`.
+
+```bash
+gbrain doctor # conversation_label_facts
+gbrain repair conversation-labels # preview: every candidate, per-page outcome, hash
+gbrain repair conversation-labels --apply --expect <hash> --yes
+gbrain extract-conversation-facts --source-id <id> --slugs <pages> --dry-run # printed by the preview
+gbrain extract-conversation-facts --source-id <id> --slugs <pages> --max-cost-usd <n>
+gbrain doctor
+```
+
+Candidates are active conversation-extractor facts on pages that carry a bold
+metadata label line. Each gets one class:
+
+| Class | Meaning | Retired |
+| --- | --- | --- |
+| `evidenced` | Its context names a `segment 1970-01-01` window, which only the pre-fix parser wrote (the fixed one records an undated page as not extractable). | By `--apply --expect <hash> --yes` |
+| `ambiguous` | Any other fact of a label page: a post-fix transcript with a `**Date:**` header, a model-written context, a fact that legitimately mentions a label. Nothing on the row proves the misattribution. | Only with `--include-ambiguous` and that preview's hash |
+| `excluded:<reason>` | `current_extractor` (the page's outcome carries `extractor_version`, so the fixed parser extracted it), `withdrawn`, `superseded`, `superseded_by_reference` (another fact names it), `open_loop_reference` (an open loop points at it). | Never |
+
+The preview also gives each page its outcome:
+
+| Outcome | What the apply does | Cost |
+| --- | --- | --- |
+| `non_extractable` | Retires the facts, expires the completion marker and records the page as not extractable (prose notes, an undated page, a single email), as the fixed parser would. | $0 |
+| `awaiting_reextraction` | Retires the facts and expires the completion marker; the page re-enters the ordinary extraction backlog. | The next extraction, under its own cap |
+| `cleaned` | Retires the facts; the page had no completion marker. | $0 |
+
+A per-fact apply outcome of `changed_since_preview` means the fact changed (it
+was edited, withdrawn, superseded or already expired); it stays as it is.
+
+There is no `--reextract` or `--max-usd` here: `gbrain repair` never spends.
+The preview prints the hand-off, one dry run and one capped run per 50 pages
+waiting for extraction:
+`gbrain extract-conversation-facts --source-id <id> --slugs <a,b,…> --dry-run`,
+then the same command with `--max-cost-usd <n>` (default $5 when omitted; the
+opt-in `cycle.conversation_facts_backfill` also picks them up at $1 per run and
+$5 in total). Nothing re-extracts automatically.
+
+Retired facts are expired, not deleted: each keeps its id and gains
+`retired: conversation-labels <hash>` in its context, recall stops returning
+it, and a later extraction, its orphan cleanup and `gbrain repair
+extractor-facts` leave it alone. To bring a page's facts back, re-extract the
+page with the commands above. On a managed brain each page publishes one
+database-only `managed_maintenance_conversation_label_retire` request; a rerun
+after a crash skips pages whose request already committed. A non-interactive
+apply without `--yes` exits 3 with the consent payload and changes nothing;
+`preview_changed` means the hash names no saved preview, the preview is older
+than 7 days, or the apply's `--source` or `--include-ambiguous` differs from
+the preview's. Under a live `gbrain serve` on PGLite the command is refused at
+once: stop the serve, run the repair, then restart the serve (the refusal's
+`fix` names the steps).
+
+Conversation outcomes now record the parser version (`extractor_version=<n>`
+in the outcome row). Doctor `conversation_outcomes_stale` counts outcomes a
+later parser version would reconsider; they are never reopened automatically.
+
<a id="captured-facts"></a>
### Captured facts
@@ -1120,6 +1192,7 @@ Then recover what doctor names, in this order (skip a step whose check is ok):
| `[gbrain] warning: OPENAI_API_KEY in this process's environment differs from openai_api_key …`; doctor `embedding_key_source` warns | `embedding_key_source` ([provider key source](#embedding-key-source)) | `gbrain doctor` (`embedding_key_source`) | remove the variable and restart that process, or `gbrain config unset openai_api_key` | the warning no longer prints; `gbrain doctor` shows `embedding_key_source` ok | user (owns the key) | `credentials` |
| `The OpenAI embedding provider rejected its key (HTTP 401)` | [`embedding_auth_failed`](write-refusals.md#embedding_auth_failed) | `gbrain doctor` (`embedding_key_source`, `embedding_provider`) | the printed fix for the key source in effect, then `gbrain embed --stale` | `gbrain doctor` shows `embedding_provider` ok | user (owns the key) | `credentials`; `paid` for `embed --stale` |
| Conversation facts missing from recall after managed writes | `extractor_facts_expired` | `gbrain repair extractor-facts` | `gbrain repair extractor-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` | brain host, after the user agrees | `destructive` (rewrites expired facts) |
+| Recall returns conversation facts such as "Date said …" or "Attendees said …", or facts dated 1970-01-01; doctor `conversation_label_facts` warns; the upgrade banner prints `conversation_label_facts: N (explicit_kind_required; …)` | `gbrain repair conversation-labels` (ambiguous: add `--include-ambiguous`) | `gbrain repair conversation-labels --apply --expect <hash> --yes`, then the printed `gbrain extract-conversation-facts --slugs … --dry-run` | `gbrain doctor --only conversation_label_facts --json` | brain host, after the user agrees | `destructive` (retires facts; no model calls) |
### Upgrading to v0.60.20.0
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 337aae2d80..f0db9cfd91 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -12,6 +12,8 @@
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
+| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
+| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
diff --git a/docs/w9f/F.md b/docs/w9f/F.md
new file mode 100644
index 0000000000..dd00cd4630
--- /dev/null
+++ b/docs/w9f/F.md
@@ -0,0 +1,48 @@
+# Wave 9 follow-ups, lane F: repair old label facts
+
+Integrator notes for the release PR (no version stamped).
+
+## CHANGELOG lines
+
+- New `gbrain repair conversation-labels` retires conversation facts that the
+ parser before v0.60.69 extracted from meeting-note labels (`**Date:**`,
+ `**Attendees:**`, …) read as speakers, often dated 1970-01-01. It previews
+ every candidate with its class and a hash, makes no model calls, and needs
+ the user's consent to apply (`--apply --expect <hash> --yes`). Retired facts
+ are expired, not deleted. Prose and undated pages are recorded as not
+ extractable at no cost; other pages re-enter the extraction backlog and the
+ preview prints the capped re-extract commands
+ (`gbrain extract-conversation-facts --slugs … --dry-run`).
+- Doctor `conversation_label_facts` counts the facts the repair would retire
+ by default and points at its preview.
+- `gbrain extract-conversation-facts --slugs <a,b,…>` processes exactly the
+ named pages.
+- A conversation page whose completion marker was expired is extracted again,
+ and re-extraction no longer deletes facts an open loop or another fact's
+ `superseded_by` still references (they are expired instead) or facts the
+ label repair retired.
+
+## BEHAVIOR_CHANGES candidates
+
+> `gbrain repair conversation-labels` (new, explicit-only) retires conversation facts misattributed to meeting-note labels; it never runs from `gbrain repair --all`, doctor remediation or the upgrade, and it makes no model calls.
+
+> Re-extracting a conversation page now keeps facts an open loop or a superseding fact references, as expired history, instead of deleting them.
+
+## Decisions applied
+
+- Decision 4 (A): apply expires an approved id set (captured-facts pattern);
+ nothing is hard-deleted.
+- Decision 5 (A): default set = rows whose context carries
+ `segment 1970-01-01`; everything else on a label page is ambiguous, behind
+ `--include-ambiguous` with its own hash. Confirmed no post-fix path writes
+ that context: the fixed parser records an epoch-dated parse as not
+ extractable (`conversationSkip`), so it never reaches segment extraction.
+
+## Notes
+
+- Under a live `gbrain serve` on PGLite the lock refusal is already immediate
+ (`acquireLock` throws `LiveServeLockError` without waiting), and the fatal
+ CLI seam's fix is the stop → rerun → restart plan; the test pins it for this
+ command. Owner delegation for repair kinds stays a TODO.
+- Upstream master moved to v0.60.100.0 while this lane ran; the branch is
+ based on 9cc7c467 (v0.60.99.0) and does not merge it (integrator's call).
diff --git a/llms-full.txt b/llms-full.txt
index 1fb31ca51a..6750f770b6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10113,6 +10113,8 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
+| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
+| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
@@ -11457,6 +11459,78 @@ The preview warns, naming the host, when a consumer older than v0.60.11.0
published writes after `writer_version_cutoff`: an old consumer expires
restored facts again. Upgrade and restart it first.
+<a id="conversation-labels"></a>
+### Conversation labels
+
+Before v0.60.69 the conversation parser read meeting-note labels such as
+`**Date:**`, `**Attendees:**` and `**Summary:**` as speakers, so
+`gbrain extract-conversation-facts` stored facts like "Date said the review is
+on Monday", dated at 1970-01-01 when the page had no date. The parser is
+fixed, but those pages stay marked complete, so an upgrade never re-extracts
+them. `gbrain repair conversation-labels` retires those facts. It is
+explicit-only, preview-bound and destructive (it needs the user's consent),
+and it makes no model calls.
+
+**Say to your agent:** *"Doctor says some conversation facts came from
+meeting-note labels. Show me which ones before removing anything."* The agent
+runs the preview, shows you the list and, after you agree, runs the printed
+apply command with `--yes`.
+
+```bash
+gbrain doctor # conversation_label_facts
+gbrain repair conversation-labels # preview: every candidate, per-page outcome, hash
+gbrain repair conversation-labels --apply --expect <hash> --yes
+gbrain extract-conversation-facts --source-id <id> --slugs <pages> --dry-run # printed by the preview
+gbrain extract-conversation-facts --source-id <id> --slugs <pages> --max-cost-usd <n>
+gbrain doctor
+```
+
+Candidates are active conversation-extractor facts on pages that carry a bold
+metadata label line. Each gets one class:
+
+| Class | Meaning | Retired |
+| --- | --- | --- |
+| `evidenced` | Its context names a `segment 1970-01-01` window, which only the pre-fix parser wrote (the fixed one records an undated page as not extractable). | By `--apply --expect <hash> --yes` |
+| `ambiguous` | Any other fact of a label page: a post-fix transcript with a `**Date:**` header, a model-written context, a fact that legitimately mentions a label. Nothing on the row proves the misattribution. | Only with `--include-ambiguous` and that preview's hash |
+| `excluded:<reason>` | `current_extractor` (the page's outcome carries `extractor_version`, so the fixed parser extracted it), `withdrawn`, `superseded`, `superseded_by_reference` (another fact names it), `open_loop_reference` (an open loop points at it). | Never |
+
+The preview also gives each page its outcome:
+
+| Outcome | What the apply does | Cost |
+| --- | --- | --- |
+| `non_extractable` | Retires the facts, expires the completion marker and records the page as not extractable (prose notes, an undated page, a single email), as the fixed parser would. | $0 |
+| `awaiting_reextraction` | Retires the facts and expires the completion marker; the page re-enters the ordinary extraction backlog. | The next extraction, under its own cap |
+| `cleaned` | Retires the facts; the page had no completion marker. | $0 |
+
+A per-fact apply outcome of `changed_since_preview` means the fact changed (it
+was edited, withdrawn, superseded or already expired); it stays as it is.
+
+There is no `--reextract` or `--max-usd` here: `gbrain repair` never spends.
+The preview prints the hand-off, one dry run and one capped run per 50 pages
+waiting for extraction:
+`gbrain extract-conversation-facts --source-id <id> --slugs <a,b,…> --dry-run`,
+then the same command with `--max-cost-usd <n>` (default $5 when omitted; the
+opt-in `cycle.conversation_facts_backfill` also picks them up at $1 per run and
+$5 in total). Nothing re-extracts automatically.
+
+Retired facts are expired, not deleted: each keeps its id and gains
+`retired: conversation-labels <hash>` in its context, recall stops returning
+it, and a later extraction, its orphan cleanup and `gbrain repair
+extractor-facts` leave it alone. To bring a page's facts back, re-extract the
+page with the commands above. On a managed brain each page publishes one
+database-only `managed_maintenance_conversation_label_retire` request; a rerun
+after a crash skips pages whose request already committed. A non-interactive
+apply without `--yes` exits 3 with the consent payload and changes nothing;
+`preview_changed` means the hash names no saved preview, the preview is older
+than 7 days, or the apply's `--source` or `--include-ambiguous` differs from
+the preview's. Under a live `gbrain serve` on PGLite the command is refused at
+once: stop the serve, run the repair, then restart the serve (the refusal's
+`fix` names the steps).
+
+Conversation outcomes now record the parser version (`extractor_version=<n>`
+in the outcome row). Doctor `conversation_outcomes_stale` counts outcomes a
+later parser version would reconsider; they are never reopened automatically.
+
<a id="captured-facts"></a>
### Captured facts
@@ -12105,6 +12179,7 @@ Then recover what doctor names, in this order (skip a step whose check is ok):
| `[gbrain] warning: OPENAI_API_KEY in this process's environment differs from openai_api_key …`; doctor `embedding_key_source` warns | `embedding_key_source` ([provider key source](#embedding-key-source)) | `gbrain doctor` (`embedding_key_source`) | remove the variable and restart that process, or `gbrain config unset openai_api_key` | the warning no longer prints; `gbrain doctor` shows `embedding_key_source` ok | user (owns the key) | `credentials` |
| `The OpenAI embedding provider rejected its key (HTTP 401)` | [`embedding_auth_failed`](write-refusals.md#embedding_auth_failed) | `gbrain doctor` (`embedding_key_source`, `embedding_provider`) | the printed fix for the key source in effect, then `gbrain embed --stale` | `gbrain doctor` shows `embedding_provider` ok | user (owns the key) | `credentials`; `paid` for `embed --stale` |
| Conversation facts missing from recall after managed writes | `extractor_facts_expired` | `gbrain repair extractor-facts` | `gbrain repair extractor-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` | brain host, after the user agrees | `destructive` (rewrites expired facts) |
+| Recall returns conversation facts such as "Date said …" or "Attendees said …", or facts dated 1970-01-01; doctor `conversation_label_facts` warns; the upgrade banner prints `conversation_label_facts: N (explicit_kind_required; …)` | `gbrain repair conversation-labels` (ambiguous: add `--include-ambiguous`) | `gbrain repair conversation-labels --apply --expect <hash> --yes`, then the printed `gbrain extract-conversation-facts --slugs … --dry-run` | `gbrain doctor --only conversation_label_facts --json` | brain host, after the user agrees | `destructive` (retires facts; no model calls) |
### Upgrading to v0.60.20.0
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index a5e54c298e..bf6fc8793c 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -37,6 +37,7 @@ const EXEMPT = {
'src/core/persistence/effect-journal.ts': 'post-publication effects; no page text',
'src/core/repair/captured-facts.ts': 'owner-run repair that expires fact rows (shrinks only)',
'src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',
+ 'src/core/repair/conversation-labels.ts': 'owner-run repair expiring fact rows and writing an outcome row (shrinks only; page text unchanged)',
'src/core/shared-skills/publication.ts': 'skill bundles, not pages',
'src/core/persistence/prepared-import.ts': 'type definitions shared by import preparers; prepares nothing itself',
'src/commands/extract-timeline-db.ts': 'writes timeline rows; timeline never enters core',
diff --git a/src/commands/doctor/checks/conversation-outcomes.ts b/src/commands/doctor/checks/conversation-outcomes.ts
index a064c858a7..52cb60d42f 100644
--- a/src/commands/doctor/checks/conversation-outcomes.ts
+++ b/src/commands/doctor/checks/conversation-outcomes.ts
@@ -49,3 +49,31 @@ export async function conversationOutcomesStaleCheck(engine: BrainEngine, source
message: `Conversation extraction outcomes could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
}
}
+
+export const LABEL_SCAN_CAP = 1000;
+
+/**
+ * conversation_label_facts (wave 9 follow-ups, item 2): active conversation
+ * facts on meeting-note pages whose context names a 1970-01-01 segment, the
+ * signature of the pre-v0.60.69 parser reading `**Date:**`-style labels as
+ * speakers. Bounded (indexed extractor rows, capped at LABEL_SCAN_CAP and
+ * reported as at least N). Points at the repair's preview, never at apply.
+ * Read-only.
+ */
+export async function conversationLabelFactsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ const name = 'conversation_label_facts';
+ try {
+ const { countLabelFacts } = await import('../../../core/repair/conversation-labels.ts');
+ 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 { count, capped } = await countLabelFacts(engine, sources, LABEL_SCAN_CAP);
+ const details = { evidenced: count, capped, repair: 'conversation-labels', docs: 'docs/guides/repair.md#conversation-labels' };
+ if (!count) return { name, status: 'ok', details, message: 'No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).' };
+ return { name, status: 'warn', details,
+ message: `${capped ? 'At least ' : ''}${count} conversation fact(s) were extracted by the pre-v0.60.69 parser from meeting-note labels (**Date:**, **Attendees:** …) `
+ + 'read as speakers, and recall still returns them. Preview the repair on the brain host (it makes no model calls): gbrain repair conversation-labels '
+ + '— then run the apply command it prints after the user agrees.' };
+ } catch (error) {
+ return { name, status: 'warn', details: { evidenced: 'unknown' },
+ message: `Label-misattributed conversation facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 43576625b4..d9a5628327 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -296,8 +296,9 @@ export const timelineHistoryEntry: DoctorEntry = {
'stale_embedding_effects',
'google_file_modes',
'extractor_facts_expired',
- 'captured_facts_active',
+ 'conversation_label_facts',
'conversation_outcomes_stale',
+ 'captured_facts_active',
'loop_facts_drift',
],
run: runTimelineHistory,
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index eb7c7fec19..fe5c8ae230 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -205,6 +205,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: 'conversation_label_facts', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Retiring label-misattributed conversation facts is a host-side, explicit-only repair.',
+ count: d => Number(d.evidenced ?? 0),
+ impact: 'Some conversation facts were extracted from meeting-note labels read as speakers by an older parser, and recall still returns them',
+ run: async (engine, scope) => (await import('./checks/conversation-outcomes.ts')).conversationLabelFactsCheck(engine, scope.sourceIds),
+ },
{
id: 'conversation_outcomes_stale', resolution: 'operator', registration: 'wave',
hostOnly: 'Re-extracting conversation facts spends model calls on the brain host.',
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index bd6e0b7fe0..ef81da0eb2 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -77,7 +77,7 @@ import {
import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';
import { writeDerivedFacts } from '../core/persistence/derived-facts.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
-import { managedConversationPublisher, publishManagedBatch, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';
+import { clearConversationFacts, managedConversationPublisher, publishManagedBatch, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';
import { noPricingMessage } from '../core/budget/no-pricing.ts';
import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';
@@ -728,19 +728,7 @@ async function deleteOrphanFactsForPage(
): Promise<number> {
// A cleanup failure is authoritative: callers must not write a terminal or
// non-extractable marker while facts from an older snapshot may remain.
- const rows = await writeDerivedFacts(engine, sourceId, slug, db => db.executeRaw<{ count: string }>(
- `WITH del AS (
- DELETE FROM facts
- WHERE source_id = $1
- AND source_markdown_slug = $2
- AND source LIKE 'cli:extract-conversation-facts%'
- RETURNING 1
- )
- SELECT COUNT(*)::text AS count FROM del`,
- [sourceId, slug],
- ));
- const n = parseInt(rows[0]?.count ?? '0', 10);
- return Number.isFinite(n) ? n : 0;
+ return writeDerivedFacts(engine, sourceId, slug, db => clearConversationFacts(db, sourceId, slug));
}
// ---------------------------------------------------------------------------
@@ -904,7 +892,7 @@ export async function findFreshExtractionOutcomes(
FROM facts
WHERE source_id = $1
AND source_markdown_slug = ANY($2::text[])
- AND source = ANY($3::text[])
+ AND source = ANY($3::text[]) AND expired_at IS NULL
ORDER BY source_markdown_slug,
CASE WHEN source = $4 THEN 0 ELSE 1 END`,
[
@@ -1113,9 +1101,9 @@ async function processPage(
);
}
- // Page-global row_num: after delete-orphans-first the table has no
- // rows for this (sourceId, slug), so we always start from 0.
- let rowNum = 0;
+ // Page-global row_num, above every row the cleanup kept (retired or referenced history,
+ // fence rows); 0 on a page with none. A managed batch is renumbered under its lock.
+ let rowNum = state.managed ? 0 : await peekRowNumStart(state.engine, state.sourceId, page.slug);
let newestEnd: string | null = null;
let segmentsThisPage = 0;
let pageInsertedTotal = 0;
@@ -1808,6 +1796,8 @@ interface ParsedArgs {
sourceId?: string;
types?: AllowedType[];
slug?: string;
+ /** Exactly these pages (comma-separated `--slugs`; `gbrain repair conversation-labels` prints it). */
+ slugs?: string[];
dryRun?: boolean;
limit?: number;
sinceIso?: string;
@@ -1824,7 +1814,7 @@ interface ParsedArgs {
error?: string;
}
-function parseArgs(args: string[]): ParsedArgs {
+export function parseArgs(args: string[]): ParsedArgs {
const out: ParsedArgs = {};
for (let i = 0; i < args.length; i++) {
const a = args[i];
@@ -1835,6 +1825,7 @@ function parseArgs(args: string[]): ParsedArgs {
if (a === '--yes' || a === '-y') { out.yes = true; continue; }
if (a === '--override-disabled') { out.overrideDisabled = true; continue; }
if (a === '--slug') { out.slug = args[++i]; continue; }
+ if (a === '--slugs') { out.slugs = (args[++i] ?? '').split(',').map(s => s.trim()).filter(Boolean); continue; }
if (a === '--source-id') { out.sourceId = args[++i]; continue; }
if (a === '--since') { out.sinceIso = args[++i]; continue; }
if (a === '--types') {
@@ -1899,6 +1890,7 @@ Options:
Default: reads cycle.conversation_facts_backfill.types config
(falls back to the full allowlist).
--slug <slug> Process a single page (overrides multi-page enumeration).
+ --slugs <a,b,...> Process exactly these pages (comma-separated).
--dry-run Show segmentation + counts; no model calls, DB writes, or checkpoint advance.
--limit <N> Cap pages processed (default: all).
--since <iso> Only consider messages newer than this ISO timestamp.
@@ -1940,6 +1932,7 @@ function buildJobParams(args: string[]): Record<string, unknown> {
sourceId: parsed.sourceId,
types: parsed.types,
slug: parsed.slug,
+ slugs: parsed.slugs,
dryRun: parsed.dryRun,
limit: parsed.limit,
sinceIso: parsed.sinceIso,
@@ -2037,6 +2030,7 @@ export async function runExtractConversationFacts(
sourceId,
types: parsed.types,
slug: parsed.slug,
+ slugs: parsed.slugs,
dryRun: parsed.dryRun,
limit: parsed.limit,
sinceIso: parsed.sinceIso,
@@ -2132,12 +2126,8 @@ export async function runExtractConversationFacts(
if (aggregate.pages_failed > 0) {
console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry.`);
}
- if (aggregate.pages_pending) {
- console.log(` ${aggregate.pages_pending} page(s) were accepted and are still pending; rerun the same command to confirm them (no model call).`);
- }
- if (aggregate.pages_blocked) {
- console.log(` ${aggregate.pages_blocked} page(s) are blocked at their current version after a request failed; they are retried only once the page changes (each SKIP line names the receipt).`);
- }
+ if (aggregate.pages_pending) console.log(` ${aggregate.pages_pending} page(s) were accepted and are still pending; rerun the same command to confirm them (no model call).`);
+ if (aggregate.pages_blocked) console.log(` ${aggregate.pages_blocked} page(s) are blocked at their current version after a request failed; they are retried only once the page changes (each SKIP line names the receipt).`);
if (aggregate.pages_llm_fallback > 0) {
console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);
}
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 5de0ee4b7f..71acd48536 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -58,8 +58,8 @@ Options:
--only <path>, --skip <path>
frontmatter: select source-relative files (repeatable); the hash covers the selection.
--diff frontmatter: print every per-file diff, not one sample per class.
- --yes frontmatter --apply: the user agreed to the previewed file changes (destructive consent;
- without it a terminal asks, and a non-interactive run exits 3 with the consent payload).
+ --yes frontmatter, conversation-labels --apply: the user agreed to the previewed changes (destructive
+ consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).
--json Machine-readable output with a stable shape (frontmatter: every per-file diff).
Any other option is refused. There is no --max-usd here: to cap paid embedding
@@ -119,7 +119,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,
`Kinds: ${REPAIR_KINDS.join(', ')}.`);
parsed.kind = positional[0];
- if (used.has('--yes') && parsed.kind !== 'frontmatter') throw invalid('`--yes` is not accepted by gbrain repair; pass --apply to write.',
+ if (used.has('--yes') && REPAIR_REGISTRY.find(spec => spec.kind === parsed.kind)?.consent !== 'destructive') throw invalid('`--yes` is not accepted by gbrain repair; pass --apply to write.',
`Preview first with gbrain repair${parsed.kind ? ` ${parsed.kind}` : ''}, then run the same command with --apply instead of --yes.`,
['gbrain', 'repair', ...(parsed.kind ? [parsed.kind] : []), ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
const frontmatterOnly = [...used].find(flag => flag !== '--yes');
@@ -177,11 +177,13 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
if (apply && kind && expect && repairSpec(kind as RepairKind).consent === 'destructive') {
const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),
...(includeAmbiguous ? ['--include-ambiguous'] : [])];
- const auth = await consentGate({ command: `repair ${kind}`, effects: ['destructive'], actor: 'agent',
+ const custom = repairSpec(kind as RepairKind).consentText;
+ const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)})` } : {
what: `Rewrite the previewed ${kind} changes on disk and import them`,
why: `The preview ${expect} listed each file change; applying it rewrites those files in place and publishes them.`,
risk: 'Only the previewed lines change; a file that changed since the preview is skipped. Managed sources commit through the Git effect (undo with git revert); legacy sources keep a backup under ~/.gbrain/backups/frontmatter/.',
- user_message: `Apply the previewed ${kind} repair (preview ${expect.slice(0, 12)})? Each listed file is rewritten on disk exactly as the preview showed and imported again.`,
+ user_message: `Apply the previewed ${kind} repair (preview ${expect.slice(0, 12)})? Each listed file is rewritten on disk exactly as the preview showed and imported again.` };
+ const auth = await consentGate({ command: `repair ${kind}`, effects: ['destructive'], actor: 'agent', ...text,
argv: [...preview, '--apply', '--expect', expect, ...(json ? ['--json'] : [])], preview_argv: [...preview, '--json'], plan_hash: expect, args }, { json, env: engineConsentEnv(engine) });
if (!auth) return;
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e81b770294..5a95fab08e 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -59,7 +59,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
- 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
@@ -105,7 +105,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],
- 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--source', '--stale', '--yes'],
+ 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slugs', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index cec4765863..7b9388d5ea 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -58,6 +58,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'abandoned_threads',
'atom_provenance_drift',
'captured_facts_active',
+ 'conversation_label_facts',
'conversation_outcomes_stale',
'connector_checkpoints',
'connector_held_items',
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 6a99f2afd2..a68dcca96c 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -309,10 +309,8 @@ async function mergedEntities(tx: BrainEngine, sourceId: string, slugs: string[]
*/
export async function replaceConversationFacts(tx: BrainEngine, sourceId: string, slug: string,
rows: Array<Omit<ConversationFactRow, 'row_num' | 'source_markdown_slug'>>): Promise<{ deleted: number; inserted: number }> {
- const [deleted] = await tx.executeRaw<{ count: string }>(
- `WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' RETURNING 1)
- SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug]);
- if (!rows.length) return { deleted: Number(deleted?.count ?? 0), inserted: 0 };
+ const deleted = await clearConversationFacts(tx, sourceId, slug);
+ if (!rows.length) return { deleted, inserted: 0 };
const [top] = await tx.executeRaw<{ n: number | string | null }>(
'SELECT max(row_num) AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [sourceId, slug]);
const start = top?.n == null ? 0 : Number(top.n) + 1;
@@ -321,7 +319,29 @@ export async function replaceConversationFacts(tx: BrainEngine, sourceId: string
throw opError('storage_error', 'A conversation fact insert was lost; the page\'s prior facts were kept.',
`Only ${inserted} of ${rows.length} fact rows of ${slug} in source ${sourceId} were inserted, so the replacement rolled back. Run the extraction for the page again; report this if it repeats.`);
}
- return { deleted: Number(deleted?.count ?? 0), inserted };
+ return { deleted, inserted };
+}
+
+/** Context marker `gbrain repair conversation-labels` appends to the rows it retires. */
+export const LABEL_RETIRED_MARKER = 'retired: conversation-labels';
+
+/**
+ * Clears a page's prior extractor batch before a replacement, keeping the
+ * history other records depend on: a row an open loop (`open_loops.fact_id`,
+ * no FK) or another fact's `superseded_by` references is expired, never
+ * deleted, and rows `gbrain repair conversation-labels` retired stay expired.
+ * Every other extractor row of the page is deleted. Returns the rows removed
+ * from the active batch.
+ */
+export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string): Promise<number> {
+ const page = `f.source_id=$1 AND f.source_markdown_slug=$2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'`;
+ const referenced = 'EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=f.id) OR EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id)';
+ const [expired] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
+ WHERE ${page} AND f.expired_at IS NULL AND (${referenced}) RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, [sourceId, slug]);
+ const [deleted] = await db.executeRaw<{ count: string }>(`WITH del AS (DELETE FROM facts f
+ WHERE ${page} AND NOT (${referenced}) AND COALESCE(f.context,'') NOT LIKE '%${LABEL_RETIRED_MARKER}%' RETURNING 1)
+ SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug]);
+ return Number(expired?.count ?? 0) + Number(deleted?.count ?? 0);
}
/** Preparer for `managed_maintenance_conversation_facts`: a database-only publication on the page key. */
diff --git a/src/core/minions/handlers/extract-conversation-facts.ts b/src/core/minions/handlers/extract-conversation-facts.ts
index dfb4f72fe0..1ef2daffa9 100644
--- a/src/core/minions/handlers/extract-conversation-facts.ts
+++ b/src/core/minions/handlers/extract-conversation-facts.ts
@@ -36,6 +36,7 @@ export function makeExtractConversationFactsHandler(engine: BrainEngine): Minion
sourceId,
types,
slug: typeof job.data.slug === 'string' ? job.data.slug : undefined,
+ slugs: Array.isArray(job.data.slugs) ? (job.data.slugs as unknown[]).filter((v): v is string => typeof v === 'string') : undefined,
dryRun: !!job.data.dryRun,
limit: typeof job.data.limit === 'number' ? job.data.limit : undefined,
sinceIso: typeof job.data.sinceIso === 'string' ? job.data.sinceIso : undefined,
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 6cae97f472..2d77028002 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -344,6 +344,7 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Write
if (row.authority.remote) throw trustedCliRequired('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_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_fence_facts') return (await import('../cycle/extract-facts.ts')).prepareFenceFactsReconcile(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_deleted_page_facts_expire') return (await import('../cycle/extract-facts.ts')).prepareDeletedPageFactsExpiry(engine, row);
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 45a53e8cd5..688b65be4b 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' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/conversation-labels.ts b/src/core/repair/conversation-labels.ts
new file mode 100644
index 0000000000..6960b83590
--- /dev/null
+++ b/src/core/repair/conversation-labels.ts
@@ -0,0 +1,411 @@
+/**
+ * `gbrain repair conversation-labels` (wave 9 follow-ups, item 2): retire
+ * conversation facts the pre-v0.60.69 parser misattributed to meeting-note
+ * labels. That parser read `**Date:**`, `**Attendees:**`, `**Summary:**` and
+ * the other metadata labels as speakers and, on a page without a date,
+ * stamped their turns at 1970-01-01. The parser was fixed, but the stored
+ * batches stay "complete" for their content version, so an upgrade never
+ * reopens them. This kind makes no model calls.
+ *
+ * Candidates: active per-segment extractor facts (`source` exactly
+ * `cli:extract-conversation-facts`) on live pages whose text carries a bold
+ * metadata label line (METADATA_LABELS). Each is classified (Decision 5):
+ * - excluded (kept, listed with the reason): the page's outcome was
+ * recorded by the fixed extractor (`extractor_version` stamp); the claim
+ * was withdrawn; the row is superseded; another fact's `superseded_by`
+ * or an open loop (`open_loops.fact_id`, no FK) references it.
+ * - evidenced: its context carries the epoch segment marker
+ * (`segment 1970-01-01`), which the fixed parser never writes (undated
+ * pages are skipped as not extractable).
+ * - ambiguous: everything else, listed fact by fact; retired only with
+ * `--include-ambiguous` and the hash of that preview.
+ *
+ * The preview lists every candidate, a per-page outcome and the follow-on
+ * work, prints a hash over all of it and saves the approved set (one item
+ * per page) through `persistence/preview-approval.ts`. The apply (Decision 4)
+ * EXPIRES the approved ids that are still exactly as previewed, appending
+ * LABEL_RETIRED_MARKER to their context (history kept; later replacement,
+ * orphan cleanup and `repair extractor-facts` leave them alone), expires the
+ * page's obsolete completion marker, and for a page the current parser
+ * finds not extractable (prose, undated, a single email) writes that
+ * durable outcome at no cost. Every other page drops back into the ordinary
+ * extraction backlog; the preview and the apply print the hand-off commands
+ * (`gbrain extract-conversation-facts --slugs … --dry-run`, then with
+ * `--max-cost-usd`). A managed brain publishes one database-only
+ * `managed_maintenance_conversation_label_retire` request per page; an
+ * unmanaged brain writes under the page lock. Never automatic.
+ */
+import type { BrainEngine, NewFact } from '../engine.ts';
+import type { Page } from '../types.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.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 { maintenanceTransaction } from '../persistence/attribution.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { METADATA_LABELS } from '../conversation-parser/builtins.ts';
+import { parseConversation } from '../conversation-parser/parse.ts';
+import { readConversationBodyForParsing } from '../conversation-parser/body.ts';
+import { conversationSkip } from '../facts/conversation-skip.ts';
+import { LABEL_RETIRED_MARKER } from '../facts/conversation-publication.ts';
+import { LEGACY_TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from '../facts/audit-sources.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+export const CONVERSATION_LABELS_INTENT = 'managed_maintenance_conversation_label_retire';
+const SEGMENT_SOURCE = 'cli:extract-conversation-facts';
+/** The default context the pre-fix extractor wrote for an undated page's segment. */
+export const EPOCH_SEGMENT_MARKER = 'segment 1970-01-01';
+/** A bold metadata label line, as the pre-fix bold-name-no-time pattern read it (POSIX, case-insensitive). */
+const LABEL_LINE_SQL = `(^|\\n)\\*\\*(${METADATA_LABELS.join('|')})[[:space:]]*:\\*\\*`;
+const HANDOFF_SLUGS_PER_COMMAND = 50;
+const previewFix = (sourceId: string) => readFix('Previews the conversation-labels repair without changing anything; it makes no model calls.',
+ { argv: ['gbrain', 'repair', 'conversation-labels', '--source', sourceId, '--json'] });
+
+export type LabelFactClass = 'evidenced' | 'ambiguous' | 'excluded';
+export type LabelPageOutcome = 'non_extractable' | 'awaiting_reextraction' | 'cleaned';
+
+export interface LabelFactCandidate {
+ id: number;
+ source_id: string;
+ slug: string;
+ class: LabelFactClass;
+ reason: string;
+ /** Digest of the row's claim, context, entity and visibility, so an edited row is not retired. */
+ fact_hash: string;
+}
+
+/** One approved page: the facts to retire, the marker to expire and the outcome the current parser decides. */
+export interface LabelPage {
+ source_id: string;
+ slug: string;
+ page_id: number;
+ request_id: string;
+ include_ambiguous: boolean;
+ scope: string[];
+ facts: Array<Pick<LabelFactCandidate, 'id' | 'class' | 'reason' | 'fact_hash'>>;
+ outcome: LabelPageOutcome;
+ /** Not-extractable reason (non_extractable pages) and the parser-input version it was decided for. */
+ non_extractable_reason: string | null;
+ version_token: string;
+ segments: number;
+}
+
+interface PageItem extends RepairItem { page: LabelPage; hash: string; last: boolean }
+
+interface CandidateRow {
+ id: number | string; source_id: string; slug: string; fact: string; context: string | null; entity_slug: string | null; visibility: string;
+ superseded: boolean; withdrawn: boolean; referenced: boolean; open_loop: boolean; outcome_stamped: boolean;
+}
+
+/** Every candidate of these sources (or of one page), classified, in (source, page, id) order. Read-only. */
+export async function classifyLabelFacts(db: BrainEngine, sourceIds: string[], opts: { slug?: string } = {}): Promise<LabelFactCandidate[]> {
+ const rows = await db.executeRaw<CandidateRow>(`
+ SELECT f.id, f.source_id, f.source_markdown_slug AS slug, f.fact, f.context, f.entity_slug, f.visibility,
+ f.superseded_by IS NOT NULL AS superseded,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact))
+ AND (w.subject='*' OR w.subject=f.entity_slug)) AS withdrawn,
+ EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id) AS referenced,
+ EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=f.id) AS open_loop,
+ EXISTS (SELECT 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=f.source_markdown_slug
+ AND o.source IN ($3, $4) AND o.expired_at IS NULL AND o.context ~ 'extractor_version=[0-9]+$') AS outcome_stamped
+ FROM facts f JOIN pages p ON p.source_id=f.source_id AND p.slug=f.source_markdown_slug AND p.deleted_at IS NULL
+ WHERE f.source_id=ANY($1::text[]) AND f.source=$5 AND f.expired_at IS NULL
+ AND ($2::text IS NULL OR f.source_markdown_slug=$2::text)
+ AND (p.compiled_truth ~* $6 OR COALESCE(p.timeline,'') ~* $6)
+ ORDER BY f.source_id, f.source_markdown_slug, f.id`,
+ [sourceIds, opts.slug ?? null, TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, SEGMENT_SOURCE, LABEL_LINE_SQL]);
+ return rows.map(row => {
+ const [klass, reason] = classify(row);
+ return { id: Number(row.id), source_id: row.source_id, slug: row.slug, class: klass, reason,
+ fact_hash: digest([row.fact, row.context, row.entity_slug, row.visibility]) };
+ });
+}
+
+function classify(row: CandidateRow): [LabelFactClass, string] {
+ if (row.outcome_stamped) return ['excluded', 'current_extractor'];
+ if (row.withdrawn) return ['excluded', 'withdrawn'];
+ if (row.superseded) return ['excluded', 'superseded'];
+ if (row.referenced) return ['excluded', 'superseded_by_reference'];
+ if (row.open_loop) return ['excluded', 'open_loop_reference'];
+ if ((row.context ?? '').includes(EPOCH_SEGMENT_MARKER)) return ['evidenced', 'epoch_segment_context'];
+ return ['ambiguous', 'no_epoch_marker'];
+}
+
+const DETAILS: Record<string, string> = {
+ current_extractor: 'the page was extracted by the fixed parser (its outcome carries extractor_version)',
+ withdrawn: 'its claim was withdrawn (forget)',
+ superseded: 'a newer fact superseded it',
+ superseded_by_reference: 'another fact names it in superseded_by',
+ open_loop_reference: 'an open loop references it (open_loops.fact_id)',
+ epoch_segment_context: 'its context names a 1970-01-01 segment, which only the pre-fix parser wrote',
+ no_epoch_marker: 'its page has meeting-note labels, but nothing on the row proves the label misattribution',
+};
+
+/** What the current parser decides for the page at no cost: a durable not-extractable reason, or null (it needs extraction). */
+async function currentOutcome(db: BrainEngine, page: Page): Promise<{ reason: string | null; versionToken: string; segments: number }> {
+ const { currentConversationVersionToken, splitIntoSegments } = await import('../../commands/extract-conversation-facts.ts');
+ const body = await readConversationBodyForParsing(db, page);
+ const parse = parseConversation(body, { page });
+ const llmFallback = (await db.getConfig('conversation_parser.llm_fallback_enabled')) === 'true';
+ const skip = conversationSkip(page, body, parse, parse.messages, { llmFallback });
+ return { reason: skip?.reason ?? null, versionToken: await currentConversationVersionToken(db, page),
+ segments: skip ? 0 : splitIntoSegments(parse.messages, {}).length };
+}
+
+async function activeMarker(db: BrainEngine, sourceId: string, slug: string): Promise<boolean> {
+ const rows = await db.executeRaw('SELECT 1 FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source IN ($3,$4) AND expired_at IS NULL LIMIT 1',
+ [sourceId, slug, TERMINAL_AUDIT_SOURCE, LEGACY_TERMINAL_AUDIT_SOURCE]);
+ return rows.length > 0;
+}
+
+function requestIdFor(hash: string, page: Pick<LabelPage, 'source_id' | 'slug'>, attempt: number): string {
+ const h = digest(['conversation-labels-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)}`;
+}
+
+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 conversation-labels${narrowed ? ` --source ${scope.source_ids[0]}` : ''}${includeAmbiguous ? ' --include-ambiguous' : ''}`;
+}
+
+/**
+ * The commands that re-extract the pages awaiting extraction, under the
+ * extraction command's own cost cap: a dry run first, then the run. Each
+ * names at most HANDOFF_SLUGS_PER_COMMAND pages.
+ */
+export function handoffCommands(pages: Array<Pick<LabelPage, 'source_id' | 'slug' | 'outcome'>>): string[] {
+ const bySource = new Map<string, string[]>();
+ for (const page of pages) if (page.outcome === 'awaiting_reextraction') bySource.set(page.source_id, [...bySource.get(page.source_id) ?? [], page.slug]);
+ const commands: string[] = [];
+ for (const [sourceId, slugs] of bySource) {
+ for (let i = 0; i < slugs.length; i += HANDOFF_SLUGS_PER_COMMAND) {
+ const base = `gbrain extract-conversation-facts --source-id ${sourceId} --slugs ${slugs.slice(i, i + HANDOFF_SLUGS_PER_COMMAND).join(',')}`;
+ commands.push(`${base} --dry-run`, `${base} --max-cost-usd <n>`);
+ }
+ }
+ return commands;
+}
+
+function pageItem(page: LabelPage, hash: string, index: number, last: boolean): PageItem {
+ return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: `retire ${page.facts.length} label-misattributed fact(s); ${page.outcome.replaceAll('_', ' ')}`, page, hash, last };
+}
+
+/** Pages of an approved set whose retirement already committed (or whose facts are all expired already). */
+async function finishedPages(engine: BrainEngine, hash: string, pages: LabelPage[]): 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 request_id=ANY($1::uuid[])`, [pages.map(p => p.request_id)]);
+ const active = new Set((await engine.executeRaw<{ id: number | string }>('SELECT id FROM facts WHERE id=ANY($1::bigint[]) AND expired_at IS NULL',
+ [pages.flatMap(p => p.facts.map(f => f.id))])).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 => !active.has(f.id))) done.add(`${page.source_id}\u0000${page.slug}`);
+ return done;
+}
+
+export const conversationLabelsRepair: RepairHandler = {
+ kind: 'conversation-labels',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeAmbiguous = opts?.includeAmbiguous === true;
+ const command = await previewCommand(engine, scope, includeAmbiguous);
+ if (opts?.apply) {
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair conversation-labels --apply retires only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,
+ 'docs/guides/repair.md#conversation-labels');
+ }
+ const approved = await loadApprovedSet<LabelPage>(engine, { command: 'conversation-labels', 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 done = await finishedPages(engine, opts.expect, approved.items);
+ const items = approved.items.map((page, index) => pageItem(page, opts.expect!, index, index === approved.items.length - 1))
+ .filter(item => afterCursor(item.cursor, after) && !done.has(`${item.source_id}\u0000${item.slug}`));
+ if (!items.length) await clearApprovedSet(engine, { command: 'conversation-labels', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: { already_retired_pages: approved.items.length - items.length },
+ details: { handoff: handoffCommands(approved.items) } };
+ }
+ const facts = await classifyLabelFacts(engine, scope.source_ids);
+ const selected = facts.filter(fact => fact.class === 'evidenced' || fact.class === 'ambiguous' && includeAmbiguous);
+ const pages = new Map<string, LabelPage>();
+ for (const fact of selected) {
+ const key = `${fact.source_id}\u0000${fact.slug}`;
+ let page = pages.get(key);
+ if (!page) {
+ const current = (await engine.getPage(fact.slug, { sourceId: fact.source_id }))!;
+ const decided = await currentOutcome(engine, current);
+ page = { source_id: fact.source_id, slug: fact.slug, page_id: current.id, request_id: '', include_ambiguous: includeAmbiguous, scope: scope.source_ids,
+ facts: [], outcome: decided.reason ? 'non_extractable' : await activeMarker(engine, fact.source_id, fact.slug) ? 'awaiting_reextraction' : 'cleaned',
+ non_extractable_reason: decided.reason, version_token: decided.versionToken, segments: decided.segments };
+ pages.set(key, page);
+ }
+ page.facts.push({ id: fact.id, class: fact.class, reason: fact.reason, fact_hash: fact.fact_hash });
+ }
+ 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]);
+ const hash = previewHash({ kind: 'conversation-labels-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous },
+ facts, pages: [...pages.values()].map(({ request_id: _r, ...page }) => page) });
+ const approved = [...pages.values()].map(page => ({ ...page, request_id: requestIdFor(hash, page, 0) }));
+ if (approved.length) await saveApprovedSet(engine, { command: 'conversation-labels', hash }, approved);
+ const count = (klass: LabelFactClass) => facts.filter(f => f.class === klass).length;
+ const awaiting = approved.filter(p => p.outcome === 'awaiting_reextraction');
+ const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,
+ class: fact.class === 'excluded' ? `excluded:${fact.reason}` : fact.class, detail: DETAILS[fact.reason] ?? fact.reason }));
+ return {
+ items: approved.map((page, index) => pageItem(page, hash, index, index === approved.length - 1)), preview_hash: hash, listing,
+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),
+ non_extractable_pages: approved.filter(p => p.outcome === 'non_extractable').length, awaiting_reextraction_pages: awaiting.length,
+ awaiting_segments: awaiting.reduce((n, p) => n + p.segments, 0) },
+ warnings: ['This command makes no model calls.'],
+ details: { pages: approved.map(({ source_id, slug, outcome, facts: rows, segments, non_extractable_reason }) =>
+ ({ source_id, slug, outcome, facts: rows.length, segments, ...(non_extractable_reason ? { reason: non_extractable_reason } : {}) })),
+ handoff: handoffCommands(approved) },
+ };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, last } = entry as PageItem;
+ const result = await managedPersistenceEnabled(ctx.engine)
+ ? await retireManaged(ctx.engine, ctx.config, page, hash)
+ : await maintenanceTransaction(ctx.engine, async tx => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ return retirePageFacts(tx, page, hash);
+ });
+ if (last) await clearApprovedSet(ctx.engine, { command: 'conversation-labels', hash });
+ if (!result.retired.length) return { applied: false, outcome: 'changed_since_preview', reason: 'every approved fact changed since the preview' };
+ return { applied: true, outcome: result.outcome, detail: { retired: result.retired.length,
+ ...(result.changed.length ? { changed_since_preview: result.changed } : {}) } };
+ },
+ render(details) {
+ const lines: string[] = [];
+ for (const p of (details.pages ?? []) as Array<{ source_id: string; slug: string; outcome: string; facts: number; segments: number; reason?: string }>) {
+ lines.push(` ${p.source_id}:${p.slug}: retire ${p.facts} fact(s); ${p.outcome}${p.reason ? ` (${p.reason}, $0)` : p.outcome === 'awaiting_reextraction' ? ` (${p.segments} segment(s) at the next extraction)` : ''}`);
+ }
+ const handoff = (details.handoff ?? []) as string[];
+ if (handoff.length) {
+ lines.push(' This command makes no model calls. Pages awaiting re-extraction re-enter the ordinary backlog; re-extract them under the extraction cost cap '
+ + '(--max-cost-usd, default $5; or the opt-in cycle.conversation_facts_backfill at $1 per run), previewing first:');
+ for (const command of handoff) lines.push(` ${command}`);
+ }
+ return lines;
+ },
+};
+
+interface RetireResult { retired: number[]; changed: number[]; outcome: LabelPageOutcome }
+
+async function retireManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: LabelPage, hash: string): Promise<RetireResult> {
+ const unchanged: RetireResult = { retired: [], changed: page.facts.map(f => f.id), outcome: page.outcome };
+ 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: CONVERSATION_LABELS_INTENT, expected_revision: snapshot.revision, preview_hash: hash, page }, requestId);
+ }
+ return { retired: (receipt.retired as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [],
+ outcome: (receipt.page_outcome as LabelPageOutcome | undefined) ?? page.outcome };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return unchanged;
+ throw error;
+ }
+ }
+}
+
+/**
+ * Under the page lock: expire the approved facts still exactly as previewed,
+ * then the page's completion marker, then write the not-extractable outcome
+ * when the page is still at the parser input the preview decided it for.
+ */
+async function retirePageFacts(tx: BrainEngine, page: LabelPage, hash: string): Promise<RetireResult> {
+ 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 classifyLabelFacts(tx, [page.source_id], { slug: page.slug })).map(f => [f.id, f]));
+ const current = await tx.getPage(page.slug, { sourceId: page.source_id });
+ const result: RetireResult = { retired: [], changed: [], outcome: page.outcome };
+ const marker = `${LABEL_RETIRED_MARKER} ${hash.slice(0, 12)}`;
+ for (const approved of page.facts) {
+ const now = live.get(approved.id);
+ const same = !!current && current.id === page.page_id && !!now && now.class === approved.class && now.fact_hash === approved.fact_hash;
+ const updated = same ? await tx.executeRaw(`UPDATE facts SET expired_at=now(), context=concat_ws(' | ', NULLIF(context, ''), $3::text)
+ WHERE source_id=$1 AND id=$2 AND expired_at IS NULL RETURNING id`, [page.source_id, approved.id, marker]) : [];
+ if (updated.length) result.retired.push(approved.id); else result.changed.push(approved.id);
+ }
+ if (!result.retired.length || !current) return result;
+ await tx.executeRaw(`UPDATE facts SET expired_at=now() WHERE source_id=$1 AND source_markdown_slug=$2 AND source IN ($3,$4) AND expired_at IS NULL`,
+ [page.source_id, page.slug, TERMINAL_AUDIT_SOURCE, LEGACY_TERMINAL_AUDIT_SOURCE]);
+ if (page.outcome !== 'non_extractable') return result;
+ const decided = await currentOutcome(tx, current);
+ if (!decided.reason || decided.versionToken !== page.version_token) return { ...result, outcome: 'awaiting_reextraction' };
+ await tx.executeRaw(`UPDATE facts SET expired_at=now() WHERE source_id=$1 AND source_markdown_slug=$2 AND source=$3 AND expired_at IS NULL`,
+ [page.source_id, page.slug, NON_EXTRACTABLE_AUDIT_SOURCE]);
+ const [top] = await tx.executeRaw<{ n: number | string | null }>('SELECT max(row_num) AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [page.source_id, page.slug]);
+ const outcome: NewFact & { row_num: number; source_markdown_slug: string } = { fact: 'EXTRACTION_NOT_APPLICABLE', kind: 'fact', entity_slug: null,
+ source: NON_EXTRACTABLE_AUDIT_SOURCE, source_session: `${NON_EXTRACTABLE_AUDIT_SOURCE}:${page.slug}:${decided.versionToken}`, confidence: 1.0, notability: 'low',
+ context: stampExtractorVersion(`scanned, not extractable: ${decided.reason}`), row_num: top?.n == null ? 0 : Number(top.n) + 1, source_markdown_slug: page.slug };
+ const { inserted } = await tx.insertFacts([outcome], { source_id: page.source_id }); // gbrain-allow-direct-insert: the durable not-extractable outcome a label repair writes under the page lock (inside its receipted publication on a managed brain)
+ if (inserted !== 1) throw opError('storage_error', 'The not-extractable outcome was not written; nothing on the page changed.',
+ `The repair of ${page.slug} in source ${page.source_id} could not insert its not-extractable outcome, so the transaction rolled back. Preview the repair again.`,
+ { fix: previewFix(page.source_id) });
+ return result;
+}
+
+/** Preparer for `managed_maintenance_conversation_label_retire`: a database-only publication on the page key. */
+export async function prepareConversationLabelRetirement(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const intent = row.intent as { page?: LabelPage; 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 opError('invalid_params', 'The conversation-labels intent does not name its page.',
+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the page and preview it retires, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,
+ { fix: previewFix(row.source_id) });
+ }
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) {
+ throw opError('page_identity_changed', 'The conversation page was deleted or replaced before its label facts were retired.',
+ `Conversation page ${row.slug} in source ${row.source_id} was deleted or replaced after the preview, so request ${row.request_id} retired nothing. Preview the repair again.`,
+ { fix: previewFix(row.source_id) });
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ const hash = intent!.preview_hash as string;
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const result = await retirePageFacts(tx, page, hash);
+ return { status: 'completed', preview_hash: hash, retired: result.retired, changed_since_preview: result.changed, page_outcome: result.outcome };
+ } };
+}
+
+/** Doctor's bounded count of the default (evidenced) set: the classification's exclusions applied in SQL, capped. */
+export async function countLabelFacts(db: BrainEngine, sourceIds: string[], cap: number): Promise<{ count: number; capped: boolean }> {
+ const rows = await db.executeRaw<{ id: number }>(`SELECT f.id FROM facts f
+ JOIN pages p ON p.source_id=f.source_id AND p.slug=f.source_markdown_slug AND p.deleted_at IS NULL
+ WHERE f.source_id=ANY($1::text[]) AND f.source LIKE 'cli:extract-conversation-facts%' AND f.source=$2 AND f.expired_at IS NULL
+ AND f.context LIKE $3 AND (p.compiled_truth ~* $4 OR COALESCE(p.timeline,'') ~* $4)
+ AND NOT EXISTS (SELECT 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=f.source_markdown_slug
+ AND o.source IN ($6, $7) AND o.expired_at IS NULL AND o.context ~ 'extractor_version=[0-9]+$')
+ AND f.superseded_by IS NULL AND NOT EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id)
+ AND NOT EXISTS (SELECT 1 FROM open_loops l WHERE l.fact_id=f.id)
+ AND NOT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact)) AND (w.subject='*' OR w.subject=f.entity_slug))
+ LIMIT $5`, [sourceIds, SEGMENT_SOURCE, `%${EPOCH_SEGMENT_MARKER}%`, LABEL_LINE_SQL, cap + 1, TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);
+ return { count: Math.min(rows.length, cap), capped: rows.length > cap };
+}
+
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 3fc6c02bc5..ce623e3afb 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -24,7 +24,7 @@ import { initializeLocalPersistence, requestPrincipalForContext } from '../persi
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
import { shellQuote } from '../agent-output.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.ts
index d7e7b1532f..5e711c8006 100644
--- a/src/core/repair/extractor-facts.ts
+++ b/src/core/repair/extractor-facts.ts
@@ -9,7 +9,8 @@
* 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
+ * `expired_at` set, `row_num` NULL (the projection's signature), and not
+ * retired by `gbrain repair conversation-labels` (its context marker). 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
@@ -129,6 +130,7 @@ export async function classifyExtractorFacts(db: BrainEngine, sourceIds: string[
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 COALESCE(f.context, '') NOT LIKE '%retired: conversation-labels%'
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,
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index b026a20b0c..7c3ccc8b59 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -35,6 +35,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 { conversationLabelsRepair } from './conversation-labels.ts';
import { capturedFactsRepair } from './captured-facts.ts';
import { loopFactsRepair } from './loop-facts.ts';
import { orphanChildrenRepair } from './orphan-children.ts';
@@ -56,8 +57,10 @@ export interface RepairKindSpec {
checks: string[];
/** Runs only when named on the command line; never from `--all`, the remediation plan or a supplied step. */
explicit_only?: true;
- /** `destructive`: the apply rewrites user files, so it also needs the user's consent (`--yes` with the preview hash, or a terminal prompt). */
+ /** `destructive`: the apply rewrites user files or retires stored rows, so it also needs the user's consent (`--yes` with the preview hash, or a terminal prompt). */
consent?: 'destructive';
+ /** The consent payload's wording for a destructive kind: what the apply does and how to undo it (default: the frontmatter file rewrite). */
+ consentText?: { what: string; why: string; risk: string; user_message: string };
}
const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
@@ -140,6 +143,21 @@ 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.',
},
+ 'conversation-labels': {
+ handler: conversationLabelsRepair, embeds: 'none', checks: ['conversation_label_facts'], explicit_only: true, consent: 'destructive',
+ consentText: {
+ what: 'Retire the previewed label-misattributed conversation facts in the database',
+ why: 'The preview listed each fact; applying it expires exactly those rows (and the page completion markers they invalidate), with no model calls.',
+ risk: 'Database rows only: no page or file changes. Retired facts are expired, not deleted, and keep "retired: conversation-labels" in their context; '
+ + 'recall stops returning them. Re-extracting a page writes fresh facts (gbrain extract-conversation-facts --slugs <page> --dry-run, then with --max-cost-usd).',
+ user_message: 'Retire the previewed label-misattributed conversation facts? They stop appearing in recall; the rows are expired, not deleted, and nothing calls a model.',
+ },
+ summary: 'Retire conversation facts the pre-v0.60.69 parser attributed to meeting-note labels (**Date:**, **Attendees:**, …) instead of speakers. '
+ + 'Default set: facts whose context names a 1970-01-01 segment, which only that parser wrote; --include-ambiguous adds the other extractor facts of '
+ + 'label pages, listed fact by fact. Preview-bound and destructive: --apply --expect <hash> --yes expires exactly the previewed rows, expires the '
+ + 'page completion marker and writes the not-extractable outcome for prose or undated pages. No model calls; the other pages re-enter the '
+ + 'extraction backlog and the preview prints the capped re-extract commands. Withdrawn, superseded and referenced facts are kept.',
+ },
'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 '
diff --git a/test/conversation-facts-retained-history.test.ts b/test/conversation-facts-retained-history.test.ts
new file mode 100644
index 0000000000..73c66e1374
--- /dev/null
+++ b/test/conversation-facts-retained-history.test.ts
@@ -0,0 +1,83 @@
+/**
+ * Wave 9 follow-ups, item 2 (lifecycle half): the conversation extractor's
+ * own bookkeeping no longer undoes a label repair.
+ *
+ * Protects: an expired completion marker does not keep a page "complete"
+ * (the completion query reads active outcomes only); a replacement batch
+ * expires, never deletes, a row an open loop or another fact's
+ * superseded_by references, and keeps rows a label repair retired; and the
+ * hand-off flag `--slugs` selects exactly the named pages. Unmanaged PGLite,
+ * injected extractor (no gateway).
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { TERMINAL_AUDIT_SOURCE } from '../src/core/facts/audit-sources.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const SLUG = 'meetings/2026-09-28-sync';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+async function brain(run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ await engine.putPage(SLUG, { type: 'meeting', title: 'Sync', frontmatter: { date: '2026-09-28' }, compiled_truth:
+ '**Alice Example:** Can you send the plan?\n**Bob Example:** Yes, on Thursday.\n**Alice Example:** Thanks, I review on Mondays.' });
+ await run(engine);
+}
+
+const extract = (engine: BrainEngine, calls: { n: number }) => runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0,
+ overrideDisabled: true, extractor: async () => { calls.n++; return [{ fact: 'Bob Example sends the plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null, source: 'x' }]; } });
+
+test('an expired completion marker does not keep the page complete', async () => {
+ await brain(async engine => {
+ const calls = { n: 0 };
+ await extract(engine, calls);
+ expect((await extract(engine, calls)).pages_skipped_completed).toBe(1);
+ await engine.executeRaw('UPDATE facts SET expired_at=now() WHERE source=$1', [TERMINAL_AUDIT_SOURCE]);
+ const rerun = await extract(engine, calls);
+ expect(rerun).toMatchObject({ pages_processed: 1, pages_skipped_completed: 0 });
+ expect(calls.n).toBe(2);
+ });
+});
+
+test('a replacement keeps referenced and label-retired rows as expired history', async () => {
+ await brain(async engine => {
+ const calls = { n: 0 };
+ await extract(engine, calls);
+ const [first] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE source='cli:extract-conversation-facts' ORDER BY id LIMIT 1");
+ await engine.executeRaw(`INSERT INTO open_loops (source_id, dedup_key, loop_type, summary, detector, fact_id)
+ VALUES ('default', 'k', 'commitment_owed_by_me', 'Send the plan', 'manual', $1)`, [first!.id]);
+ const [retired] = await engine.insertFacts([{ fact: 'Date said Thursday', kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts',
+ context: 'from x segment 1970-01-01T00:00:00Z.. | retired: conversation-labels abc', expired_at: new Date(), row_num: 50, source_markdown_slug: SLUG }],
+ { source_id: 'default' }).then(r => r.ids);
+ const run = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0, overrideDisabled: true, force: true,
+ extractor: async () => [{ fact: 'Bob Example sends the plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null, source: 'x' }] });
+ expect(run).toMatchObject({ pages_processed: 1, facts_inserted: 1 });
+ const kept = await engine.executeRaw<{ id: number; expired: boolean }>('SELECT id, expired_at IS NOT NULL AS expired FROM facts WHERE id=ANY($1::bigint[]) ORDER BY id',
+ [[first!.id, retired!]]);
+ expect(kept.map(r => [Number(r.id), r.expired])).toEqual([[Number(first!.id), true], [Number(retired), true]]);
+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL
+ AND source='cli:extract-conversation-facts'`, [SLUG]);
+ expect(n).toBe(1);
+ });
+});
+
+test('--slugs selects exactly the named pages', async () => {
+ const { parseArgs } = await import('../src/commands/extract-conversation-facts.ts') as unknown as { parseArgs: (args: string[]) => Record<string, unknown> };
+ expect(parseArgs(['--source-id', 'default', '--slugs', 'meetings/a,meetings/b', '--dry-run'])).toMatchObject({ slugs: ['meetings/a', 'meetings/b'], dryRun: true });
+});
diff --git a/test/e2e/repair-conversation-labels-postgres.test.ts b/test/e2e/repair-conversation-labels-postgres.test.ts
new file mode 100644
index 0000000000..9a112a52f7
--- /dev/null
+++ b/test/e2e/repair-conversation-labels-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-conversation-labels.test.ts'));
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 90fbd29064..5b44785925 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -883,6 +883,33 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "evidenced": 0,
+ "repair": "conversation-labels"
+ },
+ "message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
+ "name": "conversation_label_facts",
+ "status": "ok"
+ },
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "extractor_version": 1,
+ "sample": [],
+ "scanned": 0,
+ "stale": 0,
+ "unstamped": 0
+ },
+ "message": "No conversation extraction outcome predates extractor version 1.",
+ "name": "conversation_outcomes_stale",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 25392ee55a..d9fcca456d 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -971,6 +971,33 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "evidenced": 0,
+ "repair": "conversation-labels"
+ },
+ "message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
+ "name": "conversation_label_facts",
+ "status": "ok"
+ },
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "extractor_version": 1,
+ "sample": [],
+ "scanned": 0,
+ "stale": 0,
+ "unstamped": 0
+ },
+ "message": "No conversation extraction outcome predates extractor version 1.",
+ "name": "conversation_outcomes_stale",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 28a76eba59..3584c627a4 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -964,6 +964,33 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "evidenced": 0,
+ "repair": "conversation-labels"
+ },
+ "message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
+ "name": "conversation_label_facts",
+ "status": "ok"
+ },
+ {
+ "category": "brain",
+ "details": {
+ "capped": false,
+ "docs": "docs/guides/repair.md#conversation-labels",
+ "extractor_version": 1,
+ "sample": [],
+ "scanned": 0,
+ "stale": 0,
+ "unstamped": 0
+ },
+ "message": "No conversation extraction outcome predates extractor version 1.",
+ "name": "conversation_outcomes_stale",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index e3dc166564..9f83787217 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -433,6 +433,14 @@
"category": "brain",
"name": "extractor_facts_expired"
},
+ {
+ "category": "brain",
+ "name": "conversation_label_facts"
+ },
+ {
+ "category": "brain",
+ "name": "conversation_outcomes_stale"
+ },
{
"category": "brain",
"name": "captured_facts_active"
diff --git a/test/repair-conversation-labels.test.ts b/test/repair-conversation-labels.test.ts
new file mode 100644
index 0000000000..c60babfd35
--- /dev/null
+++ b/test/repair-conversation-labels.test.ts
@@ -0,0 +1,218 @@
+/**
+ * `gbrain repair conversation-labels` (wave 9 follow-ups, item 2), on PGLite
+ * and, with a safe DATABASE_URL, Postgres
+ * (test/e2e/repair-conversation-labels-postgres.test.ts).
+ *
+ * Protects: facts the pre-v0.60.69 parser extracted from meeting-note labels
+ * read as speakers are retired only by a previewed, hash-bound, consented
+ * apply that makes no model calls: the epoch-segment rows by default, every
+ * other label-page row only with --include-ambiguous; excluded rows
+ * (withdrawn, superseded, referenced by superseded_by or an open loop, pages
+ * the fixed extractor already scanned) stay active. The apply expires the
+ * approved rows and the completion marker, writes the not-extractable outcome
+ * for a prose page, and leaves a dated transcript in the extraction backlog
+ * with hand-off commands the extraction CLI parses. The chain repair →
+ * ordinary extraction → orphan cleanup → extractor-facts repair never
+ * deletes or restores a retired or excluded row. A managed brain publishes
+ * one receipted request per page. Without consent a non-interactive apply
+ * exits 3 and changes nothing; a wrong hash refuses with preview_changed; a
+ * live serve's lock refusal names stop → repair → restart.
+ * Seams: pre-fix rows are seeded with the extractor's provenance (no
+ * gateway), extraction runs the Core with an injected extractor.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { currentConversationVersionToken, parseArgs as parseExtractArgs, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { CONVERSATION_LABELS_INTENT, EPOCH_SEGMENT_MARKER } from '../src/core/repair/conversation-labels.ts';
+import { classifyExtractorFacts } from '../src/core/repair/extractor-facts.ts';
+import { conversationLabelFactsCheck } from '../src/commands/doctor/checks/conversation-outcomes.ts';
+import { NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, outcomeExtractorVersion, stampExtractorVersion } from '../src/core/facts/audit-sources.ts';
+import { LiveServeLockError } from '../src/core/pglite-lock.ts';
+import { exclusiveFix, liveServeOwner } from '../src/core/exclusive-fix.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SEGMENT = 'cli:extract-conversation-facts';
+const PROSE = 'meetings/prose-notes';
+const DATED = 'meetings/dated-sync';
+const FIXED = 'meetings/fixed-notes';
+const epoch = (slug: string) => `from ${slug} ${EPOCH_SEGMENT_MARKER}T00:00:00Z..1970-01-01T00:00:00Z`;
+
+interface Seeded { evidenced: number[]; ambiguous: number[]; excluded: number[]; referencedBy: number; openLoop: number }
+
+async function insert(engine: BrainEngine, slug: string, rows: Array<{ fact: string; context?: string | null; source?: string; session?: string; superseded_by_row?: number }>, start = 0): Promise<number[]> {
+ const { ids } = await engine.insertFacts(rows.map((row, i) => ({ fact: row.fact, kind: 'fact' as const, entity_slug: null, visibility: 'private' as const,
+ notability: 'medium' as const, confidence: 1, source: row.source ?? SEGMENT, source_session: row.session ?? `${SEGMENT}:${slug}`, context: row.context ?? null,
+ row_num: start + i, source_markdown_slug: slug })), { source_id: 'default' });
+ return ids;
+}
+
+/** Pre-fix extractions as `extract-conversation-facts` left them before the parser fix (plus one page the fixed extractor scanned). */
+async function seed(engine: BrainEngine): Promise<Seeded> {
+ await engine.putPage(PROSE, { type: 'meeting', title: 'Planning notes', compiled_truth:
+ '**Date:** 2026-09-28\n**Attendees:** Alice Example, Bob Example\n\n## Notes\nWe went through hiring and the launch dates.\n\n## Action items\n- Bob sends the plan.' });
+ await engine.putPage(DATED, { type: 'meeting', title: 'Dated sync', frontmatter: { date: '2026-09-28' }, compiled_truth:
+ '**Date:** 2026-09-28\n**Attendees:** Alice Example, Bob Example\n\n**Alice Example:** Can you send the quarterly plan?\n**Bob Example:** Yes, on Thursday.\n**Alice Example:** Great, I review on Mondays.' });
+ await engine.putPage(FIXED, { type: 'meeting', title: 'Fixed notes', compiled_truth: '**Date:** 2026-09-28\n**Attendees:** Alice Example\n\nNotes only.' });
+ const prose = await insert(engine, PROSE, [{ fact: 'Date said the review is on Monday', context: epoch(PROSE) },
+ { fact: 'Attendees said hiring is open', context: epoch(PROSE) }, { fact: 'The launch moved to Q4', context: 'from the planning notes' },
+ { fact: 'EXTRACTION_COMPLETE', source: TERMINAL_AUDIT_SOURCE, session: `${TERMINAL_AUDIT_SOURCE}:${PROSE}:page-old` }]);
+ const dated = await insert(engine, DATED, [{ fact: 'Date said the plan is due Thursday', context: epoch(DATED) },
+ { fact: 'Bob Example sends the quarterly plan on Thursday', context: `from ${DATED} segment 2026-09-28T00:00:00Z..2026-09-28T00:00:00Z` },
+ { fact: 'Attendees said Monday reviews', context: epoch(DATED) }, { fact: 'Summary said plans slip', context: epoch(DATED) },
+ { fact: 'EXTRACTION_COMPLETE', source: TERMINAL_AUDIT_SOURCE, session: `${TERMINAL_AUDIT_SOURCE}:${DATED}:page-old` }]);
+ // A remembered fact whose superseded_by names one label row; an open loop that points at another.
+ const [newer] = await engine.insertFacts([{ fact: 'Reviews moved to Tuesdays', kind: 'fact', entity_slug: null, visibility: 'private', source: 'mcp:remember',
+ row_num: 100, source_markdown_slug: DATED }], { source_id: 'default' }).then(r => r.ids);
+ await engine.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [dated[2], newer]);
+ await engine.executeRaw(`INSERT INTO open_loops (source_id, dedup_key, loop_type, summary, detector, fact_id)
+ VALUES ('default', 'label-loop', 'commitment_owed_by_me', 'Summary follow-up', 'manual', $1)`, [dated[3]]);
+ const token = await currentConversationVersionToken(engine, (await engine.getPage(FIXED, { sourceId: 'default' }))!);
+ const fixed = await insert(engine, FIXED, [{ fact: 'Date said notes only', context: epoch(FIXED) },
+ { fact: 'EXTRACTION_NOT_APPLICABLE', source: NON_EXTRACTABLE_AUDIT_SOURCE, session: `${NON_EXTRACTABLE_AUDIT_SOURCE}:${FIXED}:${token}`,
+ context: stampExtractorVersion('scanned, not extractable: prose') }]);
+ return { evidenced: [prose[0]!, prose[1]!, dated[0]!], ambiguous: [prose[2]!, dated[1]!], excluded: [dated[2]!, dated[3]!, fixed[0]!],
+ referencedBy: dated[2]!, openLoop: dated[3]! };
+}
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; warnings?: string[];
+ listing?: Array<{ item: string; class: string }>; outcomes?: Record<string, number>; details?: { handoff?: string[]; pages?: Array<{ slug: string; outcome: string }> } }> }
+
+async function capture(run: () => Promise<unknown>): Promise<{ out: string; exitCode: number | string | undefined }> {
+ const lines: string[] = [];
+ const { log, error } = console;
+ const stdout = process.stdout.write.bind(process.stdout);
+ const previous = process.exitCode;
+ process.exitCode = 0;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ console.error = () => {};
+ process.stdout.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stdout.write;
+ try { await run(); return { out: lines.join('\n'), exitCode: process.exitCode }; }
+ finally { console.log = log; console.error = error; process.stdout.write = stdout; process.exitCode = previous; }
+}
+async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {
+ const { out } = await capture(() => runRepairCommand(engine, ['conversation-labels', ...args, '--json']));
+ return JSON.parse(out) as RepairJson;
+}
+const hashOf = (json: RepairJson) => json.results[0]!.apply_command.match(/--expect ([0-9a-f]+)/)![1]!;
+const active = async (engine: BrainEngine, ids: number[]) => (await engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE id=ANY($1::bigint[]) AND expired_at IS NULL ORDER BY id', [ids])).map(r => Number(r.id));
+const existing = async (engine: BrainEngine, ids: number[]) => (await engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE id=ANY($1::bigint[]) ORDER BY id', [ids])).map(r => Number(r.id));
+const sorted = (ids: number[]) => [...ids].sort((a, b) => a - b);
+
+async function exercise(engine: BrainEngine, managed: boolean, seeded: Seeded): Promise<void> {
+ expect((await conversationLabelFactsCheck(engine, ['default'])).details).toMatchObject({ evidenced: 3 });
+ const preview = await repair(engine, []);
+ const result = preview.results[0]!;
+ expect(result.residuals).toMatchObject({ evidenced: 3, ambiguous: 2, excluded: 3, non_extractable_pages: 1, awaiting_reextraction_pages: 1 });
+ expect(result.warnings).toContain('This command makes no model calls.');
+ expect(result.listing!.filter(l => l.class.startsWith('excluded:')).map(l => l.class).sort())
+ .toEqual(['excluded:current_extractor', 'excluded:open_loop_reference', 'excluded:superseded_by_reference']);
+ expect(result.details!.pages!.map(p => [p.slug, p.outcome]).sort()).toEqual([[DATED, 'awaiting_reextraction'], [PROSE, 'non_extractable']]);
+ // Every printed hand-off parses with the extraction command's own parser and names exactly the awaiting page.
+ const handoff = result.details!.handoff!;
+ expect(handoff).toHaveLength(2);
+ for (const command of handoff) {
+ const argv = command.replace('<n>', '1').split(' ');
+ expect(argv.slice(0, 2)).toEqual(['gbrain', 'extract-conversation-facts']);
+ const parsed = parseExtractArgs(argv.slice(2));
+ expect(parsed.error).toBeUndefined();
+ expect(parsed).toMatchObject({ sourceId: 'default', slugs: [DATED] });
+ }
+ const hash = hashOf(preview);
+ // Wrong hash: preview_changed, nothing changes.
+ const wrong = await capture(() => runRepairCommand(engine, ['conversation-labels', '--apply', '--expect', 'f'.repeat(64), '--yes', '--json']))
+ .then(r => r.out, (e: Error & { code?: string }) => e.code);
+ expect(wrong).toBe('preview_changed');
+ // Unapproved non-interactive apply: exit 3 with the database-row consent payload, nothing changes.
+ const refused = await capture(() => runRepairCommand(engine, ['conversation-labels', '--apply', '--expect', hash, '--json']));
+ expect(refused.exitCode).toBe(3);
+ const payload = JSON.parse(refused.out);
+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['destructive'] });
+ expect(JSON.stringify(payload)).toContain('expired, not deleted');
+ expect(JSON.stringify(payload)).not.toMatch(/git revert|backups\/frontmatter/);
+ expect(await active(engine, seeded.evidenced)).toEqual(sorted(seeded.evidenced));
+ // Approved apply: no model call, approved rows expired with the marker, markers expired, prose outcome written.
+ const applied = await repair(engine, ['--apply', '--expect', hash, '--yes']);
+ expect(applied.results[0]!.outcomes).toEqual({ non_extractable: 1, awaiting_reextraction: 1 });
+ expect(await active(engine, seeded.evidenced)).toEqual([]);
+ expect(await active(engine, [...seeded.ambiguous, ...seeded.excluded])).toEqual(sorted([...seeded.ambiguous, ...seeded.excluded]));
+ const [retired] = await engine.executeRaw<{ context: string }>('SELECT context FROM facts WHERE id=$1', [seeded.evidenced[0]]);
+ expect(retired!.context).toContain('retired: conversation-labels');
+ const outcomes = await engine.executeRaw<{ slug: string; fact: string; context: string | null }>(`SELECT source_markdown_slug AS slug, fact, context FROM facts
+ WHERE source_id='default' AND source IN ($1,$2) AND expired_at IS NULL ORDER BY slug`, [TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);
+ expect(outcomes.map(o => [o.slug, o.fact])).toEqual([[FIXED, 'EXTRACTION_NOT_APPLICABLE'], [PROSE, 'EXTRACTION_NOT_APPLICABLE']]);
+ expect(outcomeExtractorVersion(outcomes[1]!.context)).toBe(1);
+ if (managed) {
+ const requests = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE intent->>'kind'=$1", [CONVERSATION_LABELS_INTENT]);
+ expect(requests.map(r => r.state)).toEqual(['committed', 'committed']);
+ }
+ expect((await conversationLabelFactsCheck(engine, ['default'])).status).toBe('ok');
+ // Lifecycle: ordinary extraction re-extracts only the dated page; replacement keeps retired and referenced rows.
+ let calls = 0;
+ const run = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [PROSE, DATED, FIXED], sleepMs: 0, overrideDisabled: true,
+ extractor: async () => { calls++; return [{ fact: 'Bob Example sends the quarterly plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null, source: 'x' }]; } });
+ expect(calls).toBe(1);
+ expect(run).toMatchObject({ pages_processed: 1, pages_skipped_non_extractable: 2, pages_failed: 0 });
+ const kept = [...seeded.evidenced, ...seeded.excluded];
+ expect(await existing(engine, kept)).toEqual(sorted(kept));
+ expect(await active(engine, [seeded.openLoop, seeded.referencedBy])).toEqual([]);
+ // extractor-facts never restores a retired row.
+ const restorable = await classifyExtractorFacts(engine, ['default'], { managed });
+ expect(restorable.filter(f => kept.includes(f.id))).toEqual([]);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: managed brain: preview, consent, approved expiry and the lifecycle chain`, async () => {
+ let seeded!: Seeded;
+ await managedBrain(async ({ engine }) => exercise(engine, true, seeded), { databaseUrl, setup: async ({ engine }) => { seeded = await seed(engine); } });
+ }, 180_000);
+}
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+test('pglite: unmanaged brain: the same preview, consent and expiry, written under the page lock', async () => {
+ await exercise(engine, false, await seed(engine));
+}, 180_000);
+
+test('--include-ambiguous widens the hashed set to every label-page row', async () => {
+ const seeded = await seed(engine);
+ const preview = await repair(engine, ['--include-ambiguous']);
+ expect(preview.results[0]!.apply_command).toContain('--include-ambiguous');
+ const mismatched = await capture(() => runRepairCommand(engine, ['conversation-labels', '--apply', '--expect', hashOf(preview), '--yes', '--json']))
+ .then(r => r.out, (e: Error & { code?: string }) => e.code);
+ expect(mismatched).toBe('preview_changed');
+ await repair(engine, ['--include-ambiguous', '--apply', '--expect', hashOf(preview), '--yes']);
+ expect(await active(engine, [...seeded.evidenced, ...seeded.ambiguous])).toEqual([]);
+ expect(await active(engine, seeded.excluded)).toEqual(sorted(seeded.excluded));
+}, 180_000);
+
+test('under a live serve the refusal names stop → repair → restart', () => {
+ // acquireLock throws LiveServeLockError at once for a live serve holder (no 30 s wait);
+ // the fatal CLI seam wraps the rerun in this two-step plan.
+ const error = new LiveServeLockError('GBrain\'s local database is already open through `gbrain serve`.', { pid: 4242, transport: 'stdio' });
+ const argv = ['gbrain', 'repair', 'conversation-labels', '--apply', '--expect', 'abc', '--yes', '--json'];
+ const fix = exclusiveFix({ argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'Re-runs this command once it has the brain to itself.' }, liveServeOwner(error));
+ expect(fix).toMatchObject({ argv: ['kill', '4242'], actor: 'user', then: { argv } });
+ expect(fix.why).toContain('Reopen the agent session');
+});
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 3dbaec1fac..58edb6e371 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', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
@@ -109,7 +109,7 @@ describe('surfaces that list instead of run', () => {
expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,
docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));
}
- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair extractor-facts; gbrain repair captured-facts; gbrain repair loop-facts');
+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair loop-facts');
});
test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {