Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(patterns): one page that fails quote grounding no longer fails the paid run; repeat content refusals are held (GBRA-130 A-23)

garrytan9004b380ecb6
diff --git a/src/core/cycle/pattern-grounding.ts b/src/core/cycle/pattern-grounding.ts
new file mode 100644
index 0000000000..ad5df657de
--- /dev/null
+++ b/src/core/cycle/pattern-grounding.ts
@@ -0,0 +1,106 @@
+/**
+ * Quote-grounding isolation for the patterns phase (GBRA-130 A-23).
+ *
+ * After a completed (paid) patterns child, quote grounding rewrites every
+ * pattern page the child wrote and every leftover page a crashed run left
+ * without \`quote_verified_at\`. One page whose write-back fails is recorded
+ * here and the rest still ground; the evidence watermark is stamped as usual,
+ * so the failure never buys another child for the same evidence. Run-scoped
+ * errors and a systemic run (item-failure.ts \`ItemRun\`) still fail the phase
+ * and record nothing.
+ *
+ * Holds: a leftover page refused with a content-class error on 3 consecutive
+ * runs at the same \`content_hash\` and the same producer (the gbrain version,
+ * which carries the verifier and the writer) is held out of the leftover
+ * query. A held page is never reported as grounded: \`grounding_held\` lists it
+ * 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.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
+import type { ItemFailure } from '../item-failure.ts';
+import { VERSION } from '../../version.ts';
+
+export const GROUNDING_HOLDS_KEY = 'dream.patterns.grounding_holds';
+export const GROUNDING_HOLD_RUNS = 3;
+
+export interface GroundingHold {
+ content_hash: string | null;
+ producer: string;
+ code: string;
+ message: string;
+ attempts: number;
+ held_at: string | null;
+ last_failed_at: string;
+}
+
+/** One run's grounding: the holds it began with, the pages that failed and the pages that grounded. */
+export interface GroundingRun {
+ sourceId: string;
+ holds: Record<string, GroundingHold>;
+ failed: Array<ItemFailure & { content_hash: string | null; timeline: boolean }>;
+ grounded: Set<string>;
+}
+
+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 }> };
+}
+
+const holdsKey = (sourceId: string) => `${GROUNDING_HOLDS_KEY}.${sourceId}`;
+
+export async function beginGroundingRun(engine: BrainEngine, sourceId: string): Promise<GroundingRun> {
+ let holds: Record<string, GroundingHold> = {};
+ 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;
+ } catch { /* an unreadable record holds nothing */ }
+ return { sourceId, holds, failed: [], grounded: new Set() };
+}
+
+/** 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];
+ 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. */
+export async function finishGroundingRun(engine: BrainEngine, run: GroundingRun): Promise<GroundingReport> {
+ const now = new Date().toISOString();
+ const holds = { ...run.holds };
+ for (const slug of run.grounded) delete holds[slug];
+ for (const f of run.failed) {
+ if (f.timeline) 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 };
+ }
+ const changed = JSON.stringify(holds) !== JSON.stringify(run.holds);
+ if (changed) await engine.setConfig(holdsKey(run.sourceId), JSON.stringify({ version: 1, items: holds }));
+ 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}`;
+ 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.timeline && !!holds[f.key]?.held_at,
+ fix: f.timeline ? `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 })),
+ },
+ };
+}
+
+/** A run that failed or held a page warns, even after a clean child: a held page is not a grounded one. */
+export function withGroundingStatus(result: PhaseResult, report: GroundingReport): PhaseResult {
+ const failed = report.details.grounding_failed.length;
+ const held = report.details.grounding_held.length;
+ if (!failed && !held) return result;
+ return { ...result, status: result.status === 'ok' ? 'warn' : result.status,
+ summary: `${result.summary}; quote grounding: ${failed} page(s) failed, ${held} held (details.grounding_failed, details.grounding_held)` };
+}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 96dfd471be..411e9d8216 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -57,6 +57,8 @@ import { publishOrHold } from '../persistence/accepted-pending.ts';
import { derivedMaintenanceTransaction, isExternalTier, type DerivationDeclaration } from '../trust/taint.ts';
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';
export interface PatternsPhaseOpts {
brainDir: string;
@@ -416,11 +418,11 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con
const { putPageRefs, appends, writtenRefs, appendedUnverified } = await collectPatternOutputs(engine, job.id, cycleSourceId, config.outputSlugPrefix);
// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.
- const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, putPageRefs, appends, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);
+ const { quoteVerify, finalized, held, grounding } = await stampPatternOutputs(engine, maintenance, putPageRefs, appends, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);
const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized)
: await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);
const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,
- ...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held,
+ ...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held, ...grounding.details,
timeline_appends: appends.length, appended_unverified: appendedUnverified, child_outcome: outcome, job_id: job.id };
const appendedNote = appends.length > 0 ? `; ${appends.length} timeline entr${appends.length === 1 ? 'y' : 'ies'} appended${quoteVerify ? ' (quote-verified)' : ''}` : '';
@@ -466,7 +468,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con
// named nothing; re-running it is exactly the spend bug.
await engine.setConfig(keys.evidence, new Date(newestEvidenceMs).toISOString());
- return ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details);
+ return withGroundingStatus(ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details), grounding);
} catch (e) {
return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',
e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));
@@ -694,19 +696,23 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag
/**
* Quote-ground the pattern outputs (and pages a crashed run left unverified), then stamp provenance on the
* outputs. Returns the grounding counts (null when dream.quote_verify is off), the written refs whose managed
- * publications all landed, and the number of pages whose publication is held for a later cycle.
+ * publications all landed, the number of pages whose publication is held for a later cycle, and the grounding
+ * report (pattern-grounding.ts): a page whose grounding failed is neither stamped nor counted as written.
*/
async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null, written: Array<{ slug: string; source_id: string }>,
appends: TimelineAppend[], reflections: ReflectionRef[], derivation: Derivation & { declaration: DerivationDeclaration },
config: { outputSlugPrefix: string; sourceSlugPrefix: string }, sourceId: string, cycleDate: string, signal?: AbortSignal) {
const heldSlugs = new Set<string>();
- const pages = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs, derivation);
- const appended = await groundTimelineAppends(engine, maintenance, appends, reflections, sourceId, cycleDate, signal, heldSlugs, derivation);
- const outputs = [...written, ...[...new Set(appends.map(a => a.slug))].map(slug => ({ slug, source_id: sourceId }))];
+ const run = await beginGroundingRun(engine, sourceId);
+ const pages = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs, derivation, run);
+ const appended = await groundTimelineAppends(engine, maintenance, appends, reflections, sourceId, cycleDate, signal, heldSlugs, derivation, run);
+ const grounding = await finishGroundingRun(engine, run);
+ const outputs = [...written, ...[...new Set(appends.map(a => a.slug))].map(slug => ({ slug, source_id: sourceId }))]
+ .filter(ref => ref.source_id !== sourceId || !grounding.failedSlugs.has(ref.slug));
await stampProvenance(engine, maintenance, outputs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs, derivation);
// Holds are recorded for this cycle's source only, so a ref in any other source is never excused from verification.
const finalized = outputs.filter(ref => ref.source_id !== sourceId || !heldSlugs.has(ref.slug));
- return { quoteVerify: pages ? { ...pages, ...(appended ? { timeline_appends: appended } : {}) } : null, finalized, held: heldSlugs.size };
+ return { quoteVerify: pages ? { ...pages, ...(appended ? { timeline_appends: appended } : {}) } : null, finalized, held: heldSlugs.size, grounding };
}
async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,
@@ -734,40 +740,53 @@ async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuth
* dream.quote_verify (default on). Returns null when disabled. With `heldSlugs`
* a managed publish that is pending or contended (publicationHold) is recorded
* there and the loop moves on; without it every publish error propagates.
- * `derivation` (#5575) is the pass's taint: a page this run wrote is written back at that tier.
+ * `derivation` (#5575) is the pass's taint: a page this run wrote is written back at that tier. With `grounding`
+ * (GBRA-130 A-23) one page whose write-back fails is recorded there and the loop moves on (run-scoped errors and a
+ * systemic run still throw), and a leftover page held at its current content is skipped.
*/
export async function groundPatternPages(engine: BrainEngine, maintenance: MaintenanceAuthority | null, refs: Array<{ slug: string; source_id: string }>,
reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,
- derivation?: Derivation & { declaration: DerivationDeclaration }):
+ derivation?: Derivation & { declaration: DerivationDeclaration }, grounding?: GroundingRun):
Promise<{ pages: number; quarantined: number; repaired: number } | null> {
const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');
if (!await dreamQuoteVerifyEnabled(engine)) return null;
- const leftover = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE source_id = $1 AND slug LIKE $2 AND deleted_at IS NULL
- AND frontmatter->>'dream_generated' = 'true' AND frontmatter->>'quote_verified_at' IS NULL`, [sourceId, `${outputSlugPrefix}/%`]);
+ const leftover = (await engine.executeRaw<{ slug: string; content_hash: string | null }>(
+ `SELECT slug, content_hash FROM pages WHERE source_id = $1 AND slug LIKE $2 AND deleted_at IS NULL
+ AND frontmatter->>'dream_generated' = 'true' AND frontmatter->>'quote_verified_at' IS NULL`, [sourceId, `${outputSlugPrefix}/%`]))
+ .filter(r => !grounding || !groundingHeld(grounding, r.slug, r.content_hash ?? null));
const slugs = [...new Set([...refs.map(r => r.slug).filter(slug => slug.startsWith(`${outputSlugPrefix}/`)), ...leftover.map(r => r.slug)])];
if (slugs.length === 0) return { pages: 0, quarantined: 0, repaired: 0 };
const sources = await loadGroundingSources(engine, sourceId, reflections, groundSource);
const stats = { pages: 0, quarantined: 0, repaired: 0 };
const { serializePageToMarkdown } = await import('../markdown.ts');
+ const run = grounding ? new ItemRun('patterns.ground_pages') : null;
for (const slug of slugs) {
throwIfAborted(signal, '[dream] patterns quote verify');
- const derived = derivation && refs.some(r => r.slug === slug) ? derivation : undefined;
- const snapshot = await engine.readPageSnapshot(slug, { sourceId });
- if (!snapshot) continue;
- const ct = verifyBody(snapshot.page.compiled_truth, sources, { checks: 'quotes' });
- const tl = verifyBody(snapshot.page.timeline ?? '', sources, { checks: 'quotes' });
- const quarantined = [...ct.quarantined, ...tl.quarantined];
- stats.pages++;
- stats.quarantined += quarantined.length;
- stats.repaired += ct.normalized + ct.near + tl.normalized + tl.near;
- // #6236: the reflection list is stored once per page (lossless), not on every claim.
- const { frontmatter } = withClaimSources({ ...snapshot.page.frontmatter, quote_verified_at: cycleDate },
- quarantined.map(c => ({ ...c, detected_at: cycleDate })), sources.map(x => x.path));
- const page = { ...snapshot.page,
- compiled_truth: ct.body.trim() ? ct.body : (await import('./synthesize-verify.ts')).ALL_CLAIMS_QUARANTINED_BODY,
- timeline: tl.body, frontmatter };
- await writeGroundedPage(engine, maintenance, snapshot, serializePageToMarkdown(page, snapshot.tags), sourceId, heldSlugs, derived);
+ let contentHash: string | null = null;
+ try {
+ const derived = derivation && refs.some(r => r.slug === slug) ? derivation : undefined;
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot) continue;
+ contentHash = snapshot.page.content_hash ?? null;
+ const ct = verifyBody(snapshot.page.compiled_truth, sources, { checks: 'quotes' });
+ const tl = verifyBody(snapshot.page.timeline ?? '', sources, { checks: 'quotes' });
+ const quarantined = [...ct.quarantined, ...tl.quarantined];
+ stats.pages++;
+ stats.quarantined += quarantined.length;
+ stats.repaired += ct.normalized + ct.near + tl.normalized + tl.near;
+ // #6236: the reflection list is stored once per page (lossless), not on every claim.
+ const { frontmatter } = withClaimSources({ ...snapshot.page.frontmatter, quote_verified_at: cycleDate },
+ quarantined.map(c => ({ ...c, detected_at: cycleDate })), sources.map(x => x.path));
+ const page = { ...snapshot.page,
+ compiled_truth: ct.body.trim() ? ct.body : (await import('./synthesize-verify.ts')).ALL_CLAIMS_QUARANTINED_BODY,
+ timeline: tl.body, frontmatter };
+ await writeGroundedPage(engine, maintenance, snapshot, serializePageToMarkdown(page, snapshot.tags), sourceId, heldSlugs, derived);
+ run?.succeed();
+ grounding?.grounded.add(slug);
+ } catch (error) {
+ if (!run || !grounding) throw error;
+ grounding.failed.push({ ...run.fail(slug, error), content_hash: contentHash, timeline: false });
+ }
}
return stats;
}
@@ -829,11 +848,12 @@ 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 and derivation as groundPatternPages.
+ * 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.
*/
export async function groundTimelineAppends(engine: BrainEngine, maintenance: MaintenanceAuthority | null, appends: TimelineAppend[],
reflections: ReflectionRef[], sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,
- derivation?: Derivation & { declaration: DerivationDeclaration }): Promise<{ entries: number; quarantined: number; repaired: number; segmented_skipped: number } | null> {
+ 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;
const stats = { entries: 0, quarantined: 0, repaired: 0, segmented_skipped: 0 };
@@ -841,40 +861,49 @@ 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;
for (const slug of [...new Set(appends.map(a => a.slug))]) {
throwIfAborted(signal, '[dream] patterns timeline quote verify');
- // 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 (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`);
- 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)) {
- const at = timeline.indexOf(append.block);
- if (at < 0) continue;
- stats.entries++;
- const verified = verifyBody(append.block, sources, { checks: 'quotes' });
- if (verified.quarantined.length > 0) {
- stats.quarantined += verified.quarantined.length;
- quarantined.push(...verified.quarantined.map(c => ({ ...c, detected_at: cycleDate })));
- timeline = removeTimelineBlock(timeline, at, append.block.length, append.marker);
- removed.push(append.entry);
- } else if (verified.changed) {
- stats.repaired += verified.normalized + verified.near;
- timeline = timeline.slice(0, at) + verified.body + timeline.slice(at + append.block.length);
+ let contentHash: string | null = null;
+ 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;
+ 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`);
+ 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)) {
+ const at = timeline.indexOf(append.block);
+ if (at < 0) continue;
+ stats.entries++;
+ const verified = verifyBody(append.block, sources, { checks: 'quotes' });
+ if (verified.quarantined.length > 0) {
+ stats.quarantined += verified.quarantined.length;
+ quarantined.push(...verified.quarantined.map(c => ({ ...c, detected_at: cycleDate })));
+ timeline = removeTimelineBlock(timeline, at, append.block.length, append.marker);
+ removed.push(append.entry);
+ } else if (verified.changed) {
+ stats.repaired += verified.normalized + verified.near;
+ timeline = timeline.slice(0, at) + verified.body + timeline.slice(at + append.block.length);
+ }
}
+ if (timeline === (snapshot.page.timeline ?? '')) 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();
+ } catch (error) {
+ if (!run || !grounding) throw error;
+ grounding.failed.push({ ...run.fail(slug, error), content_hash: contentHash, timeline: true });
}
- if (timeline === (snapshot.page.timeline ?? '')) 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);
}
return stats;
}
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index e4d0f7f165..1dce5202c9 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -30,6 +30,8 @@ export const ISOLATE_SITES = {
'consolidate.buckets': 'A-22',
'extract_facts.expire_deleted': 'A-21',
'maintain.cycle_sources': 'A-41',
+ 'patterns.ground_pages': 'A-23',
+ 'patterns.ground_timeline_appends': 'A-23',
} as const satisfies Record<string, string>;
export type IsolateSite = keyof typeof ISOLATE_SITES;
diff --git a/test/pathological/a23-patterns-grounding.test.ts b/test/pathological/a23-patterns-grounding.test.ts
new file mode 100644
index 0000000000..44615771ab
--- /dev/null
+++ b/test/pathological/a23-patterns-grounding.test.ts
@@ -0,0 +1,240 @@
+/**
+ * GBRA-130 A-23: after a completed (paid) patterns child, quote grounding
+ * walks every pattern page the child wrote plus every leftover pattern page a
+ * crashed run left without quote_verified_at, and wrote each back with no
+ * per-page catch. One leftover page whose write-back is refused failed the
+ * phase after the child was paid for, left the evidence watermark unstamped,
+ * and so paid for a new child every cadence period. Now the page is reported
+ * in details.grounding_failed with its code, the other pages ground, the
+ * watermark is stamped and the phase warns; a page refused with a content
+ * error on 3 runs at the same content hash and producer version is held out
+ * of the leftover query (details.grounding_held, with the command that retries
+ * it) until the page or the producer changes. Run-scoped errors still fail it.
+ *
+ * Authoring gate: (1) protects per-page isolation of groundPatternPages and
+ * groundTimelineAppends, the watermark on an isolated failure and the durable
+ * hold; (2) fails when a grounding loop loses its catch, a failure blocks the
+ * watermark, or a hold never clears; (3) test/cycle-patterns-quote-verify.test.ts
+ * covers healthy pages only; (4) no production seam: the refusal is a real
+ * 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 { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+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 { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const PREFIX = 'wiki/personal/patterns';
+const LEFTOVER = PREFIX + '/old-theme';
+const FRESH = PREFIX + '/new-theme';
+const HOLDS_KEY = 'dream.patterns.grounding_holds.default';
+const EVIDENCE_KEY = 'dream.patterns.last_evidence_ts';
+
+async function withPatternsBrain(databaseUrl: string | undefined, run: (engine: BrainEngine, brainDir: string) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-a23-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, ANTHROPIC_API_KEY: 'sk-ant-test' }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');
+ await engine.setConfig('dream.quote_verify', 'true');
+ for (const [i, body] of ['I keep saying "ship smaller pieces" when projects stall.', 'Again I told myself to ship smaller pieces.', 'Shipping smaller pieces worked this week.'].entries()) {
+ await importFromContent(engine, 'wiki/personal/reflections/r' + (i + 1), '---\ntype: note\ntitle: r' + (i + 1) + '\n---\n' + body + '\n', { noEmbed: true, sourceId: 'default' });
+ }
+ await run(engine, dir);
+ } finally { await close(); }
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}
+
+/** A pattern page a crashed run left without quote_verified_at. */
+const leftover = (engine: BrainEngine, slug = LEFTOVER, body = 'Small pieces recur.') => importFromContent(engine, slug,
+ '---\ntype: note\ntitle: ' + slug + '\ndream_generated: true\n---\n' + body + '\n', { noEmbed: true, sourceId: 'default' });
+
+/** Refuses every update of the named pages, the way the database refuses one row's write (a check violation). */
+async function refuseWrites(engine: BrainEngine, slugs: string[]): Promise<void> {
+ const list = slugs.map(s => "'" + s + "'").join(',');
+ await engine.executeRaw('CREATE OR REPLACE FUNCTION patho_refuse_page() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.slug IN (' + list
+ + ") THEN RAISE EXCEPTION 'write refused for %', NEW.slug USING ERRCODE = '23514'; END IF; RETURN NEW; END $$");
+ await engine.executeRaw('DROP TRIGGER IF EXISTS patho_refuse_page ON pages');
+ await engine.executeRaw('CREATE TRIGGER patho_refuse_page BEFORE UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION patho_refuse_page()');
+}
+const allowWrites = (engine: BrainEngine) => engine.executeRaw('DROP TRIGGER IF EXISTS patho_refuse_page ON pages');
+
+/** A completed patterns child that writes FRESH through put_page (the inline drain and its completion wait, spied). */
+async function withCompletedChild<T>(engine: BrainEngine, run: () => Promise<T>, afterChild?: () => void): 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]);
+ await importFromContent(e, FRESH, '---\ntype: note\ntitle: New theme\n---\nShipping smaller pieces recurs (run ' + children + ').\n', { noEmbed: true, sourceId: 'default' });
+ await e.executeRaw("INSERT INTO subagent_tool_executions(job_id,message_idx,tool_use_id,tool_name,input,status,ordinal) VALUES($1,0,'toolu_0','brain_put_page',$2::jsonb,'complete',0)",
+ [Number(job!.id), JSON.stringify({ slug: FRESH })]);
+ 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 patterns = (engine: BrainEngine, brainDir: string, once = true) => runPhasePatterns(engine, { brainDir, dryRun: false, once, cycleDate: '2026-10-15' });
+type GroundingRow = { slug: string; code: string; fix: string; held?: boolean };
+const holds = async (engine: BrainEngine) => JSON.parse((await engine.getConfig(HOLDS_KEY)) ?? '{}') as { items?: Record<string, { attempts: number; held_at: string | null; producer: string }> };
+
+describe('A-23 patterns grounding isolates one page whose write-back is refused', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test('[' + backend + '] a refused leftover pattern page is reported, the new page grounds and the watermark is stamped', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await leftover(engine);
+ await refuseWrites(engine, [LEFTOVER]);
+ const before = await snapshotItems(engine, 'default');
+ const { result } = await withCompletedChild(engine, () => expectUnitNotAborted(() => patterns(engine, brainDir)));
+ expect(result.error?.code).toBeUndefined();
+ expect(result.status).toBe('warn');
+ const failed = result.details.grounding_failed as GroundingRow[];
+ expect(failed).toHaveLength(1);
+ expectItemFailure({ key: failed[0]!.slug, code: failed[0]!.code, fix: failed[0]!.fix }, { key: LEFTOVER, code: 'invalid_data', fix: /^gbrain dream --phase patterns --once --source default$/ });
+ expect((await engine.getPage(FRESH))!.frontmatter.quote_verified_at).toBe('2026-10-15');
+ expect((await engine.getPage(LEFTOVER))!.frontmatter.quote_verified_at).toBeUndefined();
+ expect(await engine.getConfig(EVIDENCE_KEY)).not.toBeNull();
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: [FRESH] });
+ const again = await withCompletedChild(engine, () => patterns(engine, brainDir, false));
+ expect(again.children).toBe(0);
+ expect(again.result.details.reason ?? again.result.summary).toMatch(/no_new_evidence|none newer/);
+ });
+ }, 120_000);
+
+ test('[' + backend + '] three content refusals at one content hash hold the page out of the leftover query until it changes', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await leftover(engine);
+ await refuseWrites(engine, [LEFTOVER]);
+ for (let run = 1; run <= 3; run++) {
+ const { result } = await withCompletedChild(engine, () => patterns(engine, brainDir));
+ expect({ run, failed: (result.details.grounding_failed as GroundingRow[]).map(f => f.slug) }).toEqual({ run, failed: [LEFTOVER] });
+ }
+ expect((await holds(engine)).items?.[LEFTOVER]).toMatchObject({ attempts: 3 });
+ expect((await holds(engine)).items?.[LEFTOVER]?.held_at).not.toBeNull();
+ const { result } = await withCompletedChild(engine, () => patterns(engine, brainDir));
+ expect(result.details.grounding_failed).toEqual([]);
+ expect(result.status).toBe('warn');
+ const held = result.details.grounding_held as GroundingRow[];
+ expectItemFailure({ key: held[0]!.slug, code: held[0]!.code, fix: held[0]!.fix },
+ { key: LEFTOVER, code: 'invalid_data', fix: new RegExp('^gbrain config unset ' + HOLDS_KEY.replace(/\./g, '\\.') + ' && gbrain dream --phase patterns --once --source default$') });
+ await allowWrites(engine);
+ await leftover(engine, LEFTOVER, 'Small pieces recur, edited.');
+ const cleared = await withCompletedChild(engine, () => patterns(engine, brainDir));
+ expect(cleared.result.details.grounding_held).toEqual([]);
+ expect(cleared.result.status).toBe('ok');
+ expect((await engine.getPage(LEFTOVER))!.frontmatter.quote_verified_at).toBe('2026-10-15');
+ expect((await holds(engine)).items?.[LEFTOVER]).toBeUndefined();
+ });
+ }, 180_000);
+
+ test('[' + backend + '] a held page is retried once the producer version changes', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await leftover(engine);
+ await refuseWrites(engine, [LEFTOVER]);
+ for (let run = 1; run <= 3; run++) await withCompletedChild(engine, () => patterns(engine, brainDir));
+ const stored = await holds(engine);
+ stored.items![LEFTOVER]!.producer = '0.0.0-older';
+ await engine.setConfig(HOLDS_KEY, JSON.stringify(stored));
+ await allowWrites(engine);
+ const { result } = await withCompletedChild(engine, () => patterns(engine, brainDir));
+ expect(result.details.grounding_held).toEqual([]);
+ expect((await engine.getPage(LEFTOVER))!.frontmatter.quote_verified_at).toBe('2026-10-15');
+ });
+ }, 180_000);
+
+ test('[' + backend + '] most pages refused trips the breaker and holds nothing', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ const slugs = ['a', 'b', 'c', 'd', 'e'].map(x => PREFIX + '/' + x + '-theme');
+ for (const slug of slugs) await leftover(engine, slug);
+ await refuseWrites(engine, slugs);
+ const { result } = await withCompletedChild(engine, () => patterns(engine, brainDir));
+ expect(result.status).toBe('fail');
+ expect(result.error?.message).toMatch(/items failed at patterns\.ground_pages/);
+ expect(await engine.getConfig(HOLDS_KEY)).toBeNull();
+ expect(await engine.getConfig(EVIDENCE_KEY)).toBeNull();
+ });
+ }, 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test('[' + backend + '] a run-scoped error while grounding a page still fails the phase (' + name + ')', async () => {
+ await withPatternsBrain(databaseUrl, async (engine, brainDir) => {
+ await leftover(engine);
+ const injected = error();
+ // Transaction engines inherit from the engine, so the override forwards `this` (a bound read would leave the transaction).
+ const read = engine.readPageSnapshot;
+ const inject = () => {
+ engine.readPageSnapshot = async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {
+ if (slug === LEFTOVER) throw injected;
+ return read.call(this, slug, opts);
+ } as BrainEngine['readPageSnapshot'];
+ };
+ try {
+ const { result } = await withCompletedChild(engine, () => patterns(engine, brainDir), inject);
+ expect(result.status).toBe('fail');
+ expect(result.error?.code).toBe('PATTERNS_PHASE_FAIL');
+ } finally { engine.readPageSnapshot = read; }
+ expect(await engine.getConfig(HOLDS_KEY)).toBeNull();
+ expect(await engine.getConfig(EVIDENCE_KEY)).toBeNull();
+ });
+ }, 120_000);
+ }
+ }
+});
+
+/** Two pages with one new timeline entry each, quoting text the reflections never said (so grounding rewrites both). */
+async function appendedPages(engine: BrainEngine): Promise<TimelineAppend[]> {
+ const out: TimelineAppend[] = [];
+ for (const slug of [PREFIX + '/a-theme', PREFIX + '/b-theme']) {
+ const rendered = renderTimelineEntry({ date: '2026-10-10', summary: 'You wrote "always test on staging" again', source: 'wiki/personal/reflections/r3' }, slug)!;
+ await importFromContent(engine, slug, '---\ntype: note\ntitle: ' + slug + "\ndream_generated: true\nquote_verified_at: '2026-10-01'\n---\nA theme.\n\n<!-- timeline -->\n## Timeline\n\n" + rendered.block + '\n',
+ { noEmbed: true, sourceId: 'default' });
+ out.push({ slug, requestId: 'req-' + slug, block: rendered.block, marker: '<!-- no marker -->', entry: rendered.canonical });
+ }
+ 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>() });
+
+describe('A-23 timeline-append grounding isolates one page whose write-back is refused', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test('[' + backend + '] a refused timeline-append page is recorded and the other page still grounds', async () => {
+ await withPatternsBrain(databaseUrl, async engine => {
+ const appends = await appendedPages(engine);
+ await refuseWrites(engine, [PREFIX + '/a-theme']);
+ const before = await snapshotItems(engine, 'default');
+ const grounding = groundingRun();
+ const stats = await expectUnitNotAborted(() => groundTimelineAppends(engine, null, appends, REFLECTIONS, 'default', '2026-10-15', undefined, new Set(), undefined, grounding as never));
+ expect(stats?.quarantined).toBe(2);
+ expectItemFailure(grounding.failed[0], { key: PREFIX + '/a-theme', code: 'invalid_data' });
+ expect((await engine.getPage(PREFIX + '/b-theme'))!.timeline).not.toContain('always test on staging');
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { expectProgress: [PREFIX + '/b-theme'], progressFields: ['content_hash'] });
+ });
+ }, 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test('[' + backend + '] a run-scoped error while grounding timeline appends still stops grounding (' + name + ')', async () => {
+ await withPatternsBrain(databaseUrl, async engine => {
+ const appends = await appendedPages(engine);
+ const injected = error();
+ const read = engine.readPageSnapshot;
+ engine.readPageSnapshot = (async () => { throw injected; }) as BrainEngine['readPageSnapshot'];
+ const grounding = groundingRun();
+ try {
+ await expect(groundTimelineAppends(engine, null, appends, REFLECTIONS, 'default', '2026-10-15', undefined, new Set(), undefined, grounding as never)).rejects.toBe(injected);
+ } finally { engine.readPageSnapshot = read; }
+ expect(grounding.failed).toEqual([]);
+ });
+ }, 120_000);
+ }
+ }
+});
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index d59a6d4e60..2f14aebdf6 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -27,4 +27,10 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {
'maintain.cycle_sources': { file: 'test/pathological/a41-maintain-sources.test.ts',
item: 'a source whose cycle throws is blocked with its code and the next source still cycles',
run: "a run-scoped error in one source's cycle still stops maintain" },
+ 'patterns.ground_pages': { file: 'test/pathological/a23-patterns-grounding.test.ts',
+ item: 'a refused leftover pattern page is reported, the new page grounds and the watermark is stamped',
+ run: 'a run-scoped error while grounding a page still fails the phase' },
+ 'patterns.ground_timeline_appends': { file: 'test/pathological/a23-patterns-grounding.test.ts',
+ item: 'a refused timeline-append page is recorded and the other page still grounds',
+ run: 'a run-scoped error while grounding timeline appends still stops grounding' },
};
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 0346f75723..4df583a08b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -220,6 +220,7 @@ test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
test/pathological/a21-facts-expire-deleted.test.ts
test/pathological/a22-consolidate-buckets.test.ts
+test/pathological/a23-patterns-grounding.test.ts
test/pathological/a41-maintain-sources.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts