Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): entity-anchored retrieval for entity-scoped current-state query/search behind search.entity_anchoring (default off); shared with pinned refresh; gate harnesses

garrytan2fa44f149a35
diff --git a/evals/entity-anchoring/query-gate.ts b/evals/entity-anchoring/query-gate.ts
new file mode 100644
index 0000000000..1de11c3b18
--- /dev/null
+++ b/evals/entity-anchoring/query-gate.ts
@@ -0,0 +1,129 @@
+/**
+ * Entity-anchored query retrieval, gate 1 (docs/eval/decisions/entity-anchoring-query/).
+ * The appended-corrections workload of the pinned-questions run 3, read
+ * through the real `query` op with `search.entity_anchoring` on and off in the
+ * same brain, by the same reader, at equal tokens (the top rows in rank order
+ * up to 200 tokens) and at full evidence (16 rows). Expansion is off so the
+ * only model call per read is the reader.
+ *
+ * bun evals/entity-anchoring/query-gate.ts --plan --seeds 42,7,1234
+ * bun evals/entity-anchoring/query-gate.ts --offline --json --seeds 42 --entities 2
+ * bun evals/entity-anchoring/query-gate.ts --run --yes --max-usd 4 --seeds 42,7,1234 --embeddings voyage:voyage-4 --json
+ */
+import { writeFileSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { handleToolCall } from '../../src/mcp/server.ts';
+import { normalizeModelId } from '../../src/core/model-id.ts';
+import { ENTITY_ANCHORING_KEY } from '../../src/core/search/entity-anchor.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { BATCHES, RATIOS, aggregate, appendedHash, applyEventsForTest, fit, generateAppendedWorkload, question, summarize,
+ type AppendedWorkload, type ArmRun } from '../pinned-questions/appended-gate.ts';
+import { SpendGuard, correctFor, offlineArms, paidArms, priced, readerAnswer, staleFor, type GateOpts } from '../pinned-questions/benefit-gate.ts';
+
+export const ARMS = ['anchoring_on', 'anchoring_off', 'anchoring_on_full', 'anchoring_off_full'] as const;
+export const BUDGET_TOKENS = 200;
+const FULL_ROWS = 16;
+
+export interface QueryGateOpts { workload: AppendedWorkload; readerModel: string; embed: boolean; reader: GateOpts['reader'] }
+
+export async function runQueryGate(opts: QueryGateOpts): Promise<{ arms: ArmRun[]; triggered: number; states: number }> {
+ const w = opts.workload;
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const arms = Object.fromEntries(ARMS.map(a => [a, { arm: a, reads: [], lifecycle_usd: 0, refresh_attempts: 0 } as ArmRun])) as Record<typeof ARMS[number], ArmRun>;
+ const remembered = new Map<string, string>();
+ let triggered = 0;
+ try {
+ const { runEmbedCore } = await import('../../src/commands/embed.ts');
+ const rows = async (q: string, on: boolean) => {
+ await engine.setConfig(ENTITY_ANCHORING_KEY, on ? 'true' : 'false');
+ return await handleToolCall(engine, 'query', { query: q, limit: FULL_ROWS, expand: false, use_cache: false }) as SearchResult[];
+ };
+ for (let b = 0; b < BATCHES; b++) {
+ await applyEventsForTest(engine, w.batches[b]!, remembered);
+ if (opts.embed) {
+ const r = await runEmbedCore(engine, { stale: true, sourceId: 'default', quiet: true });
+ if (r.failures > 0) throw new Error(`embedding failed for ${r.failures} page(s)`);
+ }
+ for (const e of w.entities) {
+ const gold = w.gold[e.slug]![b]!;
+ const past = new Set(w.history[e.slug]!);
+ const q = question(e.name);
+ const read = async (arm: ArmRun, context: string) => {
+ const r = await readerAnswer(opts.reader, opts.readerModel, q, context);
+ arm.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(r.text, gold), stale: staleFor(r.text, gold, past), usd: priced(r.model, r.input_tokens, r.output_tokens) });
+ };
+ const on = await rows(q, true);
+ const off = await rows(q, false);
+ if (on.some(r => r.entity_anchored)) triggered++;
+ const parts = (rs: SearchResult[]) => rs.map(r => `[${r.slug}] ${r.chunk_text}`);
+ await read(arms.anchoring_on, fit(parts(on), BUDGET_TOKENS));
+ await read(arms.anchoring_off, fit(parts(off), BUDGET_TOKENS));
+ await read(arms.anchoring_on_full, parts(on).join('\n'));
+ await read(arms.anchoring_off_full, parts(off).join('\n'));
+ }
+ }
+ } finally {
+ await engine.disconnect();
+ }
+ return { arms: Object.values(arms), triggered, states: w.entities.length * BATCHES };
+}
+
+type Summary = ReturnType<typeof summarize>;
+
+/** Preregistered gate 1: in every seed the key-on arm has higher accuracy or lower freshness lag, and lower accuracy in no seed. */
+export function decideGate(perSeed: Array<{ seed: number; summary: Summary[] }>) {
+ const seeds = perSeed.map(({ seed, summary }) => {
+ const at = (arm: string) => summary.find(s => s.reads_per_write === 1 && s.arm === arm)!;
+ const on = at('anchoring_on'), off = at('anchoring_off');
+ const higher = on.accuracy > off.accuracy, fresher = on.freshness.mean_lag_batches < off.freshness.mean_lag_batches;
+ return { seed, on_accuracy: on.accuracy, off_accuracy: off.accuracy, on_lag: on.freshness.mean_lag_batches, off_lag: off.freshness.mean_lag_batches,
+ on_stale: on.stale_wrong_rate, off_stale: off.stale_wrong_rate, wins: higher || fresher, accuracy_lower: on.accuracy < off.accuracy };
+ });
+ return { seeds, pass: seeds.every(s => s.wins && !s.accuracy_lower) };
+}
+
+if (import.meta.main) {
+ const args = process.argv.slice(2);
+ const flag = (n: string) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; };
+ const json = args.includes('--json');
+ const seeds = (flag('--seeds') ?? '42').split(',').map(Number);
+ const readerModel = flag('--reader-model') ?? 'anthropic:claude-sonnet-5-5';
+ const embeddingModel = flag('--embeddings');
+ const entities = Number(flag('--entities') ?? 6);
+ const workloads = seeds.map(seed => generateAppendedWorkload(seed, entities));
+ const states = entities * BATCHES;
+ // Two budgeted reads (~650 in / 50 out) and two full-evidence reads (~2k in / 50 out) per state, run 3's sizes x1.25.
+ const estimate = seeds.length * states * (2 * priced(readerModel, 650, 50) + 2 * priced(readerModel, 2_000, 50));
+ if (args.includes('--plan') || (!args.includes('--offline') && !args.includes('--run'))) {
+ console.log(JSON.stringify({ mode: 'plan', seeds, workload_hashes: workloads.map(appendedHash), states_per_seed: states, reader_model: readerModel, embedding_model: embeddingModel ?? null, est_usd: estimate }, null, 2));
+ process.exit(0);
+ }
+ const paid = args.includes('--run');
+ const cap = Number(flag('--max-usd'));
+ if (paid && (!args.includes('--yes') || !Number.isFinite(cap) || cap < estimate)) {
+ console.error(`Refusing a paid run: pass --yes and --max-usd >= the estimate ($${estimate.toFixed(2)}).`);
+ process.exit(3);
+ }
+ if (embeddingModel && !paid) { console.error('--embeddings needs --run (offline mode makes no network calls).'); process.exit(2); }
+ const guard = new SpendGuard(paid ? cap : Infinity);
+ if (paid) {
+ const { configureGateway } = await import('../../src/core/ai/gateway.ts');
+ configureGateway({ chat_model: normalizeModelId(readerModel), ...(embeddingModel ? { embedding_model: embeddingModel, embedding_dimensions: 1024 } : {}), env: { ...process.env } as Record<string, string> });
+ }
+ const reader = paid ? paidArms(readerModel, guard).reader : offlineArms(readerModel, readerModel).reader;
+ const perSeed: Array<{ seed: number; workload_hash: string; triggered: number; states: number; summary: Summary[]; reads: unknown[] }> = [];
+ for (const workload of workloads) {
+ const out = await runQueryGate({ workload, readerModel, embed: !!embeddingModel, reader });
+ perSeed.push({ seed: workload.seed, workload_hash: appendedHash(workload), triggered: out.triggered, states: out.states,
+ summary: RATIOS.flatMap(ratio => out.arms.map(r => summarize(r, workload, ratio, null))), reads: out.arms.map(r => ({ arm: r.arm, reads: r.reads })) });
+ const partial = flag('--partial');
+ if (partial) writeFileSync(partial, JSON.stringify({ metered_spend_usd: guard.spent, per_seed: perSeed }, null, 2));
+ if (!json) console.error(`[query-gate] seed ${workload.seed} done; metered spend $${guard.spent.toFixed(4)}`);
+ }
+ const out = { mode: paid ? 'run' : 'offline', plumbing_only: !paid, seeds, entities, batches: BATCHES, reader_model: readerModel, embedding_model: embeddingModel ?? null,
+ budget_tokens: BUDGET_TOKENS, full_rows: FULL_ROWS, metered_spend_usd: Number.isFinite(guard.spent) ? guard.spent : null,
+ gate: decideGate(perSeed), aggregate: aggregate(perSeed.map(s => s.summary)), per_seed: perSeed };
+ console.log(json ? JSON.stringify(out, null, 2) : JSON.stringify(out));
+}
diff --git a/evals/entity-anchoring/regression.ts b/evals/entity-anchoring/regression.ts
new file mode 100644
index 0000000000..8c2705fbb5
--- /dev/null
+++ b/evals/entity-anchoring/regression.ts
@@ -0,0 +1,110 @@
+/**
+ * Entity-anchored query retrieval, gate 2 (docs/eval/decisions/entity-anchoring-query/):
+ * the existing retrieval evals that cover `query`, each run through the
+ * `query` op with `search.entity_anchoring` on and off. Hermetic and
+ * keyword-only (no gateway): NamedThingBench, the relational retrieval-quality
+ * fixture, and the LongMemEval nightly fixture ingested the way
+ * `gbrain eval longmemeval` ingests it. Each corpus also runs a cue-added
+ * variant (" now" appended) as a diagnostic, so anchoring fires on corpora
+ * whose questions never ask for a current state. `--dump-off <file>` writes the
+ * key-off rows for a byte-identity check against a build without the change.
+ *
+ * bun evals/entity-anchoring/regression.ts --json
+ */
+import { readFileSync, writeFileSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { handleToolCall } from '../../src/mcp/server.ts';
+import { scoreQuestion, type NamedThingQuestion } from '../../src/eval/retrieval-quality/harness.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { haystackToPages, sessionSlug } from '../../src/eval/longmemeval/adapter.ts';
+import { loadNamedThingQuestions, seedNamedThingCorpus } from '../../test/fixtures/retrieval-quality/namedthing/corpus.ts';
+import { RELATIONAL_QUESTIONS, seedRelationalCorpus } from '../../test/fixtures/retrieval-quality/relational/corpus.ts';
+
+const KEY = 'search.entity_anchoring';
+type Row = { slug: string; entity_anchored?: string };
+const dump: Record<string, unknown> = {};
+
+async function freshEngine(): Promise<PGLiteEngine> {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ return engine;
+}
+
+async function ranked(engine: PGLiteEngine, query: string, on: boolean, label: string): Promise<Row[]> {
+ await engine.setConfig(KEY, on ? 'true' : 'false');
+ const rows = await handleToolCall(engine, 'query', { query, limit: 10, expand: false, use_cache: false }) as Row[];
+ if (!on) dump[`${label}::${query}`] = rows;
+ return rows;
+}
+
+interface CorpusReport { corpus: string; questions: number; triggered: number; recall10_lower: string[]; recall10_higher: number;
+ mean_recall10: { on: number; off: number }; mean_rr: { on: number; off: number }; negative_clean_lost: string[] }
+
+async function scoreCorpus(corpus: string, engine: PGLiteEngine, questions: NamedThingQuestion[]): Promise<CorpusReport> {
+ const r: CorpusReport = { corpus, questions: questions.length, triggered: 0, recall10_lower: [], recall10_higher: 0, mean_recall10: { on: 0, off: 0 }, mean_rr: { on: 0, off: 0 }, negative_clean_lost: [] };
+ for (const q of questions) {
+ const on = await ranked(engine, q.query, true, corpus);
+ const off = await ranked(engine, q.query, false, corpus);
+ if (on.some(x => x.entity_anchored)) r.triggered++;
+ const son = scoreQuestion(q, on.map(x => x.slug)), soff = scoreQuestion(q, off.map(x => x.slug));
+ if (son.recall_at_10 < soff.recall_at_10) r.recall10_lower.push(q.query);
+ if (son.recall_at_10 > soff.recall_at_10) r.recall10_higher++;
+ if (soff.negative_clean === true && son.negative_clean === false) r.negative_clean_lost.push(q.query);
+ r.mean_recall10.on += son.recall_at_10 / questions.length; r.mean_recall10.off += soff.recall_at_10 / questions.length;
+ r.mean_rr.on += son.reciprocal_rank / questions.length; r.mean_rr.off += soff.reciprocal_rank / questions.length;
+ }
+ return r;
+}
+
+const withCue = (qs: NamedThingQuestion[]) => qs.map(q => ({ ...q, query: `${q.query.replace(/[?.!\s]+$/, '')} now?` }));
+
+async function longMemEval(path: string, cue: boolean): Promise<CorpusReport> {
+ const qs = readFileSync(path, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
+ const r: CorpusReport = { corpus: `longmemeval-nightly${cue ? '+now' : ''}`, questions: qs.length, triggered: 0, recall10_lower: [], recall10_higher: 0, mean_recall10: { on: 0, off: 0 }, mean_rr: { on: 0, off: 0 }, negative_clean_lost: [] };
+ for (const q of qs) {
+ const engine = await freshEngine();
+ try {
+ for (const p of haystackToPages(q)) await importFromContent(engine, p.slug, p.content, { noEmbed: true });
+ const gold = new Set<string>((q.answer_session_ids ?? []).map((id: string) => sessionSlug(q.question_id, id)));
+ const text = cue ? `${String(q.question).replace(/[?.!\s]+$/, '')} now?` : q.question;
+ const recall = (rows: Row[]) => gold.size ? rows.filter(x => gold.has(x.slug)).length / gold.size : 0;
+ const rr = (rows: Row[]) => { const i = rows.findIndex(x => gold.has(x.slug)); return i < 0 ? 0 : 1 / (i + 1); };
+ const on = await ranked(engine, text, true, r.corpus), off = await ranked(engine, text, false, r.corpus);
+ if (on.some(x => x.entity_anchored)) r.triggered++;
+ if (recall(on) < recall(off)) r.recall10_lower.push(q.question_id);
+ if (recall(on) > recall(off)) r.recall10_higher++;
+ r.mean_recall10.on += recall(on) / qs.length; r.mean_recall10.off += recall(off) / qs.length;
+ r.mean_rr.on += rr(on) / qs.length; r.mean_rr.off += rr(off) / qs.length;
+ } finally {
+ await engine.disconnect();
+ }
+ }
+ return r;
+}
+
+if (import.meta.main) {
+ const args = process.argv.slice(2);
+ const flag = (n: string) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; };
+ const reports: CorpusReport[] = [];
+ for (const [name, seed, questions] of [
+ ['namedthing', seedNamedThingCorpus, loadNamedThingQuestions()],
+ ['relational', seedRelationalCorpus, RELATIONAL_QUESTIONS],
+ ] as const) {
+ const engine = await freshEngine();
+ try {
+ await seed(engine);
+ reports.push(await scoreCorpus(name, engine, [...questions]));
+ reports.push(await scoreCorpus(`${name}+now`, engine, withCue([...questions])));
+ } finally {
+ await engine.disconnect();
+ }
+ }
+ const lme = new URL('../../test/fixtures/longmemeval-nightly.jsonl', import.meta.url).pathname;
+ reports.push(await longMemEval(lme, false), await longMemEval(lme, true));
+ const asWritten = reports.filter(r => !r.corpus.endsWith('+now'));
+ const out = { mode: 'hermetic', keyword_only: true, pass: asWritten.every(r => r.recall10_lower.length === 0), reports };
+ const dumpPath = flag('--dump-off');
+ if (dumpPath) writeFileSync(dumpPath, JSON.stringify(dump, null, 2));
+ console.log(args.includes('--json') ? JSON.stringify(out, null, 2) : JSON.stringify(out));
+}
diff --git a/evals/pinned-questions/appended-gate.ts b/evals/pinned-questions/appended-gate.ts
index 1f8c943428..2fd9d873c5 100644
--- a/evals/pinned-questions/appended-gate.ts
+++ b/evals/pinned-questions/appended-gate.ts
@@ -45,7 +45,7 @@ import { listPins } from '../../src/core/questions/store.ts';
import { CITIES, SpendGuard, correctFor, offlineArms, paidArms, priced, readerAnswer, staleFor, tokens, type GateOpts } from './benefit-gate.ts';
export const RATIOS = [1, 10, 100] as const;
-const BATCHES = 12;
+export const BATCHES = 12;
const DAY = 86_400_000;
type EventKind = 'create' | 'note' | 'conflict_a' | 'conflict_b' | 'remember' | 'forget' | 'make_private';
@@ -101,7 +101,7 @@ export function appendedHash(w: AppendedWorkload): string {
return createHash('sha256').update(JSON.stringify(w)).digest('hex').slice(0, 16);
}
-const question = (name: string) => `Which city does ${name} build widgets in now?`;
+export const question = (name: string) => `Which city does ${name} build widgets in now?`;
const noteSlug = (entity: string, b: number, suffix = '') => `notes/${entity.split('/')[1]}-update-${b}${suffix}`;
const noteBody = (name: string, b: number, text: string, date: string, extra = '') =>
`---\ntype: note\ntitle: ${name} update ${b}\ndate: ${date}\n${extra}---\n${text}\n`;
@@ -183,7 +183,7 @@ export interface AppendedOpts {
arms: Pick<GateOpts, 'questionChat' | 'reader' | 'think'>;
}
-const fit = (parts: string[], budget: number) => {
+export const fit = (parts: string[], budget: number) => {
let context = '';
for (const part of parts) {
const next = `${context}\n${part}`;
diff --git a/src/core/config.ts b/src/core/config.ts
index 86effa2970..0af2efaee2 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1380,6 +1380,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.return_budget_conversation',
'search.return_budget_max_remote',
'search.evidence_date_header', // C1: one-line date header per delivered block (default off; search/evidence-date.ts)
+ 'search.entity_anchoring', // entity-anchored retrieval for entity-scoped current-state query/search (default off; search/entity-anchor.ts)
'think.return_unit',
// Models tier system (v0.31.12)
'models.default',
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 33b1a75108..e883a3c967 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -11,6 +11,7 @@ import { readHolders } from './context.ts';
*/
import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';
+import { applyEntityAnchoring, entityAnchoringEnabled } from '../search/entity-anchor.ts';
import { resolveSearchDateBounds } from '../search/date-bounds.ts';
import { loadSearchModeConfig, resolveSearchMode, SOURCE_BOOSTS_KEY } from '../search/mode.ts';
import { looksConceptShaped, classifyQueryShape } from '../search/query-intent.ts';
@@ -638,8 +639,11 @@ const search: Operation = {
};
const primary = await hybridSearchCached(ctx.engine, queryText, { ...searchOpts, onMeta: (m) => { capturedMeta = m; } });
const declarations = new DeclarationMemo();
- const results = (await withDeclaredNameFanOut(primary, queryText, declarations,
+ let results = (await withDeclaredNameFanOut(primary, queryText, declarations,
(alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 }))).map(r => ({ ...r }));
+ if (offset === 0 && !types && await entityAnchoringEnabled(ctx.engine)) {
+ results = (await applyEntityAnchoring(ctx.engine, queryText, results, { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false })).results;
+ }
stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
@@ -885,6 +889,12 @@ const query: Operation = {
limit: altLimit, excludePrivate, requireSafeChunks: ctx.remote !== false, takesHoldersAllowList: readHolders(ctx),
expansion: false, types, ...querySourceScope,
}));
+ if (!p.offset && !types && !p.since && !p.until && !p.lang && !p.symbol_kind && !p.near_symbol && await entityAnchoringEnabled(ctx.engine)) {
+ results = (await applyEntityAnchoring(ctx.engine, queryText, results, {
+ ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false,
+ tokenBudget: !plan && typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,
+ })).results;
+ }
// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;
// reads the stamped honesty signals: evidence, exact_lookup, rerank
// score), attach grade + query shape to the retrieval meta on EVERY call,
diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.ts
index cbff9baf20..d1493c5e1c 100644
--- a/src/core/questions/refresh.ts
+++ b/src/core/questions/refresh.ts
@@ -27,6 +27,7 @@ import { canonicalLookup } from '../model-pricing.ts';
import { chat as gatewayChat, probeChatModel } from '../ai/gateway.ts';
import { classifyLlmCallFailure } from '../think/index.ts';
import { PINNED_QUESTION_MARKER, normalizeQuestion, sentenceId } from './identity.ts';
+import { entityAnchoredPages, prefixAnchoredPages } from '../search/entity-anchor.ts';
import { FACT_HASH_SQL, TAKE_HASH_SQL, TIMELINE_HASH_SQL, evaluateAnswer, type EvidenceKind } from './freshness.ts';
import { ownerClaims, readQuestionPage } from './pages.ts';
import { acquireLease, getPin, pinId, releaseLease, type AnswerSentence, type PinRow } from './store.ts';
@@ -67,7 +68,6 @@ export type RefreshOutcome =
export const EST_INPUT_TOKENS = 8_000;
export const MAX_OUTPUT_TOKENS = 2_000;
const MAX_PAGES = 16;
-const MAX_ANCHORED = 10;
const MAX_FACTS = 30;
const MAX_TIMELINE = 20;
const MAX_TAKES = 20;
@@ -144,37 +144,17 @@ function launderingIndex(rows: PublishedAnswer[]): Array<{ text: string; at: num
interface CandidatePage { id: number; slug: string; source_id: string; generation: string | number; revision: string | null; type: string; compiled_truth: string; marker: boolean; updated_at: Date | string }
-const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-
/**
- * Pages anchored to the pin's scope, newest first: for an entity, its own page
- * and every page that links to it or names it as a word; for a slug prefix,
- * the newest pages under it. Keyword retrieval alone ranks every page that
- * shares the question's words alike, so the newest note about the entity can
- * fall outside the window once notes accumulate.
+ * Pages anchored to the pin's scope, newest first (search/entity-anchor.ts):
+ * for an entity, its own page and every page that links to it or names it as
+ * a word; for a slug prefix, the newest pages under it. Keyword retrieval
+ * alone ranks every page that shares the question's words alike, so the
+ * newest note about the entity can fall outside the window once notes
+ * accumulate.
*/
async function anchoredSlugs(engine: BrainEngine, pin: PinRow): Promise<string[]> {
- if (pin.scope_entity) {
- const [entity] = await engine.executeRaw<{ id: number; title: string | null }>(
- 'SELECT id, title FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [pin.source_id, pin.scope_entity]);
- const names = [...new Set([pin.scope_entity.split('/').pop()!, ...(entity?.title ? [entity.title] : [])].filter(n => n.length >= 3))];
- const pattern = `\\m(${names.map(escapeRegex).join('|')})\\M`;
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT p.slug FROM pages p WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug <> $2
- AND p.type NOT IN ('question', 'synthesis') AND NOT (p.frontmatter ? '${PINNED_QUESTION_MARKER}')
- AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer)))
- ORDER BY COALESCE(p.effective_date, p.updated_at) DESC, p.id DESC LIMIT ${MAX_ANCHORED}`,
- [pin.source_id, pin.scope_entity, pattern, entity?.id ?? null]);
- return [pin.scope_entity, ...rows.map(r => r.slug)];
- }
- if (pin.scope_slug_prefix) {
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE $2
- AND type NOT IN ('question', 'synthesis') AND NOT (frontmatter ? '${PINNED_QUESTION_MARKER}')
- ORDER BY COALESCE(effective_date, updated_at) DESC, id DESC LIMIT ${MAX_ANCHORED}`,
- [pin.source_id, `${pin.scope_slug_prefix.replace(/[\\%_]/g, '\\$&')}%`]);
- return rows.map(r => r.slug);
- }
+ if (pin.scope_entity) return [pin.scope_entity, ...(await entityAnchoredPages(engine, pin.source_id, pin.scope_entity)).pages.map(p => p.slug)];
+ if (pin.scope_slug_prefix) return (await prefixAnchoredPages(engine, pin.source_id, pin.scope_slug_prefix)).map(p => p.slug);
return [];
}
diff --git a/src/core/search/entity-anchor.ts b/src/core/search/entity-anchor.ts
new file mode 100644
index 0000000000..045bbe9be3
--- /dev/null
+++ b/src/core/search/entity-anchor.ts
@@ -0,0 +1,156 @@
+/**
+ * Entity-anchored retrieval. Keyword and vector ranking treat every note that
+ * shares a question's words alike, so once notes about an entity accumulate
+ * the newest one can fall outside the window. Anchoring reads pages by their
+ * relation to one entity instead: the entity page first, then pages that
+ * link to it or name it as a word, newest first.
+ *
+ * Shared by pinned-question refresh (`retrieveEvidence`, owner reads) and the
+ * `query` / `search` ops (`applyEntityAnchoring`, behind
+ * `search.entity_anchoring`, default off). Detection is deterministic: a
+ * current-state cue in the query and exactly one entity page whose title the
+ * query mentions. No model call.
+ *
+ * Read safety: candidate selection reads page ids only; every row this module
+ * returns to a search caller comes from `getChunkWindows`, which re-authorizes
+ * each page under the caller's read scope (source, deleted, projection,
+ * archived source, quarantine, private pages, safe chunks). A page that fails
+ * is absent.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PageReadScope, SearchResult } from '../types.ts';
+import { PINNED_QUESTION_MARKER } from '../questions/identity.ts';
+import { isFactEntityPage } from '../entities/resolve.ts';
+import { pageReadFilter } from './read-policy-sql.ts';
+import { containsTokenRun, isTitleMentionedInQuery, tokenizeTitle } from './title-match.ts';
+import { enforceTokenBudget } from './token-budget.ts';
+
+export const ENTITY_ANCHORING_KEY = 'search.entity_anchoring';
+/** Anchored pages read per entity (the entity page is extra). */
+export const MAX_ANCHORED = 10;
+
+export interface AnchoredPage { id: number; slug: string }
+
+const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+/** The entity page (when live) and up to `limit` pages that link to it or name it, newest first. */
+export async function entityAnchoredPages(engine: BrainEngine, sourceId: string, entitySlug: string, limit = MAX_ANCHORED): Promise<{ entity: AnchoredPage | null; pages: AnchoredPage[] }> {
+ const [entity] = await engine.executeRaw<{ id: number; title: string | null }>(
+ 'SELECT id, title FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, entitySlug]);
+ const names = [...new Set([entitySlug.split('/').pop()!, ...(entity?.title ? [entity.title] : [])].filter(n => n.length >= 3))];
+ const pattern = `\\m(${names.map(escapeRegex).join('|')})\\M`;
+ const rows = await engine.executeRaw<{ id: number; slug: string }>(
+ `SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug <> $2
+ AND p.type NOT IN ('question', 'synthesis') AND NOT (p.frontmatter ? '${PINNED_QUESTION_MARKER}')
+ AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer)))
+ ORDER BY COALESCE(p.effective_date, p.updated_at) DESC, p.id DESC LIMIT ${limit}`,
+ [sourceId, entitySlug, pattern, entity?.id ?? null]);
+ return { entity: entity ? { id: Number(entity.id), slug: entitySlug } : null, pages: rows.map(r => ({ id: Number(r.id), slug: r.slug })) };
+}
+
+/** The newest pages under a slug prefix (question and synthesis pages excluded). */
+export async function prefixAnchoredPages(engine: BrainEngine, sourceId: string, prefix: string, limit = MAX_ANCHORED): Promise<AnchoredPage[]> {
+ const rows = await engine.executeRaw<{ id: number; slug: string }>(
+ `SELECT id, slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE $2
+ AND type NOT IN ('question', 'synthesis') AND NOT (frontmatter ? '${PINNED_QUESTION_MARKER}')
+ ORDER BY COALESCE(effective_date, updated_at) DESC, id DESC LIMIT ${limit}`,
+ [sourceId, `${prefix.replace(/[\\%_]/g, '\\$&')}%`]);
+ return rows.map(r => ({ id: Number(r.id), slug: r.slug }));
+}
+
+/** Asks for the present state of something: "now", "currently", "latest", "these days" and similar. */
+const CURRENT_STATE_CUE = /\b(now|nowadays|currently|current|latest|most recent(ly)?|newest|today|these days|at the moment|at present|presently|still|anymore|any more|as of (today|now))\b/i;
+
+export function asksForCurrentState(query: string): boolean {
+ return CURRENT_STATE_CUE.test(query);
+}
+
+interface EntityCandidate { id: number; slug: string; title: string; type: string | null; source_id: string }
+
+/**
+ * The one entity page (person, company, organization, project, deal,
+ * concept...) whose title the query mentions as a token run, readable under
+ * `scope`. A title contained in a longer matched title is the same mention
+ * ("Acme" inside "Acme Labs"). Zero or several entities: null.
+ */
+export async function namedEntity(engine: BrainEngine, query: string, scope: PageReadScope): Promise<EntityCandidate | null> {
+ const params: unknown[] = [query.toLowerCase()];
+ const filter = pageReadFilter('p', scope, params, true);
+ const rows = await engine.executeRaw<EntityCandidate>(
+ `SELECT p.id, p.slug, p.title, p.type, p.source_id FROM pages p
+ WHERE ${filter} AND p.title IS NOT NULL AND length(p.title) >= 3 AND strpos($1, lower(p.title)) > 0
+ ORDER BY p.source_id, p.slug LIMIT 50`, params);
+ const matches = rows.filter(r => isFactEntityPage(r.slug, r.type) && isTitleMentionedInQuery(query, r.title));
+ const outer = matches.filter(m => !matches.some(o => o !== m && o.title.length > m.title.length && containsTokenRun(tokenizeTitle(o.title), tokenizeTitle(m.title))));
+ return outer.length === 1 ? { ...outer[0]!, id: Number(outer[0]!.id) } : null;
+}
+
+export interface EntityAnchorOpts extends PageReadScope {
+ /** Search token budget the caller asked for; the anchored set is re-packed to it. */
+ tokenBudget?: number;
+}
+
+export interface EntityAnchorResult { results: SearchResult[]; entity: string | null; anchored: number }
+
+/**
+ * Entity-anchored ordering for an entity-scoped current-state query: the
+ * entity page, then pages that link to it or name it, newest first, ahead of
+ * the organic rows. A page already in the organic set keeps its row (moved
+ * up, other chunks of it dropped); a missing page is read through
+ * `getChunkWindows` under the caller's scope. Anchored rows take at most half
+ * of the row count, the row count never grows, and the token budget is
+ * re-applied. Not entity-scoped, nothing readable, or any error: the organic
+ * results unchanged.
+ */
+export async function applyEntityAnchoring(engine: BrainEngine, query: string, results: SearchResult[], opts: EntityAnchorOpts): Promise<EntityAnchorResult> {
+ const unchanged = { results, entity: null, anchored: 0 };
+ if (!asksForCurrentState(query)) return unchanged;
+ try {
+ const entity = await namedEntity(engine, query, opts);
+ if (!entity) return unchanged;
+ const { pages } = await entityAnchoredPages(engine, entity.source_id, entity.slug);
+ const rowCount = results.length > 0 ? results.length : MAX_ANCHORED;
+ const slots = Math.max(1, Math.ceil(rowCount / 2));
+ const ordered = [{ id: entity.id, slug: entity.slug }, ...pages];
+ const windows = await engine.getChunkWindows(
+ ordered.map((p, i) => ({ page_id: p.id, from_index: 0, to_index: 0, priority: i })),
+ { sourceId: entity.source_id, excludePrivate: opts.excludePrivate, requireSafeChunks: opts.requireSafeChunks, chunkSources: ['compiled_truth'], maxRows: ordered.length });
+ const byId = new Map(windows.map(w => [w.page_id, w]));
+ const titles = new Map((await engine.executeRaw<{ id: number; title: string }>(
+ 'SELECT id, title FROM pages WHERE id = ANY($1::int[])', [ordered.map(p => p.id)])).map(r => [Number(r.id), r.title]));
+ const anchored: SearchResult[] = [];
+ for (const p of ordered) {
+ if (anchored.length >= slots) break;
+ const organic = results.find(r => r.page_id === p.id);
+ const window = byId.get(p.id);
+ if (!window) continue;
+ if (organic) { anchored.push({ ...organic, entity_anchored: p.id === entity.id ? 'entity' : 'linked' }); continue; }
+ const chunk = window.chunks[0];
+ if (!chunk) continue;
+ anchored.push({
+ page_id: p.id, slug: window.slug, title: titles.get(p.id) ?? window.slug, type: window.type as SearchResult['type'], source_id: window.source_id,
+ chunk_text: chunk.chunk_text, chunk_index: chunk.chunk_index, chunk_id: chunk.id, chunk_source: chunk.chunk_source as SearchResult['chunk_source'],
+ score: 0, stale: false, entity_anchored: p.id === entity.id ? 'entity' : 'linked',
+ } as SearchResult);
+ }
+ if (anchored.length === 0) return unchanged;
+ const anchoredIds = new Set(anchored.map(r => r.page_id));
+ const top = results.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), 0) || 1;
+ anchored.forEach((r, i) => { r.score = top + (anchored.length - i) * 1e-6; r.base_score ??= r.score; });
+ const merged = [...anchored, ...results.filter(r => !anchoredIds.has(r.page_id))].slice(0, rowCount);
+ const budgeted = opts.tokenBudget ? enforceTokenBudget(merged, opts.tokenBudget).results : merged;
+ return { results: budgeted, entity: `${entity.source_id}:${entity.slug}`, anchored: budgeted.filter(r => r.entity_anchored).length };
+ } catch {
+ return unchanged;
+ }
+}
+
+/** `search.entity_anchoring` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
+export async function entityAnchoringEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ const raw = (await engine.getConfig(ENTITY_ANCHORING_KEY))?.trim().toLowerCase();
+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index 6d6a32b113..d213baa34f 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1049,6 +1049,12 @@ export interface SearchResult {
* title_match_boost so the frozen EVIDENCE_ENUM is untouched.
*/
exact_lookup?: 'slug' | 'title';
+ /**
+ * Set when `search.entity_anchoring` moved or added this row for an
+ * entity-scoped current-state query (search/entity-anchor.ts): the named
+ * entity's page, or a page that links to it or names it (newest first).
+ */
+ entity_anchored?: 'entity' | 'linked';
/**
* T4 — the strongest signal that surfaced this page (alias_hit >
* exact_title_match > high_vector_match > keyword_exact > weak_semantic).
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index 2a36753941..2c15bf671d 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -41,6 +41,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.return_budget_conversation',
'search.return_budget_max_remote',
'search.evidence_date_header', // search/evidence-delivery.ts (C1)
+ 'search.entity_anchoring', // search/entity-anchor.ts (ops/search.ts)
];
describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {
diff --git a/test/search-entity-anchor.test.ts b/test/search-entity-anchor.test.ts
new file mode 100644
index 0000000000..20bb8b131f
--- /dev/null
+++ b/test/search-entity-anchor.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Entity-anchored retrieval (search/entity-anchor.ts, `search.entity_anchoring`):
+ * deterministic detection (current-state cue + exactly one named entity),
+ * anchored order (entity page, then linking/naming pages newest first), the
+ * row-count and token-budget contract, read safety for remote callers, and
+ * the off path. PGLite, keyword-only, no network.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { handleToolCall } from '../src/mcp/server.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { applyEntityAnchoring, asksForCurrentState, entityAnchoringEnabled, namedEntity, ENTITY_ANCHORING_KEY } from '../src/core/search/entity-anchor.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { localCtx, newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';
+
+let engine: PGLiteEngine;
+let sourceId: string;
+const Q = 'Which city does acme-example build widgets in now?';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ sourceId = await newSource(engine);
+ await putPage(engine, sourceId, 'companies/acme-example', page('company', 'acme-example', 'acme-example builds widgets in Lisbon.'));
+ await putPage(engine, sourceId, 'companies/beta-example', page('company', 'beta-example', 'beta-example builds widgets in Porto.'));
+ await putPage(engine, sourceId, 'companies/acme-example-labs', page('company', 'acme-example labs', 'acme-example labs builds gadgets.', 'date: 2026-01-01\n'));
+ for (let i = 1; i <= 8; i++) {
+ const day = String(i).padStart(2, '0');
+ await putPage(engine, sourceId, `notes/acme-update-${i}`, page('note', `update ${i}`, `As of 2026-03-${day}, acme-example builds widgets in City${i}. Widgets and cities and widgets.`, `date: 2026-03-${day}\n`));
+ }
+ await putPage(engine, sourceId, 'notes/acme-update-9', page('note', 'update 9', 'As of 2026-03-20, acme-example builds widgets in Secretville.', 'date: 2026-03-20\nvisibility: private\n'));
+ for (let i = 1; i <= 12; i++) await putPage(engine, sourceId, `notes/widget-chatter-${i}`, page('note', `chatter ${i}`, `Which city builds widgets now? Widgets widgets widgets city ${i}.`));
+}, 120_000);
+
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+const query = async (params: Record<string, unknown>) => await handleToolCall(engine, 'query', { query: Q, expand: false, use_cache: false, source_id: sourceId, ...params }) as SearchResult[];
+
+describe('detection', () => {
+ test('current-state cues', () => {
+ for (const q of ['Where is acme-example based now?', 'What is the latest on acme-example?', 'Who currently leads acme-example?', 'Is acme-example still in Lisbon?']) expect(asksForCurrentState(q)).toBe(true);
+ for (const q of ['Where was acme-example founded?', 'acme-example widgets', 'Nowhere near acme-example']) expect(asksForCurrentState(q)).toBe(false);
+ });
+
+ test('exactly one named entity page; a title inside a longer matched title is the same mention', async () => {
+ expect((await namedEntity(engine, Q, { sourceId }))?.slug).toBe('companies/acme-example');
+ expect((await namedEntity(engine, 'What does acme-example labs build now?', { sourceId }))?.slug).toBe('companies/acme-example-labs');
+ expect(await namedEntity(engine, 'Do acme-example and beta-example build widgets now?', { sourceId })).toBeNull();
+ expect(await namedEntity(engine, 'Which city builds widgets now?', { sourceId })).toBeNull();
+ });
+});
+
+describe('query with search.entity_anchoring', () => {
+ test('off (unset or false): no row is anchored and the rows are the same', async () => {
+ expect(await entityAnchoringEnabled(engine)).toBe(false);
+ const unset = await query({ limit: 8 });
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ const off = await query({ limit: 8 });
+ expect(JSON.stringify(off)).toBe(JSON.stringify(unset));
+ expect(unset.some(r => r.entity_anchored)).toBe(false);
+ });
+
+ test('on: the entity page, then the newest naming pages, within the same row count', async () => {
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ const off = await query({ limit: 8 });
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'true');
+ const on = await query({ limit: 8 });
+ expect(on).toHaveLength(off.length);
+ expect(on.slice(0, 4).map(r => [r.slug, r.entity_anchored])).toEqual([
+ ['companies/acme-example', 'entity'], ['notes/acme-update-9', 'linked'], ['notes/acme-update-8', 'linked'], ['notes/acme-update-7', 'linked']]);
+ expect(on.filter(r => r.entity_anchored)).toHaveLength(Math.ceil(off.length / 2));
+ expect(new Set(on.map(r => r.page_id)).size).toBe(on.length);
+ for (let i = 1; i < on.length; i++) expect(on[i]!.score).toBeLessThanOrEqual(on[i - 1]!.score);
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ });
+
+ test('on: the token budget still holds', async () => {
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'true');
+ const on = await query({ limit: 8, token_budget: 60 });
+ const used = on.reduce((n, r) => n + Math.ceil(((r.title ?? '').length + r.chunk_text.length) / 4), 0);
+ expect(on.length).toBeGreaterThan(0);
+ expect(used).toBeLessThanOrEqual(80);
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ });
+
+ test('on: skipped with offset or a type filter', async () => {
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'true');
+ expect((await query({ limit: 4, offset: 2 })).some(r => r.entity_anchored)).toBe(false);
+ expect((await query({ limit: 4, types: ['note'] })).some(r => r.entity_anchored)).toBe(false);
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ });
+
+ test('on, remote caller: a private page is never anchored in; search shares the path', async () => {
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'true');
+ const auth = { token: 't', clientId: 'anchor-probe', scopes: ['read'], sourceId, allowedSources: [sourceId] };
+ for (const tool of ['query', 'search']) {
+ const r = await dispatchToolCall(engine, tool, { query: Q, limit: 8, expand: false }, { remote: true, transport: 'stdio', sourceId, auth, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } });
+ const text = r.content.map(c => (c as { text?: string }).text ?? '').join('\n');
+ expect(text).not.toContain('Secretville');
+ expect(text).not.toContain('acme-update-9');
+ expect(text).toContain('acme-update-8');
+ }
+ await engine.setConfig(ENTITY_ANCHORING_KEY, 'false');
+ });
+
+ test('a query that names no entity or asks no current state is unchanged', async () => {
+ const organic = await query({ limit: 6 });
+ const ctx = localCtx(engine, sourceId);
+ for (const q of ['Which city builds widgets now?', 'Where was acme-example founded?']) {
+ const out = await applyEntityAnchoring(ctx.engine, q, organic, { sourceId });
+ expect(out.results).toBe(organic);
+ expect(out.anchored).toBe(0);
+ }
+ });
+});