Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(think): save syntheses to the think source and scope citation binding (#5426)
garrytan6791c1ef9854
diff --git a/src/commands/think.ts b/src/commands/think.tsindex fce401875e..006735fa81 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -203,7 +203,7 @@ prints what would have been the input (exit 0).// Persist if --save (the runThink path doesn't auto-persist; CLI does it explicitly)if (save) {- const persisted = await persistSynthesis(engine, result);+ const persisted = await persistSynthesis(engine, result, { sourceId, allowedSources });savedSlug = persisted.slug || undefined; // '' = persist-skip signal (#10)evidenceInserted = persisted.evidenceInserted;for (const w of persisted.warnings) result.warnings.push(w);diff --git a/src/core/cycle/auto-think.ts b/src/core/cycle/auto-think.tsindex 928c33dba0..567f67ab0b 100644--- a/src/core/cycle/auto-think.ts+++ b/src/core/cycle/auto-think.ts@@ -42,6 +42,8 @@ export interface AutoThinkPhaseOpts {client?: ThinkLLMClient;/** Override the audit-ledger path (tests). */auditPath?: string;+ /** #5426: source the cycle runs for; syntheses are saved there. */+ sourceId?: string;}export interface AutoThinkConfig {@@ -173,6 +175,7 @@ export async function runPhaseAutoThink(// Fail-closed trust: the local dream cycle must say so explicitly, or// trajectory injection degrades to visibility='world' rows.remote: false,+ ...(opts.sourceId ? { sourceId: opts.sourceId } : {}),});// #1698: an empty synthesis (no LLM available / malformed output / empty-JSON answer)// must NOT count as complete or advance the cooldown — that is the same silent-success@@ -185,7 +188,7 @@ export async function runPhaseAutoThink(const warnings = [...result.warnings];let slug: string | undefined;if (config.autoCommit) {- const persisted = await persistSynthesis(engine, result);+ const persisted = await persistSynthesis(engine, result, opts.sourceId ? { sourceId: opts.sourceId } : {});slug = persisted.slug || undefined; // '' = persist-skip signal (#1698)warnings.push(...persisted.warnings);}diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex d263cdde33..39dcee0457 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -238,7 +238,10 @@ const think: Operation = {let savedSlug: string | undefined;let evidenceInserted = 0;if (safeSave) {- const persisted = await persistSynthesis(ctx.engine, result);+ const persisted = await persistSynthesis(ctx.engine, result, {+ sourceId: ctx.sourceId,+ ...(thinkScope.allowedSources ? { allowedSources: thinkScope.allowedSources } : {}),+ });savedSlug = persisted.slug;evidenceInserted = persisted.evidenceInserted;for (const w of persisted.warnings) result.warnings.push(w);diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex f79e9979ae..44541d92c9 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -447,17 +447,28 @@ async function persistCitations(engine: BrainEngine,synthesisPageId: number,citations: ParsedCitation[],+ scope: { sourceId?: string; allowedSources?: string[] } = {},): Promise<{ inserted: number; warnings: string[] }> {const warnings: string[] = [];+ // #5426: the same slug can exist in several sources. Bind each citation to+ // a page in the sources the synthesis drew from (preferring its own source),+ // never to a same-slug page elsewhere in the brain. Unscoped only for an+ // unscoped think.+ const sources = scope.allowedSources?.length ? scope.allowedSources : scope.sourceId ? [scope.sourceId] : null;// Resolve unique slugs to page_idsconst slugToPageId = new Map<string, number>();for (const c of citations) {if (c.row_num === null) continue; // page-level, skipif (slugToPageId.has(c.page_slug)) continue;- const rows = await engine.executeRaw<{ id: number }>(- `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,- [c.page_slug],- );+ const rows = sources+ ? await engine.executeRaw<{ id: number }>(+ `SELECT id FROM pages WHERE slug = $1 AND source_id = ANY($2::text[]) ORDER BY (source_id = $3) DESC, id LIMIT 1`,+ [c.page_slug, sources, scope.sourceId ?? ''],+ )+ : await engine.executeRaw<{ id: number }>(+ `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,+ [c.page_slug],+ );if (rows[0]) slugToPageId.set(c.page_slug, rows[0].id);}const evidenceInputs: SynthesisEvidenceInput[] = [];@@ -1000,6 +1011,7 @@ export function stripGapsSection(answer: string): string {export async function persistSynthesis(engine: BrainEngine,result: ThinkResult,+ scope: { sourceId?: string; allowedSources?: string[] } = {},): Promise<{ slug: string; evidenceInserted: number; warnings: string[] }> {// #1698: never persist an empty synthesis. Returned signal (NOT a throw, F3) so// the MCP `think` op can return the gather result + warning instead of a bare error@@ -1039,9 +1051,9 @@ export async function persistSynthesis(pages_gathered: result.pagesGathered,takes_gathered: result.takesGathered,},- });+ }, scope.sourceId ? { sourceId: scope.sourceId } : undefined);- const persisted = await persistCitations(engine, page.id, result.citations);+ const persisted = await persistCitations(engine, page.id, result.citations, scope);return { slug, evidenceInserted: persisted.inserted, warnings: persisted.warnings };}diff --git a/test/think-save-source.test.ts b/test/think-save-source.test.tsnew file mode 100644index 0000000000..408a685a40--- /dev/null+++ b/test/think-save-source.test.ts@@ -0,0 +1,91 @@+/**+ * #5426: `think --save` wrote every synthesis to source `default` and bound+ * its citations by bare slug, so on a multi-source brain the synthesis landed+ * in the wrong source and its evidence could point at a same-slug page in+ * another source. persistSynthesis now takes the think's scope from all three+ * callers (CLI think, the think op, auto-think).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { readFileSync } from 'fs';+import { resolve } from 'path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { persistSynthesis, type ThinkResult } from '../src/core/think/index.ts';++let engine: PGLiteEngine;+let defaultAliceId: number;+let alphaAliceId: number;++function synthesis(question: string): ThinkResult {+ return {+ question,+ answer: 'Alice leads Acme [people/alice-example#1].',+ gaps: [],+ citations: [{ page_slug: 'people/alice-example', row_num: 1, citation_index: 1 }],+ modelUsed: 'stub',+ pagesGathered: 1,+ takesGathered: 1,+ warnings: [],+ synthesisOk: true,+ } as unknown as ThinkResult;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alpha', 'Alpha'), ('beta', 'Beta') ON CONFLICT (id) DO NOTHING`);+ defaultAliceId = (await engine.putPage('people/alice-example', { title: 'Alice', type: 'person', compiled_truth: 'Default Alice.' })).id;+ alphaAliceId = (await engine.putPage('people/alice-example', { title: 'Alice', type: 'person', compiled_truth: 'Alpha Alice.' }, { sourceId: 'alpha' })).id;+ expect(alphaAliceId).not.toBe(defaultAliceId);+ await engine.addTakesBatch([+ { page_id: defaultAliceId, row_num: 1, claim: 'Default claim', kind: 'fact', holder: 'world', weight: 1 },+ { page_id: alphaAliceId, row_num: 1, claim: 'Alpha claim', kind: 'fact', holder: 'world', weight: 1 },+ ]);+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+}, 60_000);++async function evidenceFor(slug: string, sourceId: string): Promise<number[]> {+ const rows = await engine.executeRaw<{ take_page_id: number }>(+ `SELECT e.take_page_id FROM synthesis_evidence e JOIN pages p ON p.id = e.synthesis_page_id WHERE p.slug = $1 AND p.source_id = $2`,+ [slug, sourceId],+ );+ return rows.map(r => Number(r.take_page_id));+}++describe('#5426 think --save persists into the think source', () => {+ test('the synthesis lands in the requested source and cites that source\'s page', async () => {+ const saved = await persistSynthesis(engine, synthesis('alpha question'), { sourceId: 'alpha' });+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = $1`, [saved.slug]);+ expect(rows.map(r => r.source_id)).toEqual(['alpha']);+ expect(await evidenceFor(saved.slug, 'alpha')).toEqual([alphaAliceId]);+ });++ test('a citation outside the gathered sources is not bound to a same-slug page elsewhere', async () => {+ const saved = await persistSynthesis(engine, synthesis('beta question'), { sourceId: 'beta' });+ expect(saved.warnings).toContain('CITATION_PAGE_NOT_IN_BRAIN: people/alice-example#1');+ expect(await evidenceFor(saved.slug, 'beta')).toEqual([]);+ });++ test('a federated think binds to a gathered source, preferring its own', async () => {+ const saved = await persistSynthesis(engine, synthesis('federated question'), { sourceId: 'beta', allowedSources: ['beta', 'alpha'] });+ expect(await evidenceFor(saved.slug, 'beta')).toEqual([alphaAliceId]);+ });++ test('an unscoped think keeps the default source', async () => {+ const saved = await persistSynthesis(engine, synthesis('unscoped question'));+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = $1`, [saved.slug]);+ expect(rows.map(r => r.source_id)).toEqual(['default']);+ });++ test('all three callers pass their scope', () => {+ const read = (p: string) => readFileSync(resolve(import.meta.dir, '..', p), 'utf-8');+ expect(read('src/commands/think.ts')).toContain('persistSynthesis(engine, result, { sourceId, allowedSources })');+ expect(read('src/core/ops/takes.ts')).toMatch(/persistSynthesis\(ctx\.engine, result, \{\s*sourceId: ctx\.sourceId/);+ expect(read('src/core/cycle/auto-think.ts')).toContain('persistSynthesis(engine, result, opts.sourceId ? { sourceId: opts.sourceId } : {})');+ });+});