Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): typed conversation_pipeline skip and doctor opt-in note (#6557)

time-attack93b1f1f3f4e2
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index f54d56dcb9..6c764bc98d 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -8,7 +8,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/facts/conversation-windows.ts` — conversation windowing for `extract-conversation-facts` (#6267, wave 15 P2.5): `splitIntoSegments(messages, { gapMinutes, maxMessages, sinceIso, maxChars, pageTitle })` cuts gap groups, keeps only groups with `MIN_SEGMENT_MESSAGES` (2) original messages, then packs each eligible group into windows bounded by `DEFAULT_SEGMENT_MAX_MESSAGES` (30) and `SEGMENT_TEXT_CHAR_LIMIT` (6,500 rendered chars, header included). Every eligible turn lands in exactly one window; a turn whose own line overflows is split by `splitTurnText` at sentence, then whitespace, then code-point boundaries (never inside a surrogate pair; `pieces.join('')` is the original) with the `speaker (timestamp): ` prefix on every piece; an original singleton stays ineligible; a header that leaves fewer than 32 chars of room throws before any window exists. `renderSegmentForExtraction(pageTitle, segment)` renders the unchanged prompt shape and throws on an over-budget hand-built segment instead of clipping it. Owns the tunables the command re-exports (`DEFAULT_SEGMENT_GAP_MINUTES`, `MAX_PAGE_SEGMENT_GAP_MINUTES`). Pinned by `test/conversation-windows-6267.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`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`. Since #6267 it also owns the `ConversationMessage`, `ConversationSegment` and `SplitSegmentsOpts` types the windowing module and the command share.
-- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).
+- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix (conversation-pipeline types, `CONVERSATION_PIPELINE_TYPES`, skip as `conversation_pipeline`, #6557: the opt-in conversation facts backfill owns them; doctor `facts_extraction_health` names the opt-in and its caps when such pages exist and the backfill is off). Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).
- `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). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. 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. The typed-claim examples keep a bare `$` as USD (series compare by `(metric, unit, period)`, so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by `test/facts-extract-currency-examples-6274.test.ts`. Pinned by `test/facts-extract-structured-output.test.ts`.
diff --git a/src/commands/doctor/checks/knowledge-health.ts b/src/commands/doctor/checks/knowledge-health.ts
index c954f79126..69a706ee29 100644
--- a/src/commands/doctor/checks/knowledge-health.ts
+++ b/src/commands/doctor/checks/knowledge-health.ts
@@ -12,7 +12,7 @@ import { computeEffectiveDate } from '../../../core/effective-date.ts';
import { zeroTotalContradictionsCheck } from '../../../core/eval-contradictions/run-health.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { checkError, doctorVerify } from '../check-fix.ts';
+import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
async function runEvalCapture(ctx: DoctorContext): Promise<Check[]> {
const { progress } = ctx;
@@ -275,6 +275,13 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
: `Facts:absorb activity in last 24h (under threshold ${threshold}): ${summary}.`,
});
}
+ const note = await conversationPipelineNote(engine);
+ const check = checks[checks.length - 1];
+ if (note && check) {
+ check.message = `${check.message} ${note.message}`;
+ check.details = { ...(check.details ?? {}), conversation_pipeline: note.details };
+ if (!check.fix) check.fix = note.fix;
+ }
} catch (err) {
const code = (err as { code?: string } | null)?.code;
if (code === '42P01' || code === '42703') {
@@ -298,6 +305,39 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
return checks;
}
+/**
+ * #6557: conversation-shaped pages skip the page-write backstop
+ * (`conversation_pipeline`); their facts come from the opt-in conversation
+ * facts backfill. When such pages exist and the backfill is off, name the
+ * opt-in and its spend caps; enabling it is the user's call.
+ */
+async function conversationPipelineNote(engine: ReturnType<typeof connectedEngine>) {
+ const { CONVERSATION_PIPELINE_TYPES, CONVERSATION_PIPELINE_ENABLE_KEY, BACKSTOP_RESCUE_SLUG_PREFIXES } =
+ await import('../../../core/facts/eligibility.ts');
+ const { loadCfg } = await import('../../../core/cycle/conversation-facts-backfill.ts');
+ const cfg = await loadCfg(engine);
+ if (cfg.enabled) return null;
+ const [row] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages
+ WHERE deleted_at IS NULL AND type = ANY($1::text[]) AND NOT (slug LIKE ANY($2::text[]))`,
+ [CONVERSATION_PIPELINE_TYPES, BACKSTOP_RESCUE_SLUG_PREFIXES.map(p => `${p}%`)]);
+ const pages = Number(row?.n ?? 0);
+ if (pages === 0) return null;
+ const caps = `$${cfg.maxCostUsd.toFixed(2)} per source and $${cfg.maxTotalCostUsd.toFixed(2)} per cycle, ` +
+ `${cfg.maxWalltimeMin} min per source and ${cfg.maxTotalWalltimeMin} min per cycle`;
+ return {
+ message: `${pages} conversation page(s) are not read by the page-write facts backstop (conversation_pipeline); ` +
+ `their facts come from the conversation facts backfill, which is off. Enabling it makes paid model calls, capped at ${caps}: ` +
+ `gbrain config set ${CONVERSATION_PIPELINE_ENABLE_KEY} true.`,
+ details: { reason: 'conversation_pipeline', pages, enable_key: CONVERSATION_PIPELINE_ENABLE_KEY,
+ caps: { max_cost_usd: cfg.maxCostUsd, max_total_cost_usd: cfg.maxTotalCostUsd,
+ max_walltime_min: cfg.maxWalltimeMin, max_total_walltime_min: cfg.maxTotalWalltimeMin } },
+ fix: agentFix(['gbrain', 'config', 'set', CONVERSATION_PIPELINE_ENABLE_KEY, 'true'],
+ `Turns on the conversation facts backfill, which extracts facts from imported conversation pages with paid model calls capped at ${caps}; the spend is the user's call.`,
+ 'facts_extraction_health', { ask_user: true, consent: ['paid'] }),
+ };
+}
+
export const factsExtractionEntry: DoctorEntry = {
name: 'facts_extraction_health',
emits: ['facts_extraction_health'],
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 411ed0cc61..92bc32b993 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -89,7 +89,7 @@ export interface ConversationFactsBackfillPhaseResult {
const CFG_PREFIX = 'cycle.conversation_facts_backfill';
-interface ResolvedConfig {
+export interface ResolvedConfig {
enabled: boolean;
maxCostUsd: number; // per source per cycle
maxTotalCostUsd: number; // brain-wide per cycle
@@ -106,7 +106,8 @@ interface ResolvedConfig {
workers: number;
}
-async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
+/** The backfill's resolved config (switch, caps, types); doctor reads the same values. */
+export async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
const get = (k: string) => engine.getConfig(`${CFG_PREFIX}.${k}`);
const [enabled, maxCost, maxTotalCost, maxWall, maxTotalWall, typesRaw, workersRaw] =
await Promise.all([
diff --git a/src/core/facts/eligibility.ts b/src/core/facts/eligibility.ts
index 8d611f27f3..b386714174 100644
--- a/src/core/facts/eligibility.ts
+++ b/src/core/facts/eligibility.ts
@@ -32,6 +32,10 @@
* extracted; the directory says it's a meeting regardless of the
* legacy frontmatter type. Test fixtures cover all four combinations.)
*
+ * Conversation-shaped types (conversation, imessage, slack threads, email
+ * digests) skip with `conversation_pipeline`: their facts come from the
+ * opt-in conversation facts backfill, not the page-write backstop.
+ *
* Reasons returned for the skipped envelope are stable strings consumed
* by tests and observability (the doctor's facts_extraction_health check
* groups by reason).
@@ -39,7 +43,7 @@
import { isQuarantined } from '../quarantine.ts';
import type { PageType } from '../types.ts';
-import { isFrontmatterFlagOff } from './conversation-types.ts';
+import { ALLOWED_TYPES, isFrontmatterFlagOff, pageTypesForAllowed } from './conversation-types.ts';
export type EligibilityResult = { ok: true } | { ok: false; reason: string };
@@ -86,6 +90,17 @@ const ELIGIBLE_TYPES: PageType[] = [
const MIN_BODY_CHARS = 80;
+/**
+ * Page types the backstop leaves to the opt-in conversation facts pipeline
+ * (#6557): the paid backfill reads them in message windows under its own cost
+ * caps, so a write never fires an uncapped extraction for them. Skips carry
+ * `conversation_pipeline` and name the opt-in.
+ */
+export const CONVERSATION_PIPELINE_TYPES: readonly string[] = pageTypesForAllowed(ALLOWED_TYPES)
+ .filter(t => !(ELIGIBLE_TYPES as string[]).includes(t));
+export const CONVERSATION_PIPELINE_ENABLE_KEY = 'cycle.conversation_facts_backfill.enabled';
+export const BACKSTOP_RESCUE_SLUG_PREFIXES: readonly string[] = RESCUE_SLUG_PREFIXES;
+
export function isFactsBackstopEligible(
slug: string,
parsed: { type: PageType; compiled_truth: string; frontmatter: Record<string, unknown> } | null | undefined,
@@ -104,7 +119,9 @@ export function isFactsBackstopEligible(
const typeOk = ELIGIBLE_TYPES.includes(parsed.type);
const slugOk = RESCUE_SLUG_PREFIXES.some(p => slug.startsWith(p));
- if (!typeOk && !slugOk) return { ok: false, reason: `kind:${parsed.type}` };
+ if (!typeOk && !slugOk) {
+ return { ok: false, reason: CONVERSATION_PIPELINE_TYPES.includes(parsed.type) ? 'conversation_pipeline' : `kind:${parsed.type}` };
+ }
return { ok: true };
}
diff --git a/test/facts-conversation-pipeline-6557.test.ts b/test/facts-conversation-pipeline-6557.test.ts
new file mode 100644
index 0000000000..176ca3a933
--- /dev/null
+++ b/test/facts-conversation-pipeline-6557.test.ts
@@ -0,0 +1,59 @@
+/**
+ * #6557: conversation pages skip the page-write facts backstop on purpose (the
+ * opt-in conversation facts backfill owns them, under its own spend caps). The
+ * skip is typed (`conversation_pipeline`) and doctor's facts_extraction_health
+ * names the opt-in and its caps when such pages exist and the backfill is off.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { factsExtractionEntry } from '../src/commands/doctor/checks/knowledge-health.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+const BODY = 'Alice Example: we agreed to move the launch to Friday. Bob Example: fine, I will tell the team tomorrow morning.';
+const run = async () => {
+ const checks = await factsExtractionEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ expect(checks).toHaveLength(1);
+ return checks[0]!;
+};
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+
+describe('facts_extraction_health names the conversation pipeline (#6557)', () => {
+ test('no conversation pages: no note', async () => {
+ const check = await run();
+ expect(check.message).not.toContain('conversation_pipeline');
+ });
+
+ test('conversation pages with the backfill off: the note names the opt-in, its caps, and asks the user', async () => {
+ await engine.putPage('conversations/2026-10-01-thread', { type: 'conversation', title: 'Thread', compiled_truth: BODY });
+ await engine.putPage('meetings/2026-10-02-call', { type: 'conversation', title: 'Call', compiled_truth: BODY });
+ const check = await run();
+ expect(check.message).toContain('1 conversation page(s) are not read by the page-write facts backstop (conversation_pipeline)');
+ expect(check.message).toContain('capped at $1.00 per source and $5.00 per cycle, 20 min per source and 30 min per cycle');
+ expect(check.message).toContain('gbrain config set cycle.conversation_facts_backfill.enabled true');
+ expect((check.details as Record<string, unknown>).conversation_pipeline).toMatchObject({ reason: 'conversation_pipeline', pages: 1 });
+ expect(check.fix).toMatchObject({
+ argv: ['gbrain', 'config', 'set', 'cycle.conversation_facts_backfill.enabled', 'true'], ask_user: true, consent: ['paid'],
+ });
+ });
+
+ test('configured caps are the ones stated', async () => {
+ await engine.setConfig('cycle.conversation_facts_backfill.max_cost_usd', '0.5');
+ const check = await run();
+ expect(check.message).toContain('capped at $0.50 per source');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_cost_usd', '1');
+ });
+
+ test('backfill on: no note', async () => {
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+ const check = await run();
+ expect(check.message).not.toContain('conversation_pipeline');
+ });
+});
diff --git a/test/facts-eligibility.test.ts b/test/facts-eligibility.test.ts
index e7952dacbd..0a959cf96b 100644
--- a/test/facts-eligibility.test.ts
+++ b/test/facts-eligibility.test.ts
@@ -166,3 +166,20 @@ describe('isFactsBackstopEligible — quarantined pages', () => {
expect(isFactsBackstopEligible(slug, parsed)).toEqual({ ok: true });
});
});
+
+// #6557: conversation-shaped pages belong to the opt-in conversation facts pipeline; the skip says so.
+describe('isFactsBackstopEligible — conversation pipeline types', () => {
+ test.each(['conversation', 'imessage', 'imessage-daily', 'slack-thread', 'slack-dm-day', 'email-digest'])(
+ '%s skips with reason conversation_pipeline', (type) => {
+ const { parsed } = fixture({ type: type as PageType });
+ expect(isFactsBackstopEligible('conversations/2026-10-01-thread', parsed)).toEqual({ ok: false, reason: 'conversation_pipeline' });
+ });
+ test('a non-conversation ineligible type keeps its kind reason', () => {
+ const { parsed } = fixture({ type: 'person' as PageType });
+ expect(isFactsBackstopEligible('people/alice-example', parsed)).toEqual({ ok: false, reason: 'kind:person' });
+ });
+ test('a conversation page under a rescue prefix stays eligible', () => {
+ const { parsed } = fixture({ type: 'conversation' as PageType });
+ expect(isFactsBackstopEligible('meetings/2026-10-01-call', parsed)).toEqual({ ok: true });
+ });
+});