Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): memoize the paid re-extraction per page content so the doctor sequence converges (#6764)
garrytan0564da61a88a
diff --git a/.wave18-fragments/lane3.md b/.wave18-fragments/lane3.mdindex 37770ba16c..c56718ae0e 100644--- a/.wave18-fragments/lane3.md+++ b/.wave18-fragments/lane3.md@@ -141,3 +141,15 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place- The free relink is the trusted-local intent `managed_maintenance_conversation_relink` (database-only, no files, no model) on a managed brain; an unmanaged brain has no maintenance coordinator, so it uses the same writeDerivedFacts maintenance transaction as the extractor itself.- All Lane 3 rows in this file are S2.+## [S2] #6764 follow-up (v4 DX: the free, paid, manual sequence converges)++- The paid attempt is memoized per (source_id, transcript slug, content_hash) in the existing `fact_relink_attempts` table (tier `paid_reextract`, `target_slug` the page, `reason` the hash, keyed on the page's completion outcome row); no schema change and no migration. Every completed extraction of a page writes it (unmanaged `extract-conversation-facts.ts`, managed `conversation-publication.ts` `applyEntry`), so a page already extracted with entity hints and write-time inference on its current content is never offered the paid argv again. New module `src/core/facts/conversation-memo.ts`.+- Doctor `details.conversation.fix` gains `manual`: no envelope `fix` and no paid argv; the message names the hand route (forget it and remember it again with --entity) until the page's content changes, which re-arms `reextract`.+- Free outcomes: only `RELINK_REASONS` memoized:true misses (`ambiguous`, `unverified_match`) stay tried for good; `no_page`, `no_mention` and `withdrawn` misses are re-armed for the free relink by any page created in the source after the attempt.+- `extract-conversation-facts.ts` is 2081 of its 2087 ceiling (one import line). No TSV change.+- Doctor golden drift: none new from this follow-up (`details.conversation.fix` gains the value `manual`; no new field).+- Test: test/conversation-memo-6764.test.ts (free, paid at zero price with N=1, then manual and no paid argv; a new entity page re-arms a `no_page` row; a content edit re-arms the paid fallback). Fails 3/3 on 6be0e3410, passes 3/3 after. test/conversation-facts-managed.test.ts gains the managed memo test (pglite here; postgres in the e2e tier).++### src/core/behavior-change-notice.ts (append to the second #6764 row)++- "Once a page was re-extracted on its current content, doctor stops offering the paid re-extraction for it and lists the facts left for linking by hand (`--entity`); editing the page offers it again."diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex dde8d836c4..daa0874a08 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` 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`.+- `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 memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`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. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). 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.mdindex d10b4cbf20..e74496257c 100644--- a/docs/architecture/key-files/core-persistence-facts.md+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -10,5 +10,6 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.- `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.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` (reason the miss), 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-memo.ts` — #6764 what makes free relink, then paid re-extraction, then linking by hand converge, all in `fact_relink_attempts`: `conversationTriedSql` (a `conversation_unresolved` memo, re-armed for the free relink by any page created in the source after it unless `RELINK_REASONS` memoizes the reason), `conversationPaidSql` and `recordReextractMemo` (tier `paid_reextract`, `target_slug` the page, `reason` its `content_hash`, keyed on the page's completion outcome row; written when an extraction of the page completes, unmanaged in `extract-conversation-facts.ts` and managed in `conversation-publication.ts` `applyEntry`). No schema change. Test: `test/conversation-memo-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/guides/facts-relink.md b/docs/guides/facts-relink.mdindex 4000669053..706cdcd0f0 100644--- a/docs/guides/facts-relink.md+++ b/docs/guides/facts-relink.md@@ -136,6 +136,15 @@ 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.+A miss the table below does not remember (`no_page`, `no_mention`,+`withdrawn`) is tried for free again once a new page is created in the+source, for example the missing entity page.++Every completed extraction of a page is remembered with the page's content+hash. While the page still has that content, doctor offers no paid+re-extraction for it: facts still unlinked there are listed for linking by+hand (forget each one and remember it again with `--entity`). Editing the+page's content offers the re-extraction again.## Why a fact was not linkeddiff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.tsindex 8a8880de7d..9ab6ba0b92 100644--- a/src/commands/doctor/checks/unlinked-facts.ts+++ b/src/commands/doctor/checks/unlinked-facts.ts@@ -30,7 +30,7 @@ import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';import type { Check } from '../../doctor.ts';import type { Action } from '../../../core/agent-output.ts';import { doctorVerify } from '../check-fix.ts';-import { CONVERSATION_UNRESOLVED } from '../../../core/facts/relink-reasons.ts';+import { conversationPaidSql, conversationTriedSql } from '../../../core/facts/conversation-memo.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';export const UNLINKED_NEW_SHARE_WARN = 0.25;@@ -40,15 +40,20 @@ export const UNLINKED_WINDOW_PER_SOURCE = 100_000;/** Conversation pages one re-extraction fix names (`--slugs`). */export const CONVERSATION_FIX_SLUGS = 50;const DERIVED = `f.source LIKE 'cli:extract-conversation-facts%'`;+/** The conversation share's fixes, in the order doctor offers them: free relink, then the paid fallback, then by hand. */+const CONVERSATION_FIXES = ['relink', 'reextract', 'manual'] as const;+type ConversationFix = typeof CONVERSATION_FIXES[number];export interface UnlinkedFactsStats {sources: number;window: { active: number; unlinked: number; fence_owned: number; conversation: number; capped: boolean };/*** The conversation share's fix target: the source with the most unlinked conversation-extractor rows free relink has- * not tried (`fix: 'relink'`), else the most it tried and could not resolve (`fix: 'reextract'`), with those rows' pages, most rows first.+ * not tried (`fix: 'relink'`), else the most it tried and could not resolve on pages not yet re-extracted on their+ * current content (`fix: 'reextract'`), else the most left after both (`fix: 'manual'`: link by hand, no paid+ * offer until the page content changes), with those rows' pages, most rows first.*/- conversation: { source_id: string; fix: 'relink' | 'reextract'; pages: number; slugs: string[] } | null;+ conversation: { source_id: string; fix: 'relink' | 'reextract' | 'manual'; pages: number; slugs: string[] } | null;new_7d: { facts: number; unlinked: number; no_subject: number; conversation_unresolved: number };no_subject: number | null;origins: Array<{ origin: string; unlinked: number }>;@@ -73,15 +78,18 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readonconst hasAttempts = !!tables.attempts;const ids = sourceIds?.length ? [...sourceIds] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map((r) => r.id);const audit = [...AUDIT_ROW_SOURCES];- const tried = hasAttempts ? `EXISTS (SELECT 1 FROM fact_relink_attempts a WHERE a.source_id = f.source_id AND a.fact_id = f.id AND a.outcome = '${CONVERSATION_UNRESOLVED}')` : 'false';- const windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number; conversation: number; conversation_tried: number }>(+ const tried = hasAttempts ? conversationTriedSql : 'false';+ const paid = hasAttempts ? conversationPaidSql : 'false';+ const windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number; conversation: number; conversation_tried: number; conversation_paid: number }>(`SELECT s.id AS source_id, w.origin, COUNT(*)::int AS active, COUNT(*) FILTER (WHERE w.unlinked)::int AS unlinked,COUNT(*) FILTER (WHERE w.unlinked AND w.fence_owned AND NOT w.derived)::int AS fence_owned,COUNT(*) FILTER (WHERE w.unlinked AND w.derived)::int AS conversation,- COUNT(*) FILTER (WHERE w.unlinked AND w.derived AND w.tried)::int AS conversation_tried+ COUNT(*) FILTER (WHERE w.unlinked AND w.derived AND w.tried)::int AS conversation_tried,+ COUNT(*) FILTER (WHERE w.unlinked AND w.derived AND w.tried AND w.paid)::int AS conversation_paidFROM unnest($1::text[]) AS s(id) CROSS JOIN LATERAL (SELECT ${ORIGIN} AS origin, f.entity_slug IS NULL AS unlinked, ${DERIVED} AS derived,CASE WHEN f.entity_slug IS NULL AND ${DERIVED} THEN ${tried} ELSE false END AS tried,+ CASE WHEN f.entity_slug IS NULL AND ${DERIVED} THEN ${paid} ELSE false END AS paid,(f.row_num IS NOT NULL OR f.source_markdown_slug IS NOT NULL) AS fence_ownedFROM facts f WHERE f.source_id = s.id AND ${ACTIVE}ORDER BY f.created_at DESC LIMIT $3) w@@ -90,11 +98,12 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readon);const perSource = new Map<string, number>();const byOrigin = new Map<string, number>();- const derivedBySource = new Map<string, { untried: number; tried: number }>();+ const derivedBySource = new Map<string, Record<ConversationFix, number>>();for (const r of windowRows) {perSource.set(r.source_id, (perSource.get(r.source_id) ?? 0) + n(r.active));- const d = derivedBySource.get(r.source_id) ?? { untried: 0, tried: 0 };- derivedBySource.set(r.source_id, { untried: d.untried + n(r.conversation) - n(r.conversation_tried), tried: d.tried + n(r.conversation_tried) });+ const d = derivedBySource.get(r.source_id) ?? { relink: 0, reextract: 0, manual: 0 };+ derivedBySource.set(r.source_id, { relink: d.relink + n(r.conversation) - n(r.conversation_tried),+ reextract: d.reextract + n(r.conversation_tried) - n(r.conversation_paid), manual: d.manual + n(r.conversation_paid) });if (n(r.unlinked) > 0) byOrigin.set(r.origin, (byOrigin.get(r.origin) ?? 0) + n(r.unlinked));}const judged = hasAttempts@@ -123,13 +132,13 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readonrelinked = {};for (const r of rows.filter((x) => x.outcome === 'linked')) relinked[r.tier ?? 'unknown'] = (relinked[r.tier ?? 'unknown'] ?? 0) + n(r.n);}- const fixKind = [...derivedBySource.values()].some(d => d.untried > 0) ? 'relink' : 'reextract';- const share = (d: { untried: number; tried: number }) => fixKind === 'relink' ? d.untried : d.tried;- const [derivedSource] = [...derivedBySource].filter(([, d]) => share(d) > 0).sort((a, b) => share(b[1]) - share(a[1]) || a[0].localeCompare(b[0]));+ const fixKind = CONVERSATION_FIXES.find(k => [...derivedBySource.values()].some(d => d[k] > 0)) ?? 'manual';+ const [derivedSource] = [...derivedBySource].filter(([, d]) => d[fixKind] > 0).sort((a, b) => b[1][fixKind] - a[1][fixKind] || a[0].localeCompare(b[0]));+ const hitSql = { relink: `NOT ${tried}`, reextract: `${tried} AND NOT ${paid}`, manual: `${tried} AND ${paid}` }[fixKind];let conversation: UnlinkedFactsStats['conversation'] = null;if (derivedSource) {const pages = await engine.executeRaw<{ slug: string }>(- `SELECT w.slug FROM (SELECT f.source_markdown_slug AS slug, f.entity_slug IS NULL AND ${DERIVED} AND ${fixKind === 'relink' ? 'NOT ' : ''}${tried} AS hit+ `SELECT w.slug FROM (SELECT f.source_markdown_slug AS slug, f.entity_slug IS NULL AND ${DERIVED} AND ${hitSql} AS hitFROM facts f WHERE f.source_id = $1 AND ${ACTIVE} ORDER BY f.created_at DESC LIMIT $3) wWHERE w.hit AND w.slug IS NOT NULL GROUP BY w.slug ORDER BY COUNT(*) DESC, w.slug`,[derivedSource[0], audit, UNLINKED_WINDOW_PER_SOURCE],@@ -179,10 +188,12 @@ export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { t];if (stats.origins.length > 0) parts.push(`top origins: ${stats.origins.slice(0, 3).map((o) => `${o.origin} ${o.unlinked}`).join(', ')}`);const c = stats.conversation;- const fix = c ? (c.fix === 'relink' ? relinkFix : reextractFix)(c, opts.thinClient === true) : undefined;- const conversationHint = !fix ? '' : c!.fix === 'relink'- ? ` Conversation facts are derived from their page, so plain relink never examines them; link them for free (preview first): ${fix.preview_argv!.join(' ')}. Facts it cannot resolve fall back to a paid re-extraction.`- : ` Free conversation relink could not resolve these conversation facts; re-extract instead (paid, preview first): ${fix.preview_argv!.join(' ')}.`;+ const fix = c && c.fix !== 'manual' ? (c.fix === 'relink' ? relinkFix : reextractFix)(c, opts.thinClient === true) : undefined;+ const conversationHint = !c ? '' : c.fix === 'manual'+ ? ` ${c.pages} conversation page(s) in source ${c.source_id} (${c.slugs.join(', ')}) were re-extracted on their current content and free relink still could not resolve their facts with no entity; link each by hand (forget it and remember it again with --entity). Re-extraction is offered again when a page's content changes.`+ : c.fix === 'relink'+ ? ` Conversation facts are derived from their page, so plain relink never examines them; link them for free (preview first): ${fix!.preview_argv!.join(' ')}. Facts it cannot resolve fall back to a paid re-extraction.`+ : ` Free conversation relink could not resolve these conversation facts; re-extract instead (paid, preview first): ${fix!.preview_argv!.join(' ')}.`;return {status: warn ? 'warn' : 'ok',message: `${parts.join('; ')}${warn || w.unlinked > 0 ? `. ${warn ? `Over ${UNLINKED_NEW_SHARE_WARN * 100}% of new facts are unlinked; ` : ''}${hint}` : ''}${conversationHint}`,diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 5012e048f3..b476f31e23 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -113,6 +113,7 @@ import {} from '../core/entities/resolve-on-save.ts';import { CONVERSATION_ENTITY_HINTS_CAP, conversationEntityHints } from '../core/facts/conversation-entity-hints.ts';import { inferConversationSubjects } from '../core/facts/conversation-subject-infer.ts';+import { recordReextractMemo } from '../core/facts/conversation-memo.ts';// Re-exported verbatim so existing importers (this file's own helpers below// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,@@ -1133,7 +1134,7 @@ async function processPage(// page's facts in one transaction.const terminal = terminalAuditFact(page.slug, rowNum, snapshot.versionToken);if (state.managed) managedRows.push(terminal);- else await writeDerivedFacts(state.engine, state.sourceId, page.slug, db => db.insertFacts([terminal], { source_id: state.sourceId })); // gbrain-allow-direct-insert: page-level TERMINAL audit row (Codex C7 / E16) marks extraction completion in the durable facts table — there's no fence equivalent because this is internal audit state, not user-facing knowledge+ else await writeDerivedFacts(state.engine, state.sourceId, page.slug, db => db.insertFacts([terminal], { source_id: state.sourceId }).then(async r => { await recordReextractMemo(db, state.sourceId, page.slug); return r; })); // #6764 paid-attempt memo; gbrain-allow-direct-insert: page-level TERMINAL audit row (Codex C7 / E16) marks extraction completion in the durable facts table — there's no fence equivalent because this is internal audit state, not user-facing knowledgerowNum++;} else if (fullyProcessed && newestEnd !== null) {process.stderr.write(diff --git a/src/core/facts/conversation-memo.ts b/src/core/facts/conversation-memo.tsnew file mode 100644index 0000000000..a200edd2b2--- /dev/null+++ b/src/core/facts/conversation-memo.ts@@ -0,0 +1,51 @@+/**+ * #6764: what doctor `unlinked_facts` and `gbrain facts relink --conversation`+ * remember about a conversation page's unlinked derived rows, so the free+ * pass, then the paid fallback, then the manual route converge instead of+ * cycling. All of it lives in `fact_relink_attempts` (no new table):+ *+ * - Free outcome, per fact row (`outcome = conversation_unresolved`, `reason`+ * the subject-inference miss). Only the reasons `RELINK_REASONS` memoizes+ * (`ambiguous`, `unverified_match`: the user has to act) stay tried for+ * good. Any other miss (`no_page`, `no_mention`, `withdrawn`) is re-armed+ * by a page created in the source after the attempt, since a new entity page+ * can resolve it for free; until then the paid fallback is next.+ * - Paid attempt, per page and content (`tier = paid_reextract`, `target_slug`+ * the page, `reason` its `content_hash`, `fact_id` the page's completion+ * outcome row): written whenever an extraction of the page completes,+ * because the extractor already ran with entity hints and write-time+ * inference on that content. While it matches the page's current content,+ * rows still unresolved there are informational (link by hand); a content+ * change re-arms the paid fallback.+ */+import type { BrainEngine } from '../engine.ts';+import { TERMINAL_AUDIT_SOURCE } from './audit-sources.ts';+import { CONVERSATION_UNRESOLVED, RELINK_REASONS } from './relink-reasons.ts';++export const PAID_REEXTRACT = 'paid_reextract';++const REARMED = Object.entries(RELINK_REASONS).filter(([, r]) => !r.memoized).map(([code]) => `'${code}'`).join(', ');++/** SQL (fact alias `f`): the free relink already tried this row, and no page created since has re-armed an unmemoized miss. */+export const conversationTriedSql = `EXISTS (SELECT 1 FROM fact_relink_attempts a WHERE a.source_id = f.source_id AND a.fact_id = f.id+ AND a.outcome = '${CONVERSATION_UNRESOLVED}'+ AND NOT (a.reason IN (${REARMED}) AND EXISTS (SELECT 1 FROM pages np WHERE np.source_id = f.source_id AND np.deleted_at IS NULL AND np.created_at > a.attempted_at)))`;++/** SQL (fact alias `f`): an extraction of this row's page completed on the page's current content. */+export const conversationPaidSql = `EXISTS (SELECT 1 FROM fact_relink_attempts pa JOIN pages pp ON pp.source_id = pa.source_id AND pp.slug = pa.target_slug AND pp.deleted_at IS NULL+ WHERE pa.source_id = f.source_id AND pa.tier = '${PAID_REEXTRACT}' AND pa.target_slug = f.source_markdown_slug AND pa.reason = COALESCE(pp.content_hash, ''))`;++/** After a page's extraction completes: its paid-attempt memo for the current content (replacing older ones). */+export async function recordReextractMemo(db: BrainEngine, sourceId: string, slug: string): Promise<void> {+ const [table] = await db.executeRaw<{ t: string | null }>(`SELECT to_regclass('fact_relink_attempts')::text AS t`);+ if (!table?.t) return;+ const [outcome] = await db.executeRaw<{ id: number | string; hash: string }>(+ `SELECT f.id, COALESCE(p.content_hash, '') AS hash FROM facts f JOIN pages p ON p.source_id = f.source_id AND p.slug = f.source_markdown_slug AND p.deleted_at IS NULL+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.source = $3 AND f.expired_at IS NULL ORDER BY f.id DESC LIMIT 1`, [sourceId, slug, TERMINAL_AUDIT_SOURCE]);+ if (!outcome) return;+ await db.executeRaw(`DELETE FROM fact_relink_attempts WHERE source_id = $1 AND tier = $2 AND target_slug = $3`, [sourceId, PAID_REEXTRACT, slug]);+ await db.executeRaw(`INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, reason, tier, model, target_slug, run_id, attempted_at)+ VALUES ($1, $2, $3, $4, $3, NULL, $5, NULL, now())+ ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, tier = EXCLUDED.tier, target_slug = EXCLUDED.target_slug, attempted_at = EXCLUDED.attempted_at`,+ [sourceId, Number(outcome.id), PAID_REEXTRACT, outcome.hash, slug]);+}diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 86b2352bce..3f7e180edf 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -76,6 +76,7 @@ import { ALLOWED_TYPES, pageTypesForAllowed, type AllowedType } from './conversaimport { withWriteTrust } from '../persistence/context.ts';import { conversationDerivation } from '../persistence/derived-facts.ts';import { RELINKED_DERIVED_ROW, inheritRelinkedEntities } from './conversation-relink-carry.ts';+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';@@ -497,6 +498,7 @@ async function applyEntry(tx: BrainEngine, row: WriteRequest, entry: Conversatioif (flags[i] && ids.length === kept.length) await recordFlaggedRow(tx, flags[i]!, { table: 'facts', id, sourceId: row.source_id });}const outcome = entry.rows.find(fact => OUTCOME_SOURCES.has(fact.source));+ if (outcome?.source === TERMINAL_AUDIT_SOURCE) await recordReextractMemo(tx, row.source_id, entry.slug); // #6764return { ...base, status: 'committed', deleted, facts_inserted: kept.filter(fact => !OUTCOME_SOURCES.has(fact.source)).length,page_outcome: outcome ? (outcome.source === TERMINAL_AUDIT_SOURCE ? 'complete' : 'non_extractable') : null, newest_end: entry.newest_end,vectors_dropped: vectors ? 0 : entry.rows.filter(fact => fact.embedding).length };diff --git a/src/core/facts/conversation-relink.ts b/src/core/facts/conversation-relink.tsindex 8a5a35b7e3..5ab794721c 100644--- a/src/core/facts/conversation-relink.ts+++ b/src/core/facts/conversation-relink.ts@@ -19,7 +19,8 @@* it. A row inference cannot resolve gets a `conversation_unresolved` memo in* `fact_relink_attempts` (operational, like relink's model verdict memos), so* doctor `unlinked_facts` offers it the paid re-extraction fallback instead- * of this relink again. Trusted local CLI only.+ * of this relink again; conversation-memo.ts says which misses a new page+ * re-arms and how the paid attempt is remembered. Trusted local CLI only.*/import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';@@ -36,6 +37,7 @@ import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persisimport { writeDerivedFacts } from '../persistence/derived-facts.ts';import { AUDIT_ROW_SOURCES } from './audit-sources.ts';import { CONVERSATION_UNRESOLVED } from './relink-reasons.ts';+import { conversationTriedSql } from './conversation-memo.ts';import { appendContextNote } from './subject-infer.ts';import { inferConversationSubject } from './conversation-subject-infer.ts';@@ -70,7 +72,7 @@ async function hasAttemptsTable(engine: BrainEngine): Promise<boolean> {/** The pages with the most unlinked derived rows not yet tried by this relink, up to `limit`. */export async function conversationRelinkPages(engine: BrainEngine, sourceId: string, limit = CONVERSATION_RELINK_PAGES): Promise<string[]> {const untried = await hasAttemptsTable(engine)- ? 'AND NOT EXISTS (SELECT 1 FROM fact_relink_attempts a WHERE a.source_id = f.source_id AND a.fact_id = f.id)' : '';+ ? `AND NOT ${conversationTriedSql}` : '';const rows = await engine.executeRaw<{ slug: string }>(`SELECT f.source_markdown_slug AS slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NOT NULL AND ${ACTIVE}AND ${derivedConversationRow('$2')} ${untried}diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.tsindex f548e8ce00..9d28e6455d 100644--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@ -179,6 +179,19 @@ for (const backend of testBackends()) {}, { databaseUrl });}, 120_000);+ test(`${backend}: a completed managed extraction remembers the paid attempt for the page's current content (#6764)`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ expect(await extract(engine, { n: 0 })).toMatchObject({ pages_processed: 1, pages_failed: 0 });+ const [outcome] = (await extractorRows(engine)).filter(r => r.fact === 'EXTRACTION_COMPLETE');+ const memos = await engine.executeRaw<{ fact_id: number | string; tier: string; target_slug: string; current: boolean }>(+ `SELECT a.fact_id, a.tier, a.target_slug, a.reason = p.content_hash AS current FROM fact_relink_attempts a+ JOIN pages p ON p.source_id = a.source_id AND p.slug = a.target_slug WHERE a.source_id = 'default'`);+ expect(memos.map(m => ({ ...m, fact_id: Number(m.fact_id) }))).toEqual([{ fact_id: Number(outcome!.id), tier: 'paid_reextract', target_slug: SLUG, current: true }]);+ }, { databaseUrl });+ }, 120_000);+test(`${backend}: a crash after admission replays the stored batch with zero model calls`, async () => {await managedBrain(async brain => {const { engine } = brain;diff --git a/test/conversation-memo-6764.test.ts b/test/conversation-memo-6764.test.tsnew file mode 100644index 0000000000..8046451965--- /dev/null+++ b/test/conversation-memo-6764.test.ts@@ -0,0 +1,126 @@+/**+ * #6764 convergence: doctor `unlinked_facts` walks a conversation page's+ * unlinked facts through the free relink, then the paid re-extraction, then+ * the manual route, and stops there. The paid attempt is remembered per+ * (source, page, content hash), so a page re-extracted on its current+ * content is never offered the paid argv again until its content changes;+ * a miss `RELINK_REASONS` does not memoize (`no_page`) is re-armed by a page+ * created later. Hermetic: PGLite plus a zero-price stubbed chat transport.+ */+import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { runExtractConversationFacts } from '../src/commands/extract-conversation-facts.ts';+import { runConversationRelink } from '../src/core/facts/conversation-relink.ts';+import { unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';++const MODEL = 'litellm:zero-price-chat';+const MEETING = 'meetings/2026-08-12-lease-review';+const TRANSCRIPT = [+ '**Owner Example** (2026-08-12 10:00 AM): She signed the lease renewal yesterday.',+ '**Beta Example** (2026-08-12 10:01 AM): Good, she starts in September.',+].join('\n');+const config = { engine: 'pglite', embedding_disabled: true } as never;++let engine: PGLiteEngine;+let chatCalls = 0;++beforeEach(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ resetGateway();+ configureGateway({ chat_model: MODEL, embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ base_urls: { litellm: 'http://localhost:4000' }, env: { LITELLM_BASE_URL: 'http://localhost:4000', OPENAI_API_KEY: 'test' } });+ chatCalls = 0;+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ chatCalls++;+ return { text: JSON.stringify({ facts: [{ fact: 'She signed the lease renewal', kind: 'event', entity: null, confidence: 1, notability: 'high' }] }),+ blocks: [], stopReason: 'end', usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'litellm' };+ });+ await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('facts.extraction_model', MODEL);+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');+ await engine.setConfig('pricing.overrides', JSON.stringify({ [MODEL]: { input: 0, output: 0 } }));+ await engine.setConfig('embedding.disabled', 'true');+ await engine.putPage(MEETING, { type: 'meeting' as never, title: 'Lease review', compiled_truth: TRANSCRIPT, timeline: '', frontmatter: { date: '2026-08-12' } });+}, 60_000);++afterEach(async () => {+ __setChatTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++async function legacyRow(fact: string): Promise<void> {+ 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', $2, 0, $3, now(), now())`, [fact, `from ${MEETING} segment 2026-08-12`, MEETING]);+}++async function doctor() {+ const verdict = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));+ return { verdict, conversation: (verdict.details as { conversation: { fix: string; slugs: string[] } | null }).conversation };+}++async function run(argv: string[]): Promise<string> {+ const lines: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((s: unknown) => { lines.push(String(s)); });+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`process.exit(${code})`); }) as never);+ try { await runExtractConversationFacts(engine, argv); } finally { log.mockRestore(); err.mockRestore(); exit.mockRestore(); }+ return lines.join('\n');+}++test('free, then paid, then by hand: once the page was re-extracted on its content, doctor offers no paid argv again', async () => {+ await legacyRow('She signed the lease renewal');+ expect((await doctor()).conversation).toMatchObject({ fix: 'relink', slugs: [MEETING] });+ expect(await runConversationRelink(engine, config, { sourceId: 'default' })).toMatchObject({ linked: 0, unresolved: 1 });++ const paid = await doctor();+ expect(paid.conversation).toMatchObject({ fix: 'reextract', slugs: [MEETING] });+ const out = await run(paid.verdict.fix!.argv!.slice(2).map(a => a === '<N>' ? '1' : a));+ expect(out).toContain('Spent ~$0.0000');+ expect(chatCalls).toBeGreaterThan(0);++ for (let step = 0; step < 3; step++) {+ const d = await doctor();+ if (d.conversation?.fix !== 'relink') break;+ await runConversationRelink(engine, config, { sourceId: 'default', slugs: d.conversation.slugs });+ }+ const done = await doctor();+ expect(done.conversation).toMatchObject({ fix: 'manual', slugs: [MEETING] });+ expect(done.verdict.fix).toBeUndefined();+ expect(done.verdict.message).toContain('remember it again with --entity');+ expect(JSON.stringify(done.verdict)).not.toContain('extract-conversation-facts --source-id');+ const calls = chatCalls;+ expect(await runConversationRelink(engine, config, { sourceId: 'default' })).toMatchObject({ pages: [] });+ expect((await doctor()).conversation).toMatchObject({ fix: 'manual' });+ expect(chatCalls).toBe(calls);+});++test('a no_page miss is re-armed for the free relink by creating the entity page', async () => {+ await legacyRow('Carol Example joined the board');+ expect(await runConversationRelink(engine, config, { sourceId: 'default' })).toMatchObject({ linked: 0, unresolved: 1 });+ expect(await engine.executeRaw<{ reason: string }>('SELECT reason FROM fact_relink_attempts')).toEqual([{ reason: 'no_page' }]);+ expect((await doctor()).conversation).toMatchObject({ fix: 'reextract' });++ await engine.putPage('people/carol-example', { type: 'person' as never, title: 'Carol Example', compiled_truth: '# Carol Example', timeline: '', frontmatter: {} });+ const rearmed = await doctor();+ expect(rearmed.conversation).toMatchObject({ fix: 'relink', slugs: [MEETING] });+ expect(await runConversationRelink(engine, config, { sourceId: 'default', slugs: rearmed.conversation!.slugs })).toMatchObject({ linked: 1, unresolved: 0 });+ expect((await doctor()).conversation).toBeNull();+ expect(chatCalls).toBe(0);+});++test('changing the transcript content re-arms the paid fallback', async () => {+ await legacyRow('She signed the lease renewal');+ await runConversationRelink(engine, config, { sourceId: 'default' });+ await run((await doctor()).verdict.fix!.argv!.slice(2).map(a => a === '<N>' ? '1' : a));+ await runConversationRelink(engine, config, { sourceId: 'default' });+ expect((await doctor()).conversation).toMatchObject({ fix: 'manual' });++ await engine.putPage(MEETING, { type: 'meeting' as never, title: 'Lease review', compiled_truth: `${TRANSCRIPT}\n**Owner Example** (2026-08-12 10:02 AM): The keys are ready.`, timeline: '', frontmatter: { date: '2026-08-12' } });+ const changed = await doctor();+ expect(changed.conversation).toMatchObject({ fix: 'reextract', slugs: [MEETING] });+ expect(changed.verdict.fix!.argv).toContain('--max-cost-usd');+});