Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): ground interpretations around valid evidence (#5917)

time-attacka4c3b85221fe
diff --git a/docs/guides/system-one.md b/docs/guides/system-one.md
index 0d87e63b49..b35f8b4856 100644
--- a/docs/guides/system-one.md
+++ b/docs/guides/system-one.md
@@ -234,14 +234,24 @@ explicitly on Jev, it needs `decide.egress.private allow`.
### claim support (`grounding`)
-After the mechanical checks in dream synthesis, each new claim that passes
-only because it has no quote, number or attribution is checked against up
-to three source windows: "is this claim supported by these sources?". An
-unsupported claim goes to the existing quarantine lane as
-`unsupported_paraphrase`; weak source coverage records
-`insufficient_context` instead. It only adds a check and can never admit a
-claim the mechanical checks rejected. On Jev it needs
-`decide.egress.private allow`.
+When this optional slot is on, every substantive new prose claim that passes
+Dream's mechanical checks is checked against up to three source excerpts:
+"is this claim supported by these sources?". A valid quote, number or speaker
+name does not prove the interpretation around it. Quote repairs happen before
+this check, so quarantine removes the repaired claim from the published body.
+
+An unsupported claim with adequate source coverage goes to the existing
+quarantine lane as `unsupported_paraphrase`. Coverage uses the distinct content
+words in the selected excerpts together, with the existing 25% floor (or a
+normalized substring hit); evidence omitted from those excerpts does not count.
+Weak coverage records `insufficient_context` and keeps the mechanical result.
+The check can never admit a claim the mechanical checks rejected. On Jev it
+needs `decide.egress.private allow`.
+
+This broader coverage can require more decision calls. The existing page/phase
+deadlines and budget limits still apply; behavior when off, on timeout or on a
+provider error is unchanged. Passing mechanical checks alone is not proof of full
+factual support, and enabling this slot does not guarantee the judge is correct.
### contradiction (`conflict`)
diff --git a/src/core/cycle/grounding-decide.ts b/src/core/cycle/grounding-decide.ts
index c6a77756d0..0339fff078 100644
--- a/src/core/cycle/grounding-decide.ts
+++ b/src/core/cycle/grounding-decide.ts
@@ -2,14 +2,14 @@
* S8 `grounding`: claim support for dream pages, decided by a System One
* provider after the mechanical checks (synthesize-verify.ts).
*
- * verifyDreamPage (mechanical, sync) ──▶ units that pass ONLY because they
- * carry no quote, number or attribution
+ * verifyDreamPage (mechanical, sync) ──▶ substantive new passing units,
+ * including units with valid quotes, numbers or speaker attribution
* │ per unit: up to three source windows (normalized-substring,
* │ keyword and embedding neighbours over the page's transcripts)
* ▼ one `noul` per unit, ONE REQUEST PER UNIT (background lane)
* p ≥ threshold → pass
* p ≥ threshold − margin → margin_hold (kept)
- * low p, no window above keyword floor → insufficient_context (kept)
+ * low p, weak selected-window coverage → insufficient_context (kept)
* low p, adequate coverage → quarantine (`unsupported_paraphrase`)
*
* Runs at both verifyDreamPage call sites and finishes (or times out to the
@@ -34,7 +34,7 @@ import { splitTurnWindows } from './triage-decide.ts';
/** Source windows per claim (fixed by design). */
export const GROUNDING_MAX_WINDOWS = 3;
-/** Coverage floor: a window must hold at least this share of the claim's content words. */
+/** Coverage floor: the selected windows together must hold at least this share of the claim's content words. */
export const GROUNDING_KEYWORD_FLOOR = 0.25;
/** One page's decision, and the whole S8 pass per dream phase run. */
export const GROUNDING_PAGE_MS = 30_000;
@@ -92,7 +92,11 @@ export function selectSourceWindows(claim: string, index: readonly IndexedWindow
const bySim = scored.filter((s) => s.sim > -1 && !used.has(s.i)).sort((a, b) => b.sim - a.sim || a.i - b.i);
if (bySim[0]) take(bySim[0].i, 'embedding');
for (const s of byOverlap) take(s.i, 'keyword');
- const adequate = scored.some((s) => s.substring || s.overlap >= GROUNDING_KEYWORD_FLOOR);
+ // A multi-clause claim can draw on several turns: assess the excerpts the
+ // judge actually receives together, never a window it does not see.
+ const covered = new Set([...used].flatMap((i) => [...index[i]!.words]));
+ const overlap = words.size ? [...words].filter((word) => covered.has(word)).length / words.size : 0;
+ const adequate = picked.some((w) => w.via === 'substring') || overlap >= GROUNDING_KEYWORD_FLOOR;
return { windows: picked, coverage: adequate ? 'adequate' : 'weak' };
}
diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.ts
index 38fc29575e..680e98b811 100644
--- a/src/core/cycle/synthesize-verify.ts
+++ b/src/core/cycle/synthesize-verify.ts
@@ -905,7 +905,7 @@ export interface BodyVerification {
quarantined: QuarantinedClaim[];
provenance: QuoteProvenance[];
failures: Record<ClaimFailure, number>;
- /** New units that pass only because they carry no quote, number or attribution (System One S8 checks these). */
+ /** Substantive new units that pass the mechanical checks, with their final quote repairs (System One S8 checks these). */
groundingUnits: string[];
}
@@ -1064,7 +1064,17 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
} else {
edits.push(...unitEdits);
provenance.push(...unitProvenance);
- if (unitSpans.length === 0 && mentioned.size === 0 && isGroundingCandidate(body, u.start, unquoted)) groundingUnits.push(text);
+ // Mechanical evidence validates a quote or number, not the interpretation
+ // around it, so S8 judges every substantive new passing unit, attributed
+ // and numeric ones and labels around valid quotes included. It sees the
+ // final quote repairs: its quarantine reducer removes units by exact text.
+ if (isGroundingCandidate(body, u.start, masked.slice(u.start, u.end))) {
+ let repaired = text;
+ for (const e of [...unitEdits].sort((a, b) => b.start - a.start)) {
+ repaired = repaired.slice(0, e.start - u.start) + e.text + repaired.slice(e.end - u.start);
+ }
+ groundingUnits.push(repaired);
+ }
}
}
@@ -1077,12 +1087,11 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
/** Units shorter than this many words (labels, headings, fragments) are not claims S8 judges. */
const MIN_GROUNDING_UNIT_WORDS = 5;
-/** A passing unit with no number, not a heading, long enough to be a claim. */
-function isGroundingCandidate(body: string, start: number, unquoted: string): boolean {
+/** A passing prose unit, not a heading, long enough to be a claim. */
+function isGroundingCandidate(body: string, start: number, prose: string): boolean {
const lineStart = body.lastIndexOf('\n', start - 1) + 1;
if (/^[ \t]*#{1,6}[ \t]/.test(body.slice(lineStart, start + 1))) return false;
- if (numericFacts(unquoted).size > 0) return false;
- return (unquoted.match(/\p{L}[\p{L}'-]*/gu) ?? []).length >= MIN_GROUNDING_UNIT_WORDS;
+ return (prose.match(/\p{L}[\p{L}'-]*/gu) ?? []).length >= MIN_GROUNDING_UNIT_WORDS;
}
/** Drop REMOVED markers and the empty list items / blank runs they leave, keeping the body's trailing newline. */
@@ -1119,7 +1128,7 @@ function recordList<T>(fm: Record<string, unknown> | undefined, key: string, pic
*/
export interface VerifiedDreamPage extends VerifiablePage {
changed: boolean;
- /** New units that pass only for lack of a quote, number or attribution, per body (S8 input). */
+ /** Substantive new units that pass the mechanical checks, per body (S8 input). */
groundingUnits: Array<{ body: 'compiled_truth' | 'timeline'; text: string }>;
}
diff --git a/test/cycle-synthesize-grounding-coverage.test.ts b/test/cycle-synthesize-grounding-coverage.test.ts
new file mode 100644
index 0000000000..f0a43d2bdb
--- /dev/null
+++ b/test/cycle-synthesize-grounding-coverage.test.ts
@@ -0,0 +1,81 @@
+/**
+ * #5917 / #5911: S8 grounding judges the interpretation around valid evidence.
+ *
+ * Protects: a unit whose quote, number or speaker mention passes the
+ * mechanical checks still reaches the opt-in S8 judge (with its final quote
+ * repairs), so "attended the conference" around a valid ticket quote can be
+ * quarantined. Fails when: verifyBody exempts quoted, attributed or numeric
+ * units from groundingUnits again, or hands S8 the pre-repair text the
+ * quarantine reducer cannot find. Why new: the existing slot test pinned the
+ * old exemption.
+ */
+import { describe, expect, test } from 'bun:test';
+import { emptyQuoteVerifyStats, groundSource, normForGrounding, quarantineUnits, verifyBody, verifyDreamPage } from '../src/core/cycle/synthesize-verify.ts';
+
+const ticket = 'I signed up for a ticket and got it; I still have to travel to the conference.';
+const source = groundSource('/fixtures/2026-04-03-session.md', `User: ${ticket}\nAssistant: Noted.`);
+
+describe('semantic grounding covers interpretations around mechanically valid evidence', () => {
+ test('speaker mention and supported year do not certify completed attendance', () => {
+ const claim = 'The user reached a personal milestone in 2026: attending the conference.';
+ const verified = verifyBody(claim, [source]);
+ expect(verified.quarantined).toEqual([]);
+ expect(verified.body).toBe(claim);
+ expect(verified.groundingUnits).toEqual([claim]);
+ });
+
+ test('an exact ticket quote does not certify the surrounding attendance claim', () => {
+ const claim = `**Attendance:** The user attended the conference: "${ticket}"`;
+ const verified = verifyBody(claim, [source]);
+ expect(verified.exact).toBe(1);
+ expect(verified.quarantined).toEqual([]);
+ expect(verified.groundingUnits).toEqual([claim]);
+ });
+
+ test.each([
+ 'The user attended the conference after obtaining the ticket.',
+ 'A completed milestone in 2026 was attending the conference.',
+ 'A completed milestone on April 3 was attending the conference.',
+ ])('speaker/date evidence alone does not exclude %s', claim => {
+ const verified = verifyBody(claim, [source]);
+ expect(verified.quarantined).toEqual([]);
+ expect(verified.groundingUnits).toEqual([claim]);
+ });
+
+ test('headings, fragments, non-prose and failed mechanical checks stay excluded', () => {
+ const body = [
+ '## The user attended the conference in 2026',
+ 'Ticket status.',
+ '`The user attended the conference in 2026.`',
+ 'The user paid $999 for a conference ticket.',
+ 'The user said "this entirely fabricated quotation should never become evidence".',
+ ].join('\n\n');
+ const verified = verifyBody(body, [source]);
+ expect(verified.groundingUnits).toEqual([]);
+ expect(verified.quarantined.map(q => q.reason)).toEqual(['number_not_in_source', 'quote_not_in_source']);
+ });
+
+ test('only new claims are selected on an existing page', () => {
+ const prior = 'The user reached a personal milestone in 2026: attending the conference.';
+ const added = 'The user obtained a ticket for the conference.';
+ const verified = verifyBody(`${prior}\n\n${added}`, [source], { priorNorm: normForGrounding(prior) });
+ expect(verified.groundingUnits).toEqual([added]);
+ expect(verified.body).toContain(prior);
+ });
+
+ test('semantic quarantine uses final quote repairs and leaves the supported neighboring unit', () => {
+ const exact = 'A reliable cache mustn’t disappear — even during a deployment.';
+ const transcript = groundSource('/fixtures/cache.md', `User: ${exact}`);
+ const claim = 'The user completed deployment: "A reliable cache mustn\'t disappear - even during a deployment."';
+ const neighbor = 'The user wants a reliable cache during a deployment.';
+ const page = verifyDreamPage({ compiled_truth: `${claim}\n\n${neighbor}`, timeline: '', frontmatter: {} },
+ [transcript], { prior: null, checkedAt: '2026-04-03' }, emptyQuoteVerifyStats());
+ const repaired = `The user completed deployment: "${exact}"`;
+ expect(page.compiled_truth).toContain(repaired);
+ expect(page.groundingUnits.map(u => u.text)).toEqual([repaired, neighbor]);
+ const output = quarantineUnits(page, [{ body: 'compiled_truth', text: repaired, reason: 'unsupported_paraphrase', detail: 'completion not shown' }],
+ [transcript.path], '2026-04-03');
+ expect(output.compiled_truth).toBe(neighbor);
+ expect(output.frontmatter.unverified_claims).toEqual([expect.objectContaining({ text: repaired, reason: 'unsupported_paraphrase' })]);
+ });
+});
diff --git a/test/decide/grounding-slot.serial.test.ts b/test/decide/grounding-slot.serial.test.ts
index c178d33eac..1ba64d5229 100644
--- a/test/decide/grounding-slot.serial.test.ts
+++ b/test/decide/grounding-slot.serial.test.ts
@@ -1,10 +1,10 @@
/**
* System One S8 (claim support) — pure decision logic plus the real call
* site (verifyAndRepairDreamPages on PGLite) with a fixture decide transport.
- * The managed postprocess site is covered by grounding-postprocess.serial.test.ts.
+ * Managed publication is covered by managed-synthesis-postprocess.test.ts.
*
* Protects: verifyBody's new `groundingUnits` output lists only passing units
- * with no quote, number or attribution (existing fields unchanged); up to
+ * including valid quotes, numbers and attribution (existing fields unchanged); up to
* three source windows (substring, keyword, embedding); weak coverage records
* insufficient_context and keeps the unit; a low answer with adequate
* coverage quarantines as `unsupported_paraphrase` before the page is written;
@@ -41,14 +41,20 @@ const FABRICATED = 'Allegedly: "we will rewrite everything in a single weekend s
describe('S8 grounding units from verifyBody', () => {
const src = [groundSource('/t/s.md', TRANSCRIPT)];
- test('only passing units without quote, number or attribution; headings and fragments excluded', () => {
+ test('all substantive passing units; headings, fragments and mechanical failures excluded', () => {
const body = [
'## Storage strategy notes', '', SUPPORTED, 'Short fragment here.',
'The user said "reliable memories should survive every tool".', 'The team budgets 250 servers for storage next year.',
'Assistant recommended boring storage for the whole tier.', FABRICATED, WEAK,
].join('\n');
const r = verifyBody(body, src);
- expect(r.groundingUnits).toEqual([SUPPORTED, WEAK]);
+ expect(r.groundingUnits).toEqual([
+ SUPPORTED,
+ 'The user said "reliable memories should survive every tool".',
+ 'The team budgets 250 servers for storage next year.',
+ 'Assistant recommended boring storage for the whole tier.',
+ WEAK,
+ ]);
expect(r.quarantined.map((q) => q.reason)).toEqual(['quote_not_in_source']);
});
@@ -88,6 +94,31 @@ describe('S8 source windows, reducer and what-if', () => {
.toEqual({ pass: 1, quarantine: 1, insufficient_context: 1, margin_hold: 0 });
});
+ test('coverage can span the selected excerpts without counting evidence the judge never receives', () => {
+ const claim = 'Conference attendance and workshop registration became important memorable personal milestones.';
+ const index = indexSourceWindows([
+ { path: '/fixtures/conference.md', content: 'User: I obtained a conference ticket.\nAssistant: Noted.' },
+ { path: '/fixtures/workshop.md', content: 'User: I completed workshop registration.\nAssistant: Noted.' },
+ ]);
+ const selected = selectSourceWindows(claim, index);
+ expect(selected.windows.every(w => w.overlap < 0.25)).toBe(true);
+ expect(selected.coverage).toBe('adequate');
+ expect(selectSourceWindows('Coastal volleyball holidays always create unexpected personal milestones.', index).coverage).toBe('weak');
+ });
+
+ test('coverage counts distinct words in selected windows, not repeated or omitted words', () => {
+ const claim = 'Alpha beta gamma delta epsilon zeta theta kappa lambda sigma omega polar solar lunar coastal velvet.';
+ const index = indexSourceWindows(['alpha', 'beta', 'gamma', 'delta'].map((word, i) =>
+ ({ path: `/fixtures/word-${i}.md`, content: `User: ${word}` })));
+ const selected = selectSourceWindows(claim, index);
+ expect(selected.windows).toHaveLength(3);
+ expect(selected.coverage).toBe('weak'); // all four windows would reach the floor
+ expect(selectSourceWindows(claim, indexSourceWindows([
+ { path: '/fixtures/repeated.md', content: 'User: alpha alpha alpha alpha.\nAssistant: alpha alpha alpha alpha.' },
+ ])).coverage).toBe('weak');
+ expect(selectSourceWindows(claim, []).coverage).toBe('weak');
+ });
+
test('quarantineUnits removes only present units and records unsupported_paraphrase', () => {
const page = verifyDreamPage({ compiled_truth: `${SUPPORTED}\n\n${UNSUPPORTED}`, timeline: '', frontmatter: {} }, [groundSource('/t/s.md', TRANSCRIPT)], { prior: null, checkedAt: '2026-09-30' }, emptyQuoteVerifyStats());
expect(page.groundingUnits.map((u) => u.text)).toEqual([SUPPORTED, UNSUPPORTED]);
@@ -182,6 +213,33 @@ describe('S8 off', () => {
});
describe('S8 on at verifyAndRepairDreamPages', () => {
+ test('quarantines unsupported attendance despite a valid quote/year; supported ticket remains searchable', async () => {
+ const ticket = 'I signed up for a ticket and got it; I still have to travel to the conference.';
+ const content = `User: ${ticket}\nAssistant: We are discussing the conference in 2026.\nUser: I completed the workshop in 2026.`;
+ const sourcePath = '/fixtures/2026-04-03-session.md';
+ const unsupported = [
+ 'The user reached a personal milestone in 2026: attending the conference.',
+ `**Attendance:** The user attended the conference: "${ticket}"`,
+ ];
+ const supported = ['The user obtained a ticket for the conference.', 'The user completed the workshop in 2026.'];
+ for (const [k, v] of Object.entries(S8_ON)) await engine.setConfig(k, v);
+ transport(claim => unsupported.includes(claim) ? 0.05 : 0.93);
+ const since = await readVerifyEpoch(engine);
+ const slug = `wiki/personal/reflections/attendance-${++n}-abc123`;
+ await importFromContent(engine, slug, ['---', 'type: note', '---', ...supported, ...unsupported].join('\n\n'),
+ { noEmbed: true, remote: false, sourceId: 'default' });
+ const grounding = await resolveGroundingDecide(engine);
+ await verifyAndRepairDreamPages(engine, [{ slug, source_id: 'default', raw_source: sourcePath }],
+ new Map([[sourcePath, { content }]]), { since, checkedAt: '2026-04-03', grounding });
+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;
+ expect(questions.sort()).toEqual([...supported, ...unsupported].sort());
+ expect(page.compiled_truth).toBe(supported.join('\n\n'));
+ expect(reasonsOf(page.frontmatter)).toEqual(['unsupported_paraphrase', 'unsupported_paraphrase']);
+ expect((await engine.searchKeyword('attending conference', { limit: 5 })).some(hit => hit.slug === slug)).toBe(false);
+ expect((await engine.searchKeyword('obtained ticket', { limit: 5 })).some(hit => hit.slug === slug)).toBe(true);
+ expect(grounding!.stats).toMatchObject({ units: 4, pass: 2, quarantine: 2 });
+ });
+
test('quarantines an unsupported paraphrase before write-back; weak coverage is insufficient_context; the fabricated unit is never asked', async () => {
await engine.executeRaw('SELECT 1');
for (const [k, v] of Object.entries(S8_ON)) await engine.setConfig(k, v);
diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.ts
index 585ac4f4a9..6493b2ff65 100644
--- a/test/managed-synthesis-postprocess.test.ts
+++ b/test/managed-synthesis-postprocess.test.ts
@@ -10,7 +10,8 @@ import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/
import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, __setDecideTransportForTests } from '../src/core/ai/gateway.ts';
+import { flushDecideWrites } from '../src/core/ai/decide/store.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
import * as staleEmbedding from '../src/core/embed-stale.ts';
@@ -48,7 +49,7 @@ async function fixture(run: (f: {
engine: BrainEngine; sourceId: string; root: string;
opts: { brainDir: string; sourceId: string; dryRun: boolean; inputFile: string; date: string };
calls: () => number; edit: (slug: string) => Promise<void>;
-}) => Promise<void>, outputCount = 1) {
+}) => Promise<void>, outputCount = 1, outputBody?: string) {
for (const engine of engines) {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-synth-postprocess-'));
const root = join(dir, 'brain');
@@ -84,7 +85,7 @@ async function fixture(run: (f: {
? JSON.stringify({ score: 0.9, content_type: 'reflection', segments: [{ quote, note: 'evidence' }], entities: [], reasons: ['durable insight'] })
: JSON.stringify({ pages: Array.from({ length: outputCount }, (_, i) => ({
slug: `wiki/personal/reflections/session${i ? `-${i}` : ''}-${hash}`, title: `Session ${i}`, type: 'note',
- body: `A memory strategy with [[people/example]]. Evidence item ${i}. Allegedly: "an entirely invented quotation that should lose its marks".`,
+ body: outputBody ?? `A memory strategy with [[people/example]]. Evidence item ${i}. Allegedly: "an entirely invented quotation that should lose its marks".`,
})), skipped: false });
return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
usage: { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 },
@@ -99,6 +100,8 @@ async function fixture(run: (f: {
} });
});
} finally {
+ await flushDecideWrites();
+ __setDecideTransportForTests(null);
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
__setChatTransportForTests(null);
__setEmbedTransportForTests(null);
@@ -114,6 +117,62 @@ async function outputSlug(engine: BrainEngine, sourceId: string): Promise<string
return row.slug;
}
+test('managed native synthesis quarantines interpretations around valid evidence before mirror/chunk publication', async () => {
+ const supported = 'Reliable memories should survive every tool change.';
+ const unsupported = [
+ 'The user completed the durability roadmap in 2026.',
+ 'The user completed the roadmap: "we charge for durability because reliable memories should survive every tool".',
+ ];
+ await fixture(async ({ engine, sourceId, root, opts }) => {
+ const groundingConfig = {
+ 'decide.provider': 'typesafe:jev-1.13.0', 'decide.slots.grounding.mode': 'on',
+ 'decide.slots.grounding.threshold': '0.5', 'decide.slots.grounding.force_on': 'true',
+ 'decide.egress.private': 'allow', 'decide.egress.typesafe.conversation': 'allow',
+ 'decide.budget.daily_usd': '50',
+ };
+ const previousConfig = new Map(await Promise.all(Object.keys(groundingConfig).map(async key => [key, await engine.getConfig(key)] as const)));
+ try {
+ for (const [key, value] of Object.entries(groundingConfig)) await engine.setConfig(key, value);
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { TYPESAFE_API_KEY: 'sk-test-typesafe' } });
+ const claims: string[] = [];
+ __setDecideTransportForTests(async (_url, init) => {
+ const payload = JSON.parse(init.body as string);
+ const answers: Record<string, unknown> = {};
+ for (const [id, question] of Object.entries<any>(payload.questions)) {
+ claims.push(question.instructions.claim);
+ answers[id] = { type: 'noul', noul: unsupported.includes(question.instructions.claim) ? 0.05 : 0.93 };
+ }
+ return new Response(JSON.stringify({ model: 'jev-1.13.0', answers, usage: { input_tokens: 200, output_tokens: 3 } }));
+ });
+ const report = await runPhaseSynthesize(engine, opts);
+ expect(report.status).toBe('ok');
+ expect(claims).toEqual(expect.arrayContaining(unsupported));
+ const slug = await outputSlug(engine, sourceId);
+ const page = (await engine.readPageSnapshot(slug, { sourceId }))!.page;
+ const rendered = readFileSync(join(root, `${slug}.md`), 'utf8');
+ expect(page.compiled_truth).toContain(supported);
+ expect(page.compiled_truth).not.toContain('completed');
+ expect(page.frontmatter.unverified_claims).toEqual(expect.arrayContaining(unsupported.map(text =>
+ expect.objectContaining({ text, reason: 'unsupported_paraphrase' }))));
+ expect(rendered).toContain('unsupported_paraphrase');
+ expect(rendered.slice(rendered.indexOf('\n---\n') + 5)).not.toContain('completed');
+ const chunks = await engine.executeRaw<{ content: string }>('SELECT c.chunk_text AS content FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug=$1 AND p.source_id=$2', [slug, sourceId]);
+ const chunkText = chunks.map(c => c.content).join('\n');
+ expect(chunkText).toContain(supported);
+ expect(chunkText).not.toContain('completed');
+ expect((await engine.searchKeyword('Reliable memories', { limit: 5, sourceId })).some(hit => hit.slug === slug)).toBe(true);
+ expect((await engine.searchKeyword('completed durability roadmap', { limit: 5, sourceId })).some(hit => hit.slug === slug)).toBe(false);
+ } finally {
+ await flushDecideWrites();
+ for (const [key, value] of previousConfig) {
+ if (value === null) await engine.unsetConfig(key);
+ else await engine.setConfig(key, value);
+ }
+ }
+ }, 1, [supported, ...unsupported, 'Related context: [[people/example]].'].join('\n\n'));
+}, 120_000);
+
async function interruptAfterChild(engine: BrainEngine, sourceId: string, opts: Parameters<typeof runPhaseSynthesize>[1]) {
const controller = new AbortController();
const result = await runPhaseSynthesize(engine, { ...opts, signal: controller.signal, yieldDuringPhase: async () => {