Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): free conversation relink is the primary unlinked_facts fix (#6764)
garrytan9d22a479b043
diff --git a/docs/.wave18-fragments/lane3.md b/docs/.wave18-fragments/lane3.mdindex 0ba63d31b6..f5b19a81df 100644--- a/docs/.wave18-fragments/lane3.md+++ b/docs/.wave18-fragments/lane3.md@@ -95,3 +95,21 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place### 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.++## #6764 (d1b, own commit: drop it if Garry picks d1a) free conversation relink as the doctor's primary fix++### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)++```ts+ { since: '<WAVE>', text: 'New `gbrain facts relink --conversation` links the conversation extractor\'s facts that were stored without an entity, for free: a fact naming exactly one entity page in full is linked (context note `entity relinked from mention`), one write per page (a receipted coordinator request on a managed brain), no model call (#6764). Doctor `unlinked_facts` now prescribes it first for those rows (consent none, the agent runs it, preview `--dry-run`); a fact it cannot resolve is recorded (`fact_relink_attempts` outcome `conversation_unresolved`), and only then does the doctor offer the paid, capped re-extraction of its page.' },+```++### CHANGELOG.md (wave entry, Fixed; same bullet as the #6764 line above, extended)++- `gbrain facts relink --conversation` links existing conversation facts to the people and companies they name, for free; doctor offers it before any paid re-extraction (#6764).++### Notes++- New maintenance intent kind `managed_maintenance_conversation_relink`, dispatched in `src/core/persistence/prepared-maintenance.ts` (one line, not a listed registry). New canonical-writer census row for `src/core/facts/conversation-relink.ts` in `docs/architecture/canonical-writers.tsv` (ceiling 1, boundary coordinator).+- Module sizes: `src/commands/facts.ts` 201 lines, `src/core/facts/conversation-relink.ts` 187 (new), `src/core/persistence/prepared-maintenance.ts` 590; none is listed in the TSV and all are under the new-file cap. No TSV change.+- Dropping this commit (d1a) restores the commit before it exactly: doctor prescribes the paid re-extraction for every unlinked conversation row. The commit also edits that commit's own tests (seeding a `conversation_unresolved` memo so they still exercise the paid envelope).diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 94057b0f8f..d3a89393f7 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -8,6 +8,7 @@ src/core/persistence/takes-prepare.ts 4 coordinator Semantic takes apply only thsrc/commands/extract-timeline-db.ts 2 coordinator `gbrain extract timeline --source db` (#5904): on a managed brain the timeline retraction and insert run only inside the managed_maintenance_timeline_extract publication (prepareTimelineExtract; owner-checked by maintenancePreflight, page key locked, revision-bound); only an unmanaged brain retracts and batch-inserts directly, where no canonical writer enforcement applies.src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain each page's fact rows and outcome row are frozen into one database-only managed_maintenance_conversation_facts request (facts/conversation-publication.ts) after a maintenance preflight before provider work; the coordinator's preparer revalidates page identity, revision and parser-input snapshot under the page key. Unmanaged calls keep their direct engine writes behind the SQL guard (writeDerivedFacts refuses on a managed brain).src/core/facts/conversation-publication.ts 4 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) and inserts each member page's frozen entry inside the coordinator publication of its admitted managed_maintenance_conversation_facts batch request, after rechecking authority, page identity, revision and version token under each page key (a moved page is skipped and reported, never failing the batch; a page whose rows fail validation gets a blocked not-extractable outcome row); a lost insert rolls the publication back. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction.+src/core/facts/conversation-relink.ts 1 coordinator `gbrain facts relink --conversation` (#6764) sets entity_slug and the relink note on a conversation page's unlinked derived rows still exactly as planned (same claim, unlinked, active, target page live) under the page key: one database-only managed_maintenance_conversation_relink request per page on a managed brain (the preparer authorizes the anchor and the page), one writeDerivedFacts maintenance transaction per page on an unmanaged brain.src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair preflights every target before the first backup/write.src/commands/import.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 5918da36e3..aadf9bbacc 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -31,4 +31,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those, reads through `deadlineEngine` (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`.- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.-- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` 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`.+- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain, a bounded re-extraction of those pages (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd 1`, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdindex 927e9a2039..a2732a972d 100644--- a/docs/architecture/key-files/core-persistence-facts.md+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -9,4 +9,5 @@ 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`.+- `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`.diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.mdindex 46b5dc459b..4cf1610f48 100644--- a/docs/guides/facts-relink.md+++ b/docs/guides/facts-relink.md@@ -115,6 +115,25 @@ gbrain forget <fact-id>gbrain remember "<the fact>" --provenance "<source>" --entity <slug>```+## Conversation facts++Facts `gbrain extract-conversation-facts` stored without an entity belong to+their conversation page, so plain `gbrain facts relink` never examines them.+Link them for free, with the same rule as write-time inference (exactly one+entity page named in full, no competing name, no model call):++```bash+gbrain facts relink --conversation --dry-run # what would link; writes nothing+gbrain facts relink --conversation # the 50 pages with the most untried unlinked facts+gbrain facts relink --conversation --slugs a,b # exactly these pages+```++A linked fact stays on its conversation page with the entity set and the note+`entity relinked from mention`. A fact no entity can be proven for is recorded,+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.+## Why a fact was not linked| Reason | Remembered | What to do |diff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.tsindex 89e31d941a..6ef600ea92 100644--- a/src/commands/doctor/checks/unlinked-facts.ts+++ b/src/commands/doctor/checks/unlinked-facts.ts@@ -10,8 +10,10 @@* `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 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+ * (#6764: plain relink never examines them; `gbrain facts relink+ * --conversation` links them for free, and re-extraction, which runs+ * write-time inference, is the paid fallback for rows that free relink+ * already tried), 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@@ -25,6 +27,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/conversation-relink.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';export const UNLINKED_NEW_SHARE_WARN = 0.25;@@ -38,8 +41,11 @@ const DERIVED = `f.source LIKE 'cli:extract-conversation-facts%'`;export interface UnlinkedFactsStats {sources: number;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;+ /**+ * 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.+ */+ conversation: { source_id: string; fix: 'relink' | 'reextract'; pages: number; slugs: string[] } | null;new_7d: { facts: number; unlinked: number; no_subject: number };no_subject: number | null;origins: Array<{ origin: string; unlinked: number }>;@@ -64,12 +70,15 @@ 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 windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number; conversation: number }>(+ 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 }>(`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)::int AS conversation,+ COUNT(*) FILTER (WHERE w.unlinked AND w.derived AND w.tried)::int AS conversation_triedFROM 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,(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@@ -78,10 +87,11 @@ 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>();+ const derivedBySource = new Map<string, { untried: number; tried: 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));+ 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) });if (n(r.unlinked) > 0) byOrigin.set(r.origin, (byOrigin.get(r.origin) ?? 0) + n(r.unlinked));}const judged = hasAttempts@@ -109,16 +119,18 @@ 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 [derivedSource] = [...derivedBySource].filter(([, c]) => c > 0).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));+ 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]));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+ `SELECT w.slug FROM (SELECT f.source_markdown_slug AS slug, f.entity_slug IS NULL AND ${DERIVED} AND ${fixKind === 'relink' ? 'NOT ' : ''}${tried} 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],);- conversation = { source_id: derivedSource[0], pages: pages.length, slugs: pages.slice(0, CONVERSATION_FIX_SLUGS).map(r => r.slug) };+ conversation = { source_id: derivedSource[0], fix: fixKind, pages: pages.length, slugs: pages.slice(0, CONVERSATION_FIX_SLUGS).map(r => r.slug) };}return {sources: ids.length,@@ -161,8 +173,11 @@ export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { t`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(' ')}.` : '';+ 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(' ')}.`;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}`,@@ -172,8 +187,21 @@ export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { t}/**- * #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+ * #6764: the conversation share's free fix, `gbrain facts relink --conversation` over the pages holding the most+ * unlinked derived rows it has not tried in one source: write-mode subject inference, no model call, one write per page.+ */+function relinkFix(c: NonNullable<UnlinkedFactsStats['conversation']>, thinClient: boolean): Action {+ const argv = ['gbrain', 'facts', 'relink', '--conversation', '--source', c.source_id, '--slugs', c.slugs.join(',')];+ return {+ argv, preview_argv: [...argv, '--dry-run'], consent: [], actor: thinClient ? 'host_admin' : 'agent', requires_exclusive: false, verify: doctorVerify('unlinked_facts'),+ why: `${c.pages} conversation page(s) in source ${c.source_id} hold extracted facts with no entity that free relink has not tried${c.pages > c.slugs.length ? ` (the ${c.slugs.length} with the most are named)` : ''}. `+ + 'Relink links each one that names exactly one entity page in full, with no model call; the dry run lists the links and writes nothing.',+ };+}++/**+ * #6764: the conversation share's paid fallback, for rows free relink already tried: a bounded re-extraction of the pages+ * holding the most such rows in one source, capped at $1, with a* free dry run as the preview. Re-extraction reruns the extractor with the* page's entity hints and write-time subject inference.*/@@ -182,7 +210,7 @@ function reextractFix(c: NonNullable<UnlinkedFactsStats['conversation']>, thinClreturn {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)` : ''}. `+ why: `${c.pages} conversation page(s) in source ${c.source_id} hold extracted facts with no entity that free relink could not resolve${c.pages > c.slugs.length ? ` (the ${c.slugs.length} with the most are named)` : ''}. `+ 'Re-extraction calls the fact-extraction model again (up to $1) with the page\'s entity hints and write-time subject inference; the dry run shows the plan and makes no model call.',};}diff --git a/src/commands/facts.ts b/src/commands/facts.tsindex 5c4c28ce73..7c1d2d4aac 100644--- a/src/commands/facts.ts+++ b/src/commands/facts.ts@@ -7,6 +7,7 @@ import type { BrainEngine } from '../core/engine.ts';import type { GBrainConfig } from '../core/config.ts';import { RELINK_DEFAULT_LIMIT, RELINK_DEFAULT_MAX_USD, runFactsRelink, type RelinkOptions, type RelinkReport } from '../core/facts/relink.ts';import { RELINK_REASONS, type RelinkReason } from '../core/facts/relink-reasons.ts';+import { CONVERSATION_RELINK_PAGES, runConversationRelink, type ConversationRelinkReport } from '../core/facts/conversation-relink.ts';export function factsHelpText(): string {return `Usage: gbrain facts <subcommand>@@ -29,6 +30,14 @@ gbrain facts relink [flags]--examples <n> Example facts per outcome (default 3)--json Machine-readable report (schema_version ${1})+gbrain facts relink --conversation [--source <id>] [--slugs <a,b>] [--dry-run] [--json]+ Link the conversation extractor's facts saved without an entity (plain+ relink never examines them), free only: a fact naming exactly one entity+ page in full is linked, one write per page. Without --slugs, the+ ${CONVERSATION_RELINK_PAGES} pages with the most untried unlinked facts. Facts it cannot+ resolve are recorded, and the report prints the paid re-extraction for+ their pages.+Relink never creates pages and never supersedes a fact. Exact duplicates areretired (expired, kept in history). Linked facts are queued for the System Oneconflict sweep when that slot is on. Free tiers cost nothing; the model tier@@ -124,6 +133,41 @@ export function formatRelinkReport(report: RelinkReport, args: string[]): stringreturn lines.join('\n');}+export function formatConversationRelinkReport(r: ConversationRelinkReport, args: string[]): string {+ const lines = [`${r.dry_run ? 'DRY RUN: would link' : 'Linked'} ${r.linked} conversation fact(s) on ${r.pages.length} page(s) in source ${r.source_id}`+ + ` (mention tier, no model call); ${r.unresolved} unresolved${r.changed ? `; ${r.changed} changed before the write (run again)` : ''}.`];+ for (const p of r.pages) lines.push(` ${p.slug}: ${p.linked} linked, ${p.unresolved} unresolved`);+ if (r.dry_run && r.linked) lines.push(`Apply with:\n gbrain facts relink ${args.filter(a => a !== '--dry-run').join(' ')}`);+ if (r.reextract_slugs.length) {+ const base = `gbrain extract-conversation-facts --source-id ${r.source_id} --slugs ${r.reextract_slugs.join(',')} --force`;+ lines.push(`No entity could be proven for ${r.unresolved} fact(s). Re-extraction calls the fact model again (paid); preview, then run with a cap:\n ${base} --dry-run\n ${base} --max-cost-usd 1`);+ }+ return lines.join('\n');+}++/** `--conversation` flags: --source, --slugs, --dry-run, --json; anything else is a usage error. */+async function runConversation(engine: BrainEngine, args: string[], config: GBrainConfig, sourceId: string): Promise<number> {+ const opts: { sourceId: string; slugs?: string[]; dryRun?: boolean } = { sourceId };+ let json = false;+ for (let i = 0; i < args.length; i++) {+ const a = args[i]!;+ const v = args[i + 1];+ if (a === '--conversation') continue;+ if (a === '--json') json = true;+ else if (a === '--dry-run') opts.dryRun = true;+ else if ((a === '--source' || a === '--slugs') && v !== undefined && !v.startsWith('--')) {+ if (a === '--source') opts.sourceId = v; else opts.slugs = v.split(',').map(s => s.trim()).filter(Boolean);+ i++;+ } else {+ console.error(`gbrain facts relink --conversation: ${a === '--source' || a === '--slugs' ? `${a} requires a value` : `unknown flag ${a} (takes --source, --slugs, --dry-run, --json)`}`);+ return 1;+ }+ }+ const report = await runConversationRelink(engine, config, opts);+ console.log(json ? JSON.stringify(report, null, 2) : formatConversationRelinkReport(report, args));+ return 0;+}+/** Exit code: 0 for complete and partial runs (limit or budget), 1 for usage errors. */export async function runFactsCommand(engine: BrainEngine, args: string[], config: GBrainConfig, sourceId: string): Promise<number> {const sub = args[0];@@ -140,6 +184,7 @@ export async function runFactsCommand(engine: BrainEngine, args: string[], conficonsole.log(factsHelpText());return 0;}+ if (rest.includes('--conversation')) return runConversation(engine, rest, config, sourceId);const parsed = parseRelinkArgs(rest, sourceId);if (parsed.error) {console.error(`gbrain facts relink: ${parsed.error}`);diff --git a/src/core/facts/conversation-relink.ts b/src/core/facts/conversation-relink.tsnew file mode 100644index 0000000000..557e1bedf3--- /dev/null+++ b/src/core/facts/conversation-relink.ts@@ -0,0 +1,187 @@+/**+ * #6764: `gbrain facts relink --conversation`, the free relink of the+ * conversation extractor's derived rows (`cli:extract-conversation-facts*`)+ * that were stored without an entity. `gbrain facts relink` never examines+ * them (they are row-numbered rows of the conversation page), and before+ * write-time inference (conversation-subject-infer.ts) every such row was+ * stored unlinked.+ *+ * Per page, each unlinked derived row runs `inferConversationSubject`+ * (`inferFactSubject` in `write` mode, visibility-filtered, withdrawn claims+ * skipped); no model is called. A page's proven links are one write: a+ * managed brain publishes one database-only `managed_maintenance_conversation_relink`+ * request holding the page's key (the coordinator transaction carries the+ * receipt), an unmanaged brain one maintenance transaction at the page's+ * derived tier. The write sets `entity_slug` and appends the+ * `entity relinked from <tier>` note only on rows still exactly as planned+ * (same claim, still unlinked and active, target page live); the row stays a+ * derived row of the conversation page, and a `linked` attempt row records+ * 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.+ */+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import type { FactVisibility } from './visibility.ts';+import { opError } from '../ops/contract.ts';+import { digest } from '../persistence/digest.ts';+import { isTerminal } from '../persistence/model.ts';+import { getWriteRequest } from '../persistence/journal.ts';+import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';+import { waitForWrite, writeResponse } from '../persistence/service.ts';+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { writeDerivedFacts } from '../persistence/derived-facts.ts';+import { AUDIT_ROW_SOURCES } from './audit-sources.ts';+import { appendContextNote } from './subject-infer.ts';+import { inferConversationSubject } from './conversation-subject-infer.ts';++export const CONVERSATION_RELINK_INTENT = 'managed_maintenance_conversation_relink';+/** The request slug: a dot-led segment no page can hold; the page's own key is locked with it. */+export const CONVERSATION_RELINK_ANCHOR = '.maintenance/conversation-relink';+/** The `fact_relink_attempts` outcome of a derived row this relink could not resolve. */+export const CONVERSATION_UNRESOLVED = 'conversation_unresolved';+/** Pages one run relinks when no `--slugs` are named. */+export const CONVERSATION_RELINK_PAGES = 50;+/** The SQL predicate (on alias `f`, audit sources as `$audit`) of a conversation extractor's derived fact row. */+export const derivedConversationRow = (audit: string) => `f.source LIKE 'cli:extract-conversation-facts%' AND f.source <> ALL(${audit}::text[])`;+const ACTIVE = 'f.entity_slug IS NULL AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())';++export interface ConversationRelinkRow { id: number; fact: string; entity_slug: string; context: string }+interface PagePlan { slug: string; link: ConversationRelinkRow[]; misses: Array<{ id: number; reason: string }> }+export interface ConversationRelinkReport {+ source_id: string;+ dry_run: boolean;+ pages: Array<{ slug: string; linked: number; unresolved: number; changed: number }>;+ linked: number;+ unresolved: number;+ /** Planned links whose row moved before the write (left for the next run). */+ changed: number;+ /** Pages still holding unresolved rows: the paid re-extraction fallback names them. */+ reextract_slugs: string[];+}++async function hasAttemptsTable(engine: BrainEngine): Promise<boolean> {+ const [row] = await engine.executeRaw<{ t: string | null }>(`SELECT to_regclass('fact_relink_attempts')::text AS t`);+ return !!row?.t;+}++/** 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)' : '';+ 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}+ GROUP BY f.source_markdown_slug ORDER BY COUNT(*) DESC, f.source_markdown_slug LIMIT $3`, [sourceId, [...AUDIT_ROW_SOURCES], limit]);+ return rows.map(r => r.slug);+}++async function planPages(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<PagePlan[]> {+ const rows = await engine.executeRaw<{ id: number | string; fact: string; context: string | null; visibility: FactVisibility; slug: string }>(+ `SELECT f.id, f.fact, f.context, f.visibility, f.source_markdown_slug AS slug FROM facts f+ WHERE f.source_id = $1 AND f.source_markdown_slug = ANY($2::text[]) AND ${ACTIVE} AND ${derivedConversationRow('$3')}+ ORDER BY f.source_markdown_slug, f.id`, [sourceId, slugs, [...AUDIT_ROW_SOURCES]]);+ const pages = new Map<string, PagePlan>();+ for (const row of rows) {+ const page = pages.get(row.slug) ?? { slug: row.slug, link: [], misses: [] };+ pages.set(row.slug, page);+ const inferred = await inferConversationSubject(engine, sourceId, row.visibility, row.fact);+ if (inferred.slug === null) page.misses.push({ id: Number(row.id), reason: inferred.reason });+ else page.link.push({ id: Number(row.id), fact: row.fact, entity_slug: inferred.slug, context: appendContextNote(row.context, `entity relinked from ${inferred.via}`) });+ }+ return slugs.flatMap(slug => pages.get(slug) ?? []);+}++/** Under the page's lock: link the planned rows still exactly as planned, recording each link. */+async function linkRows(tx: BrainEngine, sourceId: string, slug: string, rows: ConversationRelinkRow[]): Promise<number[]> {+ const linked: number[] = [];+ const attempts = await hasAttemptsTable(tx);+ for (const row of rows) {+ const done = await tx.executeRaw<{ id: number | string }>(+ `UPDATE facts f SET entity_slug = $4, context = $5 WHERE f.source_id = $1 AND f.id = $2 AND f.source_markdown_slug = $3 AND f.fact = $6+ AND ${ACTIVE} AND ${derivedConversationRow('$7')}+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $4 AND p.deleted_at IS NULL) RETURNING f.id`,+ [sourceId, row.id, slug, row.entity_slug, row.context, row.fact, [...AUDIT_ROW_SOURCES]]);+ if (!done.length) continue;+ linked.push(row.id);+ if (attempts) await tx.executeRaw(+ `INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, reason, tier, model, target_slug, run_id, attempted_at)+ VALUES ($1, $2, 'linked', NULL, 'mention', NULL, $3, NULL, now())+ ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = 'linked', reason = NULL, tier = 'mention', model = NULL,+ target_slug = EXCLUDED.target_slug, run_id = NULL, attempted_at = EXCLUDED.attempted_at`, [sourceId, row.id, row.entity_slug]);+ }+ return linked;+}++function requestIdFor(sourceId: string, slug: string, rows: ConversationRelinkRow[], attempt: number): string {+ const h = digest(['conversation-relink-v1', sourceId, slug, rows.map(r => [r.id, r.entity_slug, r.context]), attempt]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+}++async function publishManaged(engine: BrainEngine, config: GBrainConfig, authority: NonNullable<Awaited<ReturnType<typeof maintenancePreflight>>>,+ sourceId: string, page: PagePlan): Promise<number[]> {+ for (let attempt = 0; ; attempt++) {+ const requestId = requestIdFor(sourceId, page.slug, page.link, attempt);+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;+ let receipt: Record<string, unknown>;+ if (prior) {+ await authorizeStoredRequest(engine, prior);+ receipt = writeResponse(await waitForWrite(engine, prior, config));+ } else {+ receipt = await submitDatabaseMaintenanceIntent(engine, authority, CONVERSATION_RELINK_ANCHOR,+ { kind: CONVERSATION_RELINK_INTENT, expected_revision: null, page: page.slug, rows: page.link }, requestId);+ }+ return (receipt.linked as number[] | undefined) ?? [];+ }+}++export async function runConversationRelink(engine: BrainEngine, config: GBrainConfig,+ opts: { sourceId: string; slugs?: string[]; dryRun?: boolean }): Promise<ConversationRelinkReport> {+ const slugs = opts.slugs?.length ? opts.slugs : await conversationRelinkPages(engine, opts.sourceId);+ const plans = await planPages(engine, opts.sourceId, slugs);+ const report: ConversationRelinkReport = { source_id: opts.sourceId, dry_run: !!opts.dryRun, pages: [], linked: 0, unresolved: 0, changed: 0, reextract_slugs: [] };+ const authority = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId);+ const memo = !opts.dryRun && await hasAttemptsTable(engine);+ for (const page of plans) {+ let linked = page.link.length;+ if (!opts.dryRun && page.link.length) {+ linked = (authority ? await publishManaged(engine, config, authority, opts.sourceId, page)+ : await writeDerivedFacts(engine, opts.sourceId, page.slug, db => linkRows(db, opts.sourceId, page.slug, page.link))).length;+ }+ if (memo) for (const miss of page.misses) await engine.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, 'mention', NULL, NULL, NULL, now())+ ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, tier = 'mention',+ model = NULL, target_slug = NULL, run_id = NULL, attempted_at = EXCLUDED.attempted_at`, [opts.sourceId, miss.id, CONVERSATION_UNRESOLVED, miss.reason]);+ const changed = page.link.length - linked;+ report.pages.push({ slug: page.slug, linked, unresolved: page.misses.length, changed });+ report.linked += linked;+ report.unresolved += page.misses.length;+ report.changed += changed;+ if (page.misses.length) report.reextract_slugs.push(page.slug);+ }+ return report;+}++/** Preparer for `managed_maintenance_conversation_relink`: one page's links, database-only, holding the page's key. */+export async function prepareConversationRelink(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const intent = row.intent as { page?: unknown; rows?: ConversationRelinkRow[] } | null;+ const page = intent?.page;+ const rows = intent?.rows;+ if (row.slug !== CONVERSATION_RELINK_ANCHOR || typeof page !== 'string' || !Array.isArray(rows) || !rows.length+ || rows.some(r => !Number.isSafeInteger(r?.id) || typeof r.fact !== 'string' || typeof r.entity_slug !== 'string' || typeof r.context !== 'string')) {+ throw opError('invalid_params', 'The conversation relink intent does not name its page and rows.',+ `Request ${row.request_id} in source ${row.source_id} does not name the conversation page and the rows it links, so nothing changed. Preview the relink again with gbrain facts relink --conversation --source ${row.source_id} --dry-run.`);+ }+ const authorize = async (db: BrainEngine) => {+ await authorizeWrite(db, row.authority, 'submit_job', row.slug);+ await authorizeWrite(db, row.authority, 'submit_job', page);+ };+ await authorize(engine);+ return { observedRevision: null, noop: true, additionalPageKeys: [{ sourceId: row.source_id, slug: page }], validate: authorize,+ apply: async tx => ({ status: 'completed', page, linked: await linkRows(tx, row.source_id, page, rows) }) };+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 2fa3885687..4c5c00ce84 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -501,6 +501,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);+ if (row.intent?.kind === 'managed_maintenance_conversation_relink') return (await import('../facts/conversation-relink.ts')).prepareConversationRelink(engine, row);if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);if (row.intent?.kind === 'managed_maintenance_fence_facts') return (await import('../cycle/extract-facts.ts')).prepareFenceFactsReconcile(engine, row, config);if (row.intent?.kind === 'managed_maintenance_deleted_page_facts_expire') return (await import('../cycle/extract-facts.ts')).prepareDeletedPageFactsExpiry(engine, row);diff --git a/test/conversation-facts-unlinked-6764.test.ts b/test/conversation-facts-unlinked-6764.test.tsindex 582a244134..7fcbe1699b 100644--- a/test/conversation-facts-unlinked-6764.test.ts+++ b/test/conversation-facts-unlinked-6764.test.ts@@ -8,9 +8,10 @@* `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+ * counts them apart from fence rows, and for rows the free conversation+ * relink could not resolve prescribes a bounded, source-qualified, capped+ * re-extraction (preview first) instead of plain `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@@ -114,19 +115,26 @@ describe('#6764 unlinked_facts names conversation rows and their real fix', () =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 () => {+ /** #6764 d1b: free relink tried every derived row and could not resolve it. */+ async function memoUnresolved() {+ await engine.executeRaw(`INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, reason, tier)+ SELECT source_id, id, 'conversation_unresolved', 'no_mention', 'mention' FROM facts WHERE source LIKE 'cli:extract-conversation-facts%'`);+ }++ test('origin conversation, counted apart from fence rows; rows free relink could not resolve get a capped re-extraction 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())`);+ await memoUnresolved();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'] } });+ expect(verdict.details).toMatchObject({ conversation: { source_id: 'default', fix: 'reextract', pages: 2, slugs: ['meetings/a', 'meetings/b'] } });const fix = verdict.fix!;expect(fix).toMatchObject({ consent: ['paid', 'egress'], actor: 'agent', ask_user: true, verify: { argv: ['gbrain', 'doctor', '--only', 'unlinked_facts', '--json'] } });expect(fix.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', 'meetings/a,meetings/b', '--force', '--max-cost-usd', '1']);@@ -136,6 +144,7 @@ describe('#6764 unlinked_facts names conversation rows and their real fix', () =});test('at most 50 slugs in the argv; the total stays in details', async () => {+ // Untried rows: the free relink names the pages (test/conversation-relink-6764.test.ts covers that envelope).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(',');@@ -171,9 +180,10 @@ 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]);+ // An older run stored the fact with no entity (no hints, no inference), and free relink could not resolve it then.+ const [old] = await engine.executeRaw<{ id: string }>(`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()) RETURNING id`, [MEETING]);+ await engine.executeRaw(`INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, reason, tier) VALUES ('default', $1, 'conversation_unresolved', 'no_mention', 'mention')`, [old!.id]);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 });diff --git a/test/conversation-relink-6764.test.ts b/test/conversation-relink-6764.test.tsnew file mode 100644index 0000000000..cd3b8886b6--- /dev/null+++ b/test/conversation-relink-6764.test.ts@@ -0,0 +1,148 @@+/**+ * #6764 (d1b): the free conversation relink, `gbrain facts relink --conversation`.+ *+ * Protects: a conversation-extractor fact stored without an entity that names+ * exactly one live entity page is linked for free (write-mode inference, no+ * model), one write per page, on an unmanaged brain (maintenance+ * transaction) and a managed one (one receipted coordinator request); the dry+ * run writes nothing; an unresolvable fact gets a `conversation_unresolved`+ * memo and is named for the paid re-extraction; outcome rows and other pages+ * are untouched. Doctor `unlinked_facts` prescribes this free relink+ * (consent none, agent runs it) for untried rows and the paid re-extraction+ * only once relink tried and failed; the fixture renders the envelope, runs+ * the preview, the argv and the verify, and the finding moves on.+ * Regression: doctor prescribing paid re-extraction for rows a free pass links.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runFactsCommand } from '../src/commands/facts.ts';+import { runConversationRelink, CONVERSATION_RELINK_INTENT } from '../src/core/facts/conversation-relink.ts';+import { unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';+import * as inference from '../src/core/facts/conversation-subject-infer.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const MEETING = 'meetings/2026-08-12-lease-review';+const OTHER = 'meetings/2026-08-13-standup';+const config = { engine: 'pglite', embedding_disabled: true } as unknown as GBrainConfig;++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); });++async function seed(db: BrainEngine): Promise<void> {+ for (const slug of [MEETING, OTHER]) {+ await db.putPage(slug, { type: 'meeting' as never, title: slug, compiled_truth: 'notes', timeline: '', frontmatter: { date: '2026-08-12' } });+ }+ await db.putPage('people/alice-example', { type: 'person' as never, title: 'Alice Example', compiled_truth: '# Alice Example', timeline: '', frontmatter: {} });+ const row = (slug: string, n: number, fact: string, source = 'cli:extract-conversation-facts') => db.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from)+ VALUES ('default', NULL, $1, $2, $3, $4, $5, now(), now())`, [fact, source, `from ${slug} segment 2026-08-12`, n, slug]);+ await row(MEETING, 0, 'Alice Example signed the lease renewal');+ await row(MEETING, 1, 'The renewal starts in September');+ await row(MEETING, 2, 'EXTRACTION_COMPLETE', 'cli:extract-conversation-facts:terminal');+ await row(OTHER, 0, 'Alice Example will send the deck');+}++async function facts(db: BrainEngine, slug = MEETING) {+ return db.executeRaw<{ fact: string; entity_slug: string | null; context: string | null }>(+ 'SELECT fact, entity_slug, context FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', ['default', slug]);+}++async function cli(db: BrainEngine, argv: string[]): Promise<{ code: number; out: string }> {+ const lines: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((s: unknown) => { lines.push(String(s)); });+ try { return { code: await runFactsCommand(db, argv, config, 'default'), out: lines.join('\n') }; } finally { log.mockRestore(); }+}++describe('#6764 gbrain facts relink --conversation (unmanaged)', () => {+ beforeEach(async () => { await resetPgliteState(engine); await seed(engine); });++ test('the dry run writes nothing and names the paid fallback for the unresolved page', async () => {+ const { code, out } = await cli(engine, ['relink', '--conversation', '--slugs', MEETING, '--dry-run']);+ expect(code).toBe(0);+ expect(out).toContain('DRY RUN: would link 1 conversation fact(s) on 1 page(s) in source default');+ expect(out).toContain(`gbrain extract-conversation-facts --source-id default --slugs ${MEETING} --force --dry-run`);+ expect((await facts(engine)).map(r => r.entity_slug)).toEqual([null, null, null]);+ expect(await engine.executeRaw('SELECT 1 FROM fact_relink_attempts')).toHaveLength(0);+ });++ test('apply links the provable fact on the named page only, memoizes the miss, leaves the outcome row', async () => {+ const { code } = await cli(engine, ['relink', '--conversation', '--slugs', MEETING]);+ expect(code).toBe(0);+ const rows = await facts(engine);+ expect(rows.map(r => r.entity_slug)).toEqual(['people/alice-example', null, null]);+ expect(rows[0]!.context).toBe(`from ${MEETING} segment 2026-08-12 — entity relinked from mention`);+ expect((await facts(engine, OTHER)).map(r => r.entity_slug)).toEqual([null]);+ const attempts = await engine.executeRaw<{ outcome: string; target_slug: string | null }>('SELECT outcome, target_slug FROM fact_relink_attempts ORDER BY outcome');+ expect(attempts).toEqual([{ outcome: 'conversation_unresolved', target_slug: null }, { outcome: 'linked', target_slug: 'people/alice-example' }]);+ });++ test('without --slugs it takes the pages with untried rows; a rerun finds nothing new', async () => {+ const first = await runConversationRelink(engine, config, { sourceId: 'default' });+ expect(first).toMatchObject({ linked: 2, unresolved: 1, reextract_slugs: [MEETING] });+ const again = await runConversationRelink(engine, config, { sourceId: 'default' });+ expect(again).toMatchObject({ linked: 0, unresolved: 0, pages: [] });+ });++ test('a row that moved after the plan is not linked; it is reported as changed', async () => {+ const real = inference.inferConversationSubject;+ const spy = spyOn(inference, 'inferConversationSubject').mockImplementation(async (db, sourceId, visibility, fact) => {+ const result = await real(db, sourceId, visibility, fact);+ if (result.slug) await db.executeRaw(`UPDATE facts SET fact = fact || ' (edited)' WHERE source_markdown_slug = $1 AND fact = $2`, [MEETING, fact]);+ return result;+ });+ try {+ const report = await runConversationRelink(engine, config, { sourceId: 'default', slugs: [MEETING] });+ expect(spy).toHaveBeenCalled();+ expect(report).toMatchObject({ linked: 0, changed: 1, unresolved: 1 });+ } finally { spy.mockRestore(); }+ expect((await facts(engine)).map(r => r.entity_slug)).toEqual([null, null, null]);+ });+});++describe('#6764 doctor: free relink first, paid re-extraction only for rows it tried', () => {+ beforeEach(async () => { await resetPgliteState(engine); await seed(engine); });++ test('fixture: render the relink envelope, run its preview, its argv and the verify', async () => {+ const before = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));+ const fix = before.fix!;+ expect(fix).toMatchObject({ consent: [], actor: 'agent', verify: { argv: ['gbrain', 'doctor', '--only', 'unlinked_facts', '--json'] } });+ expect(fix.argv).toEqual(['gbrain', 'facts', 'relink', '--conversation', '--source', 'default', '--slugs', `${MEETING},${OTHER}`]);+ expect(fix.preview_argv).toEqual([...fix.argv!, '--dry-run']);+ expect(renderAction(fix as never, cliRenderContext()).next).toBe('run');+ expect(before.message).toContain('link them for free (preview first): gbrain facts relink --conversation');+ expect((await cli(engine, fix.preview_argv!.slice(2))).code).toBe(0);+ expect((await unlinkedFactsStats(engine, ['default']))!.window.conversation).toBe(3);+ expect((await cli(engine, fix.argv!.slice(2))).code).toBe(0);+ const after = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));+ expect(after.details).toMatchObject({ window: { conversation: 1 }, conversation: { fix: 'reextract', pages: 1, slugs: [MEETING] } });+ expect(after.fix).toMatchObject({ consent: ['paid', 'egress'], ask_user: true });+ expect(after.fix!.argv).toEqual(['gbrain', 'extract-conversation-facts', '--source-id', 'default', '--slugs', MEETING, '--force', '--max-cost-usd', '1']);+ });++ test('the remote report asks the brain host operator to run the relink', async () => {+ const verdict = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']), { thinClient: true });+ expect(verdict.fix).toMatchObject({ actor: 'host_admin', consent: [] });+ });+});++describe('#6764 gbrain facts relink --conversation (managed)', () => {+ test('one receipted coordinator request per page links the row', async () => {+ await managedBrain(async ({ engine: db }) => {+ const report = await runConversationRelink(db, config, { sourceId: 'default', slugs: [MEETING, OTHER] });+ expect(report).toMatchObject({ linked: 2, unresolved: 1, changed: 0 });+ expect((await facts(db)).map(r => r.entity_slug)).toEqual(['people/alice-example', null, null]);+ expect((await facts(db, OTHER)).map(r => r.entity_slug)).toEqual(['people/alice-example']);+ const requests = await db.executeRaw<{ state: string }>(`SELECT state FROM persistence_requests WHERE intent->>'kind' = $1`, [CONVERSATION_RELINK_INTENT]);+ expect(requests.map(r => r.state)).toEqual(['committed', 'committed']);+ }, { setup: async ({ engine: db }) => { await seed(db); } });+ }, 120_000);+});