Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 4: synthesis on the generation primitive (#7065)

garrytanb6a411896408
diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsv
index 79db46b13a..fd54f886ad 100644
--- a/docs/architecture/derived-census.tsv
+++ b/docs/architecture/derived-census.tsv
@@ -9,6 +9,7 @@ src/core/engine.ts 3 engine BrainEngine interface declarations of softDeletePage
src/core/facts/derivation-inputs.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
src/core/generations/adapters/atoms.ts 1 primitive the unmanaged atom adapter retires through retireDerivedPagesInTransaction inside the generation activation (publish.ts)
src/core/generations/adapters/chronicle-events.ts 1 primitive the Life Chronicle event adapter retires dropped events (with their timeline projection rows) through retireDerivedPagesInTransaction inside the generation activation (publish.ts, managed.ts; GBRA-161 PR 3)
+src/core/generations/adapters/synthesis.ts 1 primitive the synthesis adapter retires matched earlier outputs of a re-synthesized transcript (synthesis-resynthesis) and operator-approved cleanup retirements (synthesis-cleanup) through retireDerivedPagesInTransaction inside the generation activation (publish.ts; GBRA-161 PR 4, #7065)
src/core/minions/handlers/ingest-capture.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
src/core/ops/extraction.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
src/core/page-body/segment-rewrite.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 1f512ebd3e..c31971893c 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -35,7 +35,7 @@ src/core/cycle/extract-facts.ts runExtractFacts 382 seed: W5 baseline, refactor
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 510 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift details; +10 #7269 (GBRA-161 PR 4): a T3 group hashes without the synthesis model, and a rewrite that would leave a deterministic-tier page at its current template body and visibility is skipped unchanged
-src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data
+src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1054 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +6 GBRA-161 PR 4 (#7065): the synthesis generation activation after postprocess (logic in cycle/synthesize-generations.ts), its file holds and details.synthesis_generations
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/import-file.ts importFromContent 692 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts); +3 Wave B review: reuseSegments option (a rename re-preparation reuses the staged segmented body) and the remote fence merge over fenceBody; +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut it
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index ad60342332..218b626597 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -618,3 +618,4 @@ src/core/generations/adapters/page.ts pageVersionEvidence sql INLINE legacy-adop
src/core/generations/adapters/atoms.ts atomGenerationAdapter sql META input size only: body_bytes for a segmented page, octet_length of an inline page columns (pages leave body_bytes NULL inline)
src/core/generations/repair.ts releaseManaged field INLINE assertInlineBody refuses a segmented origin page before the managed release reads its body to bind the origin
src/core/search/exact-scan.ts buildExactBatchStatement sql META #7191: octet_length of the body columns (stored size, never the body) decides an unreadable page
+src/core/cycle/synthesize-generations.ts pages sql INLINE reads the synthesis outputs of one re-synthesized transcript for the predecessor coverage match (generations/synthesis-coverage.ts); segmented pages are excluded in SQL, so a segmented earlier output is never compared and stays live as an unreadable unmatched predecessor
diff --git a/src/core/config.ts b/src/core/config.ts
index a2265a0a71..59ca651196 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1766,8 +1766,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on
'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend
- // GBRA-161: the generation primitive's restore window, shrink floor, item cap and retirement valve (generations/config.ts)
- 'generations.restore_days', 'generations.shrink_floor', 'generations.max_items', 'generations.valve.max_per_run', 'generations.valve.max_ratio',
+ // GBRA-161: the generation primitive's restore window, shrink floor, item cap and retirement valve (generations/config.ts); PR 4 (#7065): synthesis retire_previous, default on
+ 'generations.restore_days', 'generations.shrink_floor', 'generations.max_items', 'generations.valve.max_per_run', 'generations.valve.max_ratio', 'generations.synthesis.retire_previous',
// #2179: clamp window for DCR-requested per-client token TTLs. Read by
// `gbrain serve --http` at startup; unset min defaults to 300s, unset max
// defaults fail-closed to max(--token-ttl, min).
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.ts
index 8672ec9b7e..cd66368d4f 100644
--- a/src/core/cycle/derived-write-through.ts
+++ b/src/core/cycle/derived-write-through.ts
@@ -210,6 +210,27 @@ export async function writeDreamPageFile(engine: BrainEngine, brainDir: string,
return { written: true, path: filePath };
}
+/**
+ * GBRA-161 PR 4: remove the file of a dream page a generation retired, resolved the way `writeDreamPageFile` wrote it, only
+ * when the retired page (or one of its versions) holds everything in it; re-read right before the unlink. A file holding
+ * an edit the database lacks stays, with its `file_database_drift` entry returned as `held`.
+ */
+export async function removeDreamPageFile(engine: BrainEngine, brainDir: string, slug: string, sourceId: string,
+ nativeSourceId: string): Promise<{ removed: boolean; held?: string }> {
+ if (await isWriteThroughDisabled(engine) || await urlCloneReadOnly(engine, sourceId)) return { removed: false };
+ const target = await resolvePageWriteTarget(engine, slug, sourceId);
+ if (!target.ok && (!brainDir || (target.skipped !== 'no_repo_configured' && target.skipped !== 'repo_not_found'))) return { removed: false };
+ const filePath = target.ok ? target.filePath
+ : sourceId === nativeSourceId ? join(brainDir, `${slug}.md`) : join(brainDir, '.sources', sourceId, `${slug}.md`);
+ if (!existsSync(filePath)) return { removed: false };
+ const check = await replaceableFile(engine, sourceId, slug, filePath);
+ if (!check.ok || readFileSync(filePath, 'utf-8') !== check.expectedFileBytes) {
+ return { removed: false, held: fileDatabaseDriftToken(slug, sourceId, 'before', "the retired dream page's file was not removed") };
+ }
+ rmSync(filePath, { force: true });
+ return { removed: true };
+}
+
/** #6982: the hold entry for a dream page whose file holds an edit the database lacks. */
function dreamFileDriftToken(slug: string, sourceId: string, when: 'before' | 'during'): string {
return fileDatabaseDriftToken(slug, sourceId, when, 'the dream output stays in the database only', 'the dream reverse-write');
diff --git a/src/core/cycle/extract-atoms-generation.ts b/src/core/cycle/extract-atoms-generation.ts
index 5e76dce0fb..eae0d1bc2b 100644
--- a/src/core/cycle/extract-atoms-generation.ts
+++ b/src/core/cycle/extract-atoms-generation.ts
@@ -64,15 +64,16 @@ export function transcriptRoot(filePath: string, corpusDir: string, meetingDir:
* basename or content hash, so two files of one name in two folders never share a key. A file a live generation names as
* its locator keeps that generation's key (the rename map). A file whose key has no live generation but whose content
* equals the input of a live transcript generation whose file is gone was moved: it keeps that key, and the generation's
- * locator follows it (recorded even when the unchanged file is not extracted again).
+ * locator follows it (recorded even when the unchanged file is not extracted again). `kind`: the ledger kind whose live
+ * generations hold the rename map (atoms by default; synthesis keys its outputs the same way, GBRA-161 PR 4).
*/
export async function resolveTranscriptKeys(engine: BrainEngine, sourceId: string, transcripts: ReadonlyArray<{ filePath: string; contentHash: string; root?: { path: string; label: string } }>,
- dryRun: boolean): Promise<Map<string, string>> {
+ dryRun: boolean, kind: string = ATOM_KIND): Promise<Map<string, string>> {
const own = new Map(transcripts.map(t => [t.filePath, t.root ? `${t.root.label}/${relative(resolve(t.root.path), resolve(t.filePath)).split(sep).join('/')}` : t.filePath]));
if (!transcripts.length) return own;
const live = await engine.executeRaw<{ id: number; owner_key: string; locator: string | null; input_pin: string | null }>(
`SELECT id, owner_key, locator, input_pin FROM derived_generations WHERE source_id=$1 AND kind=$2 AND state='live' AND owner_key LIKE $3`,
- [sourceId, ATOM_KIND, `${TRANSCRIPT_KEY_PREFIX}%`]);
+ [sourceId, kind, `${TRANSCRIPT_KEY_PREFIX}%`]);
const located = new Set<string>();
for (const t of transcripts) {
const at = live.find(row => row.locator === t.filePath);
diff --git a/src/core/cycle/synthesize-generations.ts b/src/core/cycle/synthesize-generations.ts
new file mode 100644
index 0000000000..368266b39d
--- /dev/null
+++ b/src/core/cycle/synthesize-generations.ts
@@ -0,0 +1,137 @@
+/**
+ * GBRA-161 PR 4 (#7065, plan D3; Captain decision (a), applying the plan Garry approved on Oct 21: replace only on a
+ * complete, non-empty result, always version first, always reversible): the activation of each re-synthesized
+ * transcript's outputs, run after postprocess and the provenance stamp. New outputs publish as they always did (the
+ * children write them); this records them as the transcript's new `synthesis` generation and retires an earlier output
+ * only when it is matched (generations/synthesis-coverage.ts). An unmatched earlier output stays live and
+ * `gbrain repair generations --kind synthesis --mode cleanup` lists it.
+ *
+ * A transcript is complete only when every child job of every chunk completed after reading its whole chunk; otherwise
+ * (or with `generations.synthesis.retire_previous` off) its generation is partial: the new outputs are recorded and
+ * nothing retires. The shrink floor and the valve of the primitive still apply.
+ */
+import { isAbsolute } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import type { ProposedItem } from '../generations/contract.ts';
+import { publishGeneration, readLiveGeneration, type PublishRequest } from '../generations/publish.ts';
+import { planManagedGeneration } from '../generations/managed.ts';
+import { admitInPlaceGeneration, resumeRetireMembers } from '../generations/managed-retire.ts';
+import { SYNTHESIS_KIND, synthesisAdapter, synthesisOwnerKey, type SynthesisGenerationContext } from '../generations/adapters/synthesis.ts';
+import { matchPredecessor, type PredecessorMatch, type SynthesisPage } from '../generations/synthesis-coverage.ts';
+import { removeDreamPageFile } from './derived-write-through.ts';
+import { resolveTranscriptKeys, transcriptRoot } from './extract-atoms-generation.ts';
+
+export const RETIRE_PREVIOUS_KEY = 'generations.synthesis.retire_previous';
+
+/** `generations.synthesis.retire_previous`: on unless set to false, off, no or 0. */
+export async function retirePreviousEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ const value = (await engine.getConfig(RETIRE_PREVIOUS_KEY).catch(() => null))?.trim().toLowerCase();
+ return !['false', 'off', 'no', '0'].includes(value ?? '');
+}
+
+type Unmatched = Extract<PredecessorMatch, { matched: false }>;
+/** An earlier output the activation left live: why (`unreadable`: segmented or gone, never compared) and what it holds alone. */
+export interface UnmatchedPredecessor { slug: string; why: Unmatched['why'] | 'unreadable'; missing: Unmatched['missing'] | null }
+
+export interface SynthesisActivationDetails {
+ activated: number;
+ partial: number;
+ retired: string[];
+ unmatched: string[];
+ held: Array<{ owner_key: string; reason: string }>;
+ failed: Array<{ owner_key: string; error: string }>;
+ file_holds: string[];
+ resumed_members: number;
+}
+
+export interface SynthesisActivationInput {
+ sourceId: string;
+ maintenance: MaintenanceAuthority | null;
+ brainDir: string;
+ transcripts: ReadonlyArray<{ filePath: string; contentHash: string; content: string; basename: string }>;
+ refs: ReadonlyArray<{ slug: string; source_id: string; raw_source?: string }>;
+ outcomes: ReadonlyArray<{ jobId: number; status: string }>;
+ jobRawSource: ReadonlyMap<number, string>;
+ /** Basenames whose submission was deferred or cancelled this run (never complete). */
+ deferred: ReadonlySet<string>;
+ /** A publication still pending or in conflict: no transcript is complete this run. */
+ publicationIncomplete: boolean;
+ corpusDir: string | null;
+ meetingDir: string | null;
+}
+
+async function pages(engine: BrainEngine, sourceId: string, slugs: readonly string[]): Promise<SynthesisPage[]> {
+ if (!slugs.length) return [];
+ const rows = await engine.executeRaw<{ slug: string; title: string | null; body: string | null }>(
+ `SELECT slug, title, COALESCE(compiled_truth, '') || E'\\n' || COALESCE(timeline, '') AS body FROM pages
+ WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND body_storage <> 'segmented' ORDER BY slug`, [sourceId, [...slugs]]);
+ return rows.map(row => ({ slug: row.slug, title: row.title ?? '', body: row.body ?? '' }));
+}
+
+/** Activates one synthesis generation per transcript this run synthesized; never throws for one transcript. */
+export async function activateSynthesisGenerations(engine: BrainEngine, input: SynthesisActivationInput): Promise<SynthesisActivationDetails> {
+ const details: SynthesisActivationDetails = { activated: 0, partial: 0, retired: [], unmatched: [], held: [], failed: [], file_holds: [], resumed_members: 0 };
+ const { sourceId, maintenance } = input;
+ if (maintenance) details.resumed_members = await resumeRetireMembers(engine, maintenance, SYNTHESIS_KIND);
+ const submitted = input.transcripts.filter(t => [...input.jobRawSource.values()].includes(t.filePath));
+ if (!submitted.length) return details;
+ const retireOn = await retirePreviousEnabled(engine);
+ const keys = await resolveTranscriptKeys(engine, sourceId, submitted.map(t => ({ filePath: t.filePath, contentHash: t.contentHash,
+ ...(isAbsolute(t.filePath) && input.corpusDir ? { root: transcriptRoot(t.filePath, input.corpusDir, input.meetingDir ?? undefined) } : {}) })), false, SYNTHESIS_KIND);
+ for (const t of submitted) {
+ const key = { kind: SYNTHESIS_KIND, sourceId, ownerKey: synthesisOwnerKey(keys.get(t.filePath) ?? t.filePath) };
+ try {
+ const jobs = [...input.jobRawSource].filter(([, path]) => path === t.filePath).map(([jobId]) => jobId);
+ const complete = !input.publicationIncomplete && !input.deferred.has(t.basename)
+ && jobs.every(jobId => input.outcomes.find(outcome => outcome.jobId === jobId)?.status === 'completed');
+ const context: SynthesisGenerationContext = { locator: t.filePath, transcriptInput: { pin: t.contentHash, size: Buffer.byteLength(t.content) } };
+ const fresh = [...new Set(input.refs.filter(ref => ref.source_id === sourceId && ref.raw_source === t.filePath).map(ref => ref.slug))];
+ const live = await readLiveGeneration(engine, key);
+ const earlier = [...(live?.items.keys() ?? [])].filter(slug => !fresh.includes(slug));
+ if (!fresh.length && !live) continue;
+ const partial = !complete || !retireOn;
+ const unmatched: UnmatchedPredecessor[] = [];
+ if (!partial) {
+ const successors = await pages(engine, sourceId, fresh);
+ const readable = new Map((await pages(engine, sourceId, earlier)).map(page => [page.slug, page]));
+ for (const slug of earlier) {
+ const page = readable.get(slug);
+ const match = page ? matchPredecessor(page, successors) : null;
+ if (!match) unmatched.push({ slug, why: 'unreadable', missing: null });
+ else if (!match.matched) unmatched.push({ slug, why: match.why, missing: match.missing });
+ }
+ }
+ const proposed = partial ? fresh : [...fresh, ...unmatched.map(entry => entry.slug)];
+ const rows = await synthesisAdapter.readItems(engine, key, proposed, context);
+ const items: ProposedItem[] = proposed.flatMap(slug => { const row = rows.get(slug); return row?.live ? [{ key: slug, content: '', identityHash: row.identityHash }] : []; });
+ const request: PublishRequest<SynthesisGenerationContext> = { key, items, input: context.transcriptInput, partial, context, locator: t.filePath,
+ ...(unmatched.length ? { note: { unmatched } } : {}) };
+ let retired: string[] = [];
+ if (maintenance) {
+ const plan = await planManagedGeneration(engine, synthesisAdapter, request, { locator: t.filePath });
+ if (plan.kind === 'held') { details.held.push({ owner_key: key.ownerKey, reason: plan.outcome.reason }); continue; }
+ if (plan.kind === 'publish') {
+ await admitInPlaceGeneration(engine, maintenance, plan);
+ retired = plan.members.filter(member => member.action === 'retire').map(member => member.slug);
+ }
+ } else {
+ const outcome = await publishGeneration(engine, synthesisAdapter, request);
+ if (outcome.state === 'held') { details.held.push({ owner_key: key.ownerKey, reason: outcome.reason }); continue; }
+ retired = outcome.retired;
+ for (const slug of retired) {
+ const file = await removeDreamPageFile(engine, input.brainDir, slug, sourceId, sourceId);
+ if (file.held) details.file_holds.push(file.held);
+ }
+ }
+ details.activated++;
+ if (partial) details.partial++;
+ details.retired.push(...retired);
+ details.unmatched.push(...unmatched.map(entry => entry.slug));
+ } catch (error) {
+ details.failed.push({ owner_key: key.ownerKey, error: error instanceof Error ? error.message : String(error) });
+ process.stderr.write(`[dream] synthesize: the synthesis generation of ${key.ownerKey} was not activated (${error instanceof Error ? error.message : String(error)}); every output stays live.\n`);
+ }
+ }
+ return details;
+}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 58de3168f0..44e4f46a5f 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -76,6 +76,7 @@ import { buildManifestContext, buildLinkManifest, type ManifestContext } from '.
import { resolveCycleDate, utcDate } from './cycle-date.ts';
import { throwIfAborted } from '../abort-check.ts';
import { stampDreamProvenance, summaryProvenanceLines } from './dream-provenance.ts';
+import { activateSynthesisGenerations } from './synthesize-generations.ts';
import { putDerivedPage, summaryDerivation, withTranscriptTaint } from './dream-taint.ts';
import { findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
@@ -1194,6 +1195,11 @@ async function runPhaseSynthesizeInner(
// #4077: nothing below runs for a cancelled cycle — no phase-end embed
// spend, no cooldown stamp (the next run must retry these transcripts).
throwIfAborted(opts.signal, '[dream] synthesize completion');
+ const synthesisGenerations = await activateSynthesisGenerations(engine, { sourceId: cycleSourceId, maintenance, brainDir: opts.brainDir,
+ transcripts: worthProcessing, refs: writtenRefs, outcomes: childOutcomes, jobRawSource, deferred: new Set(budgetExhaustedDeferrals),
+ publicationIncomplete: publishPending > 0 || postprocessConflicts.length > 0 || postprocessDeferral !== null,
+ corpusDir: config.corpusDir, meetingDir: config.meetingTranscriptsDir });
+ fileHolds.push(...synthesisGenerations.file_holds);
// CDX-8: deferred-embed closure. Oneshot children write chunks with
// `embedding IS NULL`; the global `embed` phase only runs on SOME
@@ -1370,6 +1376,7 @@ async function runPhaseSynthesizeInner(
written_slugs: writtenSlugs,
reverse_write_count: reverseWriteCount,
child_outcomes: childOutcomes,
+ synthesis_generations: synthesisGenerations,
// Children submitted (one per chunk for chunked transcripts; one per
// transcript for single-chunk). Differs from transcripts_processed
// when chunking is in play.
diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.ts
index 75b382aff5..68a5c79801 100644
--- a/src/core/generations/adapters/index.ts
+++ b/src/core/generations/adapters/index.ts
@@ -5,8 +5,9 @@
import type { GenerationAdapter } from '../contract.ts';
import { atomGenerationAdapter } from './atoms.ts';
import { chronicleEventAdapter } from './chronicle-events.ts';
+import { synthesisAdapter } from './synthesis.ts';
-const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, chronicleEventAdapter].map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));
+const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, chronicleEventAdapter, synthesisAdapter].map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));
/** The adapter of `kind`; a hyphenated spelling (`chronicle-event`) names the same kind. */
export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind) ?? adapters.get(kind.replaceAll('-', '_')); }
diff --git a/src/core/generations/adapters/synthesis.ts b/src/core/generations/adapters/synthesis.ts
new file mode 100644
index 0000000000..dbd4a33736
--- /dev/null
+++ b/src/core/generations/adapters/synthesis.ts
@@ -0,0 +1,67 @@
+/**
+ * GBRA-161 PR 4 (#7065, plan D3): the synthesis adapter. One owner key per transcript (`transcript:<root>/<path>`, the
+ * PR 1b transcript key: its path relative to the corpus root it was found under, with the rename map), kind `synthesis`.
+ * The items are the reflection and original pages the synthesize phase's children write for it (`dream_generated`,
+ * `raw_source` naming the transcript). New outputs publish as they always did, written by the children; the activation
+ * (cycle/synthesize-generations.ts) records them and retires, versioned and stamped `synthesis-resynthesis`, only the
+ * earlier outputs a complete re-synthesis matched (generations/synthesis-coverage.ts). Every other earlier output is
+ * carried into the new generation and stays live. An output written before the ledger is never adopted as an earlier
+ * output (no legacy evidence), so the existing duplicate backlog is untouched.
+ */
+import type { BrainEngine } from '../../engine.ts';
+import { opError } from '../../ops/contract.ts';
+import { retireDerivedPagesInTransaction, type DerivedRetiredBy } from '../../persistence/derived-retirement-hold.ts';
+import type { GenerationAdapter, GenerationKey, InputState } from '../contract.ts';
+import { importPageItem, pageItemRow, preimageIdentity, preimageMarkdown, readPageRows } from './page.ts';
+import { TRANSCRIPT_KEY_PREFIX } from './atoms.ts';
+
+export const SYNTHESIS_KIND = 'synthesis';
+export const SYNTHESIS_RETIRED_BY: DerivedRetiredBy = 'synthesis-resynthesis';
+export const SYNTHESIS_CLEANUP_RETIRED_BY: DerivedRetiredBy = 'synthesis-cleanup';
+
+/** What one activation hands the adapter: the transcript's current file and the input the children read. */
+export interface SynthesisGenerationContext { locator: string; transcriptInput: InputState }
+
+export const synthesisOwnerKey = (transcriptKey: string) => `${TRANSCRIPT_KEY_PREFIX}${transcriptKey}`;
+
+function assertKey(key: GenerationKey): void {
+ if (!key.ownerKey.startsWith(TRANSCRIPT_KEY_PREFIX)) throw new Error(`not a synthesis owner key: ${key.ownerKey}`);
+}
+
+/** Item keys the live generation of `key` records (still owned whatever file they name). */
+async function recordedKeys(db: BrainEngine, key: GenerationKey): Promise<Set<string>> {
+ const rows = await db.executeRaw<{ item_key: string }>(
+ `SELECT i.item_key FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id
+ WHERE g.source_id=$1 AND g.kind=$2 AND g.owner_key=$3 AND g.state='live' AND i.action <> 'retired'`, [key.sourceId, key.kind, key.ownerKey]);
+ return new Set(rows.map(row => row.item_key));
+}
+
+export const synthesisAdapter: GenerationAdapter<SynthesisGenerationContext> = {
+ kind: SYNTHESIS_KIND,
+ retiredBy: SYNTHESIS_RETIRED_BY,
+ modelProduced: true,
+ publishesInPlace: true,
+ lockKeys: (key, itemKeys) => itemKeys.map(slug => ({ sourceId: key.sourceId, slug })),
+ async readInput(_engine, key, context) {
+ assertKey(key);
+ return context?.transcriptInput ?? null;
+ },
+ async readItems(engine, key, itemKeys, context) {
+ assertKey(key);
+ const recorded = await recordedKeys(engine, key);
+ const locator = context?.locator ?? null;
+ const rows = await readPageRows(engine, key.sourceId, `p.slug = ANY($2::text[]) OR (p.deleted_at IS NULL AND $3::text IS NOT NULL
+ AND p.frontmatter->>'raw_source' = $3 AND p.frontmatter->>'dream_generated' = 'true')`, [[...new Set([...itemKeys, ...recorded])], locator]);
+ return new Map(rows.map(row => [row.slug, pageItemRow(row, row.frontmatter?.dream_generated === true
+ && (recorded.has(row.slug) || (locator !== null && row.frontmatter?.raw_source === locator)))]));
+ },
+ // An output written before the ledger is never another generation's earlier output: the backlog stays as it is.
+ legacyEvidence: async () => new Set<string>(),
+ async publishItems(_tx, key, items) {
+ throw opError('generation_live_conflict', `The synthesis generation of ${key.ownerKey} was not activated: ${items.slice(0, 5).map(item => item.key).join(', ')} changed after the run read it; nothing was retired.`,
+ 'Nothing to do: every output stays live, and the next re-synthesis of the transcript plans from the pages as they are.', { docs: 'docs/architecture/generations.md#synthesis' });
+ },
+ retireItems: (tx, key, itemKeys, retiredBy) => retireDerivedPagesInTransaction(tx, key.sourceId, itemKeys, retiredBy),
+ restoreItem: (tx, key, itemKey, preimage) => importPageItem(tx, key.sourceId, itemKey, preimageMarkdown(preimage)),
+ preimageIdentity,
+};
diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.ts
index 9a6ccc75f7..35ad01bacd 100644
--- a/src/core/generations/contract.ts
+++ b/src/core/generations/contract.ts
@@ -43,6 +43,11 @@ export interface GenerationAdapter<C = unknown> {
* members, nothing left pending); a restore runs as one coordinated request (managed.ts).
*/
databaseOnly?: boolean;
+ /**
+ * Its producer writes the items itself before the activation (synthesis: the phase's children). The activation records
+ * them where they are and never writes one; a managed plan keeps them without members and only retires (managed-retire.ts).
+ */
+ publishesInPlace?: boolean;
/** Page keys locked before the ledger row, in slug order with the input guard (D7). */
lockKeys(key: GenerationKey, itemKeys: readonly string[]): Array<{ sourceId: string; slug: string }>;
/** The input as stored now, or null when it is gone. `context` carries an input the database does not hold (a transcript). */
diff --git a/src/core/generations/managed-retire.ts b/src/core/generations/managed-retire.ts
new file mode 100644
index 0000000000..9fdbb8024c
--- /dev/null
+++ b/src/core/generations/managed-retire.ts
@@ -0,0 +1,122 @@
+/**
+ * GBRA-161 PR 4: the managed activation of a kind whose producer writes its items itself (`publishesInPlace`: synthesis).
+ * One admission transaction records the activation and admits the `managed_generation_activate` request and one
+ * `managed_generation_retire` member per retired item (version first through the page delete, stamped with the
+ * generation's `retired_by`, refusing unless its item is pending on the live generation the activation made). A crash
+ * after the activation leaves the items retire_pending (still live): `resumeRetireMembers` finishes them on the next run,
+ * and an item edited since keeps its content.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { loadConfig, type GBrainConfig } from '../config.ts';
+import { opError } from '../ops/contract.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import { admitWriteInTransaction, getWriteRequest } from '../persistence/journal.ts';
+import { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { preparePageMutation } from '../persistence/page-prepare.ts';
+import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { waitForWrite, writeResponse } from '../persistence/service.ts';
+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
+import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
+import { generationAdapter } from './adapters/index.ts';
+import type { GenerationKey } from './contract.ts';
+import { assertMemberPending, GENERATION_ACTIVATE_SLUG, listPendingMembers, memberRequestId, recordActivation, settleMember,
+ type ActivationIntent, type ManagedPlan } from './managed.ts';
+
+export const GENERATION_RETIRE_INTENT = 'managed_generation_retire';
+
+interface RetireIntent extends Record<string, unknown> {
+ kind: typeof GENERATION_RETIRE_INTENT; activationId: string; generationKey: GenerationKey; expected_revision: string; retiredBy: DerivedRetiredBy;
+}
+
+async function waitAll(engine: BrainEngine, maintenance: MaintenanceAuthority, rows: WriteRequest[]): Promise<void> {
+ const wait = maintenance.wait ??= new MaintenanceWriteWait();
+ const config = loadConfig() ?? { engine: engine.kind };
+ for (const row of rows) {
+ try { writeResponse(wait.observe(await waitForWrite(engine, row, config as GBrainConfig, wait.ms()))); }
+ catch (error) { if (!acceptedPendingReceipt(error)) throw error; }
+ }
+}
+
+/** Admits a planned publication of an in-place kind: its activation, then one retire member per retired item. Returns the activation id. */
+export async function admitInPlaceGeneration(engine: BrainEngine, maintenance: MaintenanceAuthority, plan: Extract<ManagedPlan, { kind: 'publish' }>): Promise<string> {
+ const { writer, binding } = maintenance;
+ const { activationId, key, retiredBy } = plan.intent;
+ const retires: Array<{ slug: string; pageId: number; intent: RetireIntent }> = [];
+ for (const member of plan.members) {
+ const snapshot = await engine.readPageSnapshot(member.slug, { sourceId: key.sourceId });
+ if (member.action !== 'retire' || !snapshot) throw opError('page_identity_changed', 'A page the generation retires changed before admission.',
+ `${member.slug} in source ${key.sourceId} was removed or is not a retirement of activation ${activationId}; nothing was admitted. The next run plans again from the pages as they are.`);
+ await authorizeWrite(engine, writer, 'delete_page', member.slug);
+ retires.push({ slug: member.slug, pageId: Number(snapshot.page.id), intent: { kind: GENERATION_RETIRE_INTENT, activationId, generationKey: key,
+ expected_revision: snapshot.revision, retiredBy } });
+ }
+ const activation: ActivationIntent = { ...plan.intent, runKey: activationId };
+ const rows = await engine.transaction(async tx => {
+ await recordActivation(tx, plan.intent);
+ const admit = (slug: string, pageId: number | null, requestId: string, intent: Record<string, unknown>) => admitWriteInTransaction(tx, {
+ principal: writer.principal, authority: writer, operation: 'submit_job', sourceId: key.sourceId, sourceIncarnation: writer.sourceIncarnation,
+ worktreeId: binding?.worktree_id, topologyGeneration: binding?.topology_generation, slug, pageId, requestId, callerIntent: intent, intent });
+ const accepted = [await admit(GENERATION_ACTIVATE_SLUG, null, activationId, activation)];
+ for (const retire of retires) accepted.push(await admit(retire.slug, retire.pageId, memberRequestId(activationId, retire.slug, 'retire'), retire.intent));
+ return accepted;
+ });
+ await waitAll(engine, maintenance, rows);
+ return activationId;
+}
+
+/** Preparer of `managed_generation_retire` (trusted local only): the versioned page delete of one pending retirement. */
+export async function prepareGenerationRetireMember(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+ const p = row.intent as RetireIntent | null;
+ if (!p || p.kind !== GENERATION_RETIRE_INTENT || row.authority.remote || !p.generationKey || p.generationKey.sourceId !== row.source_id
+ || !generationAdapter(p.generationKey.kind)?.publishesInPlace) {
+ throw opError('permission_denied', 'Unsupported generation retirement request.',
+ `Request ${row.request_id} in source ${row.source_id} is not a generation retirement the trusted local writer admitted, so the coordinator refused it before any change. Retirements run only from the gbrain CLI on the brain host.`);
+ }
+ await assertMemberPending(engine, row, p.activationId, p.generationKey.kind);
+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
+ const prepared = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
+ return { ...prepared, validate: async tx => {
+ await assertMemberPending(tx, row, p.activationId, p.generationKey.kind);
+ await authorizeWrite(tx, row.authority, 'delete_page', row.slug);
+ await prepared.validate?.(tx);
+ }, apply: async tx => {
+ const result = await prepared.apply(tx);
+ if (!prepared.noop) {
+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [p.retiredBy, new Date().toISOString(), row.page_id, row.source_id]);
+ await settleMember(tx, p.activationId, row.slug);
+ }
+ return { ...result, retired_by: p.retiredBy, activation_id: p.activationId };
+ } };
+}
+
+/**
+ * Finishes the retire_pending items an earlier run of `kind` left in this source: a member still queued is waited on; one
+ * that ended without committing is submitted again under a fresh id bound to the failed one, unless its page changed
+ * since the activation planned it (then the page keeps its content and the mark clears). Returns how many it touched.
+ */
+export async function resumeRetireMembers(engine: BrainEngine, maintenance: MaintenanceAuthority, kind: string): Promise<number> {
+ const { writer, binding } = maintenance;
+ const pending = (await listPendingMembers(engine, [writer.sourceId], kind)).filter(member => member.action === 'retire');
+ const adapter = generationAdapter(kind)!;
+ for (const member of pending) {
+ let row = await getWriteRequest(engine, writer.principal, memberRequestId(member.activation_id, member.slug, 'retire'));
+ if (row && ['queued', 'running', 'recovering'].includes(row.state)) { await waitAll(engine, maintenance, [row]); row = await getWriteRequest(engine, writer.principal, row.request_id); }
+ if (row?.state === 'committed') continue;
+ const key: GenerationKey = { kind, sourceId: member.source_id, ownerKey: member.owner_key };
+ const snapshot = await engine.readPageSnapshot(member.slug, { sourceId: member.source_id });
+ const current = snapshot ? (await adapter.readItems(engine, key, [member.slug])).get(member.slug) : undefined;
+ if (!snapshot || !current?.live || current.identityHash !== member.identity) { await engine.transaction(tx => settleMember(tx, member.activation_id, member.slug)); continue; }
+ const prior = row?.intent as RetireIntent | undefined;
+ const intent: RetireIntent = { kind: GENERATION_RETIRE_INTENT, activationId: member.activation_id, generationKey: key, expected_revision: snapshot.revision,
+ retiredBy: prior?.retiredBy ?? adapter.retiredBy };
+ const resubmitted = await engine.transaction(tx => admitWriteInTransaction(tx, { principal: writer.principal, authority: writer, operation: 'submit_job',
+ sourceId: member.source_id, sourceIncarnation: writer.sourceIncarnation, worktreeId: binding?.worktree_id, topologyGeneration: binding?.topology_generation,
+ slug: member.slug, pageId: Number(snapshot.page.id), requestId: memberRequestId(member.activation_id, member.slug, `retire:after:${row?.id ?? 'missing'}`),
+ callerIntent: intent, intent }));
+ await waitAll(engine, maintenance, [resubmitted]);
+ }
+ return pending.length;
+}
diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.ts
index 026206fdbc..e4be494584 100644
--- a/src/core/generations/managed.ts
+++ b/src/core/generations/managed.ts
@@ -64,6 +64,8 @@ export interface ActivationPlanIntent {
/** The adapter context the activation reads the input and items with (atoms: the transcript file). */
context: unknown;
locator: string | null;
+ /** Completeness evidence the producer adds (PublishRequest.note). */
+ note?: Record<string, unknown>;
}
/** The journaled activation intent: the plan plus the run key its batch shares. */
export type ActivationIntent = ActivationPlanIntent & { runKey: string } & Record<string, unknown>;
@@ -102,20 +104,25 @@ export async function planManagedGeneration<C>(engine: BrainEngine, adapter: Gen
}
if (plan.kind === 'unchanged' && !request.items.length) return { kind: 'unchanged' };
const retires = plan.kind === 'publish' ? plan.retires : [];
+ // A kind whose producer already wrote its items (publishesInPlace) keeps each one live at its identity without a member.
+ const inPlace = adapter.publishesInPlace === true ? request.items.filter(item => { const row = rows.get(item.key); return row?.live && row.identityHash === item.identityHash; }) : [];
+ if (adapter.publishesInPlace && inPlace.length !== request.items.length) {
+ throw liveConflict(request.key, request.items.filter(item => !inPlace.includes(item)).map(item => item.key));
+ }
const members: Array<ActivationMember & { item?: ProposedItem }> = [
- ...request.items.map(item => { const row = rows.get(item.key);
+ ...request.items.filter(item => !inPlace.includes(item)).map(item => { const row = rows.get(item.key);
return row?.live ? { slug: item.key, action: 'overwrite' as const, identity: item.identityHash, before: row.identityHash, item,
...(adapter.databaseOnly && item.identityHash !== row.identityHash ? { preimage: row.preimage().json } : {}) }
: { slug: item.key, action: 'create' as const, identity: item.identityHash, before: null, item }; }),
...retires.map(slug => ({ slug, action: 'retire' as const, identity: rows.get(slug)!.identityHash, before: rows.get(slug)!.identityHash })),
];
const operationId = publishOperationId(planned as PublishRequest<unknown>, setHash);
- const kept = request.approved && plan.kind === 'publish' ? plan.kept : [];
+ const kept = request.approved && plan.kind === 'publish' ? plan.kept : inPlace.map(item => item.key);
return { kind: 'publish', members, intent: { kind: GENERATION_ACTIVATE_INTENT, activationId: activationRequestId(operationId, opts.scope ?? null), key: request.key,
expectedGeneration: planned.expectedGeneration!, input: request.input ?? input, operationId, setHash, runId: request.runId ?? null, partial: request.partial === true,
proof: request.proof ?? null, retiredBy: request.approved?.retiredBy ?? opts.retiredBy ?? adapter.retiredBy, approved: request.approved !== undefined,
members: members.map(({ item: _item, ...member }) => member), kept, carried: plan.kind === 'publish' ? plan.carried : [],
- context: request.context ?? null, locator: opts.locator ?? null } };
+ context: request.context ?? null, locator: opts.locator ?? null, ...(request.note ? { note: request.note } : {}) } };
}
/** Records an admitted activation and its members, in the admission transaction (before any member runs). */
@@ -173,7 +180,7 @@ export async function prepareGenerationActivation(engine: BrainEngine, row: Writ
];
if (databaseOnly) await adapter.retireItems(tx, p.key, p.members.filter(member => member.action === 'retire').map(member => member.slug), p.retiredBy);
const activated = await activateGeneration(tx, p.key, live, { operationId: p.operationId, runId: p.runId ?? undefined, input, setHash: p.setHash,
- completeness: { complete: !p.partial, proof: p.proof?.kind ?? null, managed: true, ...(p.approved ? { approved: p.retiredBy } : {}) },
+ completeness: { complete: !p.partial, proof: p.proof?.kind ?? null, managed: true, ...(p.approved ? { approved: p.retiredBy } : {}), ...p.note },
activationId: p.activationId, locator: p.locator }, items);
await tx.executeRaw(`UPDATE derived_generation_activations SET state='activated', generation_id=$2, updated_at=now() WHERE id=$1`, [p.activationId, activated.id]);
const retires = p.members.filter(member => member.action === 'retire').length;
diff --git a/src/core/generations/plan.ts b/src/core/generations/plan.ts
index 7307512b83..109cf35773 100644
--- a/src/core/generations/plan.ts
+++ b/src/core/generations/plan.ts
@@ -25,6 +25,11 @@ export interface PlanInput {
input: InputState | null;
config: GenerationsConfig;
modelProduced: boolean;
+ /**
+ * The producer wrote the proposal itself under new keys (publishesInPlace: synthesis): the floor measures the result
+ * against the live generation's items alone, never against the outputs this run just wrote.
+ */
+ inPlace?: boolean;
strictOrder?: boolean;
/** A partial result (input cut short): writes its items, retires nothing. */
additive: boolean;
@@ -73,8 +78,9 @@ export function planGeneration(input: PlanInput): Plan {
if (!proposal.length && retires.length && !input.proofHolds) return held('no_proof');
if (Math.max(puts.length, retires.length) > config.maxItems) return held('oversize', { max_items: config.maxItems });
const shrinkReleased = input.release === 'shrunk' || input.release === 'attempts_exhausted';
- if (input.modelProduced && !input.additive && !shrinkReleased && proposal.length && retires.length && proposal.length < ownedBefore.size
- && proposal.length < config.shrinkFloor * ownedBefore.size * ratio) return held('shrunk');
+ const floorBase = input.inPlace ? recorded.size : ownedBefore.size;
+ if (input.modelProduced && !input.additive && !shrinkReleased && proposal.length && retires.length && proposal.length < floorBase
+ && proposal.length < config.shrinkFloor * floorBase * ratio) return held('shrunk');
if (retires.length) {
const total = (input.release === 'valve' ? 0 : input.valve.windowRetired) + retires.length;
const ratioLimit = config.valveMaxRatio * Math.max(input.valve.ownedTotal, ownedBefore.size);
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.ts
index 330e490d27..1558b8a44b 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -44,6 +44,8 @@ export interface PublishRequest<C = unknown> {
onRetired?: (tx: BrainEngine, retired: readonly string[]) => Promise<void>;
/** A transcript key's current file, recorded on the generation so a moved file keeps its key. */
locator?: string;
+ /** Recorded on the generation's completeness evidence (synthesis: the earlier outputs it left live, for the cleanup listing). */
+ note?: Record<string, unknown>;
}
export type PublishOutcome =
@@ -222,7 +224,7 @@ export async function planPublication<C>(db: BrainEngine, adapter: GenerationAda
const valve = await readValve(db, key, request.runId);
const proven = request.proof?.kind === 'originIneligible' ? await adapter.proofHolds?.(db, key, request.proof) === true
: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false;
- const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, strictOrder: adapter.strictOrder, additive: request.partial === true,
+ const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, inPlace: adapter.publishesInPlace, strictOrder: adapter.strictOrder, additive: request.partial === true,
proofHolds: proven, evidence, valve, release: request.release?.reason, approvedRetire: request.approved?.retire, approvedExpect: request.approved?.expect });
return { input, rows, plan };
}
@@ -277,7 +279,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
await faultPoint('generation:retired', { sourceId: key.sourceId, operation: key.kind });
const activated = await activateGeneration(tx, key, live, { operationId, runId: request.runId, input, setHash, locator: request.locator,
completeness: { complete: !request.partial, proof: request.proof?.kind ?? null, released: request.release?.reason ?? null,
- ...(request.approved ? { approved: request.approved.retiredBy } : {}) } }, ledgerItems(plan, rows, live));
+ ...(request.approved ? { approved: request.approved.retiredBy } : {}), ...request.note } }, ledgerItems(plan, rows, live));
if (plan.retires.length) await bumpValve(tx, key, request.runId, plan.retires.length);
return { state: 'published', generationId: activated.id, generation: activated.generation, puts: plan.puts.map(item => item.key), kept: plan.kept,
adopted: plan.adopted, retired: plan.retires, protected: plan.protectedKeys } satisfies PublishOutcome;
diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.ts
index aab218d3fa..ef3a10d4a9 100644
--- a/src/core/generations/repair.ts
+++ b/src/core/generations/repair.ts
@@ -13,7 +13,10 @@
* - cleanup: lists what a managed source's activations left behind (GBRA-161 PR 1b): items an activated generation still
* waits on a member request for (resumed by the next extraction run) and orphan candidates (pages a `create` member
* wrote for an activation that never happened), each with its activation id. It is preview-only: an orphan is never
- * retired automatically. The synthesis unmatched-predecessor retire joins this mode in PR 4.
+ * retired automatically. A kind whose producer publishes in place (synthesis, GBRA-161 PR 4) also lists each earlier
+ * output a live generation left live because the re-synthesis did not match it (`unmatched_predecessor`, with why and
+ * what it still holds alone); `--apply --expect <hash> --yes` retires exactly the previewed ones (`retired_by:
+ * synthesis-cleanup`, versioned, restorable through the restore mode). Pending members and orphans stay list-only.
*
* Explicit-only, preview-bound, destructive consent: the preview saves the set under its hash and `--apply --expect <hash>
* --yes` applies exactly that set, rechecking each key under its locks (`changed_since_preview` otherwise).
@@ -32,7 +35,9 @@ import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcom
import { generationAdapter, generationKinds } from './adapters/index.ts';
import { readGenerationsConfig, restoreDaysHint } from './config.ts';
import { RELEASABLE_HELD_REASONS, type GenerationAdapter, type GenerationKey, type HeldReason, type ProposedItem } from './contract.ts';
-import { listOrphanCandidates, listPendingMembers, requestUuid } from './managed.ts';
+import { listOrphanCandidates, listPendingMembers, planManagedGeneration, requestUuid } from './managed.ts';
+import { admitInPlaceGeneration } from './managed-retire.ts';
+import { SYNTHESIS_CLEANUP_RETIRED_BY } from './adapters/synthesis.ts';
import { activateGeneration, assertItemsLive, itemSetHash, lockGeneration, publishGeneration, readLiveGeneration, type LedgerItem } from './publish.ts';
export const GENERATION_MODES = ['restore', 'release-held', 'cleanup'] as const;
@@ -84,7 +89,10 @@ interface ReleaseEntry {
attempts: number; proposal_bytes: number | null; items: number; refused: string[];
}
interface CleanupEntry {
- mode: 'cleanup'; id: number; source_id: string; owner_key: string; slug: string; activation_id: string; state: 'pending_overwrite' | 'retire_pending' | 'orphan_candidate'; refused: string[];
+ mode: 'cleanup'; id: number; source_id: string; owner_key: string; slug: string; activation_id: string;
+ state: 'pending_overwrite' | 'retire_pending' | 'orphan_candidate' | 'unmatched_predecessor'; refused: string[];
+ /** unmatched_predecessor: the live generation that left it, its identity at preview, why it was not matched and what it holds alone. */
+ generation_id?: number; identity?: string; why?: string; missing?: { claims: number; quotes: number; citations: number } | null;
}
type Entry = RestoreEntry | ReleaseEntry | CleanupEntry;
interface EntryItem extends RepairItem { entry: Entry; hash: string; last: boolean; selection: GenerationsSelection }
@@ -131,6 +139,28 @@ async function planRestore(db: BrainEngine, adapter: GenerationAdapter<unknown>,
return { target, revive: revive.sort(), retire: retire.sort(), refused: refused.sort(), preimages, rows };
}
+/** The earlier outputs live generations of an in-place kind left live unmatched, still live, unedited and still theirs. */
+async function unmatchedPredecessors(db: BrainEngine, adapter: GenerationAdapter<unknown>, sources: string[], selection: GenerationsSelection) {
+ const params: unknown[] = [sources, adapter.kind];
+ const where = selectorSql(selection, params, 'g');
+ const rows = await db.executeRaw<{ id: number; source_id: string; owner_key: string; activation_id: string | null; unmatched: Array<{ slug: string; why: string; missing: CleanupEntry['missing'] }> }>(
+ `SELECT g.id, g.source_id, g.owner_key, g.activation_id, g.completeness->'unmatched' AS unmatched FROM derived_generations g
+ WHERE g.source_id = ANY($1::text[]) AND g.kind = $2 AND g.state = 'live' AND jsonb_typeof(g.completeness->'unmatched') = 'array'${where} ORDER BY g.id`, params);
+ const out: Array<Omit<CleanupEntry, 'mode' | 'id' | 'refused'>> = [];
+ for (const row of rows) {
+ const key = keyOf(adapter.kind, row.source_id, row.owner_key);
+ const live = await readLiveGeneration(db, key);
+ const items = await adapter.readItems(db, key, row.unmatched.map(entry => entry.slug));
+ for (const entry of row.unmatched) {
+ const item = items.get(entry.slug);
+ if (!item?.live || live?.items.get(entry.slug) !== item.identityHash) continue;
+ out.push({ source_id: row.source_id, owner_key: row.owner_key, slug: entry.slug, activation_id: row.activation_id ?? `generation:${row.id}`,
+ state: 'unmatched_predecessor', generation_id: Number(row.id), identity: item.identityHash, why: entry.why, missing: entry.missing });
+ }
+ }
+ return out;
+}
+
async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown>, sources: string[], selection: GenerationsSelection, id?: number): Promise<Entry[]> {
const params: unknown[] = [sources, adapter.kind];
if (selection.mode === 'cleanup') {
@@ -144,6 +174,7 @@ async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown
...pending.map(row => ({ source_id: row.source_id, owner_key: row.owner_key, slug: row.slug, activation_id: row.activation_id,
state: row.action === 'retire' ? 'retire_pending' as const : 'pending_overwrite' as const })),
...orphans.map(row => ({ source_id: row.source_id, owner_key: row.owner_key, slug: row.slug, activation_id: row.activation_id, state: 'orphan_candidate' as const })),
+ ...(adapter.publishesInPlace ? await unmatchedPredecessors(db, adapter, sources, selection) : []),
].map((row, index) => ({ mode: 'cleanup' as const, id: index + 1, ...row, refused: [] }));
}
if (selection.mode === 'restore') {
@@ -178,6 +209,10 @@ async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown
function describeEntry(entry: Entry): string {
const refused = entry.refused.length ? `; refused: ${entry.refused.join(', ')}` : '';
+ if (entry.mode === 'cleanup' && entry.state === 'unmatched_predecessor') {
+ const missing = entry.missing ? `; holds alone ${entry.missing.claims} claim(s), ${entry.missing.quotes} quote(s), ${entry.missing.citations} citation(s)` : '';
+ return `unmatched predecessor ${entry.slug} (generation ${entry.generation_id}, ${entry.why === 'no_subject' ? 'no successor on the same subject' : entry.why === 'unreadable' ? 'its body was not compared (segmented)' : 'the successor does not cover it'}${missing}), live until you retire it`;
+ }
if (entry.mode === 'cleanup') return `${entry.state.replace('_', ' ')} ${entry.slug} (activation ${entry.activation_id})${entry.state === 'orphan_candidate' ? ', never retired automatically' : ', resumed by the next extraction run'}`;
if (entry.mode === 'release-held') return `held ${entry.reason}, ${entry.items} item(s), ${entry.attempts} attempt(s)${refused}`;
return `generation ${entry.generation} back to ${entry.restore_to}: revive ${entry.revive.length}, retire ${entry.retire.length}${refused}`;
@@ -220,7 +255,7 @@ export const generationsRepair: RepairHandler = {
listing: entries.map(entry => ({ item: `${entry.source_id}:${entry.mode === 'cleanup' ? entry.slug : entry.owner_key}`,
class: entry.mode === 'cleanup' ? entry.state : entry.refused.length ? 'refused' : entry.mode, detail: describeEntry(entry) })) };
}
- if (selection.mode === 'cleanup') {
+ if (selection.mode === 'cleanup' && !adapter.publishesInPlace) {
throw new OperationError('invalid_params', `gbrain repair generations --mode cleanup only lists pending members and orphan candidates for --kind ${selection.kind}; there is nothing to apply.`,
`Pending members resume on the next extraction run of their source. An orphan candidate is never retired automatically: show the user ${command} and delete one only if they decide to.`,
'docs/guides/repair.md#generations');
@@ -254,7 +289,8 @@ export const generationsRepair: RepairHandler = {
async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unknown>, approved: Entry, selection: GenerationsSelection): Promise<RepairItemOutcome> {
const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
- if (approved.mode === 'cleanup') return { applied: false, outcome: 'refused', reason: `${approved.slug}: cleanup entries are listed, never applied` };
+ if (approved.mode === 'cleanup' && approved.state === 'unmatched_predecessor') return retireUnmatched(ctx.engine, adapter, approved);
+ if (approved.mode === 'cleanup') return { applied: false, outcome: 'listed', reason: `${approved.slug}: ${approved.state.replace('_', ' ')} entries are listed, never applied` };
if (approved.refused.length) return { applied: false, outcome: 'refused', reason: approved.refused.join(', ') };
const key = keyOf(adapter.kind, approved.source_id, approved.owner_key);
if (approved.mode === 'release-held') {
@@ -280,6 +316,35 @@ async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unkn
return { applied: true, outcome: 'restored', detail: { generation: restored.generation, restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length } };
}
+/**
+ * GBRA-161 PR 4: the operator's retirement of one previewed unmatched predecessor, as an approved retirement of its key
+ * (versioned, `retired_by: synthesis-cleanup`, bound to the identity the preview showed). Unmanaged: one transaction, its
+ * file removed after when the database holds everything in it; managed: one activation and its retire member through the writer.
+ */
+async function retireUnmatched(engine: BrainEngine, adapter: GenerationAdapter<unknown>, approved: CleanupEntry): Promise<RepairItemOutcome> {
+ const key = keyOf(adapter.kind, approved.source_id, approved.owner_key);
+ const changed = (why: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason: `${approved.slug}: ${why}` });
+ const live = await readLiveGeneration(engine, key);
+ if (!approved.identity || live?.items.get(approved.slug) !== approved.identity) return changed('the page or its generation changed since the preview');
+ const request = { key, items: [], runId: `cleanup:${approved.generation_id}:${approved.slug}`,
+ approved: { retire: [approved.slug], retiredBy: SYNTHESIS_CLEANUP_RETIRED_BY, expect: { [approved.slug]: approved.identity } } };
+ if (await managedPersistenceEnabled(engine)) {
+ const { maintenancePreflight } = await import('../persistence/prepared-maintenance.ts');
+ const authority = await maintenancePreflight(engine, key.sourceId);
+ if (!authority) return { applied: false, outcome: 'refused', reason: `${approved.slug}: the source is no longer managed; preview again` };
+ const plan = await planManagedGeneration(engine, adapter, request, { retiredBy: SYNTHESIS_CLEANUP_RETIRED_BY });
+ if (plan.kind !== 'publish') return changed(plan.kind === 'held' ? `held (${plan.outcome.reason})` : 'nothing left to retire');
+ await admitInPlaceGeneration(engine, authority, plan);
+ return { applied: true, outcome: 'retired', detail: { retired_by: SYNTHESIS_CLEANUP_RETIRED_BY } };
+ }
+ const outcome = await publishGeneration(engine, adapter, request);
+ if (outcome.state === 'held') return { applied: false, outcome: 'refused', reason: `${approved.slug}: held (${outcome.reason})` };
+ if (outcome.state !== 'published' || !outcome.retired.includes(approved.slug)) return changed('the page changed since the preview');
+ const { removeDreamPageFile } = await import('../cycle/derived-write-through.ts');
+ const file = await removeDreamPageFile(engine, '', approved.slug, key.sourceId, '');
+ return { applied: true, outcome: 'retired', detail: { generation: outcome.generation, retired_by: SYNTHESIS_CLEANUP_RETIRED_BY, ...(file.held ? { file_held: file.held } : {}) } };
+}
+
/** The approved restore of one key, under its locks in the caller's transaction: 'changed', the refused keys, or the new generation. */
async function restoreGeneration(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, approved: RestoreEntry): Promise<'changed' | string[] | { generation: number }> {
const live = await readLiveGeneration(tx, key);
diff --git a/src/core/generations/synthesis-coverage.ts b/src/core/generations/synthesis-coverage.ts
new file mode 100644
index 0000000000..8834a2f9eb
--- /dev/null
+++ b/src/core/generations/synthesis-coverage.ts
@@ -0,0 +1,91 @@
+/**
+ * GBRA-161 PR 4 (#7065, plan D3 and CEO-outside r3 F3): when one synthesis output of a transcript may retire because a
+ * re-synthesis replaced it. Pure. An earlier output is matched, and so retires at activation, only when it is an exact
+ * duplicate of a page of the new generation, or when both hold:
+ * - subject: a page of the new generation has the same normalized subject stem, its slug without the hash suffix
+ * (and the date the prompt puts in front of the topic), or the same lowercased title tokens;
+ * - coverage: every claim unit (each sentence outside a quote), every verbatim quote (a `>` block or a quoted span) and
+ * every citation (wikilink or link target) of the earlier page appears in some page of the new generation.
+ * Anything else is unmatched: it stays live and `gbrain repair generations --kind synthesis --mode cleanup` lists it.
+ */
+
+export interface SynthesisPage { slug: string; title: string; body: string }
+
+export type PredecessorMatch =
+ | { matched: true; why: 'duplicate' | 'covered'; successor: string }
+ | { matched: false; why: 'no_subject' | 'uncovered'; missing: { claims: number; quotes: number; citations: number } };
+
+const HASH_SUFFIX = /-[0-9a-f]{6}(?:-c\d+)?$/;
+const DATE_PREFIX = /^\d{4}-\d{2}-\d{2}-/;
+
+/** The slug without its transcript hash suffix and the date the synthesis prompt puts before the topic. */
+export function subjectStem(slug: string): string {
+ const segments = slug.toLowerCase().replace(HASH_SUFFIX, '').split('/');
+ segments[segments.length - 1] = segments[segments.length - 1]!.replace(DATE_PREFIX, '');
+ return segments.join('/');
+}
+
+/** The lowercased title words, as a sorted set. */
+export function titleTokens(title: string): string {
+ return [...new Set(title.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])].sort().join(' ');
+}
+
+/** Text compared for coverage: link syntax reduced to its visible text, markdown emphasis and case dropped, spacing collapsed. */
+export function normalizeText(text: string): string {
+ return text.normalize('NFKC')
+ .replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"')
+ .replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2').replace(/\[\[([^\]]+)\]\]/g, '$1')
+ .replace(/\[([^\]]*)\]\(([^)]*)\)/g, '$1')
+ .replace(/[*_`~]/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
+}
+
+const unit = (text: string) => normalizeText(text).replace(/^[-+*•]\s+/, '').replace(/^\d+[.)]\s+/, '').replace(/[\s.!?;:,]+$/, '');
+
+/** The citation targets of a body: wikilink targets and link targets. */
+export function citations(body: string): string[] {
+ const out = new Set<string>();
+ for (const m of body.matchAll(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g)) out.add(m[1]!.trim().toLowerCase());
+ for (const m of body.matchAll(/\[[^\]]*\]\(([^)\s]+)[^)]*\)/g)) out.add(m[1]!.trim().toLowerCase());
+ return [...out].sort();
+}
+
+/** The verbatim quotes of a body: each `>` block and each double-quoted span of three or more words. */
+export function quotes(body: string): string[] {
+ const out: string[] = [];
+ let block: string[] = [];
+ const flush = () => { if (block.length) out.push(unit(block.join(' '))); block = []; };
+ for (const line of body.split('\n')) {
+ const m = /^\s*>\s?(.*)$/.exec(line);
+ if (m) block.push(m[1]!); else flush();
+ }
+ flush();
+ const prose = body.split('\n').filter(line => !/^\s*>/.test(line)).join('\n').replace(/[\u201C\u201D]/g, '"');
+ for (const m of prose.matchAll(/"([^"\n]+)"/g)) if ((m[1]!.match(/[\p{L}\p{N}]+/gu) ?? []).length >= 3) out.push(unit(m[1]!));
+ return out.filter(Boolean);
+}
+
+/** The claim units of a body: every sentence outside quote blocks and headings. */
+export function claimUnits(body: string): string[] {
+ const prose = body.split('\n').filter(line => !/^\s*>/.test(line) && !/^\s*#/.test(line)).join('\n');
+ return prose.split(/\n+|(?<=[.!?])\s+/).map(unit).filter(text => /[\p{L}\p{N}]/u.test(text));
+}
+
+/** Whether `earlier` may retire now that `successors` (the new generation's pages) are live. */
+export function matchPredecessor(earlier: SynthesisPage, successors: readonly SynthesisPage[]): PredecessorMatch {
+ const body = normalizeText(earlier.body);
+ const duplicate = successors.find(page => normalizeText(page.body) === body);
+ if (duplicate) return { matched: true, why: 'duplicate', successor: duplicate.slug };
+ const stem = subjectStem(earlier.slug);
+ const tokens = titleTokens(earlier.title);
+ const subject = successors.find(page => subjectStem(page.slug) === stem || (tokens !== '' && titleTokens(page.title) === tokens));
+ const corpus = successors.map(page => normalizeText(page.body)).join('\n');
+ const cited = new Set(successors.flatMap(page => citations(page.body)));
+ const missing = {
+ claims: claimUnits(earlier.body).filter(text => !corpus.includes(text)).length,
+ quotes: quotes(earlier.body).filter(text => !corpus.includes(text)).length,
+ citations: citations(earlier.body).filter(target => !cited.has(target)).length,
+ };
+ if (!subject) return { matched: false, why: 'no_subject', missing };
+ if (missing.claims || missing.quotes || missing.citations) return { matched: false, why: 'uncovered', missing };
+ return { matched: true, why: 'covered', successor: subject.slug };
+}
diff --git a/src/core/persistence/derived-retirement-hold.ts b/src/core/persistence/derived-retirement-hold.ts
index e33ce6e50b..22cc20e89c 100644
--- a/src/core/persistence/derived-retirement-hold.ts
+++ b/src/core/persistence/derived-retirement-hold.ts
@@ -15,7 +15,7 @@ import { maintenanceTransaction } from './attribution.ts';
import { GENERATION_BOUNDS, RESTORE_DAYS_SQL } from '../generations/config.ts';
/** The `retired_by` stamps derived writers put on the pages they retire. */
-export const DERIVED_RETIRED_BY = ['extract-atoms', 'managed-reextract', 'stale-atoms', 'life-chronicle', 'generation-restore'] as const;
+export const DERIVED_RETIRED_BY = ['extract-atoms', 'managed-reextract', 'stale-atoms', 'life-chronicle', 'generation-restore', 'synthesis-resynthesis', 'synthesis-cleanup'] as const;
export type DerivedRetiredBy = typeof DERIVED_RETIRED_BY[number];
/** The unmanaged extract_atoms retirement of atoms a completed re-extraction did not reproduce. */
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 4619103d9a..54387db536 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -89,6 +89,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_atom_')) return (await import('./atom-maintenance.ts')).prepareManagedAtomMutation(e, row, cfg);
if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_activate') return (await import('../generations/managed.ts')).prepareGenerationActivation(e, row);
if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_restore') return (await import('../generations/repair.ts')).prepareGenerationRestore(e, row);
+ if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_retire') return (await import('../generations/managed-retire.ts')).prepareGenerationRetireMember(e, row, cfg);
if (row.operation === 'extract_facts' && String(row.intent?.kind).startsWith('managed_facts_')) return (await import('./facts-prepare.ts')).prepareManagedFactsMutation(e, row, cfg);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('connector_v2_')) return (await import('./connector-sync.ts')).prepareConnectorMutation(e, row);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_connector_')) return (await import('./connector-sync.ts')).prepareOutdatedConnectorMutation(e, row);
diff --git a/test/e2e/g4-synthesis-resynthesis-7065-postgres.test.ts b/test/e2e/g4-synthesis-resynthesis-7065-postgres.test.ts
new file mode 100644
index 0000000000..f2d093e36f
--- /dev/null
+++ b/test/e2e/g4-synthesis-resynthesis-7065-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/g4-synthesis-resynthesis-7065.test.ts'));
diff --git a/test/pathological/g4-synthesis-resynthesis-7065.test.ts b/test/pathological/g4-synthesis-resynthesis-7065.test.ts
new file mode 100644
index 0000000000..5bedd8d8a2
--- /dev/null
+++ b/test/pathological/g4-synthesis-resynthesis-7065.test.ts
@@ -0,0 +1,254 @@
+/**
+ * GBRA-161 PR 4 (#7065): a re-synthesis replaces the earlier outputs of the same transcript only on a complete result,
+ * always version first, always reversible. Real synthesize phase runs (oneshot children through the existing chat
+ * transport stub, no paid calls) on PGLite and Postgres: the matched earlier output retires at activation, an unmatched
+ * one stays live and is listed for cleanup, a chunk failure retires nothing, a restore brings the earlier output back,
+ * \`generations.synthesis.retire_previous=false\` retires nothing, and an output from before the ledger is never adopted.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { appendFileSync, existsSync, 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 { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let dataDir: string;
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ __setMaintenanceWriteWaitForTests(5_000);
+ dataDir = mkdtempSync(join(tmpdir(), 'gbrain-g4-resynth-db-'));
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ 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 () => {
+ __setMaintenanceWriteWaitForTests(null);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ resetGateway();
+ rmSync(dataDir, { recursive: true, force: true });
+});
+
+const usage = { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 };
+const PREFIX = 'wiki/personal/reflections';
+const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+const SINCE = new Date(Date.now() - 86_400_000).toISOString();
+
+interface Fixture { engine: BrainEngine; sourceId: string; root: string; corpus: string; transcript: string; managed: boolean }
+/** What the fake model writes for one child: the slug stem and body per page, keyed by the hash suffix the prompt names. */
+type Writer = (hash: string) => Array<{ stem: string; title: string; body: string }> | 'fail';
+
+const TRANSCRIPT = '[user]\nWe moved the storage plan to object storage and we charge for durability.\n\n' + '[assistant]\nNoted, discussing the roadmap.\n\n'.repeat(15);
+
+async function fixture(managed: boolean, run: (f: Fixture) => Promise<void>) {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-g4-resynth-'));
+ const f: Fixture = { engine, sourceId: `resynth-${randomUUID().slice(0, 8)}`, root: join(dir, 'brain'), corpus: join(dir, 'corpus'), transcript: '', managed };
+ f.transcript = join(f.corpus, 'sess-a.txt');
+ for (const path of [f.root, f.corpus]) mkdirSync(path);
+ writeFileSync(f.transcript, TRANSCRIPT);
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), ANTHROPIC_API_KEY: 'sk-test-resynth' }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [f.sourceId, f.root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('generations.synthesis.retire_previous', 'true');
+ await claimWorktree(engine, f.sourceId, f.root);
+ for (const [key, value] of Object.entries({
+ 'dream.synthesize.enabled': 'true', 'dream.synthesize.cooldown_hours': '0', 'dream.synthesize.min_chars': '100',
+ 'dream.synthesize.link_manifest': 'false', 'dream.synthesize.mode': 'oneshot', 'dream.synthesize.session_corpus_dir': f.corpus,
+ 'dream.synthesize.quote_verify': 'false', 'dream.synthesize.budget_usd': 'unlimited',
+ 'models.dream.synthesize': 'anthropic:claude-sonnet-4-6', 'models.dream.triage': 'anthropic:claude-sonnet-4-6', 'agent.use_gateway_loop': 'true',
+ })) await engine.setConfig(key, value);
+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await run(f);
+ });
+ } finally {
+ __setChatTransportForTests(null);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+/** One synthesize run whose children write what \`writer\` returns; a 'fail' child mangles its oneshot and its fallback write is refused (dead). */
+async function synthesize(f: Fixture, writer: Writer) {
+ const failTurns = new Map<string, number>();
+ __setChatTransportForTests(async opts => {
+ const mk = (text: string, blocks: unknown[] = [{ type: 'text', text }], stop = 'end') =>
+ ({ text, blocks, stopReason: stop, usage, model: opts.model!, providerId: 'anthropic' }) as never;
+ if ((opts.system ?? '').startsWith('You triage a conversation transcript')) {
+ return mk(JSON.stringify({ score: 0.9, content_type: 'reflection', segments: [{ quote: 'we charge for durability', note: 'evidence' }], entities: [], reasons: ['durable insight'] }));
+ }
+ const convo = JSON.stringify(opts.messages);
+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(convo)?.[1] ?? 'missing';
+ const pages = writer(hash);
+ if (pages === 'fail') {
+ const turn = (failTurns.get(hash) ?? 0) + 1;
+ failTurns.set(hash, turn);
+ if (turn === 1) return mk('here you go! pages!');
+ if (turn === 2) return mk('', [{ type: 'tool-call', toolCallId: `tc-${hash}`, toolName: 'brain_put_page', input: { slug: 'notallowed/sneaky-page', content: 'nope' } }], 'tool_calls');
+ return mk('done');
+ }
+ return mk(JSON.stringify({ pages: pages.map(p => ({ slug: `${PREFIX}/${p.stem}-${hash}`, title: p.title, type: 'note', body: p.body })), skipped: false }));
+ });
+ const result = await runPhaseSynthesize(f.engine, { brainDir: f.root, sourceId: f.sourceId, dryRun: false });
+ __setChatTransportForTests(null);
+ return result;
+}
+
+/** Grows the transcript, so the next run re-synthesizes it under a new content hash (same path, same transcript key). */
+const grow = (f: Fixture, turn: string) => appendFileSync(f.transcript, `[user]\n${turn}\n\n`);
+
+async function pages(f: Fixture) {
+ return f.engine.executeRaw<{ slug: string; deleted: boolean; retired_by: string | null; versions: number }>(
+ `SELECT p.slug, p.deleted_at IS NOT NULL AS deleted, p.frontmatter->>'retired_by' AS retired_by,
+ (SELECT count(*)::int FROM page_versions v WHERE v.page_id = p.id) AS versions
+ FROM pages p WHERE p.source_id = $1 AND p.slug LIKE $2 ORDER BY p.slug`, [f.sourceId, `${PREFIX}/%`]);
+}
+const live = async (f: Fixture) => (await pages(f)).filter(p => !p.deleted).map(p => p.slug);
+const byStem = async (f: Fixture, stem: string) => (await pages(f)).filter(p => p.slug.startsWith(`${PREFIX}/${stem}-`));
+
+async function repair(f: Fixture, mode: 'restore' | 'cleanup', apply?: string) {
+ const scope = await resolveRepairScope(f.engine, f.sourceId);
+ return (await repairRunner(f.engine, { apply: apply !== undefined, logger: quiet })).run('generations', scope,
+ { explicit: true, sourceFlag: f.sourceId, ...(apply ? { expect: apply, yes: true } : {}), generations: { kind: 'synthesis', mode, since: SINCE } } as never);
+}
+
+const PLAN = 'The storage plan moved to object storage.\n\n> we charge for durability\n\nDecided with [[people/alice-example]].';
+const PLAN_COVERED = PLAN + '\n\nThe team also set a weekly review of the storage costs.';
+
+for (const managed of [false, true]) describe(`${managed ? 'managed' : 'unmanaged'} re-synthesis (#7065)`, () => {
+ test('a complete re-synthesis retires the earlier output it covers: versioned, stamped synthesis-resynthesis, file removed', async () => {
+ await fixture(managed, async f => {
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);
+ const [first] = await byStem(f, 'storage-plan');
+ expect(first?.deleted).toBe(false);
+ if (!managed) expect(existsSync(join(f.root, `${first!.slug}.md`))).toBe(true);
+ grow(f, 'We also agreed on a weekly review of the storage costs.');
+ const result = await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ const after = await byStem(f, 'storage-plan');
+ expect(after).toHaveLength(2);
+ const earlier = after.find(p => p.slug === first!.slug)!;
+ const successor = after.find(p => p.slug !== first!.slug)!;
+ expect(successor.deleted).toBe(false);
+ expect({ deleted: earlier.deleted, retired_by: earlier.retired_by }).toEqual({ deleted: true, retired_by: 'synthesis-resynthesis' });
+ expect(earlier.versions).toBeGreaterThan(0);
+ expect((result.details as { synthesis_generations?: { retired: string[] } }).synthesis_generations?.retired).toEqual([first!.slug]);
+ if (!managed) expect(existsSync(join(f.root, `${first!.slug}.md`))).toBe(false);
+ });
+ }, 180_000);
+});
+
+describe('unmanaged re-synthesis (#7065): what stays live', () => {
+ test('an earlier output holding an unquoted claim the successor lacks stays live; cleanup lists it and retires it only on apply', async () => {
+ await fixture(false, async f => {
+ const unique = 'The storage budget is capped at four hundred dollars a month.';
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: `${PLAN}\n\n${unique}` }]);
+ const [first] = await byStem(f, 'storage-plan');
+ grow(f, 'We also agreed on a weekly review of the storage costs.');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ expect((await live(f)).filter(slug => slug.includes('storage-plan'))).toHaveLength(2);
+ const preview = await repair(f, 'cleanup');
+ const listing = (preview as unknown as { listing?: Array<{ item: string; class: string; detail: string }> }).listing ?? [];
+ expect(listing.map(row => [row.item, row.class])).toEqual([[`${f.sourceId}:${first!.slug}`, 'unmatched_predecessor']]);
+ expect(listing[0]!.detail).toContain('holds alone 1 claim(s), 0 quote(s), 0 citation(s)');
+ expect((await byStem(f, 'storage-plan')).find(p => p.slug === first!.slug)?.deleted).toBe(false);
+ await repair(f, 'cleanup', preview.preview_hash!);
+ const earlier = (await byStem(f, 'storage-plan')).find(p => p.slug === first!.slug)!;
+ expect({ deleted: earlier.deleted, retired_by: earlier.retired_by }).toEqual({ deleted: true, retired_by: 'synthesis-cleanup' });
+ });
+ }, 180_000);
+
+ test('a chunk failure holds the generation partial and retires nothing; the next complete run retires it', async () => {
+ await fixture(false, async f => {
+ await f.engine.setConfig('dream.synthesize.max_prompt_tokens', '100000');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);
+ const [first] = await byStem(f, 'storage-plan');
+ grow(f, `We also agreed on a weekly review of the storage costs.\n\n${'[assistant]\nA long digression about the roadmap and its many milestones.\n\n'.repeat(6_000)}`);
+ const partial = await synthesize(f, hash => hash.endsWith('-c1') ? 'fail' : [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ const outcomes = (partial.details as { child_outcomes: Array<{ status: string }> }).child_outcomes.map(o => o.status).sort();
+ expect(outcomes).toEqual(['completed', 'dead']);
+ expect((await byStem(f, 'storage-plan')).find(p => p.slug === first!.slug)?.deleted).toBe(false);
+ expect((partial.details as { synthesis_generations: { partial: number; retired: string[] } }).synthesis_generations).toMatchObject({ partial: 1, retired: [] });
+ const done = await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ expect((done.details as { synthesis_generations: { retired: string[] } }).synthesis_generations.retired).toEqual([first!.slug]);
+ });
+ }, 300_000);
+
+ test('restore brings the retired earlier output back and retires the successor, both versioned', async () => {
+ await fixture(false, async f => {
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);
+ const [first] = await byStem(f, 'storage-plan');
+ grow(f, 'We also agreed on a weekly review of the storage costs.');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ const successor = (await live(f)).find(slug => slug.includes('storage-plan'))!;
+ expect(successor).not.toBe(first!.slug);
+ const preview = await repair(f, 'restore');
+ await repair(f, 'restore', preview.preview_hash!);
+ const after = await byStem(f, 'storage-plan');
+ expect(after.find(p => p.slug === first!.slug)?.deleted).toBe(false);
+ expect(after.find(p => p.slug === successor)).toMatchObject({ deleted: true, retired_by: 'generation-restore' });
+ const [body] = await f.engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, first!.slug]);
+ expect(body!.compiled_truth).toContain('The storage plan moved to object storage.');
+ });
+ }, 180_000);
+
+ test('generations.synthesis.retire_previous=false retires nothing; switched back on, the next re-synthesis retires', async () => {
+ await fixture(false, async f => {
+ await f.engine.setConfig('generations.synthesis.retire_previous', 'false');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);
+ const [first] = await byStem(f, 'storage-plan');
+ grow(f, 'We also agreed on a weekly review of the storage costs.');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ expect((await live(f)).filter(slug => slug.includes('storage-plan'))).toHaveLength(2);
+ await f.engine.setConfig('generations.synthesis.retire_previous', 'true');
+ grow(f, 'Nothing else changed.');
+ const on = await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ expect((on.details as { synthesis_generations: { retired: string[] } }).synthesis_generations.retired.sort())
+ .toEqual((await byStem(f, 'storage-plan')).filter(p => p.deleted).map(p => p.slug).sort());
+ expect((await byStem(f, 'storage-plan')).find(p => p.slug === first!.slug)?.deleted).toBe(true);
+ });
+ }, 240_000);
+
+ test('an output written before the ledger is never retired; what the ledger recorded since is', async () => {
+ await fixture(false, async f => {
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);
+ const [backlog] = await byStem(f, 'storage-plan');
+ await f.engine.executeRaw(`DELETE FROM derived_generation_items WHERE generation_id IN (SELECT id FROM derived_generations WHERE source_id=$1 AND kind='synthesis')`, [f.sourceId]);
+ await f.engine.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind='synthesis'`, [f.sourceId]);
+ grow(f, 'We also agreed on a weekly review of the storage costs.');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ const second = (await live(f)).find(slug => slug.includes('storage-plan') && slug !== backlog!.slug)!;
+ expect((await byStem(f, 'storage-plan')).find(p => p.slug === backlog!.slug)?.deleted).toBe(false);
+ grow(f, 'Nothing else changed.');
+ await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN_COVERED }]);
+ const after = await byStem(f, 'storage-plan');
+ expect(after.find(p => p.slug === backlog!.slug)?.deleted).toBe(false);
+ expect(after.find(p => p.slug === second)).toMatchObject({ deleted: true, retired_by: 'synthesis-resynthesis' });
+ });
+ }, 240_000);
+});