Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): hint a conversation page's own entities to the extractor (#6731)

garrytanc9b869b8495d
diff --git a/docs/.wave18-fragments/lane3.md b/docs/.wave18-fragments/lane3.md
index 570bb42e51..47b3eb2d67 100644
--- a/docs/.wave18-fragments/lane3.md
+++ b/docs/.wave18-fragments/lane3.md
@@ -55,3 +55,23 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
### scripts/module-size-limits.tsv
- No row change: `src/core/cycle/extract-atoms.ts` is 1653 of its 1654 ceiling after this commit.
+
+## #6731 conversation extractor entity hints
+
+### 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 tells the extractor which entities the conversation page itself links (its frontmatter attendees and the entity pages its body links, same source, up to 40 slugs), so facts about those people and companies are stored on their pages instead of a guess from a first name (#6731). A private entity is hinted only when the run writes private facts. The `extract_facts` operation\'s prompt and 5-hint cap are unchanged.' },
+```
+
+### CHANGELOG.md (wave entry, Fixed; credit)
+
+- Conversation fact extraction passes the page's own linked entities to the extractor as hints, so more meeting facts link to the right person or company page (#6731). Contributed by @troyhoffman-oss (design from #6736; reimplemented with slug-only hints, a visibility filter and the op prompt left unchanged).
+
+### PR body
+
+- `Supersedes #6736`.
+
+### 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).
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 5e5e050aa9..32767fea7e 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.
-- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).
+- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Each page's own entities go to the extractor as `entityHints` (slugs, `src/core/facts/conversation-entity-hints.ts`, computed once per page, cap `CONVERSATION_ENTITY_HINTS_CAP` = 40 through `ExtractInput.entityHintsCap`): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; the `extract_facts` op keeps its 5-hint cap and prompt. Pinned by `test/conversation-entity-hints.test.ts`. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); `extract --stale` replaces through `replaceDerivedLinks`, the db link walk through `replaceDerivedLinksBatch`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently. `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows).
- `src/commands/extract-timeline-db.ts` — the `extract timeline --source db` walk (`extractTimelineFromDB`), also used by `runExtractCore` for a timeline-only pass on a managed brain. Managed brains (every fresh `gbrain init` brain) publish each page that needs a change as one database-only maintenance request (`managed_maintenance_timeline_extract`, owner-checked by `maintenancePreflight`, request id bound to the page revision; `prepareTimelineExtract` is dispatched from `prepareMaintenanceMutation`): under the page lock it retracts rows the current text no longer produces and inserts the canonical tuples with no stored row (`unrecordedCanonicalTimeline`); a page with nothing to change admits no request, and a page edited meanwhile is skipped. Unmanaged brains batch raw inserts. A refused write prints `refused: <code>; nothing written; existing timeline rows are untouched`, the summary counts written versus refused (a request still pending counts as not confirmed) with `gbrain extract --stale` and the `write-refusals.md#extract-timeline-refused` anchor, and the CLI exits 1 (the `extract` job throws). Pinned by `test/extract-timeline-db-managed.test.ts`, `test/e2e/extract-timeline-db-postgres.test.ts`, `test/fresh-init-db-extract.serial.test.ts`.
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index c1d5b13bb7..91b857cc90 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -111,6 +111,7 @@ import {
mergeSaveTimeResolutionCounts,
resolveExtractedEntitiesForSave,
} from '../core/entities/resolve-on-save.ts';
+import { CONVERSATION_ENTITY_HINTS_CAP, conversationEntityHints } from '../core/facts/conversation-entity-hints.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,
@@ -1023,6 +1024,7 @@ async function processPage(
let pageInsertedTotal = 0;
const managedRows: Array<NewFact & { row_num: number; source_markdown_slug: string }> = [];
const pageResolution = emptySaveTimeResolutionCounts();
+ const entityHints = await conversationEntityHints(state.engine, state.sourceId, page.slug, state.factVisibility); // #6731
for (const seg of segments) {
if (state.segmentLimit > 0 && segmentsThisPage >= state.segmentLimit) break;
@@ -1037,23 +1039,12 @@ async function processPage(
// per-segment extraction failure aborts the page rather than silently
// dropping facts.
let extracted: ExtractedFact[];
+ const input: ExtractInput = { turnText: text, sessionId, source: PER_SEGMENT_SOURCE_PREFIX, engine: state.engine, abortSignal: state.signal,
+ entityHints, entityHintsCap: CONVERSATION_ENTITY_HINTS_CAP };
if (state.extractor) {
- extracted = await state.extractor({
- turnText: text,
- sessionId,
- source: PER_SEGMENT_SOURCE_PREFIX,
- engine: state.engine,
- abortSignal: state.signal,
- });
+ extracted = await state.extractor(input);
} else {
- const extraction = await extractFactsFromTurnWithOutcome({
- turnText: text,
- sessionId,
- source: PER_SEGMENT_SOURCE_PREFIX,
- engine: state.engine,
- abortSignal: state.signal,
- observationDate: segmentObservationDate(page, seg.startIso),
- });
+ const extraction = await extractFactsFromTurnWithOutcome({ ...input, observationDate: segmentObservationDate(page, seg.startIso) });
if (!extraction.ok) {
// #3669 — rethrow BudgetExhausted UNWRAPPED. Wrapping it in a plain
// Error strips the BUDGET_EXHAUSTED tag, so the worker pool's D13
diff --git a/src/core/facts/conversation-entity-hints.ts b/src/core/facts/conversation-entity-hints.ts
new file mode 100644
index 0000000000..5580218236
--- /dev/null
+++ b/src/core/facts/conversation-entity-hints.ts
@@ -0,0 +1,55 @@
+/**
+ * #6731: the entities a conversation page itself names, forwarded to the
+ * fact extractor as entity hints.
+ *
+ * A meeting transcript says "Paul" and "the Maple"; the page already links
+ * `people/paul-example` (frontmatter `attendees:`) and
+ * `projects/the-maple` (a body wikilink). With those slugs in the prompt the
+ * model names the fact by slug and the save-time resolver lands it on that
+ * page instead of guessing from a first name.
+ *
+ * Only edges the page's author wrote count: the page's own frontmatter edges
+ * (attendees point at the meeting, with the meeting as origin), body markdown
+ * and wikilinks, resolved bare wikilinks and manual links. Derived edges
+ * (`mentions`, atom/concept provenance) were inferred from the same text, so
+ * they are left out. Hints stay in the page's source (the resolver resolves
+ * there) and name live fact-entity pages only. Hints are slugs, and a slug
+ * carries the entity's name, so a private entity is hinted only when the
+ * run's facts are private too.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { FactVisibility } from './visibility.ts';
+import { isFactEntityPage } from '../entities/resolve.ts';
+import { isPrivatePage } from '../search/private-visibility.ts';
+
+/** Hints a conversation page forwards: a meeting's attendees plus what it links run to a few dozen (extract_facts keeps ENTITY_HINTS_CAP). */
+export const CONVERSATION_ENTITY_HINTS_CAP = 40;
+
+const AUTHORED_LINK_SOURCES = new Set(['markdown', 'frontmatter', 'wikilink-resolved', 'manual']);
+
+export async function conversationEntityHints(engine: BrainEngine, sourceId: string, pageSlug: string,
+ factVisibility: FactVisibility): Promise<string[]> {
+ const [outgoing, incoming] = await Promise.all([
+ engine.getLinks(pageSlug, { sourceId }),
+ engine.getBacklinks(pageSlug, { sourceId }),
+ ]);
+ const ordered = new Set<string>();
+ for (const link of incoming) {
+ if (link.link_source === 'frontmatter' && link.origin_slug === pageSlug && link.from_source_id === sourceId
+ && (link.origin_source_id ?? sourceId) === sourceId) ordered.add(link.from_slug);
+ }
+ for (const link of outgoing) {
+ if (AUTHORED_LINK_SOURCES.has(link.link_source ?? '') && link.to_source_id === sourceId) ordered.add(link.to_slug);
+ }
+ ordered.delete(pageSlug);
+ if (ordered.size === 0) return [];
+ const rows = await engine.executeRaw<{ slug: string; type: string | null; frontmatter: unknown }>(
+ 'SELECT slug, type, frontmatter FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL',
+ [sourceId, [...ordered]],
+ );
+ const pages = new Map(rows.map(row => [row.slug, row]));
+ return [...ordered].filter(slug => {
+ const page = pages.get(slug);
+ return !!page && isFactEntityPage(slug, page.type) && (factVisibility === 'private' || !isPrivatePage(page));
+ }).slice(0, CONVERSATION_ENTITY_HINTS_CAP);
+}
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index ab40684134..b643929b43 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -268,6 +268,8 @@ export interface ExtractInput {
sessionId?: string | null;
/** Existing canonical entity slugs the agent already resolved (D4 hint). */
entityHints?: string[];
+ /** Hints the prompt forwards; defaults to ENTITY_HINTS_CAP (the extract_facts contract). */
+ entityHintsCap?: number;
/** Source identifier for provenance — e.g. 'mcp:put_page' or 'mcp:extract_facts'. */
source: string;
/**
@@ -649,7 +651,7 @@ export async function extractFactsFromTurnWithOutcome(
const dateLine = variant.dateGrounding ? `${observationDateLine(input.observationDate ?? null)}\n` : '';
const userContent = `${dateLine}<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${
input.entityHints && input.entityHints.length
- ? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, ENTITY_HINTS_CAP).join(', ')}.`
+ ? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, input.entityHintsCap ?? ENTITY_HINTS_CAP).join(', ')}.`
: ''
}`;
let result: ChatResult;
diff --git a/test/conversation-entity-hints.test.ts b/test/conversation-entity-hints.test.ts
new file mode 100644
index 0000000000..9b962cc5fd
--- /dev/null
+++ b/test/conversation-entity-hints.test.ts
@@ -0,0 +1,134 @@
+/**
+ * #6731: extract-conversation-facts forwards the page's own entities to the
+ * extractor as entity hints (slugs only), so a transcript's "Paul" lands on
+ * the attendee's page instead of a guess from a first name.
+ *
+ * Protects: hints come only from edges the page's author wrote (frontmatter
+ * attendees with this page as origin, body markdown/wikilinks, manual links),
+ * same source, entity pages only; derived mention edges, other meetings and
+ * the page itself are left out. A private entity's slug (slugs carry names)
+ * is never hinted when the run writes world-visible facts. Both the injected
+ * and production extractor branches get the hints, on unmanaged and managed
+ * brains, and the extract_facts op prompt keeps its 5-hint cap.
+ * Regression: a processPage that passes no hints, or that hints a private
+ * entity into world facts.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { CONVERSATION_ENTITY_HINTS_CAP, conversationEntityHints } from '../src/core/facts/conversation-entity-hints.ts';
+import { ENTITY_HINTS_CAP, extractFactsFromTurnWithOutcome, type ExtractInput } from '../src/core/facts/extract.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const MEETING = 'meetings/2026-08-12-maple-leasing';
+const BODY = [
+ '**Alice Example** (2026-08-12 10:00 AM): Paul says the Maple is 92% preleased.',
+ '**Beta Example** (2026-08-12 10:01 AM): Good, renewals open Monday.',
+].join('\n');
+const HINTED = ['people/alice-example', 'people/paul-example', 'projects/the-maple'];
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+afterEach(() => { __setChatTransportForTests(null); resetGateway(); });
+
+async function seed(db: BrainEngine): Promise<void> {
+ const page = (slug: string, type: string, title: string, body = `# ${title}`, frontmatter: Record<string, unknown> = {}) =>
+ db.putPage(slug, { type: type as never, title, compiled_truth: body, timeline: '', frontmatter });
+ await page(MEETING, 'meeting', 'Maple Leasing', BODY, { date: '2026-08-12' });
+ await page('people/alice-example', 'person', 'Alice Example');
+ await page('people/paul-example', 'person', 'Paul Example');
+ await page('people/secret-example', 'person', 'Secret Example', '# Secret Example', { visibility: 'private' });
+ await page('projects/the-maple', 'project', 'The Maple');
+ await page('companies/mentioned-co', 'company', 'Mentioned Co');
+ await page('meetings/earlier', 'meeting', 'An earlier call');
+ // sync's link extraction: attendees are frontmatter edges into the meeting, with the meeting as origin
+ for (const who of ['people/alice-example', 'people/paul-example', 'people/secret-example']) {
+ await db.addLink(who, MEETING, '', 'attended', 'frontmatter', MEETING, 'attendees');
+ }
+ await db.addLink(MEETING, 'projects/the-maple', '', 'mentions', 'markdown');
+ await db.addLink(MEETING, 'meetings/earlier', '', 'mentions', 'markdown');
+ // an auto-derived mention edge is not the page's own reference
+ await db.addLink(MEETING, 'companies/mentioned-co', '', 'mentions', 'mentions');
+}
+
+async function quietly<T>(fn: () => Promise<T>): Promise<T> {
+ const spy = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try { return await fn(); } finally { spy.mockRestore(); }
+}
+
+describe('#6731 conversation pages hint their own entities', () => {
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await seed(engine);
+ });
+
+ test('attendees first, then linked entity pages; private entities only into private facts', async () => {
+ expect(await conversationEntityHints(engine, 'default', MEETING, 'world')).toEqual(HINTED);
+ expect(await conversationEntityHints(engine, 'default', MEETING, 'private')).toEqual(
+ ['people/alice-example', 'people/paul-example', 'people/secret-example', 'projects/the-maple']);
+ });
+
+ test('the injected extractor gets the hints on every segment; world facts never carry a private slug', async () => {
+ await engine.setConfig('facts.default_visibility', 'world');
+ const inputs: ExtractInput[] = [];
+ await quietly(() => runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [MEETING], sleepMs: 0, overrideDisabled: true,
+ extractor: async (input) => { inputs.push(input); return []; } }));
+ expect(inputs.length).toBeGreaterThan(0);
+ for (const input of inputs) {
+ expect(input.entityHints).toEqual(HINTED);
+ expect(input.entityHintsCap).toBe(CONVERSATION_ENTITY_HINTS_CAP);
+ }
+ });
+
+ test('the production extractor sends the hints to the model', async () => {
+ await engine.setConfig('facts.default_visibility', 'world');
+ const seen: string[] = [];
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ seen.push(String(opts.messages.at(-1)?.content ?? ''));
+ return { text: JSON.stringify({ facts: [] }), blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ await quietly(() => runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [MEETING], sleepMs: 0, overrideDisabled: true }));
+ expect(seen.length).toBeGreaterThan(0);
+ for (const prompt of seen) expect(prompt).toContain(`Known entity slugs the user already mentioned: ${HINTED.join(', ')}.`);
+ });
+});
+
+describe('#6731 the extract_facts prompt keeps its cap', () => {
+ test('without a cap the prompt forwards ENTITY_HINTS_CAP hints; a conversation cap forwards more', async () => {
+ const seen: string[] = [];
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ seen.push(String(opts.messages.at(-1)?.content ?? ''));
+ return { text: JSON.stringify({ facts: [] }), blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ const hints = Array.from({ length: 12 }, (_, i) => `people/p-${i}`);
+ await extractFactsFromTurnWithOutcome({ turnText: 'Paul shipped it.', source: 'test', embedding: null, entityHints: hints });
+ await extractFactsFromTurnWithOutcome({ turnText: 'Paul shipped it.', source: 'test', embedding: null, entityHints: hints, entityHintsCap: CONVERSATION_ENTITY_HINTS_CAP });
+ expect(seen[0]).toContain(`Known entity slugs the user already mentioned: ${hints.slice(0, ENTITY_HINTS_CAP).join(', ')}.`);
+ expect(seen[1]).toContain(`Known entity slugs the user already mentioned: ${hints.join(', ')}.`);
+ });
+});
+
+test('#6731 managed brain: the extractor gets the page hints before the batch publishes', async () => {
+ await managedBrain(async ({ engine: db }) => {
+ await db.setConfig('facts.extraction_enabled', 'true');
+ await db.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ const inputs: ExtractInput[] = [];
+ const result = await quietly(() => runExtractConversationFactsCore(db, { sourceId: 'default', slugs: [MEETING], sleepMs: 0, overrideDisabled: true,
+ extractor: async (input) => { inputs.push(input); return []; } }));
+ expect(result).toMatchObject({ pages_processed: 1, pages_failed: 0 });
+ expect(inputs.length).toBeGreaterThan(0);
+ for (const input of inputs) expect(input.entityHints).toEqual(['people/alice-example', 'people/paul-example', 'people/secret-example', 'projects/the-maple']);
+ }, { setup: async ({ engine: db }) => { await seed(db); } });
+}, 120_000);