Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-facts): one shared eligibility rule so the backlog can drain (#5330)

garrytanab2fb313819f
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 252fb91347..8b140f1949 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).
-- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.
+- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.
- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.
diff --git a/src/commands/doctor/checks/conversation-coverage.ts b/src/commands/doctor/checks/conversation-coverage.ts
index de01941940..ef743a9d2d 100644
--- a/src/commands/doctor/checks/conversation-coverage.ts
+++ b/src/commands/doctor/checks/conversation-coverage.ts
@@ -10,7 +10,7 @@
* `gbrain conversation-parser scan <slug>`.
*/
import type { BrainEngine } from '../../../core/engine.ts';
-import { ALLOWED_TYPES } from '../../../core/facts/conversation-types.ts';
+import { ALLOWED_TYPES, isConversationFactsEligiblePage, requireParseableConversationFlag } from '../../../core/facts/conversation-types.ts';
import type { Check } from '../../doctor.ts';
export async function computeConversationFormatCoverageCheck(
@@ -25,9 +25,11 @@ export async function computeConversationFormatCoverageCheck(
// PageFilters supports singular `type` only; iterate the allowed types
// and cap at ~50/each to land at ~200 total max.
const sample: import('../../../core/types.ts').Page[] = [];
+ // #5330: sample only pages the extractor would claim.
+ const strict = await requireParseableConversationFlag(engine);
for (const t of allowedTypes) {
const slice = await engine.listPages({ limit: 50, type: t as import('../../../core/types.ts').PageType });
- sample.push(...slice);
+ sample.push(...slice.filter(page => isConversationFactsEligiblePage(page, allowedTypes, strict)));
}
if (sample.length === 0) {
return {
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 1a80494a05..a29a25f73e 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -9,7 +9,7 @@ import type { Check } from '../../doctor.ts';
import { loadConfig, type GBrainConfig } from '../../../core/config.ts';
// Leaf module (no flag surface of its own) — see that file for why this
// isn't imported from extract-conversation-facts.ts directly (#4135).
-import { ALLOWED_TYPES } from '../../../core/facts/conversation-types.ts';
+import { ALLOWED_TYPES, conversationFactsEligibleSql, pageTypesForAllowed, isConversationFactsEligiblePage, requireParseableConversationFlag } from '../../../core/facts/conversation-types.ts';
function hasNonEmptyChatFallbackChain(value: unknown): boolean {
if (Array.isArray(value)) {
@@ -560,6 +560,9 @@ export async function computeConversationFactsBacklogCheck(
}
}
+ // #5330: the extractor's eligibility rule (aliases + conversation_parseable), not type alone.
+ const concreteTypes = pageTypesForAllowed(types as Parameters<typeof pageTypesForAllowed>[0]);
+ const strict = await requireParseableConversationFlag(engine);
const rows = await engine.executeRaw<{
backlog: string | number;
completed: string | number;
@@ -583,7 +586,7 @@ export async function computeConversationFactsBacklogCheck(
AND f.source_session = f.source || ':' || p.slug || ':page-' ||
p.content_hash || '-' ||
COALESCE(TO_CHAR(p.effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD'), 'none')
- WHERE p.type = ANY($1::text[])
+ WHERE ${conversationFactsEligibleSql('p', '$1', strict)}
AND p.deleted_at IS NULL
AND COALESCE(BTRIM(p.frontmatter->>'raw_transcript'), '') = ''
AND p.content_hash IS NOT NULL
@@ -594,7 +597,7 @@ export async function computeConversationFactsBacklogCheck(
COALESCE(SUM(completed), 0) AS completed,
COALESCE(SUM(CASE WHEN completed = 0 THEN non_extractable ELSE 0 END), 0) AS non_extractable
FROM outcomes`,
- [types],
+ [concreteTypes],
);
let backlog = Number(rows[0]?.backlog ?? 0);
@@ -610,17 +613,17 @@ export async function computeConversationFactsBacklogCheck(
const verifierSources = await engine.executeRaw<{ source_id: string }>(
`SELECT DISTINCT source_id
FROM pages
- WHERE type = ANY($1::text[])
+ WHERE ${conversationFactsEligibleSql('pages', '$1', strict)}
AND deleted_at IS NULL
AND (
COALESCE(BTRIM(frontmatter->>'raw_transcript'), '') <> ''
OR content_hash IS NULL
)
ORDER BY source_id`,
- [types],
+ [concreteTypes],
);
for (const { source_id: sourceId } of verifierSources) {
- for (const type of types) {
+ for (const type of concreteTypes) {
let offset = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
@@ -632,6 +635,7 @@ export async function computeConversationFactsBacklogCheck(
});
if (batch.length === 0) break;
const verifyInProcess = batch.filter((page) => {
+ if (!isConversationFactsEligiblePage(page, concreteTypes, strict)) return false;
const raw = page.frontmatter?.raw_transcript;
return (typeof raw === 'string' && raw.trim().length > 0) ||
page.content_hash == null;
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 6c40847e5a..dd0a2ad52d 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -96,7 +96,7 @@ import { withRefreshingLock, LockUnavailableError } from '../core/db-lock.ts';
import { assertFactsEmbeddingDimMatchesConfig } from '../core/embedding-dim-check.ts';
import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';
import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';
-import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';
+import { ALLOWED_TYPES, ALLOWED_TYPE_ALIASES, isConversationFactsEligiblePage, pageTypesForAllowed, requireParseableConversationFlag, type AllowedType } from '../core/facts/conversation-types.ts';
import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';
import {
emptySaveTimeResolutionCounts,
@@ -112,6 +112,7 @@ import {
// consumer that only needs the six values doesn't also pull in this file's
// own CLI flag surface.
export { ALLOWED_TYPES };
+export { ALLOWED_TYPE_ALIASES, pageTypesForAllowed };
export type { AllowedType };
// Re-exported for existing importers (test/extract-conversation-facts.test.ts,
@@ -186,40 +187,6 @@ export const DEFAULT_MAX_COST_USD = 5.0;
// `--types` flag is an explicit per-run override; cycle config is the
// single source of truth.
-/**
- * Granular collector page-types that alias into each canonical conversation
- * bucket. The v2 type-consolidation pack retypes these to the canonical names
- * (`slack-dm-day`/`slack-thread` → `slack`, `email-digest` → `email`), but a
- * brain that hasn't run that pack still carries the collector's granular types
- * in `pages.type`. Without this expansion, `listPages({ type: 'slack' })`
- * matches zero rows on such brains and the whole comms corpus is silently
- * skipped (facts stay empty → `find_trajectory` returns nothing). The canonical
- * name is always included first so consolidated brains keep working unchanged.
- */
-export const ALLOWED_TYPE_ALIASES: Record<AllowedType, readonly string[]> = {
- conversation: ['conversation'],
- meeting: ['meeting'],
- slack: ['slack', 'slack-dm-day', 'slack-thread'],
- email: ['email', 'email-digest'],
- imessage: ['imessage'],
- 'imessage-daily': ['imessage-daily'],
-};
-
-/**
- * Expand the requested logical types to the concrete `pages.type` values to
- * enumerate, canonical-first and de-duplicated. Unknown types pass through
- * unchanged so an explicit override is never dropped.
- */
-export function pageTypesForAllowed(types: readonly AllowedType[]): string[] {
- const out: string[] = [];
- for (const t of types) {
- for (const concrete of ALLOWED_TYPE_ALIASES[t] ?? [t]) {
- if (!out.includes(concrete)) out.push(concrete);
- }
- }
- return out;
-}
-
/**
* Pagination batch size for listPages enumeration. Per-batch memory
* worst case = BATCH × MAX_PAGE_BODY_BYTES = 250MB at default 10
@@ -604,7 +571,6 @@ function pageBodyBytes(page: Page): number {
// ---------------------------------------------------------------------------
const TYPES_CONFIG_KEY = 'cycle.conversation_facts_backfill.types';
-
async function resolveTypesFromConfig(
engine: BrainEngine,
explicit?: AllowedType[],
@@ -1363,6 +1329,7 @@ export async function runExtractConversationFactsCore(
}
const types = await resolveTypesFromConfig(engine, opts.types);
+ const strictEligibility = await requireParseableConversationFlag(engine);
const dryRun = !!opts.dryRun;
const sleepMs = opts.sleepMs ?? DEFAULT_INTER_CALL_SLEEP_MS;
const segmentLimit = opts.segmentLimit ?? 0;
@@ -1495,7 +1462,7 @@ export async function runExtractConversationFactsCore(
result.pages_skipped_disappeared++;
continue;
}
- if (!concreteTypes.includes(page.type)) {
+ if (!isConversationFactsEligiblePage(page, concreteTypes, strictEligibility)) {
result.pages_skipped++;
result.pages_skipped_type_mismatch++;
continue;
@@ -1508,7 +1475,7 @@ export async function runExtractConversationFactsCore(
result.pages_skipped_disappeared++;
return;
}
- if (!concreteTypes.includes(page.type)) {
+ if (!isConversationFactsEligiblePage(page, concreteTypes, strictEligibility)) {
result.pages_skipped++;
result.pages_skipped_type_mismatch++;
return;
@@ -1538,7 +1505,8 @@ export async function runExtractConversationFactsCore(
});
if (batch.length === 0) break;
- let claimable = batch;
+ let claimable = batch.filter(page => isConversationFactsEligiblePage(page, concreteTypes, strictEligibility));
+ result.pages_skipped += batch.length - claimable.length;
// Checkpoints are an intra-page cursor; fresh durable outcomes are
// the page-level selection authority and survive checkpoint GC.
if (!opts.force && claimable.length > 0) {
diff --git a/src/core/facts/conversation-types.ts b/src/core/facts/conversation-types.ts
index 38b2fbcaf3..2254ee6908 100644
--- a/src/core/facts/conversation-types.ts
+++ b/src/core/facts/conversation-types.ts
@@ -25,6 +25,8 @@
* (`src/core/cycle/conversation-facts-backfill.ts`) imports this leaf
* directly and is part of the drift-guarded set.
*/
+import type { BrainEngine } from '../engine.ts';
+
export const ALLOWED_TYPES = Object.freeze([
'conversation',
'meeting',
@@ -35,3 +37,76 @@ export const ALLOWED_TYPES = Object.freeze([
] as const);
export type AllowedType = (typeof ALLOWED_TYPES)[number];
+
+/**
+ * Granular collector page-types that alias into each canonical conversation
+ * bucket. The v2 type-consolidation pack retypes these to the canonical names
+ * (`slack-dm-day`/`slack-thread` → `slack`, `email-digest` → `email`), but a
+ * brain that hasn't run that pack still carries the collector's granular types
+ * in `pages.type`. Without this expansion, `listPages({ type: 'slack' })`
+ * matches zero rows on such brains and the whole comms corpus is silently
+ * skipped (facts stay empty → `find_trajectory` returns nothing). The canonical
+ * name is always included first so consolidated brains keep working unchanged.
+ */
+export const ALLOWED_TYPE_ALIASES: Record<AllowedType, readonly string[]> = {
+ conversation: ['conversation'],
+ meeting: ['meeting'],
+ slack: ['slack', 'slack-dm-day', 'slack-thread'],
+ email: ['email', 'email-digest'],
+ imessage: ['imessage'],
+ 'imessage-daily': ['imessage-daily'],
+};
+
+/**
+ * Expand the requested logical types to the concrete `pages.type` values to
+ * enumerate, canonical-first and de-duplicated. Unknown types pass through
+ * unchanged so an explicit override is never dropped.
+ */
+export function pageTypesForAllowed(types: readonly AllowedType[]): string[] {
+ const out: string[] = [];
+ for (const t of types) {
+ for (const concrete of ALLOWED_TYPE_ALIASES[t] ?? [t]) {
+ if (!out.includes(concrete)) out.push(concrete);
+ }
+ }
+ return out;
+}
+
+export const REQUIRE_PARSEABLE_FLAG_CONFIG_KEY = 'cycle.conversation_facts_backfill.require_parseable_flag';
+
+const FLAG_TRUE = ['true', '1', 'yes', 'on'];
+const FLAG_FALSE = ['false', '0', 'no', 'off'];
+const flagText = (v: unknown): string => (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? String(v).trim().toLowerCase() : '');
+
+/** Strict eligibility (opt-in): only `type: conversation` or an explicit `conversation_parseable: true`. */
+export async function requireParseableConversationFlag(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ return FLAG_TRUE.includes(flagText(await engine.getConfig(REQUIRE_PARSEABLE_FLAG_CONFIG_KEY)));
+}
+
+/**
+ * #5330 — the one conversation-facts eligibility rule, shared by the
+ * extractor, the doctor backlog and the format-coverage sample. A page of an
+ * allowed type is eligible unless its frontmatter says
+ * `conversation_parseable: false` (a source-evidence page that shares a
+ * conversation type but holds no conversation). In strict mode only
+ * `type: conversation` or `conversation_parseable: true` is eligible.
+ * `concreteTypes` are `pages.type` values (the extractor's pageTypesForAllowed).
+ */
+export function isConversationFactsEligiblePage(
+ page: { type: string; frontmatter?: Record<string, unknown> | null },
+ concreteTypes: readonly string[],
+ strict = false,
+): boolean {
+ if (!concreteTypes.includes(page.type)) return false;
+ const marker = flagText(page.frontmatter?.conversation_parseable);
+ if (FLAG_FALSE.includes(marker)) return false;
+ return !strict || page.type === 'conversation' || FLAG_TRUE.includes(marker);
+}
+
+/** SQL twin of isConversationFactsEligiblePage over `alias`; `typesParam` binds the concrete types. */
+export function conversationFactsEligibleSql(alias: string, typesParam: string, strict: boolean): string {
+ const marker = `LOWER(BTRIM(COALESCE(${alias}.frontmatter->>'conversation_parseable', '')))`;
+ const list = (values: string[]) => values.map(v => `'${v}'`).join(', ');
+ return `${alias}.type = ANY(${typesParam}::text[]) AND ${marker} NOT IN (${list(FLAG_FALSE)})` +
+ (strict ? ` AND (${alias}.type = 'conversation' OR ${marker} IN (${list(FLAG_TRUE)}))` : '');
+}
diff --git a/test/conversation-facts-eligibility.test.ts b/test/conversation-facts-eligibility.test.ts
new file mode 100644
index 0000000000..981693e03a
--- /dev/null
+++ b/test/conversation-facts-eligibility.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #5330: conversation-facts eligibility is one shared rule. A source-evidence
+ * page that shares a conversation type but holds no conversation is marked
+ * `conversation_parseable: false`; the extractor skips it and the doctor
+ * backlog stops counting it, so the backlog can drain. Strict mode
+ * (`cycle.conversation_facts_backfill.require_parseable_flag`) admits only
+ * `type: conversation` or an explicit `conversation_parseable: true`.
+ */
+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 { computeConversationFactsBacklogCheck } from '../src/commands/doctor.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import {
+ REQUIRE_PARSEABLE_FLAG_CONFIG_KEY,
+ conversationFactsEligibleSql,
+ isConversationFactsEligiblePage,
+ pageTypesForAllowed,
+} from '../src/core/facts/conversation-types.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+});
+
+const TRANSCRIPT = '**Alice** (2024-03-15 9:00 AM): hello\n**Bob** (2024-03-15 9:01 AM): hi';
+
+async function seed(slug: string, type: string, frontmatter: Record<string, unknown>, body = TRANSCRIPT): Promise<void> {
+ await engine.putPage(slug, { type, title: slug, compiled_truth: body, timeline: '', frontmatter });
+}
+
+describe('isConversationFactsEligiblePage', () => {
+ const types = pageTypesForAllowed(['conversation', 'email']);
+ test('allowed type, unless marked not parseable', () => {
+ expect(isConversationFactsEligiblePage({ type: 'email', frontmatter: {} }, types)).toBe(true);
+ expect(isConversationFactsEligiblePage({ type: 'email-digest', frontmatter: {} }, types)).toBe(true);
+ expect(isConversationFactsEligiblePage({ type: 'note', frontmatter: {} }, types)).toBe(false);
+ for (const marker of [false, 'false', 'no', 0, 'OFF']) {
+ expect(isConversationFactsEligiblePage({ type: 'email', frontmatter: { conversation_parseable: marker } }, types)).toBe(false);
+ }
+ });
+ test('strict mode admits conversation pages and explicit markers only', () => {
+ expect(isConversationFactsEligiblePage({ type: 'email', frontmatter: {} }, types, true)).toBe(false);
+ expect(isConversationFactsEligiblePage({ type: 'email', frontmatter: { conversation_parseable: true } }, types, true)).toBe(true);
+ expect(isConversationFactsEligiblePage({ type: 'conversation', frontmatter: {} }, types, true)).toBe(true);
+ expect(isConversationFactsEligiblePage({ type: 'conversation', frontmatter: { conversation_parseable: 'false' } }, types, true)).toBe(false);
+ });
+ test('the SQL twin selects exactly the pages the predicate admits', async () => {
+ const pages: Array<[string, string, Record<string, unknown>]> = [
+ ['email/a', 'email', {}],
+ ['email/b', 'email', { conversation_parseable: false }],
+ ['email/c', 'email', { conversation_parseable: 'true' }],
+ ['email/d', 'email-digest', { conversation_parseable: 'no' }],
+ ['conversations/e', 'conversation', {}],
+ ['notes/f', 'note', {}],
+ ];
+ for (const [slug, type, fm] of pages) await seed(slug, type, fm);
+ for (const strict of [false, true]) {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages p WHERE ${conversationFactsEligibleSql('p', '$1', strict)} ORDER BY slug`, [types]);
+ const expected = pages.filter(([, type, fm]) => isConversationFactsEligiblePage({ type, frontmatter: fm }, types, strict)).map(([slug]) => slug).sort();
+ expect(rows.map(r => r.slug)).toEqual(expected);
+ }
+ });
+});
+
+describe('#5330 the backlog drains', () => {
+ test('a source-evidence page marked not parseable is neither claimed nor counted', async () => {
+ await seed('email/threads/parseable', 'email', {});
+ await seed('email/messages/source-evidence', 'email', { conversation_parseable: false }, '# Message record\n\nnot a transcript');
+
+ expect((await computeConversationFactsBacklogCheck(engine)).details?.backlog).toBe(1);
+
+ const claimed: string[] = [];
+ const result = await runExtractConversationFactsCore(engine, {
+ sourceId: 'default', types: ['email'], sleepMs: 0,
+ extractor: async input => { claimed.push(input.turnText); return []; },
+ });
+ expect(result.pages_skipped).toBeGreaterThanOrEqual(1);
+ expect(claimed.every(t => !t.includes('Message record'))).toBe(true);
+ expect((await computeConversationFactsBacklogCheck(engine)).details?.backlog).toBe(0);
+
+ const single = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'email/messages/source-evidence', sleepMs: 0 });
+ expect(single.pages_skipped_type_mismatch).toBe(1);
+ expect(single.pages_processed).toBe(0);
+ });
+
+ test('strict mode leaves unmarked shared-type pages out of the backlog', async () => {
+ await seed('email/unmarked', 'email', {});
+ await seed('email/marked', 'email', { conversation_parseable: true });
+ await seed('conversations/plain', 'conversation', {});
+ await engine.setConfig(REQUIRE_PARSEABLE_FLAG_CONFIG_KEY, 'true');
+ expect((await computeConversationFactsBacklogCheck(engine)).details?.backlog).toBe(2);
+ });
+
+ test('granular collector types count, as the extractor enumerates them', async () => {
+ await seed('email/digest', 'email-digest', {});
+ expect((await computeConversationFactsBacklogCheck(engine)).details?.backlog).toBe(1);
+ });
+});