Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): parse queries holding 32+ dash runs; CRAG grades always carry the rank-1 rerank score
time-attack0faf6c0cf17f
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 3c6f918dc2..ae0b5c81e8 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -116,7 +116,7 @@ import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } fromimport { PAGE_SORT_SQL } from './types.ts';import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import {@@ -1414,7 +1414,7 @@ export class PGLiteEngine implements BrainEngine {}// v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.- const params: unknown[] = [query, innerLimit, limit, offset];+ const params: unknown[] = [collapseWebsearchDashRuns(query), innerLimit, limit, offset];let extraFilter = '';if (opts?.language) {params.push(opts.language);@@ -1614,7 +1614,7 @@ export class PGLiteEngine implements BrainEngine {});}- const params: unknown[] = [query, limit, offset];+ const params: unknown[] = [collapseWebsearchDashRuns(query), limit, offset];let extraFilter = '';if (opts?.language) {params.push(opts.language);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex fa1df50ee4..86c08b9aef 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -106,7 +106,7 @@ import { logConnectionEvent } from './connection-audit.ts';import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';@@ -975,7 +975,7 @@ export class PostgresEngine implements BrainEngine {});}- const params: unknown[] = [query];+ const params: unknown[] = [collapseWebsearchDashRuns(query)];let typeClause = '';if (type) {params.push(type);@@ -1103,7 +1103,7 @@ export class PostgresEngine implements BrainEngine {const previous = relaxed ? await tx`SHOW enable_seqscan` : [];if (relaxed) await tx`SET LOCAL enable_seqscan = off`;const boundParams = [...params];- boundParams[0] = queryText;+ boundParams[0] = collapseWebsearchDashRuns(queryText);const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);if (relaxed) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;return rows;@@ -1190,7 +1190,7 @@ export class PostgresEngine implements BrainEngine {});}- const params: unknown[] = [query];+ const params: unknown[] = [collapseWebsearchDashRuns(query)];let typeClause = '';if (type) {params.push(type);diff --git a/src/core/search/crag.ts b/src/core/search/crag.tsindex a3627d7fc1..f1bd0d7b10 100644--- a/src/core/search/crag.ts+++ b/src/core/search/crag.ts@@ -173,31 +173,35 @@ export function gradeRetrievalConfidence(if (results.length === 0) return { level: 'weak', reason: 'zero_results' };const top = results[0];const floor = typeof opts.minTopScore === 'number' ? opts.minTopScore : DEFAULT_CRAG_MIN_TOP;+ // Calibrated cross-encoder score of rank 1 when the reranker ran (System One rubric levels are not calibrated).+ // Every grade carries it, including the identity tiers that decide before it: a verbatim quote grades+ // `high_vector_match`, and a reader of `top_rerank_score` must still see that the reranker ran.+ const reranked = typeof top.rerank_score === 'number' && Number.isFinite(top.rerank_score) && top.rerank_score_kind !== 'rubric';+ const rerankScore = reranked ? { top_rerank_score: top.rerank_score! } : {};// Identity-tier signals win outright — retrieval FOUND the named thing.if (top.exact_lookup !== undefined) {- return { level: 'strong', reason: 'exact_lookup', top_evidence: top.evidence };+ return { level: 'strong', reason: 'exact_lookup', top_evidence: top.evidence, ...rerankScore };}if (top.alias_hit === true || top.evidence === 'alias_hit') {- return { level: 'strong', reason: 'alias_hit', top_evidence: top.evidence };+ return { level: 'strong', reason: 'alias_hit', top_evidence: top.evidence, ...rerankScore };}if (top.evidence === 'exact_title_match') {- return { level: 'strong', reason: 'exact_title_match', top_evidence: top.evidence };+ return { level: 'strong', reason: 'exact_title_match', top_evidence: top.evidence, ...rerankScore };}if (top.evidence === 'high_vector_match') {- return { level: 'strong', reason: 'high_vector_match', top_evidence: top.evidence };+ return { level: 'strong', reason: 'high_vector_match', top_evidence: top.evidence, ...rerankScore };}// System One S3 (only stamped when the slot acted): the top kept candidate cleared the evidence threshold.if (!opts.ignoreDecideEvidence && top.decide_evidence?.clears) {- return { level: 'strong', reason: 'decide_evidence', top_evidence: top.evidence };+ return { level: 'strong', reason: 'decide_evidence', top_evidence: top.evidence, ...rerankScore };}- // Calibrated cross-encoder signal when the reranker ran (System One rubric levels are not calibrated).- if (typeof top.rerank_score === 'number' && Number.isFinite(top.rerank_score) && top.rerank_score_kind !== 'rubric') {- return top.rerank_score >= floor- ? { level: 'strong', reason: 'rerank_top', top_evidence: top.evidence, top_rerank_score: top.rerank_score }- : { level: 'weak', reason: 'rerank_top_below_floor', top_evidence: top.evidence, top_rerank_score: top.rerank_score };+ if (reranked) {+ return top.rerank_score! >= floor+ ? { level: 'strong', reason: 'rerank_top', top_evidence: top.evidence, ...rerankScore }+ : { level: 'weak', reason: 'rerank_top_below_floor', top_evidence: top.evidence, ...rerankScore };}// No reranker: fall back to the T4 evidence contract. An OR-relaxeddiff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 1294ebcef4..1905a7db9e 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -258,6 +258,23 @@ export function buildBestPerPagePoolCte(candidateCte: string): string {export const MAX_WEBSEARCH_QUERY_CHARS = 64_000;export const MAX_WEBSEARCH_QUERY_TERMS = 256;+/** Longest run of dash negations `websearch_to_tsquery` parses: its operator stack holds 32 entries. */+export const MAX_WEBSEARCH_DASH_RUN = 31;++/**+ * Collapse runs of more than MAX_WEBSEARCH_DASH_RUN dash negations to their+ * parity. websearch_to_tsquery reads every `-` before a term as one more NOT+ * (`x ---- y` is `'x' & !!!!'y'`), so a markdown rule or setext underline of+ * 32+ dashes (`-----...` or `- - - ...`) overflows its operator stack and+ * raises `tsquery stack too small`, failing the keyword and title arms for+ * the whole query. An even run becomes a space and an odd run a single `-`:+ * the tsquery a deeper stack would build. Shorter runs, and so every query+ * that parses today, pass through unchanged.+ */+export function collapseWebsearchDashRuns(query: string): string {+ return query.replace(/-(?:\s*-){31,}/g, run => ((run.match(/-/g)!.length % 2) === 1 ? ' -' : ' '));+}+/*** Bound caller text before feeding it to `websearch_to_tsquery`.*@@ -265,7 +282,8 @@ export const MAX_WEBSEARCH_QUERY_TERMS = 256;* large, high-term-count strings. Keep ordinary exact-title/body searches* untouched, but cap pasted grounding blobs before they reach SQL.*/-export function boundWebsearchQuery(query: string): string {+export function boundWebsearchQuery(raw: string): string {+ const query = collapseWebsearchDashRuns(raw);if (query.length <= MAX_WEBSEARCH_QUERY_CHARS) {let terms = 0;for (const _ of query.matchAll(/[\p{L}\p{N}]+/gu)) {diff --git a/test/search/crag.test.ts b/test/search/crag.test.tsindex 270961f99b..c84995981e 100644--- a/test/search/crag.test.ts+++ b/test/search/crag.test.ts@@ -44,6 +44,15 @@ describe('gradeRetrievalConfidence (#1663)', () => {expect(weak.reason).toBe('rerank_top_below_floor');});+ test('every grade carries the rank-1 rerank score when the reranker ran, including identity tiers', () => {+ for (const evidence of ['high_vector_match', 'exact_title_match', 'alias_hit'] as const) {+ const g = gradeRetrievalConfidence([r({ evidence, rerank_score: 0.91 })]);+ expect({ level: g.level, reason: g.reason, top_rerank_score: g.top_rerank_score }).toEqual({ level: 'strong', reason: evidence, top_rerank_score: 0.91 });+ }+ expect(gradeRetrievalConfidence([r({ evidence: 'high_vector_match' })]).top_rerank_score).toBeUndefined();+ expect(gradeRetrievalConfidence([r({ evidence: 'high_vector_match', rerank_score: 3, rerank_score_kind: 'rubric' })]).top_rerank_score).toBeUndefined();+ });+test('floor is overridable', () => {expect(gradeRetrievalConfidence([r({ rerank_score: 0.15 })], { minTopScore: 0.1 }).level).toBe('strong');expect(gradeRetrievalConfidence([r({ rerank_score: 0.15 })], { minTopScore: 0.3 }).level).toBe('weak');diff --git a/test/websearch-dash-runs.test.ts b/test/websearch-dash-runs.test.tsnew file mode 100644index 0000000000..dd8b1e66a7--- /dev/null+++ b/test/websearch-dash-runs.test.ts@@ -0,0 +1,80 @@+import { installFixtureChunks } from './helpers/page-projection.ts';+/**+ * A query holding a markdown rule or setext underline of 32+ dashes+ * (`-----...`, `- - - ...`) used to fail the keyword and title arms:+ * websearch_to_tsquery reads every dash as one more NOT and its operator+ * stack holds 32 entries (`tsquery stack too small`). Pasted passages hit it;+ * the eval readiness probe quotes the start of a session's longest turn, and+ * assistant turns open with `Section\n-----` headings.+ *+ * `collapseWebsearchDashRuns` collapses such a run to its parity (the tsquery+ * a deeper stack would build) and leaves every shorter run, so every query+ * that parses today, byte-identical. Real in-memory PGLite.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import * as SR from '../src/core/search/sql-ranking.ts';++let engine: PGLiteEngine;+const { boundWebsearchQuery } = SR as any; const collapseWebsearchDashRuns = (SR as any).collapseWebsearchDashRuns ?? ((q: string) => q); const MAX_WEBSEARCH_DASH_RUN = 31;+const parse = async (q: string) => (await engine.executeRaw<{ q: string }>(`SELECT websearch_to_tsquery('english', $1)::text AS q`, [q]))[0]!.q;+const RULE = '-'.repeat(73);+const PASSAGE = `Sure, here is an outline for the pandas module:\n\nTime series analysis using Pandas\n${RULE}\n\n### Background:\n\nAs a data analyst you review banking transaction data`;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('conversations/outline', { type: 'note', title: 'Time series analysis using Pandas', compiled_truth: PASSAGE });+ await installFixtureChunks(engine, 'conversations/outline', [{ chunk_index: 0, chunk_text: PASSAGE, chunk_source: 'compiled_truth' }]);+ await engine.putPage('conversations/other', { type: 'note', title: 'Garden notes', compiled_truth: 'Repotting a fern in spring.' });+ await installFixtureChunks(engine, 'conversations/other', [{ chunk_index: 0, chunk_text: 'Repotting a fern in spring.', chunk_source: 'compiled_truth' }]);+});++afterAll(async () => {+ await engine.disconnect();+}, 30_000);++describe('collapseWebsearchDashRuns', () => {+ test('a run websearch_to_tsquery can parse passes through byte-identical', async () => {+ for (const q of ['x y', 'x - y', 'x -y', 'foo-bar', `x ${'-'.repeat(MAX_WEBSEARCH_DASH_RUN)} y`, `x ${'- '.repeat(MAX_WEBSEARCH_DASH_RUN)}y`, 'Pandas\n-----\n\n### Background', '']) {+ expect(collapseWebsearchDashRuns(q)).toBe(q);+ await parse(q);+ }+ });++ test('a longer run used to overflow the operator stack and now parses as its parity', async () => {+ for (const n of [MAX_WEBSEARCH_DASH_RUN + 1, 40, 41, 73, 200]) {+ for (const run of ['-'.repeat(n), Array(n).fill('-').join(' ')]) {+ const q = `x ${run} y`;+ await expect(parse(q)).rejects.toThrow('tsquery stack too small');+ const parity = n % 2 === 1 ? `x - y` : `x y`;+ expect(await parse(collapseWebsearchDashRuns(q))).toBe(await parse(parity));+ }+ }+ });++ test('boundWebsearchQuery (the title arm) collapses the run too', () => {+ expect(boundWebsearchQuery(`x ${'-'.repeat(40)} y`)).toBe('x y');+ });+});++describe('keyword and title arms on a passage holding a 73-dash rule', () => {+ test('raw websearch_to_tsquery fails on the passage (the bug)', async () => {+ await expect(parse(PASSAGE)).rejects.toThrow('tsquery stack too small');+ });++ test('searchKeyword returns the page instead of failing', async () => {+ const hits = await engine.searchKeyword(PASSAGE, { limit: 10 });+ expect(hits.map(h => h.slug)).toEqual(['conversations/outline']);+ });++ test('searchKeywordChunks returns the chunk instead of failing', async () => {+ const hits = await engine.searchKeywordChunks(PASSAGE, { limit: 10 });+ expect(hits.map(h => h.slug)).toEqual(['conversations/outline']);+ });++ test('searchTitles no longer fails on the passage', async () => {+ await engine.searchTitles(PASSAGE, { limit: 10 });+ });+});