Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): managed synthesis honours pre-managed completions whose output still exists (#6924)

garrytan3d3cc5f336a7
diff --git a/src/core/cycle/synthesize-completion.ts b/src/core/cycle/synthesize-completion.ts
index b45a592ecd..7847cbca0b 100644
--- a/src/core/cycle/synthesize-completion.ts
+++ b/src/core/cycle/synthesize-completion.ts
@@ -15,11 +15,25 @@ import type { DiscoveredTranscript } from './transcript-discovery.ts';
* #5145: split transcripts into already-synthesized and candidates BEFORE the
* paid triage pass. Classic brains (no maintenance) and dry runs (maintenance
* forced null) used to triage completed transcripts first and only skip them
- * afterwards, re-buying triage whenever the verdict cache expired. Legacy
- * `dream:synth:` keys count on classic brains only (as the fan-out always
- * did); a dry run on a managed brain reads the source incarnation read-only
- * so its synth-v2 keys match the identity a real run would use. The key lists
- * are returned for the fan-out's own per-transcript checks.
+ * afterwards, re-buying triage whenever the verdict cache expired. A dry run
+ * on a managed brain reads the source incarnation read-only so its synth-v2
+ * keys match the identity a real run would use.
+ *
+ * `retainedSkips` maps each transcript the fan-out must skip without
+ * re-attaching children to its skip reason: legacy `dream:synth:` completions
+ * and, on a managed brain, synth-v2 completions under the bare source id.
+ * Completions keyed to this run's own identity stay out of the map; the
+ * fan-out re-checks them against `successfulV2Keys` (a managed run re-attaches
+ * their children for postprocessing).
+ *
+ * #6924: on a managed brain a completion without an incarnation (legacy keys,
+ * bare-source synth-v2 keys) was recorded before the brain went managed, so
+ * its identity cannot say which row of this source id it belongs to. It
+ * counts only when this source still holds that synthesis's output: a live
+ * `dream_generated` page whose `raw_source` names the transcript (matched by
+ * basename, like the keys). Pages are deleted with their source row, so a
+ * completion of a removed and re-added source, or of another source, never
+ * suppresses synthesis.
*/
export async function partitionCompletedSynthesis(
engine: BrainEngine,
@@ -27,19 +41,48 @@ export async function partitionCompletedSynthesis(
sourceId: string,
maintenance: MaintenanceAuthority | null,
dryRun: boolean,
-): Promise<{ completed: Set<string>; successfulLegacyKeys: string[]; successfulV2Keys: string[]; synthesisIdentity: string }> {
+): Promise<{ completed: Set<string>; retainedSkips: Map<string, string>; successfulV2Keys: string[]; synthesisIdentity: string }> {
const incarnation = maintenance
? maintenance.writer.sourceIncarnation
: dryRun ? await readManagedSourceIncarnation(engine, sourceId) : null;
const synthesisIdentity = incarnation !== null ? `${sourceId}/${incarnation}` : sourceId;
const successfulV2Keys = await loadSuccessfulSynthesisKeys(engine, sourceId, 'dream:synth-v2:');
- const successfulLegacyKeys = incarnation !== null ? [] : await loadSuccessfulSynthesisKeys(engine, sourceId, 'dream:synth:');
- const completed = new Set(transcripts.filter(t => {
+ const successfulLegacyKeys = await loadSuccessfulSynthesisKeys(engine, sourceId, 'dream:synth:');
+ const retainedOutputs = incarnation !== null ? await loadRetainedOutputSources(engine, sourceId) : null;
+ const completed = new Set<string>();
+ const retainedSkips = new Map<string, string>();
+ for (const t of transcripts) {
const hash16 = t.contentHash.slice(0, 16);
- return findLegacyCompletion(successfulLegacyKeys, t.filePath, hash16) !== null
- || findSynthV2Completion(successfulV2Keys, t.filePath, hash16, synthesisIdentity) !== null;
- }).map(t => t.filePath));
- return { completed, successfulLegacyKeys, successfulV2Keys, synthesisIdentity };
+ const current = findSynthV2Completion(successfulV2Keys, t.filePath, hash16, synthesisIdentity);
+ if (current) completed.add(t.filePath);
+ if (retainedOutputs && (current || !retainedOutputs.has(basename(t.filePath)))) continue;
+ const legacy = findLegacyCompletion(successfulLegacyKeys, t.filePath, hash16);
+ const premanaged = retainedOutputs ? findSynthV2Completion(successfulV2Keys, t.filePath, hash16, sourceId) : null;
+ const reason = legacy ? `already_synthesized_legacy_${legacy === 'chunked' ? 'chunked' : 'single_chunk'}`
+ : premanaged ? `already_synthesized_v2_${premanaged === 'chunked' ? 'chunked' : 'single_chunk'}` : null;
+ if (!reason) continue;
+ completed.add(t.filePath);
+ retainedSkips.set(t.filePath, reason);
+ }
+ return { completed, retainedSkips, successfulV2Keys, synthesisIdentity };
+}
+
+/**
+ * #6924: basenames of the transcripts this source's live synthesis output
+ * names (`raw_source`, stamped on every classic synthesis page by
+ * stampDreamProvenance).
+ */
+async function loadRetainedOutputSources(engine: BrainEngine, sourceId: string): Promise<Set<string>> {
+ const rows = await engine.executeRaw<{ raw_source: string }>(
+ `SELECT DISTINCT frontmatter->>'raw_source' AS raw_source
+ FROM pages
+ WHERE source_id = $1
+ AND deleted_at IS NULL
+ AND frontmatter->>'dream_generated' = 'true'
+ AND COALESCE(frontmatter->>'raw_source', '') <> ''`,
+ [sourceId],
+ );
+ return new Set(rows.map(row => basename(row.raw_source)));
}
/**
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 8033aecb0b..3e2e3b3320 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -77,7 +77,7 @@ import { resolveCycleDate, utcDate } from './cycle-date.ts';
import { throwIfAborted } from '../abort-check.ts';
import { stampDreamProvenance, summaryProvenanceLines } from './dream-provenance.ts';
import { putDerivedPage, summaryDerivation, withTranscriptTaint } from './dream-taint.ts';
-import { findLegacyCompletion, findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
+import { findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
// Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the
// allow-list loader to filing-rules.ts (#2397); patterns.ts and the
@@ -531,7 +531,7 @@ async function runPhaseSynthesizeInner(
process.stderr.write(`[dream] warning: verdict cache sweep failed: ${e instanceof Error ? e.message : String(e)}\n`);
}
- const { completed, successfulLegacyKeys, successfulV2Keys, synthesisIdentity } = await partitionCompletedSynthesis(engine, transcripts, opts.sourceId ?? 'default', maintenance, opts.dryRun);
+ const { completed, retainedSkips, successfulV2Keys, synthesisIdentity } = await partitionCompletedSynthesis(engine, transcripts, opts.sourceId ?? 'default', maintenance, opts.dryRun);
const synthesisState = { candidates: transcripts.length - completed.size, already_synthesized: completed.size };
const pass = await runTriagePass(engine, transcripts.filter(t => !completed.has(t.filePath)), {
model: config.triage.model,
@@ -741,19 +741,12 @@ async function runPhaseSynthesizeInner(
// completed under the pre-v2 path-based key family — single-chunk OR
// a full chunked set — treat as already-synthesized and skip.
// Prevents a full paid re-synthesis when the corpus root moves or
- // the chunking outcome changes across versions.
- const legacyCompletion = findLegacyCompletion(
- successfulLegacyKeys,
- t.filePath,
- hash16,
- );
- if (legacyCompletion) {
- skipReports.push({
- filePath: t.filePath,
- reason: legacyCompletion === 'chunked'
- ? 'already_synthesized_legacy_chunked'
- : 'already_synthesized_legacy_single_chunk',
- });
+ // the chunking outcome changes across versions. #6924: a managed
+ // brain also skips completions recorded before it went managed
+ // (partitionCompletedSynthesis decides which ones count).
+ const retainedSkip = retainedSkips.get(t.filePath);
+ if (retainedSkip) {
+ skipReports.push({ filePath: t.filePath, reason: retainedSkip });
continue;
}
diff --git a/test/cycle-synthesize-premanaged-completion.test.ts b/test/cycle-synthesize-premanaged-completion.test.ts
new file mode 100644
index 0000000000..b485c6042e
--- /dev/null
+++ b/test/cycle-synthesize-premanaged-completion.test.ts
@@ -0,0 +1,226 @@
+/**
+ * #6924: synthesis completions a brain recorded before it went managed.
+ *
+ * A managed run keys its synth-v2 completions `<source>/<incarnation>`; the
+ * classic runs before activation wrote legacy `dream:synth:` keys and synth-v2
+ * keys under the bare source id. Those used to be ignored after activation, so
+ * re-enabling synthesize re-synthesized every transcript (duplicate pages and
+ * paid spend).
+ *
+ * The rule: a completion without an incarnation counts on a managed brain
+ * only when its own source still holds that synthesis's output (a live
+ * `dream_generated` page whose `raw_source` names the transcript). Pages are
+ * deleted with their source row, so a completion of another source, or of a
+ * removed and re-added source, never suppresses synthesis.
+ *
+ * Dry runs use a triage model with no provider recipe: a transcript that
+ * reaches triage shows up as `degraded`, one screened out first never does.
+ */
+
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';
+import { executeRawJsonb } from '../src/core/sql-query.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { managedSynthesisFixture } from './helpers/managed-synthesis-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let dataDir: string;
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ dataDir = mkdtempSync(join(tmpdir(), 'gbrain-premanaged-synth-'));
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: join(dataDir, 'pglite') });
+ await engine.initSchema();
+ engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine);
+ closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(dataDir, { recursive: true, force: true });
+});
+
+interface DryRunDetails {
+ triage: { degraded: number };
+ synthesis_state: { candidates: number; already_synthesized: number };
+}
+
+interface Corpus {
+ engine: BrainEngine;
+ write: (name: string) => { filePath: string; name: string; hash16: string };
+ addSource: () => Promise<string>;
+ job: (sourceId: string, key: string) => Promise<void>;
+ archived: (sourceId: string, key: string) => Promise<void>;
+ output: (sourceId: string, rawSource: string, opts?: { deleted?: boolean; dreamGenerated?: boolean }) => Promise<void>;
+ dryRun: (sourceId: string) => Promise<DryRunDetails>;
+}
+
+/** One corpus per engine: transcripts on disk plus sources, completions and output pages seeded before managed mode. */
+async function withCorpus(run: (c: Corpus) => Promise<void>): Promise<void> {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(dataDir, 'corpus-'));
+ const corpusDir = join(dir, 'corpus');
+ const brainDir = join(dir, 'brain');
+ mkdirSync(corpusDir);
+ mkdirSync(brainDir);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const [key, value] of Object.entries({
+ 'dream.synthesize.enabled': 'true', 'dream.synthesize.cooldown_hours': '0',
+ 'dream.synthesize.session_corpus_dir': corpusDir, 'models.dream.triage': 'no-such-provider:judge',
+ })) await engine.setConfig(key, value);
+ let pages = 0;
+ await run({
+ engine,
+ write: name => {
+ const content = `conversation in ${name}\n`.repeat(200);
+ writeFileSync(join(corpusDir, name), content);
+ return { filePath: join(corpusDir, name), name, hash16: createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16) };
+ },
+ addSource: async () => {
+ const id = `premanaged-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ return id;
+ },
+ job: async (sourceId, key) => {
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, finished_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-done', 'completed',
+ jsonb_build_object('source_id', $1::text), $2, now())`, [sourceId, key]);
+ },
+ archived: async (sourceId, key) => {
+ await engine.executeRaw('INSERT INTO dream_synthesis_completions (source_id, idempotency_key) VALUES ($1, $2)', [sourceId, key]);
+ },
+ output: async (sourceId, rawSource, opts = {}) => {
+ await executeRawJsonb(engine,
+ `INSERT INTO pages (source_id, slug, type, title, deleted_at, frontmatter)
+ VALUES ($1, $2, 'note', 'Synthesis output', CASE WHEN $3::boolean THEN now() END, $4::jsonb)`,
+ [sourceId, `wiki/personal/reflections/output-${++pages}`, opts.deleted === true],
+ [{ ...(opts.dreamGenerated === false ? {} : { dream_generated: true }), raw_source: rawSource }]);
+ },
+ dryRun: async sourceId => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const result = await runPhaseSynthesize(engine, { brainDir, sourceId, dryRun: true });
+ expect(result.status).toBe('ok');
+ return result.details as unknown as DryRunDetails;
+ },
+ });
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+const v2Key = (identity: string, name: string, hash16: string) =>
+ `dream:synth-v2:${encodeURIComponent(identity)}:filename:${encodeURIComponent(name)}:${hash16}`;
+
+describe('#6924 managed synthesis and completions recorded before activation', () => {
+ test('a managed dry run skips pre-managed completions whose output this source still holds', async () => {
+ await withCorpus(async ({ engine, write, addSource, job, archived, output, dryRun }) => {
+ const source = await addSource();
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [source]);
+ const single = write('2026-09-01-single.txt');
+ const chunked = write('2026-09-02-chunked.txt');
+ const legacy = write('2026-09-03-legacy.txt');
+ const pruned = write('2026-09-04-pruned.txt');
+ const current = write('2026-09-05-current.txt');
+ write('2026-09-06-new.txt');
+ await job(source, v2Key(source, single.name, single.hash16));
+ await job(source, `${v2Key(source, chunked.name, chunked.hash16)}:c0of2`);
+ await job(source, `${v2Key(source, chunked.name, chunked.hash16)}:c1of2`);
+ await job(source, `dream:synth:/old/root/${legacy.name}:${legacy.hash16}`);
+ await archived(source, v2Key(source, pruned.name, pruned.hash16));
+ await job(source, v2Key(`${source}/${incarnation}`, current.name, current.hash16));
+ for (const t of [single, chunked, pruned]) await output(source, t.filePath);
+ await output(source, `/old/root/${legacy.name}`);
+ const d = await dryRun(source);
+ expect(d.synthesis_state).toEqual({ candidates: 1, already_synthesized: 5 });
+ expect(d.triage.degraded).toBe(1);
+ });
+ }, 120_000);
+
+ test('a pre-managed completion never counts unless this source holds its output', async () => {
+ await withCorpus(async ({ write, addSource, job, archived, output, dryRun }) => {
+ const source = await addSource();
+ const other = await addSource();
+ const noOutput = write('2026-09-11-no-output.txt');
+ const outputElsewhere = write('2026-09-12-output-elsewhere.txt');
+ const otherCompletion = write('2026-09-13-other-completion.txt');
+ const deletedOutput = write('2026-09-14-deleted-output.txt');
+ const userPage = write('2026-09-15-user-page.txt');
+ const oldIncarnation = write('2026-09-16-old-incarnation.txt');
+ await job(source, v2Key(source, noOutput.name, noOutput.hash16));
+ await job(source, v2Key(source, outputElsewhere.name, outputElsewhere.hash16));
+ await output(other, outputElsewhere.filePath);
+ await job(other, v2Key(other, otherCompletion.name, otherCompletion.hash16));
+ await job(other, `dream:synth:${otherCompletion.filePath}:${otherCompletion.hash16}`);
+ await archived(other, v2Key(other, otherCompletion.name, otherCompletion.hash16));
+ await output(source, otherCompletion.filePath);
+ await job(source, v2Key(source, deletedOutput.name, deletedOutput.hash16));
+ await output(source, deletedOutput.filePath, { deleted: true });
+ await job(source, v2Key(source, userPage.name, userPage.hash16));
+ await output(source, userPage.filePath, { dreamGenerated: false });
+ await job(source, v2Key(`${source}/${randomUUID()}`, oldIncarnation.name, oldIncarnation.hash16));
+ await output(source, oldIncarnation.filePath);
+ const d = await dryRun(source);
+ expect(d.synthesis_state).toEqual({ candidates: 6, already_synthesized: 0 });
+ expect(d.triage.degraded).toBe(6);
+ });
+ }, 120_000);
+
+ test('completions of a removed source do not carry over to a source re-added under the same id', async () => {
+ await withCorpus(async ({ engine, write, addSource, job, archived, output, dryRun }) => {
+ const source = await addSource();
+ const t = write('2026-09-21-recreated.txt');
+ await job(source, v2Key(source, t.name, t.hash16));
+ await job(source, `dream:synth:${t.filePath}:${t.hash16}`);
+ await archived(source, v2Key(source, t.name, t.hash16));
+ await output(source, t.filePath);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [source]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [source]);
+ const d = await dryRun(source);
+ expect(d.synthesis_state).toEqual({ candidates: 1, already_synthesized: 0 });
+ expect(d.triage.degraded).toBe(1);
+ });
+ }, 120_000);
+});
+
+test('#6924 a managed run skips a transcript the classic runs synthesized and submits nothing for it', async () => {
+ await managedSynthesisFixture(engines, async ({ engine, sourceId, opts, calls }) => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const classic = await runPhaseSynthesize(engine, opts);
+ expect(classic.status).toBe('ok');
+ expect(classic.details.pages_written).toBe(1);
+ const [page] = await engine.executeRaw<{ raw_source: string }>(
+ "SELECT frontmatter->>'raw_source' AS raw_source FROM pages WHERE source_id=$1 AND frontmatter->>'dream_generated'='true' AND slug LIKE 'wiki/personal/reflections/%'", [sourceId]);
+ expect(page.raw_source).toBe(opts.inputFile);
+ const spent = calls();
+ const jobsBefore = await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const managed = await runPhaseSynthesize(engine, opts);
+ expect(managed.status).toBe('ok');
+ expect(managed.details.synthesis_state).toEqual({ candidates: 0, already_synthesized: 1 });
+ expect(managed.details.skips).toEqual([{ filePath: opts.inputFile, reason: 'already_synthesized_v2_single_chunk' }]);
+ expect(managed.details.children_submitted).toBe(0);
+ expect(calls()).toBe(spent);
+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(jobsBefore);
+ });
+}, 240_000);
diff --git a/test/e2e/cycle-synthesize-premanaged-completion-postgres.test.ts b/test/e2e/cycle-synthesize-premanaged-completion-postgres.test.ts
new file mode 100644
index 0000000000..a91aff5688
--- /dev/null
+++ b/test/e2e/cycle-synthesize-premanaged-completion-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../cycle-synthesize-premanaged-completion.test.ts'));