Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): conversation relink survives re-extraction; doctor sequences free then paid with an approved cap (#6764)

garrytan7d8caca7ba65
diff --git a/docs/.wave18-fragments/lane3.md b/.wave18-fragments/lane3.md
similarity index 81%
rename from docs/.wave18-fragments/lane3.md
rename to .wave18-fragments/lane3.md
index c92b271ff9..82186b9680 100644
--- a/docs/.wave18-fragments/lane3.md
+++ b/.wave18-fragments/lane3.md
@@ -82,12 +82,12 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
```ts
- { since: '<WAVE>', text: '`gbrain extract-conversation-facts` (and the `conversation_facts_backfill` cycle phase) now runs the free write-time subject inference on facts the extractor returns without an entity, so a fact naming exactly one entity page in full is stored on that entity (context note `entity inferred from mention`; off with `facts.entity_inference false`) (#6764). Doctor `unlinked_facts` counts the conversation extractor\'s unlinked rows on their own (origin `conversation`, no longer inside fence-owned) and, because `gbrain facts relink` never examines them, its fix is a bounded, source-qualified re-extraction of the pages with the most (`--slugs`, up to 50, `--force --max-cost-usd 1`, preview `--dry-run`; paid, asks the user first). A `replaces` naming a conversation-derived fact now says to re-extract its page instead of hinting at a fence edit.' },
+ { since: '<WAVE>', text: '`gbrain extract-conversation-facts` (and the `conversation_facts_backfill` cycle phase) now runs the free write-time subject inference on facts the extractor returns without an entity, so a fact naming exactly one entity page in full is stored on that entity (context note `entity inferred from mention`; off with `facts.entity_inference false`) (#6764). Doctor `unlinked_facts` counts the conversation extractor\'s unlinked rows on their own (origin `conversation`, no longer inside fence-owned) and, because `gbrain facts relink` never examines them, its fix is a bounded, source-qualified re-extraction of the pages with the most (`--slugs`, up to 50, `--force --max-cost-usd <N>` with the approved amount as the input `N`, preview `--dry-run`; paid, asks the user first). A `replaces` naming a conversation-derived fact now says to re-extract its page instead of hinting at a fence edit.' },
```
### CHANGELOG.md (wave entry, Fixed)
-- Facts extracted from conversations now link to the person or company they name when only one entity page matches, and doctor's `unlinked_facts` gives conversation facts a fix that can act on them (a capped re-extraction of the named pages, previewed first) instead of `gbrain facts relink`, which never touched them (#6764).
+- Facts extracted from conversations now link to the person or company they name when only one entity page matches, and doctor's `unlinked_facts` gives conversation facts a fix that can act on them (a re-extraction of the named pages capped at the amount the user approves, previewed first) instead of `gbrain facts relink`, which never touched them (#6764).
### scripts/module-size-limits.tsv
@@ -97,7 +97,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- New exported symbols (no registry rows needed): `CONVERSATION_FIX_SLUGS` (doctor/checks/unlinked-facts.ts), `inferConversationSubjects` (core/facts/conversation-subject-infer.ts). The `replaces_cross_page_derived` suggestion lives in core/persistence/verb-errors.ts beside the existing `replaces_cross_page` text; no error-registry code was added.
-## #6764 (d1b, own commit: drop it if Garry picks d1a) free conversation relink as the doctor's primary fix
+## #6764 free conversation relink as the doctor's primary fix (decision d1b)
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -113,10 +113,23 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- New maintenance intent kind `managed_maintenance_conversation_relink`, dispatched in `src/core/persistence/prepared-maintenance.ts` (one line, not a listed registry). New canonical-writer census row for `src/core/facts/conversation-relink.ts` in `docs/architecture/canonical-writers.tsv` (ceiling 1, boundary coordinator).
- Module sizes: `src/commands/facts.ts` 201 lines, `src/core/facts/conversation-relink.ts` 187 (new), `src/core/persistence/prepared-maintenance.ts` 590; none is listed in the TSV and all are under the new-file cap. No TSV change.
-- Dropping this commit (d1a) restores the commit before it exactly: doctor prescribes the paid re-extraction for every unlinked conversation row. The commit also edits that commit's own tests (seeding a `conversation_unresolved` memo so they still exercise the paid envelope).
## Gate follow-ups (all items)
- `src/core/cli-flag-registry.generated.ts`: regenerated with `bun run build:flag-registry` in the separate final commit "INTEGRATOR-ROW: regenerate cli-flag-registry for lane 3" (tests docs-cli-commands, remediation-command-resolution, cli-flag-validation and conversation-facts-type-allowlist-drift need it). Additive only: facts +`--conversation --force --slugs --source-id`, doctor +`--conversation --entity --retry-model`, lint +`--max-cost-usd --slugs`, maintain and sync +`--conversation`. Drop it and rerun the generator after the lanes merge.
- New exemption in `scripts/check-core-guard-coverage.mjs` (conversation-relink.ts: database-only fact rows, page text unchanged) and a write-attribution row in `docs/architecture/system-of-record.md`.
- gstack pregate `literals` reports ~643 test locations "still carrying" MENTION_EXTRACTOR_VERSION 5. Every hit except test/mentions-pass.test.ts (fixed to use the symbol) is an unrelated literal 5 (array indexes, model names, counts); no test pins the mention version as a number. The `lanes` check flags this fragment file, which the integrator deletes.
+
+
+## #6764 follow-up (v3 review r2-d1)
+
+- The free path is `gbrain facts relink --conversation` (a flag on the existing verb). It stays a receipted, database-only linkage of the derived row: `entity_slug` plus the `entity relinked from mention` note on the row itself, one maintenance transaction per page (a `managed_maintenance_conversation_relink` request on a managed brain). Conversation ownership, fact id, provenance and trust are kept and no Markdown is edited, so the doctor envelope asks no consent (`[]`, actor agent; `host_admin` on the remote path). Conversation pages have no `## Facts` fence (canonical projection and the extract_facts reconcile skip extractor rows, #1928), so `FACTS_FENCE_COLUMNS` having no entity column does not matter here.
+- `extract-conversation-facts --force` keeps the link: `clearConversationFacts` expires relinked rows instead of deleting them and the replacement row of the same claim inherits the entity (new module `src/core/facts/conversation-relink-carry.ts`). Tested unmanaged and managed with write-time inference off, plus the extract_facts reconcile.
+- Every derived row the free pass examines is memoized in `fact_relink_attempts` (`linked` or `conversation_unresolved`), so doctor sequences free relink while untried rows exist, then the paid fallback scoped to the memoized pages (at most 50) with `--max-cost-usd <N>` and `inputs: [{ name: 'N' }]`.
+- 25% rule: memoized `conversation_unresolved` rows are excluded from the new-fact share like `no_subject` (`details.new_7d.conversation_unresolved`).
+- `RELINK_REASONS.fence_owned` text names `gbrain facts relink --conversation` (the guide table in docs/guides/facts-relink.md matches).
+
+### src/core/behavior-change-notice.ts (replace the #6764 rows' paid-fallback wording)
+
+- In both #6764 rows, the paid fallback is "capped at the amount the user approves (`--max-cost-usd <N>`)", not "`--max-cost-usd 1`", and the second row should add: "A re-extraction of the page keeps a relinked fact's entity on the claim's new row. Rows the free pass could not resolve no longer count toward doctor's 25% new-fact warning."
+
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index d3a89393f7..776b7705ed 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -7,7 +7,7 @@ src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one
src/core/persistence/takes-prepare.ts 4 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation. takes_remove deletes the removed row inside the same coordinated apply (#5167).
src/commands/extract-timeline-db.ts 2 coordinator `gbrain extract timeline --source db` (#5904): on a managed brain the timeline retraction and insert run only inside the managed_maintenance_timeline_extract publication (prepareTimelineExtract; owner-checked by maintenancePreflight, page key locked, revision-bound); only an unmanaged brain retracts and batch-inserts directly, where no canonical writer enforcement applies.
src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain each page's fact rows and outcome row are frozen into one database-only managed_maintenance_conversation_facts request (facts/conversation-publication.ts) after a maintenance preflight before provider work; the coordinator's preparer revalidates page identity, revision and parser-input snapshot under the page key. Unmanaged calls keep their direct engine writes behind the SQL guard (writeDerivedFacts refuses on a managed brain).
-src/core/facts/conversation-publication.ts 4 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) and inserts each member page's frozen entry inside the coordinator publication of its admitted managed_maintenance_conversation_facts batch request, after rechecking authority, page identity, revision and version token under each page key (a moved page is skipped and reported, never failing the batch; a page whose rows fail validation gets a blocked not-extractable outcome row); a lost insert rolls the publication back. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction.
+src/core/facts/conversation-publication.ts 6 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) and inserts each member page's frozen entry inside the coordinator publication of its admitted managed_maintenance_conversation_facts batch request, after rechecking authority, page identity, revision and version token under each page key (a moved page is skipped and reported, never failing the batch; a page whose rows fail validation gets a blocked not-extractable outcome row); a lost insert rolls the publication back. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction. The clear also expires rows the free conversation relink linked, after deleting the previous clear's expired relinked copies, so the replacement inherits their entity (#6764, conversation-relink-carry.ts).
src/core/facts/conversation-relink.ts 1 coordinator `gbrain facts relink --conversation` (#6764) sets entity_slug and the relink note on a conversation page's unlinked derived rows still exactly as planned (same claim, unlinked, active, target page live) under the page key: one database-only managed_maintenance_conversation_relink request per page on a managed brain (the preparer authorizes the anchor and the page), one writeDerivedFacts maintenance transaction per page on an unmanaged brain.
src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.
src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair preflights every target before the first backup/write.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index aadf9bbacc..dde8d836c4 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -31,4 +31,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those, reads through `deadlineEngine` (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`.
- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.
-- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain, a bounded re-extraction of those pages (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd 1`, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
+- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain, a bounded re-extraction of those pages (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index a2732a972d..d10b4cbf20 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -11,3 +11,4 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text (lowercase Unicode page-slug letters without combining marks; a literal glued to further letters is not a literal), resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
- `src/core/facts/conversation-subject-infer.ts` — #6764 write-time subject inference for `gbrain extract-conversation-facts` (both the classic and managed branches, trusted local only) and the free conversation relink. `inferConversationSubject` is the per-fact rule (a withdrawn claim misses as `withdrawn`); `inferConversationSubjects(engine, sourceId, visibility, rows)` gives each row the extractor left without an entity the slug `inferFactSubject` proves in `write` mode (mention tier; `excludePrivate` for world rows) plus the `entity inferred from <tier>` context note, unless `facts.entity_inference` is off or the claim was withdrawn. The row stays a derived row of the conversation page (`entity_slug` column only). Test: `test/conversation-facts-unlinked-6764.test.ts`.
- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts`, which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
+- `src/core/facts/conversation-relink-carry.ts` — #6764 how a free conversation relink survives a batch replacement: `clearConversationFacts` (conversation-publication.ts) expires the page's relinked rows (`RELINKED_DERIVED_ROW`: entity set and `entity relinked from` in the context) instead of deleting them, after deleting the previous clear's expired copies, and `inheritRelinkedEntities` gives each inserted row with no entity whose claim matches one of them that entity (live page only) and the relink note, in `replaceConversationFacts` (managed and unmanaged replacement) and `insertGatedFacts` (unmanaged per-segment inserts). One active copy, link kept. Test: `test/conversation-relink-6764.test.ts`.
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index f30c1e1290..6109f0f3bf 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -246,7 +246,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.
- `src/core/facts/backstop.ts` (1): the facts backstop's DB-only fallbacks insert each fact through one helper, in `maintenanceTransaction` at the extraction's derived tier; managed brains publish through the facts request preparer.
-- `src/core/facts/conversation-publication.ts` (3): the managed conversation-facts preparer clears each member page's prior rows and inserts its frozen entry (or a blocked outcome row) inside the coordinator publication of its admitted batch request; the unmanaged cleanup runs the same clear in `maintenanceTransaction`.
+- `src/core/facts/conversation-publication.ts` (4): the managed conversation-facts preparer clears each member page's prior rows and inserts its frozen entry (or a blocked outcome row) inside the coordinator publication of its admitted batch request; the unmanaged cleanup runs the same clear in `maintenanceTransaction`. Its page clear also expires the rows `gbrain facts relink --conversation` linked (after deleting the previous clear's expired copies), inside the same transaction (#6764).
- `src/core/facts/conversation-relink.ts` (1): `gbrain facts relink --conversation`: a `managed_maintenance_conversation_relink` request on managed brains; the unmanaged relink runs in `writeDerivedFacts` (`maintenanceTransaction`).
- `src/core/facts/derivation-inputs.ts` (3): `hideDerivedRows` expires derived facts, deactivates derived takes and soft-deletes derived pages inside the purge's coordinated transaction, attributed to the purge request.
- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.md
index 4cf1610f48..0ad12e0d22 100644
--- a/docs/guides/facts-relink.md
+++ b/docs/guides/facts-relink.md
@@ -129,7 +129,10 @@ gbrain facts relink --conversation --slugs a,b # exactly these pages
```
A linked fact stays on its conversation page with the entity set and the note
-`entity relinked from mention`. A fact no entity can be proven for is recorded,
+`entity relinked from mention`: same row, provenance and trust, no Markdown
+edit, so it needs no consent. A re-extraction of the page
+(`extract-conversation-facts --force`) keeps the link on the claim's new row
+without a second copy. A fact no entity can be proven for is recorded,
so doctor `unlinked_facts` then offers a paid re-extraction of its page
(`gbrain extract-conversation-facts --slugs … --force`, previewed with
`--dry-run`, capped with `--max-cost-usd`) instead of this relink again.
@@ -151,7 +154,7 @@ so doctor `unlinked_facts` then offers a paid re-extraction of its page
| `fence_malformed` | no | The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun. |
| `claim_unfenceable` | no | The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity. |
| `visibility_conflict` | no | The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun. |
-| `fence_owned` | no | The fact lives in another page fence (a transcript). Relink does not move fence-owned facts. |
+| `fence_owned` | no | The fact lives in another page fence or is a conversation page's extracted fact. Relink does not move fence-owned facts; link conversation facts with gbrain facts relink --conversation (free, preview with --dry-run). |
| `budget_exhausted` | no | The model tier reached --max-usd. Raise --max-usd (or pass off) and rerun with the printed continuation command. |
| `revision_conflict` | no | The fact or the entity page changed while relink ran. Rerun. |
diff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.ts
index c73ccbf37f..8a8880de7d 100644
--- a/src/commands/doctor/checks/unlinked-facts.ts
+++ b/src/commands/doctor/checks/unlinked-facts.ts
@@ -17,7 +17,10 @@
* 7-day links by tier from write-time inference and from relink.
*
* Warns when more than 25% of at least 20 new facts (facts judged
- * no_subject excluded) are unlinked. Every query is bounded by created_at
+ * no_subject excluded, and conversation rows the free conversation relink
+ * judged unresolvable, `conversation_unresolved`: only the paid fallback can
+ * still link them, so they are named in the conversation fix instead) are
+ * unlinked. Every query is bounded by created_at
* through idx_facts_since (source_id, created_at DESC WHERE expired_at IS
* NULL) or by primary key; without fact_relink_attempts (a brain before
* v187) the relink figures are omitted and nothing is excluded.
@@ -46,7 +49,7 @@ export interface UnlinkedFactsStats {
* not tried (`fix: 'relink'`), else the most it tried and could not resolve (`fix: 'reextract'`), with those rows' pages, most rows first.
*/
conversation: { source_id: string; fix: 'relink' | 'reextract'; pages: number; slugs: string[] } | null;
- new_7d: { facts: number; unlinked: number; no_subject: number };
+ new_7d: { facts: number; unlinked: number; no_subject: number; conversation_unresolved: number };
no_subject: number | null;
origins: Array<{ origin: string; unlinked: number }>;
inferred_7d: { page: number; mention: number };
@@ -100,6 +103,7 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readon
const [recent] = await engine.executeRaw<Record<string, unknown>>(
`SELECT COUNT(*)::int AS facts, COUNT(*) FILTER (WHERE f.entity_slug IS NULL)::int AS unlinked,
COUNT(*) FILTER (WHERE f.entity_slug IS NULL AND ${judged})::int AS no_subject,
+ COUNT(*) FILTER (WHERE f.entity_slug IS NULL AND ${tried})::int AS conversation_unresolved,
COUNT(*) FILTER (WHERE ${INFERRED} AND ${INFERRED_TIER} = 'page')::int AS inferred_page,
COUNT(*) FILTER (WHERE ${INFERRED} AND ${INFERRED_TIER} = 'mention')::int AS inferred_mention
FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.created_at >= now() - interval '7 days' AND ${ACTIVE}`,
@@ -142,7 +146,7 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readon
conversation: windowRows.reduce((sum, r) => sum + n(r.conversation), 0),
capped: [...perSource.values()].some((c) => c >= UNLINKED_WINDOW_PER_SOURCE),
},
- new_7d: { facts: n(recent?.facts), unlinked: n(recent?.unlinked), no_subject: n(recent?.no_subject) },
+ new_7d: { facts: n(recent?.facts), unlinked: n(recent?.unlinked), no_subject: n(recent?.no_subject), conversation_unresolved: n(recent?.conversation_unresolved) },
no_subject: noSubject,
origins: [...byOrigin].map(([origin, unlinked]) => ({ origin, unlinked })).sort((a, b) => b.unlinked - a.unlinked || a.origin.localeCompare(b.origin)),
inferred_7d: { page: n(recent?.inferred_page), mention: n(recent?.inferred_mention) },
@@ -159,8 +163,9 @@ const pct = (part: number, whole: number) => whole > 0 ? `${(100 * part / whole)
export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { thinClient?: boolean } = {}): Omit<Check, 'name'> {
if (!stats) return { status: 'ok', message: 'No facts table yet; nothing to link.' };
const { window: w, new_7d: recent } = stats;
- const eligible = recent.facts - recent.no_subject;
- const unlinkedNew = recent.unlinked - recent.no_subject;
+ const judged = recent.no_subject + recent.conversation_unresolved;
+ const eligible = recent.facts - judged;
+ const unlinkedNew = recent.unlinked - judged;
const warn = eligible >= UNLINKED_NEW_MIN_FACTS && unlinkedNew / eligible > UNLINKED_NEW_SHARE_WARN;
const hint = opts.thinClient
? 'ask the brain host operator to run: gbrain facts relink --dry-run'
@@ -188,7 +193,7 @@ export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { t
/**
* #6764: the conversation share's free fix, `gbrain facts relink --conversation` over the pages holding the most
- * unlinked derived rows it has not tried in one source: write-mode subject inference, no model call, one write per page.
+ * unlinked derived rows it has not tried in one source: write-mode subject inference, no model call, one receipted database-only write per page (no Markdown edit, so no consent).
*/
function relinkFix(c: NonNullable<UnlinkedFactsStats['conversation']>, thinClient: boolean): Action {
const argv = ['gbrain', 'facts', 'relink', '--conversation', '--source', c.source_id, '--slugs', c.slugs.join(',')];
@@ -201,17 +206,18 @@ function relinkFix(c: NonNullable<UnlinkedFactsStats['conversation']>, thinClien
/**
* #6764: the conversation share's paid fallback, for rows free relink already tried: a bounded re-extraction of the pages
- * holding the most such rows in one source, capped at $1, with a
+ * holding the most such rows in one source (at most 50), capped at the USD amount the user approves (`<N>`), with a
* free dry run as the preview. Re-extraction reruns the extractor with the
* page's entity hints and write-time subject inference.
*/
function reextractFix(c: NonNullable<UnlinkedFactsStats['conversation']>, thinClient: boolean): Action {
const base = ['gbrain', 'extract-conversation-facts', '--source-id', c.source_id, '--slugs', c.slugs.join(','), '--force'];
return {
- argv: [...base, '--max-cost-usd', '1'], preview_argv: [...base, '--dry-run'], consent: ['paid', 'egress'],
+ argv: [...base, '--max-cost-usd', '<N>'], preview_argv: [...base, '--dry-run'], consent: ['paid', 'egress'],
+ inputs: [{ name: 'N', how: 'The most the user approves for this re-extraction in USD, after seeing the plan from preview_argv (for example 1).' }],
actor: thinClient ? 'host_admin' : 'agent', ask_user: true, requires_exclusive: false, verify: doctorVerify('unlinked_facts'),
why: `${c.pages} conversation page(s) in source ${c.source_id} hold extracted facts with no entity that free relink could not resolve${c.pages > c.slugs.length ? ` (the ${c.slugs.length} with the most are named)` : ''}. `
- + 'Re-extraction calls the fact-extraction model again (up to $1) with the page\'s entity hints and write-time subject inference; the dry run shows the plan and makes no model call.',
+ + 'Re-extraction calls the fact-extraction model again (up to the approved <N> USD) with the page\'s entity hints and write-time subject inference; the dry run shows the plan and makes no model call.',
};
}
diff --git a/src/commands/facts.ts b/src/commands/facts.ts
index 7c1d2d4aac..4bb9eb63bb 100644
--- a/src/commands/facts.ts
+++ b/src/commands/facts.ts
@@ -140,7 +140,7 @@ export function formatConversationRelinkReport(r: ConversationRelinkReport, args
if (r.dry_run && r.linked) lines.push(`Apply with:\n gbrain facts relink ${args.filter(a => a !== '--dry-run').join(' ')}`);
if (r.reextract_slugs.length) {
const base = `gbrain extract-conversation-facts --source-id ${r.source_id} --slugs ${r.reextract_slugs.join(',')} --force`;
- lines.push(`No entity could be proven for ${r.unresolved} fact(s). Re-extraction calls the fact model again (paid); preview, then run with a cap:\n ${base} --dry-run\n ${base} --max-cost-usd 1`);
+ lines.push(`No entity could be proven for ${r.unresolved} fact(s). Re-extraction calls the fact model again (paid); preview, then run with the amount the user approves:\n ${base} --dry-run\n ${base} --max-cost-usd <N>`);
}
return lines.join('\n');
}
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 55b1cab9e3..86b2352bce 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -75,6 +75,7 @@ import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_
import { ALLOWED_TYPES, pageTypesForAllowed, type AllowedType } from './conversation-types.ts';
import { withWriteTrust } from '../persistence/context.ts';
import { conversationDerivation } from '../persistence/derived-facts.ts';
+import { RELINKED_DERIVED_ROW, inheritRelinkedEntities } from './conversation-relink-carry.ts';
import { recordTaintEdges } from '../trust/taint.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';
import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
@@ -406,6 +407,7 @@ export async function replaceConversationFacts(tx: BrainEngine, sourceId: string
rows: Array<Omit<ConversationFactRow, 'row_num' | 'source_markdown_slug'>>): Promise<{ deleted: number; inserted: number; ids: number[] }> {
const deleted = await clearConversationFacts(tx, sourceId, slug);
if (!rows.length) return { deleted, inserted: 0, ids: [] };
+ rows = await inheritRelinkedEntities(tx, sourceId, slug, rows);
const [top] = await tx.executeRaw<{ n: number | string | null }>(
'SELECT max(row_num) AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [sourceId, slug]);
const start = top?.n == null ? 0 : Number(top.n) + 1;
@@ -425,18 +427,23 @@ export const LABEL_RETIRED_MARKER = 'retired: conversation-labels';
* history other records depend on: a row an open loop (`open_loops.fact_id`,
* no FK) or another fact's `superseded_by` references is expired, never
* deleted, and rows `gbrain repair conversation-labels` retired stay expired.
- * Every other extractor row of the page is deleted. Returns the rows removed
- * from the active batch.
+ * A row `gbrain facts relink --conversation` linked is expired too, so the
+ * replacement inherits its entity (conversation-relink-carry.ts); the previous
+ * clear's expired relinked rows go first. Every other extractor row of the
+ * page is deleted. Returns the rows removed from the active batch.
*/
export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string): Promise<number> {
const page = `f.source_id=$1 AND f.source_markdown_slug=$2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'`;
const referenced = 'EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=f.id) OR EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id)';
+ await db.executeRaw(`DELETE FROM facts f WHERE ${page} AND f.expired_at IS NOT NULL AND ${RELINKED_DERIVED_ROW} AND NOT (${referenced})`, [sourceId, slug]);
+ const [relinked] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
+ WHERE ${page} AND f.expired_at IS NULL AND ${RELINKED_DERIVED_ROW} RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, [sourceId, slug]);
const [expired] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
WHERE ${page} AND f.expired_at IS NULL AND (${referenced}) RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, [sourceId, slug]);
const [deleted] = await db.executeRaw<{ count: string }>(`WITH del AS (DELETE FROM facts f
- WHERE ${page} AND NOT (${referenced}) AND COALESCE(f.context,'') NOT LIKE '%${LABEL_RETIRED_MARKER}%' RETURNING 1)
+ WHERE ${page} AND NOT (${referenced}) AND COALESCE(f.context,'') NOT LIKE '%${LABEL_RETIRED_MARKER}%' AND NOT (${RELINKED_DERIVED_ROW}) RETURNING 1)
SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug]);
- return Number(expired?.count ?? 0) + Number(deleted?.count ?? 0);
+ return Number(relinked?.count ?? 0) + Number(expired?.count ?? 0) + Number(deleted?.count ?? 0);
}
diff --git a/src/core/facts/conversation-relink-carry.ts b/src/core/facts/conversation-relink-carry.ts
new file mode 100644
index 0000000000..6d74d37204
--- /dev/null
+++ b/src/core/facts/conversation-relink-carry.ts
@@ -0,0 +1,39 @@
+/**
+ * #6764: how a free conversation relink survives re-extraction.
+ *
+ * `gbrain facts relink --conversation` links a derived conversation row in
+ * place (entity_slug set, `entity relinked from <tier>` appended to its
+ * context; the row stays the page's derived row, so it has no fence to lose
+ * and fence projection never touches it). A replacement of the page's batch
+ * (`extract-conversation-facts --force`, a newer extractor version) clears
+ * the page first: `clearConversationFacts` expires those relinked rows
+ * instead of deleting them (and deletes the previous run's expired copies), and
+ * each inserted row with no entity whose claim matches one of them inherits
+ * its entity and note. The relink holds, and the page never carries two active
+ * copies of the claim.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { appendContextNote } from './subject-infer.ts';
+
+/** The SQL predicate (on alias `f`) of a derived row the free conversation relink linked. */
+export const RELINKED_DERIVED_ROW = `f.entity_slug IS NOT NULL AND COALESCE(f.context, '') LIKE '%entity relinked from %'`;
+const NOTE = /entity relinked from ([a-z]+)/;
+
+/** `rows` with the entity a cleared relinked row of page `slug` carried for the same claim, when that entity page is still live. */
+export async function inheritRelinkedEntities<T extends { fact: string; entity_slug?: string | null; context?: string | null }>(
+ db: BrainEngine, sourceId: string, slug: string, rows: T[]): Promise<T[]> {
+ if (!rows.some(row => !row.entity_slug)) return rows;
+ const prior = await db.executeRaw<{ fact: string; entity_slug: string; context: string }>(
+ `SELECT f.fact, f.entity_slug, f.context FROM facts f
+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.source LIKE 'cli:extract-conversation-facts%' AND f.expired_at IS NOT NULL
+ AND ${RELINKED_DERIVED_ROW}
+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.entity_slug AND p.deleted_at IS NULL)
+ ORDER BY f.id DESC`, [sourceId, slug]);
+ if (!prior.length) return rows;
+ const byClaim = new Map<string, { entity_slug: string; context: string }>();
+ for (const p of prior) if (!byClaim.has(p.fact)) byClaim.set(p.fact, p);
+ return rows.map(row => {
+ const p = row.entity_slug ? undefined : byClaim.get(row.fact);
+ return p ? { ...row, entity_slug: p.entity_slug, context: appendContextNote(row.context ?? null, `entity relinked from ${NOTE.exec(p.context)?.[1] ?? 'mention'}`) } : row;
+ });
+}
diff --git a/src/core/facts/relink-reasons.ts b/src/core/facts/relink-reasons.ts
index 8d13f544ad..3aaa0cc3c6 100644
--- a/src/core/facts/relink-reasons.ts
+++ b/src/core/facts/relink-reasons.ts
@@ -18,7 +18,7 @@ export const RELINK_REASONS = {
fence_malformed: { memoized: false, fix: 'The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun.' },
claim_unfenceable: { memoized: false, fix: 'The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity.' },
visibility_conflict: { memoized: false, fix: 'The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun.' },
- fence_owned: { memoized: false, fix: 'The fact lives in another page fence (a transcript). Relink does not move fence-owned facts.' },
+ fence_owned: { memoized: false, fix: 'The fact lives in another page fence or is a conversation page\'s extracted fact. Relink does not move fence-owned facts; link conversation facts with gbrain facts relink --conversation (free, preview with --dry-run).' },
budget_exhausted: { memoized: false, fix: 'The model tier reached --max-usd. Raise --max-usd (or pass off) and rerun with the printed continuation command.' },
revision_conflict: { memoized: false, fix: 'The fact or the entity page changed while relink ran. Rerun.' },
} as const satisfies Record<string, { memoized: boolean; fix: string }>;
diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.ts
index eeee0e92be..888ba678ed 100644
--- a/src/core/persistence/derived-facts.ts
+++ b/src/core/persistence/derived-facts.ts
@@ -5,6 +5,7 @@ import { managedPersistenceEnabled } from './ownership.ts';
import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
+import { inheritRelinkedEntities } from '../facts/conversation-relink-carry.ts';
/**
* #5575 I2: the conversation fact extractor's context is the page alone, so
@@ -28,8 +29,9 @@ async function recordInsertedEdges(tx: BrainEngine, sourceId: string, result: un
* counted and skipped.
*/
type FenceRow = NewFact & { row_num: number; source_markdown_slug: string };
-export async function insertGatedFacts(tx: BrainEngine, sourceId: string, slug: string, rows: FenceRow[],
+export async function insertGatedFacts(tx: BrainEngine, sourceId: string, slug: string, batch: FenceRow[],
derivation: Awaited<ReturnType<typeof conversationDerivation>>): Promise<{ inserted: number; ids: number[]; write_gate: GateTally }> {
+ const rows = await inheritRelinkedEntities(tx, sourceId, slug, batch); // #6764: a cleared free-relinked claim keeps its entity
const cfg = await derivedGateConfig(tx);
const input = derivedGateInput(derivation.trust);
const write_gate = emptyGateTally();
diff --git a/test/conversation-facts-unlinked-6764.test.ts b/test/conversation-facts-unlinked-6764.test.ts
index 7fcbe1699b..f554cc97b4 100644
--- a/test/conversation-facts-unlinked-6764.test.ts
+++ b/test/conversation-facts-unlinked-6764.test.ts
@@ -137,7 +137,8 @@ describe('#6764 unlinked_facts names conversation rows and their real fix', () =
expect(verdict.details).toMatchObject({ conversation: { source_id: 'default', fix: 'reextract', pages: 2, slugs: ['meetings/a', 'meetings/b'] } });
const fix = verdict.fix!;
expect(fix).toMatchObject({ consent: ['paid', 'egress'], actor: 'agent', ask_user: true, verify: { argv: ['gbrain', 'doctor', '--only', 'unlinked_facts', '--json'] } });
- expect(fix.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', 'meetings/a,meetings/b', '--force', '--max-cost-usd', '1']);
+ expect(fix.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', 'meetings/a,meetings/b', '--force', '--max-cost-usd', '<N>']);
+ expect(fix.inputs).toEqual([{ name: 'N', how: expect.stringContaining('USD') }]);
expect(fix.preview_argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', 'meetings/a,meetings/b', '--force', '--dry-run']);
expect(renderAction(fix as never, cliRenderContext()).next).toBe('ask_user');
expect(renderAction(fix as never, dispatchRenderContext({ remote: true, transport: 'http' } as never)).next).toBe('ask_user');
@@ -192,7 +193,7 @@ describe('#6764 fixture: the conversation fix envelope clears the finding', () =
try {
await runExtractConversationFacts(engine, fix.preview_argv!.slice(2));
expect((await unlinkedFactsStats(engine, ['default']))!.window.conversation).toBe(1);
- const parsed = parseArgs(fix.argv!.slice(2));
+ const parsed = parseArgs(fix.argv!.slice(2).map(a => a === '<N>' ? '1' : a)); // the agent fills the approved amount
expect(parsed).toMatchObject({ sourceId: 'default', slugs: [MEETING], force: true, maxCostUsd: 1 });
await runExtractConversationFactsCore(engine, { sourceId: parsed.sourceId!, slugs: parsed.slugs, force: parsed.force, maxCostUsd: parsed.maxCostUsd,
sleepMs: 0, overrideDisabled: true, extractor: async () => [{ fact: 'Alice Example signed the lease renewal', kind: 'event', confidence: 0.9,
diff --git a/test/conversation-relink-6764.test.ts b/test/conversation-relink-6764.test.ts
index cd3b8886b6..2cc3d51783 100644
--- a/test/conversation-relink-6764.test.ts
+++ b/test/conversation-relink-6764.test.ts
@@ -10,8 +10,14 @@
* are untouched. Doctor `unlinked_facts` prescribes this free relink
* (consent none, agent runs it) for untried rows and the paid re-extraction
* only once relink tried and failed; the fixture renders the envelope, runs
- * the preview, the argv and the verify, and the finding moves on.
- * Regression: doctor prescribing paid re-extraction for rows a free pass links.
+ * the preview, the argv and the verify, and the finding moves on. The link
+ * is stored on the derived row itself (`entity_slug`; conversation pages have
+ * no fence, and fence projection skips extractor rows), so the extract_facts
+ * reconcile keeps it, and `extract-conversation-facts --force` (unmanaged and
+ * managed) carries it to the claim's new row with no second copy. Memoized
+ * unresolved rows are left out of the 25% new-fact rule.
+ * Regression: doctor prescribing paid re-extraction for rows a free pass links,
+ * re-prescribing the free pass after it ran, and a re-extraction dropping a link.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -19,6 +25,9 @@ import type { GBrainConfig } from '../src/core/config.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runFactsCommand } from '../src/commands/facts.ts';
import { runConversationRelink, CONVERSATION_RELINK_INTENT } from '../src/core/facts/conversation-relink.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
import { unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';
import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';
import * as inference from '../src/core/facts/conversation-subject-infer.ts';
@@ -27,6 +36,12 @@ import { managedBrain } from './helpers/managed-brain.ts';
const MEETING = 'meetings/2026-08-12-lease-review';
const OTHER = 'meetings/2026-08-13-standup';
+const LINKED = 'Alice Example signed the lease renewal';
+const UNRESOLVED = 'The renewal starts in September';
+const TRANSCRIPT = [
+ '**Owner Example** (2026-08-12 10:00 AM): Alice Example signed the lease renewal yesterday.',
+ '**Beta Example** (2026-08-12 10:01 AM): Good, the renewal starts in September.',
+].join('\n');
const config = { engine: 'pglite', embedding_disabled: true } as unknown as GBrainConfig;
let engine: PGLiteEngine;
@@ -39,7 +54,7 @@ afterAll(async () => { await engine.disconnect(); });
async function seed(db: BrainEngine): Promise<void> {
for (const slug of [MEETING, OTHER]) {
- await db.putPage(slug, { type: 'meeting' as never, title: slug, compiled_truth: 'notes', timeline: '', frontmatter: { date: '2026-08-12' } });
+ await db.putPage(slug, { type: 'meeting' as never, title: slug, compiled_truth: slug === MEETING ? TRANSCRIPT : 'notes', timeline: '', frontmatter: { date: '2026-08-12' } });
}
await db.putPage('people/alice-example', { type: 'person' as never, title: 'Alice Example', compiled_truth: '# Alice Example', timeline: '', frontmatter: {} });
const row = (slug: string, n: number, fact: string, source = 'cli:extract-conversation-facts') => db.executeRaw(
@@ -56,6 +71,28 @@ async function facts(db: BrainEngine, slug = MEETING) {
'SELECT fact, entity_slug, context FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', ['default', slug]);
}
+/** Active rows of a claim anywhere in the source. */
+const active = (db: BrainEngine, fact: string) => db.executeRaw<{ entity_slug: string | null; source_markdown_slug: string; context: string | null }>(
+ 'SELECT entity_slug, source_markdown_slug, context FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL ORDER BY id', ['default', fact]);
+
+/** `extract-conversation-facts --force` on MEETING, the extractor stubbed to return both claims unlinked. */
+async function reextract(db: BrainEngine) {
+ const spy = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ return await runExtractConversationFactsCore(db, { sourceId: 'default', slugs: [MEETING], sleepMs: 0, overrideDisabled: true, force: true,
+ extractor: async () => [LINKED, UNRESOLVED].map(fact => ({ fact, kind: 'event', confidence: 0.9, entity_slug: null, source: 'test', notability: 'high' }) as ExtractedFact) });
+ } finally { spy.mockRestore(); }
+}
+
+/** One active copy of the linked claim: a derived row of MEETING carrying the entity and the relink note. */
+async function expectKept(db: BrainEngine): Promise<void> {
+ const rows = await active(db, LINKED);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ entity_slug: 'people/alice-example', source_markdown_slug: MEETING });
+ expect(rows[0]!.context).toContain('entity relinked from mention');
+ expect((await active(db, UNRESOLVED)).map(r => [r.entity_slug, r.source_markdown_slug])).toEqual([[null, MEETING]]);
+}
+
async function cli(db: BrainEngine, argv: string[]): Promise<{ code: number; out: string }> {
const lines: string[] = [];
const log = spyOn(console, 'log').mockImplementation((s: unknown) => { lines.push(String(s)); });
@@ -108,6 +145,27 @@ describe('#6764 gbrain facts relink --conversation (unmanaged)', () => {
});
});
+describe('#6764 the link survives re-extraction and fence reconcile', () => {
+ beforeEach(async () => { await resetPgliteState(engine); await seed(engine); });
+
+ test('extract-conversation-facts --force (twice) and the extract_facts reconcile keep one linked copy', async () => {
+ await engine.setConfig('facts.entity_inference', 'off'); // the carried link, not write-time inference, must keep it
+ try {
+ await runConversationRelink(engine, config, { sourceId: 'default', slugs: [MEETING] });
+ await expectKept(engine);
+ expect(await reextract(engine)).toMatchObject({ pages_processed: 1, pages_failed: 0 });
+ await expectKept(engine);
+ const reconcile = await runExtractFacts(engine, { sourceId: 'default' });
+ expect(reconcile).toMatchObject({ guardTriggered: false, factsDeleted: 0 });
+ await expectKept(engine);
+ await reextract(engine);
+ await expectKept(engine);
+ const expired = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM facts WHERE fact=$1 AND expired_at IS NOT NULL`, [LINKED]);
+ expect(expired[0]!.n).toBe(1);
+ } finally { await engine.unsetConfig('facts.entity_inference'); }
+ });
+});
+
describe('#6764 doctor: free relink first, paid re-extraction only for rows it tried', () => {
beforeEach(async () => { await resetPgliteState(engine); await seed(engine); });
@@ -125,7 +183,20 @@ describe('#6764 doctor: free relink first, paid re-extraction only for rows it t
const after = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
expect(after.details).toMatchObject({ window: { conversation: 1 }, conversation: { fix: 'reextract', pages: 1, slugs: [MEETING] } });
expect(after.fix).toMatchObject({ consent: ['paid', 'egress'], ask_user: true });
- expect(after.fix!.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', MEETING, '--force', '--max-cost-usd', '1']);
+ expect(after.fix!.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', MEETING, '--force', '--max-cost-usd', '<N>']);
+ expect(after.message).not.toContain('gbrain facts relink --conversation');
+ });
+
+ test('memoized unresolved rows are left out of the 25% new-fact rule and named in the paid fallback', async () => {
+ for (let i = 0; i < 24; i++) {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from)
+ VALUES ('default', NULL, $1, 'cli:extract-conversation-facts', 'from x', $2, $3, now(), now())`, [`Unattributed remark ${i}`, 10 + i, MEETING]);
+ }
+ expect(unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default'])).status).toBe('warn');
+ await runConversationRelink(engine, config, { sourceId: 'default' });
+ const after = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ expect(after.details).toMatchObject({ new_7d: { conversation_unresolved: 25, eligible: 2 }, conversation: { fix: 'reextract', slugs: [MEETING] } });
+ expect(after.status).toBe('ok');
});
test('the remote report asks the brain host operator to run the relink', async () => {
@@ -139,10 +210,14 @@ describe('#6764 gbrain facts relink --conversation (managed)', () => {
await managedBrain(async ({ engine: db }) => {
const report = await runConversationRelink(db, config, { sourceId: 'default', slugs: [MEETING, OTHER] });
expect(report).toMatchObject({ linked: 2, unresolved: 1, changed: 0 });
+ await expectKept(db);
expect((await facts(db)).map(r => r.entity_slug)).toEqual(['people/alice-example', null, null]);
expect((await facts(db, OTHER)).map(r => r.entity_slug)).toEqual(['people/alice-example']);
const requests = await db.executeRaw<{ state: string }>(`SELECT state FROM persistence_requests WHERE intent->>'kind' = $1`, [CONVERSATION_RELINK_INTENT]);
expect(requests.map(r => r.state)).toEqual(['committed', 'committed']);
+ await db.setConfig('facts.entity_inference', 'off'); // the carried link, not write-time inference, must keep it
+ expect(await reextract(db)).toMatchObject({ pages_processed: 1, pages_failed: 0 });
+ await expectKept(db);
}, { setup: async ({ engine: db }) => { await seed(db); } });
}, 120_000);
});