Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): relational arm spans every source for unscoped callers (#5640)
garrytanaa1dd0c4405a
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 5c99feca76..dda81f610b 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -68,7 +68,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.-- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts` and `test/pack-relation-direction-engine.test.ts`.+- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal `__all__` resolves no seeds, fail-closed) → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts`, `test/relational-recall-scope-sources.test.ts` and `test/pack-relation-direction-engine.test.ts`.- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.tsindex 1ee8863de3..3ed2a317ec 100644--- a/src/core/search/relational-recall.ts+++ b/src/core/search/relational-recall.ts@@ -27,6 +27,8 @@import type { BrainEngine } from '../engine.ts';import type { SearchResult, PageType, RelationalFanoutRow, PageReadPolicy } from '../types.ts';import { createAuditWriter } from '../audit/audit-writer.ts';+import { listSources } from '../sources-ops.ts';+import { ALL_SOURCES } from '../source-id.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { buildVisibilityClause } from './sql-ranking.ts';import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';@@ -80,13 +82,25 @@ function truncate(msg: string, max = 200): string {return msg.length <= max ? msg : msg.slice(0, max - 1) + '…';}-/** Sources to resolve a seed against. Federated → the set; scalar → [id];- * unscoped/__all__ → ['default'] (single-source brains; multi-source- * enumeration under __all__ is a v1 limitation). */-function scopeSources(opts: RelationalArmOpts): string[] {+/** Sources to resolve a seed against. Federated → the set; scalar → [id].+ *+ * Unscoped (trusted local; the `query` op resolves `__all__` to unscoped for+ * local callers) → every non-archived source. The prior `['default']`+ * fallback made `--source-id __all__` a shipped-contract bug on multi-source+ * brains: the keyword and vector arms spanned every source while this arm+ * answered from `default` alone. Cost: one resolver chain per non-archived+ * source. Traversal is still WITHIN each seed's source (E2=A) — only seed+ * RESOLUTION widens here, never the walk.+ *+ * A literal `__all__` that reaches this arm comes from a caller whose scope+ * was NOT resolved by a trusted-local path, so it must stay fail-closed:+ * resolve no seeds (the arm no-ops) rather than widen to every source. */+async function scopeSources(engine: BrainEngine, opts: RelationalArmOpts): Promise<string[]> {if (opts.sourceIds && opts.sourceIds.length > 0) return opts.sourceIds;- if (opts.sourceId && opts.sourceId !== '__all__') return [opts.sourceId];- return ['default'];+ if (opts.sourceId === ALL_SOURCES) return [];+ if (opts.sourceId) return [opts.sourceId];+ const sources = await listSources(engine);+ return sources.map(s => s.id);}/** Page types a relation's seed may be besides an entity. The entity resolver@@ -303,7 +317,7 @@ export async function buildRelationalArm(meta.kind = parsed.kind;try {- const sources = scopeSources(opts);+ const sources = await scopeSources(engine, opts);const fanoutOpts = {sourceId: opts.sourceId,sourceIds: opts.sourceIds,diff --git a/test/relational-recall-scope-sources.test.ts b/test/relational-recall-scope-sources.test.tsnew file mode 100644index 0000000000..1c40fa30ff--- /dev/null+++ b/test/relational-recall-scope-sources.test.ts@@ -0,0 +1,111 @@+/**+ * Relational arm source scoping: unscoped spans every non-archived source.+ *+ * The `query` op's help text promises `__all__` spans every source for+ * trusted local callers, and the keyword + vector arms honor it. The+ * relational arm's `scopeSources` fell back to `['default']` for an unscoped+ * caller, so on a multi-source brain `gbrain query --source __all__ "who+ * invested in widget-co"` answered relationally from `default` alone — a+ * shipped-contract bug when the edge lives in another source.+ *+ * Pins (PGLite, same harness as test/relational-recall.test.ts):+ * - unscoped arm resolves the seed in a NON-default source and returns its+ * edge row (fails pre-fix: seed only resolved against `default`)+ * - unscoped resolution skips archived sources, matching the keyword and+ * vector arms' visibility clause+ * - a literal `sourceId: '__all__'` stays fail-closed → empty arm, even+ * when `default` holds a matching edge (trusted local `__all__` arrives+ * unscoped; the literal survives only for remote callers whose scope+ * resolution must not widen)+ * - a scalar sourceId still scopes to exactly that source (unchanged)+ *+ * Traversal remains WITHIN each seed's source (E2=A): only seed resolution+ * widens, never the walk.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { buildRelationalArm } from '../src/core/search/relational-recall.ts';+import type { ChunkInput } from '../src/core/types.ts';++let eng: PGLiteEngine;++beforeAll(async () => {+ eng = new PGLiteEngine();+ await eng.connect({});+ await eng.initSchema();+ for (const id of ['team', 'attic']) {+ await eng.executeRaw(+ 'INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING',+ [id],+ );+ }++ // The widget-co fixture lives in source `team`; `default` holds nothing+ // for it. The investor's body never names the company — only the edge+ // connects them.+ await eng.putPage('companies/widget-co', {+ type: 'company', title: 'Widget Co', compiled_truth: 'A payments company.', timeline: '',+ }, { sourceId: 'team' });+ await eng.putPage('people/alice-example', {+ type: 'person', title: 'Alice Example',+ compiled_truth: 'Alice is a seed-stage investor based in Lisbon.', timeline: '',+ }, { sourceId: 'team' });+ // Hydration only surfaces pages with an installed text projection (the+ // currentTextProjectionFilter arm of the shared visibility clause).+ await installFixtureChunks(eng, 'people/alice-example', [{+ chunk_index: 0, chunk_text: 'Alice is a seed-stage investor based in Lisbon.',+ chunk_source: 'compiled_truth', token_count: 8,+ }] satisfies ChunkInput[], { sourceId: 'team' });+ await eng.addLink('people/alice-example', 'companies/widget-co', '', 'invested_in', 'manual',+ undefined, undefined, { fromSourceId: 'team', toSourceId: 'team' });++ // gadget-co: one edge in `default` (the literal-__all__ probe) and one in+ // the archived source `attic` (must stay invisible to unscoped callers).+ for (const [sid, investor] of [['default', 'bob-example'], ['attic', 'carol-example']] as const) {+ await eng.putPage('companies/gadget-co', {+ type: 'company', title: 'Gadget Co', compiled_truth: 'A hardware company.', timeline: '',+ }, { sourceId: sid });+ const text = `${investor} is an angel investor.`;+ await eng.putPage(`people/${investor}`, {+ type: 'person', title: investor, compiled_truth: text, timeline: '',+ }, { sourceId: sid });+ await installFixtureChunks(eng, `people/${investor}`, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 6,+ }] satisfies ChunkInput[], { sourceId: sid });+ await eng.addLink(`people/${investor}`, 'companies/gadget-co', '', 'invested_in', 'manual',+ undefined, undefined, { fromSourceId: sid, toSourceId: sid });+ }+ await eng.executeRaw(`UPDATE sources SET archived = true WHERE id = 'attic'`);+}, 60_000);++afterAll(async () => { await eng.disconnect(); });++describe('scopeSources spans every source for an unscoped caller', () => {+ test('unscoped arm returns the edge row from a non-default source', async () => {+ const list = await buildRelationalArm(eng, 'who invested in widget-co');+ const alice = list.find(r => r.slug === 'people/alice-example');+ expect(alice).toBeDefined();+ expect(alice!.source_id).toBe('team');+ expect(alice!.relational_via_link_types).toEqual(['invested_in']);+ });++ test('unscoped resolution skips archived sources', async () => {+ const list = await buildRelationalArm(eng, 'who invested in gadget-co');+ expect(list.map(r => `${r.source_id}:${r.slug}`)).toEqual(['default:people/bob-example']);+ });++ test("a literal sourceId '__all__' stays fail-closed: empty arm", async () => {+ expect(await buildRelationalArm(eng, 'who invested in widget-co', { sourceId: '__all__' })).toEqual([]);+ expect(await buildRelationalArm(eng, 'who invested in gadget-co', { sourceId: '__all__' })).toEqual([]);+ });++ test('a scalar sourceId still scopes to exactly that source', async () => {+ const scoped = await buildRelationalArm(eng, 'who invested in widget-co', { sourceId: 'team' });+ expect(scoped.map(r => r.slug)).toContain('people/alice-example');++ const wrong = await buildRelationalArm(eng, 'who invested in widget-co', { sourceId: 'default' });+ expect(wrong).toEqual([]);+ });+});