Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keyword search labels rows that match the query as written keyword_exact
garrytanf74f0a23b165
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49d23cea54..37768e2b03 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@ identifiers and attribution are available in the pre-removal Git revision- `get_backlinks` with a `type` that other pages in the brain have, but no page linking to this one has, now returns the normal empty answer plus a note listing the types the linking pages do have. Before, it refused with `unknown type`, so an agent walking several accounts by type was refused once per account. A type no page has is still refused, and the refusal now also lists the brain's own page types. For a remote caller, both checks count only pages that caller can read: a type found only on private pages, pages whose readers leave the caller out, deleted pages or another source is treated as a type that does not exist and is never named.- `list_pages` with a `type` that no page has still returns the same empty list, but now adds a note naming the page types the brain does have, most common first (up to 12, with counts). Before, a guessed type such as `account` on a brain that files accounts as `crm` came back as a bare `[]`, which reads like "no such pages". A remote caller's note names only types of pages it can read.+- `search` with `match: "keyword"` now labels every row that matches the query as written `keyword_exact`, including rows from your own `"A" OR "B"` query or a one-word query. Their match scores sit below the cutoff the label used to need, so they were labelled `weak_semantic`, which told agents the batched lookup the instructions recommend had found nothing solid. `create_safety` (the "don't write a duplicate" hint) is unchanged for these rows. Rows found only by gbrain's own fallback of loosening a query to any-word matching stay `weak_semantic`, and default (hybrid) search is unchanged.## [0.60.651.0] - 2026-11-10diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 198dd347ac..11f0313cb7 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The `vector` strategy runs the production query path: `embedQuery` (query-side `input_type` on asymmetric providers) in the resolved embedding column's model, searched on that column — `embed()` is the document side and would handicap the vector baseline.-- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so an agent never reads one blended score, decides "no strong match, safe to create", and writes a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent. `keyword_relaxed` rows never earn `keyword_exact`; CRAG grades a relaxed top `weak` (A4-2).+- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so one blended score never reads as "safe to create"). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor`; never the blended score, so a keyword+boost pile-up can't earn it; legacy `HIGH_MATCH_FLOOR=0.85` is exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`; GBRA-449: any strict row under `EvidenceOpts.keywordMode`, which only search `match: "keyword"` sets, except a `matched_alias` row) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) agents key off instead of a raw threshold. `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent; `create_safety` ignores `keywordMode`, so a relabelled row keeps `unknown`. `keyword_relaxed` rows never earn `keyword_exact`; CRAG grades a relaxed top `weak` (A4-2).- `src/core/search/expansion.ts` — Multi-query expansion via Haiku. Exports `sanitizeQueryForPrompt` + `sanitizeExpansionOutput` (prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search. `expandQuery` returns the original first plus 2-3 variants; `hybridSearch` re-enforces `queries[0]` = the caller's query and dedupes repeats, then fuses each variant's vector list as a role `variant` arm through `src/core/search/fusion-lists.ts` (see that entry), where the variant arms share `search.expansion_variant_budget` as total RRF weight — `null` (every bundle's default) is legacy equal weight, the configuration under which the LongMemEval receipt shows expansion halving strict `recall_all@5` (93.19% plain hybrid vs 54.89% with expansion, paired +3 / -183; `docs/architecture/RETRIEVAL.md` "Multi-query expansion"). The harness records `expansion_variants` per row and `--expansion-replay` serves them back so a budget sweep changes only the budget.diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 3e3ef354b7..c58601aae5 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -21,7 +21,7 @@ import { validateSlug } from '../utils.ts';import { ALL_SOURCES, NO_SOURCES, isValidSourceId } from '../source-id.ts';import { encodeDeepResearchId } from '../deep-research-id.ts';import { isSearchMode } from '../search/mode.ts';-import { stampEvidence } from '../search/evidence.ts';+import { stampEvidence, type EvidenceOpts } from '../search/evidence.ts';import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';import type { SearchResult, HybridSearchMeta, PageReadScope, PageReadPolicy } from '../types.ts';import { resolveExcludePrivatePages, isPrivatePage } from '../search/private-visibility.ts';@@ -1236,8 +1236,8 @@ export function resolvePerCallMode(ctx: OperationContext, raw: unknown, opName =}/** T4 — stamp evidence/create_safety on a result set, fail-soft. */-export function stampEvidenceSafe(results: SearchResult[]): void {- try { stampEvidence(results); } catch { /* non-fatal */ }+export function stampEvidenceSafe(results: SearchResult[], opts?: EvidenceOpts): void {+ try { stampEvidence(results, opts); } catch { /* non-fatal */ }}export function stampDeepResearchIds(results: SearchResult[]): void {diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 7f4b4e145e..9fb4654f48 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -223,11 +223,12 @@ async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>,}/** Keyword rows (every one a direct FTS hit): the markers hybridSearch would stamp, then bookkeeping. */-async function stampKeywordRows(ctx: OperationContext, results: SearchResult[], scope: SourceScope & { excludePrivate: boolean }, queryText: string, startedAt: number, timings: SearchTimings): Promise<void> {+async function stampKeywordRows(ctx: OperationContext, results: SearchResult[], scope: SourceScope & { excludePrivate: boolean }, queryText: string, startedAt: number, timings: SearchTimings, keywordMode: boolean): Promise<void> {// #3783: mark before stamping so evidence still reads keyword_exact.markKeywordHits(results);stampDeepResearchIds(results);- stampEvidenceSafe(results);+ // GBRA-449: with match "keyword" each row satisfies the caller's own keyword statement (this path never OR-relaxes), whatever its score.+ stampEvidenceSafe(results, { keywordMode });// #1699 / #160: the content_flag channel and the unverified-stub marker still surface off the hybrid path.await timings.stage('post_fusion', () => stampContentFlags(ctx.engine, results, scope));await timings.stage('post_fusion', () => stampUnverifiedExtractions(ctx.engine, results, scope));@@ -769,7 +770,7 @@ const search: Operation = {let keywordBound: DegradedStageEntry | undefined;const results = await keepFrontmatterMatches(ctx.engine, (page ? page.rows : dedupResults(await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts,onKeywordIncomplete: reason => { keywordBound = { stage: 'keyword_candidates_incomplete', reason }; } })).finally(lexicalDone.resolve))).map(r => ({ ...r })), where);- await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt, timings);+ await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt, timings, paging.match === 'keyword');// #3800: cap AFTER capture/meta so eval + cache see the real payload.return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap, timings,async rows => withCountMeta(withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, filterHintFor: { op: 'search', p }, timings }),diff --git a/src/core/search/evidence.ts b/src/core/search/evidence.tsindex 4b3dad065b..7cea7d99a6 100644--- a/src/core/search/evidence.ts+++ b/src/core/search/evidence.ts@@ -20,7 +20,8 @@* keyword_exact — surfaced by a strict lexical arm (keyword/title FTS,* keyword_hit=true, not keyword_relaxed) with a solid* score (#3783 — a solid blended score alone no longer- * earns this label)+ * earns this label); in keyword mode (GBRA-449) any+ * strict keyword row, whatever its score* weak_semantic — everything else (low-confidence tail)** create_safety:@@ -65,6 +66,15 @@ export const DEFAULT_HIGH_COSINE_FLOOR = 0.8;export interface EvidenceOpts {/** Cosine floor for high_vector_match (default DEFAULT_HIGH_COSINE_FLOOR). */cosineFloor?: number;+ /**+ * GBRA-449: the rows come from a keyword-mode search (search `match: "keyword"`;+ * not the operator's `search.mcp_keyword_only` route), where every strict row satisfies the query as the+ * caller wrote it, its own OR included. Such a row (unless it matched only an+ * entity name the engine added, `matched_alias`) is keyword_exact whatever its+ * score; normalized ts_rank for an OR or one-word query sits far under+ * SOLID_MATCH_FLOOR. create_safety still follows the score floor.+ */+ keywordMode?: boolean;}export function classifyEvidence(r: SearchResult, opts: EvidenceOpts = {}): Evidence {@@ -85,7 +95,10 @@ export function classifyEvidence(r: SearchResult, opts: EvidenceOpts = {}): Evid// zero-strict-recall fallback) matched some query terms, not the query, so// it is not lexically verified.const base = typeof r.base_score === 'number' ? r.base_score : r.score;- if (r.keyword_hit === true && r.keyword_relaxed !== true && Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) {+ // GBRA-449: keyword mode waives the floor for a row that matched the caller's own statement, not an engine-added+ // name (matched_alias: the row matched only one of the entity's other names the engine ORed into the query).+ const callersOwnMatch = opts.keywordMode === true && !r.matched_alias;+ if (r.keyword_hit === true && r.keyword_relaxed !== true && (callersOwnMatch || (Number.isFinite(base) && base >= SOLID_MATCH_FLOOR))) {return 'keyword_exact';}return 'weak_semantic';@@ -119,12 +132,14 @@ export function createSafetyFor(evidence: Evidence): CreateSafety {/*** Stamp `evidence` + `create_safety` on every result in place. Called once at* the end of the hybrid pipeline (after the alias hop, before slice) so the- * agent-facing result carries the contract. Idempotent.+ * agent-facing result carries the contract. Idempotent. GBRA-449: create_safety+ * is derived from the label without `keywordMode`, so a keyword-mode row+ * relabelled keyword_exact under the score floor keeps the `unknown` it had.*/export function stampEvidence(results: SearchResult[], opts: EvidenceOpts = {}): void {for (const r of results) {const e = classifyEvidence(r, opts);r.evidence = e;- r.create_safety = createSafetyFor(e);+ r.create_safety = createSafetyFor(opts.keywordMode ? classifyEvidence(r, { ...opts, keywordMode: false }) : e);}}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 035117ca10..6647e48a19 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -516,6 +516,7 @@ test/schema-missing-tables.test.tstest/schema-replay-deadlock-6143.test.tstest/scripts/test-stress-postgres.test.tstest/search-entity-facts-eligibility.test.ts+test/search-keyword-evidence-label-gbra449.test.tstest/search-read-keyword-bound.test.tstest/search-remote-page-cap.test.tstest/search-transcript-quote-8384.test.tsdiff --git a/test/search-keyword-evidence-label-gbra449.test.ts b/test/search-keyword-evidence-label-gbra449.test.tsnew file mode 100644index 0000000000..905dc2ee69--- /dev/null+++ b/test/search-keyword-evidence-label-gbra449.test.ts@@ -0,0 +1,134 @@+/**+ * GBRA-449 fix 3: in keyword mode every row a strict keyword statement+ * returned matches the query as the caller wrote it, so it is labelled+ * keyword_exact whatever its normalized ts_rank score.+ *+ * Protects (red before: '"2026-08-04" OR "2026-08-08"' and 'Escalated' with+ * match: "keyword" labelled every row weak_semantic, because their scores sit+ * under SOLID_MATCH_FLOOR):+ * - the three repro shapes (one quoted date, the caller's own explicit OR, one+ * word) label every row keyword_exact in keyword mode;+ * - create_safety keeps the value it had before for every relabelled row+ * (unknown under the floor, probable above it);+ * - a row that matched only through the engine's OR relaxation+ * (keyword_relaxed) or only through an entity name the engine added+ * (matched_alias) stays weak_semantic under the floor, and so does a+ * below-floor row outside keyword mode (stampEvidence unit cases);+ * - hybrid search (the default match) keeps its labels.+ * Database-only (repo-less) brain: pages are imported straight into the+ * database (importFromContent, the put_page import path), no checkout; keyless (no embedding provider). PGLite always, Postgres when+ * DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import type { SearchResult } from '../src/core/types.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { SOLID_MATCH_FLOOR, stampEvidence } from '../src/core/search/evidence.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++type Row = { slug: string; evidence: string; create_safety: string; score: number };++describe('stampEvidence keyword mode (GBRA-449)', () => {+ const row = (extra: Partial<SearchResult>) => ({ slug: 'contracts/c1', score: 0.2, base_score: 0.2, keyword_hit: true, ...extra }) as SearchResult;+ test('a strict keyword row under the floor is keyword_exact with the create_safety it had (unknown)', () => {+ const r = row({});+ stampEvidence([r], { keywordMode: true });+ expect([r.evidence, r.create_safety]).toEqual(['keyword_exact', 'unknown']);+ });+ test('a strict keyword row at the floor keeps keyword_exact and probable', () => {+ const r = row({ score: SOLID_MATCH_FLOOR, base_score: SOLID_MATCH_FLOOR });+ stampEvidence([r], { keywordMode: true });+ expect([r.evidence, r.create_safety]).toEqual(['keyword_exact', 'probable']);+ });+ test('an OR-relaxed row stays weak_semantic in keyword mode', () => {+ const r = row({ keyword_relaxed: true, score: 0.9, base_score: 0.9 });+ stampEvidence([r], { keywordMode: true });+ expect([r.evidence, r.create_safety]).toEqual(['weak_semantic', 'unknown']);+ });+ test('a row that matched only an entity name the engine added (matched_alias) keeps the floor in keyword mode', () => {+ const r = row({ matched_alias: 'Acme Example' });+ stampEvidence([r], { keywordMode: true });+ expect([r.evidence, r.create_safety]).toEqual(['weak_semantic', 'unknown']);+ });+ test('a row with no keyword_hit stays weak_semantic in keyword mode', () => {+ const r = row({ keyword_hit: undefined });+ stampEvidence([r], { keywordMode: true });+ expect([r.evidence, r.create_safety]).toEqual(['weak_semantic', 'unknown']);+ });+ test('outside keyword mode the floor still applies', () => {+ const r = row({});+ stampEvidence([r]);+ expect([r.evidence, r.create_safety]).toEqual(['weak_semantic', 'unknown']);+ });+});++for (const backend of testBackends()) {+ describe('[' + backend + '] search match: keyword labels the caller\'s own matches keyword_exact (GBRA-449)', () => {+ let engine: BrainEngine;+ const config = { engine: backend } as never;+ const local = { remote: false, sourceId: 'default', config };+ const remote = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };++ beforeAll(async () => {+ if (backend === 'postgres') {+ const pg = new PostgresEngine();+ await pg.connect({ database_url: requirePostgresTestDatabase() });+ engine = pg;+ } else {+ const lite = new PGLiteEngine();+ await lite.connect({});+ engine = lite;+ }+ await engine.initSchema();+ __setEmbedTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ }, 180_000);+ afterAll(async () => { resetGateway(); await engine.disconnect(); });++ const put = (slug: string, type: string, body: string) =>+ importFromContent(engine, slug, ['---', 'type: ' + type, 'title: ' + slug, '---', body, ''].join('\n'), { noEmbed: true });++ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await put('contracts/c1', 'contract', 'Renewal date: 2026-08-04.');+ await put('contracts/c2', 'contract', 'Renewal date: 2026-08-08.');+ for (let i = 1; i <= 6; i++) await put('tickets/t' + i, 'ticket', 'Ticket ' + i + ' status: Escalated to tier two.');+ });++ async function search(query: string, extra: Record<string, unknown>, opts: Record<string, unknown> = local): Promise<Row[]> {+ const r = await dispatchToolCall(engine, 'search', { query, ...extra }, opts as never);+ expect(r.isError).not.toBe(true);+ const body = JSON.parse(r.content[0]!.text);+ return (Array.isArray(body) ? body : body.results) as Row[];+ }+ const labels = (rows: Row[]) => rows.map(r => r.slug + ' ' + r.evidence + ' ' + r.create_safety).sort();++ test('one quoted date: keyword_exact, create_safety unchanged (probable above the floor)', async () => {+ const rows = await search('"2026-08-04"', { match: 'keyword' });+ expect(labels(rows)).toEqual(['contracts/c1 keyword_exact probable']);+ });++ test('the caller\'s own OR and a single word: every row keyword_exact, create_safety stays unknown', async () => {+ for (const opts of [local, remote]) {+ const or = await search('"2026-08-04" OR "2026-08-08"', { match: 'keyword' }, opts);+ expect(labels(or)).toEqual(['contracts/c1 keyword_exact unknown', 'contracts/c2 keyword_exact unknown']);+ expect(or.every(r => r.score < SOLID_MATCH_FLOOR)).toBe(true);+ const word = await search('Escalated', { match: 'keyword' }, opts);+ expect(labels(word)).toEqual([1, 2, 3, 4, 5, 6].map(i => 'tickets/t' + i + ' keyword_exact unknown'));+ }+ });++ test('a keyword query no page satisfies is not relaxed into weak rows', async () => {+ expect(await search('Escalated zebra', { match: 'keyword' })).toEqual([]);+ });++ test('hybrid search (default match) keeps its labels', async () => {+ expect(labels(await search('"2026-08-04" OR "2026-08-08"', {}))).toEqual(['contracts/c1 weak_semantic unknown', 'contracts/c2 weak_semantic unknown']);+ expect(labels(await search('Escalated', {}))).toEqual([1, 2, 3, 4, 5, 6].map(i => 'tickets/t' + i + ' weak_semantic unknown'));+ });+ });+}