Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(conversation-facts): email threads parse; meeting metadata is never a speaker; prose meetings leave the backlog (#5025, D-N2)
time-attack47a15684b7c8
diff --git a/docs/architecture/conversation-parser-patterns.md b/docs/architecture/conversation-parser-patterns.mdindex 23b06093b1..a1cb5491e6 100644--- a/docs/architecture/conversation-parser-patterns.md+++ b/docs/architecture/conversation-parser-patterns.md@@ -96,7 +96,8 @@ inside an otherwise unrelated long document. Also setfully-matching anchor line to land at or before that index in the scoredlines. A short title or heading before the transcript starts still qualifies;an anchor group appearing well past the bound falls back to the ordinary-flat-density score instead.+flat-density score instead. A pattern that sets the bound also accepts a single+anchor inside it, so a one-message email thread under its title line parses.Use `score_full_body: true` for a broad grammar that also occurs in ordinaryprose. For example, `**Label:** text` can be either a transcript line or a bold@@ -137,12 +138,36 @@ formats:- `**Speaker** (09:15): text` uses `bold-paren-time`.- `**Speaker** (9:15 AM): text` uses `bold-paren-time-12h`.-- `**Speaker:** text` uses `bold-name-no-time`. Its `repeat_speaker_min_turns: 3` structure gate returns no_match when three or more turns never repeat a speaker — a status note's `**Status:**`/`**Owner:**`/`**Next step:**` labels are not a conversation (gbrain-evals N12-1).+- `**Speaker:** text` uses `bold-name-no-time`. Its `repeat_speaker_min_turns: 3` structure gate returns no_match when three or more turns never repeat a speaker — a status note's `**Status:**`/`**Owner:**`/`**Next step:**` labels are not a conversation (gbrain-evals N12-1). A bold label that is exactly a meeting-note metadata label (`METADATA_LABELS` in `builtins.ts`: Attendees, Date, Location, Summary, Agenda, Action items and similar, case-insensitive) is never a speaker, so `**Attendees:**` / `**Date:**` header lines on meeting notes are not turns.- `**Speaker** (2026-04-09 9:15 AM): text` uses `imessage-slack`.Keeping these examples in both `test_negative` and parser regression tests makesthe non-shadowing contract executable.+## Email threads++`email-thread-heading` reads gbrain's Gmail thread page+(`src/core/google/google-render.ts`): one `## <From> · YYYY-MM-DD HH:MM` heading+per message, `## → <From> · …` for a sent message, the message body below it.+The speaker is the From display name (the `<address>` and quotes are dropped;+a bare address stays as is) and the heading time is UTC. Because each anchor+carries its own date, other headings in an email body are message text, not+folded speakers. extract-conversation-facts treats a thread as one+conversation: unless the page sets `conversation_segment_gap_minutes`, the+segment gap is the 7-day maximum instead of 30 minutes.++## Meeting notes and undated pages++A meeting or email page that yields no speaker turns and has the shape of+meeting notes or a calendar event (`looksLikeMeetingNotes`: a bold metadata+label line, or an Attendees / Participants / Agenda / Action items section) is+recorded as scanned, not extractable, when no LLM fallback is configured; it+leaves the backlog until the page changes. Other speaker-less pages stay+retryable. A time-only parse on a page with no date would place every turn on+1970-01-01; extract-conversation-facts records it as not extractable instead+(adding a `date:` reopens it). The parser itself still reports those+timestamps.+## Single-quoted speaker objectsThe `python-dict-utterance` pattern recognizes this narrow export shape withoutdiff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 1cefb0359e..bb96e08b89 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 time-windowed segments (30-min gap or 30-msg cap; 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=25MB`); **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}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--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) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. 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. 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. 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 time-windowed segments (30-min gap or 30-msg cap; 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=25MB`); **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) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. 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. 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 meeting notes, 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); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. 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, and every other file looked deleted and was skipped in silence; 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 directory-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: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `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.- `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/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex bdbc617b5b..fe8a0717e1 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -16,7 +16,7 @@ src/commands/dream-retriage.ts runDreamRetriage 524 seed: W5 baseline, refactorsrc/commands/embed.ts embedAllStale 566 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning; +2 Foundations 1 F4d: a time-budget stop with stale chunks left records reason, remaining count and resume command (src/core/embed-budget-stop.ts)src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 wave 8 lane D1 #5885: stale-drain takes pass call and its watchdog progress countersrc/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/extract-conversation-facts.ts processPage 308 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes)+src/commands/extract-conversation-facts.ts processPage 319 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes); +11 fix wave 9 lane P (#5025, D-N2): terminal not-extractable skip call (decision in facts/conversation-skip.ts) and the email-thread segment gapsrc/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts)src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 727900d5bb..859e62cb93 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -379,6 +379,7 @@ import {type ParseConversationOpts as OrchestratorParseOpts,} from '../core/conversation-parser/parse.ts';import { readConversationBodyForParsing } from '../core/conversation-parser/body.ts';+import { terminalConversationSkip } from '../core/facts/conversation-skip.ts';import { runLlmFallback } from '../core/conversation-parser/llm-fallback.ts';import { resolveModel, resolveTierDefault } from '../core/model-config.ts';import { FAILED_EXIT_CODE } from '../core/exit-codes.ts';@@ -1022,19 +1023,30 @@ async function processPage();}}- const gapMinutes = pageSegmentGapMinutes(page);+ // #5025 / N2: undated time-only turns, or a prose meeting/email page, end+ // in a terminal not-extractable outcome instead of epoch-dated facts or a+ // rescan every run.+ const terminalSkip = terminalConversationSkip(page, body, parseResult.phase, messages, Boolean(state.llmFallbackModel));+ if (terminalSkip) {+ process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: ${terminalSkip.message}\n`);+ messages = [];+ }+ // An email thread is one conversation even when replies are hours apart;+ // a frontmatter conversation_segment_gap_minutes still wins.+ const gapMinutes = pageSegmentGapMinutes(page) ??+ (parseResult.matched_pattern_id === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);const allSegments = splitIntoSegments(messages, { gapMinutes });const segments = splitIntoSegments(messages, { gapMinutes, sinceIso });if (segments.length === 0) {state.result.pages_skipped++;- if (!declinedUnrecognizedSpeaker) {+ if (!declinedUnrecognizedSpeaker && !terminalSkip) {if (messages.length === 0) state.result.pages_skipped_unparsed++;else if (allSegments.length === 0) state.result.pages_skipped_insufficient_turns++;else state.result.pages_skipped_since++;}if (!state.dryRun &&- parseResult.phase !== 'no_match' &&+ (parseResult.phase !== 'no_match' || terminalSkip !== null) &&allSegments.length === 0 &&// #4136 — a decline must stay NON-TERMINAL. The audit row is keyed by// a content versionToken and skips the page on every future run; a@@ -1043,9 +1055,9 @@ async function processPage(// orphan cleanup below until the page re-extracts.)!declinedUnrecognizedSpeaker) {- const reason = messages.length === 0+ const reason = terminalSkip?.reason ?? (messages.length === 0? 'no conversation messages found'- : 'fewer than two eligible messages';+ : 'fewer than two eligible messages');if (await snapshotIsCurrent(state.engine, state.sourceId, snapshot)) {if (state.managed) {await replacePageFacts(state, snapshot, async tx => [diff --git a/src/core/conversation-parser/builtins.ts b/src/core/conversation-parser/builtins.tsindex 32862b390f..a213bce973 100644--- a/src/core/conversation-parser/builtins.ts+++ b/src/core/conversation-parser/builtins.ts@@ -69,6 +69,36 @@ const speakerObjectRegex = new RegExp('u',);+/**+ * Bold labels that open meeting-note metadata lines (`**Date:** …`), never a+ * speaker turn. bold-name-no-time rejects a label that is exactly one of+ * these (case-insensitive).+ */+export const METADATA_LABELS: readonly string[] = [+ 'attendees?', 'participants?', 'present', 'absent', 'invitees?', 'guests?',+ 'date', 'time', 'when', 'where', 'location', 'venue', 'duration',+ 'summary', 'agenda', 'notes?', 'subject', 'title', 'topics?', 'purpose',+ 'organi[sz]er', 'host', 'facilitator', 'recording', 'transcript', 'meeting',+ 'action items?', 'next steps?', 'decisions?', 'key points?', 'takeaways?', 'outcomes?',+ 'status', 'owner', 'tags?', 'links?', 'source', 'type', 'context', 'background',+];++const METADATA_LINE = new RegExp(`^\\*\\*(?:${METADATA_LABELS.join('|')})\\s*:\\*\\*`, 'i');+const METADATA_SECTION = /^#{1,3}\s+(?:attendees|participants|agenda|action items)\s*$/i;++/**+ * #5025: whether a page that produced no speaker turns has the shape of+ * meeting notes or a calendar event (a bold metadata label line such as+ * `**Attendees:**`, or an Attendees / Participants / Agenda / Action items+ * section) rather than a transcript in a format the parser does not know.+ */+export function looksLikeMeetingNotes(body: string): boolean {+ return body.split(/\r?\n/).some((line) => {+ const t = line.trim();+ return METADATA_LINE.test(t) || METADATA_SECTION.test(t);+ });+}+export const BUILTIN_PATTERNS: readonly PatternEntry[] = [// -------------------------------------------------------------------// INLINE-DATE patterns (date in every line; less ambiguous; tried first).@@ -473,6 +503,12 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [// shape so that disabling telegram-bracket yields an honest// no_match instead of capturing speaker="[18:37] Name" at midnight.//+ // METADATA LABELS (#5025 / N2): meeting notes open with+ // `**Attendees:** …` / `**Date:** …` header lines. Those labels are+ // never speakers, so the second lookahead rejects a bold label that is+ // exactly one of METADATA_LABELS; a prose meeting page then has no+ // anchor at all instead of two "turns" by Attendees and Date.+ //// BROAD-REGEX GUARD (score_full_body): `**Label:** text` is a// common prose idiom (`**Note:**`, `**Owner:**`). A notes page// with a few bold labels clustered in its first 10 lines would@@ -483,7 +519,7 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [origin: 'builtin',// Matches: **Speaker Name:** message text (colon INSIDE bold,// speaker must not start with `[` — see lookahead rationale above).- regex: /^\*\*(?!\[)(.+?):\*\*\s*(.*)$/,+ regex: new RegExp(`^\\*\\*(?!\\[)(?!(?:${METADATA_LABELS.join('|')})\\s*:\\*\\*)(.+?):\\*\\*\\s*(.*)$`, 'i'),captures: {speaker_group: 1,text_group: 2,@@ -515,6 +551,10 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [// — the `(?!\[)` lookahead rejects it so disabling// telegram-bracket yields no_match, not speaker="[18:37] Alice":'**[18:37] \u{1f464} Alice:** hello',+ // Meeting-note metadata labels are never speakers (#5025 / N2):+ '**Attendees:** Alice Example, Bob Example',+ '**Date:** 2026-09-07',+ '**Action items:** ship the draft',],source_doc:'Circleback / Granola / Zoom meeting-transcript export shape: `**Speaker:** text` with no per-line timestamp',@@ -854,6 +894,46 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [source_doc:'gbrain nightly transcript ingest: compiled_truth bodies use markdown headings per turn',},+ {+ // gbrain's Gmail thread page (src/core/google/google-render.ts): one+ // `## <From> · YYYY-MM-DD HH:MM` heading per message (`## → <From> · …`+ // for a sent message), the body below it. The time is UTC (the+ // renderer slices an ISO instant). The speaker is the From display+ // name; speaker_clean drops the `<address>` and surrounding quotes.+ // The ` · date time` suffix keeps ordinary `## Section` headings out,+ // and the 2-line preamble allowance lets a one-message thread (title+ // line, then the only heading) score as a conversation.+ id: 'email-thread-heading',+ origin: 'builtin',+ regex: /^##\s+(?:→\s+)?(\S.*?)\s+·\s+(\d{4}-\d{2}-\d{2})\s+(\d{1,2}):(\d{2})\s*()$/u,+ captures: {+ speaker_group: 1,+ date_group: 2,+ hour_group: 3,+ minute_group: 4,+ text_group: 5,+ },+ date_source: 'inline',+ time_format: '24h',+ timezone_policy: 'inline_utc',+ multi_line: true,+ score_continuations_as_body: true,+ score_continuations_max_preamble_lines: 2,+ quick_reject: /^##\s.*\s·\s\d{4}-\d{2}-\d{2}\s/u,+ speaker_clean: /^[^\p{L}\p{N}]+|["']?\s*<[^>]*>\s*$|["']$/gu,+ test_positive: [+ '## Alice Example <[email protected]> · 2026-09-07 12:21',+ '## → Bob Example <[email protected]> · 2026-09-07 14:05',+ '## [email protected] · 2026-09-08 09:10',+ ],+ test_negative: [+ '## Summary',+ '## Alice Example · yesterday',+ '# Alice Example <[email protected]> · 2026-09-07 12:21',+ '## Alice Example <[email protected]> · 2026-09-07 12:21 extra words',+ ],+ source_doc: 'gbrain Gmail thread render (src/core/google/google-render.ts renderThreadPage)',+ },{id: 'python-dict-utterance',origin: 'builtin',diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.tsindex eaaf66f743..0ae99f22c7 100644--- a/src/core/conversation-parser/parse.ts+++ b/src/core/conversation-parser/parse.ts@@ -346,10 +346,14 @@ export function applyPattern(// is diagnostic-only (zero behavior change here): collect the folded// labels so ParseResult can surface them. Fence-aware so a transcript// whose answers paste markdown/shell inside code fences is not flagged.+ // A heading anchor that carries its own inline date (email-thread-heading)+ // cannot be mistaken for a section title, so its other headings are body+ // text, not lost speakers.const headingAnchored =diag !== undefined &&entry.multi_line === true &&entry.score_continuations_as_body === true &&+ entry.captures.date_group === undefined &&(entry.test_positive ?? []).some((s) => /^#{2,3}\s/.test(s));let fenceMarker: '```' | '~~~' | null = null;const collectFoldedHeading = (line: string): void => {@@ -604,7 +608,8 @@ function scoreFromLines(entry.multi_line &&entry.quick_reject &&anchorCandidates > 0 &&- (anchored >= 2 || firstLineAnchored) &&+ (anchored >= 2 || firstLineAnchored ||+ (entry.score_continuations_max_preamble_lines !== undefined && anchored === 1)) &&distinctSpeakersOk &&preambleOk) {@@ -619,8 +624,9 @@ function scoreFromLines(** Quick_reject is honored. Patterns that opt into* `score_continuations_as_body` may exclude continuation lines from the- * denominator only after the scorer sees two anchors, or an anchor on the- * first non-blank line. Otherwise the ordinary full-body density applies.+ * denominator only after the scorer sees two anchors, an anchor on the+ * first non-blank line, or (with a preamble bound) one anchor inside the+ * preamble. Otherwise the ordinary full-body density applies.** Exported for tests.*/diff --git a/src/core/conversation-parser/types.ts b/src/core/conversation-parser/types.tsindex 113a47bbe9..267261861f 100644--- a/src/core/conversation-parser/types.ts+++ b/src/core/conversation-parser/types.ts@@ -214,6 +214,8 @@ export interface PatternEntry {* (like a bare `**You:**` heading) that are plausible prose labels on* their own: distinct-speaker count alone still lets a single* illustrative example pair anywhere in a long document through.+ * A pattern that sets it also accepts a single anchor inside the+ * preamble (a one-message email thread under its title line).*/score_continuations_max_preamble_lines?: number;/**diff --git a/src/core/facts/conversation-skip.ts b/src/core/facts/conversation-skip.tsnew file mode 100644index 0000000000..f2accd611c--- /dev/null+++ b/src/core/facts/conversation-skip.ts@@ -0,0 +1,46 @@+/**+ * Terminal "not extractable" outcomes for conversation-facts extraction+ * (#5025 / N2), decided after parsing and before segmentation. A terminal+ * outcome is recorded against the page's content version, so the page+ * leaves the backlog until it changes.+ *+ * - Undated: a time-only parse on a page with no date anchors every turn+ * on 1970-01-01, so its facts would be dated at the epoch.+ * - Prose: a meeting or email page with no speaker turns and the shape of+ * meeting notes or a calendar event, when no LLM fallback is configured.+ * Other speaker-less pages stay retryable (a later parser may learn+ * their format).+ */+import { looksLikeMeetingNotes } from '../conversation-parser/builtins.ts';+import { deriveDateContext } from '../conversation-parser/parse.ts';+import type { ParsePhase } from '../conversation-parser/types.ts';+import type { Page } from '../types.ts';+import { ALLOWED_TYPE_ALIASES } from './conversation-types.ts';++const PROSE_PAGE_TYPES = new Set([...ALLOWED_TYPE_ALIASES.meeting, ...ALLOWED_TYPE_ALIASES.email]);++export interface TerminalConversationSkip {+ /** Recorded on the not-extractable audit row. */+ reason: string;+ /** The operator-facing line: what happened and what reopens the page. */+ message: string;+}++export function terminalConversationSkip(+ page: Page,+ body: string,+ phase: ParsePhase,+ messages: ReadonlyArray<{ timestamp: string }>,+ llmFallback: boolean,+): TerminalConversationSkip | null {+ if (messages.length > 0) {+ if (deriveDateContext({ page }).source !== 'epoch_default' || !messages.some((m) => m.timestamp.startsWith('1970-01-01T'))) return null;+ return {+ reason: 'no page date to place message times',+ message: 'no page date to place message times (they would read 1970-01-01); add a date: to the page frontmatter to extract it',+ };+ }+ if (phase !== 'no_match' || llmFallback || !PROSE_PAGE_TYPES.has(page.type) || !looksLikeMeetingNotes(body)) return null;+ const reason = `no speaker turns in this ${page.type} page (prose, not a transcript)`;+ return { reason, message: `${reason}; not extractable until the page changes` };+}diff --git a/test/conversation-facts-email-meeting.test.ts b/test/conversation-facts-email-meeting.test.tsnew file mode 100644index 0000000000..7b70429040--- /dev/null+++ b/test/conversation-facts-email-meeting.test.ts@@ -0,0 +1,151 @@+/**+ * #5025 + N2: conversation facts on email and meeting pages.+ *+ * Protects: a Gmail thread page as gbrain renders it parses into one turn+ * per message (sender display name, heading time), including a one-message+ * thread, and its facts extract; meeting-note metadata labels+ * (`**Attendees:**`, `**Date:**`) are never speakers; a prose meeting page is+ * marked not extractable once and then leaves the backlog instead of being+ * rescanned every run; a time-only parse on a page with no date never yields+ * facts dated 1970-01-01.+ * Fails when: email pages parse to zero turns and stay "retryable" forever,+ * or a prose meeting page parses into turns by "Attendees" and "Date" at the+ * epoch (the pre-fix behavior).+ * Seams: real PGLite; the extractor is injected (no model calls).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { parseConversation } from '../src/core/conversation-parser/parse.ts';+import { looksLikeMeetingNotes } from '../src/core/conversation-parser/builtins.ts';+import { renderThreadPage } from '../src/core/google/google-render.ts';+import type { GmailMessageMeta } from '../src/core/google/types.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runExtractConversationFactsCore, NON_EXTRACTABLE_AUDIT_SOURCE } from '../src/commands/extract-conversation-facts.ts';+import { computeConversationFactsBacklogCheck } from '../src/commands/doctor/checks/search-eval.ts';++function message(over: Partial<GmailMessageMeta>): GmailMessageMeta {+ const dateIso = over.dateIso ?? '2026-09-07T12:21:00.000Z';+ return {+ id: '18c2f4a9b3d21e01', threadId: '18c2f4a9b3d21e00', from: 'Alice Example <[email protected]>',+ fromAddress: '[email protected]', to: ['[email protected]'], cc: [], subject: 'Planning call',+ dateIso, internalDateMs: Date.parse(dateIso), labelIds: [], listUnsubscribe: false,+ bodyText: 'Can we move the planning call to Thursday?', ...over,+ };+}++const twoMessageThread = () => renderThreadPage({+ threadId: '18c2f4a9b3d21e00', account: '[email protected]', messages: [+ message({}),+ message({+ id: '18c2f4a9b3d21e02', from: '"Bob Example" <[email protected]>', fromAddress: '[email protected]',+ to: ['[email protected]'], subject: 'Re: Planning call', dateIso: '2026-09-07T14:05:00.000Z',+ labelIds: ['SENT'], bodyText: 'Thursday works. I will send an invite.',+ }),+ ],+})!.markdown;++const PROSE_MEETING = `---+type: meeting+title: Weekly sync+date: 2026-09-07+---+# Weekly sync++**Attendees:** Alice Example, Bob Example+**Date:** 2026-09-07++## Summary++The team agreed to ship the widget on Friday. Bob owns the launch checklist.+`;++describe('parser', () => {+ test('a Gmail thread page parses one turn per message with the sender name and heading time', () => {+ const body = twoMessageThread().split('\n---\n').slice(1).join('\n---\n');+ const r = parseConversation(body, {});+ expect(r.matched_pattern_id).toBe('email-thread-heading');+ expect(r.messages.map((m) => [m.speaker, m.timestamp])).toEqual([+ ['Alice Example', '2026-09-07T12:21:00Z'],+ ['Bob Example', '2026-09-07T14:05:00Z'],+ ]);+ expect(r.messages[1]!.text).toContain('Thursday works.');+ expect(r.unrecognized_headings).toBeUndefined();+ });++ test('a one-message thread under its title still parses', () => {+ const body = `# Planning call\n\n## Alice Example <[email protected]> · 2026-09-07 12:21\n\n${'Line of a long message.\n'.repeat(40)}`;+ const r = parseConversation(body, {});+ expect(r.matched_pattern_id).toBe('email-thread-heading');+ expect(r.messages.map((m) => m.speaker)).toEqual(['Alice Example']);+ });++ test('meeting-note metadata labels are never speakers', () => {+ expect(parseConversation(PROSE_MEETING, { fallbackDate: '2026-09-07' }).phase).toBe('no_match');+ const withTurns = [+ '**Attendees:** Alice Example, Bob Example', '**Date:** 2026-09-07',+ '**Alice Example:** Shall we ship Friday?', '**Bob Example:** Yes, I own the checklist.', '**Alice Example:** Great.',+ ].join('\n');+ const r = parseConversation(withTurns, { fallbackDate: '2026-09-07' });+ expect(r.messages.map((m) => m.speaker)).toEqual(['Alice Example', 'Bob Example', 'Alice Example']);+ });++ test('looksLikeMeetingNotes recognizes metadata labels and attendee sections only', () => {+ expect(looksLikeMeetingNotes(PROSE_MEETING)).toBe(true);+ expect(looksLikeMeetingNotes('# Event\n\n## Attendees\n\n- [email protected]')).toBe(true);+ expect(looksLikeMeetingNotes('## Summary\n\nAn unsupported transcript without speaker anchors.')).toBe(false);+ });+});++describe('extractor', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ afterAll(async () => {+ await engine.disconnect();+ });+ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ const extractor = async (input: { turnText: string }) => [+ { fact: 'The planning call moved to Thursday', kind: 'event' as const, confidence: 1, entity_slug: null, source: 'test', context: input.turnText },+ ];++ test('an email thread page extracts facts from its messages', async () => {+ await importFromContent(engine, 'email/planning-call', twoMessageThread(), { noEmbed: true });+ const r = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'email/planning-call', extractor, sleepMs: 0 });+ expect(r).toMatchObject({ pages_processed: 1, pages_skipped_unparsed: 0, segments_processed: 1, facts_inserted: 1 });+ });++ test('a prose meeting page is marked not extractable once, then skipped', async () => {+ await importFromContent(engine, 'meetings/weekly-sync', PROSE_MEETING, { noEmbed: true });+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');+ const backlog = async () => (await computeConversationFactsBacklogCheck(engine)).details?.backlog;+ expect(await backlog()).toBe(1);+ let calls = 0;+ const counting = async (input: { turnText: string }) => { calls++; return extractor(input); };+ const first = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'meetings/weekly-sync', extractor: counting, sleepMs: 0 });+ expect(first).toMatchObject({ pages_skipped: 1, pages_skipped_unparsed: 0, pages_skipped_insufficient_turns: 0, pages_marked_non_extractable: 1, facts_inserted: 0 });+ const [audit] = await engine.executeRaw<{ fact: string }>('SELECT context AS fact FROM facts WHERE source = $1', [NON_EXTRACTABLE_AUDIT_SOURCE]);+ expect(audit!.fact).toContain('no speaker turns in this meeting page');+ const second = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'meetings/weekly-sync', extractor: counting, sleepMs: 0 });+ expect(second).toMatchObject({ pages_skipped_non_extractable: 1, pages_marked_non_extractable: 0 });+ expect(calls).toBe(0);+ expect(await backlog()).toBe(0);+ });++ test('a time-only parse on a page with no date yields no epoch-dated facts', async () => {+ await engine.putPage('conversations/undated', {+ type: 'conversation', title: 'Undated chat', timeline: '', frontmatter: {},+ compiled_truth: ['**Alice Example:** Shall we ship Friday?', '**Bob Example:** Yes.', '**Alice Example:** Great.', '**Bob Example:** Done.'].join('\n'),+ });+ const r = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'conversations/undated', extractor, sleepMs: 0 });+ expect(r).toMatchObject({ facts_inserted: 0, pages_marked_non_extractable: 1, pages_skipped_unparsed: 0 });+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE valid_from < '1971-01-01'`);+ expect(Number(rows[0]!.n)).toBe(0);+ });+});