Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): synthesize checks completed synthesis before paid triage on classic brains and dry runs (#5145)
time-attack695e3b9547af
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 21e64967ef..d7213a897a 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -76,6 +76,7 @@ import { resolveCycleDate, utcDate } from './cycle-date.ts';import { throwIfAborted } from '../abort-check.ts';import { stampDreamProvenance } from './dream-provenance.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.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@@ -527,11 +528,26 @@ async function runPhaseSynthesizeInner(process.stderr.write(`[dream] warning: verdict cache sweep failed: ${e instanceof Error ? e.message : String(e)}\n`);}- const synthesisIdentity = maintenance ? `${opts.sourceId ?? 'default'}/${maintenance.writer.sourceIncarnation}` : opts.sourceId ?? 'default';- const retainedKeys = maintenance ? await loadSuccessfulSynthesisKeys(engine, opts.sourceId ?? 'default', 'dream:synth-v2:') : [];- const retained = new Set(transcripts.filter(t => maintenance && findSynthV2Completion(retainedKeys, t.filePath,- t.contentHash.slice(0, 16), synthesisIdentity)).map(t => t.filePath));- const pass = await runTriagePass(engine, transcripts.filter(t => !retained.has(t.filePath)), {+ // #5145: completed synthesis is checked BEFORE the paid triage pass on+ // every path. 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.+ // A dry run on a managed brain reads the source incarnation (read-only)+ // so its v2 keys match the identity a real run would use.+ const synthSourceId = opts.sourceId ?? 'default';+ const managedIncarnation = maintenance+ ? maintenance.writer.sourceIncarnation+ : opts.dryRun ? await readManagedSourceIncarnation(engine, synthSourceId) : null;+ const synthesisIdentity = managedIncarnation !== null ? `${synthSourceId}/${managedIncarnation}` : synthSourceId;+ const retainedKeys = await loadSuccessfulSynthesisKeys(engine, synthSourceId, 'dream:synth-v2:');+ const legacyKeys = managedIncarnation !== null ? [] : await loadSuccessfulSynthesisKeys(engine, synthSourceId, 'dream:synth:');+ const completed = new Set(transcripts.filter(t => {+ const hash16 = t.contentHash.slice(0, 16);+ return findLegacyCompletion(legacyKeys, t.filePath, hash16) !== null+ || findSynthV2Completion(retainedKeys, t.filePath, hash16, synthesisIdentity) !== null;+ }).map(t => t.filePath));+ 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,maxChars: config.triage.maxChars,maxTokens: config.triage.maxTokens,@@ -541,9 +557,12 @@ async function runPhaseSynthesizeInner(signal: opts.signal,rescue: rescueConfigOf(config.triage), decide: await resolveTriageDecide(engine),}, opts.yieldDuringPhase);- pass.reports.push(...transcripts.filter(t => retained.has(t.filePath)).map(t => ({ filePath: t.filePath,+ // Completed transcripts flow on to the fan-out loop, which records their+ // already_synthesized skip (classic) or collects their completed children+ // (managed). They are not screening results: the triage counters below+ // describe only the candidates that were actually screened.+ pass.reports.push(...transcripts.filter(t => completed.has(t.filePath)).map(t => ({ filePath: t.filePath,worth: true, score: null, content_type: null, cached: true, reasons: ['retained_completed_output'] })));- pass.cacheHits += retained.size;const verdicts = pass.reports;// Read-time gate: retuning dream.triage.threshold (or the rescue knobs)@@ -592,12 +611,15 @@ async function runPhaseSynthesizeInner(// synthesis. Codex finding #8: --dry-run does NOT mean "zero LLM calls";// it means "skip the synthesis model."if (opts.dryRun) {- return ok(`dry-run: ${worthProcessing.length} of ${transcripts.length} transcripts would synthesize${deferralSuffix}`, {+ const wouldSynthesize = worthProcessing.filter(t => !completed.has(t.filePath)).length;+ const doneSuffix = completed.size > 0 ? `; ${completed.size} already synthesized` : '';+ return ok(`dry-run: ${wouldSynthesize} of ${synthesisState.candidates} transcripts would synthesize${doneSuffix}${deferralSuffix}`, {transcripts_discovered: transcripts.length,transcripts_processed: 0,pages_written: 0,verdicts,triage: triageDetails,+ synthesis_state: synthesisState,dryRun: true,});}@@ -619,6 +641,7 @@ async function runPhaseSynthesizeInner(pages_written: 0,verdicts,triage: triageDetails,+ synthesis_state: synthesisState,});}@@ -679,8 +702,8 @@ async function runPhaseSynthesizeInner(const skipReports: Array<{ filePath: string; reason: string }> = [];const maxCharsPerChunk = computeChunkCharBudget(config.model, config.maxPromptTokens);- const successfulLegacyKeys = maintenance ? [] : await loadSuccessfulSynthesisKeys(engine, cycleSourceId, 'dream:synth:');- const successfulV2Keys = maintenance ? retainedKeys : await loadSuccessfulSynthesisKeys(engine, cycleSourceId, 'dream:synth-v2:');+ const successfulLegacyKeys = legacyKeys;+ const successfulV2Keys = retainedKeys;// Per-source daily submission cap (D2D: default 0 = disabled; opt-in// backstop via dream.synthesize.max_submissions_per_source_per_day).@@ -1032,6 +1055,7 @@ async function runPhaseSynthesizeInner(skips: skipReports,verdicts,triage: triageDetails,+ synthesis_state: synthesisState,});}@@ -1312,6 +1336,7 @@ async function runPhaseSynthesizeInner(skips: skipReports,verdicts,triage: triageDetails,+ synthesis_state: synthesisState,synthesis: {jobs: childIds.length,max_turns_config: config.maxTurns,@@ -1370,6 +1395,7 @@ async function runPhaseSynthesizeInner(summary_slug: summarySlug,verdicts,triage: triageDetails,+ synthesis_state: synthesisState,synthesis: {jobs: childIds.length,max_turns_config: config.maxTurns,@@ -2958,6 +2984,21 @@ async function collectChildPutPageSlugs(* makes a synthesized transcript eligible again. Loads source-scoped* completions once per phase; no repeated history scan per transcript.*/+/**+ * #5145: the source incarnation a managed real run would key its synth-v2+ * completions under, read without the write preflight (dry runs never+ * register a writer). Null on a classic brain or when the read fails.+ */+async function readManagedSourceIncarnation(engine: BrainEngine, sourceId: string): Promise<string | null> {+ try {+ if (!await managedPersistenceEnabled(engine)) return null;+ const [row] = await engine.executeRaw<{ incarnation: string | null }>('SELECT incarnation FROM sources WHERE id = $1', [sourceId]);+ return row?.incarnation ?? null;+ } catch {+ return null;+ }+}+async function loadSuccessfulSynthesisKeys(engine: BrainEngine,sourceId: string,diff --git a/test/cycle-synthesize-completion-before-triage-5145.test.ts b/test/cycle-synthesize-completion-before-triage-5145.test.tsnew file mode 100644index 0000000000..accb778dca--- /dev/null+++ b/test/cycle-synthesize-completion-before-triage-5145.test.ts@@ -0,0 +1,101 @@+/**+ * #5145 (fix wave 9) — synthesize checks completed synthesis BEFORE the paid+ * triage pass on classic brains and in dry runs.+ *+ * Pre-fix only the managed real-run path consulted completion keys before+ * triage. A classic brain, or any `--dry-run`, triaged already-synthesized+ * transcripts first (a paid judge call whenever the verdict cache had+ * expired) and skipped them only afterwards; the dry run returned before any+ * completion check at all.+ *+ * The triage model is set to an id with no provider recipe, so the judge+ * resolves to null and no network call is possible: a transcript that+ * reaches triage shows up as `degraded`, one that is screened out first does+ * not reach triage at all.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';++let engine: PGLiteEngine;+let schemaVersion: string;+let brainDir: string;+let corpusDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version')) ?? '7';+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-5145-brain-'));+ corpusDir = mkdtempSync(join(tmpdir(), 'gbrain-5145-corpus-'));+ await engine.setConfig('dream.synthesize.enabled', 'true');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);+ await engine.setConfig('models.dream.triage', 'no-such-provider:judge');+});++function writeTranscript(name: string): { filePath: string; hash16: string } {+ const content = `conversation in ${name}\n`.repeat(200);+ const filePath = join(corpusDir, name);+ writeFileSync(filePath, content);+ return { filePath, hash16: createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16) };+}++async function seedCompleted(idempotencyKey: string): Promise<void> {+ 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', 'default'), $1, now())`,+ [idempotencyKey],+ );+}++interface Details {+ triage: { judged: number; degraded: number; cache_hits: number; deferred: number };+ synthesis_state: { candidates: number; already_synthesized: number };+ skips?: Array<{ filePath: string; reason: string }>;+}++describe('#5145 completed synthesis is screened out before triage', () => {+ test('dry run on an unchanged classic brain makes no triage call for a v2-completed transcript', async () => {+ const done = writeTranscript('2026-09-01-done.txt');+ await seedCompleted(`dream:synth-v2:default:filename:${encodeURIComponent('2026-09-01-done.txt')}:${done.hash16}`);+ const result = await runPhaseSynthesize(engine, { brainDir, dryRun: true });+ const d = result.details as unknown as Details;+ expect(d.triage.judged).toBe(0);+ expect(d.triage.degraded).toBe(0);+ expect(d.triage.cache_hits).toBe(0);+ expect(d.synthesis_state).toEqual({ candidates: 0, already_synthesized: 1 });+ expect(result.summary).toContain('0 of 0 transcripts would synthesize; 1 already synthesized');+ rmSync(brainDir, { recursive: true, force: true });+ rmSync(corpusDir, { recursive: true, force: true });+ }, 60_000);++ test('a classic real run skips a legacy-key completion without triaging it; new transcripts are still screened', async () => {+ const done = writeTranscript('2026-09-02-legacy.txt');+ writeTranscript('2026-09-03-new.txt');+ await seedCompleted(`dream:synth:${done.filePath}:${done.hash16}`);+ const result = await runPhaseSynthesize(engine, { brainDir, dryRun: false });+ const d = result.details as unknown as Details;+ expect(d.synthesis_state).toEqual({ candidates: 1, already_synthesized: 1 });+ expect(d.triage.degraded).toBe(1);+ expect(d.skips).toContainEqual({ filePath: done.filePath, reason: 'already_synthesized_legacy_single_chunk' });+ rmSync(brainDir, { recursive: true, force: true });+ rmSync(corpusDir, { recursive: true, force: true });+ }, 60_000);+});