Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): conversation facts get write-time subject inference and a doctor fix that can act on them (#6764)

garrytan87d3b7ffbf6b
diff --git a/docs/.wave18-fragments/lane3.md b/docs/.wave18-fragments/lane3.md
index 47b3eb2d67..0ba63d31b6 100644
--- a/docs/.wave18-fragments/lane3.md
+++ b/docs/.wave18-fragments/lane3.md
@@ -75,3 +75,23 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
### scripts/module-size-limits.tsv
- `src/commands/extract-conversation-facts.ts` shrinks from 2087 to 2078 in this commit (the two extractor call sites share one input object). Lower its ceiling when the integrator settles the TSV after the later lane 3 commits (the #6764 commit adds a few lines back; see that section).
+
+## #6764 conversation facts: write-time subject inference and a doctor fix that can act on them
+
+### 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.' },
+```
+
+### 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).
+
+### scripts/module-size-limits.tsv
+
+- `src/commands/extract-conversation-facts.ts` is 2079 of its 2087 ceiling after this commit (the inference logic lives in the new `src/core/facts/conversation-subject-infer.ts`). The integrator can lower the ceiling to 2079 when settling the TSV.
+
+### Notes
+
+- 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.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 0b984c4067..5918da36e3 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -31,3 +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` is 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, verify `gbrain doctor --only unlinked_facts --json`; test `test/conversation-facts-unlinked-6764.test.ts`), because 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/commands-2.md b/docs/architecture/key-files/commands-2.md
index 2a276576e6..c1532be560 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -18,7 +18,6 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/ontology-facts.ts` — `ontology_facts_fenced` (#6264; wave check, host-only): counts ontology observations the pre-fix `extract_facts` fence step moved onto an entity page's Facts table, restorable ones by state (`fenced`, `retired`) plus `excluded` (withdrawn, consolidated, duplicate; never a finding), through `classifyOntologyFacts`, and names `gbrain repair ontology-facts`. Read-only; an inspection error reports health unknown.
-- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set), origins (`mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`, and the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle`, `chronicle_config_invalid` and `auto_chronicle_default_on` (#5876), registered after `unlinked_facts`, config-plane only (no provider calls). `auto_chronicle`: off by choice is ok with `severity: info`, `readiness: disabled_by_choice`; an invalid word warns `auto_chronicle_invalid`; when on it reads `core/chronicle/ledger-stats.ts` and warns `judge_llm_unavailable` (pending pages, no chat provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and `gbrain dream --phase chronicle`. Every warn carries `details.fix` (an Action: argv/consent/actor) and `fix_hint`. `chronicle_config_invalid` warns on an out-of-range stored `chronicle.*` value. `auto_chronicle_default_on` is ok/info with `ask_user` and keep/opt-out decisions until `gbrain config set auto_chronicle` acknowledges. Test: `test/auto-chronicle-surfaces-5876.test.ts`.
- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index b2b287f614..927e9a2039 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -9,3 +9,4 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
- `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). `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`.
diff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.ts
index c725614dd9..89e31d941a 100644
--- a/src/commands/doctor/checks/unlinked-facts.ts
+++ b/src/commands/doctor/checks/unlinked-facts.ts
@@ -9,7 +9,9 @@
* unlinked share of facts created in the last 7 days, how many facts
* `gbrain facts relink` already judged to have no subject (`no_subject`),
* the fence-owned unlinked rows (row_num or source_markdown_slug set: relink
- * rewrites their fence row), the top origins of unlinked facts, and the
+ * rewrites their fence row), the conversation extractor's derived rows
+ * (#6764: relink never examines them; re-extraction, which runs write-time
+ * inference, is their fix), the top origins of unlinked facts, and the
* 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
@@ -21,16 +23,23 @@
import type { BrainEngine } from '../../../core/engine.ts';
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 { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
export const UNLINKED_NEW_SHARE_WARN = 0.25;
export const UNLINKED_NEW_MIN_FACTS = 20;
/** Newest active facts per source the overall share is computed over. */
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%'`;
export interface UnlinkedFactsStats {
sources: number;
- window: { active: number; unlinked: number; fence_owned: number; capped: boolean };
+ window: { active: number; unlinked: number; fence_owned: number; conversation: number; capped: boolean };
+ /** The source with the most unlinked conversation-extractor rows in the window, and their pages (most rows first). */
+ conversation: { source_id: string; pages: number; slugs: string[] } | null;
new_7d: { facts: number; unlinked: number; no_subject: number };
no_subject: number | null;
origins: Array<{ origin: string; unlinked: number }>;
@@ -39,7 +48,7 @@ export interface UnlinkedFactsStats {
}
const ACTIVE = `f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source <> ALL($2::text[])`;
-const ORIGIN = `CASE WHEN f.source = 'mcp:put_page' THEN 'mcp:put_page'
+const ORIGIN = `CASE WHEN ${DERIVED} THEN 'conversation' WHEN f.source = 'mcp:put_page' THEN 'mcp:put_page'
WHEN f.source LIKE 'mcp:%' OR f.source LIKE 'sync:%' OR f.source LIKE 'hook:%' OR f.source IN ('file_upload', 'code_import') THEN 'extraction'
ELSE 'remember' END`;
const INFERRED = `(f.context LIKE 'entity inferred from %' OR f.context LIKE '% — entity inferred from %')`;
@@ -55,11 +64,12 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readon
const 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 windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number }>(
+ const windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number; conversation: 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)::int AS fence_owned
+ 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
FROM unnest($1::text[]) AS s(id) CROSS JOIN LATERAL (
- SELECT ${ORIGIN} AS origin, f.entity_slug IS NULL AS unlinked,
+ SELECT ${ORIGIN} AS origin, f.entity_slug IS NULL AS unlinked, ${DERIVED} AS derived,
(f.row_num IS NOT NULL OR f.source_markdown_slug IS NOT NULL) AS fence_owned
FROM facts f WHERE f.source_id = s.id AND ${ACTIVE}
ORDER BY f.created_at DESC LIMIT $3) w
@@ -68,8 +78,10 @@ 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, number>();
for (const r of windowRows) {
perSource.set(r.source_id, (perSource.get(r.source_id) ?? 0) + n(r.active));
+ derivedBySource.set(r.source_id, (derivedBySource.get(r.source_id) ?? 0) + n(r.conversation));
if (n(r.unlinked) > 0) byOrigin.set(r.origin, (byOrigin.get(r.origin) ?? 0) + n(r.unlinked));
}
const judged = hasAttempts
@@ -97,12 +109,25 @@ export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readon
relinked = {};
for (const r of rows.filter((x) => x.outcome === 'linked')) relinked[r.tier ?? 'unknown'] = (relinked[r.tier ?? 'unknown'] ?? 0) + n(r.n);
}
+ const [derivedSource] = [...derivedBySource].filter(([, c]) => c > 0).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
+ 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} AS hit
+ FROM facts f WHERE f.source_id = $1 AND ${ACTIVE} ORDER BY f.created_at DESC LIMIT $3) w
+ WHERE 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],
+ );
+ conversation = { source_id: derivedSource[0], pages: pages.length, slugs: pages.slice(0, CONVERSATION_FIX_SLUGS).map(r => r.slug) };
+ }
return {
sources: ids.length,
+ conversation,
window: {
active: windowRows.reduce((sum, r) => sum + n(r.active), 0),
unlinked: windowRows.reduce((sum, r) => sum + n(r.unlinked), 0),
fence_owned: windowRows.reduce((sum, r) => sum + n(r.fence_owned), 0),
+ 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) },
@@ -130,16 +155,35 @@ export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { t
: 'preview links: gbrain facts relink --dry-run';
if (w.active === 0 && recent.facts === 0) return { status: 'ok', message: 'No active facts yet; nothing to link.', details: { ...stats, fix: hint } };
const parts = [
- `${pct(w.unlinked, w.active)} of ${w.active} active facts have no entity (${w.unlinked}${w.capped ? `; newest ${UNLINKED_WINDOW_PER_SOURCE} per source` : ''}; ${w.fence_owned} fence-owned)`,
+ `${pct(w.unlinked, w.active)} of ${w.active} active facts have no entity (${w.unlinked}${w.capped ? `; newest ${UNLINKED_WINDOW_PER_SOURCE} per source` : ''}; ${w.fence_owned} fence-owned${w.conversation ? `; ${w.conversation} from conversation extraction` : ''})`,
`last 7 days: ${pct(unlinkedNew, eligible)} of ${eligible} new facts unlinked`,
stats.no_subject === null ? 'relink history unavailable (fact_relink_attempts missing)' : `${stats.no_subject} judged no_subject`,
`7-day links: inferred page ${stats.inferred_7d.page}, mention ${stats.inferred_7d.mention}${stats.relinked_7d ? `; relink ${Object.entries(stats.relinked_7d).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([t, c]) => `${t} ${c}`).join(', ') || 'none'}` : ''}`,
];
if (stats.origins.length > 0) parts.push(`top origins: ${stats.origins.slice(0, 3).map((o) => `${o.origin} ${o.unlinked}`).join(', ')}`);
+ const fix = stats.conversation ? reextractFix(stats.conversation, opts.thinClient === true) : undefined;
+ const conversationHint = fix ? ` Conversation facts are derived from their page, so relink never examines them; 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}` : ''}`,
+ message: `${parts.join('; ')}${warn || w.unlinked > 0 ? `. ${warn ? `Over ${UNLINKED_NEW_SHARE_WARN * 100}% of new facts are unlinked; ` : ''}${hint}` : ''}${conversationHint}`,
details: { ...stats, new_7d: { ...recent, eligible, unlinked_eligible: unlinkedNew }, fix: hint },
+ ...(fix ? { fix } : {}),
+ };
+}
+
+/**
+ * #6764: the conversation share's fix, a bounded re-extraction of the pages
+ * holding the most unlinked derived rows in one source, capped at $1, 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'],
+ 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${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.',
};
}
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 91b857cc90..46eb291397 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -112,6 +112,7 @@ import {
resolveExtractedEntitiesForSave,
} 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';
// Re-exported verbatim so existing importers (this file's own helpers below
// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,
@@ -1086,7 +1087,7 @@ async function processPage(
// (above) ran every fact through the shipped resolver cascade (#3729/#4052),
// so master's per-row resolveEntitySlug mapper (#4567's independent fix for
// the same issue) is superseded rather than layered on top.
- const rows = extracted.map((fact, i) => ({
+ const rows = await inferConversationSubjects(state.engine, state.sourceId, state.factVisibility, extracted.map((fact, i) => ({ // #6764
...fact, visibility: state.factVisibility,
row_num: rowNum + i,
source_markdown_slug: page.slug,
@@ -1098,7 +1099,7 @@ async function processPage(
...segmentValidFrom(fact.valid_from, seg.startIso),
context:
fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,
- }));
+ })));
if (state.managed) {
managedRows.push(...rows);
} else {
diff --git a/src/core/facts/conversation-subject-infer.ts b/src/core/facts/conversation-subject-infer.ts
new file mode 100644
index 0000000000..6308651ba2
--- /dev/null
+++ b/src/core/facts/conversation-subject-infer.ts
@@ -0,0 +1,46 @@
+/**
+ * #6764: write-time fact subject inference for the conversation extractor's
+ * bulk path (`gbrain extract-conversation-facts`, the backfill phase) and for
+ * the free conversation relink (`gbrain facts relink --conversation`).
+ *
+ * The extractor sometimes returns a fact with no entity, or one the save-time
+ * resolver could not resolve. Such a fact gets the subject `inferFactSubject`
+ * proves from identity evidence, in `write` mode (exactly one live entity
+ * page named in full; any competing name vetoes), with the
+ * `entity inferred from <tier>` note the doctor counts. The conversation page
+ * is never an entity page, so only the mention tier can fire.
+ *
+ * The row stays a derived row of the conversation page: `entity_slug` is a
+ * column on it, and nothing is written to the entity page, so the backstop's
+ * fence and target-page authority checks do not apply. What does: a
+ * withdrawn claim and visibility (a private page never resolves, nor counts
+ * toward uniqueness, for a world fact). The extractor also honours the
+ * `facts.entity_inference` kill switch; relink ignores it, as
+ * `gbrain facts relink` does. Trusted local callers only.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { FactVisibility } from './visibility.ts';
+import { appendContextNote, inferFactSubject, isEntityInferenceEnabled, type InferResult } from './subject-infer.ts';
+import { inferenceNote } from './subject-infer-write.ts';
+import { isFactWithdrawn } from './withdrawal.ts';
+import { isNullLikeEntity } from './write-single.ts';
+
+/** One conversation fact's subject: the inferred entity, or why none was proven (`withdrawn` when the claim was withdrawn on it). */
+export async function inferConversationSubject(engine: BrainEngine, sourceId: string, visibility: FactVisibility, fact: string,
+): Promise<InferResult | { slug: null; reason: 'withdrawn'; resolved: string[] }> {
+ const inferred = await inferFactSubject(engine, sourceId, { fact, mode: 'write', excludePrivate: visibility === 'world' });
+ if (inferred.slug !== null && await isFactWithdrawn(engine, sourceId, visibility, fact, inferred.slug)) return { slug: null, reason: 'withdrawn', resolved: [inferred.slug] };
+ return inferred;
+}
+
+export async function inferConversationSubjects<T extends { fact: string; entity_slug?: string | null; context?: string | null }>(
+ engine: BrainEngine, sourceId: string, visibility: FactVisibility, rows: T[]): Promise<T[]> {
+ if (!rows.length || !(await isEntityInferenceEnabled(engine))) return rows;
+ const out: T[] = [];
+ for (const row of rows) {
+ if (!isNullLikeEntity(row.entity_slug)) { out.push(row); continue; }
+ const inferred = await inferConversationSubject(engine, sourceId, visibility, row.fact);
+ out.push(inferred.slug === null ? row : { ...row, entity_slug: inferred.slug, context: appendContextNote(row.context, inferenceNote(inferred.via)) });
+ }
+ return out;
+}
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 94584ddbec..6ed91d981e 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -134,6 +134,12 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
return { status: 'inserted', candidate: null };
}
+/** #6764: a conversation-derived fact changes when its page is re-extracted (forget + remember would only withdraw it). */
+function replacesDerivedSuggestion(sourceId: string, slug: string): string {
+ const base = `gbrain extract-conversation-facts --source-id ${sourceId} --slugs ${slug} --force`;
+ return `Re-extract the conversation page to change its facts: preview with ${base} --dry-run, then run ${base} --max-cost-usd <n> (paid).`;
+}
+
/**
* `remember.replaces`: the caller names the fact the new one replaces. Checked,
* zero-model: the target must be an active fact in this source with the same
@@ -172,8 +178,9 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
'Pass the same entity as the fact being replaced, or forget the old fact and remember the new one separately.');
}
if (candidate.source_markdown_slug && candidate.source_markdown_slug !== opts.pageSlug) {
- throw verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}.`,
- 'Forget the old fact, then remember the new one.');
+ const derived = String(candidate.source ?? '').startsWith('cli:extract-conversation-facts');
+ throw verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}${derived ? ', extracted from that conversation page' : ''}.`,
+ derived ? replacesDerivedSuggestion(sourceId, candidate.source_markdown_slug) : 'Forget the old fact, then remember the new one.');
}
const exact = await decideSingleFact(engine, sourceId, input, null, undefined, undefined, { excludePrivate: opts.excludePrivate });
if (exact.status === 'duplicate') {
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 4edd52a196..5a3fc8f457 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -129,7 +129,7 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
if (code === 'purged_content') return { reason: code, message: 'This content was purged from this source and cannot be saved again.',
suggestion: PURGED_SUGGESTION };
const memory = code === 'invalid_params' ? MEMORY_REFUSAL.exec(message ?? '') : null;
- if (memory) return { reason: code, message: message!, suggestion: MEMORY_REFUSAL_SUGGESTION[memory[1]!]! };
+ if (memory) return { reason: code, message: message!, suggestion: MEMORY_REFUSAL_SUGGESTION[/, extracted from that conversation page\.$/.test(message!) ? 'replaces_cross_page_derived' : memory[1]!]! };
const reason = isWriteErrorCode(code) ? code : 'storage_error';
return { reason, message: `The write did not commit: it ended with ${reason}, and nothing was saved.`,
suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };
@@ -146,6 +146,7 @@ const MEMORY_REFUSAL_SUGGESTION: Record<string, string> = {
target_expired: 'Remember the new claim without replaces.',
replaces_entity_mismatch: 'Pass the same entity as the fact being replaced, or forget the old fact and remember the new one separately.',
replaces_cross_page: 'Forget the old fact, then remember the new one.',
+ replaces_cross_page_derived: 'Re-extract the conversation page named here to change its facts: preview with gbrain extract-conversation-facts --slugs <page> --force --dry-run, then run it with --max-cost-usd <n> (paid).',
replaces_duplicate: 'Forget the replaced fact if it is no longer true; the existing fact named here already says the new claim.',
};
diff --git a/test/conversation-facts-unlinked-6764.test.ts b/test/conversation-facts-unlinked-6764.test.ts
new file mode 100644
index 0000000000..582a244134
--- /dev/null
+++ b/test/conversation-facts-unlinked-6764.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #6764: conversation-extractor facts and the unlinked_facts doctor check.
+ *
+ * Protects: (1) write-time free subject inference on the conversation
+ * extractor's bulk path: a fact the extractor returned with no entity that
+ * names exactly one live entity page in full is linked to it with the
+ * `entity inferred from mention` note (unmanaged and managed), the
+ * `facts.entity_inference` kill switch stops it, an extractor-named entity is
+ * never overridden, and a private entity page never links a world fact.
+ * (2) doctor `unlinked_facts` labels those rows origin `conversation`,
+ * counts them apart from fence rows, and for them prescribes a bounded,
+ * source-qualified, capped re-extraction (preview first) instead of
+ * `gbrain facts relink`, which never examines derived rows. (3) a
+ * `remember --replaces` aimed at a conversation-derived fact names
+ * re-extraction instead of forget-then-remember.
+ * Regression: the bulk path skipping inference; the doctor mislabeling the
+ * origin as remember and prescribing relink for rows relink cannot touch.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { parseArgs, runExtractConversationFacts, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';
+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';
+import { dispatchRenderContext, dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const MEETING = 'meetings/2026-08-12-lease-review';
+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');
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function seedPages(db: BrainEngine, aliceFrontmatter: Record<string, unknown> = {}): Promise<void> {
+ await db.putPage(MEETING, { type: 'meeting' as never, title: 'Lease review', compiled_truth: TRANSCRIPT, 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: aliceFrontmatter });
+ await db.putPage('people/bob-example', { type: 'person' as never, title: 'Bob Example', compiled_truth: '# Bob Example', timeline: '', frontmatter: {} });
+}
+
+async function extract(db: BrainEngine, fact: Partial<ExtractedFact> = {}) {
+ 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 () => [{ fact: 'Alice Example signed the lease renewal', kind: 'event', confidence: 0.9, entity_slug: null,
+ source: 'test', notability: 'high', ...fact } as ExtractedFact] });
+ } finally { spy.mockRestore(); }
+}
+
+async function extracted(db: BrainEngine) {
+ return db.executeRaw<{ entity_slug: string | null; context: string | null }>(
+ `SELECT entity_slug, context FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND source='cli:extract-conversation-facts' AND expired_at IS NULL`, [MEETING]);
+}
+
+describe('#6764 write-time inference on conversation facts', () => {
+ beforeEach(async () => { await resetPgliteState(engine); await seedPages(engine); });
+
+ test('a fact naming one entity page in full links to it, with the inference note', async () => {
+ await extract(engine);
+ const [row] = await extracted(engine);
+ expect(row!.entity_slug).toBe('people/alice-example');
+ expect(row!.context).toContain(' — entity inferred from mention');
+ expect(row!.context!.startsWith(`from ${MEETING} segment `)).toBe(true);
+ });
+
+ test('the kill switch stops it, and an extractor-named entity is kept', async () => {
+ await engine.setConfig('facts.entity_inference', 'off');
+ await extract(engine);
+ expect((await extracted(engine)).map(r => r.entity_slug)).toEqual([null]);
+ await engine.unsetConfig('facts.entity_inference');
+ await extract(engine, { entity_slug: 'people/bob-example' });
+ expect((await extracted(engine)).map(r => r.entity_slug)).toEqual(['people/bob-example']);
+ });
+
+ test('a private entity page never links a world fact; it links a private one', async () => {
+ await resetPgliteState(engine);
+ await seedPages(engine, { visibility: 'private' });
+ await engine.setConfig('facts.default_visibility', 'world');
+ await extract(engine);
+ expect((await extracted(engine)).map(r => r.entity_slug)).toEqual([null]);
+ await engine.unsetConfig('facts.default_visibility');
+ await extract(engine);
+ expect((await extracted(engine)).map(r => r.entity_slug)).toEqual(['people/alice-example']);
+ });
+
+ test('managed brain: the published batch carries the inferred entity', async () => {
+ await managedBrain(async ({ engine: db }) => {
+ const result = await extract(db);
+ expect(result).toMatchObject({ pages_processed: 1, pages_failed: 0 });
+ const [row] = await extracted(db);
+ expect(row!.entity_slug).toBe('people/alice-example');
+ expect(row!.context).toContain('entity inferred from mention');
+ }, { setup: async ({ engine: db }) => { await seedPages(db); } });
+ }, 120_000);
+});
+
+describe('#6764 unlinked_facts names conversation rows and their real fix', () => {
+ beforeEach(async () => { await resetPgliteState(engine); });
+
+ async function seedDerived(slug: string, count: number, sourceId = 'default') {
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from)
+ SELECT $1, NULL, 'derived ' || $2 || ' ' || g, 'cli:extract-conversation-facts', 'from ' || $2, g, $2, now(), now()
+ FROM generate_series(1, $3::int) AS g`, [sourceId, slug, count]);
+ }
+
+ test('origin conversation, counted apart from fence rows, with a capped re-extraction preview for this source only', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`);
+ await seedDerived('meetings/a', 6);
+ await seedDerived('meetings/b', 3);
+ await seedDerived('meetings/elsewhere', 4, 'other');
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, row_num, source_markdown_slug, created_at, valid_from)
+ VALUES ('default', NULL, 'fence fact', 'mcp:put_page', 1, 'notes/n1', now(), now())`);
+ const stats = await unlinkedFactsStats(engine, ['default']);
+ expect(stats!.window).toMatchObject({ unlinked: 10, fence_owned: 1, conversation: 9 });
+ expect(stats!.origins).toEqual([{ origin: 'conversation', unlinked: 9 }, { origin: 'mcp:put_page', unlinked: 1 }]);
+ const verdict = unlinkedFactsVerdict(stats);
+ expect(verdict.message).toContain('9 from conversation extraction');
+ expect(verdict.details).toMatchObject({ conversation: { source_id: 'default', 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.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');
+ });
+
+ test('at most 50 slugs in the argv; the total stays in details', async () => {
+ for (let i = 0; i < 55; i++) await seedDerived(`meetings/m${String(i).padStart(2, '0')}`, 1);
+ const verdict = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ const slugs = verdict.fix!.argv![verdict.fix!.argv!.indexOf('--slugs') + 1]!.split(',');
+ expect(slugs).toHaveLength(50);
+ expect(verdict.details).toMatchObject({ conversation: { pages: 55 } });
+ });
+
+ test('no conversation rows: the relink hint and no structured fix, as before', async () => {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, created_at, valid_from) VALUES ('default', NULL, 'free fact', 'cli:remember', now(), now())`);
+ const verdict = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ expect(verdict.fix).toBeUndefined();
+ expect(verdict.message).toContain('gbrain facts relink --dry-run');
+ });
+});
+
+describe('#6764 replacing a conversation-derived fact names re-extraction', () => {
+ beforeEach(async () => { await disposePersistenceConsumer(engine); await resetPgliteState(engine); await seedPages(engine); });
+
+ test('remember --replaces on an extracted conversation fact points at extract-conversation-facts', async () => {
+ await extract(engine);
+ const [row] = await engine.executeRaw<{ id: string }>(`SELECT id FROM facts WHERE source_markdown_slug=$1 AND source='cli:extract-conversation-facts'`, [MEETING]);
+ const res = await dispatchToolCall(engine, 'remember', { fact: 'Alice Example renewed the lease for two years', provenance: 'test',
+ entity: 'people/alice-example', visibility: 'private', replaces: String(row!.id) }, { remote: false });
+ expect(res.isError).toBe(true);
+ const body = res.content[0]!.text!;
+ expect(body).toContain('replaces_cross_page');
+ expect(body).toContain('gbrain extract-conversation-facts');
+ expect(body).not.toContain('Forget the old fact, then remember the new one.');
+ });
+});
+
+describe('#6764 fixture: the conversation fix envelope clears the finding', () => {
+ beforeEach(async () => { await resetPgliteState(engine); await seedPages(engine); });
+
+ test('render, run the free preview, run the capped argv with the extractor stubbed, verify cleared', async () => {
+ // An older run stored the fact with no entity (no hints, no inference).
+ 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, 'Alice Example signed the lease renewal', 'cli:extract-conversation-facts', 'from ${MEETING}', 0, $1, now(), now())`, [MEETING]);
+ const before = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ const fix = before.fix!;
+ expect(renderAction(fix as never, cliRenderContext())).toMatchObject({ next: 'ask_user', preview_argv: fix.preview_argv });
+ const spy = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ 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));
+ 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,
+ entity_slug: null, source: 'test', notability: 'high' } as ExtractedFact] });
+ } finally { spy.mockRestore(); log.mockRestore(); }
+ const after = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ expect(after.fix).toBeUndefined();
+ expect((after.details as any).conversation).toBeNull();
+ });
+});