Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 5: dream summary, think synthesis and drift report as single-item page generations (S-2, S-10, S-11)

garrytan8494cb0f015d
diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsv
index fd54f886ad..3f1e3a88a6 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/single-page.ts 1 primitive the single-item page adapter (dream_summary, think_synthesis, drift_report) retires only through retireDerivedPagesInTransaction inside the generation activation (publish.ts); a publish replaces its one page in place and never retires it (GBRA-161 PR 5)
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
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 218b626597..d6f8ba6b75 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -111,9 +111,6 @@ src/core/cycle/concept-publication.ts preserveCanonicalFences field INLINE asser
src/core/cycle/concept-publication.ts publishClassicConcept call:serializeMarkdown INLINE
src/core/cycle/concept-publication.ts publishClassicConcept field INLINE
src/core/cycle/concept-publication.ts publishManagedConcept call:serializeMarkdown INLINE
-src/core/cycle/dream-taint.ts putDerivedPage call:putPage SEGW
-src/core/cycle/dream-taint.ts putDerivedPage field SEGW compares the prior body from readStoredBody; a segmented prior reads NULL, so it is versioned before the putPage
-src/core/cycle/drift.ts runPhaseDrift call:putPage INLINE
src/core/cycle/drift.ts runPhaseDrift call:serializeMarkdown INLINE
src/core/cycle/edge-contradictions.ts removeTimelineLine call:serializeMarkdown SEGW
src/core/cycle/edge-contradictions.ts removeTimelineLine field SEGW
@@ -545,7 +542,6 @@ src/core/sweep.ts runMaintenanceSweep sql STREAM LIKE over NULL never matches a
src/core/think/gather.ts renderPagesBlockDetailed field LEAD segmented page: getter throws page_body_segmented
src/core/think/gather.ts runGather field LEAD visibleLeads reads Page.compiled_truth from listPages/search: segmented page: getter throws page_body_segmented (lead source in PR 2)
src/core/think/index.ts composeExtractiveFallback field LEAD
-src/core/think/index.ts persistSynthesis call:putPage SEGW
src/core/think/persist-take.ts assertTakeFileCanonical field SEGW compares the inline page body outside the takes section with the file; a segmented page reads NULL, never matches, and the take is refused before any write
src/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows field STREAM
src/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows sql STREAM
@@ -615,6 +611,10 @@ src/core/generations/adapters/page.ts preimageIdentity field NONE hashes a ledge
src/core/generations/adapters/page.ts preimageMarkdown call:serializeMarkdown NONE serializes a ledger preimage JSON copy for restore; segmented and oversize pages have no preimage
src/core/generations/adapters/page.ts preimageMarkdown field NONE reads the body field of a ledger preimage JSON copy; segmented and oversize pages have no preimage
src/core/generations/adapters/page.ts pageVersionEvidence sql INLINE legacy-adoption evidence: hashes retained page_versions copies of derived atom pages and compares identity hashes only; segmented versions (compiled_truth NULL) are skipped
+src/core/generations/adapters/single-page.ts writePage call:putPage SEGW writes a single-item derived page (dream summary, think synthesis, drift report) from the writer's proposed content or a ledger preimage; a segmented live page is held segmented_unsupported by the generation before any write
+src/core/generations/adapters/single-page.ts writePage field INLINE passes the proposed content's compiled_truth to putPage; no stored page body is read (the prior page is versioned by createVersion)
+src/core/generations/adapters/single-page.ts singlePageAdapter field NONE restoreItem reads the body field of a ledger preimage JSON copy; segmented and oversize pages have no preimage
+src/core/generations/adapters/single-page.ts publishSinglePage field NONE hashes the writer's proposed content for the item identity; no stored page body is read
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
diff --git a/src/commands/think.ts b/src/commands/think.ts
index d26a3a9710..259ee7daa2 100644
--- a/src/commands/think.ts
+++ b/src/commands/think.ts
@@ -263,8 +263,9 @@ prints what would have been the input (exit 0).
// F8: keyless-by-design output carries its explanation as an info notice.
if (result.synthesis_status === 'no_llm') captureOpNotice(keylessThinkNotice());
+ const { persist_base: _persistBase, ...visible } = result;
const { result: jsonDoc, stderr: noticeText } = applyCliOpNotices({
- ...result,
+ ...visible,
cost_usd: costUsd ?? null,
saved_slug: savedSlug ?? null,
evidence_inserted: evidenceInserted,
diff --git a/src/core/cycle/dream-taint.ts b/src/core/cycle/dream-taint.ts
index 49b81bfbf4..6291041b1e 100644
--- a/src/core/cycle/dream-taint.ts
+++ b/src/core/cycle/dream-taint.ts
@@ -15,8 +15,7 @@
import { resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { parseMarkdown } from '../markdown.ts';
-import { readStoredBody } from '../facts/file-body-guard.ts';
-import { declareDerivation, deriveTrust, derivedMaintenanceTransaction, derivedWriteTrust, frontmatterTaint, type DerivationDeclaration } from '../trust/taint.ts';
+import { declareDerivation, deriveTrust, derivedWriteTrust, frontmatterTaint, type DerivationDeclaration } from '../trust/taint.ts';
import type { TaintInput, TrustTier, WriteTrust } from '../trust/tier.ts';
import { CONVERSATION_PAGE_URI_PREFIX } from './transcript-discovery.ts';
@@ -68,22 +67,6 @@ export async function summaryDerivation(engine: BrainEngine, sourceId: string, s
return { trust, inputs, declaration: declareDerivation(trust, inputs) };
}
-/**
- * An unmanaged derived page write (the dream summary): putPage at the derivation's tier, lowered, with its input edges.
- * #6982: a live body it replaces with a different one is kept in page_versions first (putPage itself keeps none), and
- * `tags` (the ones its file declares) are stored as the importer stores them, so the file compares equal to the page.
- */
-export async function putDerivedPage(engine: BrainEngine, derivation: Derivation, slug: string,
- page: Parameters<BrainEngine['putPage']>[1], opts: { sourceId: string; tags?: readonly string[] }): Promise<void> {
- await derivedMaintenanceTransaction(engine, derivation, async tx => {
- const prior = await readStoredBody(tx, opts.sourceId, slug, true);
- if (prior && (prior.compiled_truth !== page.compiled_truth || (prior.timeline ?? '') !== (page.timeline ?? ''))) await tx.createVersion(slug, { sourceId: opts.sourceId });
- const written = await tx.putPage(slug, page, { sourceId: opts.sourceId });
- for (const tag of opts.tags ?? []) await tx.addTag(slug, tag, { sourceId: opts.sourceId, tagSource: 'frontmatter' });
- return { result: undefined, rows: [{ table: 'pages' as const, id: Number(written.id), sourceId: opts.sourceId }] };
- });
-}
-
/** One patterns pass's derivation: every reflection submitted in its prompt. */
export function patternsDerivation(submitted: Array<{ taint?: TaintInput }>): Derivation & { declaration: DerivationDeclaration } {
const inputs = submitted.flatMap(r => (r.taint ? [r.taint] : []));
diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.ts
index d06a66c120..93811b81a4 100644
--- a/src/core/cycle/drift.ts
+++ b/src/core/cycle/drift.ts
@@ -30,7 +30,8 @@ import { resolveModel } from '../model-config.ts';
import type { DreamPhaseResult } from './auto-think.ts';
import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';
import { serializeMarkdown } from '../markdown.ts';
-import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { OperationError } from '../ops/contract.ts';
+import { DRIFT_REPORT_KIND, publishSinglePage } from '../generations/adapters/single-page.ts';
import { publishOrHold, type PublicationHold } from '../persistence/accepted-pending.ts';
export interface DriftPhaseOpts {
@@ -336,6 +337,7 @@ export async function runPhaseDrift(
const judge = opts.judge ?? defaultDriftJudge;
const cutoffIso = shiftCalendarDate(cycleDate, -config.lookbackDays);
+ const reportRevision = maintenance ? null : (await engine.readPageSnapshot(`reports/drift-${cycleDate}`, { sourceId: 'default', includeDeleted: true }))?.revision ?? null;
const judged: JudgedCandidate[] = [];
let budgetExhausted = false;
let failed = 0;
@@ -379,12 +381,14 @@ export async function runPhaseDrift(
{ expectedRevision: snapshot?.revision ?? null, file: false }));
if (reportHold) reportSlug = undefined;
} else {
- await maintenanceTransaction(engine, tx => tx.putPage(reportSlug!, {
- type: 'note',
- frontmatter: { report_type: 'drift' },
- title: `Drift report ${cycleDate}`,
- compiled_truth: buildReportBody(judged, config, modelId),
- }));
+ try {
+ await publishSinglePage(engine, { kind: DRIFT_REPORT_KIND, sourceId: 'default', slug: reportSlug, expectedRevision: reportRevision,
+ page: { type: 'note', frontmatter: { report_type: 'drift' }, title: `Drift report ${cycleDate}`, compiled_truth: buildReportBody(judged, config, modelId) } });
+ } catch (e) {
+ if (!(e instanceof OperationError && e.code === 'generation_fenced')) throw e;
+ process.stderr.write(`[drift] ${reportSlug} changed while this run composed it, so it was left as it is; the next cycle writes it.\n`);
+ reportSlug = undefined;
+ }
}
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 44e4f46a5f..d2b5d47c60 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -77,7 +77,8 @@ 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 { summaryDerivation, withTranscriptTaint } from './dream-taint.ts';
+import { DREAM_SUMMARY_KIND, publishSinglePage } from '../generations/adapters/single-page.ts';
import { findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
// Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the
@@ -682,6 +683,7 @@ async function runPhaseSynthesizeInner(
// verified whole; older pages are verified on their newly written units.
const verifySince = await readVerifyEpoch(engine);
const childIds: number[] = [];
+ const summaryRevision = maintenance ? null : (await engine.readPageSnapshot(buildDreamSummarySlug(config.outputRoot, summaryDate), { sourceId: cycleSourceId, includeDeleted: true }))?.revision ?? null;
/** Map child job_id → chunk metadata for D6 orchestrator-side slug rewrite. */
const chunkInfo = new Map<number, { idx: number; hash6: string }>();
/** #1978: map child job_id → source transcript path so written pages get a raw_source stamp. */
@@ -1188,7 +1190,7 @@ async function runPhaseSynthesizeInner(
const writtenSlugs = writtenRefs.map(r => r.slug);
if (SUMMARY_SLUG_RE.test(summarySlug) && !publishPending) {
const preserveSummary = !writtenRefs.length && await engine.readPageSnapshot(summarySlug, { sourceId: cycleSourceId });
- if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)
+ if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance, summaryRevision)
.then(held => held && fileHolds.push(held), (e: unknown) => { deferPublishOrThrow(e, summarySlug); publishPending++; });
}
@@ -3058,8 +3060,8 @@ export function renderPageToMarkdown(page: Page, tags: string[]): string {
const SUMMARY_LINK_SAMPLE_LIMIT = 20;
/**
- * Write the cycle's summary index page: the database row (the prior body kept in page_versions, `putDerivedPage`),
- * then its file through `writeDreamPageFile` (#6982). Returns the file's `file_database_drift` entry when the file
+ * Write the cycle's summary index page: the database row (unmanaged: a single-item `dream_summary` generation bound to
+ * `expectedRevision`, the summary's revision before the run's children were submitted (read here when not given), the prior page versioned first; GBRA-161 PR 5), then its file through `writeDreamPageFile` (#6982). Returns the file's `file_database_drift` entry when the file
* holds an edit the database lacks and was kept.
*/
async function writeSummaryPage(
@@ -3072,8 +3074,11 @@ async function writeSummaryPage(
sourceId = 'default',
signal?: AbortSignal,
maintenance?: MaintenanceAuthority | null,
+ expectedRevision?: string | null,
): Promise<string | undefined> {
throwIfAborted(signal, '[dream] synthesize summary');
+ const revision = expectedRevision !== undefined || maintenance ? expectedRevision ?? null
+ : (await engine.readPageSnapshot(summarySlug, { sourceId, includeDeleted: true }))?.revision ?? null;
const completed = childOutcomes.filter(c => c.status === 'completed').length;
const failed = childOutcomes.length - completed;
@@ -3127,13 +3132,16 @@ async function writeSummaryPage(
const [{ parseMarkdown }, derivation] = await Promise.all([import('../markdown.ts'), summaryDerivation(engine, sourceId, writtenSlugs)]);
const parsed = parseMarkdown(fullMarkdown);
- if (!maintenance) await putDerivedPage(engine, derivation, summarySlug, {
- type: parsed.type,
- title: parsed.title,
- compiled_truth: parsed.compiled_truth,
- timeline: parsed.timeline,
- frontmatter: parsed.frontmatter,
- }, { sourceId, tags: parsed.tags });
+ if (!maintenance) {
+ try {
+ await publishSinglePage(engine, { kind: DREAM_SUMMARY_KIND, sourceId, slug: summarySlug, expectedRevision: revision, derivation, page: { type: parsed.type,
+ title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags } });
+ } catch (e) {
+ if (!(e instanceof OperationError && e.code === 'generation_fenced')) throw e;
+ process.stderr.write(`[dream] summary ${summarySlug} changed while this run composed it, so it was left as it is; the next run writes it.\n`);
+ return undefined;
+ }
+ }
const fileWriteRaw = (await engine.getConfig('dream.synthesize.summary_file_write'))?.trim().toLowerCase();
const fileWriteEnabled = !(fileWriteRaw === 'false' || fileWriteRaw === '0' || fileWriteRaw === 'off');
diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.ts
index 68a5c79801..43703b38e8 100644
--- a/src/core/generations/adapters/index.ts
+++ b/src/core/generations/adapters/index.ts
@@ -6,8 +6,10 @@ import type { GenerationAdapter } from '../contract.ts';
import { atomGenerationAdapter } from './atoms.ts';
import { chronicleEventAdapter } from './chronicle-events.ts';
import { synthesisAdapter } from './synthesis.ts';
+import { dreamSummaryAdapter, driftReportAdapter, thinkSynthesisAdapter } from './single-page.ts';
-const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, chronicleEventAdapter, synthesisAdapter].map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));
+const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, chronicleEventAdapter, synthesisAdapter, dreamSummaryAdapter, thinkSynthesisAdapter,
+ driftReportAdapter].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/single-page.ts b/src/core/generations/adapters/single-page.ts
new file mode 100644
index 0000000000..812bc7c3d6
--- /dev/null
+++ b/src/core/generations/adapters/single-page.ts
@@ -0,0 +1,112 @@
+/**
+ * GBRA-161 PR 5: single-item page generations, for the derived pages one writer rewrites in place under a fixed slug: the
+ * dream summary (kind `dream_summary`, S-2), the `think` synthesis page (`think_synthesis`, S-10) and the drift report
+ * (`drift_report`, S-11). One owner key per page (`page:<slug>`) and one item, the page itself.
+ *
+ * - Expected revision: the writer passes the page revision it read before composing (null: no page). It is the
+ * generation's input pin, rechecked under the page lock, so a writer whose page changed since is fenced
+ * (`generation_fenced`, `pin_moved`) and writes nothing.
+ * - Version first: a live page the write changes is copied to `page_versions` (`gbrain restore`) and its bounded preimage
+ * is kept on the ledger (`gbrain repair generations --kind <kind> --mode restore`), in the same transaction.
+ * - Trust: a derived page carries its derivation (the writer's tier and taint inputs), applied in that transaction.
+ *
+ * Managed brains keep their coordinated page request, which already binds the expected revision and versions first.
+ */
+import type { BrainEngine } from '../../engine.ts';
+import type { PageType } from '../../types.ts';
+import { retireDerivedPagesInTransaction } from '../../persistence/derived-retirement-hold.ts';
+import { lowerToDerivedTier, recordTaintEdges } from '../../trust/taint.ts';
+import type { TaintInput, WriteTrust } from '../../trust/tier.ts';
+import type { GenerationAdapter, GenerationKey } from '../contract.ts';
+import { publishGeneration, type PublishOutcome } from '../publish.ts';
+import { pageIdentityHash, pageItemRow, preimageIdentity, readPageRows, type PageRowData } from './page.ts';
+
+export const DREAM_SUMMARY_KIND = 'dream_summary';
+export const THINK_SYNTHESIS_KIND = 'think_synthesis';
+export const DRIFT_REPORT_KIND = 'drift_report';
+export type SinglePageKind = typeof DREAM_SUMMARY_KIND | typeof THINK_SYNTHESIS_KIND | typeof DRIFT_REPORT_KIND;
+
+export interface SinglePageContent {
+ type: string; title: string; compiled_truth: string; timeline?: string; frontmatter: Record<string, unknown>; tags?: readonly string[];
+}
+export interface SinglePageDerivation { trust: WriteTrust; inputs: readonly TaintInput[] }
+export interface SinglePageContext { page: SinglePageContent; derivation?: SinglePageDerivation }
+
+export const singlePageOwnerKey = (slug: string) => `page:${slug}`;
+const slugOf = (key: GenerationKey) => key.ownerKey.slice('page:'.length);
+
+async function readRow(engine: BrainEngine, sourceId: string, slug: string): Promise<PageRowData | undefined> {
+ return (await readPageRows(engine, sourceId, 'p.slug = $2', [slug]))[0];
+}
+
+/** Writes the page: the live page it changes goes to page_versions first; then the derivation's tier and input edges. */
+async function writePage(tx: BrainEngine, sourceId: string, slug: string, page: SinglePageContent, identity: string, derivation?: SinglePageDerivation): Promise<void> {
+ const prior = await readRow(tx, sourceId, slug);
+ if (prior && !prior.deleted && !prior.segmented && pageIdentityHash(prior) !== identity) await tx.createVersion(slug, { sourceId });
+ const written = await tx.putPage(slug, { type: page.type as PageType, title: page.title, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',
+ frontmatter: page.frontmatter }, { sourceId });
+ for (const tag of page.tags ?? []) await tx.addTag(slug, tag, { sourceId, tagSource: 'frontmatter' });
+ if (!derivation) return;
+ await lowerToDerivedTier(tx as never, 'pages', [Number(written.id)], derivation.trust);
+ await recordTaintEdges(tx, { table: 'pages', id: Number(written.id), sourceId }, derivation.inputs);
+}
+
+function singlePageAdapter(kind: SinglePageKind): GenerationAdapter<SinglePageContext> {
+ return {
+ kind,
+ retiredBy: 'generation-restore',
+ modelProduced: false,
+ lockKeys: key => [{ sourceId: key.sourceId, slug: slugOf(key) }],
+ async readInput(engine, key) {
+ const snapshot = await engine.readPageSnapshot(slugOf(key), { sourceId: key.sourceId, includeDeleted: true });
+ return { pin: snapshot?.revision ?? 'absent', size: 0 };
+ },
+ async readItems(engine, key) {
+ const row = await readRow(engine, key.sourceId, slugOf(key));
+ return new Map(row ? [[row.slug, pageItemRow(row, true)]] : []);
+ },
+ legacyEvidence: async () => new Set<string>(),
+ async publishItems(tx, key, items, context) {
+ for (const item of items) await writePage(tx, key.sourceId, item.key, context!.page, item.identityHash, context!.derivation);
+ },
+ retireItems: (tx, key, itemKeys, retiredBy) => retireDerivedPagesInTransaction(tx, key.sourceId, itemKeys, retiredBy),
+ async restoreItem(tx, key, itemKey, preimage) {
+ const page: SinglePageContent = { type: String(preimage.type), title: String(preimage.title), compiled_truth: String(preimage.compiled_truth ?? ''),
+ timeline: String(preimage.timeline ?? ''), frontmatter: (preimage.frontmatter as Record<string, unknown>) ?? {}, tags: (preimage.tags as string[]) ?? [] };
+ await writePage(tx, key.sourceId, itemKey, page, preimageIdentity(preimage));
+ },
+ preimageIdentity,
+ };
+}
+
+export const dreamSummaryAdapter = singlePageAdapter(DREAM_SUMMARY_KIND);
+export const thinkSynthesisAdapter = singlePageAdapter(THINK_SYNTHESIS_KIND);
+export const driftReportAdapter = singlePageAdapter(DRIFT_REPORT_KIND);
+const ADAPTERS: Record<SinglePageKind, GenerationAdapter<SinglePageContext>> = {
+ [DREAM_SUMMARY_KIND]: dreamSummaryAdapter, [THINK_SYNTHESIS_KIND]: thinkSynthesisAdapter, [DRIFT_REPORT_KIND]: driftReportAdapter,
+};
+
+export interface SinglePageRequest extends SinglePageContext {
+ kind: SinglePageKind; sourceId: string; slug: string;
+ /** The page revision the writer read before composing; null when there was no page. */
+ expectedRevision: string | null;
+ runId?: string;
+}
+
+/**
+ * Publishes one single-item page generation (unmanaged). The tags the page already holds stay (a write never removes one),
+ * so the item identity covers them. Throws `generation_fenced` when the page moved past `expectedRevision`; returns the
+ * outcome and the page id.
+ */
+export async function publishSinglePage(engine: BrainEngine, request: SinglePageRequest): Promise<{ outcome: PublishOutcome; pageId: number | null }> {
+ const { kind, sourceId, slug, page } = request;
+ const current = await readRow(engine, sourceId, slug);
+ const tags = [...new Set([...(current && !current.deleted ? current.tags : []), ...(page.tags ?? [])])];
+ const identityHash = pageIdentityHash({ type: page.type, title: page.title, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',
+ frontmatter: page.frontmatter, tags });
+ const outcome = await publishGeneration(engine, ADAPTERS[kind], { key: { kind, sourceId, ownerKey: singlePageOwnerKey(slug) }, items: [{ key: slug, content: '', identityHash }],
+ input: { pin: request.expectedRevision ?? 'absent', size: 0 }, context: { page, derivation: request.derivation }, runId: request.runId,
+ ...(request.derivation ? { trust: request.derivation.trust } : {}) });
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);
+ return { outcome, pageId: row ? Number(row.id) : null };
+}
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.ts
index 1558b8a44b..c4f0d39c81 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -18,6 +18,7 @@ import { policyHash, readGenerationsConfig, type GenerationsConfig } from './con
import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
import type { GenerationAdapter, GenerationKey, HeldReason, InputState, ItemRow, Preimage, ProposedItem } from './contract.ts';
import { planGeneration, type LiveGeneration, type Plan } from './plan.ts';
+import type { WriteTrust } from '../trust/tier.ts';
import { proofHolds, type EmptySourceProof } from './proofs.ts';
/** The largest held proposal the ledger keeps (UTF-8 bytes of its JSON); a larger one is held without a releasable copy. */
@@ -46,6 +47,8 @@ export interface PublishRequest<C = unknown> {
locator?: string;
/** Recorded on the generation's completeness evidence (synthesis: the earlier outputs it left live, for the cleanup listing). */
note?: Record<string, unknown>;
+ /** The write trust of a derived item (single-page kinds): the activation transaction is attributed at this tier. */
+ trust?: WriteTrust;
}
export type PublishOutcome =
@@ -283,7 +286,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
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;
- });
+ }, request.trust);
if (outcome.state === 'published') await faultPoint('generation:activated', { sourceId: key.sourceId, operation: key.kind });
return outcome;
} catch (error) {
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 0928e51ea6..d8bdbb8e55 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -385,7 +385,7 @@ const think: Operation = {
const { recordThinkAnswer, feedbackMetaFields } = await import('../feedback/record.ts');
const feedbackMeta = feedbackMetaFields(await recordThinkAnswer(ctx, 'think', result));
delete result.feedback_evidence; delete result.taint_refs;
- const { persist: _persist, ...visible } = result;
+ const { persist: _persist, persist_base: _persistBase, ...visible } = result;
return {
...visible,
...feedbackMeta,
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 40c03b5d4e..147f726055 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -40,7 +40,8 @@ import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';
import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';
import { classifyIntent } from './intent.ts';
-import { deriveTrust, derivedMaintenanceTransaction, type TaintRef } from '../trust/taint.ts';
+import { deriveTrust, type TaintRef } from '../trust/taint.ts';
+import { publishSinglePage, THINK_SYNTHESIS_KIND } from '../generations/adapters/single-page.ts';
/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */
export interface ThinkLLMClient {
@@ -244,6 +245,8 @@ export interface ThinkResult {
unverified_quotes?: Array<{ text: string; reason: string }>;
/** What `persistSynthesis` saves: the raw answer with every claim unit carrying an unverified quote removed, and those units. */
persist?: { answer: string; unverified_claims: Array<{ text: string; reason: string; detail: string }> };
+ /** The synthesis page as the run found it before gathering (GBRA-161 PR 5): `persistSynthesis` binds its write to this revision. */
+ persist_base?: { sourceId: string; slug: string; revision: string | null };
/** Diagnostics for `--explain` callers (CLI surface for v0.29). */
diagnostics: {
pagesFromHybrid: number;
@@ -611,6 +614,9 @@ export async function runThink(
if (resolvedWindow?.source === 'question') warnings.push('WINDOW_FROM_QUESTION');
const windowMeta = resolvedWindow ? { window_source: resolvedWindow.source } : {};
const temporal = await resolveThinkTemporalContext(engine, { referenceDate: opts.referenceDate });
+ const persistSlug = synthesisSlug(opts.question, new Date().toISOString().slice(0, 10));
+ const persistBase = { sourceId: opts.sourceId ?? 'default', slug: persistSlug,
+ revision: (await engine.readPageSnapshot(persistSlug, { sourceId: opts.sourceId ?? 'default', includeDeleted: true }))?.revision ?? null };
// Resolve the model through the 6-tier chain.
const modelUsed = await resolveModel(engine, {
@@ -1040,6 +1046,7 @@ export async function runThink(
},
temporal: { reference_date: temporal.referenceDate, time_zone: temporal.timeZone },
...windowMeta,
+ persist_base: persistBase,
};
}
@@ -1100,9 +1107,17 @@ export function stripGapsSection(answer: string): string {
return kept.replace(/\s+$/, '');
}
+/** The synthesis page of a question on a day: `synthesis/<slugified-question>-<date>`. */
+function synthesisSlug(question: string, today: string): string {
+ const slugSafe = question.toLowerCase().replace(/[^a-z0-9\s]+/g, '').trim().replace(/\s+/g, '-').slice(0, 60) || 'untitled';
+ return `synthesis/${slugSafe}-${today}`;
+}
+
/**
* Persist a synthesis page + its evidence. Returns the saved slug.
- * Synthesis pages are written under `synthesis/<slugified-question>-<date>.md`.
+ * Synthesis pages are written under `synthesis/<slugified-question>-<date>.md` as a single-item `think_synthesis`
+ * generation (GBRA-161 PR 5): bound to the revision the run found before gathering (`persist_base`, else read now), so a
+ * page that changed meanwhile is fenced (`generation_fenced`), and the page it replaces is versioned first.
*/
export async function persistSynthesis(
engine: BrainEngine,
@@ -1118,13 +1133,7 @@ export async function persistSynthesis(
}
const today = new Date().toISOString().slice(0, 10);
- const slugSafe = result.question
- .toLowerCase()
- .replace(/[^a-z0-9\s]+/g, '')
- .trim()
- .replace(/\s+/g, '-')
- .slice(0, 60) || 'untitled';
- const slug = `synthesis/${slugSafe}-${today}`;
+ const slug = synthesisSlug(result.question, today);
// Build the markdown body. A claim whose quote is not in the evidence is not saved as prose;
// it goes to frontmatter unverified_claims (reviewable with get_page, out of search and recall).
@@ -1137,8 +1146,11 @@ export async function persistSynthesis(
].filter(Boolean).join('\n');
const derivation = await deriveTrust(engine, result.taint_refs ?? [], { channel: 'derive:think' });
- const page = await derivedMaintenanceTransaction(engine, derivation, async tx => {
- const written = await tx.putPage(slug, {
+ const sourceId = scope.sourceId ?? 'default';
+ const base = result.persist_base;
+ const expectedRevision = base && base.slug === slug && base.sourceId === sourceId ? base.revision
+ : (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }))?.revision ?? null;
+ const { pageId } = await publishSinglePage(engine, { kind: THINK_SYNTHESIS_KIND, sourceId, slug, expectedRevision, derivation, page: {
title: result.question.slice(0, 200),
type: 'synthesis',
compiled_truth: body,
@@ -1151,11 +1163,9 @@ export async function persistSynthesis(
takes_gathered: result.takesGathered,
...(result.persist?.unverified_claims.length ? { unverified_claims: result.persist.unverified_claims.map(c => ({ ...c, sources: ['think evidence'], detected_at: today })) } : {}),
},
- }, scope.sourceId ? { sourceId: scope.sourceId } : undefined);
- return { result: written, rows: [{ table: 'pages' as const, id: written.id, sourceId: scope.sourceId ?? 'default' }] };
- });
+ } });
- const persisted = await persistCitations(engine, page.id, result.citations, scope);
+ const persisted = await persistCitations(engine, pageId!, result.citations, scope);
return { slug, evidenceInserted: persisted.inserted, warnings: persisted.warnings };
}
diff --git a/test/cycle-synthesize-summary-page.test.ts b/test/cycle-synthesize-summary-page.test.ts
index 4d134724e0..74dfc7accb 100644
--- a/test/cycle-synthesize-summary-page.test.ts
+++ b/test/cycle-synthesize-summary-page.test.ts
@@ -15,7 +15,6 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { __testing } from '../src/core/cycle/synthesize.ts';
-import type { PageInput } from '../src/core/types.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { lintContent } from '../src/commands/lint.ts';
@@ -35,24 +34,24 @@ const writeSummaryPage = (
__testing as unknown as { writeSummaryPage: SummaryWriter }
).writeSummaryPage;
+// GBRA-161 PR 5: the unmanaged summary write is a single-item dream_summary generation (ledger, versions, revision
+// fence), which a putPage stub cannot serve, so the rendering tests write through a real PGLite brain and read the page back.
+let renderEngine: PGLiteEngine;
+beforeAll(async () => {
+ renderEngine = new PGLiteEngine();
+ await renderEngine.connect({});
+ await renderEngine.initSchema();
+});
+afterAll(async () => {
+ await renderEngine.disconnect();
+});
+
async function renderSummary(writtenSlugs: string[]): Promise<{ body: string; markdown: string }> {
const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-dream-summary-'));
- let stored: PageInput | undefined;
- const engine = {
- putPage: async (_slug: string, page: PageInput) => {
- stored = page;
- return {};
- },
- // #4506 dual-write suppressor reads this knob; default-on path.
- getConfig: async (_key: string) => null,
- // The summary write runs in a maintenance transaction; the stub is its own transaction engine.
- executeRaw: async () => [],
- addTag: async () => {},
- transaction: async <T>(fn: (tx: BrainEngine) => Promise<T>) => fn(engine),
- } as unknown as BrainEngine;
+ await resetPgliteState(renderEngine);
try {
await writeSummaryPage(
- engine,
+ renderEngine,
brainDir,
'dream-cycle-summaries/2026-08-20',
'2026-08-20',
@@ -63,6 +62,7 @@ async function renderSummary(writtenSlugs: string[]): Promise<{ body: string; ma
{ jobId: 3, status: 'failed' },
],
);
+ const stored = await renderEngine.getPage('dream-cycle-summaries/2026-08-20');
if (!stored) throw new Error('summary page was not persisted');
return {
body: stored.compiled_truth,
diff --git a/test/e2e/g5-single-page-generations-postgres.test.ts b/test/e2e/g5-single-page-generations-postgres.test.ts
new file mode 100644
index 0000000000..f9bcc29101
--- /dev/null
+++ b/test/e2e/g5-single-page-generations-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/g5-single-page-generations.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index bb7917e316..31747ab8c0 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -8365,6 +8365,7 @@
"modelUsed: string",
"pagesGathered: number",
"persist?: { answer: string; unverified_claims: Array<{ text: string; reason: string; detail: string; }>; } | undefined",
+ "persist_base?: { sourceId: string; slug: string; revision: string | null; } | undefined",
"question: string",
"quote_check?: { grounded: number; repaired: number; unverified: number; } | undefined",
"requested_model?: string | undefined",
diff --git a/test/pathological/g5-single-page-generations.test.ts b/test/pathological/g5-single-page-generations.test.ts
new file mode 100644
index 0000000000..a007f627ee
--- /dev/null
+++ b/test/pathological/g5-single-page-generations.test.ts
@@ -0,0 +1,178 @@
+/**
+ * GBRA-161 PR 5 (S-2, S-10, S-11): the dream summary, the think synthesis page and the drift report are single-item page
+ * generations. Each writer binds its write to the page revision it read before composing, so a page that changed while it
+ * composed is fenced and keeps its content; each overwrite is versioned (page_versions, the ledger preimage) and
+ * restorable through gbrain repair generations. Real writers on PGLite and Postgres; model calls are the existing stubs.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runThink, persistSynthesis, type ThinkLLMClient } from '../../src/core/think/index.ts';
+import { runPhaseDrift } from '../../src/core/cycle/drift.ts';
+import { runPhaseSynthesize } from '../../src/core/cycle/synthesize.ts';
+import { resolveCycleDate } from '../../src/core/cycle/cycle-date.ts';
+import { _resetBudgetMeterWarningsForTest } from '../../src/core/cycle/budget-meter.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+/** The slug persistSynthesis saves a question's answer under (synthesis/<slugified question>-<date>). */
+const synthesisSlug = (q: string, today: string) => `synthesis/${q.toLowerCase().replace(/[^a-z0-9\s]+/g, '').trim().replace(/\s+/g, '-').slice(0, 60) || 'untitled'}-${today}`;
+const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+const codeOf = (error: unknown) => error instanceof OperationError ? error.code : String(error);
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine, dir: string) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-g5-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, ANTHROPIC_API_KEY: 'sk-test-g5' }, async () => {
+ _resetWriteThroughCacheForTest();
+ _resetBudgetMeterWarningsForTest();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try { await run(engine, dir); } finally { __setChatTransportForTests(null); resetGateway(); await close(); }
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}
+
+const body = async (engine: BrainEngine, slug: string, sourceId = 'default') => (await engine.executeRaw<{ compiled_truth: string }>(
+ 'SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]?.compiled_truth ?? null;
+const versions = async (engine: BrainEngine, slug: string, sourceId = 'default') => (await engine.executeRaw<{ compiled_truth: string }>(
+ 'SELECT v.compiled_truth FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id', [sourceId, slug])).map(r => r.compiled_truth);
+const handEdit = (engine: BrainEngine, slug: string, text: string, sourceId = 'default') =>
+ engine.putPage(slug, { type: 'note', title: 'Edited by hand', compiled_truth: text }, { sourceId });
+
+/** Previews and applies gbrain repair generations --mode restore for one kind; returns the applied outcome items. */
+async function restore(engine: BrainEngine, kind: string, sourceId = 'default') {
+ const scope = await resolveRepairScope(engine, sourceId);
+ const generations = { kind, mode: 'restore' as const, since: new Date(Date.now() - 86_400_000).toISOString() };
+ const preview = await (await repairRunner(engine, { apply: false, logger: quiet })).run('generations', scope, { explicit: true, sourceFlag: sourceId, generations } as never);
+ expect(preview.preview_hash).toBeTruthy();
+ const applied = await (await repairRunner(engine, { apply: true, logger: quiet })).run('generations', scope,
+ { explicit: true, sourceFlag: sourceId, expect: preview.preview_hash, yes: true, generations } as never);
+ return applied.outcome_items ?? [];
+}
+
+function thinkClient(answer: string, during?: () => Promise<void>): ThinkLLMClient {
+ return { create: async () => {
+ await during?.();
+ return { id: 'msg_stub', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', stop_sequence: null,
+ usage: { input_tokens: 10, output_tokens: 10, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },
+ content: [{ type: 'text', text: JSON.stringify({ answer, citations: [], gaps: [] }) }] } as never;
+ } };
+}
+
+async function seedDrift(engine: BrainEngine) {
+ const alice = await engine.putPage('people/alice-example', { title: 'Alice', type: 'person', compiled_truth: 'Alice content' });
+ await engine.addTakesBatch([{ page_id: alice.id, row_num: 1, claim: 'Strong technical founder', kind: 'take', holder: 'world', weight: 0.6 }]);
+ await engine.addTimelineEntriesBatch([{ slug: 'people/alice-example', date: new Date().toISOString().slice(0, 10), source: 'meeting', summary: 'Funding round closed' }]);
+ for (const [k, v] of Object.entries({ 'dream.drift.enabled': 'true', 'dream.drift.lookback_days': '30', 'dream.drift.budget': '1.0' })) await engine.setConfig(k, v);
+}
+const drift = (engine: BrainEngine, dir: string, reasoning: string, during?: () => Promise<void>) => runPhaseDrift(engine, { dryRun: false, auditPath: join(dir, `drift-${randomUUID()}.jsonl`),
+ judge: async () => { await during?.(); return { drifted: true, confidence: 0.9, reasoning, suggested_weight: 0.3 }; } });
+
+async function synthesisRig(engine: BrainEngine, dir: string) {
+ const root = join(dir, 'brain'), corpus = join(dir, 'corpus');
+ mkdirSync(root); mkdirSync(corpus);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2) ON CONFLICT (id) DO NOTHING', ['g5src', root]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, 'g5src', root);
+ for (const [k, v] 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': 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(k, v);
+ const usage = { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 };
+ const run = async (name: string, during?: () => Promise<void>) => {
+ writeFileSync(join(corpus, `${name}.txt`), `[user]\nWe settled the storage plan for ${name}.\n\n${'[assistant]\nNoted.\n\n'.repeat(20)}`);
+ __setChatTransportForTests(async opts => {
+ const mk = (text: string) => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end', 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: [], entities: [], reasons: ['durable'] }));
+ await during?.();
+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(JSON.stringify(opts.messages))?.[1] ?? 'missing';
+ return mk(JSON.stringify({ pages: [{ slug: `wiki/personal/reflections/${name}-${hash}`, title: name, type: 'note', body: `The storage plan for ${name} is settled with [[people/alice-example]].` }], skipped: false }));
+ });
+ const result = await runPhaseSynthesize(engine, { brainDir: root, sourceId: 'g5src', dryRun: false });
+ __setChatTransportForTests(null);
+ return result;
+ };
+ return { run, summary: `dream-cycle-summaries/${await resolveCycleDate(engine, {})}` };
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`GBRA-161 PR 5 single-page generations (${backend})`, () => {
+ test('think: a synthesis page edited while the run composed is fenced and keeps the edit', async () => {
+ await withBrain(databaseUrl, async engine => {
+ const question = 'What about storage plans?';
+ const slug = synthesisSlug(question, new Date().toISOString().slice(0, 10));
+ const result = await runThink(engine, { question, client: thinkClient('The plan is settled.', () => handEdit(engine, slug, 'A person wrote this.').then(() => {})) });
+ expect(codeOf(await persistSynthesis(engine, result).catch(e => e))).toBe('generation_fenced');
+ expect(await body(engine, slug)).toBe('A person wrote this.');
+ });
+ }, 120_000);
+
+ test('think: a same-day re-save versions the earlier page and repair generations restores it', async () => {
+ await withBrain(databaseUrl, async engine => {
+ const question = 'What about storage plans?';
+ await persistSynthesis(engine, await runThink(engine, { question, client: thinkClient('First answer about storage.') }));
+ const saved = await persistSynthesis(engine, await runThink(engine, { question, client: thinkClient('Second answer about storage.') }));
+ expect(await body(engine, saved.slug)).toContain('Second answer about storage.');
+ expect((await versions(engine, saved.slug)).some(v => v.includes('First answer about storage.'))).toBe(true);
+ expect((await restore(engine, 'think_synthesis')).map(item => item.outcome)).toEqual(['restored']);
+ expect(await body(engine, saved.slug)).toContain('First answer about storage.');
+ });
+ }, 120_000);
+
+ test('drift: a report edited while the judge ran is fenced and keeps the edit', async () => {
+ await withBrain(databaseUrl, async (engine, dir) => {
+ await seedDrift(engine);
+ const slug = `reports/drift-${await resolveCycleDate(engine, {})}`;
+ const result = await drift(engine, dir, 'evidence shifted', () => handEdit(engine, slug, 'A person wrote this.').then(() => {}));
+ expect(result.detail).not.toContain(slug);
+ expect(await body(engine, slug)).toBe('A person wrote this.');
+ });
+ }, 120_000);
+
+ test('drift: a same-day rerun versions the earlier report and repair generations restores it', async () => {
+ await withBrain(databaseUrl, async (engine, dir) => {
+ await seedDrift(engine);
+ const slug = `reports/drift-${await resolveCycleDate(engine, {})}`;
+ await drift(engine, dir, 'first-reasoning');
+ await drift(engine, dir, 'second-reasoning');
+ expect(await body(engine, slug)).toContain('second-reasoning');
+ expect((await versions(engine, slug)).some(v => v.includes('first-reasoning'))).toBe(true);
+ expect((await restore(engine, 'drift_report')).map(item => item.outcome)).toEqual(['restored']);
+ expect(await body(engine, slug)).toContain('first-reasoning');
+ });
+ }, 120_000);
+
+ test('dream summary: a summary edited while the children ran is fenced and keeps the edit', async () => {
+ await withBrain(databaseUrl, async (engine, dir) => {
+ const rig = await synthesisRig(engine, dir);
+ expect((await rig.run('alpha')).status).not.toBe('fail');
+ expect(await body(engine, rig.summary, 'g5src')).toContain('alpha');
+ await rig.run('beta', () => handEdit(engine, rig.summary, 'A person wrote this.', 'g5src').then(() => {}));
+ expect(await body(engine, rig.summary, 'g5src')).toBe('A person wrote this.');
+ });
+ }, 180_000);
+
+ test('dream summary: a same-day rerun versions the earlier summary and repair generations restores it', async () => {
+ await withBrain(databaseUrl, async (engine, dir) => {
+ const rig = await synthesisRig(engine, dir);
+ await rig.run('alpha');
+ await rig.run('beta');
+ expect(await body(engine, rig.summary, 'g5src')).toContain('beta');
+ expect((await versions(engine, rig.summary, 'g5src')).some(v => v.includes('alpha'))).toBe(true);
+ expect((await restore(engine, 'dream_summary', 'g5src')).map(item => item.outcome)).toEqual(['restored']);
+ expect(await body(engine, rig.summary, 'g5src')).toContain('alpha');
+ });
+ }, 180_000);
+ });
+}