Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search: chain evidence survives fusion, guarantees and delivery

garrytanab4ddbfa574c
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index d95c8fff62..ed7f07f2b0 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -561,6 +561,7 @@ const recall: Operation = {
create_safety: r.create_safety,
provenance: r.slug,
...(r.delivered ? { delivered: r.delivered } : {}),
+ ...(r.relational ? { relational: r.relational } : {}),
})),
...(searchDegraded ? { search_degraded: searchDegraded } : {}),
}
diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.ts
index 1b76378d71..b0a35cae25 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -156,7 +156,16 @@ export async function searchVectorFallback(
stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
// System One S3 evidence gate (no-op when the slot is off), at the fused path's position.
const kwGated = await applyEvidenceGate(req.decide, query, kwHopped);
- const kwSliced = kwGated.slice(offset, offset + limit);
+ // #3995 — the same guaranteed page-1 relational evidence as the other two
+ // return paths: a vector failure must not drop a fired arm's answer.
+ let kwPool = kwGated;
+ let kwRelSlot: RelationalEvidenceSlotDecision | undefined;
+ if (relationalList.length > 0) {
+ const r = ensureRelationalEvidenceSlot(kwGated, relationalList, limit, offset, { cosineFloor: resolvedMode.evidence_cosine_floor });
+ kwPool = r.pool;
+ kwRelSlot = r.decision;
+ }
+ const kwSliced = kwPool.slice(offset, offset + limit);
// v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.
const { results: kwBudgeted, meta: kwBudgetMeta } = enforceTokenBudget(kwSliced, resolvedMode.tokenBudget);
await stampContentFlags(engine, kwBudgeted, opts);
@@ -181,6 +190,7 @@ export async function searchVectorFallback(
...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0
? { token_budget: kwBudgetMeta }
: {}),
+ ...(kwRelSlot ? { relational_evidence_slot: kwRelSlot } : {}),
});
return kwBudgeted;
}
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
index d51730538c..61d4b13b86 100644
--- a/src/core/search/lean-rows.ts
+++ b/src/core/search/lean-rows.ts
@@ -27,7 +27,7 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set([
'id', 'slug', 'title', 'type', 'chunk_text', 'score', 'effective_date', 'source_id', 'chunk_id',
'evidence', 'create_safety',
'injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',
- 'message_id', 'thread_id', 'source_subject',
+ 'message_id', 'thread_id', 'source_subject', 'relational',
]);
/** Explicit `fields` wins; then trusted local callers get full rows; then the transport's choice (default lean). */
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 032f6c606f..4be84ed12b 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -208,6 +208,15 @@ async function hydrate(
return out;
}
+/**
+ * Rows that may claim a relational guarantee (pin, page-1 slot): one-hop rows
+ * and chain answers. A chain's intermediate or origin page is evidence, not an
+ * answer, so it never satisfies a guarantee meant for the answer.
+ */
+export function answerRows(list: readonly SearchResult[]): SearchResult[] {
+ return list.filter(r => r.relational === undefined || r.relational.role === 'answer');
+}
+
/**
* #3995 — decision stamp for the guaranteed page-1 relational evidence slot.
* Surfaced through HybridSearchMeta.relational_evidence_slot so `--explain`
@@ -249,6 +258,7 @@ export function ensureRelationalEvidenceSlot(
offset: number,
evidenceOpts?: EvidenceOpts,
): { pool: SearchResult[]; decision?: RelationalEvidenceSlotDecision } {
+ relationalList = answerRows(relationalList);
if (offset > 0 || limit <= 0 || relationalList.length === 0) return { pool };
const pageKey = (r: SearchResult) => `${r.source_id ?? 'default'}:${r.slug}`;
const relKeys = new Set(relationalList.map(pageKey));
diff --git a/src/core/search/relational-rerank-pin.ts b/src/core/search/relational-rerank-pin.ts
index a75dff6c43..207fb319b2 100644
--- a/src/core/search/relational-rerank-pin.ts
+++ b/src/core/search/relational-rerank-pin.ts
@@ -147,6 +147,8 @@ export function pinRelationalRows(
opts: PinRelationalRowsOpts,
): SearchResult[] {
const max = Number.isFinite(opts.max) ? Math.floor(opts.max) : 0;
+ // Chain intermediates/origins are evidence, not answers: they never claim a pin.
+ relationalList = relationalList.filter(r => r.relational === undefined || r.relational.role === 'answer');
if (max <= 0 || reranked.length === 0 || relationalList.length === 0) return reranked;
const relKeys = new Set(relationalList.map(pageKey));
diff --git a/src/core/search/rrf-page-fusion.ts b/src/core/search/rrf-page-fusion.ts
index b25cd2625e..ba701e6b49 100644
--- a/src/core/search/rrf-page-fusion.ts
+++ b/src/core/search/rrf-page-fusion.ts
@@ -48,6 +48,10 @@ export type RrfEntry = { result: SearchResult; score: number; own: number; keywo
export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: number; weight?: number }>): RrfEntry[] {
const chunks = new Map<string, RrfEntry>();
const pages = new Map<string, number>();
+ // Graph evidence is page-level: the relational arm may surface a page's
+ // canonical chunk while keyword/vector pick another chunk of the same page,
+ // so the evidence rides on whichever of the page's rows survives.
+ const graphEvidence = new Map<string, Partial<SearchResult>>();
for (const { list, k, weight } of lists) {
const w = weight ?? 1;
const votedPages = new Set<string>();
@@ -59,6 +63,9 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
votedPages.add(page);
pages.set(page, (pages.get(page) ?? 0) + rrfScore);
}
+ if (!graphEvidence.has(page) && (r.relational !== undefined || r.relational_seed !== undefined)) {
+ graphEvidence.set(page, pickGraphEvidence(r));
+ }
const key = rrfKey(r);
const existing = chunks.get(key);
if (existing) {
@@ -79,6 +86,12 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
}
}
const entries = Array.from(chunks.values());
+ for (const e of entries) {
+ const evidence = graphEvidence.get(rrfPageKey(e.result));
+ if (evidence && e.result.relational === undefined && e.result.relational_seed === undefined) {
+ e.result = { ...e.result, ...evidence };
+ }
+ }
const leads = new Map<string, RrfEntry>();
for (const e of entries) {
e.score = e.own;
@@ -89,3 +102,11 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
for (const [page, lead] of leads) lead.score = pages.get(page) ?? lead.own;
return entries;
}
+
+const GRAPH_EVIDENCE_FIELDS = ['relational', 'relational_seed', 'relational_hop', 'relational_path', 'relational_via_link_types'] as const;
+
+function pickGraphEvidence(r: SearchResult): Partial<SearchResult> {
+ const out: Record<string, unknown> = {};
+ for (const f of GRAPH_EVIDENCE_FIELDS) if (r[f] !== undefined) out[f] = r[f];
+ return out as Partial<SearchResult>;
+}
diff --git a/src/core/search/token-budget.ts b/src/core/search/token-budget.ts
index 2e771222ab..5df1de6dfc 100644
--- a/src/core/search/token-budget.ts
+++ b/src/core/search/token-budget.ts
@@ -67,14 +67,18 @@ function sliceToTokens(text: string, maxTokens: number): string {
}
/**
- * Per-result token cost: title + chunk_text. Slug is metadata and
+ * Per-result token cost: title + chunk_text + chain evidence edges (which
+ * do enter the assistant context). Slug is metadata and
* doesn't enter the assistant context, so we don't count it. If a
* caller wants a different cost model (e.g. including timeline detail
* or compiled_truth length), they can pre-shape the chunk_text before
* calling enforceTokenBudget.
*/
export function resultTokens(r: SearchResult): number {
- return estimateTokens(r.title) + estimateTokens(r.chunk_text);
+ const graph = r.relational
+ ? r.relational.edges.reduce((n, e) => n + estimateTokens(`${e.stored_from} ${e.link_type} ${e.stored_to} ${e.context ?? ''}`), 0)
+ : 0;
+ return estimateTokens(r.title) + estimateTokens(r.chunk_text) + graph;
}
export interface TokenBudgetMeta {
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index e908726d51..ad66a26209 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -629,7 +629,7 @@ export function renderPagesBlock(
const title = String(page.title ?? '');
const slugIdentity = slug.split('/').pop()?.replace(/[-_]/g, ' ') ?? '';
const content = String(page.chunk_text ?? page.compiled_truth ?? page.snippet ?? '');
- const flag = p.injection_suspected ? `${INJECTION_SUSPECTED_LINE}\n` : '';
+ const flag = (p.injection_suspected ? `${INJECTION_SUSPECTED_LINE}\n` : '') + graphEvidenceLine(p);
// Evidence delivery: the block was already budgeted and cut around its
// hits; render it whole (capped only by excerptLen).
if (typeof opts.verbatim === 'function' ? opts.verbatim(p) : opts.verbatim) {
@@ -649,6 +649,14 @@ export function renderPagesBlock(
}).join('\n\n');
}
+/** One line naming the typed links that put a chain row in the context (slugs and link types only). */
+function graphEvidenceLine(p: SearchResult): string {
+ const edges = p.relational?.edges ?? [];
+ if (edges.length === 0) return '';
+ const clean = (v: string) => v.replace(/[\r\n<>]/g, ' ');
+ return `Graph evidence (${p.relational!.role}): ${edges.map(e => `${clean(e.stored_from)} -${clean(e.link_type)}-> ${clean(e.stored_to)}`).join('; ')}\n`;
+}
+
export function takesHitToTakeForPrompt(h: TakeHit | Take): {
page_slug: string; row_num: number; claim: string; kind: string;
holder: string; weight: number; source?: string | null; since_date?: string | null;
diff --git a/src/core/types.ts b/src/core/types.ts
index dafb5f8e78..0808ee26e4 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -918,6 +918,14 @@ export interface SearchResult {
relational_hop?: number;
/** Shortest connecting slug path seed→…→result (for "how I know this"). */
relational_path?: string[];
+ /**
+ * Multi-hop chain evidence: why a chain put this page here. `role` is the
+ * page's place on the chain (a candidate answer, an intermediate page, or the
+ * page an edge was written on), not a correctness claim; `path_count` counts
+ * retained paths and is not corroboration. `edges` is the best path's
+ * evidence, at most three edges.
+ */
+ relational?: RelationalEvidence;
/**
* Ranker wave — set when `pinRelationalRows` (relational-rerank-pin.ts)
* re-pinned this relational-arm row above the reranked text rows. Autocut
@@ -1537,6 +1545,22 @@ export interface RelationalFanoutOpts extends PageReadPolicy {
limit?: number;
}
+/** Chain evidence carried on a search row (SearchResult.relational). */
+export interface RelationalEvidence {
+ role: 'answer' | 'support' | 'origin';
+ seed: string;
+ hop: number;
+ path_count: number;
+ edges: Array<{
+ link_type: string;
+ stored_from: string;
+ stored_to: string;
+ orientation: 'canonical' | 'stored' | 'flipped' | 'uncertain';
+ context: string | null;
+ origin: string | null;
+ }>;
+}
+
/**
* Options for BrainEngine.relationalChainHop: one bounded, oriented expansion
* step of a multi-hop relational chain. `subjectTypes`/`objectTypes` are the
diff --git a/test/search/relational-chain-delivery.test.ts b/test/search/relational-chain-delivery.test.ts
new file mode 100644
index 0000000000..444d2c71e0
--- /dev/null
+++ b/test/search/relational-chain-delivery.test.ts
@@ -0,0 +1,78 @@
+/**
+ * Chain evidence survives delivery (pure).
+ *
+ * Protects: graph evidence rides on whichever chunk of a page survives fusion
+ * (keyword may pick chunk 7 while the relational arm supplies chunk 1); arm
+ * rows are never mutated; a chain's intermediate or origin page never claims
+ * the relational pin or the page-1 slot meant for an answer; the token budget
+ * counts the evidence edges; remote lean rows keep the evidence field.
+ * Regression it catches: evidence dropped when another arm saw the page first,
+ * a support page satisfying the answer guarantee, evidence stripped from lean
+ * rows.
+ */
+import { describe, test, expect } from 'bun:test';
+import { accumulateRrf } from '../../src/core/search/rrf-page-fusion.ts';
+import { ensureRelationalEvidenceSlot } from '../../src/core/search/relational-recall.ts';
+import { pinRelationalRows } from '../../src/core/search/relational-rerank-pin.ts';
+import { resultTokens } from '../../src/core/search/token-budget.ts';
+import { leanRow } from '../../src/core/search/lean-rows.ts';
+import type { RelationalEvidence, SearchResult } from '../../src/core/types.ts';
+
+function row(slug: string, chunkId: number, extra: Partial<SearchResult> = {}): SearchResult {
+ return {
+ slug, page_id: 0, title: slug, type: 'person', chunk_text: `text of ${slug}`, chunk_source: 'compiled_truth',
+ chunk_id: chunkId, chunk_index: 0, score: 0.5, stale: false, source_id: 'default', ...extra,
+ };
+}
+
+const evidence = (role: RelationalEvidence['role']): RelationalEvidence => ({
+ role, seed: 'people/alice-example', hop: 2, path_count: 1,
+ edges: [{ link_type: 'founded', stored_from: 'companies/acme-example', stored_to: 'people/bob-example', orientation: 'flipped', context: 'founded by bob', origin: null }],
+});
+
+describe('fusion carries graph evidence at page level', () => {
+ test('a keyword row for another chunk of the page gains the chain evidence; arm rows stay untouched', () => {
+ const kw = row('people/bob-example', 7);
+ const chain = row('people/bob-example', 1, { relational: evidence('answer'), relational_seed: 'people/alice-example' });
+ const entries = accumulateRrf([{ list: [kw], k: 60 }, { list: [chain], k: 60 }]);
+ const kwEntry = entries.find(e => e.result.chunk_id === 7)!;
+ expect(kwEntry.result.relational?.role).toBe('answer');
+ expect(kwEntry.result.relational_seed).toBe('people/alice-example');
+ expect(kw.relational).toBeUndefined();
+ });
+
+ test('pages the chain never reached gain nothing', () => {
+ const entries = accumulateRrf([{ list: [row('people/carol-example', 3)], k: 60 }, { list: [row('people/bob-example', 1, { relational: evidence('answer') })], k: 60 }]);
+ expect(entries.find(e => e.result.slug === 'people/carol-example')!.result.relational).toBeUndefined();
+ });
+});
+
+describe('relational guarantees are for answers only', () => {
+ const support = row('companies/acme-example', 2, { relational: evidence('support') });
+ const answer = row('people/bob-example', 1, { relational: evidence('answer') });
+
+ test('a support page on page 1 does not satisfy the slot; the answer is injected', () => {
+ const pool = [row('a', 10), support, row('b', 11)];
+ const r = ensureRelationalEvidenceSlot(pool, [support, answer], 3, 0);
+ expect(r.decision).toMatchObject({ action: 'injected', slug: 'people/bob-example' });
+ });
+
+ test('the rerank pin never pins a support page', () => {
+ const reranked = [row('a', 10), row('b', 11), support, answer];
+ const out = pinRelationalRows(reranked, [support, answer], { max: 3 });
+ expect(out[0].slug).toBe('people/bob-example');
+ expect(out.find(r => r.slug === 'companies/acme-example')?.relational_pinned).toBeUndefined();
+ });
+});
+
+describe('budget and lean rows', () => {
+ test('token cost includes the evidence edges', () => {
+ const plain = row('people/bob-example', 1);
+ expect(resultTokens({ ...plain, relational: evidence('answer') })).toBeGreaterThan(resultTokens(plain));
+ });
+
+ test('lean rows keep the relational field', () => {
+ const lean = leanRow({ ...row('people/bob-example', 1), relational: evidence('answer') } as unknown as Record<string, unknown>);
+ expect(lean.relational).toBeDefined();
+ });
+});