Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(patterns): a timeline append whose grounding write-back failed is stored and retried on the next run before the evidence and paid-child gates; 3 content refusals hold it (GBRA-130 A-23)

garrytan4e1918734b28
diff --git a/src/core/cycle/pattern-grounding.ts b/src/core/cycle/pattern-grounding.ts
index 474e579875..4ea3d832d7 100644
--- a/src/core/cycle/pattern-grounding.ts
+++ b/src/core/cycle/pattern-grounding.ts
@@ -16,15 +16,27 @@
* with the command that retries it. Editing the page or upgrading gbrain
* releases it on the next run; \`gbrain config unset <key>\` releases every
* hold of the source at once. Transient failures are never held and reset the
- * count. Timeline-append failures are reported, never held: those entries are
- * this run's only, so no later run retries them.
+ * count.
+ *
+ * Timeline appends: the entries a child appended live only in that run, so a
+ * page whose append grounding fails is recorded with the entries and the
+ * reflections they are grounded against in `dream.patterns.grounding_appends.<source>`
+ * before the evidence watermark is stamped. Every later run retries them before
+ * its evidence and paid-child gates and drops each entry once its page grounds
+ * (or the entry is gone). The same 3-run content rule holds a page's appends
+ * (listed in `grounding_held` with `timeline_appends`); editing the page or
+ * upgrading gbrain releases them. That key is never unset to release a hold:
+ * it is the only copy of the entries still to verify.
*/
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
-import type { ItemFailure } from '../item-failure.ts';
+import type { ItemFailure, ItemRun } from '../item-failure.ts';
+import type { TaintInput } from '../trust/tier.ts';
+import type { TimelineAppend } from './patterns.ts';
import { VERSION } from '../../version.ts';
export const GROUNDING_HOLDS_KEY = 'dream.patterns.grounding_holds';
+export const GROUNDING_APPENDS_KEY = 'dream.patterns.grounding_appends';
export const GROUNDING_HOLD_RUNS = 3;
export interface GroundingHold {
@@ -37,38 +49,82 @@ export interface GroundingHold {
last_failed_at: string;
}
-/** One run's grounding: the holds it began with, the pages that failed and the pages that grounded. */
+/** Timeline entries still to ground on one page, with the reflections (and their tiers) they are grounded against. */
+export interface AppendInputs { appends: TimelineAppend[]; reflections: Array<{ slug: string; taint?: TaintInput }> }
+export type PendingAppends = GroundingHold & AppendInputs;
+
+/**
+ * One run's grounding: the holds and pending appends it began with, the pages that failed (a timeline-append
+ * failure carries its inputs), the pages that grounded, the request ids of appends resolved per page, and the
+ * breaker every timeline-append call of the run shares.
+ */
export interface GroundingRun {
sourceId: string;
holds: Record<string, GroundingHold>;
- failed: Array<ItemFailure & { content_hash: string | null; timelineAppend: boolean }>;
+ pending: Record<string, PendingAppends>;
+ failed: Array<ItemFailure & { content_hash: string | null; timelineAppend: boolean; inputs?: AppendInputs }>;
grounded: Set<string>;
+ appendsResolved: Map<string, Set<string>>;
+ appendRun?: ItemRun;
}
export interface GroundingReport {
failedSlugs: Set<string>;
details: { grounding_failed: Array<{ slug: string; code: string; message: string; held: boolean; fix: string }>;
- grounding_held: Array<{ slug: string; code: string; content_hash: string | null; held_at: string; fix: string }> };
+ grounding_held: Array<{ slug: string; code: string; content_hash: string | null; held_at: string; fix: string; timeline_appends?: number }> };
}
const holdsKey = (sourceId: string) => `${GROUNDING_HOLDS_KEY}.${sourceId}`;
+const appendsKey = (sourceId: string) => `${GROUNDING_APPENDS_KEY}.${sourceId}`;
-export async function beginGroundingRun(engine: BrainEngine, sourceId: string): Promise<GroundingRun> {
- let holds: Record<string, GroundingHold> = {};
+async function readItems<T>(engine: BrainEngine, key: string): Promise<Record<string, T>> {
try {
- const stored = JSON.parse((await engine.getConfig(holdsKey(sourceId))) ?? '{}') as { version?: number; items?: Record<string, GroundingHold> };
- if (stored.version === 1 && stored.items && typeof stored.items === 'object') holds = stored.items;
+ const stored = JSON.parse((await engine.getConfig(key)) ?? '{}') as { version?: number; items?: Record<string, T> };
+ if (stored.version === 1 && stored.items && typeof stored.items === 'object') return stored.items;
} catch { /* an unreadable record holds nothing */ }
- return { sourceId, holds, failed: [], grounded: new Set() };
+ return {};
+}
+
+export async function beginGroundingRun(engine: BrainEngine, sourceId: string): Promise<GroundingRun> {
+ return { sourceId, holds: await readItems(engine, holdsKey(sourceId)), pending: await readItems(engine, appendsKey(sourceId)),
+ failed: [], grounded: new Set(), appendsResolved: new Map() };
}
-/** A leftover page held at its current content and this producer is skipped; any change releases it. */
-export function groundingHeld(run: GroundingRun, slug: string, contentHash: string | null): boolean {
- const hold = run.holds[slug];
+/** A page (leftover, or one with pending appends) held at its current content and this producer is skipped; any change releases it. */
+export function groundingHeld(run: GroundingRun, slug: string, contentHash: string | null, holds: Record<string, GroundingHold> = run.holds): boolean {
+ const hold = holds[slug];
return !!hold?.held_at && hold.content_hash === contentHash && hold.producer === VERSION;
}
-/** Merges this run into the stored holds (only when it finished: a systemic or run-scoped stop never reaches here) and reports both. */
+function nextHold(prior: GroundingHold | undefined, f: GroundingRun['failed'][number], now: string): GroundingHold {
+ const attempts = prior && prior.content_hash === f.content_hash && prior.producer === VERSION && prior.code === f.code ? prior.attempts + 1 : 1;
+ return { content_hash: f.content_hash, producer: VERSION, code: f.code, message: f.message.slice(0, 300), attempts,
+ held_at: attempts >= GROUNDING_HOLD_RUNS ? prior?.held_at ?? now : null, last_failed_at: now };
+}
+
+/** Pending appends after this run: resolved entries leave, failed ones merge in (a transient failure keeps them at 0 attempts). */
+function nextPending(run: GroundingRun, now: string): Record<string, PendingAppends> {
+ const pending = { ...run.pending };
+ for (const [slug, resolved] of run.appendsResolved) {
+ const left = pending[slug]?.appends.filter(a => !resolved.has(a.requestId));
+ if (!left) continue;
+ if (left.length) pending[slug] = { ...pending[slug]!, appends: left };
+ else delete pending[slug];
+ }
+ for (const f of run.failed) {
+ if (!f.inputs) continue;
+ const prior = pending[f.key];
+ const appends = [...(prior?.appends ?? [])];
+ for (const a of f.inputs.appends) if (!appends.some(p => p.requestId === a.requestId)) appends.push(a);
+ const reflections = [...(prior?.reflections ?? [])];
+ for (const r of f.inputs.reflections) if (!reflections.some(p => p.slug === r.slug)) reflections.push(r);
+ const hold = f.class === 'content' ? nextHold(prior, f, now) : { ...nextHold(undefined, f, now), attempts: 0 };
+ pending[f.key] = { ...hold, appends, reflections };
+ }
+ return pending;
+}
+
+/** Merges this run into the stored holds and pending appends (only when it finished: a systemic or run-scoped stop never reaches here) and reports them. */
export async function finishGroundingRun(engine: BrainEngine, run: GroundingRun): Promise<GroundingReport> {
const now = new Date().toISOString();
const holds = { ...run.holds };
@@ -76,22 +132,26 @@ export async function finishGroundingRun(engine: BrainEngine, run: GroundingRun)
for (const f of run.failed) {
if (f.timelineAppend) continue;
if (f.class !== 'content') { delete holds[f.key]; continue; }
- const prior = holds[f.key];
- const attempts = prior && prior.content_hash === f.content_hash && prior.producer === VERSION && prior.code === f.code ? prior.attempts + 1 : 1;
- holds[f.key] = { content_hash: f.content_hash, producer: VERSION, code: f.code, message: f.message.slice(0, 300), attempts,
- held_at: attempts >= GROUNDING_HOLD_RUNS ? prior?.held_at ?? now : null, last_failed_at: now };
+ holds[f.key] = nextHold(holds[f.key], f, now);
}
- const changed = JSON.stringify(holds) !== JSON.stringify(run.holds);
- if (changed) await engine.setConfig(holdsKey(run.sourceId), JSON.stringify({ version: 1, items: holds }));
+ if (JSON.stringify(holds) !== JSON.stringify(run.holds)) await engine.setConfig(holdsKey(run.sourceId), JSON.stringify({ version: 1, items: holds }));
+ const pending = nextPending(run, now);
+ if (JSON.stringify(pending) !== JSON.stringify(run.pending)) await engine.setConfig(appendsKey(run.sourceId), JSON.stringify({ version: 1, items: pending }));
const release = `gbrain config unset ${holdsKey(run.sourceId)} && gbrain dream --phase patterns --once --source ${run.sourceId}`;
const retry = `gbrain dream --phase patterns --once --source ${run.sourceId}`;
+ const inspect = (slug: string) => `gbrain get --source ${run.sourceId} -- ${slug}`;
return {
failedSlugs: new Set(run.failed.map(f => f.key)),
details: {
- grounding_failed: run.failed.map(f => ({ slug: f.key, code: f.code, message: f.message.slice(0, 300), held: !f.timelineAppend && !!holds[f.key]?.held_at,
- fix: f.timelineAppend ? `gbrain get --source ${run.sourceId} -- ${f.key}` : holds[f.key]?.held_at ? release : retry })),
- grounding_held: Object.entries(holds).filter(([, h]) => h.held_at && h.producer === VERSION)
- .map(([slug, h]) => ({ slug, code: h.code, content_hash: h.content_hash, held_at: h.held_at!, fix: release })),
+ grounding_failed: run.failed.map(f => ({ slug: f.key, code: f.code, message: f.message.slice(0, 300),
+ held: f.timelineAppend ? !!pending[f.key]?.held_at : !!holds[f.key]?.held_at,
+ fix: f.timelineAppend ? inspect(f.key) : holds[f.key]?.held_at ? release : retry })),
+ grounding_held: [
+ ...Object.entries(holds).filter(([, h]) => h.held_at && h.producer === VERSION)
+ .map(([slug, h]) => ({ slug, code: h.code, content_hash: h.content_hash, held_at: h.held_at!, fix: release })),
+ ...Object.entries(pending).filter(([, h]) => h.held_at && h.producer === VERSION)
+ .map(([slug, h]) => ({ slug, code: h.code, content_hash: h.content_hash, held_at: h.held_at!, fix: inspect(slug), timeline_appends: h.appends.length })),
+ ],
},
};
}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 2f9af12f3b..188072845c 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -58,7 +58,7 @@ import { derivedMaintenanceTransaction, isExternalTier, type DerivationDeclarati
import { storedTrustTier, type TaintInput } from '../trust/tier.ts';
import { patternsDerivation, type Derivation } from './dream-taint.ts';
import { ItemRun } from '../item-failure.ts';
-import { beginGroundingRun, finishGroundingRun, groundingHeld, withGroundingStatus, type GroundingRun } from './pattern-grounding.ts';
+import { beginGroundingRun, finishGroundingRun, groundingHeld, withGroundingStatus, type GroundingReport, type GroundingRun } from './pattern-grounding.ts';
export interface PatternsPhaseOpts {
brainDir: string;
@@ -158,6 +158,7 @@ export async function runPhasePatterns(
opts: PatternsPhaseOpts,
): Promise<PhaseResult> {
let config: PatternsConfig, evidenceKey: string, cadenceKey: string, reflections: ReflectionRef[];
+ let retried: AppendRetry | null = null;
try {
throwIfAborted(opts.signal, '[dream] patterns');
config = await loadPatternsConfig(engine);
@@ -179,6 +180,8 @@ export async function runPhasePatterns(
// Gather reflections within lookback window.
reflections = await gatherReflections(engine, config.lookbackDays, config.sourceSlugPrefix, opts.sourceId ?? 'default');
+ // GBRA-130 A-23: before any gate can skip the pass, so a failed append never waits on new evidence or a paid child.
+ if (!opts.dryRun) retried = await retryPendingAppends(engine, opts, opts.sourceId ?? 'default');
} catch (e) {
return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',
e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));
@@ -188,10 +191,10 @@ export async function runPhasePatterns(
// enough evidence of their own), and that pass's pattern pages are external.
const external = reflections.filter(r => isExternalTier(r.taint?.tier ?? 'unknown'));
const owner = await runPatternsPass(engine, opts, config, reflections.filter(r => !external.includes(r)), { evidence: evidenceKey, cadence: cadenceKey });
- if (!external.length) return owner;
+ if (!external.length) return withAppendRetry(owner, retried);
const externalPass = external.length >= config.minEvidence
? await runPatternsPass(engine, opts, config, external, { evidence: `${evidenceKey}.external`, cadence: `${cadenceKey}.external` }) : null;
- return mergeExternalPass(owner, externalPass, external.length);
+ return withAppendRetry(mergeExternalPass(owner, externalPass, external.length), retried);
}
/** One patterns child over one partition of the reflections; `keys` are that partition's evidence watermark and cadence stamp. */
@@ -715,6 +718,63 @@ async function stampPatternOutputs(engine: BrainEngine, maintenance: Maintenance
return { quoteVerify: pages ? { ...pages, ...(appended ? { timeline_appends: appended } : {}) } : null, finalized, held: heldSlugs.size, grounding };
}
+type AppendRetry = { report: GroundingReport; stats: { pages: number; entries: number; quarantined: number; repaired: number } };
+
+/**
+ * GBRA-130 A-23: ground the timeline appends earlier runs failed to ground (pattern-grounding.ts), each page against
+ * the reflections its entries were appended under and written back at their derivation, then reverse-write (or verify
+ * the managed publication of) the pages that grounded. A page held at its current content is not attempted. Null when
+ * nothing is pending.
+ */
+async function retryPendingAppends(engine: BrainEngine, opts: PatternsPhaseOpts, sourceId: string): Promise<AppendRetry | null> {
+ const run = await beginGroundingRun(engine, sourceId);
+ const slugs = Object.keys(run.pending);
+ if (slugs.length === 0) return null;
+ const hashes = new Map((await engine.executeRaw<{ slug: string; content_hash: string | null }>(
+ 'SELECT slug, content_hash FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL', [sourceId, slugs]))
+ .map(r => [r.slug, r.content_hash ?? null]));
+ const due = slugs.filter(slug => !groundingHeld(run, slug, hashes.get(slug) ?? null, run.pending));
+ const maintenance = due.length ? await maintenancePreflight(engine, sourceId, opts.brainDir) : null;
+ const cycleDate = opts.cycleDate ?? await resolveCycleDate(engine);
+ const heldSlugs = new Set<string>();
+ const stats = { pages: 0, entries: 0, quarantined: 0, repaired: 0 };
+ for (const slug of due) {
+ const { appends, reflections } = run.pending[slug]!;
+ const grounded = await groundTimelineAppends(engine, maintenance, appends, reflections, sourceId, cycleDate, opts.signal, heldSlugs, patternsDerivation(reflections), run);
+ if (!grounded) break;
+ stats.pages++;
+ stats.entries += grounded.entries;
+ stats.quarantined += grounded.quarantined;
+ stats.repaired += grounded.repaired;
+ }
+ const report = await finishGroundingRun(engine, run);
+ const rewritten = [...run.appendsResolved.keys()].filter(slug => !heldSlugs.has(slug)).map(slug => ({ slug, source_id: sourceId }));
+ if (rewritten.length) {
+ if (maintenance) await verifyMaintenanceOutputs(engine, maintenance, rewritten);
+ else await reverseWriteRefs(engine, opts.brainDir, rewritten, sourceId, opts.signal);
+ }
+ return { report, stats };
+}
+
+/**
+ * The pending-append retry rides on the phase result: its failures lead `grounding_failed`; a pass that grounded
+ * already lists every hold, else the retry's held appends are listed. A failed or held retry warns, even when the
+ * pass skipped.
+ */
+function withAppendRetry(result: PhaseResult, retried: AppendRetry | null): PhaseResult {
+ if (!retried) return result;
+ const { report, stats } = retried;
+ const passGrounded = Array.isArray(result.details.grounding_held);
+ const failed = [...report.details.grounding_failed, ...((result.details.grounding_failed ?? []) as GroundingReport['details']['grounding_failed'])];
+ const held = passGrounded ? result.details.grounding_held as GroundingReport['details']['grounding_held']
+ : report.details.grounding_held.filter(h => h.timeline_appends);
+ const details = { ...result.details, timeline_append_retry: stats, grounding_failed: failed, grounding_held: held };
+ const retryHeld = passGrounded ? 0 : held.length;
+ if (!report.details.grounding_failed.length && !retryHeld) return { ...result, details };
+ return { ...result, details, status: result.status === 'ok' || result.status === 'skipped' ? 'warn' : result.status,
+ summary: `${result.summary}; timeline-append retry: ${report.details.grounding_failed.length} page(s) failed, ${retryHeld} held (details.grounding_failed, details.grounding_held)` };
+}
+
async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,
refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal: AbortSignal | undefined,
heldSlugs: Set<string>, derivation: Derivation & { declaration: DerivationDeclaration }): Promise<void> {
@@ -796,7 +856,7 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maint
* through the segment reader (its body columns are NULL); one over the single-string ceiling is not a grounding
* source, so a quote only it holds goes to unverified_claims, and the skip is logged.
*/
-async function loadGroundingSources<T>(engine: BrainEngine, sourceId: string, reflections: ReflectionRef[],
+async function loadGroundingSources<T>(engine: BrainEngine, sourceId: string, reflections: Array<{ slug: string }>,
groundSource: (path: string, content: string, opts: { tolerant: boolean }) => T): Promise<T[]> {
const sourcePages = await engine.executeRaw<{ id: number; slug: string; body_storage: string | null; body_bytes: number | string | null; compiled_truth: string | null; timeline: string | null }>(
'SELECT id, slug, body_storage, body_bytes, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL',
@@ -848,11 +908,13 @@ async function writeGroundedPage(engine: BrainEngine, maintenance: MaintenanceAu
* put_page) against this run's reflections. A failing entry leaves the timeline for frontmatter `unverified_claims`
* (a materialized marker line in front of it goes with it); a near or normalized quote is repaired in place. Every
* other byte of the page, earlier verified content and its stored claim sources included, is kept, and an entry no
- * longer on the page is skipped. Returns null when dream.quote_verify is off. Holds, derivation and `grounding`
- * (per-page isolation, never a durable hold here) as groundPatternPages.
+ * longer on the page is skipped. Returns null when dream.quote_verify is off. Holds, derivation and `grounding` as
+ * groundPatternPages, except that every call of one run shares the run's breaker, a failed page carries its entries and
+ * reflections (pattern-grounding.ts stores them for a later run) and a page whose entries are settled (written back,
+ * unchanged or gone, and not held) has them resolved.
*/
export async function groundTimelineAppends(engine: BrainEngine, maintenance: MaintenanceAuthority | null, appends: TimelineAppend[],
- reflections: ReflectionRef[], sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,
+ reflections: Array<{ slug: string; taint?: TaintInput }>, sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,
derivation?: Derivation & { declaration: DerivationDeclaration }, grounding?: GroundingRun): Promise<{ entries: number; quarantined: number; repaired: number; segmented_skipped: number } | null> {
const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');
if (!await dreamQuoteVerifyEnabled(engine)) return null;
@@ -861,24 +923,32 @@ export async function groundTimelineAppends(engine: BrainEngine, maintenance: Ma
const sources = await loadGroundingSources(engine, sourceId, reflections, groundSource);
const { serializePageToMarkdown } = await import('../markdown.ts');
const [{ materializedSnapshot }, { bodyUnread }] = await Promise.all([import('../persistence/segmented-apply.ts'), import('../page-body/page-shape.ts')]);
- const run = grounding ? new ItemRun('patterns.ground_timeline_appends') : null;
+ const run = grounding ? (grounding.appendRun ??= new ItemRun('patterns.ground_timeline_appends')) : null;
for (const slug of [...new Set(appends.map(a => a.slug))]) {
throwIfAborted(signal, '[dream] patterns timeline quote verify');
let contentHash: string | null = null;
+ const slugAppends = appends.filter(a => a.slug === slug);
+ const resolve = () => {
+ if (!grounding || heldSlugs?.has(slug)) return;
+ const resolved = grounding.appendsResolved.get(slug) ?? new Set<string>();
+ for (const a of slugAppends) resolved.add(a.requestId);
+ grounding.appendsResolved.set(slug, resolved);
+ };
try {
// A segmented page within the single-string ceiling is read back as strings; over it, its appends stay as written (counted, logged).
const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }));
- if (!snapshot) continue;
+ if (!snapshot) { resolve(); continue; }
contentHash = snapshot.page.content_hash ?? null;
if (bodyUnread(snapshot.page)) {
stats.segmented_skipped++;
process.stderr.write(`[dream] patterns quote verify: ${slug} is a segmented page over the single-string ceiling; its timeline appends were not verified.\n`);
+ resolve();
continue;
}
let timeline = snapshot.page.timeline ?? '';
const quarantined: Array<Record<string, unknown>> = [];
const removed: TimelineAppend['entry'][] = [];
- for (const append of appends.filter(a => a.slug === slug)) {
+ for (const append of slugAppends) {
const at = timeline.indexOf(append.block);
if (at < 0) continue;
stats.entries++;
@@ -893,16 +963,18 @@ export async function groundTimelineAppends(engine: BrainEngine, maintenance: Ma
timeline = timeline.slice(0, at) + verified.body + timeline.slice(at + append.block.length);
}
}
- if (timeline === (snapshot.page.timeline ?? '')) continue;
+ if (timeline === (snapshot.page.timeline ?? '')) { resolve(); continue; }
const frontmatter = quarantined.length
? withClaimSources(snapshot.page.frontmatter as Record<string, unknown>, quarantined, sources.map(x => x.path)).frontmatter
: snapshot.page.frontmatter;
await writeGroundedPage(engine, maintenance, snapshot, serializePageToMarkdown({ ...snapshot.page, timeline, frontmatter }, snapshot.tags),
sourceId, heldSlugs, derivation, removed);
run?.succeed();
+ resolve();
} catch (error) {
if (!run || !grounding) throw error;
- grounding.failed.push({ ...run.fail(slug, error), content_hash: contentHash, timelineAppend: true });
+ grounding.failed.push({ ...run.fail(slug, error), content_hash: contentHash, timelineAppend: true,
+ inputs: { appends: slugAppends, reflections: reflections.map(r => ({ slug: r.slug, ...(r.taint ? { taint: r.taint } : {}) })) } });
}
}
return stats;
diff --git a/test/pathological/a23-patterns-grounding.test.ts b/test/pathological/a23-patterns-grounding.test.ts
index 44615771ab..9c00d2349c 100644
--- a/test/pathological/a23-patterns-grounding.test.ts
+++ b/test/pathological/a23-patterns-grounding.test.ts
@@ -19,7 +19,7 @@
* trigger on pages, and the child is the spied inline drain.
*/
import { describe, expect, spyOn, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
@@ -28,6 +28,10 @@ import * as synthesize from '../../src/core/cycle/synthesize.ts';
import * as wait from '../../src/core/minions/wait-for-completion.ts';
import { groundTimelineAppends, runPhasePatterns, type TimelineAppend } from '../../src/core/cycle/patterns.ts';
import { renderTimelineEntry } from '../../src/core/timeline-write-through.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { buildBrainTools } from '../../src/core/minions/tools/brain-allowlist.ts';
+import { retainToolWriteRequestId } from '../../src/core/minions/tool-write-identity.ts';
+import { persistToolExecComplete, persistToolExecPending } from '../../src/core/minions/handlers/subagent-persistence.ts';
import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
import { withEnv } from '../helpers/with-env.ts';
import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
@@ -203,7 +207,7 @@ async function appendedPages(engine: BrainEngine): Promise<TimelineAppend[]> {
return out;
}
const REFLECTIONS = [1, 2, 3].map(i => ({ slug: 'wiki/personal/reflections/r' + i })) as never;
-const groundingRun = () => ({ sourceId: 'default', holds: {}, failed: [] as Array<{ key: string; code: string }>, grounded: new Set<string>() });
+const groundingRun = () => ({ sourceId: 'default', holds: {}, pending: {}, failed: [] as Array<{ key: string; code: string }>, grounded: new Set<string>(), appendsResolved: new Map<string, Set<string>>() });
describe('A-23 timeline-append grounding isolates one page whose write-back is refused', () => {
for (const { backend, databaseUrl } of pathologicalArms()) {
@@ -238,3 +242,96 @@ describe('A-23 timeline-append grounding isolates one page whose write-back is r
}
}
});
+
+const APPENDED = PREFIX + '/a-theme';
+const APPENDS_KEY = 'dream.patterns.grounding_appends.default';
+
+/** A pattern page an earlier run verified; a later child appends a timeline entry to it. */
+const verifiedPage = (engine: BrainEngine, body = 'A theme.') => importFromContent(engine, APPENDED,
+ '---\ntype: note\ntitle: A theme\ndream_generated: true\nquote_verified_at: \'2026-10-01\'\n---\n' + body + '\n', { noEmbed: true, sourceId: 'default' });
+
+/**
+ * A completed patterns child that appends one entry quoting text the reflections never said, through the real
+ * brain tool and the subagent tool-execution ledger (production request ids and receipts); `afterChild` runs
+ * once the child is done and before grounding.
+ */
+async function withAppendingChild<T>(engine: BrainEngine, databaseUrl: string | undefined, run: () => Promise<T>, afterChild?: () => Promise<unknown>): Promise<{ result: T; children: number }> {
+ let children = 0;
+ const drain = spyOn(synthesize, 'runSubagentsInline').mockImplementation((async (e: BrainEngine, _queue: unknown, queueName: string) => {
+ children++;
+ const [job] = await e.executeRaw<{ id: number }>('SELECT id FROM minion_jobs WHERE queue = $1 ORDER BY id DESC LIMIT 1', [queueName]);
+ const jobId = Number(job!.id);
+ const tool = buildBrainTools({ subagentId: jobId, engine: e, config: { engine: databaseUrl ? 'postgres' : 'pglite' } as GBrainConfig,
+ allowedSlugPrefixes: [PREFIX + '/*'], sourceId: 'default' }).find(t => t.name === 'brain_add_timeline_entry')!;
+ const input: Record<string, unknown> = { slug: APPENDED, date: '2026-10-1' + children, summary: 'You wrote "always test on staging" again (run ' + children + ')', source: 'wiki/personal/reflections/r3' };
+ retainToolWriteRequestId(input, jobId, 1, 0, 'toolu_0', tool.name);
+ await persistToolExecPending(e, jobId, 1, 0, 'toolu_0', tool.name, input);
+ await persistToolExecComplete(e, jobId, 1, 0, 'toolu_0', await tool.execute(input, { engine: e, jobId, remote: true }));
+ await afterChild?.();
+ }) as never);
+ const completed = spyOn(wait, 'waitForCompletionRenewing').mockImplementation((async (_q: unknown, jobId: number) => ({ id: jobId, status: 'completed', error_text: null })) as never);
+ try { return { result: await run(), children }; } finally { drain.mockRestore(); completed.mockRestore(); }
+}
+const pendingAppends = async (engine: BrainEngine) => JSON.parse((await engine.getConfig(APPENDS_KEY)) ?? '{}') as { items?: Record<string, { attempts: number; held_at: string | null; appends: unknown[] }> };
+
+describe('A-23 a timeline append whose grounding write-back failed is retried on a later run', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test('[' + backend + '] the failed append is recorded durably and the next run grounds it without a new child', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await verifiedPage(engine);
+ const first = await withAppendingChild(engine, databaseUrl, () => patterns(engine, brainDir), () => refuseWrites(engine, [APPENDED]));
+ expect(first.result.status).toBe('warn');
+ expectItemFailure((first.result.details.grounding_failed as GroundingRow[])[0], { key: APPENDED, code: 'invalid_data' });
+ expect((await engine.getPage(APPENDED))!.timeline).toContain('always test on staging');
+ expect(readFileSync(join(brainDir, APPENDED + '.md'), 'utf8')).toContain('always test on staging');
+ expect(await engine.getConfig(EVIDENCE_KEY)).not.toBeNull();
+ expect((await pendingAppends(engine)).items?.[APPENDED]).toMatchObject({ attempts: 1, held_at: null });
+
+ await allowWrites(engine);
+ const before = await snapshotItems(engine, 'default');
+ const again = await withAppendingChild(engine, databaseUrl, () => expectUnitNotAborted(() => patterns(engine, brainDir, false)));
+ expect(again.children).toBe(0);
+ expect(again.result.details.reason).toBe('no_new_evidence');
+ expect(again.result.details.grounding_failed).toEqual([]);
+ expect(again.result.details.timeline_append_retry).toMatchObject({ pages: 1, entries: 1, quarantined: 1 });
+ const page = (await engine.getPage(APPENDED))!;
+ expect(page.timeline).not.toContain('always test on staging');
+ expect((page.frontmatter.unverified_claims as Array<{ text: string }>).map(c => c.text).join('\n')).toContain('always test on staging');
+ expect((await engine.getTimeline(APPENDED, { sourceId: 'default' })).map(r => r.summary).join('\n')).not.toContain('always test on staging');
+ expect(readFileSync(join(brainDir, APPENDED + '.md'), 'utf8').split('\n---\n').slice(1).join('\n---\n')).not.toContain('always test on staging');
+ expect(await engine.getConfig(APPENDS_KEY)).toBe(JSON.stringify({ version: 1, items: {} }));
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { expectProgress: [APPENDED], progressFields: ['content_hash'] });
+ });
+ }, 180_000);
+
+ test('[' + backend + '] an append refused on 3 runs at one content hash is held with a typed warning until the page changes', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await verifiedPage(engine);
+ await withAppendingChild(engine, databaseUrl, () => patterns(engine, brainDir), () => refuseWrites(engine, [APPENDED]));
+ for (let run = 2; run <= 3; run++) {
+ const { result } = await withAppendingChild(engine, databaseUrl, () => patterns(engine, brainDir, false));
+ expect({ run, status: result.status, failed: (result.details.grounding_failed as GroundingRow[]).map(f => f.slug) }).toEqual({ run, status: 'warn', failed: [APPENDED] });
+ }
+ expect((await pendingAppends(engine)).items?.[APPENDED]).toMatchObject({ attempts: 3 });
+ expect((await pendingAppends(engine)).items?.[APPENDED]?.held_at).not.toBeNull();
+ const held = await withAppendingChild(engine, databaseUrl, () => patterns(engine, brainDir, false));
+ expect(held.children).toBe(0);
+ expect(held.result.status).toBe('warn');
+ expect(held.result.details.grounding_failed).toEqual([]);
+ const rows = held.result.details.grounding_held as Array<GroundingRow & { timeline_appends?: number }>;
+ expect(rows.map(r => ({ slug: r.slug, code: r.code, timeline_appends: r.timeline_appends }))).toEqual([{ slug: APPENDED, code: 'invalid_data', timeline_appends: 1 }]);
+ expectItemFailure({ key: rows[0]!.slug, code: rows[0]!.code, fix: rows[0]!.fix }, { key: APPENDED, code: 'invalid_data', fix: /^gbrain get --source default -- wiki\/personal\/patterns\/a-theme$/ });
+ expect((await pendingAppends(engine)).items?.[APPENDED]).toMatchObject({ attempts: 3 });
+
+ await allowWrites(engine);
+ const timeline = (await engine.getPage(APPENDED))!.timeline;
+ await importFromContent(engine, APPENDED, '---\ntype: note\ntitle: A theme\ndream_generated: true\nquote_verified_at: \'2026-10-01\'\n---\nA theme, edited.\n\n<!-- timeline -->\n## Timeline\n\n' + timeline.replace(/^[\s\S]*?## Timeline\n+/, '') + '\n', { noEmbed: true, sourceId: 'default' });
+ const released = await withAppendingChild(engine, databaseUrl, () => patterns(engine, brainDir, false));
+ expect(released.result.details.grounding_held).toEqual([]);
+ expect(released.result.status).toBe('skipped');
+ expect((await engine.getPage(APPENDED))!.timeline).not.toContain('always test on staging');
+ expect((await pendingAppends(engine)).items?.[APPENDED]).toBeUndefined();
+ });
+ }, 240_000);
+ }
+});