Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(think): evidence gather and internal breadth callers skip adaptive return (#5890)

garrytan2fa0e1f82015
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 3515381e6c..06cef30bb4 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -26,3 +26,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.
- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.
+
+- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index ca0131259e..e099b0f526 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -28,7 +28,7 @@ src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposi
src/commands/upgrade.ts runPostUpgrade 319 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ai/gateway.ts chat 311 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/brainstorm/orchestrator.ts _runBrainstormInner 412 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTS
src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane merge
src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/src/commands/enrich.ts b/src/commands/enrich.ts
index d2e32c9011..8c10574921 100644
--- a/src/commands/enrich.ts
+++ b/src/commands/enrich.ts
@@ -40,6 +40,7 @@ import type { OperationContext } from '../core/operations.ts';
import { configureGatewayIfUninitialized, isAvailable, chat, getChatModel, withBudgetTracker } from '../core/ai/gateway.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason } from '../core/budget/budget-tracker.ts';
import { hybridSearch } from '../core/search/hybrid.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../core/search/internal-breadth.ts';
import { serializeMarkdown } from '../core/markdown.ts';
import { listSources } from '../core/sources-ops.ts';
import {
@@ -307,6 +308,7 @@ async function retrieveEvidence(
// 3. Hybrid search on the entity name — pages that mention it.
try {
const hits = await hybridSearch(engine, title || slug, {
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
limit: HYBRID_SEARCH_LIMIT,
sourceId,
});
diff --git a/src/commands/whoknows.ts b/src/commands/whoknows.ts
index f60fe758b1..122fa0ef8a 100644
--- a/src/commands/whoknows.ts
+++ b/src/commands/whoknows.ts
@@ -39,6 +39,7 @@ import type { PageReadPolicy } from '../core/types.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { PageType, SearchResult } from '../core/types.ts';
import { hybridSearch } from '../core/search/hybrid.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../core/search/internal-breadth.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
@@ -192,6 +193,7 @@ export async function findExperts(
// v0.34.1 (#861, D3): thread source-scope so an authenticated MCP
// client only ranks experts within its accessible sources.
const results: SearchResult[] = await hybridSearch(engine, opts.topic, {
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
types,
limit: innerLimit,
salience: 'off',
diff --git a/src/core/brainstorm/orchestrator.ts b/src/core/brainstorm/orchestrator.ts
index 11bf0dfa4f..580f1de6c6 100644
--- a/src/core/brainstorm/orchestrator.ts
+++ b/src/core/brainstorm/orchestrator.ts
@@ -34,6 +34,7 @@
import type { BrainEngine } from '../engine.ts';
import { chat as defaultChat, embedQuery, type ChatResult, type ChatOpts } from '../ai/gateway.ts';
import { hybridSearch, hybridSearchCached } from '../search/hybrid.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
import { fetchFar, type CloseRef, type FarPage } from './domain-bank.ts';
import { StructuredAgentError } from '../errors.ts';
import { classifyBrainstormError } from './error-classify.ts';
@@ -626,6 +627,7 @@ async function _runBrainstormInner(
// hybridSearch for close-set. Limit to profile.k_close. Source-scoped.
let closeResults = await hybridSearch(engine, opts.question, {
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
limit: profile.k_close,
sourceId: opts.sourceId,
sourceIds: opts.sourceIds,
diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts
index 0e44d0289d..a8dad3b615 100644
--- a/src/core/cycle/grade-takes.ts
+++ b/src/core/cycle/grade-takes.ts
@@ -37,6 +37,7 @@
import { createHash } from 'node:crypto';
import { BaseCyclePhase, effectivePhaseDeadlineMs, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
import { hybridSearch } from '../search/hybrid.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
import type { SearchResult } from '../types.ts';
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';
@@ -389,6 +390,7 @@ export async function defaultEvidenceRetriever(
): Promise<string> {
try {
const hits = await hybridSearch(engine, take.claim, {
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
limit: EVIDENCE_SEARCH_LIMIT,
expansion: false,
...(scope.sourceIds && scope.sourceIds.length > 0
diff --git a/src/core/search/internal-breadth.ts b/src/core/search/internal-breadth.ts
new file mode 100644
index 0000000000..7744ea9f22
--- /dev/null
+++ b/src/core/search/internal-breadth.ts
@@ -0,0 +1,14 @@
+/**
+ * Search options for internal callers that need the full ranked set (#5890).
+ *
+ * Autocut (score-cliff sizing) and adaptive return (intent cap: 2 pages for
+ * entity queries, 6 otherwise) trim results for a human reader, before the
+ * limit slice. Evidence gathering, close-set retrieval, expert ranking,
+ * take grading and enrichment ask for a breadth-sized limit and apply their
+ * own precision step, so both trims silently starve them. These callers
+ * spread this object into their `hybridSearch` options.
+ */
+export const INTERNAL_BREADTH_SEARCH_OPTS = Object.freeze({
+ autocut: false,
+ adaptiveReturn: false,
+} as const);
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index 5339adcfb5..e908726d51 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -17,6 +17,7 @@
import type { BrainEngine, TakeHit, Take } from '../engine.ts';
import { hybridSearch } from '../search/hybrid.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import type { Page, SearchResult } from '../types.ts';
import { filterPagesToWindow, type TemporalWindow } from './temporal-window.ts';
@@ -151,16 +152,15 @@ export async function runGather(
let windowDiagnostic: ThinkGatherResult['diagnostics']['window'];
// Stream 1: hybrid page search (existing primitive).
- // autocut: false on both legs (#4561) — autocut is default-ON in
- // balanced/tokenmax and cuts BEFORE the limit slice, so an evidence
- // gather sized for breadth (default 40) could collapse to minKeep=1 and
- // starve synthesis. Same breadth reason as the CRAG escalation re-run in
- // ops/search.ts; precision trimming is the synth prompt's job here.
+ // Both legs opt out of the reader-facing trims (autocut #4561, adaptive
+ // return #5890): each cuts BEFORE the limit slice, so an evidence gather
+ // sized for breadth (default 40) could collapse to 1-6 pages and starve
+ // synthesis. Precision trimming is the synth prompt's job here.
const pagesPromise = (window ? Promise.all([
hybridSearch(engine, opts.question, {
limit: Math.min(gatherLimit * 4, 200),
expansion: false,
- autocut: false,
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
...pageScope,
decide,
}),
@@ -182,7 +182,7 @@ export async function runGather(
}) : hybridSearch(engine, opts.question, {
limit: gatherLimit,
expansion: false,
- autocut: false,
+ ...INTERNAL_BREADTH_SEARCH_OPTS,
...pageScope,
decide,
})).catch((e) => {
diff --git a/test/internal-breadth-callers.serial.test.ts b/test/internal-breadth-callers.serial.test.ts
new file mode 100644
index 0000000000..535a1d4a2b
--- /dev/null
+++ b/test/internal-breadth-callers.serial.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #5890 — every internal breadth caller of hybridSearch opts out of both
+ * reader-facing trims (autocut + adaptive return) through the one shared
+ * INTERNAL_BREADTH_SEARCH_OPTS object: think gather (both legs), brainstorm
+ * close-set, grade-takes evidence, whoknows and enrich.
+ *
+ * Gather, grade-takes and whoknows are driven through their real entry
+ * points with hybridSearch captured; brainstorm and enrich (whose entry
+ * points need an LLM and a candidate pipeline) are pinned at the call site.
+ *
+ * Serial: mock.module (isolation guard R2).
+ */
+
+import { describe, expect, mock, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import * as realHybrid from '../src/core/search/hybrid.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { INTERNAL_BREADTH_SEARCH_OPTS } from '../src/core/search/internal-breadth.ts';
+
+const captured: Array<Record<string, unknown>> = [];
+
+mock.module('../src/core/search/hybrid.ts', () => ({
+ ...realHybrid,
+ hybridSearch: async (_engine: unknown, _query: string, opts: Record<string, unknown>) => {
+ captured.push(opts);
+ return [];
+ },
+}));
+
+const { runGather } = await import('../src/core/think/gather.ts');
+const { defaultEvidenceRetriever } = await import('../src/core/cycle/grade-takes.ts');
+const { findExperts } = await import('../src/commands/whoknows.ts');
+
+const engineStub = {
+ searchTakes: async () => [],
+ listPages: async () => [],
+} as unknown as BrainEngine;
+
+function expectBreadth(opts: Record<string, unknown> | undefined) {
+ expect(opts).toBeDefined();
+ expect(opts!.autocut).toBe(false);
+ expect(opts!.adaptiveReturn).toBe(false);
+}
+
+describe('internal breadth callers pass INTERNAL_BREADTH_SEARCH_OPTS (#5890)', () => {
+ test('the shared object disables both reader-facing trims', () => {
+ expect(INTERNAL_BREADTH_SEARCH_OPTS).toEqual({ autocut: false, adaptiveReturn: false });
+ expect(Object.isFrozen(INTERNAL_BREADTH_SEARCH_OPTS)).toBe(true);
+ });
+
+ test('think gather, plain and temporal-window legs', async () => {
+ captured.length = 0;
+ await runGather(engineStub, { question: 'what changed in the payments migration' });
+ await runGather(engineStub, {
+ question: 'what changed last week',
+ window: { startMs: Date.UTC(2026, 0, 1), endMs: Date.UTC(2026, 0, 8) },
+ });
+ expect(captured).toHaveLength(2);
+ for (const opts of captured) expectBreadth(opts);
+ });
+
+ test('grade-takes evidence retriever', async () => {
+ captured.length = 0;
+ await defaultEvidenceRetriever(engineStub, { claim: 'Acme will ship in Q3', page_slug: 'people/alice-example' } as never, { sourceId: 'default' });
+ expect(captured).toHaveLength(1);
+ expectBreadth(captured[0]);
+ });
+
+ test('whoknows expert search', async () => {
+ captured.length = 0;
+ await findExperts(engineStub, { topic: 'payments infrastructure' });
+ expect(captured).toHaveLength(1);
+ expectBreadth(captured[0]);
+ });
+
+ test('brainstorm close-set and enrich spread the shared object into their hybridSearch call', () => {
+ for (const rel of ['src/core/brainstorm/orchestrator.ts', 'src/commands/enrich.ts']) {
+ const src = readFileSync(join(import.meta.dir, '..', rel), 'utf8');
+ const calls = [...src.matchAll(/await hybridSearch\([^,]+,[^,]+,\s*\{([^}]*)\}/g)];
+ expect(calls.length).toBeGreaterThan(0);
+ for (const call of calls) expect(call[1]).toContain('...INTERNAL_BREADTH_SEARCH_OPTS');
+ }
+ });
+});
diff --git a/test/think-gather-adaptive-return.serial.test.ts b/test/think-gather-adaptive-return.serial.test.ts
new file mode 100644
index 0000000000..247dc2725a
--- /dev/null
+++ b/test/think-gather-adaptive-return.serial.test.ts
@@ -0,0 +1,76 @@
+/**
+ * #5890 — think/synthesize evidence gather must not be trimmed by adaptive
+ * return. With `search.adaptive_return` on, the reader-facing intent cap
+ * (entity 2 pages, other 6) used to cut a breadth-sized gather of 12
+ * matching meetings to 2 or 6 pages before synthesis saw them.
+ *
+ * Real PGLite + real runGather. Embeddings are mocked deterministically so
+ * hybridSearch takes the vector path (the keyword-only short-circuit skips
+ * adaptive return and would hide the bug).
+ *
+ * Serial: mock.module + process-global gateway config.
+ */
+
+import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as realEmbedding from '../src/core/embedding.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+
+function unitVector(seed: number): Float32Array {
+ const arr = new Float32Array(1536);
+ for (let i = 0; i < arr.length; i++) arr[i] = Math.sin(1 + i * 0.001) + seed * 0.0001 * Math.cos(i);
+ const norm = Math.sqrt(arr.reduce((s, v) => s + v * v, 0));
+ return arr.map((v) => v / norm);
+}
+
+mock.module('../src/core/embedding.ts', () => ({
+ ...realEmbedding,
+ embed: async () => unitVector(0),
+ embedQuery: async () => unitVector(0),
+}));
+
+const { runGather } = await import('../src/core/think/gather.ts');
+const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+
+let engine: InstanceType<typeof PGLiteEngine>;
+let tmpHome: string;
+const savedHome = process.env.GBRAIN_HOME;
+const MEETINGS = 12;
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-5890-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-fake' } });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 1; i <= MEETINGS; i++) {
+ const slug = `meetings/zorblax-review-${i}`;
+ const body = `Zorblax review ${i}: the team discussed the Zorblax rollout, risks and next steps.`;
+ await engine.putPage(slug, { type: 'meeting', title: `Zorblax review ${i}`, compiled_truth: body });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth', embedding: unitVector(i) }]);
+ }
+ await engine.setConfig('search.adaptive_return', 'true');
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ resetGateway();
+ if (savedHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = savedHome;
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('#5890 gather keeps breadth with adaptive return on', () => {
+ for (const question of ['Zorblax', 'what did the team decide about the zorblax rollout']) {
+ test(`"${question}" gathers all ${MEETINGS} meetings`, async () => {
+ const result = await runGather(engine, { question, remote: false });
+ const meetings = result.pages.filter((p) => p.slug.startsWith('meetings/zorblax-review-'));
+ expect(new Set(meetings.map((p) => p.slug)).size).toBe(MEETINGS);
+ }, 30_000);
+ }
+});