Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(dream): synthesize discovers imported type: conversation pages from the DB (#4419)

garrytan8aa8ba751978
diff --git a/src/core/config.ts b/src/core/config.ts
index 47359e4b31..ce2185b6a9 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1441,7 +1441,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// not a conversation_parser.* prefix: fallback is the only opt-in consumer.
'conversation_parser.llm_fallback_enabled',
// Dream cycle config
- 'dream.synthesize.session_corpus_dir',
+ 'dream.synthesize.session_corpus_dir', 'dream.synthesize.conversation_pages', // #4419 conversation pages feed synthesis
'dream.synthesize.meeting_transcripts_dir',
'dream.synthesize.last_completion_ts',
'dream.synthesize.verdict_model',
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index ec300b84e0..03f470d94f 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -81,7 +81,7 @@ import { stampDreamProvenance } from './dream-provenance.ts';
export { runSubagentsInline, runDrainRenewalTick };
import { loadAllowedSlugPrefixes } from './filing-rules.ts';
export { loadAllowedSlugPrefixes };
-import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscript } from './transcript-discovery.ts';
+import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscript, conversationPagesOptedIn, conversationPagesNotConsumed, withConversationPages } from './transcript-discovery.ts';
import { loadStorageConfig, isDbOnly } from '../storage-config.ts';
import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';
import type { Page, PageType } from '../types.ts';
@@ -443,9 +443,9 @@ async function runPhaseSynthesizeInner(
config.subagentWaitTimeoutMs = clamped.waitTimeoutMs;
// Allow ad-hoc --input to run even when config is disabled.
- if (!opts.inputFile && !config.corpusDir) {
- return skipped('not_configured',
- 'dream.synthesize.session_corpus_dir is unset');
+ if (!opts.inputFile && !config.corpusDir && !(await conversationPagesOptedIn(engine))) {
+ return await conversationPagesNotConsumed(engine, opts.sourceId ?? 'default')
+ ?? skipped('not_configured', 'dream.synthesize.session_corpus_dir is unset');
}
if (!opts.inputFile && !config.enabled) {
if (!opts.once) {
@@ -483,11 +483,11 @@ async function runPhaseSynthesizeInner(
// them. Best-effort — a probe that's never run is a normal early state.
const priorContradictionsBlock = await loadPriorContradictionsBlock(engine);
- // Discover.
- const transcripts = opts.inputFile
+ // Discover: the corpus walk (or --input) plus #4419 imported conversation pages.
+ const transcripts = await withConversationPages(engine, opts, config, opts.inputFile
? loadAdHocTranscript(opts.inputFile, config.minChars, config.excludePatterns, opts.bypassDreamGuard)
- : discoverTranscripts({
- corpusDir: config.corpusDir!,
+ : !config.corpusDir ? [] : discoverTranscripts({
+ corpusDir: config.corpusDir,
meetingTranscriptsDir: config.meetingTranscriptsDir ?? undefined,
minChars: config.minChars,
excludePatterns: config.excludePatterns,
@@ -507,7 +507,7 @@ async function runPhaseSynthesizeInner(
].map(prefix => join(opts.brainDir, prefix)),
// #5413: corpus files captured from gbrain's own claude-cli calls.
selfCaptureSessionIds: claudeCliSelfSessionIds(),
- });
+ }));
if (transcripts.length === 0) {
return ok('no transcripts to process', { transcripts_processed: 0, pages_written: 0 });
@@ -1603,7 +1603,7 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>
const corpusDir = await engine.getConfig('dream.synthesize.session_corpus_dir');
// v2: enabled defaults to true when corpus dir is configured, false otherwise.
// Explicit enabled=false still wins for pausing synthesis without removing corpus config.
- const enabled = enabledRaw === 'false' ? false : (enabledRaw === 'true' || !!corpusDir);
+ const enabled = enabledRaw === 'false' ? false : (enabledRaw === 'true' || !!corpusDir || await conversationPagesOptedIn(engine));
const meetingTranscriptsDir = await engine.getConfig('dream.synthesize.meeting_transcripts_dir');
const excludeStr = await engine.getConfig('dream.synthesize.exclude_patterns');
// v0.28: resolveModel() unifies CLI flag > new key > deprecated key > models.default > env > fallback
diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.ts
index 9643f6715a..463944f1b2 100644
--- a/src/core/cycle/transcript-discovery.ts
+++ b/src/core/cycle/transcript-discovery.ts
@@ -6,7 +6,9 @@
* Returns a list of file paths + content + content_hash so the caller
* can key the verdict cache and dispatch one subagent per transcript.
*
- * No DB; pure filesystem + crypto. Tested with hermetic temp directories.
+ * The corpus walk is pure filesystem + crypto (hermetic temp-dir tests);
+ * the conversation-page section at the end reads `type: conversation`
+ * pages from the database (#4419).
*/
import { readFileSync, readdirSync, statSync } from 'node:fs';
@@ -15,6 +17,9 @@ import { createHash } from 'node:crypto';
import { pruneDir } from '../sync.ts';
import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';
import { corpusFileSessionId } from '../context/corpus-segments.ts';
+import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
export interface DiscoveredTranscript {
/** Absolute path to the transcript file. */
@@ -396,3 +401,163 @@ export function readSingleTranscript(
inferredDate: dateMatch ? dateMatch[1] : null,
};
}
+
+// ── #4419: imported type: conversation pages (database discovery) ───────
+/*
+ * Dream's synthesize phase discovers imported `type: conversation`
+ * pages from the database, beside the filesystem corpus walk.
+ *
+ * `gbrain transcripts ingest` (and the chat connectors) already parse,
+ * role-filter, redact and render each session as a conversation page; this
+ * section hands those page bodies to synthesis as transcripts so a native
+ * import needs no parallel `.txt` exporter. Discovery is scoped to the
+ * cycle's source, filters dates on the page's `date` frontmatter, applies
+ * the same min_chars / exclude_patterns / self-consumption rules as the
+ * corpus walk, and keys each page as `gbrain-page://<source>/<slug>` with a
+ * sha256 of its body, so the verdict cache and synthesis idempotency keys
+ * stay stable until the page changes.
+ */
+
+export const CONVERSATION_PAGE_URI_PREFIX = 'gbrain-page://';
+
+export interface ConversationPageDiscoverOpts {
+ sourceId: string;
+ minChars?: number;
+ excludePatterns?: string[];
+ date?: string;
+ from?: string;
+ to?: string;
+ bypassGuard?: boolean;
+ /** #5413: gbrain's own claude-cli session ids; their imported pages are self-captures. */
+ selfCaptureSessionIds?: ReadonlySet<string>;
+}
+
+interface ConversationRow {
+ slug: string;
+ compiled_truth: string;
+ frontmatter: Record<string, unknown> | string | null;
+}
+
+function frontmatterOf(row: ConversationRow): Record<string, unknown> {
+ if (!row.frontmatter) return {};
+ if (typeof row.frontmatter === 'string') {
+ try { return JSON.parse(row.frontmatter) as Record<string, unknown>; } catch { return {}; }
+ }
+ return row.frontmatter;
+}
+
+function pageDate(fm: Record<string, unknown>, slug: string): string | null {
+ const raw = fm.date instanceof Date ? fm.date.toISOString() : typeof fm.date === 'string' ? fm.date : '';
+ return DATE_RE.exec(raw)?.[1] ?? DATE_RE.exec(slug.split('/').pop() ?? '')?.[1] ?? null;
+}
+
+/** Live conversation pages in one source (used for the not-consumed warning). */
+export async function countConversationPages(engine: BrainEngine, sourceId: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT count(*)::text AS n FROM pages WHERE source_id = $1 AND type = 'conversation' AND deleted_at IS NULL`,
+ [sourceId],
+ );
+ return Number(rows[0]?.n ?? 0);
+}
+
+export async function discoverConversationPages(
+ engine: BrainEngine,
+ opts: ConversationPageDiscoverOpts,
+): Promise<DiscoveredTranscript[]> {
+ const minChars = opts.minChars ?? 2000;
+ const rows = await engine.executeRaw<ConversationRow>(
+ `SELECT slug, compiled_truth, frontmatter FROM pages
+ WHERE source_id = $1 AND type = 'conversation' AND deleted_at IS NULL
+ AND length(compiled_truth) >= $2::int
+ ORDER BY slug`,
+ [opts.sourceId, minChars],
+ );
+ const excludes = compileExcludePatterns(opts.excludePatterns);
+ let excluded = 0;
+ let guarded = 0;
+ const out: DiscoveredTranscript[] = [];
+ for (const row of rows) {
+ const fm = frontmatterOf(row);
+ const date = pageDate(fm, row.slug);
+ if (opts.date || opts.from || opts.to) {
+ if (!date) continue;
+ if (opts.date && date !== opts.date) continue;
+ if (opts.from && date < opts.from) continue;
+ if (opts.to && date > opts.to) continue;
+ }
+ if (fm.mode === 'lsd' || (fm.dream_generated === true && !opts.bypassGuard)) { guarded++; continue; }
+ const imported = fm.transcript_import as { session_id?: unknown } | undefined;
+ if (typeof imported?.session_id === 'string' && opts.selfCaptureSessionIds?.has(imported.session_id)) { guarded++; continue; }
+ if (excludes.some((re) => re.test(row.compiled_truth))) { excluded++; continue; }
+ out.push({
+ filePath: `${CONVERSATION_PAGE_URI_PREFIX}${opts.sourceId}/${row.slug}`,
+ contentHash: hashContent(row.compiled_truth),
+ content: row.compiled_truth,
+ basename: row.slug.split('/').pop() ?? row.slug,
+ inferredDate: date,
+ });
+ }
+ if (excluded > 0) {
+ process.stderr.write(`[dream] excluded ${excluded} conversation page(s) matching exclude_patterns; set dream.synthesize.exclude_patterns to change\n`);
+ }
+ if (guarded > 0) {
+ process.stderr.write(`[dream] skipped ${guarded} conversation page(s): dream output or gbrain's own sessions (self-consumption guard)\n`);
+ }
+ return out;
+}
+
+/** dream.synthesize.conversation_pages: on by default with a corpus dir, `true` opts in without one, `false` off. */
+async function conversationPagesSetting(engine: Pick<BrainEngine, 'getConfig'>): Promise<string | undefined> {
+ return (await engine.getConfig('dream.synthesize.conversation_pages'))?.trim().toLowerCase() || undefined;
+}
+
+export async function conversationPagesOptedIn(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ return (await conversationPagesSetting(engine)) === 'true';
+}
+
+/**
+ * The synthesize phase's transcript list: the corpus walk (or `--input`)
+ * first, then the source's conversation pages when the setting is on; a page
+ * whose body hash a corpus file already carries is not processed twice.
+ */
+export async function withConversationPages(
+ engine: BrainEngine,
+ opts: { inputFile?: string; sourceId?: string; date?: string; from?: string; to?: string; bypassDreamGuard?: boolean },
+ config: { corpusDir: string | null; minChars: number; excludePatterns: string[] },
+ corpus: DiscoveredTranscript[],
+): Promise<DiscoveredTranscript[]> {
+ if (opts.inputFile) return corpus;
+ const setting = await conversationPagesSetting(engine);
+ if (setting === 'false' || (setting !== 'true' && !config.corpusDir)) return corpus;
+ const pages = await discoverConversationPages(engine, {
+ sourceId: opts.sourceId ?? 'default', minChars: config.minChars, excludePatterns: config.excludePatterns,
+ date: opts.date, from: opts.from, to: opts.to, bypassGuard: opts.bypassDreamGuard,
+ selfCaptureSessionIds: claudeCliSelfSessionIds(),
+ });
+ const seen = new Set(corpus.map((t) => t.contentHash));
+ return [...corpus, ...pages.filter((p) => !seen.has(p.contentHash))];
+}
+
+/**
+ * #4419: synthesis is not configured (no corpus dir, conversation_pages
+ * unset) but the source holds imported conversation pages. Returns a warn
+ * naming the opt-in instead of a clean zero-work skip; null when there is
+ * nothing to say (no pages, or the operator set conversation_pages=false).
+ */
+export async function conversationPagesNotConsumed(engine: BrainEngine, sourceId: string): Promise<PhaseResult | null> {
+ if (await conversationPagesSetting(engine)) return null;
+ const n = await countConversationPages(engine, sourceId);
+ if (n === 0) return null;
+ const fix = 'gbrain config set dream.synthesize.conversation_pages true';
+ return {
+ phase: 'synthesize',
+ status: 'warn',
+ duration_ms: 0,
+ summary: `${n} imported conversation page(s) in source ${sourceId} are not fed to Dream: synthesis is not configured. ` +
+ `Fix: ${fix} (or set dream.synthesize.session_corpus_dir); silence with dream.synthesize.conversation_pages false.`,
+ details: {
+ reason: 'not_configured', code: 'conversation_pages_not_consumed', conversation_pages: n, source_id: sourceId,
+ fix, docs: 'docs/guides/chat-connectors.md#feed-imported-conversations-to-dream',
+ },
+ };
+}
diff --git a/test/dream-conversation-pages.test.ts b/test/dream-conversation-pages.test.ts
new file mode 100644
index 0000000000..b6f589ed51
--- /dev/null
+++ b/test/dream-conversation-pages.test.ts
@@ -0,0 +1,113 @@
+/**
+ * #4419 — natively imported conversations reach Dream. A Hermes `state.db`
+ * ingested with `gbrain transcripts ingest` lands as `type: conversation`
+ * pages; the synthesize phase now discovers those pages from the database
+ * (source-scoped, date-filtered, keyed by body hash) instead of only walking
+ * `dream.synthesize.session_corpus_dir`. When synthesis is not configured
+ * but conversation pages exist, the phase warns with the opt-in command
+ * instead of returning a clean zero-work skip.
+ *
+ * Keyless: triage verdicts degrade to "no configured provider", which is
+ * enough to prove discovery (every discovered transcript gets a verdict).
+ */
+import { describe, expect, afterAll, beforeAll } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { keylessDreamTest as test } from './helpers/keyless-dream-test.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';
+import { discoverConversationPages } from '../src/core/cycle/transcript-discovery.ts';
+import { buildHermesFixture } from './fixtures/transcripts/hermes-fixture-builder.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+
+let engine: PGLiteEngine;
+const dirs: string[] = [];
+const tmp = (label: string) => { const d = mkdtempSync(join(tmpdir(), `gbrain-4419-${label}-`)); dirs.push(d); return d; };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+});
+
+async function ingestHermes(sourceId: string): Promise<string[]> {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [sourceId]);
+ const dbPath = buildHermesFixture(tmp('hermes'));
+ const r = await runTranscriptsIngest(engine, { paths: [dbPath], sourceId, format: 'hermes' });
+ expect(r.sessionsImported).toBeGreaterThan(0);
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND type = 'conversation' AND deleted_at IS NULL ORDER BY slug`, [sourceId]);
+ expect(rows.length).toBeGreaterThan(0);
+ return rows.map((r) => r.slug);
+}
+
+async function reset(): Promise<void> {
+ await resetPgliteState(engine);
+ await engine.setConfig('dream.synthesize.min_chars', '0');
+}
+
+type Verdicts = Array<{ filePath: string }>;
+
+describe('#4419 Dream discovers imported conversation pages', () => {
+ test('state.db -> ingest -> conversation pages -> synthesize triage, scoped to the cycle source', async () => {
+ await reset();
+ const slugsA = await ingestHermes('src-a');
+ await ingestHermes('src-b');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', tmp('empty-corpus'));
+ const result = await runPhaseSynthesize(engine, { brainDir: tmp('brain'), dryRun: true, sourceId: 'src-a' });
+ expect(result.status).toBe('ok');
+ const paths = ((result.details as { verdicts: Verdicts }).verdicts).map((v) => v.filePath).sort();
+ expect(paths).toEqual(slugsA.map((s) => `gbrain-page://src-a/${s}`).sort());
+ expect(paths.some((p) => p.includes('src-b'))).toBe(false);
+ }, 60_000);
+
+ test('conversation_pages=true feeds Dream without a corpus dir', async () => {
+ expect([...KNOWN_CONFIG_KEYS]).toContain('dream.synthesize.conversation_pages');
+ await reset();
+ const slugs = await ingestHermes('default');
+ await engine.setConfig('dream.synthesize.conversation_pages', 'true');
+ const result = await runPhaseSynthesize(engine, { brainDir: tmp('brain'), dryRun: true });
+ expect(result.status).toBe('ok');
+ expect(((result.details as { verdicts: Verdicts }).verdicts)).toHaveLength(slugs.length);
+ }, 60_000);
+
+ test('not configured + conversation pages present -> actionable warn, not a clean skip', async () => {
+ await reset();
+ await ingestHermes('default');
+ const result = await runPhaseSynthesize(engine, { brainDir: tmp('brain'), dryRun: true });
+ expect(result.status).toBe('warn');
+ expect(result.details).toMatchObject({ code: 'conversation_pages_not_consumed', source_id: 'default' });
+ expect(result.summary).toContain('gbrain config set dream.synthesize.conversation_pages true');
+
+ await engine.setConfig('dream.synthesize.conversation_pages', 'false');
+ const silenced = await runPhaseSynthesize(engine, { brainDir: tmp('brain'), dryRun: true });
+ expect(silenced.status).toBe('skipped');
+ expect((silenced.details as { reason: string }).reason).toBe('not_configured');
+ }, 60_000);
+
+ test('date filter, stable body-hash keys, and the self-consumption guard', async () => {
+ await reset();
+ const [slug] = await ingestHermes('default');
+ const [page] = await engine.executeRaw<{ d: string }>(`SELECT frontmatter->>'date' AS d FROM pages WHERE slug = $1`, [slug]);
+ const first = await discoverConversationPages(engine, { sourceId: 'default', minChars: 0, date: page.d });
+ expect(first.map((t) => t.filePath)).toContain(`gbrain-page://default/${slug}`);
+ expect(await discoverConversationPages(engine, { sourceId: 'default', minChars: 0, date: '1999-01-01' })).toEqual([]);
+
+ const again = await discoverConversationPages(engine, { sourceId: 'default', minChars: 0 });
+ const hashOf = (list: typeof first) => list.find((t) => t.filePath.endsWith(slug))!.contentHash;
+ expect(hashOf(again)).toBe(hashOf(first));
+ await engine.executeRaw(`UPDATE pages SET compiled_truth = compiled_truth || ' edited' WHERE slug = $1`, [slug]);
+ expect(hashOf(await discoverConversationPages(engine, { sourceId: 'default', minChars: 0 }))).not.toBe(hashOf(first));
+
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"dream_generated": true}'::jsonb WHERE slug = $1`, [slug]);
+ const guarded = await discoverConversationPages(engine, { sourceId: 'default', minChars: 0 });
+ expect(guarded.some((t) => t.filePath.endsWith(slug))).toBe(false);
+ }, 60_000);
+});