Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(g6): the phase reports a synthesis child's S8 grounding counts; extract_entities tests pin the batched publication (GBRA-60)
garrytan915c2cb754f8
diff --git a/src/core/cycle/synthesize-child-verify.ts b/src/core/cycle/synthesize-child-verify.tsindex f107222b4e..2978f4cfe3 100644--- a/src/core/cycle/synthesize-child-verify.ts+++ b/src/core/cycle/synthesize-child-verify.ts@@ -16,10 +16,14 @@ import { isSegmentedPage } from '../page-body/page-shape.ts';import { CONVERSATION_PAGE_URI_PREFIX } from './transcript-discovery.ts';import { emptyQuoteVerifyStats, groundSource, verifyDreamPage, type QuoteVerifyStats, type VerifiablePage } from './synthesize-verify.ts';import { attributionChecksEnabled } from './attribution-checks.ts';-import { resolveGroundingDecide } from './grounding-decide.ts';+import { resolveGroundingDecide, type GroundingStats } from './grounding-decide.ts';++const GROUNDING_COUNTS = ['pages', 'units', 'pass', 'quarantine', 'insufficient_context', 'margin_hold', 'kept_on_error', 'input_tokens', 'cost_usd'] as const;+/** The S8 grounding counts one child page added: the phase reports them in its own grounding stats. */+export type GroundingCounts = Partial<Record<typeof GROUNDING_COUNTS[number], number>>;/** What a child's ledger row records about the page it wrote: the transcript it verified against, and that page's stats. */-export interface ChildVerification { transcript_hash: string; quote_verify: boolean; stats: QuoteVerifyStats }+export interface ChildVerification { transcript_hash: string; quote_verify: boolean; stats: QuoteVerifyStats; grounding?: GroundingCounts }const sha256 = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex');@@ -58,6 +62,7 @@ export async function verifyChildPages(engine: BrainEngine, spec: DreamOutputSpeconst out: Array<{ content: string; verification: ChildVerification }> = [];for (const { slug, content } of pages) {const stats = emptyQuoteVerifyStats();+ const before = grounding ? { ...grounding.stats } : undefined;const parsed = parseMarkdown(content, slug);const existing = (await engine.readPageSnapshot(slug, { sourceId }))?.page ?? null;if (existing && isSegmentedPage(existing)) return null;@@ -79,11 +84,20 @@ export async function verifyChildPages(engine: BrainEngine, spec: DreamOutputSpe}}out.push({ content: serializeMarkdown(page.frontmatter, page.compiled_truth, page.timeline, { type: parsed.type, title: parsed.title, tags: parsed.tags }),- verification: { transcript_hash: spec.transcript_hash, quote_verify: spec.quote_verify, stats } });+ verification: { transcript_hash: spec.transcript_hash, quote_verify: spec.quote_verify, stats,+ ...(grounding && before ? { grounding: Object.fromEntries(GROUNDING_COUNTS.map(key => [key, grounding.stats[key] - before[key]])) } : {}) } });}return out;}+/** Adds one child page's S8 grounding counts into the phase's grounding stats. */+export function addGroundingCounts(into: GroundingStats, from: GroundingCounts): void {+ for (const key of GROUNDING_COUNTS) {+ const value = from[key];+ if (typeof value === 'number' && Number.isFinite(value)) into[key] += value;+ }+}+/** Adds one child page's verify stats into the phase's. */export function addVerifyStats(into: QuoteVerifyStats, from: Partial<QuoteVerifyStats>): void {for (const key of Object.keys(into) as Array<keyof QuoteVerifyStats>) {diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex f9e4b13614..462f39baae 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -18,11 +18,11 @@ import type { PhaseResult } from '../cycle.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';import { transcriptDerivation } from './dream-taint.ts';import { declareDerivation, readDerivationDeclaration } from '../trust/taint.ts';-import { addVerifyStats, type ChildVerification } from './synthesize-child-verify.ts';+import { addGroundingCounts, addVerifyStats, type ChildVerification } from './synthesize-child-verify.ts';import { storedPageTier } from '../trust/page-write.ts';-import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';+import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource } from './synthesize-verify.ts';import { attributionChecksEnabled } from './attribution-checks.ts';-import { resolveGroundingDecide } from './grounding-decide.ts';+import { resolveGroundingDecide, type GroundingDecide } from './grounding-decide.ts';import { resolveCycleDate } from './cycle-date.ts';import { DEFERRED_READ_LABEL, isPostprocessReadTimeout, pendingOutputsFor, readPostprocessDeferrals, recordPostprocessPass,type DeferredRead, type PendingOutput, type PostprocessDeferral } from './synthesize-postprocess-deferral.ts';@@ -170,7 +170,7 @@ export async function postprocessManagedSynthesis(childIds: number[],jobRawSource: Map<number, string>,transcripts: DiscoveredTranscript[],- opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal; grounding?: GroundingPass;+ opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal; grounding?: GroundingDecide;/** The child outputs slug discovery already loaded (loadCommittedOutputsOrDefer). */committedOutputs?: CommittedOutputs;/** #5575 I2: files under it are third-party speech; their outputs publish external_untrusted. */@@ -323,7 +323,10 @@ export async function postprocessManagedSynthesis(dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path, ...(transcript.seat ? { seat: transcript.seat } : {}) } } : snapshot.page;if (opts.quoteVerify) {const prior = child?.quote_verify ? 'child' : since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;- if (prior === 'child') addVerifyStats(stats, child!.stats);+ if (prior === 'child') {+ addVerifyStats(stats, child!.stats);+ if (opts.grounding && child!.grounding) addGroundingCounts(opts.grounding.stats, child!.grounding);+ }else if (prior === 'unchanged') stats.skipped_unchanged++;else {if (prior) stats.preexisting_diffed++;diff --git a/test/extract-entities-managed.test.ts b/test/extract-entities-managed.test.tsindex d88724a3e8..5955a84629 100644--- a/test/extract-entities-managed.test.ts+++ b/test/extract-entities-managed.test.ts@@ -5,7 +5,9 @@* source page's derived tier; a refusal reaches the caller as its envelope. G5 lane B: the timeline row is an* `add_timeline_entry` page mutation, so the existing entity page is seeded through the page door (a managed page has* its canonical file) and the stub's journal holds both requests; the backlink is the edge the bullet's markdown link- * derives at publication, not a direct database row. Synthetic content only.+ * derives at publication, not a direct database row. G6: a new entity's stub carries its timeline bullet in its own+ * put_page (one request, one commit), and one call's entity writes are submitted as one batch, which Postgres publishes+ * as one group. Synthetic content only.*/import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../src/core/engine.ts';@@ -96,7 +98,8 @@ describe(`extract_entities on a managed brain (#6262, ${databaseUrl ? 'postgres'});const journal = await engine.executeRaw<{ operation: string; state: string }>("SELECT operation, state FROM persistence_requests WHERE slug='people/cedar-example' ORDER BY sequence");- expect(journal).toEqual([{ operation: 'put_page', state: 'committed' }, { operation: 'add_timeline_entry', state: 'committed' }]);+ // G6: the stub's timeline bullet rides in its put_page, so the new entity is one request and one commit.+ expect(journal).toEqual([{ operation: 'put_page', state: 'committed' }]);}, { databaseUrl, setup: ({ engine }) => seed(engine) });}, 180_000);@@ -138,10 +141,28 @@ describe(`extract_entities on a managed brain (#6262, ${databaseUrl ? 'postgres'.then(() => null, e => e as { code?: string; why?: string }).finally(() => { installFaultHook(undefined); release(); });expect(error?.code).toBe('write_pending');- expect(error?.why).toContain('1 of 2 entities were written before Cedar Example: people/alice-example');- // The accepted stub publishes on its own; its timeline row and backlink wait for the rerun.- expect(await timeline(engine, 'people/cedar-example')).toEqual([]);- expect(await backlinks(engine, 'people/cedar-example')).toEqual([]);+ if (!databaseUrl) {+ expect(error?.why).toContain('1 of 2 entities were written before Cedar Example: people/alice-example');+ // The accepted stub publishes on its own; its timeline row and backlink wait for the rerun.+ expect(await timeline(engine, 'people/cedar-example')).toEqual([]);+ expect(await backlinks(engine, 'people/cedar-example')).toEqual([]);+ return;+ }+ // G6 on Postgres: Alice's bullet and Cedar's stub are one publication group, so the held stub holds Alice's bullet+ // too: nothing was written yet, and the reply claims no entity as written.+ expect(error?.why ?? '').not.toContain('were written before');+ expect(await timeline(engine, 'people/alice-example')).toEqual([]);+ expect(await page(engine, 'people/cedar-example')).toBeUndefined();+ // Released, both accepted writes publish together, each committed, in one transaction.+ let rows: Array<{ slug: string; state: string; published: string | null }> = [];+ for (const start = Date.now(); Date.now() - start < 30_000; await new Promise(r => setTimeout(r, 200))) {+ rows = await engine.executeRaw("SELECT slug,state,published_at::text AS published FROM persistence_requests WHERE slug IN ('people/alice-example','people/cedar-example') AND operation IN ('put_page','add_timeline_entry') AND intent ? 'page_batch' ORDER BY slug");+ if (rows.length === 2 && rows.every(row => row.state === 'committed')) break;+ }+ expect(rows.map(row => [row.slug, row.state])).toEqual([['people/alice-example', 'committed'], ['people/cedar-example', 'committed']]);+ expect(rows[0]!.published).toBe(rows[1]!.published);+ expect(await timeline(engine, 'people/alice-example')).toHaveLength(1);+ expect(await timeline(engine, 'people/cedar-example')).toHaveLength(1);}, { databaseUrl, setup: ({ engine }) => seed(engine) });}, 180_000);});