Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): collapse identical facts in recall and search, skip copies in conversation extraction, duplicate-facts repair, backfill source exclude (#7043)

garrytanb5cabb862ec0
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index dac5445d2d..9d1a37d173 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -226,6 +226,7 @@ src/core/repair/redacted-facts.ts 1 coordinator `gbrain repair redacted-facts` (
src/core/repair/ontology-facts.ts 1 coordinator `gbrain repair ontology-facts` (#6264) gives preview-approved ontology observations their own provenance back, clears their fence row number and expiry. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the ontology_propose path: write authority checked, source incarnation revalidated, entity and page keys locked); an unmanaged brain runs it in one maintenance transaction. It writes database-only ontology rows and never a page or file.
src/core/repair/facts-rehome.ts 1 coordinator `gbrain repair facts-rehome` (B-7, #6925) moves preview-approved database-only facts off a page-less entity_slug onto the page the strict resolver reaches. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, both slugs locked); an unmanaged brain runs one maintenance transaction per slug. It rechecks the slug, target and fact ids against the preview and never writes a page or file.
src/core/repair/consolidate-ties.ts 1 coordinator `gbrain repair consolidate-ties` (#6023) sets preview-approved typed facts that consolidation closed at their own effective instant back to open validity. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity key locked); an unmanaged brain runs one maintenance transaction per fact. It rechecks the fact, take and instant against the preview and never writes a page or file.
+src/core/repair/duplicate-facts.ts 2 coordinator `gbrain repair duplicate-facts` (#7043) supersedes preview-approved copies of one active fact (expired_at and superseded_by pointing at the kept oldest row). On a managed brain each UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity keys locked); an unmanaged brain runs one maintenanceTransaction per group. A fenced copy is first struck in its page through a revision-bound put_page (submitPageMutation), and its superseded_by link is written after that page write. It rechecks every row against the preview and never deletes a row.
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 batch of up to 25 pages on a managed brain (the preparer reclassifies each page under its lock), one maintenanceTransaction per batch 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.
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 4aae717c4a..6b293739a5 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -29,6 +29,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` under a body ledger, here `exportBodyLedger`, the same withdrawal overlay; `restore_page` of a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). `exportPagePath` writes a page whose slug is not a portable file name under an escaped name with its `slug:` line (`:` and other Windows-unsafe characters become `~`, a reserved device name or trailing dot/space gets `~` appended, an over-budget segment is cut with a `~<8 hex>` hash and marked not restorable); `runExport` returns an `ExportReport`, prints the escaped pages, and collects every `ExportPathCollision` into one refusal whose lines name each fix (`test/pathological/b5-export-unsafe-slugs.test.ts`). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.
-- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`; a segmented page is read in ranges; one over `CONVERSATION_WINDOW_BYTES` with no conversation facts is extracted from its newest window (day-header date, `tail_window` receipt, `window_rule: no_prior_facts`); one with facts is skipped with nothing cleared (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears prior facts the window may not see, until PR 4's window anchors (test `test/large-pages/segmented-conversation-facts.test.ts`)); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). A page's rows are buffered and published once after its last segment (`publishPageFacts` on an unmanaged brain, one `writeDerivedFacts` transaction; the managed batch otherwise), through `publishConversationFacts` (facts/conversation-publication.ts), so a crashed, failed, empty or partial run never removes the prior batch and a terminal audit row commits only with its page's facts (#7013); a run's `scope` is `partial` when fewer segments than in scope ran, `window` when `--since` dropped messages, else `full`, and a page that changed mid-run keeps an unmanaged run's facts as a `partial` batch. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, replay replacing a prior partial run's facts, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Each page's own entities go to the extractor as `entityHints` (slugs, `src/core/facts/conversation-entity-hints.ts`, computed once per page, cap `CONVERSATION_ENTITY_HINTS_CAP` = 40 through `ExtractInput.entityHintsCap`): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; the `extract_facts` op keeps its 5-hint cap and prompt. Pinned by `test/conversation-entity-hints.test.ts`. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then published in its receipted batch after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).
+- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`; a segmented page is read in ranges; one over `CONVERSATION_WINDOW_BYTES` with no conversation facts is extracted from its newest window (day-header date, `tail_window` receipt, `window_rule: no_prior_facts`); one with facts is skipped with nothing cleared (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears prior facts the window may not see, until PR 4's window anchors (test `test/large-pages/segmented-conversation-facts.test.ts`)); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. `publishConversationFacts` skips a non-outcome row an active conversation fact of the source already states (`findCaptureDuplicate`, no time bound; `duplicates_skipped`, #7043). The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source except `cycle.conversation_facts_backfill.exclude_sources` (reported as `sources_excluded`), and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). A page's rows are buffered and published once after its last segment (`publishPageFacts` on an unmanaged brain, one `writeDerivedFacts` transaction; the managed batch otherwise), through `publishConversationFacts` (facts/conversation-publication.ts), so a crashed, failed, empty or partial run never removes the prior batch and a terminal audit row commits only with its page's facts (#7013); a run's `scope` is `partial` when fewer segments than in scope ran, `window` when `--since` dropped messages, else `full`, and a page that changed mid-run keeps an unmanaged run's facts as a `partial` batch. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, replay replacing a prior partial run's facts, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Each page's own entities go to the extractor as `entityHints` (slugs, `src/core/facts/conversation-entity-hints.ts`, computed once per page, cap `CONVERSATION_ENTITY_HINTS_CAP` = 40 through `ExtractInput.entityHintsCap`): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; the `extract_facts` op keeps its 5-hint cap and prompt. Pinned by `test/conversation-entity-hints.test.ts`. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then published in its receipted batch after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. A lost link or timeline write on the fs walks or the slug-scoped path leaves its pages unstamped and throws `extract_write_lost` after stamping the rest (`core/extract-watermark.ts`); the sync hooks report a page whose link or timeline write failed in `errors`, never `processed`, so the caller leaves it unstamped. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); `extract --stale` replaces through `replaceDerivedLinks`, the db link walk through `replaceDerivedLinksBatch`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--retry-held] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`; failing pages are reported and skipped there, and `--retry-held` clears held ones first) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush (the unmanaged sweep): a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently. `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows). GBRA-133 2b.1: the sync hooks (`extractLinksForSlugs` / `extractTimelineForSlugs`) share one `indexMarkdownTree` walk per run (`src/commands/extract-tree.ts`, with `markdownWalk` behind `walkMarkdownFiles`) (it yields after each directory) and type link endpoints through `withEndpointPageTypes`, which parses only the walked files the pass asks a type for (repeating until nothing new is asked) instead of `loadFsPageTypes` over the whole tree; full `gbrain extract` keeps the whole-tree parse, and the two give the same links (`test/pathological/s-sync-offpath-2b.test.ts`).
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index ffa83e1144..8e6d63643a 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -10,6 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `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/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).
+- `src/core/repair/duplicate-facts.ts` — `gbrain repair duplicate-facts` (#7043), explicit-only and preview-bound (consent `destructive`). `findDuplicateFacts` (read-only) groups active facts by source, visibility, `attributed_to` and `gbrain_fact_fingerprint(fact)`, keeps the oldest row (created_at, id) and classes each group `same_entity` or `cross_entity` (retired only with `--include-cross-entity`). The apply sets `expired_at` and `superseded_by` on database-only copies (`coordinatedDatabaseWrite` with the `relink_facts` operation on a managed brain, one `maintenanceTransaction` per group otherwise) and strikes a fenced copy as `superseded by #N` through a revision-bound `put_page` when the kept row shares its fence; a copy whose kept row is elsewhere is listed as `fence_kept_elsewhere`, one on a segmented page as `segmented_page` (preview and apply). Near duplicates are never touched; a row changed since the preview reports `changed_since_preview`. Tests: `test/repair-duplicate-facts-7043.test.ts` (PGLite and Postgres).
- `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, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). 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`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 10f63a368c..8921fe50d4 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -86,7 +86,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (`slugify`; `slugifySegment` where `slugify` would delete letters; null if empty). Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities. Retired pages (#6898: `canonical: false`, a `superseded_by`/`merged_into` target, or an alias/redirect `status`) never win a guessing arm; exact, basename and alias hits follow `superseded_by` (5 hops, same source, readable, cycle-safe) or stay unresolved. Alias lookup also tries the reference's words joined by space, `-` and `_` (last slug segment, same parent dir). Pinned by `test/entity-resolve-retired-alias-6898.test.ts`.
- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable` for the drain). GBRA-130 C-9: before the drain, on every engine, the phase re-submits dead put_page `facts-absorb` jobs whose failure is retryable (`src/core/facts/dead-absorb-retry.ts`: provider or config class, once extraction is servable, at most hourly per key and `facts.absorb_retry.max_resubmits` times; set in config `facts.absorb_retry.state`); `gbrain facts retry-dead` lists, resets and clears it and doctor `facts_extraction_health` counts it. Test: `test/pathological/c-9-facts-absorb-dead.test.ts`. Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.
-- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only, wave 15 [UC2]) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts it as `would_dedup_same_page` on its result, logs the matched id, cosine and session on stderr, and inserts the fact as before. Its measured false positives (Lisbon→Porto, approved→rejected, email→phone are all counted) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
+- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts (`would_dedup_same_page`) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. `collapseFactReads` (#7043) runs it per source and visibility for recall, entity cards and `saved_facts` before `limit`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 7dd9821163..4d16a9edfe 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -292,6 +292,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/atoms-restore.ts` (3): the unmanaged `gbrain repair atoms-restore` apply archives the retired atom's version, restores it and drops its `retired_by`/`retired_at` stamp in one `maintenanceTransaction`; managed brains publish a `managed_maintenance_restore_reextract_atom` request instead.
- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.
- `src/core/repair/consolidate-ties.ts` (1): `gbrain repair consolidate-ties` reopens facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per fact on unmanaged brains.
+- `src/core/repair/duplicate-facts.ts` (2): `gbrain repair duplicate-facts` supersedes duplicate fact copies inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per group on unmanaged brains; a fenced copy is struck through a revision-bound `put_page` first.
- `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/facts-rehome.ts` (1): `gbrain repair facts-rehome` moves facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per slug on unmanaged brains.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index e5ce5e24b2..0b0fccfc7d 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1834,6 +1834,46 @@ take is not changed: if it holds the wrong statement, decide which one is
current and `gbrain forget` the other. It writes the database only; no page is
rewritten.
+<a id="duplicate-facts"></a>
+### Duplicate facts
+
+Before this release, the same claim could be stored many times: conversation
+fact extraction saved a standing prompt or instruction again for every session
+that repeated it, and recall returned every copy, so a few copies filled the
+`limit` and pushed distinct facts out (#7043, reported by @mikez93). Recall,
+the entity card and search `saved_facts` now collapse copies into one row
+(with `collapsed_count`), and extraction no longer stores a claim an active
+conversation fact of the same source already states. Copies stored before the
+upgrade stay in the database until `gbrain repair duplicate-facts` retires
+them. It is explicit-only and preview-bound, and it never runs on upgrade.
+
+**Say to your agent:** *"Preview the duplicate facts, then retire the copies
+after I agree."* The agent runs `gbrain repair duplicate-facts` and, after you
+agree, the printed apply command.
+
+```bash
+gbrain repair duplicate-facts # preview: one line per group
+gbrain repair duplicate-facts --include-cross-entity # also retire copies on other entities
+gbrain repair duplicate-facts --apply --expect <hash> --yes
+```
+
+A group is the active facts of one source, visibility and speaker whose text
+normalizes to the same fingerprint (the rule `forget` uses: case, punctuation
+and runs of whitespace do not matter). The oldest row is kept; every other copy gets
+`expired_at` and `superseded_by` pointing at it, so it leaves recall but is not
+deleted or withdrawn, and the claim can be saved again. Groups whose copies all
+sit on one entity are `same_entity`. Groups spread over several entities are
+`cross_entity`: they are listed, and retired only with `--include-cross-entity`
+(the kept row keeps its own entity). A copy that is a row of a page's Facts
+table is struck in that page as `superseded by #N` through a revision-bound
+page write when the kept row is in the same table; otherwise it is reported as
+`fence_kept_elsewhere` and kept. A copy in the Facts table of a segmented page
+is reported as `segmented_page` and kept, in the preview and in an apply that
+finds the page segmented since. Near duplicates (different wording) are never
+touched. A row that changed since the preview reports `changed_since_preview`
+and is kept. To keep the backfill from extracting one source at all, set
+`gbrain config set cycle.conversation_facts_backfill.exclude_sources '["source-a"]'`.
+
<a id="failed-writes"></a>
### Failed writes
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 7454770894..f498439ea1 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -45,7 +45,7 @@ src/core/minions/handlers/subagent.ts runSubagentViaGateway 329 seed: W5 baselin
src/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/ops/facts.ts recall.handler 354 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent); +3 W5: recall threads the page-unit ranking cut into its hybrid page arm (logic in search/page-rank-cut.ts; delivery reports it)
+src/core/ops/facts.ts recall.handler 357 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent); +3 W5: recall threads the page-unit ranking cut into its hybrid page arm (logic in search/page-rank-cut.ts; delivery reports it); +3 #7043: copies of one claim collapse before the limit cut (the collapse lives in facts/capture-dedup.ts collapseFactReads) and the row names its entity_slugs/collapsed_count
src/core/ops/search.ts query.handler 338 +5 GBRA-81 item 5 per-stage search timings: the request's SearchTimings and setup-stage binding, the image branch's limit read hoisted out of the timed vector call, and its response stage wrapper (collector logic in search/stage-timings.ts); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget); +1 W5 (#6445): query passes the page-unit ranking cut to hybrid search (logic in search/page-rank-cut.ts), merged with master growth
src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d2c83e752f..23f106a921 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli/main.ts 3018 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SEL
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 692 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts)
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
-src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts)
+src/commands/extract-conversation-facts.ts 2046 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +1 #7043: the duplicates_skipped stderr line (the source-wide duplicate check lives in core/facts/conversation-publication.ts)
src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
src/commands/jobs.ts 667 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts)
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 488c5c068d..da35d27670 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -470,6 +470,8 @@ src/core/repair/connector-fences.ts connectorFencesRepair field STREAM
src/core/repair/connector-fences.ts relocateTimelineFences field STREAM
src/core/repair/conversation-labels.ts classifyLabelFacts sql STREAM
src/core/repair/conversation-labels.ts countLabelFacts sql STREAM
+src/core/repair/duplicate-facts.ts strikeFencedCopies call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read, and its fenced copies stay active (listed as segmented_page)
+src/core/repair/duplicate-facts.ts strikeFencedCopies field INLINE inline pages only: a segmented page returns before the read, and its fenced copies stay active (listed as segmented_page)
src/core/repair/extractor-facts.ts restorePageFacts field STREAM
src/core/repair/extractor-facts.ts restorePageFacts sql STREAM
src/core/repair/fences.ts afterBytes field STREAM
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index c2b45c4570..2dacde56b8 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -32,6 +32,7 @@
"test/company-brain-runtime.test.ts": 37641,
"test/consolidate-same-instant-6023.test.ts": 13798,
"test/conversation-facts-oversized-sidecar.test.ts": 6466,
+ "test/conversation-facts-source-dedup-7043.test.ts": 12000,
"test/cycle/synthesize-concepts-merge.test.ts": 5637,
"test/decide/conflict-proposals-managed.test.ts": 5301,
"test/declared-lineage-visibility.test.ts": 3811,
@@ -352,10 +353,12 @@
"test/purge-global-marker.test.ts": 11325,
"test/purge-missing-cache-6911.test.ts": 11445,
"test/purge-read-surfaces.test.ts": 11610,
+ "test/recall-collapse-duplicates-7043.test.ts": 9000,
"test/recall-page-fill.test.ts": 7056,
"test/receipt-compaction-newest-sync-gbra130.test.ts": 6880,
"test/remediation-manual-only.test.ts": 14638,
"test/repair-apply-pending-6543.test.ts": 51967,
+ "test/repair-duplicate-facts-7043.test.ts": 9000,
"test/repair-embedding-effects.test.ts": 9932,
"test/repair-failed-writes-conflict-6429.test.ts": 9306,
"test/repair-failed-writes-drift-w411.test.ts": 5486,
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 6f264d42ad..8d147dff38 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -641,7 +641,7 @@ function logLockBusyRateLimited(sourceId: string, slug: string): void {
* active batch and the facts inserted.
*/
function publishPageFacts(state: ExtractCoreState, slug: string, rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
- scope: ConversationScope): Promise<{ deleted: number; facts_inserted: number }> {
+ scope: ConversationScope): Promise<{ deleted: number; facts_inserted: number; duplicates_skipped: number }> {
return writeDerivedFacts(state.engine, state.sourceId, slug, db => publishConversationFacts(db, state.sourceId, slug, rows, { scope }));
}
@@ -1135,7 +1135,8 @@ async function processPage(
const published = await publishPageFacts(state, page.slug, pageRows, scope);
state.result.facts_inserted += published.facts_inserted;
state.result.orphan_facts_cleaned += published.deleted;
- if (published.facts_inserted < pageRows.filter(row => row.source !== TERMINAL_AUDIT_SOURCE).length) {
+ if (published.duplicates_skipped) process.stderr.write(`[extract-conversation-facts] ${page.slug}: skipped ${published.duplicates_skipped} fact(s) an active fact of the source already states (#7043)\n`);
+ if (published.facts_inserted + published.duplicates_skipped < pageRows.filter(row => row.source !== TERMINAL_AUDIT_SOURCE).length) {
process.stderr.write(`[extract-conversation-facts] ${page.slug}: kept its prior facts; this ${scope} run's facts were not published over them (#7013)\n`);
}
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 30fb3de4fe..fc7eec7691 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -78,6 +78,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]
gbrain repair uncommitted-deletions --source <id> [--after <page-id>] [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]
gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]
+ gbrain repair duplicate-facts [--source <id>] [--include-cross-entity] [--apply --expect <preview-hash> --yes] [--json]
gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
[--apply --expect <preview-hash> --yes]] [--json]
${REPAIR_CONTENT_HELP}
@@ -103,6 +104,8 @@ Options:
preview printed under this hash. content: one hash per lane kind, comma-separated, in lane order.
--include-ambiguous
Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).
+ --include-cross-entity
+ duplicate-facts: also retire copies that sit on other entities than the kept row (its hash covers them).
--only <path>, --skip <path>
frontmatter, fences, slug-conflicts, content: select source-relative files (repeatable); the hash covers the selection.
file-drift: narrow the selected pages by canonical file path (repeatable; an exact path, or, on file-drift
@@ -137,7 +140,7 @@ Options:
--after <page-id>
uncommitted-deletions: preview the next window, below the next_after page id the previous preview printed;
the hash and the apply command carry it.
- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions --apply: the user agreed
+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions, duplicate-facts --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).
@@ -153,11 +156,12 @@ Pages a sync soft-deleted although Git never held their file (restore before the
A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/guides/repair.md#url-clone-fences.
Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held']);
+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--include-cross-entity', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held']);
const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
+ '--include-cross-entity': ['duplicate-facts'],
'--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
@@ -171,7 +175,7 @@ const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
-interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
+interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; includeCrossEntity: boolean; diff: boolean; yes: boolean;
noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;
held: boolean; side?: string; state?: string;
@@ -207,7 +211,7 @@ function fileDriftKeepRefusal(args: string[], keep: string): OperationError {
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
- const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, includeCrossEntity: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false };
const used = new Set<string>();
const positional: string[] = [];
@@ -231,6 +235,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--all') parsed.all = true;
else if (flag === '--json') parsed.json = true;
else if (flag === '--include-ambiguous') parsed.includeAmbiguous = true;
+ else if (flag === '--include-cross-entity') parsed.includeCrossEntity = true;
else if (flag === '--diff') parsed.diff = true;
else if (flag === '--yes') parsed.yes = true;
else if (flag === '--no-llm') parsed.noLlm = true;
@@ -365,7 +370,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
- const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
+ const { kind, apply, all, json, noEmbed, includeAmbiguous, includeCrossEntity, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
@@ -389,7 +394,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const scope = await resolveRepairScope(engine, source);
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'] : []), ...(requestId ? ['--request-id', requestId] : []),
+ ...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(includeCrossEntity ? ['--include-cross-entity'] : []), ...(requestId ? ['--request-id', requestId] : []),
...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),
...(afterPage !== undefined ? ['--after', String(afterPage)] : []),
...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),
@@ -405,7 +410,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
if (!auth) return;
}
const runner = await repairRunner(engine, { apply, noEmbed });
- const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
+ const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous, ...(k === kind && includeCrossEntity ? { includeCrossEntity } : {}),
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d94e084dae..371127f62e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1072,6 +1072,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7148 (GBRA-145, #7117 follow-up). `since` is restamped at the merge slot.
{ since: '0.60.347.0', text: 'After a model or dimension swap, `gbrain embed --stale`, the embed backfill and `gbrain migrate embeddings` now mark old-model chunks for re-embedding in windows of 1,000 pages (all committed together) instead of one statement over the whole brain, which a large brain cancelled at the statement timeout on every run. The drift check before the embedder probe is one page-first lookup instead of two counts over every chunk, so a count that timed out can no longer skip the swap silently; the "embedder probe failed" warning no longer names a chunk count.' },
// #7211 (GBRA-145). `since` is restamped at the merge slot.
+ // #7043, reported by @mikez93. `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'Recall, the entity card and search `saved_facts` now return one row for each claim instead of one per stored copy (#7043, reported by @mikez93): active facts of one source and visibility with the same normalized text (the fingerprint `forget` and the capture lane use) collapse into the newest copy before `limit` is applied, so the limit counts distinct claims. Copies on different entities merge only when the claim names one of those entities, and copies attributed to different speakers stay apart, as in hot memory. The row adds `collapsed_count` (copies it stands for) and, when the merged copies sit on more than one entity, `entity_slugs`; every other field is unchanged, and remote callers collapse only rows they can already see. Expired facts, `include_expired` history and near duplicates are not merged, and nothing stored changes.' },
+ { since: 'TBD', text: 'Conversation fact extraction no longer stores a fact an active conversation fact of the same source already states (same normalized text and visibility, on the same entity or on an entity the claim names, and no other speaker), whatever page or session it came from (#7043, reported by @mikez93). Before, a standing prompt or instruction repeated in every session was saved again for each one. The run prints `skipped N fact(s) an active fact of the source already states (#7043)`; re-extracting a page still replaces its own facts. Copies stored before the upgrade stay until `gbrain repair duplicate-facts` retires them.' },
+ { since: 'TBD', text: 'New explicit repair `gbrain repair duplicate-facts` (#7043): it previews each group of active facts of one source, visibility and speaker that share a fingerprint and the oldest row it keeps, and after `--apply --expect <hash> --yes` marks every other copy superseded by that row (`expired_at` and `superseded_by`; never deleted or withdrawn). Groups spread over several entities are reported as `cross_entity` and retired only with `--include-cross-entity`. Fenced copies are struck in their page as `superseded by #N` through a revision-bound page write when the kept row shares the fence, and are reported as `fence_kept_elsewhere` otherwise; copies on a segmented page are kept and reported as `segmented_page`. Near duplicates are never touched, and nothing runs on upgrade.' },
+ { since: 'TBD', text: 'New config key `cycle.conversation_facts_backfill.exclude_sources` (#7043): a JSON array or comma list of source ids the conversation facts backfill phase skips, so one source can be left out without turning the phase off. Unset (the default) skips nothing; the phase result reports `sources_excluded`.' },
{ since: '0.60.347.0', text: '`gbrain embed --facts` no longer fails a whole batch, and every later run, on one fact longer than the embedding input limit: that fact is skipped (never truncated), keeps its text and stays stale, and the result reports it (`refused_oversized`, `refused_samples` with fact ids, `refused_fix`) without counting it in `remaining` or against `--max-facts`. Doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them. Shorten or split the fact, or withdraw it with `gbrain forget <fact-id>`, and the next run embeds it once it fits.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 61585da64f..077c7987be 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -75,7 +75,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
@@ -103,13 +103,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--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-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--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', '--request-id', '--scopes', '--source', '--timeout'],
- 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],
+ 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--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', '--timings', '--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', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 92bc32b993..30b8e64759 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -37,6 +37,7 @@
* cycle.conversation_facts_backfill.max_walltime_min (20)
* cycle.conversation_facts_backfill.max_total_walltime_min (30)
* cycle.conversation_facts_backfill.types (all of ALLOWED_TYPES — src/core/facts/conversation-types.ts)
+ * cycle.conversation_facts_backfill.exclude_sources (none: a JSON array or comma list of source ids the phase skips, #7043)
*
* `.types` is the single source of truth for "enabled types" — the CLI
* default reads from the same key (Eng-v2 A2).
@@ -97,6 +98,8 @@ export interface ResolvedConfig {
maxWalltimeMin: number; // per source per cycle
maxTotalWalltimeMin: number; // brain-wide per cycle
types: AllowedType[];
+ /** #7043: source ids the phase never extracts (`exclude_sources`, default none). */
+ excludeSources: string[];
/**
* v0.41.15.0 (D9 in cycle context): in-process worker count per
* per-source invocation. Default 1 — cycle is opt-in per CLAUDE.md,
@@ -109,7 +112,7 @@ export interface ResolvedConfig {
/** The backfill's resolved config (switch, caps, types); doctor reads the same values. */
export async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
const get = (k: string) => engine.getConfig(`${CFG_PREFIX}.${k}`);
- const [enabled, maxCost, maxTotalCost, maxWall, maxTotalWall, typesRaw, workersRaw] =
+ const [enabled, maxCost, maxTotalCost, maxWall, maxTotalWall, typesRaw, workersRaw, excludeRaw] =
await Promise.all([
get('enabled'),
get('max_cost_usd'),
@@ -118,6 +121,7 @@ export async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
get('max_total_walltime_min'),
get('types'),
get('workers'),
+ get('exclude_sources'),
]);
// Truthy-string parse mirrors isFactsExtractionEnabled.
@@ -160,6 +164,7 @@ export async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
return {
enabled: enabledFlag,
+ excludeSources: parseSourceList(excludeRaw),
maxCostUsd: parseFloatOrDefault(maxCost, 1.0),
maxTotalCostUsd: parseFloatOrDefault(maxTotalCost, 5.0),
explicitCostCap: maxCost !== null || maxTotalCost !== null,
@@ -202,14 +207,16 @@ export async function runPhaseConversationFactsBackfill(
const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;
const maxWalltimeMs = cfg.maxWalltimeMin * 60_000;
- const sources = await listSources(engine);
+ const listed = await listSources(engine);
+ const excluded = listed.filter(src => cfg.excludeSources.includes(src.id)).map(src => src.id);
+ const sources = listed.filter(src => !excluded.includes(src.id));
if (sources.length === 0) {
return {
phase: 'conversation_facts_backfill',
status: 'ok',
duration_ms: Date.now() - startedAt,
- summary: 'no sources to process',
- details: { sources_count: 0 },
+ summary: excluded.length ? `no sources to process (${excluded.length} excluded by ${CFG_PREFIX}.exclude_sources)` : 'no sources to process',
+ details: { sources_count: 0, ...(excluded.length ? { sources_excluded: excluded } : {}) },
};
}
@@ -402,7 +409,8 @@ export async function runPhaseConversationFactsBackfill(
const noPricing = [...new Map(Object.values(perSourceResults)
.flatMap((r) => r.budget_pricing ? [[r.budget_pricing.model, r.budget_pricing] as const] : [])).values()];
const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent` +
- noPricing.map((g) => `. ${noPricingMessage(g)}`).join('') + notOwnedNote(sourcesNotOwned);
+ noPricing.map((g) => `. ${noPricingMessage(g)}`).join('') + notOwnedNote(sourcesNotOwned)
+ + (excluded.length ? `. Skipped ${excluded.length} source(s) listed in ${CFG_PREFIX}.exclude_sources (${excluded.join(', ')})` : '');
return {
phase: 'conversation_facts_backfill',
@@ -433,6 +441,7 @@ export async function runPhaseConversationFactsBackfill(
sources_budget_exhausted: sourcesBudgetExhausted,
sources_walltime_exhausted: sourcesWalltimeExhausted,
sources_skipped_not_owner: sourcesNotOwned,
+ sources_excluded: excluded,
no_pricing: noPricing,
types: cfg.types,
max_cost_usd: cfg.maxCostUsd,
@@ -445,6 +454,17 @@ export async function runPhaseConversationFactsBackfill(
};
}
+/** `exclude_sources`: a JSON array of source ids or a comma-separated list; anything else excludes nothing. */
+function parseSourceList(raw: string | null): string[] {
+ if (!raw?.trim()) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ if (Array.isArray(parsed)) return parsed.filter((id): id is string => typeof id === 'string' && id.trim() !== '').map(id => id.trim());
+ if (typeof parsed !== 'string') return [];
+ } catch { /* a comma-separated list */ }
+ return raw.split(',').map(id => id.trim()).filter(Boolean);
+}
+
function notOwnedNote(ids: string[]): string {
return ids.length ? `. Skipped ${ids.length} managed source(s) this host does not own (${ids.join(', ')}); run the phase on their owner host` : '';
}
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
index 36e7200592..989307d61f 100644
--- a/src/core/facts/capture-dedup.ts
+++ b/src/core/facts/capture-dedup.ts
@@ -19,10 +19,15 @@
* so a threshold can be measured before it ever deletes anything. A failed
* dedup read inserts the candidate (fail open) and warns with the lane.
* Explicit lanes (`remember`, extract_facts, sync) never pass through here.
+ * #7043: conversation-fact extraction reuses the exact-fingerprint rule with
+ * no time bound (`anchor: null`), skipping a candidate an active fact of the
+ * source already states (conversation-publication.ts).
*
* Read side (`collapseHotFacts`): rows with the same fingerprint on the same
* entity, or on different entities when the claim names one of them,
* collapse to the newest row, which carries every entity slug of its group.
+ * `collapseFactReads` applies it to reads that span sources and
+ * visibilities (recall, search's saved facts, #7043).
*/
import type { BrainEngine, FactAttribution, FactRow, FactVisibility } from '../engine.ts';
@@ -155,8 +160,10 @@ export interface CaptureScope {
sourceId: string;
lane: string;
sessionId: string | null;
- /** The source turn's own time when the lane knows it, else check time. */
- anchor: Date;
+ /** The source turn's own time when the lane knows it, else check time; null drops the time bound (#7043). */
+ anchor: Date | null;
+ /** Ignore this page's own conversation-extractor rows: a replacement is about to clear them (#7043). */
+ replacingPage?: string;
}
export interface CaptureMatch { id: number; rule: 'same_entity' | 'named_entity'; }
@@ -167,10 +174,12 @@ export async function findCaptureDuplicate(scope: CaptureScope, candidate: Captu
`SELECT id,entity_slug,source,source_session,created_at FROM facts WHERE source_id=$1 AND visibility=ANY($2::text[])
AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3) AND expired_at IS NULL AND (valid_until IS NULL OR valid_until>now())
AND ($4::text IS NULL OR attributed_to IS NULL OR attributed_to=$4)
+ AND ($5::text IS NULL OR source_markdown_slug IS DISTINCT FROM $5 OR source NOT LIKE 'cli:extract-conversation-facts%')
ORDER BY created_at DESC, id DESC LIMIT ${CAPTURE_DEDUP_SCAN_LIMIT}`,
- [scope.sourceId, visibilities, candidate.fact, candidate.attributedTo ?? null]);
+ [scope.sourceId, visibilities, candidate.fact, candidate.attributedTo ?? null, scope.replacingPage ?? null]);
const conversation = canonicalConversationKey(scope.sessionId);
- const recent = rows.filter(row => Math.abs(new Date(row.created_at).getTime() - scope.anchor.getTime()) <= CAPTURE_DEDUP_WINDOW_MS
+ const anchor = scope.anchor;
+ const recent = anchor === null ? rows : rows.filter(row => Math.abs(new Date(row.created_at).getTime() - anchor.getTime()) <= CAPTURE_DEDUP_WINDOW_MS
|| conversation !== null && isCaptureLane(row.source) && canonicalConversationKey(row.source_session) === conversation);
const same = recent.find(row => (row.entity_slug ?? null) === candidate.entitySlug);
if (same) return { id: Number(same.id), rule: 'same_entity' };
@@ -259,7 +268,9 @@ export function withCaptureDrops<R extends { inserted: number; duplicate: number
}
export type HotFactRow = FactRow & { fact_fingerprint?: string | null };
-export type CollapsedHotFact<R extends HotFactRow> = R & { entity_slugs?: string[] };
+/** What the collapse reads of a row. */
+export type CollapsibleFact = Pick<FactRow, 'id' | 'fact' | 'entity_slug' | 'attributed_to' | 'created_at'> & { fact_fingerprint?: string | null };
+export type CollapsedHotFact<R extends CollapsibleFact> = R & { entity_slugs?: string[] };
/**
* V2 hot-memory collapse: one representative (the newest row) per
@@ -269,7 +280,7 @@ export type CollapsedHotFact<R extends HotFactRow> = R & { entity_slugs?: string
* assistant) also splits by speaker, so one never hides the other.
*/
/** `members` (optional) receives raw row id -> emitted representative id, so delta can advance its facts keyset through raw rows. */
-export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine, sourceId: string, rows: R[], members?: Map<number, number>): Promise<CollapsedHotFact<R>[]> {
+export async function collapseHotFacts<R extends CollapsibleFact>(engine: BrainEngine, sourceId: string, rows: R[], members?: Map<number, number>): Promise<CollapsedHotFact<R>[]> {
const byFingerprint = new Map<string, R[]>();
for (const row of rows) {
const key = row.fact_fingerprint ?? `id:${row.id}`;
@@ -304,3 +315,61 @@ export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine
}
return out;
}
+
+/** A row of a read that spans sources and visibilities; `created_at` may arrive as text from a raw read. */
+export type FactReadRow = Omit<CollapsibleFact, 'created_at'> & { source_id: string; visibility: string; created_at: Date | string;
+ expired_at?: Date | string | null; valid_until?: Date | string | null; entity_slugs?: string[]; collapsed_count?: number; collapsed_ids?: number[] };
+/** `collapsed_ids`: every row id the representative stands for (internal; callers drop it from responses). */
+export type CollapsedFactRead<R> = R & { entity_slugs?: string[]; collapsed_count?: number; collapsed_ids?: number[] };
+
+/**
+ * #7043: `collapseHotFacts` for recall and search. Active rows collapse only
+ * within one (source, visibility), so a remote caller's already-filtered rows
+ * never meet a hidden copy; expired or lapsed rows pass through unchanged.
+ * Rows without `fact_fingerprint` get it from one read of their text. Order
+ * is preserved by representative (the group's newest row, holding its
+ * first member's place); a representative standing for several rows carries
+ * `collapsed_count` and `collapsed_ids`, and `entity_slugs` when they name
+ * more than one entity. A row that is already a representative counts as the
+ * rows it stands for, so collapsing a merged list of two collapsed reads
+ * counts each row once. A failed fingerprint read returns the rows unchanged.
+ */
+export async function collapseFactReads<R extends FactReadRow>(engine: BrainEngine, rows: R[]): Promise<CollapsedFactRead<R>[]> {
+ const now = Date.now();
+ const active = rows.filter(r => !r.expired_at && (!r.valid_until || new Date(r.valid_until).getTime() > now));
+ if (active.length < 2) return rows;
+ const missing = active.filter(r => !r.fact_fingerprint);
+ let computed: string[] = [];
+ try {
+ if (missing.length) computed = (await engine.executeRaw<{ fp: string }>(
+ 'SELECT gbrain_fact_fingerprint(c) AS fp FROM unnest($1::text[]) WITH ORDINALITY AS t(c, n) ORDER BY n', [missing.map(r => r.fact)])).map(r => r.fp);
+ } catch {
+ return rows;
+ }
+ const fingerprints = new Map(missing.map((r, i) => [r.id, computed[i]]));
+ const partitions = new Map<string, CollapsibleFact[]>();
+ for (const r of active) {
+ const key = `${r.source_id}\u0000${r.visibility}`;
+ partitions.set(key, [...(partitions.get(key) ?? []), { id: r.id, fact: r.fact, entity_slug: r.entity_slug, attributed_to: r.attributed_to,
+ created_at: new Date(r.created_at), fact_fingerprint: r.fact_fingerprint ?? fingerprints.get(r.id) ?? null }]);
+ }
+ const members = new Map<number, number>();
+ for (const [key, part] of partitions) await collapseHotFacts(engine, key.slice(0, key.indexOf('\u0000')), part, members);
+ const byId = new Map(rows.map(r => [r.id, r]));
+ const groups = new Map<number, R[]>();
+ for (const [id, rep] of members) groups.set(rep, [...(groups.get(rep) ?? []), byId.get(id)!]);
+ const out: CollapsedFactRead<R>[] = [];
+ const emitted = new Set<number>();
+ for (const row of rows) {
+ const rep = members.get(row.id);
+ if (rep === undefined) { out.push(row); continue; }
+ if (emitted.has(rep)) continue;
+ emitted.add(rep);
+ const group = groups.get(rep)!;
+ const kept = byId.get(rep)!;
+ const slugs = [...new Set([kept.entity_slug, ...group.flatMap(r => r.entity_slugs ?? [r.entity_slug])].filter((s): s is string => !!s))];
+ const ids = [...new Set(group.flatMap(r => r.collapsed_ids ?? [r.id]))].sort((a, b) => a - b);
+ out.push({ ...kept, ...(slugs.length > 1 ? { entity_slugs: slugs } : {}), ...(ids.length > 1 ? { collapsed_count: ids.length, collapsed_ids: ids } : {}) });
+ }
+ return out;
+}
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index afb2382221..fcbbe4f1c0 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -80,6 +80,7 @@ import { recordReextractMemo } from './conversation-memo.ts';
import { recordTaintEdges } from '../trust/taint.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';
import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
+import { findCaptureDuplicate } from './capture-dedup.ts';
export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';
export const CONVERSATION_FACTS_PROTOCOL = 1;
@@ -423,9 +424,12 @@ type UnnumberedFact = Omit<ConversationFactRow, 'row_num' | 'source_markdown_slu
* prior facts stay: the outcome replaces the page's prior outcome rows, so
* the page is not paid for again, a `window` run's facts are added beside
* the prior ones, and a partial run's facts are not published over them.
+ * #7043: a fact an active row of the source already states is not stored
+ * again (the capture lane's fingerprint, entity and visibility rule with no
+ * time bound); the page's own rows a replacement clears do not count.
*/
export async function publishConversationFacts(tx: BrainEngine, sourceId: string, slug: string, rows: UnnumberedFact[],
- opts: { scope: ConversationScope; requestId?: string }): Promise<{ deleted: number; facts_inserted: number }> {
+ opts: { scope: ConversationScope; requestId?: string }): Promise<{ deleted: number; facts_inserted: number; duplicates_skipped: number }> {
const derivation = await conversationDerivation(tx, sourceId, slug);
const cfg = await derivedGateConfig(tx);
const gated = rows.map(row => ({ row, decision: OUTCOME_SOURCES.has(row.source) ? null : decideFactWrite(row,
@@ -435,7 +439,15 @@ export async function publishConversationFacts(tx: BrainEngine, sourceId: string
const [active] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2
AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND f.expired_at IS NULL AND NOT (f.source = ANY($3::text[]))`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
const retire = !Number(active?.n ?? 0) || (opts.scope === 'full' && kept.length === rows.length && kept.some(({ row }) => !OUTCOME_SOURCES.has(row.source)));
- const published = retire || opts.scope === 'window' ? kept : kept.filter(({ row }) => OUTCOME_SOURCES.has(row.source));
+ const scope = { engine: tx, sourceId, lane: CONVERSATION_FACTS_SOURCE_PREFIX, sessionId: null, anchor: null, ...(retire ? { replacingPage: slug } : {}) };
+ const published: typeof kept = [];
+ let duplicates = 0;
+ for (const entry of retire || opts.scope === 'window' ? kept : kept.filter(({ row }) => OUTCOME_SOURCES.has(row.source))) {
+ const { row } = entry;
+ if (OUTCOME_SOURCES.has(row.source) || !await findCaptureDuplicate(scope, { fact: row.fact, entitySlug: row.entity_slug ?? null,
+ visibility: row.visibility ?? 'private', attributedTo: row.attributed_to ?? null })) published.push(entry);
+ else duplicates++;
+ }
const { deleted, ids } = await withWriteTrust(tx, derivation.trust, async () => {
if (retire) return replaceConversationFacts(tx, sourceId, slug, published.map(({ row }) => row));
const outcomes = published.some(({ row }) => OUTCOME_SOURCES.has(row.source)) ? await tx.executeRaw<{ id: number }>(`DELETE FROM facts
@@ -448,7 +460,7 @@ export async function publishConversationFacts(tx: BrainEngine, sourceId: string
if (decision && ids.length === published.length) await recordFlaggedRow(tx, decision, { table: 'facts', id, sourceId });
}
if (published.some(({ row }) => row.source === TERMINAL_AUDIT_SOURCE)) await recordReextractMemo(tx, sourceId, slug); // #6764
- return { deleted, facts_inserted: published.filter(({ row }) => !OUTCOME_SOURCES.has(row.source)).length };
+ return { deleted, facts_inserted: published.filter(({ row }) => !OUTCOME_SOURCES.has(row.source)).length, duplicates_skipped: duplicates };
}
/**
diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.ts
index e30ddb0622..c0aba1a4fc 100644
--- a/src/core/facts/question-recall.ts
+++ b/src/core/facts/question-recall.ts
@@ -18,6 +18,7 @@ import { MEMORY_VERBS_VERSION } from '../verbs.ts';
import { getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '../ai/gateway.ts';
import { calibrationKey } from './supersession-threshold.ts';
import { rowToFact, type FactRowSqlShape } from '../engine-sql/facts.ts';
+import { collapseFactReads, type CollapsedFactRead } from './capture-dedup.ts';
import { loadEmbeddingQueryPrefix } from '../search/query-prefix.ts';
import { embedQueryBounded, makeQueryEmbedDeadline } from '../search/hybrid.ts';
import { resolveHnswIterativeScan } from '../search/hnsw-iterative-scan.ts';
@@ -172,7 +173,8 @@ export interface QuestionRecallInput {
}
export interface QuestionRecall {
- rows: FactRow[];
+ /** Ranked rows, copies of one claim collapsed (#7043) before the `limit` cut. */
+ rows: CollapsedFactRead<FactRow>[];
/** fact id → relevance (cosine + term share + 0.1 when dated). */
relevance: Map<number, number>;
degraded?: FactsDegraded;
@@ -214,7 +216,7 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Question
embedding ? countUncomparableFacts(ctx.engine, scope, filters, embedding.length) : [],
admissionRule(ctx.engine),
]);
- const ranked = scoreFactCandidates(question, pool.candidates).filter(s => admitted(s, rule)).slice(0, input.limit);
+ const ranked = scoreFactCandidates(question, pool.candidates).filter(s => admitted(s, rule));
const unembedded = uncomparable.reduce((n, r) => n + r.n, 0);
const why = reason ?? (embedding && !pool.column ? 'facts_embedding_column_missing' : undefined);
const degraded: FactsDegraded | undefined = why || unembedded ? { ...(why ? { reason: why } : {}), ...(unembedded ? { unembedded } : {}) } : undefined;
@@ -225,7 +227,7 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Question
const byId = new Map(raw.map(r => { const row = rowToFact(r); return [row.id, { ...row, embedding: null }] as const; }));
const modelKey = embedding && pool.column ? calibrationKey(getEmbeddingModel(), getEmbeddingDimensions()) : null;
return {
- rows: ids.flatMap(id => byId.get(id) ?? []),
+ rows: (await collapseFactReads(ctx.engine, ids.flatMap(id => byId.get(id) ?? []))).slice(0, input.limit),
relevance: new Map(ranked.map(s => [s.candidate.id, Math.round(s.score * 1e4) / 1e4])),
ambiguousEntity: null,
...(degraded ? { degraded } : {}),
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index f1788f8d0d..98543390b2 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -40,7 +40,8 @@ import { ENTITY_HINTS_CAP } from '../facts/extract.ts';
import { parseTtlShorthand } from '../facts/ttl-parse.ts';
import { MEMORY_VERBS_VERSION } from '../verbs.ts';
import type { SearchResult } from '../types.ts';
-import type { BrainEngine, FactRow } from '../engine.ts';
+import { MAX_SEARCH_LIMIT, type BrainEngine, type FactRow } from '../engine.ts';
+import { collapseFactReads } from '../facts/capture-dedup.ts';
import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';
import { hasScope } from '../scope.ts';
import { renderTrustedText } from '../eligibility/labels.ts';
@@ -344,7 +345,7 @@ const recall: Operation = {
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote); // #4352: fact and page arms alike
const eligibility = await resolveReadEligibility(ctx, { minTrust: p.min_trust }); // #5575 floor + quarantine/rederive hiding
- type FactRows = Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>;
+ type FactRows = Array<Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>[number] & { entity_slugs?: string[]; collapsed_count?: number }>;
type FactRowItem = FactRows[number];
// Per-arm merge key: each arm's engine query ORDERs by a different column
// (supersessions by COALESCE(expired_at, valid_until) — #3014, entity by
@@ -363,7 +364,7 @@ const recall: Operation = {
k: toTime(keyOf(r as unknown as Record<string, unknown>)),
}));
decorated.sort((a, b) => b.k - a.k);
- return decorated.slice(0, limit).map(d => d.r);
+ return decorated.slice(0, MAX_SEARCH_LIMIT).map(d => d.r);
};
const byCreated = (rec: Record<string, unknown>) => rec.created_at ?? rec.since_date;
// The since-arms below pass eventTime:true (COALESCE(valid_from,
@@ -396,7 +397,7 @@ const recall: Operation = {
// LIMIT, so a hidden newest row never consumes a slot).
const listOpts = {
activeOnly: !includeExpired,
- limit,
+ limit: MAX_SEARCH_LIMIT,
visibility, excludePrivate,
grep: grep ?? undefined,
excludeAuditRows: true, eligibility,
@@ -429,7 +430,7 @@ const recall: Operation = {
const { resolveEntitySlug } = await import('../entities/resolve.ts');
const resolvedLists = await Promise.all(factSources.map(async (src) => {
const entitySlug = entityParam ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam) : undefined;
- const rows = await readEntityFacts(ctx, src, entitySlug, limit,
+ const rows = await readEntityFacts(ctx, src, entitySlug, MAX_SEARCH_LIMIT,
s => ctx.engine.listFactsSince(src, since, { ...listOpts, eventTime: true, entitySlug: s, sessionId: sessionParam ?? undefined }));
return { slug: entitySlug, rows };
}));
@@ -439,7 +440,7 @@ const recall: Operation = {
const { resolveEntitySlug } = await import('../entities/resolve.ts');
const resolvedLists = await Promise.all(factSources.map(async (src) => {
const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;
- return { slug, rows: await readEntityFacts(ctx, src, slug, limit, s => ctx.engine.listFactsByEntity(src, s!, { ...listOpts, sessionId: sessionParam ?? undefined })) };
+ return { slug, rows: await readEntityFacts(ctx, src, slug, MAX_SEARCH_LIMIT, s => ctx.engine.listFactsByEntity(src, s!, { ...listOpts, sessionId: sessionParam ?? undefined })) };
}));
ambiguousEntity = await unlinkedNamesakes(ctx.engine, resolvedLists.map(l => l.rows.map(r => ({ ...r, entity_slug: l.slug }))));
rows = ambiguousEntity ? [] : mergeNewest(resolvedLists.map(l => l.rows), (rec) => rec.valid_from ?? rec.created_at);
@@ -474,6 +475,8 @@ const recall: Operation = {
rows = rows.filter(r => r.fact.toLowerCase().includes(grep));
}
+ // #7043: copies of one claim (the fact arms read MAX_SEARCH_LIMIT rows) collapse after the visibility filters, before the limit cut.
+ if (!ranking) rows = (await collapseFactReads(ctx.engine, rows)).slice(0, limit);
// v0.32: optional pending-consolidation count piggy-backed on the recall
// response. Single round trip on thin-client; omitted when not requested
// so existing callers see no shape change. Sums over the SAME factSources
@@ -609,6 +612,7 @@ const recall: Operation = {
// is the protocol name for the stored source attribution.
fact_id: String(r.id),
provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),
+ ...(r.entity_slugs ? { entity_slugs: r.entity_slugs } : {}), ...(r.collapsed_count ? { collapsed_count: r.collapsed_count } : {}),
...(ranking ? { relevance: ranking.relevance.get(r.id) } : {}),
})), f => f.id)),
total: packedFacts.length,
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 7b1a987b8a..7e66da8783 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -54,7 +54,8 @@ import { pageReadFilter } from '../search/read-policy-sql.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';
import { declaredNames, titleName } from '../mentions/aliases.ts';
import { aliasPhrase, wholeQueryEntityNames, withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';
-import { entitySavedFacts } from '../search/entity-facts.ts';
+import { entitySavedFacts, SAVED_FACT_COLLAPSE_COLUMNS, stripCollapseColumns, type CollapseColumns } from '../search/entity-facts.ts';
+import { collapseFactReads } from '../facts/capture-dedup.ts';
import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';
import { keepEnumeratedRows, keywordCountMeta, parseSearchPaging, readKeywordPage, startKeywordCount, withCountMeta } from '../search/keyword-paging.ts';
import { searchLimitCap } from '../search/eval-pool-depth.ts';
@@ -347,16 +348,19 @@ async function emitFanoutNotices(ctx: OperationContext, fanout: FanoutMeta | und
if (notice) ctx.emitNotice?.(notice);
}
-export interface SavedFactMatch { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string }
+export interface SavedFactMatch { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string;
+ /** #7043: every entity of the copies this row stands for, and how many rows it stands for. */
+ entity_slugs?: string[]; collapsed_count?: number }
/**
* Facts saved with `remember` live in the facts table, not in page chunks, so
* page search never returns them (gbrain-evals Cat 40: agents saved a
* correction with remember and the next session's search missed it). This
* finds active facts whose text or entity shares at least three quarters of the query's words,
- * under the same source scope and visibility rules recall applies.
+ * under the same source scope and visibility rules recall applies, copies of one claim collapsed
+ * before the cap (#7043).
*/
-async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, queryText: string, aliases: AliasDeclaration[] = []): Promise<SavedFactMatch[]> {
+async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, queryText: string, aliases: AliasDeclaration[] = []): Promise<Array<SavedFactMatch & CollapseColumns>> {
// A query naming one of two declared names also matches facts saved under the other.
for (const a of aliases) queryText += ` ${a.name} ${a.alias}`;
const terms = [...new Set(queryText.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}'-]+/gu) ?? [])]
@@ -379,8 +383,8 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
[sources, [...AUDIT_ROW_SOURCES]],
);
if (any.length === 0) return [];
- const rows = await ctx.engine.executeRaw<SavedFactMatch & { haystack: string }>(
- `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source,
+ const rows = await ctx.engine.executeRaw<SavedFactMatch & CollapseColumns & { haystack: string }>(
+ `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source, ${SAVED_FACT_COLLAPSE_COLUMNS},
lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack
FROM facts f
WHERE f.source_id = ANY($1::text[])
@@ -393,12 +397,12 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
[sources, [...AUDIT_ROW_SOURCES], terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`)],
);
const need = Math.max(Math.min(2, terms.length), Math.ceil(terms.length * 0.75));
- return rows
+ const matched = rows
.map(r => ({ r, hits: terms.filter(t => r.haystack.includes(t)).length }))
.filter(x => x.hits >= need)
.sort((a, b) => b.hits - a.hits)
- .slice(0, 5)
.map(({ r: { haystack: _h, ...fact } }) => ({ ...fact, id: Number(fact.id) }));
+ return (await collapseFactReads(ctx.engine, matched)).slice(0, 5);
} catch {
return [];
}
@@ -455,8 +459,9 @@ async function buildRetrievalResponseMeta(
const freshness = sourceFreshness.map(f => ({ ...f, held_count: heldBySource.get(f.source_id) ?? 0 }));
// A fact the facts arm already returned as a row is not repeated beside the blocks.
const factRowIds = new Set((results as SearchResult[]).flatMap(r => r.fact_row ? [r.fact_row.id] : []));
- const savedFacts = [...entityFacts, ...matchedFacts.filter(m => !entityFacts.some(e => e.id === m.id))]
- .filter(f => !factRowIds.has(f.id));
+ // #7043: a matched fact may copy an entity fact; the merged list collapses again before the response.
+ const savedFacts = (await collapseFactReads(ctx.engine, [...entityFacts, ...matchedFacts.filter(m => !entityFacts.some(e => e.id === m.id))]
+ .filter(f => !factRowIds.has(f.id)))).map(stripCollapseColumns);
const heldNotice = heldFilesNotice(heldFiles, ctx.remote !== false);
if (heldNotice) ctx.emitNotice?.(heldNotice);
const degraded = [...(m?.degraded ?? [])];
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index f39f2a71c7..657d158448 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' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index a8c3beec79..d9960c60b1 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
@@ -98,6 +98,8 @@ export interface RepairListing { item: string; class: string; detail?: string }
* the run's paid-model allowance (it only lowers the kind's own cap). `deadline` (epoch ms) bounds a discovery scan.
*/
export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[];
+ /** `duplicate-facts` (#7043): also retire copies of a claim that sit on other entities than the kept row. */
+ includeCrossEntity?: boolean;
noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
/** `ctx.remote !== false` of the run: a remote caller's plan never names a local path (unset reads as remote). */
remote?: boolean;
@@ -308,7 +310,7 @@ function writerHeld(error: unknown): error is OperationError {
*/
export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
- explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
+ explicit?: boolean; expect?: string; includeAmbiguous?: boolean; includeCrossEntity?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
@@ -327,6 +329,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
const { cursor: resumed, runId: storedRunId } = await readCursor(ctx.engine, handler.kind, scope, opts.apply ? opts.expect : undefined);
const now = opts.now ?? Date.now;
const planOpts: RepairPlanOptions = { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip,
+ ...(opts.includeCrossEntity ? { includeCrossEntity: true } : {}),
...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),
...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,
...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),
@@ -362,7 +365,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),
...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []),
...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`
- + `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
+ + `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${opts.includeCrossEntity ? ' --include-cross-entity' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,
...(plan.scan ? { scan: plan.scan } : {}),
};
diff --git a/src/core/repair/duplicate-facts.ts b/src/core/repair/duplicate-facts.ts
new file mode 100644
index 0000000000..372d04a699
--- /dev/null
+++ b/src/core/repair/duplicate-facts.ts
@@ -0,0 +1,252 @@
+/**
+ * `gbrain repair duplicate-facts` (#7043): retire exact copies of one active
+ * fact, keeping the oldest.
+ *
+ * A group is the active facts of one source and visibility (and one speaker)
+ * that share `gbrain_fact_fingerprint`; near duplicates (rewordings) are never
+ * grouped. The oldest row (created_at, then id) is kept; every other row is
+ * superseded by it: `expired_at` set and `superseded_by` pointing at the kept
+ * row. It is a supersession, never a withdrawal, so the claim stays
+ * rememberable and the kept row keeps its entity.
+ *
+ * A group whose rows sit on more than one entity (`cross_entity`) is listed
+ * on its own and retired only with `--include-cross-entity`; the rest are
+ * `same_entity`. A fenced copy (a `## Facts` row of its page, not a
+ * conversation-extractor row) is struck in its page as `superseded by #N`
+ * through a revision-bound `put_page` (the page write path on managed and
+ * unmanaged sources alike) when the kept row is a fence row of the same page,
+ * and its `superseded_by` is then linked as the fence names it;
+ * otherwise the fence could not name the kept row, and the copy is listed as
+ * `fence_kept_elsewhere` and kept. A fenced copy on a segmented page (whose
+ * body this repair does not rewrite) is listed as `segmented_page` and kept,
+ * in the preview and in an apply that finds the page segmented since. Database-only copies are retired in one
+ * coordinated database write per group on a managed brain (one transaction
+ * otherwise).
+ *
+ * Explicit-only and preview-bound: the preview lists every group, prints a
+ * hash and saves the set; `--apply --expect <hash> --yes` retires exactly
+ * that set, rechecking each row (`changed_since_preview` for one that moved).
+ * Nothing runs on upgrade.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
+import { RELINK_OPERATION } from '../facts/relink-publish.ts';
+import { parseFactsFence, strikeFactRowInPage } from '../facts-fence.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { coordinatedDatabaseWrite } from '../persistence/database-write.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+export interface DuplicateRow {
+ id: number;
+ entity_slug: string | null;
+ /** The page whose `## Facts` fence holds the row, or null for a database-only row. */
+ fence_page: string | null;
+ row_num: number | null;
+}
+
+export interface DuplicateGroup {
+ source_id: string;
+ visibility: string;
+ fingerprint: string;
+ claim: string;
+ class: 'same_entity' | 'cross_entity';
+ kept: DuplicateRow;
+ /** Copies the apply retires. */
+ retire: DuplicateRow[];
+ /** Fenced copies whose fence cannot name the kept row; listed, never retired. */
+ held: DuplicateRow[];
+ /** Fenced copies on a segmented page; listed as `segmented_page`, never retired. */
+ segmented: DuplicateRow[];
+}
+
+/** Every same-fingerprint group of active facts in these sources, in (source, visibility, fingerprint) order. Read-only. */
+export async function findDuplicateFacts(engine: BrainEngine, sourceIds: string[]): Promise<DuplicateGroup[]> {
+ const rows = await engine.executeRaw<{ id: number | string; source_id: string; visibility: string; fp: string; fact: string; entity_slug: string | null;
+ fenced: boolean; row_num: number | string | null; source_markdown_slug: string | null; speaker: string }>(`
+ SELECT * FROM (
+ SELECT f.id, f.source_id, f.visibility, gbrain_fact_fingerprint(f.fact) AS fp, f.fact, f.entity_slug, f.row_num, f.source_markdown_slug, f.created_at,
+ COALESCE(f.attributed_to, '') AS speaker,
+ (f.row_num IS NOT NULL AND f.source_markdown_slug IS NOT NULL AND COALESCE(f.source, '') NOT LIKE 'cli:%') AS fenced,
+ count(*) OVER (PARTITION BY f.source_id, f.visibility, COALESCE(f.attributed_to, ''), gbrain_fact_fingerprint(f.fact)) AS n
+ FROM facts f
+ WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
+ AND f.superseded_by IS NULL AND COALESCE(f.source, '') <> ALL($2::text[])
+ ) d WHERE d.n > 1
+ ORDER BY d.source_id, d.visibility, d.fp, d.speaker, d.created_at, d.id`, [sourceIds, [...AUDIT_ROW_SOURCES]]);
+ const groups: DuplicateGroup[] = [];
+ let key = '';
+ for (const row of rows) {
+ const dup: DuplicateRow = { id: Number(row.id), entity_slug: row.entity_slug, fence_page: row.fenced ? row.source_markdown_slug : null,
+ row_num: row.row_num === null ? null : Number(row.row_num) };
+ const rowKey = JSON.stringify([row.source_id, row.visibility, row.fp, row.speaker]);
+ if (rowKey !== key) {
+ key = rowKey;
+ groups.push({ source_id: row.source_id, visibility: row.visibility, fingerprint: row.fp, claim: row.fact, class: 'same_entity', kept: dup, retire: [], held: [], segmented: [] });
+ continue;
+ }
+ const group = groups[groups.length - 1]!;
+ if (dup.entity_slug !== group.kept.entity_slug) group.class = 'cross_entity';
+ const strikable = dup.fence_page === null || (group.kept.fence_page === dup.fence_page && group.kept.row_num !== null);
+ (strikable ? group.retire : group.held).push(dup);
+ }
+ const fenced = groups.flatMap(g => g.retire.flatMap(r => r.fence_page ? [[g.source_id, r.fence_page]] : []));
+ if (!fenced.length) return groups;
+ const segmented = new Set((await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id, p.slug FROM pages p
+ JOIN unnest($1::text[], $2::text[]) AS t(source_id, slug) ON p.source_id = t.source_id AND p.slug = t.slug
+ WHERE p.body_storage = 'segmented' AND p.deleted_at IS NULL`, [fenced.map(f => f[0]), fenced.map(f => f[1])])).map(r => JSON.stringify([r.source_id, r.slug])));
+ for (const g of groups) {
+ g.segmented = g.retire.filter(r => r.fence_page && segmented.has(JSON.stringify([g.source_id, r.fence_page])));
+ g.retire = g.retire.filter(r => !g.segmented.includes(r));
+ }
+ return groups;
+}
+
+interface ApprovedGroup extends DuplicateGroup { selection: { source_ids: string[]; include_cross_entity: boolean } }
+interface GroupItem extends RepairItem { group: DuplicateGroup; hash: string; last: boolean }
+
+function previewCommand(scope: RepairScope, includeCrossEntity: boolean): string {
+ return `gbrain repair duplicate-facts${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${includeCrossEntity ? ' --include-cross-entity' : ''}`;
+}
+
+const sourcesOf = (engine: BrainEngine, scope: RepairScope) => 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 hashOf = (scope: RepairScope, includeCrossEntity: boolean, sources: unknown, groups: DuplicateGroup[]) =>
+ previewHash({ kind: 'duplicate-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_cross_entity: includeCrossEntity },
+ groups: groups.map(({ claim: _claim, ...g }) => g) });
+
+function item(group: DuplicateGroup, index: number, hash: string, last: boolean): GroupItem {
+ return { cursor: { phase: 1, id: index }, source_id: group.source_id, slug: group.kept.fence_page ?? group.kept.entity_slug ?? `facts/${group.kept.id}`,
+ chars: 0, action: `retire ${group.retire.length} copy(ies) of fact ${group.kept.id}`, group, hash, last };
+}
+
+const ids = (rows: DuplicateRow[]) => rows.map(r => `#${r.id}${r.entity_slug ? ` (${r.entity_slug})` : ''}`).join(', ');
+
+export const duplicateFactsRepair: RepairHandler = {
+ kind: 'duplicate-facts',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeCrossEntity = opts?.includeCrossEntity === true;
+ const command = previewCommand(scope, includeCrossEntity);
+ if (!opts?.apply) {
+ const groups = await findDuplicateFacts(engine, scope.source_ids);
+ const selected = groups.filter(g => g.retire.length && (g.class === 'same_entity' || includeCrossEntity));
+ const hash = hashOf(scope, includeCrossEntity, await sourcesOf(engine, scope), groups);
+ if (selected.length) await saveApprovedSet<ApprovedGroup>(engine, { command: 'duplicate-facts', hash },
+ selected.map(g => ({ ...g, selection: { source_ids: scope.source_ids, include_cross_entity: includeCrossEntity } })));
+ const listing: RepairListing[] = [];
+ for (const g of groups) {
+ const where = `${g.source_id}:${g.visibility}:fact#${g.kept.id}`;
+ const keeps = `keeps fact ${g.kept.id}${g.kept.entity_slug ? ` on ${g.kept.entity_slug}` : ''}`;
+ const heldCross = g.class === 'cross_entity' && !includeCrossEntity;
+ if (g.retire.length) listing.push({ item: where, class: heldCross ? 'cross_entity_held' : g.class,
+ detail: `${keeps}; ${heldCross ? 'would supersede' : 'supersedes'} ${ids(g.retire)}`
+ + (heldCross ? '; the copies sit on other entities, pass --include-cross-entity to retire them' : '') });
+ if (g.held.length) listing.push({ item: where, class: 'fence_kept_elsewhere',
+ detail: `${keeps}; the fence rows of ${ids(g.held)} cannot name a fact outside their page, so they are kept (forget or edit them in their page)` });
+ if (g.segmented.length) listing.push({ item: where, class: 'segmented_page',
+ detail: `${keeps}; ${ids(g.segmented)} sit in the Facts table of segmented page ${g.kept.fence_page}, which this repair does not rewrite, so they are kept (forget them in their page)` });
+ }
+ const count = (pick: (g: DuplicateGroup) => boolean) => groups.filter(pick).length;
+ return { items: selected.map((g, index) => item(g, index, hash, index === selected.length - 1)), preview_hash: hash, listing,
+ residuals: { same_entity_groups: count(g => g.class === 'same_entity'), cross_entity_groups: count(g => g.class === 'cross_entity'),
+ copies_to_retire: selected.reduce((n, g) => n + g.retire.length, 0),
+ cross_entity_copies_held: includeCrossEntity ? 0 : groups.filter(g => g.class === 'cross_entity').reduce((n, g) => n + g.retire.length, 0),
+ fence_kept_elsewhere: groups.reduce((n, g) => n + g.held.length, 0), segmented_page: groups.reduce((n, g) => n + g.segmented.length, 0) } };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair duplicate-facts --apply retires only the set a preview printed.',
+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`,
+ 'docs/guides/repair.md#explicit-only-repair-kinds');
+ }
+ const approved = await loadApprovedSet<ApprovedGroup>(engine, { command: 'duplicate-facts', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => hashOf(scope, includeCrossEntity, await sourcesOf(engine, scope), []) });
+ const selection = JSON.stringify({ source_ids: scope.source_ids, include_cross_entity: includeCrossEntity });
+ if (approved.items.some(g => JSON.stringify(g.selection) !== selection)) throw previewChangedError(opts.expect, command);
+ const items = approved.items.map(({ selection: _selection, ...g }, index) => item(g, index, opts.expect!, index === approved.items.length - 1));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { group, hash, last } = entry as GroupItem;
+ const { retired, segmented } = await retireGroup(ctx, entry, group);
+ if (last) await clearApprovedSet(ctx.engine, { command: 'duplicate-facts', hash });
+ const changed = group.retire.filter(r => !retired.includes(r.id) && !segmented.includes(r.id)).map(r => r.id);
+ const reasons = [...(segmented.length ? [`kept on a segmented page: ${segmented.join(', ')}`] : []), ...(changed.length ? [`kept as changed since the preview: ${changed.join(', ')}`] : [])];
+ return { applied: retired.length > 0,
+ outcome: retired.length ? (reasons.length ? 'partially_superseded' : 'superseded') : changed.length ? 'changed_since_preview' : 'segmented_page',
+ detail: { kept: group.kept.id, superseded: retired.length, ...(segmented.length ? { segmented_page: segmented.length } : {}) },
+ ...(reasons.length ? { reason: reasons.join('; ') } : {}) };
+ },
+};
+
+/** The rows still active, unsuperseded and stating the group's claim on the entity and fence row the preview saw. */
+async function unchanged(db: BrainEngine, group: DuplicateGroup, rows: DuplicateRow[]): Promise<DuplicateRow[]> {
+ const live = await db.executeRaw<{ id: number | string; entity_slug: string | null; row_num: number | string | null; source_markdown_slug: string | null }>(
+ `SELECT id, entity_slug, row_num, source_markdown_slug FROM facts
+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND visibility=$3 AND gbrain_fact_fingerprint(fact)=$4
+ AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) AND superseded_by IS NULL`,
+ [group.source_id, rows.map(r => r.id), group.visibility, group.fingerprint]);
+ const byId = new Map(live.map(r => [Number(r.id), r]));
+ return rows.filter(r => {
+ const now = byId.get(r.id);
+ return !!now && now.entity_slug === r.entity_slug && (now.row_num === null ? null : Number(now.row_num)) === r.row_num
+ && (r.fence_page === null || now.source_markdown_slug === r.fence_page);
+ });
+}
+
+type RepairContext = Parameters<RepairHandler['apply']>[0];
+
+/** One database-only write of the group: a coordinated write holding `keys` on a managed brain, one transaction otherwise. */
+async function databaseWrite(ctx: RepairContext, group: DuplicateGroup, keys: string[], write: (tx: BrainEngine) => Promise<number[]>): Promise<number[]> {
+ const managed = await coordinatedDatabaseWrite({ ...ctx, sourceId: group.source_id }, RELINK_OPERATION, keys[0]!, keys, tx => write(tx));
+ return managed ? managed.value : maintenanceTransaction(ctx.engine, write);
+}
+
+async function retireGroup(ctx: RepairContext, entry: RepairItem, group: DuplicateGroup): Promise<{ retired: number[]; segmented: number[] }> {
+ const engine = ctx.engine;
+ if (!(await unchanged(engine, group, [group.kept])).length) return { retired: [], segmented: [] };
+ const live = await unchanged(engine, group, group.retire);
+ const retired: number[] = [];
+ const dbOnly = live.filter(r => r.fence_page === null);
+ if (dbOnly.length) {
+ retired.push(...await databaseWrite(ctx, group, [...new Set([entry.slug, ...dbOnly.map(r => r.entity_slug ?? entry.slug)])], async tx => (await tx.executeRaw<{ id: number | string }>(
+ `UPDATE facts SET expired_at = now(), superseded_by = $3
+ WHERE source_id = $1 AND id = ANY($2::bigint[]) AND expired_at IS NULL AND superseded_by IS NULL
+ AND visibility = $4 AND gbrain_fact_fingerprint(fact) = $5
+ AND EXISTS (SELECT 1 FROM facts k WHERE k.source_id = $1 AND k.id = $3 AND k.expired_at IS NULL)
+ RETURNING id`, [group.source_id, dbOnly.map(r => r.id), group.kept.id, group.visibility, group.fingerprint])).map(r => Number(r.id))));
+ }
+ const fenced = live.filter(r => r.fence_page !== null);
+ if (!fenced.length) return { retired, segmented: [] };
+ const struck = await strikeFencedCopies(ctx, entry, group, fenced);
+ if (struck === 'segmented') return { retired, segmented: fenced.map(r => r.id) };
+ return { retired: [...retired, ...struck], segmented: [] };
+}
+
+/**
+ * Fenced copies on the kept row's page: struck as `superseded by #<kept row>` in one revision-bound put_page, whose
+ * projection expires them; their `superseded_by` is then linked to the kept row, as the fence's reference resolves.
+ */
+async function strikeFencedCopies(ctx: RepairContext, entry: RepairItem, group: DuplicateGroup, rows: DuplicateRow[]): Promise<number[] | 'segmented'> {
+ const slug = group.kept.fence_page!;
+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId: group.source_id });
+ if (!snapshot) return [];
+ if (isSegmentedPage(snapshot.page)) return 'segmented';
+ let page = { ...snapshot.page, compiled_truth: snapshot.page.compiled_truth ?? '', timeline: snapshot.page.timeline ?? '' };
+ const fence = [...parseFactsFence(page.compiled_truth).facts, ...parseFactsFence(page.timeline).facts];
+ if (!fence.some(f => f.rowNum === group.kept.row_num && f.active)) return [];
+ const struck = rows.filter(r => fence.some(f => f.rowNum === r.row_num && f.active));
+ if (!struck.length) return [];
+ for (const r of struck) page = strikeFactRowInPage(page, r.row_num!, group.kept.row_num!);
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, source_id: group.source_id,
+ content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'duplicate-facts', entry, snapshot.revision) } });
+ return databaseWrite(ctx, group, [slug], async tx => (await tx.executeRaw<{ id: number | string }>(
+ `UPDATE facts SET superseded_by = $3 WHERE source_id = $1 AND id = ANY($2::bigint[]) AND expired_at IS NOT NULL AND superseded_by IS NULL
+ RETURNING id`, [group.source_id, struck.map(r => r.id), group.kept.id])).map(r => Number(r.id)));
+}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index e73a2a3a1f..23e013df63 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -59,6 +59,7 @@ import { loopFactsRepair } from './loop-facts.ts';
import { ontologyFactsRepair } from './ontology-facts.ts';
import { factsRehomeRepair } from './facts-rehome.ts';
import { consolidateTiesRepair } from './consolidate-ties.ts';
+import { duplicateFactsRepair } from './duplicate-facts.ts';
import { orphanChildrenRepair } from './orphan-children.ts';
import { failedWritesRepair } from './failed-writes.ts';
import { frontmatterRepair } from './frontmatter.ts';
@@ -269,6 +270,22 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'facts back to open validity and keeps their consolidation mark; a fact that was expired, edited or reopened reports changed_since_preview. '
+ 'Database-only; no page is rewritten.',
},
+ 'duplicate-facts': {
+ handler: duplicateFactsRepair, embeds: 'effect', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Retire the previewed copies of duplicate facts, keeping the oldest row of each claim',
+ why: 'The preview listed each group of active facts that state one claim (same fingerprint, source and visibility) with the row it keeps; applying it supersedes exactly the listed copies.',
+ risk: 'Copies are expired with superseded_by pointing at the kept row, never deleted or withdrawn, so the claim stays in recall and can be saved again. '
+ + 'Fenced copies are struck in their page as "superseded by #N" through a revision-bound page write. A row that changed since the preview is kept.',
+ user_message: 'Retire the previewed duplicate fact copies? Each claim keeps its oldest row; the copies are marked superseded by it, not deleted.',
+ },
+ summary: 'Retire exact copies of one active fact (#7043): in each group of active facts of one source and visibility that share their fingerprint, the '
+ + 'oldest row is kept and every other row is superseded by it (expired_at set, superseded_by the kept row; never a withdrawal, so the claim stays '
+ + 'rememberable). Groups whose copies sit on other entities are listed as cross_entity and retired only with --include-cross-entity; the kept row keeps '
+ + 'its entity. Near duplicates are never touched. Fenced copies are struck in their page through a revision-bound put_page when the kept row is in the '
+ + 'same fence, listed as fence_kept_elsewhere otherwise, and kept as segmented_page on a segmented page. Preview-bound: --apply --expect <hash> --yes retires exactly the previewed set; a row that '
+ + 'changed since reports changed_since_preview. Runs only when named.',
+ },
'orphan-children': {
handler: orphanChildrenRepair, embeds: 'none', checks: ['child_table_orphans'], explicit_only: true,
summary: 'Delete rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page no longer exists, and clear dangling '
@@ -582,7 +599,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
* `explicit`: the operator named `kind`; required for explicit-only kinds.
* `maxLlmUsd`: what this run may spend on a paid chat model (`spends: 'llm'` kinds; undefined = no run cap).
*/
- async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
+ async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; includeCrossEntity?: boolean; only?: string[]; skip?: string[];
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {
@@ -592,7 +609,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),
...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),
...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : [])],
- explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
+ explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, includeCrossEntity: run.includeCrossEntity, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });
},
diff --git a/src/core/search/entity-facts.ts b/src/core/search/entity-facts.ts
index 3f5f76104d..06220da541 100644
--- a/src/core/search/entity-facts.ts
+++ b/src/core/search/entity-facts.ts
@@ -10,7 +10,9 @@
* returned first. One hop: an entity a returned fact names ("folded into
* Dovalto Energy", "uses Dovalto Energy's discount code") contributes its own
* newest facts, tagged `linked_from`, so a redirection reaches the value it
- * points to. Same source scope, active-fact and visibility rules as recall.
+ * points to. Same source scope, active-fact and visibility rules as recall,
+ * and recall's collapse (#7043): copies of one claim read as one fact, before
+ * the caps, so they never crowd out a distinct one.
*/
import type { BrainEngine } from '../engine.ts';
@@ -18,36 +20,51 @@ import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { privateProvenanceFilterFragment } from './private-visibility.ts';
import { factEntitySlugs } from '../mentions/siblings.ts';
import { resolveQueryEntities, type ResolvedEntity } from './alias-fanout.ts';
+import { collapseFactReads } from '../facts/capture-dedup.ts';
+import type { FactAttribution } from '../engine.ts';
export const ENTITY_FACTS_CAP = 5;
export const LINKED_FACTS_CAP = 3;
const LINKED_ENTITIES_CAP = 2;
-export interface EntityFact { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string; linked_from?: string }
+export interface EntityFact { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string; linked_from?: string;
+ /** #7043: every entity of the copies this row stands for, and how many rows it stands for. */
+ entity_slugs?: string[]; collapsed_count?: number }
-async function newestFacts(engine: BrainEngine, sourceId: string, slugs: string[], remote: boolean, limit: number): Promise<EntityFact[]> {
+/** Rows read per cap so copies of one claim collapse before the cap (#7043). */
+export const SAVED_FACTS_COLLAPSE_WINDOW = 50;
+/** The columns the collapse reads besides a saved fact's own; `stripCollapseColumns` drops them from the response. */
+export const SAVED_FACT_COLLAPSE_COLUMNS = 'f.source_id, f.visibility, f.created_at, f.attributed_to, gbrain_fact_fingerprint(f.fact) AS fact_fingerprint';
+export type CollapseColumns = { source_id: string; visibility: string; created_at: Date | string; attributed_to: FactAttribution | null; fact_fingerprint: string };
+
+/** A saved fact as the response carries it, without the collapse columns and member ids. */
+export function stripCollapseColumns<T extends CollapseColumns & { collapsed_ids?: number[] }>({ source_id: _s, visibility: _v, created_at: _c, attributed_to: _a, fact_fingerprint: _f, collapsed_ids: _i, ...rest }: T): Omit<T, keyof CollapseColumns | 'collapsed_ids'> {
+ return rest;
+}
+
+async function newestFacts(engine: BrainEngine, sourceId: string, slugs: string[], remote: boolean, limit: number): Promise<Array<EntityFact & CollapseColumns>> {
const visibility = remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : '';
- const rows = await engine.executeRaw<EntityFact>(
- `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source
+ const rows = await engine.executeRaw<EntityFact & CollapseColumns>(
+ `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source, ${SAVED_FACT_COLLAPSE_COLUMNS}
FROM facts f
WHERE f.source_id = $1 AND f.entity_slug = ANY($2::text[])
AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
AND f.source != ALL($3::text[])
${visibility}
ORDER BY f.valid_from DESC, f.id DESC
- LIMIT ${limit}`,
+ LIMIT ${SAVED_FACTS_COLLAPSE_WINDOW}`,
[sourceId, slugs, [...AUDIT_ROW_SOURCES]]);
- return rows.map(r => ({ ...r, id: Number(r.id) }));
+ return (await collapseFactReads(engine, rows.map(r => ({ ...r, id: Number(r.id) })))).slice(0, limit);
}
-/** The named entity's newest facts, then those of entities its facts name. Fail-soft: errors return []. */
-export async function entitySavedFacts(engine: BrainEngine, entity: ResolvedEntity, opts: { remote: boolean; excludePrivate: boolean }): Promise<EntityFact[]> {
+/** The named entity's newest facts, then those of entities its facts name, with the collapse columns. Fail-soft: errors return []. */
+export async function entitySavedFacts(engine: BrainEngine, entity: ResolvedEntity, opts: { remote: boolean; excludePrivate: boolean }): Promise<Array<EntityFact & CollapseColumns>> {
try {
const sourceId = entity.pages[0]!.source_id;
const own = new Set<string>();
for (const p of entity.pages) for (const s of await factEntitySlugs(engine, sourceId, p.slug, { excludePrivate: opts.excludePrivate })) own.add(s);
const facts = await newestFacts(engine, sourceId, [...own], opts.remote, ENTITY_FACTS_CAP);
- const out: EntityFact[] = [...facts];
+ const out: Array<EntityFact & CollapseColumns> = [...facts];
const seenEntities = new Set(own);
let linked = 0;
for (const f of facts) {
diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.ts
index 9d28e6455d..559a5f2e3f 100644
--- a/test/conversation-facts-managed.test.ts
+++ b/test/conversation-facts-managed.test.ts
@@ -63,16 +63,20 @@ async function putPage(brain: ManagedBrain, content: string, slug = SLUG): Promi
await disposePersistenceConsumer(brain.engine);
}
-/** One extraction run on the page with a counting extractor; `fact` shapes the returned fact. */
+/**
+ * One extraction run on the page with a counting extractor; `fact` shapes the returned fact, `factFor` per page from
+ * its turn text (#7043: a second page returning the very same claim is skipped as a duplicate, so multi-page runs
+ * give each page its own claim).
+ */
async function extract(engine: BrainEngine, calls: { n: number }, opts: { force?: boolean; segmentLimit?: number; fact?: Partial<ExtractedFact>;
- slugs?: string[]; onCall?: (turnText: string) => Promise<void> } = {}) {
+ factFor?: (turnText: string) => Partial<ExtractedFact>; slugs?: string[]; onCall?: (turnText: string) => Promise<void> } = {}) {
return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: opts.slugs ?? [SLUG], sleepMs: 0, overrideDisabled: true,
force: opts.force, segmentLimit: opts.segmentLimit,
extractor: async ({ turnText }) => {
calls.n++;
await opts.onCall?.(turnText);
return [{ fact: 'Owner Example sends the quarterly plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null,
- source: 'test', notability: 'high', ...opts.fact } as ExtractedFact];
+ source: 'test', notability: 'high', ...opts.fact, ...opts.factFor?.(turnText) } as ExtractedFact];
} });
}
@@ -85,6 +89,12 @@ async function extractorRows(engine: BrainEngine) {
const PROSE = (title: string) => ['---', `title: ${title}`, 'type: meeting', 'date: 2026-09-28', '---',
'**Date:** 2026-09-28', '**Attendees:** Alice Example, Owner Example', '', '## Notes', 'Hiring, the support backlog and the launch dates.', ''].join('\n');
const titled = (title: string) => transcript().replace('title: Plan sync', `title: ${title}`);
+const PLAN = 'Owner Example sends the quarterly plan on Thursday';
+/** #7043: the numbered plan syncs state their own claim, so no page's fact is an exact copy of another's. */
+const numbered = (turnText: string): Partial<ExtractedFact> => {
+ const n = /Plan sync (two|three)/.exec(turnText)?.[1];
+ return n ? { fact: `${PLAN} (${n})` } : {};
+};
async function factsOf(engine: BrainEngine, slug: string) {
return (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1
@@ -204,20 +214,20 @@ for (const backend of testBackends()) {
const restore = __setMaintenanceWriteWaitForTests(300);
const calls = { n: 0 };
try {
- const first = await extract(engine, calls, { slugs: [SLUG, OTHER] });
+ const first = await extract(engine, calls, { slugs: [SLUG, OTHER], factFor: numbered });
expect(first).toMatchObject({ pages_pending: 2, facts_inserted: 0 });
expect(calls.n).toBe(2);
__setMaintenanceWriteWaitForTests(20_000);
setTimeout(release, 300);
// The first page waits for the batch and replays its receipt; the second is then complete already.
- const second = await extract(engine, calls, { slugs: [SLUG, OTHER] });
+ const second = await extract(engine, calls, { slugs: [SLUG, OTHER], factFor: numbered });
expect(second).toMatchObject({ pages_processed: 1, pages_skipped_completed: 1, facts_inserted: 1 });
expect(calls.n).toBe(2);
} finally { release(); restore(); }
expect(await factsOf(engine, SLUG)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);
- expect(await factsOf(engine, OTHER)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);
+ expect(await factsOf(engine, OTHER)).toEqual([`${PLAN} (two)`, 'EXTRACTION_COMPLETE']);
expect((await requests(engine)).map(r => r.state)).toEqual(['committed']);
- const third = await extract(engine, calls, { slugs: [SLUG, OTHER] });
+ const third = await extract(engine, calls, { slugs: [SLUG, OTHER], factFor: numbered });
expect(third).toMatchObject({ pages_skipped_completed: 2 });
expect(calls.n).toBe(2);
}, { databaseUrl });
@@ -235,7 +245,7 @@ for (const backend of testBackends()) {
extractor: async ({ turnText }) => {
calls.n++;
const kind = bad && !turnText.includes('Plan sync two') ? 'not-a-kind' : 'commitment';
- return [{ fact: 'Owner Example sends the quarterly plan on Thursday', kind, confidence: 0.9, entity_slug: null, source: 'test' } as unknown as ExtractedFact];
+ return [{ fact: PLAN, kind, confidence: 0.9, entity_slug: null, source: 'test', ...numbered(turnText) } as unknown as ExtractedFact];
} });
const first = await run();
expect(first).toMatchObject({ pages_blocked: 1, pages_processed: 1, pages_failed: 0 });
@@ -339,7 +349,7 @@ for (const backend of testBackends()) {
await putPage(brain, titled('Plan sync three'), LAST);
const calls = { n: 0 };
let edited = false;
- const first = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST], onCall: async text => {
+ const first = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST], factFor: numbered, onCall: async text => {
// MOVED's entry is already in the batch when LAST is extracted; edit it before the batch publishes.
if (!edited && text.includes('Plan sync three')) { edited = true; await putPage(brain, titled('Plan sync two').replace('Thursday', 'Friday'), MOVED); }
} });
@@ -349,10 +359,10 @@ for (const backend of testBackends()) {
expect((await requests(engine)).map(r => r.state)).toEqual(['committed']);
expect(await factsOf(engine, MOVED)).toEqual([]);
expect(await factsOf(engine, NOTES)).toEqual(['EXTRACTION_NOT_APPLICABLE']);
- const second = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST] });
+ const second = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST], factFor: numbered });
expect(second).toMatchObject({ pages_processed: 1, pages_skipped_completed: 2, pages_skipped_non_extractable: 1 });
expect(calls.n).toBe(4);
- expect(await factsOf(engine, MOVED)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);
+ expect(await factsOf(engine, MOVED)).toEqual([`${PLAN} (two)`, 'EXTRACTION_COMPLETE']);
}, { databaseUrl });
}, 120_000);
diff --git a/test/conversation-facts-source-dedup-7043.test.ts b/test/conversation-facts-source-dedup-7043.test.ts
new file mode 100644
index 0000000000..9a4b76978e
--- /dev/null
+++ b/test/conversation-facts-source-dedup-7043.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #7043 (reported by @mikez93): conversation-fact extraction is an explicit
+ * lane, so the capture lanes' duplicate policy never ran on it, and a claim an
+ * agent's standing prompt repeated on every run's page was stored once per
+ * page. A candidate whose fingerprint matches an active fact of the same
+ * source is now skipped, under the capture lane's entity and visibility rules
+ * (same entity, or another entity the claim names; a world candidate only
+ * against world facts) and with no time bound. The page's own rows that a
+ * replacement clears never count, so re-extracting a page keeps its facts.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { randomUUID } from 'node:crypto';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+let engine: BrainEngine;
+
+const PLAN = 'Owner Example sends the quarterly plan on Thursday';
+const transcript = (title: string) => [
+ '---', `title: ${title}`, 'type: meeting', 'date: 2026-09-28', '---',
+ '**Alice Example:** Can you send me the quarterly plan before the review?',
+ '**Owner Example:** Yes, I will send it on Thursday with the finance appendix.',
+ '**Alice Example:** Good. I review plans on Mondays, so that works.',
+ '**Owner Example:** I will flag any launch date changes in the summary.', '',
+].join('\n');
+
+async function call(name: string, params: Record<string, unknown>) {
+ const res = await dispatchToolCall(engine, name, params, { remote: false });
+ return JSON.parse(res.content[0]!.text!) as Record<string, any>;
+}
+
+async function extract(slug: string, fact: Partial<ExtractedFact> = {}, force = false) {
+ await disposePersistenceConsumer(engine);
+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, overrideDisabled: true, force,
+ extractor: async () => [{ fact: PLAN, kind: 'commitment', confidence: 0.9, entity_slug: null, source: 'test', notability: 'high', ...fact } as ExtractedFact] });
+}
+
+async function active(text: string) {
+ return engine.executeRaw<{ id: number; source_markdown_slug: string; entity_slug: string | null; visibility: string }>(
+ `SELECT id, source_markdown_slug, entity_slug, visibility FROM facts WHERE source_id='default' AND fact=$1 AND expired_at IS NULL ORDER BY id`, [text]);
+}
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); });
+ beforeEach(async () => {
+ if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ for (const [slug, title] of [['meetings/run-1', 'Run 1'], ['meetings/run-2', 'Run 2']]) await call('put_page', { slug, content: transcript(title) });
+ for (const [slug, title] of [['people/alice-example', 'Alice Example'], ['people/bob-example', 'Bob Example']]) {
+ await call('put_page', { slug, content: `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nA person.\n` });
+ }
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('a claim another page already states is not stored again', async () => {
+ expect((await extract('meetings/run-1')).facts_inserted).toBe(1);
+ const second = await extract('meetings/run-2');
+ expect(second.pages_failed).toBe(0);
+ expect(second.facts_inserted).toBe(0);
+ expect((await active(PLAN)).map(r => r.source_markdown_slug)).toEqual(['meetings/run-1']);
+ });
+
+ test('re-extracting a page keeps its own fact', async () => {
+ await extract('meetings/run-1');
+ const again = await extract('meetings/run-1', {}, true);
+ expect(again.pages_failed).toBe(0);
+ expect((await active(PLAN)).map(r => r.source_markdown_slug)).toEqual(['meetings/run-1']);
+ });
+
+ test('a subject-relative claim on another entity is still stored', async () => {
+ await extract('meetings/run-1', { fact: 'Prefers tea.', entity_slug: 'people/alice-example' });
+ await extract('meetings/run-2', { fact: 'Prefers tea.', entity_slug: 'people/bob-example' });
+ expect((await active('Prefers tea.')).map(r => r.entity_slug)).toEqual(['people/alice-example', 'people/bob-example']);
+ });
+
+ test('a managed batch skips the copy inside its receipted publication', async () => {
+ await managedBrain(async (brain) => {
+ const outer = engine;
+ engine = brain.engine;
+ try {
+ for (const [slug, title] of [['meetings/run-1', 'Run 1'], ['meetings/run-2', 'Run 2']]) {
+ await submitPageMutation(brain.ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: transcript(title) } });
+ }
+ expect((await extract('meetings/run-1')).facts_inserted).toBe(1);
+ const second = await extract('meetings/run-2');
+ expect(second.pages_failed).toBe(0);
+ expect((await active(PLAN)).map(r => r.source_markdown_slug)).toEqual(['meetings/run-1']);
+ } finally {
+ await disposePersistenceConsumer(brain.engine);
+ engine = outer;
+ }
+ }, { databaseUrl: backend === 'postgres' ? requirePostgresTestDatabase() : undefined });
+ }, 120_000);
+
+ test('a world candidate is not matched against a private fact', async () => {
+ await engine.setConfig('facts.default_visibility', 'private');
+ await extract('meetings/run-1');
+ await engine.setConfig('facts.default_visibility', 'world');
+ await extract('meetings/run-2');
+ expect((await active(PLAN)).map(r => r.visibility)).toEqual(['private', 'world']);
+ });
+ });
+}
diff --git a/test/cycle-conversation-facts-backfill-exclude-7043.test.ts b/test/cycle-conversation-facts-backfill-exclude-7043.test.ts
new file mode 100644
index 0000000000..4713968e2d
--- /dev/null
+++ b/test/cycle-conversation-facts-backfill-exclude-7043.test.ts
@@ -0,0 +1,61 @@
+/**
+ * #7043 (reported by @mikez93): `cycle.conversation_facts_backfill.exclude_sources`
+ * names sources the backfill phase skips, so one source whose pages repeat a
+ * standing prompt can be left out without turning the phase off for every
+ * source. Unset (the default) skips nothing. A JSON array and a comma list
+ * both work. PGLite only: the key changes which sources the phase iterates,
+ * no SQL.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseConversationFactsBackfill, loadCfg } from '../src/core/cycle/conversation-facts-backfill.ts';
+
+let engine: PGLiteEngine;
+const KEY = 'cycle.conversation_facts_backfill.exclude_sources';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+ for (const id of ['source-a', 'source-b']) {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);
+ await engine.putPage(`conversations/${id}-chat`, { type: 'conversation', title: `Chat in ${id}`, timeline: '', frontmatter: {},
+ compiled_truth: '**Alice Example** (2024-03-15 9:00 AM): I signed the offer.\n**Bob Example** (2024-03-15 9:01 AM): Congrats!' }, { sourceId: id });
+ }
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await engine.executeRaw('DELETE FROM config WHERE key = $1', [KEY]); });
+
+describe('conversation_facts_backfill exclude_sources (#7043)', () => {
+ test('unset: every source runs and nothing is reported excluded', async () => {
+ expect((await loadCfg(engine)).excludeSources).toEqual([]);
+ const r = await runPhaseConversationFactsBackfill(engine, { dryRun: true });
+ const d = r.details as { per_source: Record<string, unknown>; sources_excluded: string[] };
+ expect(Object.keys(d.per_source)).toEqual(expect.arrayContaining(['default', 'source-a', 'source-b']));
+ expect(d.sources_excluded).toEqual([]);
+ });
+
+ test('a JSON array of source ids is skipped and reported', async () => {
+ await engine.setConfig(KEY, '["source-b"]');
+ const r = await runPhaseConversationFactsBackfill(engine, { dryRun: true });
+ const d = r.details as { per_source: Record<string, unknown>; sources_excluded: string[]; sources_count: number };
+ expect(Object.keys(d.per_source)).toContain('source-a');
+ expect(Object.keys(d.per_source)).not.toContain('source-b');
+ expect(d.sources_excluded).toEqual(['source-b']);
+ expect(r.summary).toContain('exclude_sources');
+ });
+
+ test('a comma list works too, and an unknown id excludes nothing else', async () => {
+ await engine.setConfig(KEY, 'source-a, source-missing');
+ expect((await loadCfg(engine)).excludeSources).toEqual(['source-a', 'source-missing']);
+ const r = await runPhaseConversationFactsBackfill(engine, { dryRun: true });
+ const d = r.details as { per_source: Record<string, unknown>; sources_excluded: string[] };
+ expect(Object.keys(d.per_source)).not.toContain('source-a');
+ expect(Object.keys(d.per_source)).toContain('source-b');
+ expect(d.sources_excluded).toEqual(['source-a']);
+ });
+});
diff --git a/test/extract-conversation-facts-plain-role.test.ts b/test/extract-conversation-facts-plain-role.test.ts
index a5c1413e4e..f4546a5db6 100644
--- a/test/extract-conversation-facts-plain-role.test.ts
+++ b/test/extract-conversation-facts-plain-role.test.ts
@@ -57,7 +57,9 @@ describe('plain role-prefixed transcripts', () => {
test('extract-conversation-facts extracts from plain and bold transcripts alike', async () => {
await seed('sessions/plain', PLAIN);
await seed('sessions/bold', BOLD);
- const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', types: ['conversation'], sleepMs: 0, extractor: async () => [fact('The user lives in Lisbon')] });
+ // #7043: each page states its own claim; the very same claim on a second page is skipped as a duplicate.
+ let page = 0;
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', types: ['conversation'], sleepMs: 0, extractor: async () => [fact(`The user lives in Lisbon (page ${++page})`)] });
expect(result.pages_skipped_unparsed).toBe(0);
expect(result.pages_processed).toBe(2);
expect(result.facts_inserted).toBeGreaterThanOrEqual(2);
diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.ts
index ecb83edd93..a7c9ef0444 100644
--- a/test/extract-conversation-facts.test.ts
+++ b/test/extract-conversation-facts.test.ts
@@ -766,7 +766,8 @@ describe('runExtractConversationFactsCore', () => {
sourceId: 'default', slug, sleepMs: 0,
extractor: async ({ turnText }) => {
extracted.push(turnText);
- return [{ fact: 'alice-example said hi', kind: 'event', confidence: 1, entity_slug: null, source: 'test' }];
+ // #7043: each body states its own claim; the very same claim on the second page is skipped as a duplicate.
+ return [{ fact: `alice-example said hi in body ${index}`, kind: 'event', confidence: 1, entity_slug: null, source: 'test' }];
},
});
expect(result).toMatchObject({ pages_processed: 1, pages_skipped_unparsed: 0, segments_processed: 1, facts_inserted: 1 });
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 9a765d5b01..074435f9e9 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -194,7 +194,7 @@ for (const backend of testBackends()) {
const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts',
- 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
+ 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
'overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror',
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6c7db283bf..19d51d6d28 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -44,6 +44,7 @@ test/company-brain-policy.test.ts
test/company-brain-runtime.test.ts
test/consolidate-same-instant-6023.test.ts
test/conversation-facts-oversized-sidecar.test.ts
+test/conversation-facts-source-dedup-7043.test.ts
test/cycle/synthesize-concepts-merge.test.ts
test/db-lock-reconnect.test.ts
test/decide/conflict-proposals-managed.test.ts
@@ -370,10 +371,12 @@ test/purge-global-marker.test.ts
test/purge-missing-cache-6911.test.ts
test/purge-read-surfaces.test.ts
test/purge-sync-tombstone-hold-7130.test.ts
+test/recall-collapse-duplicates-7043.test.ts
test/recall-page-fill.test.ts
test/receipt-compaction-newest-sync-gbra130.test.ts
test/remediation-manual-only.test.ts
test/repair-apply-pending-6543.test.ts
+test/repair-duplicate-facts-7043.test.ts
test/repair-embedding-effects.test.ts
test/repair-failed-writes-conflict-6429.test.ts
test/repair-failed-writes-drift-w411.test.ts
diff --git a/test/recall-collapse-duplicates-7043.test.ts b/test/recall-collapse-duplicates-7043.test.ts
new file mode 100644
index 0000000000..3d7a55b0ea
--- /dev/null
+++ b/test/recall-collapse-duplicates-7043.test.ts
@@ -0,0 +1,114 @@
+/**
+ * #7043 (reported by @mikez93): recall and search returned every copy of one
+ * claim, so a few copies crowded distinct facts out of the limit. Rows with
+ * the same fingerprint in one source and visibility now collapse into one row
+ * (hot memory's rule: same entity, or another entity the claim names) that
+ * carries every entity slug and how many rows it stands for, before the limit
+ * cut. Private and world copies never merge, a remote caller's world-only
+ * filter applies first, and subject-relative claims on two entities stay two
+ * rows.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+
+let engine: BrainEngine;
+
+async function call(name: string, params: Record<string, unknown>, remote = false) {
+ const res = await dispatchToolCall(engine, name, params, { remote, sourceId: 'default' });
+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any>, meta: res._meta as Record<string, any> | undefined };
+}
+
+async function fact(text: string, entity: string, day: string, visibility: 'world' | 'private' = 'world') {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from, created_at)
+ VALUES ('default', $1, $2, 'preference', $3, 'test', $4::timestamptz, $4::timestamptz)`, [entity, text, visibility, `${day}T12:00:00Z`]);
+}
+
+const EMAIL = 'Alice Example prefers email.';
+const ALICE = 'people/alice-example';
+const BOB = 'people/bob-example';
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); });
+ beforeEach(async () => {
+ if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ await call('put_page', { slug: ALICE, content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nA person.\n' });
+ await call('put_page', { slug: BOB, content: '---\ntitle: Bob Example\ntype: person\n---\n# Bob Example\n\nA person.\n' });
+ await fact('Alice Example lives in Lisbon.', ALICE, '2026-01-01');
+ await fact('Prefers tea.', ALICE, '2026-01-15');
+ await fact('Prefers tea.', BOB, '2026-01-16');
+ await fact(EMAIL, ALICE, '2026-02-01');
+ await fact(EMAIL, ALICE, '2026-02-02');
+ await fact(EMAIL, ALICE, '2026-02-03');
+ await fact(EMAIL, BOB, '2026-02-04');
+ await fact(EMAIL, ALICE, '2026-02-05', 'private');
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('recall collapses copies before the limit, so distinct facts are not crowded out', async () => {
+ const { body } = await call('recall', { limit: 5 });
+ const facts = body.facts as Array<Record<string, any>>;
+ expect(facts.map(f => f.fact)).toContain('Alice Example lives in Lisbon.');
+ const world = facts.filter(f => f.fact === EMAIL && f.visibility === 'world');
+ expect(world).toHaveLength(1);
+ expect(world[0]!.collapsed_count).toBe(4);
+ expect([...world[0]!.entity_slugs].sort()).toEqual([ALICE, BOB]);
+ expect(facts.filter(f => f.fact === EMAIL && f.visibility === 'private')).toHaveLength(1);
+ // A subject-relative claim on two entities names neither, so it stays two rows.
+ expect(facts.filter(f => f.fact === 'Prefers tea.').map(f => f.entity_slug).sort()).toEqual([ALICE, BOB]);
+ expect(facts.filter(f => f.fact === 'Prefers tea.').every(f => f.collapsed_count === undefined)).toBe(true);
+ expect(body.total).toBe(5);
+ expect(facts.every(f => !('collapsed_ids' in f))).toBe(true);
+ });
+
+ test('a remote caller sees only world rows, collapsed among themselves', async () => {
+ const { body } = await call('recall', { limit: 5 }, true);
+ const facts = body.facts as Array<Record<string, any>>;
+ expect(facts.every(f => f.visibility === 'world')).toBe(true);
+ const email = facts.filter(f => f.fact === EMAIL);
+ expect(email).toHaveLength(1);
+ expect(email[0]!.collapsed_count).toBe(4);
+ });
+
+ test('recall with a question ranks one row per claim', async () => {
+ const { body } = await call('recall', { question: 'Does Alice Example prefer email?', limit: 10 });
+ const facts = body.facts as Array<Record<string, any>>;
+ const world = facts.filter(f => f.fact === EMAIL && f.visibility === 'world');
+ expect(world).toHaveLength(1);
+ expect(world[0]!.collapsed_count).toBe(4);
+ });
+
+ test('recall by entity collapses the entity\'s copies', async () => {
+ const { body } = await call('recall', { entity: ALICE, limit: 3 });
+ const facts = body.facts as Array<Record<string, any>>;
+ expect(facts.filter(f => f.fact === EMAIL && f.visibility === 'world')).toHaveLength(1);
+ expect(facts.map(f => f.fact)).toContain('Prefers tea.');
+ });
+
+ test('search saved_facts carry one row per claim and visibility', async () => {
+ const res = await call('search', { query: 'Alice Example prefers email' });
+ const saved = (res.meta?.retrieval?.saved_facts ?? []) as Array<Record<string, any>>;
+ const email = saved.filter(f => f.fact === EMAIL);
+ expect(email).toHaveLength(2);
+ expect(email.some(f => f.collapsed_count === 4)).toBe(true);
+ expect(saved.every(f => !('fact_fingerprint' in f) && !('visibility' in f) && !('collapsed_ids' in f))).toBe(true);
+ });
+ });
+}
diff --git a/test/repair-duplicate-facts-7043.test.ts b/test/repair-duplicate-facts-7043.test.ts
new file mode 100644
index 0000000000..26e787ad12
--- /dev/null
+++ b/test/repair-duplicate-facts-7043.test.ts
@@ -0,0 +1,203 @@
+/**
+ * #7043 (reported by @mikez93): `gbrain repair duplicate-facts` retires exact
+ * copies of one active fact. In each group of active facts of one source and
+ * visibility with one fingerprint, the oldest row is kept and the others are
+ * superseded by it (expired_at set, superseded_by the kept row; never a
+ * withdrawal). Copies on other entities are listed apart and retired only
+ * with --include-cross-entity; near duplicates are never touched; a fenced
+ * copy is struck in its page as "superseded by #N" when the kept row is in the
+ * same fence and kept otherwise. Explicit-only and preview-bound.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { parseFactsFence } from '../src/core/facts-fence.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { randomUUID } from 'node:crypto';
+
+let engine: BrainEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-duplicate-facts-'));
+
+async function call(name: string, params: Record<string, unknown>) {
+ const res = await dispatchToolCall(engine, name, params, { remote: false });
+ return JSON.parse(res.content[0]!.text!) as Record<string, any>;
+}
+
+async function fact(text: string, entity: string, day: string, visibility: 'world' | 'private' = 'world'): Promise<number> {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from, created_at)
+ VALUES ('default', $1, $2, 'fact', $3, 'test', $4::timestamptz, $4::timestamptz) RETURNING id`, [entity, text, visibility, `${day}T12:00:00Z`]);
+ return Number(row!.id);
+}
+
+/** `ownHome`: keep the caller's GBRAIN_HOME (a managed brain's worktree claim lives there). */
+async function repair(args: string[], ownHome = false): Promise<Record<string, any>> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ const run = () => runRepairCommand(engine, ['duplicate-facts', ...args, '--json']);
+ try { await (ownHome ? run() : withEnv({ GBRAIN_HOME: home }, run)); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')).results[0];
+}
+
+async function state(ids: number[]) {
+ const rows = await engine.executeRaw<{ id: number; expired_at: unknown; superseded_by: number | null; entity_slug: string | null }>(
+ 'SELECT id, expired_at, superseded_by, entity_slug FROM facts WHERE id = ANY($1::bigint[]) ORDER BY id', [ids]);
+ return rows.map(r => ({ id: Number(r.id), active: r.expired_at === null, superseded_by: r.superseded_by === null ? null : Number(r.superseded_by) }));
+}
+
+const fencePage = (title: string, claim: string) => [
+ '---', `title: ${title}`, 'type: person', '---', `# ${title}`, '', '## Facts', '',
+ '<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ `| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | test | |`,
+ `| 2 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | test | |`,
+ '<!--- gbrain:facts:end -->', '',
+].join('\n');
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); rmSync(home, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ for (const [slug, title] of [['people/alice-example', 'Alice Example'], ['people/bob-example', 'Bob Example']]) {
+ await call('put_page', { slug, content: `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nA person.\n` });
+ }
+ }, 60_000);
+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });
+
+ test('same-entity copies are superseded by the oldest row; cross-entity copies wait for the flag; near duplicates stay', async () => {
+ const email = [await fact('Alice Example prefers email.', 'people/alice-example', '2026-01-01'),
+ await fact('Alice Example prefers email.', 'people/alice-example', '2026-01-02'),
+ await fact('alice example prefers email', 'people/alice-example', '2026-01-03')];
+ const privateCopy = await fact('Alice Example prefers email.', 'people/alice-example', '2026-01-04', 'private');
+ const near = await fact('Alice Example prefers e-mail.', 'people/alice-example', '2026-01-05');
+ const team = [await fact('The team ships on Fridays.', 'people/alice-example', '2026-01-01'), await fact('The team ships on Fridays.', 'people/bob-example', '2026-01-02')];
+
+ const preview = await repair([]);
+ expect(preview.residuals).toMatchObject({ same_entity_groups: 1, cross_entity_groups: 1, copies_to_retire: 2, cross_entity_copies_held: 1 });
+ expect(preview.listing.map((l: { class: string }) => l.class).sort()).toEqual(['cross_entity_held', 'same_entity']);
+ expect(preview.apply_command).toContain('--yes');
+ expect(await state(email)).toEqual(email.map(id => ({ id, active: true, superseded_by: null })));
+
+ const applied = await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(applied.applied).toBe(1);
+ expect(await state(email)).toEqual([{ id: email[0], active: true, superseded_by: null },
+ { id: email[1], active: false, superseded_by: email[0] }, { id: email[2], active: false, superseded_by: email[0] }]);
+ expect(await state([privateCopy, near, ...team])).toEqual([privateCopy, near, ...team].map(id => ({ id, active: true, superseded_by: null })));
+ // Supersession is not a withdrawal: the claim stays rememberable.
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals')).toHaveLength(0);
+
+ const cross = await repair(['--include-cross-entity']);
+ expect(cross.residuals).toMatchObject({ cross_entity_groups: 1, copies_to_retire: 1, cross_entity_copies_held: 0 });
+ await repair(['--include-cross-entity', '--apply', '--expect', cross.preview_hash, '--yes']);
+ expect(await state(team)).toEqual([{ id: team[0], active: true, superseded_by: null }, { id: team[1], active: false, superseded_by: team[0] }]);
+ expect((await repair([])).affected).toBe(0);
+ });
+
+ test('apply refuses a hash from another selection and keeps a copy that changed since the preview', async () => {
+ const ids = [await fact('Bob Example uses vim.', 'people/bob-example', '2026-01-01'), await fact('Bob Example uses vim.', 'people/bob-example', '2026-01-02'),
+ await fact('Bob Example uses vim.', 'people/bob-example', '2026-01-03')];
+ const preview = await repair([]);
+ await expect(withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['duplicate-facts', '--include-cross-entity', '--apply', '--expect', preview.preview_hash, '--yes', '--json'])))
+ .rejects.toThrow();
+ await engine.executeRaw('UPDATE facts SET expired_at = now() WHERE id = $1', [ids[2]]);
+ const applied = await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(applied.outcomes).toEqual({ partially_superseded: 1 });
+ expect(await state(ids)).toEqual([{ id: ids[0], active: true, superseded_by: null }, { id: ids[1], active: false, superseded_by: ids[0] },
+ { id: ids[2], active: false, superseded_by: null }]);
+ });
+
+ test('a managed brain retires database-only copies in a coordinated write and fenced copies through put_page', async () => {
+ const outer = engine;
+ try {
+ await managedBrain(async (brain) => {
+ engine = brain.engine;
+ await submitPageMutation(brain.ctx, { operation: 'put_page', params: { slug: 'people/carol-example', request_id: randomUUID(),
+ content: fencePage('Carol Example', 'Carol Example likes jazz.') } });
+ const carol = (await engine.executeRaw<{ id: number }>(
+ "SELECT id FROM facts WHERE source_markdown_slug='people/carol-example' AND expired_at IS NULL ORDER BY row_num")).map(r => Number(r.id));
+ const db = (await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact='Erin Example runs marathons.' ORDER BY created_at, id")).map(r => Number(r.id));
+ const preview = await repair([], true);
+ expect(preview.residuals).toMatchObject({ same_entity_groups: 2, copies_to_retire: 2 });
+ const applied = await repair(['--apply', '--expect', preview.preview_hash, '--yes'], true);
+ expect(applied.stopped).toBeUndefined();
+ expect(applied.outcomes).toEqual({ superseded: 2 });
+ expect(await state(db)).toEqual([{ id: db[0], active: true, superseded_by: null }, { id: db[1], active: false, superseded_by: db[0] }]);
+ expect(await state(carol)).toEqual([{ id: carol[0], active: true, superseded_by: null }, { id: carol[1], active: false, superseded_by: carol[0] }]);
+ await disposePersistenceConsumer(engine);
+ }, { databaseUrl: backend === 'postgres' ? requirePostgresTestDatabase() : undefined, setup: async ({ engine: e }) => {
+ for (const day of ['2026-01-01', '2026-01-02']) await e.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from, created_at)
+ VALUES ('default', 'people/erin-example', 'Erin Example runs marathons.', 'fact', 'world', 'test', $1::timestamptz, $1::timestamptz)`, [`${day}T12:00:00Z`]);
+ } });
+ } finally { engine = outer; }
+ }, 120_000);
+
+ test('a fenced copy is struck in its page when the kept row shares the fence, and kept when it does not', async () => {
+ await call('put_page', { slug: 'people/carol-example', content: fencePage('Carol Example', 'Carol Example likes jazz.') });
+ const carol = (await engine.executeRaw<{ id: number; row_num: number }>(
+ "SELECT id, row_num FROM facts WHERE source_markdown_slug='people/carol-example' AND expired_at IS NULL ORDER BY row_num")).map(r => ({ id: Number(r.id), row: Number(r.row_num) }));
+ expect(carol.map(r => r.row)).toEqual([1, 2]);
+ const dana = await fact('Dana Example plays chess.', 'people/dana-example', '2020-01-01');
+ await call('put_page', { slug: 'people/dana-example', content: fencePage('Dana Example', 'Dana Example plays chess.').replace(/\n\| 2 \|[^\n]*/, '') });
+
+ const preview = await repair([]);
+ expect(preview.residuals.fence_kept_elsewhere).toBe(1);
+ expect(preview.listing.some((l: { class: string; item: string }) => l.class === 'fence_kept_elsewhere' && l.item.endsWith(`fact#${dana}`))).toBe(true);
+ await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+
+ expect(await state(carol.map(r => r.id))).toEqual([{ id: carol[0]!.id, active: true, superseded_by: null }, { id: carol[1]!.id, active: false, superseded_by: carol[0]!.id }]);
+ const page = await call('get_page', { slug: 'people/carol-example', include_content: true });
+ const rows = parseFactsFence(String(page.content ?? page.compiled_truth)).facts;
+ expect(rows.find(r => r.rowNum === 2)).toMatchObject({ active: false, supersededBy: 1 });
+ expect(rows.find(r => r.rowNum === 1)?.active).toBe(true);
+ const danaFence = await engine.executeRaw("SELECT 1 FROM facts WHERE source_markdown_slug='people/dana-example' AND expired_at IS NULL");
+ expect(danaFence).toHaveLength(1);
+ });
+
+ test('a fenced copy on a segmented page is kept as segmented_page, in the preview and in an apply that finds the page segmented since', async () => {
+ const segment = (slug: string) => engine.executeRaw(
+ "UPDATE pages SET body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_bytes = 1 WHERE source_id = 'default' AND slug = $1", [slug]);
+ const fenceRows = async (slug: string) => (await engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE source_markdown_slug = $1 AND expired_at IS NULL ORDER BY row_num', [slug])).map(r => Number(r.id));
+ await call('put_page', { slug: 'people/erin-example', content: fencePage('Erin Example', 'Erin Example keeps bees.') });
+ await call('put_page', { slug: 'people/frank-example', content: fencePage('Frank Example', 'Frank Example builds boats.') });
+ const erin = await fenceRows('people/erin-example');
+ const frank = await fenceRows('people/frank-example');
+ await segment('people/erin-example');
+
+ const preview = await repair([]);
+ expect(preview.residuals).toMatchObject({ segmented_page: 1, copies_to_retire: 1 });
+ expect(preview.listing.some((l: { class: string; item: string }) => l.class === 'segmented_page' && l.item.endsWith(`fact#${erin[0]}`))).toBe(true);
+ await segment('people/frank-example');
+ const applied = await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+
+ expect(applied.outcomes).toEqual({ segmented_page: 1 });
+ expect(applied.outcome_items[0]).toMatchObject({ outcome: 'segmented_page', detail: { kept: frank[0], superseded: 0, segmented_page: 1 } });
+ expect(applied.outcome_items[0].reason).toContain('segmented page');
+ expect(await state([...erin, ...frank])).toEqual([...erin, ...frank].map(id => ({ id, active: true, superseded_by: null })));
+ });
+ });
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 1bdcc370f6..7abb63f7f7 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[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));