Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): scope the CRAG think escalation to the query's sources (PR #6411)
time-attackef559bdbb008
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 223dc235ce..c0fc2d4ea0 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -312,6 +312,7 @@ test/search-multimodal-no-embed.serial.test.ts global-state global-state: configtest/search-telemetry-cache-wiring.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the processtest/search/autocut-integration.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gatewaytest/search/crag-escalation-limit.serial.test.ts R2 R2: mock.module(dynamic specifier) replaces modules for every file in the process+test/search/crag-think-source-scope.serial.test.ts R2 R2: mock.module(../../src/core/search/hybrid.ts, ../../src/core/think/index.ts) replaces modules for every file in the processtest/search/hybrid-reranker-integration.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_AUDIT_DIR)test/search/operation-expansion-contract.serial.test.ts global-state global-state: spyOn hybrid.hybridSearchCached, console.logtest/search/output-redaction.serial.test.ts R2 R2: mock.module(../../src/core/eval-capture.ts, ../../src/core/search/hybrid.ts, ../../src/core/ai/gateway.ts, ../../src/core/think/index.ts) replaces modules for every file in the processdiff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 28c80bfd7f..fea1766cbd 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -57,7 +57,6 @@ import {stampDeepResearchIds,stampEvidenceSafe,maybeCaptureSearch,- thinkSourceScopeOpts,} from './context.ts';/**@@ -87,6 +86,12 @@ async function trustedSearchScope(ctx: OperationContext, p: Record<string, unknoreturn floor ? { ...scope, minTrust: floor } : scope;}+/** CRAG think escalation reads the same sources the query searched (explicit `source_id` included). */+function thinkScopeFromQueryScope(scope: SourceScope): { sourceId?: string; allowedSources?: string[] } {+ if (scope.sourceIds !== undefined) return { allowedSources: scope.sourceIds };+ return scope.sourceId !== undefined ? { sourceId: scope.sourceId } : {};+}+/*** The returned rows: redacted, snippet-capped, then projected to the caller's* row shape (C1: lean for remote callers unless `fields: "full"`, the host's@@ -1091,7 +1096,7 @@ const query: Operation = {try {const { runThink } = await import('../think/index.ts');const { embedQuery } = await import('../embedding.ts');- const thinkScope = thinkSourceScopeOpts(ctx);+ const thinkScope = thinkScopeFromQueryScope(querySourceScope);const t = await runThink(ctx.engine, {question: queryText,since: typeof p.since === 'string' ? p.since : undefined,diff --git a/test/search/crag-think-source-scope.serial.test.ts b/test/search/crag-think-source-scope.serial.test.tsnew file mode 100644index 0000000000..7554fac948--- /dev/null+++ b/test/search/crag-think-source-scope.serial.test.ts@@ -0,0 +1,72 @@+/**+ * PR #6411 diagnosis: the CRAG think escalation must read the sources the+ * query searched. An explicit per-call `source_id` used to be dropped, so+ * think ran against the context's default source instead.+ *+ * Serial: mock.module replaces hybrid search and think for the process.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { SearchResult } from '../../src/core/types.ts';+import type { OperationContext } from '../../src/core/operations.ts';++let thinkCalls: Array<Record<string, unknown>> = [];+const actualHybrid = await import('../../src/core/search/hybrid.ts');+mock.module('../../src/core/search/hybrid.ts', () => ({+ ...actualHybrid,+ hybridSearchCached: async (_engine: unknown, _query: string, opts: { sourceId?: string; sourceIds?: string[] }) => [{+ slug: 'notes/weak-hit', source_id: opts.sourceId ?? opts.sourceIds?.[0] ?? 'default', page_id: 1, title: 'Weak hit',+ type: 'note', chunk_text: 'barely related', chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0,+ score: 0.01, rerank_score: 0.01, stale: false,+ } as SearchResult],+}));+const actualThink = await import('../../src/core/think/index.ts');+mock.module('../../src/core/think/index.ts', () => ({+ ...actualThink,+ runThink: async (_engine: unknown, opts: Record<string, unknown>) => {+ thinkCalls.push(opts);+ return { answer: 'scoped answer', citations: [], modelUsed: 'synthetic-model' };+ },+}));++const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+const { operationsByName } = await import('../../src/core/operations.ts');+const { resetPgliteState } = await import('../helpers/reset-pglite.ts');+let engine: InstanceType<typeof PGLiteEngine>;++function context(): OperationContext {+ return {+ engine, remote: false, sourceId: 'beta-example', config: { engine: 'pglite' }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} },+ emitResponseMeta: () => {},+ } as OperationContext;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 30000);+beforeEach(async () => {+ await resetPgliteState(engine);+ for (const id of ['alpha-example', 'beta-example']) {+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [id]);+ }+ await engine.setConfig('search.crag_think', 'true');+ thinkCalls = [];+});+afterAll(async () => { await engine.disconnect(); });++describe('CRAG think escalation source scope', () => {+ test('an explicit source_id scopes think to that source, not the context default', async () => {+ await operationsByName.query.handler(context(), { query: 'weakly matched question', expand: false, source_id: 'alpha-example' });+ expect(thinkCalls).toHaveLength(1);+ expect(thinkCalls[0].sourceId).toBe('alpha-example');+ expect(thinkCalls[0].allowedSources).toBeUndefined();+ });++ test('without source_id think keeps the context default', async () => {+ await operationsByName.query.handler(context(), { query: 'weakly matched question', expand: false });+ expect(thinkCalls).toHaveLength(1);+ expect(thinkCalls[0].sourceId).toBe('beta-example');+ });+});