Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): relational triplet scoring with wider fanout; feedback stage and triplet tests
garrytan106519899b73
diff --git a/src/core/search/crag.ts b/src/core/search/crag.tsindex 5553b076be..a3627d7fc1 100644--- a/src/core/search/crag.ts+++ b/src/core/search/crag.ts@@ -99,7 +99,7 @@ function words(text: string): string[] {return text.normalize('NFKC').split(/[^\p{L}\p{N}]+/u).filter(Boolean);}-function contentTerms(text: string): Set<string> {+export function contentTerms(text: string): Set<string> {const out = new Set<string>();for (const w of words(text)) {const lower = w.toLowerCase();diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 7a8602f190..a25b6cfbda 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -45,7 +45,7 @@ import {} from './query-cache.ts';import { resolveHybridRequest } from './hybrid/request.ts';import { prepareSemanticCache, resolveCacheSearchMode, semanticCacheSkipped, serveSemanticCacheHit } from './hybrid/cache-stages.ts';-import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms } from './hybrid/arms.ts';+import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms, scoreRelationalArm } from './hybrid/arms.ts';import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';import { expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';@@ -1105,12 +1105,14 @@ export async function hybridSearch(// vector-arm query embedding without the gateway, so provider// availability is irrelevant — skip the keyword-only short-circuit.if (opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && !isAvailable('embedding', providerProbe) && !willTryMultimodal)) {+ await scoreRelationalArm(req, relationalList, null);return searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe);}const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);const { vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } =await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe });+ await scoreRelationalArm(req, relationalList, vectorArms.length === 0 ? null : queryEmbedding);if (vectorArms.length === 0) {return searchVectorFallback(req, lexical, relationalList, postFusionOpts);}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex a52a61787e..846fe478fc 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -3,6 +3,7 @@* Each stage reads the resolved request (HybridRequest, request.ts) and* writes its per-request accumulators only as `req.<field>`.*/+import { applyTripletScoring, loadTripletSettings } from '../triplet-score.ts';import type { ModalityMode } from '../query-intent.ts';import type { ExactLookupOpts } from '../exact-lookup.ts';import type { HybridRequest } from './request.ts';@@ -170,11 +171,14 @@ export async function buildRelationalList(req: HybridRequest): Promise<SearchRes// path; the parser only matches text-shaped relational queries anyway.)let relationalList: SearchResult[] = [];if (resolvedMode.relationalRetrieval) {+ const keep = opts?.limit ?? resolvedMode.searchLimit;+ const triplet = await loadTripletSettings(engine);relationalList = await buildRelationalArm(engine, query, {sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,depth: resolvedMode.relational_retrieval_depth,- limit: opts?.limit ?? resolvedMode.searchLimit,+ limit: triplet.enabled ? Math.min(Math.max(keep * 4, 100), 400) : keep,+ wide: triplet.enabled,// #4352 remediation: the arm hydrates titles + compiled_truth snippets// straight from pages — thread the caller's private-page gate or a// remote relational query bypasses the keyword/vector visibility clause.@@ -183,10 +187,27 @@ export async function buildRelationalList(req: HybridRequest): Promise<SearchRestakesHoldersAllowList: opts?.takesHoldersAllowList,onMeta: opts?.onRelationalMeta,});+ if (triplet.enabled) tripletKeep.set(relationalList, { keep, penalty: triplet.penalty });}return relationalList;}+const tripletKeep = new WeakMap<SearchResult[], { keep: number; penalty: number }>();++/**+ * Triplet-score the relational arm in place (no-op unless+ * `search.triplet_scoring` widened it in buildRelationalList), then trim it+ * back to the caller's limit. Keyless paths pass a null query vector.+ */+export async function scoreRelationalArm(req: HybridRequest, list: SearchResult[], queryEmbedding: Float32Array | null): Promise<void> {+ const pending = tripletKeep.get(list);+ if (!pending) return;+ tripletKeep.delete(list);+ await applyTripletScoring(req.engine, req.query, list, {+ queryEmbedding, column: req.resolvedCol.name, keep: pending.keep, penalty: pending.penalty,+ });+}+/** Modality routing (with the opt-in LLM tie-break) and query expansion. */export async function resolveModalityAndQueries(req: HybridRequest) {const { query, opts, resolvedMode, suggestions, degraded } = req;diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsindex 1a5467bbec..cd759bf4dc 100644--- a/src/core/search/read-enrichment.ts+++ b/src/core/search/read-enrichment.ts@@ -18,7 +18,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], opif (!seeds?.length) return [];const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);const direction = opts?.direction ?? 'both';- const limit = Math.min(Math.max(1, opts?.limit ?? 50), 200);+ const limit = Math.min(Math.max(1, opts?.limit ?? 50), opts?.wide ? 400 : 200);const params: unknown[] = [seeds, depth, limit];const policy = hasReadPolicy(opts) ? opts : undefined;const seed = pageReadFilter('p', policy, params, !!policy);diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.tsindex ae03fe2043..9f1fd8ed57 100644--- a/src/core/search/relational-recall.ts+++ b/src/core/search/relational-recall.ts@@ -41,6 +41,8 @@ export interface RelationalArmOpts extends PageReadPolicy {sourceIds?: string[];depth?: number;limit?: number;+ /** Fetch up to 400 candidates for triplet scoring. */+ wide?: boolean;vocab?: RelationVocab;/*** #4352 remediation — hide `visibility: private` pages from the arm's@@ -329,6 +331,7 @@ export async function buildRelationalArm(direction: parsed.direction,depth: opts.depth,limit: opts.limit,+ wide: opts.wide,};if (parsed.kind === 'connects' && parsed.seeds.length === 2) {diff --git a/src/core/search/triplet-score.ts b/src/core/search/triplet-score.tsnew file mode 100644index 0000000000..795c950112--- /dev/null+++ b/src/core/search/triplet-score.ts@@ -0,0 +1,195 @@+/**+ * Triplet scoring for the relational (typed-edge) recall arm.+ *+ * Each edge on a candidate's representative path is a triplet (from page,+ * edge, to page). Its score sums three distances to the query, each in+ * [0, 2] and scaled by (2 − importance):+ * - page distance: 1 − cosine(query vector, the page's first chunk vector),+ * in the same embedding column the vector arm used; lexical fallback+ * (1 − content-term overlap with the title) without a query vector;+ * - edge distance: 1 − content-term overlap of the query with the+ * humanized link type plus the link's context sentence;+ * - a missing part (no chunk, no vector, no context) costs a fixed penalty.+ * Importance is the element's learned feedback weight mapped into+ * 0.5 ± λ (neutral 0.5 when feedback is off). A candidate's score is its+ * worst triplet, so one irrelevant hop is never hidden by a relevant one.+ * Lower is better; ties keep the fanout order. Fail-open.+ */+import type { BrainEngine } from '../engine.ts';+import type { SearchResult } from '../types.ts';+import { contentTerms } from './crag.ts';+import { effectiveInfluence, loadFeedbackSettings } from '../feedback/settings.ts';+import { NEUTRAL_WEIGHT, readWeights } from '../feedback/store.ts';++export const DEFAULT_TRIPLET_PENALTY = 3.0;++export interface TripletSettings {+ enabled: boolean;+ penalty: number;+}++const CACHE_TTL_MS = 30_000;+let cache: { ts: number; engine: BrainEngine; value: TripletSettings } | null = null;++export async function loadTripletSettings(engine: BrainEngine): Promise<TripletSettings> {+ const now = Date.now();+ if (cache && cache.engine === engine && now - cache.ts < CACHE_TTL_MS) return cache.value;+ const get = async (k: string) => { try { return await engine.getConfig(k); } catch { return null; } };+ const [on, penalty] = await Promise.all([get('search.triplet_scoring'), get('search.triplet_penalty')]);+ const p = Number(penalty);+ const value: TripletSettings = {+ enabled: ['true', '1', 'on', 'yes'].includes((on ?? '').trim().toLowerCase()),+ penalty: Number.isFinite(p) && p > 0 && p <= 10 ? p : DEFAULT_TRIPLET_PENALTY,+ };+ cache = { ts: now, engine, value };+ return value;+}++export function _resetTripletSettingsCacheForTests(): void {+ cache = null;+}++export function termOverlap(queryTerms: Set<string>, text: string): number {+ if (queryTerms.size === 0) return 0;+ const terms = contentTerms(text);+ let hit = 0;+ for (const t of queryTerms) if (terms.has(t)) hit++;+ return hit / queryTerms.size;+}++function cosine(a: Float32Array, b: Float32Array): number {+ let dot = 0, na = 0, nb = 0;+ const n = Math.min(a.length, b.length);+ for (let i = 0; i < n; i++) { dot += a[i]! * b[i]!; na += a[i]! * a[i]!; nb += b[i]! * b[i]!; }+ return na > 0 && nb > 0 ? dot / Math.sqrt(na * nb) : 0;+}++export interface TripletInputs {+ queryTerms: Set<string>;+ penalty: number;+ /** distance in [0, 2] per page key 'source:slug', absent = missing */+ pageDistance: Map<string, number>;+ /** context text per edge key 'source:from|type|to' ('' = no context), absent = unknown edge */+ edgeContext: Map<string, string>;+ pageImportance: Map<string, number>;+ edgeImportance: Map<string, number>;+}++/** Pure scorer: worst triplet per row (lower is better). */+export function scoreRow(row: SearchResult, inp: TripletInputs): SearchResult['triplet'] | undefined {+ const source = row.source_id ?? 'default';+ const edges = row.relational_path_edges ?? [];+ if (edges.length === 0) return undefined;+ const parts: NonNullable<SearchResult['triplet']>['parts'] = [];+ for (const edge of edges) {+ const [from, type, to] = edge.split('|');+ if (!from || !type || !to) continue;+ const scale = (imp: number | undefined) => 2 - (imp ?? NEUTRAL_WEIGHT);+ const dist = (key: string) => inp.pageDistance.get(key) ?? inp.penalty;+ const fromKey = `${source}:${from}`;+ const toKey = `${source}:${to}`;+ const edgeKey = `${source}:${edge}`;+ const ctx = inp.edgeContext.get(edgeKey);+ const edgeText = `${type.replace(/[_-]+/g, ' ')} ${ctx ?? ''}`;+ const edgeDistance = ctx === undefined || ctx === ''+ ? inp.penalty+ : 1 - termOverlap(inp.queryTerms, edgeText);+ const f = dist(fromKey) * scale(inp.pageImportance.get(fromKey));+ const e = edgeDistance * scale(inp.edgeImportance.get(edgeKey));+ const t = dist(toKey) * scale(inp.pageImportance.get(toKey));+ parts.push({ edge, from: round(f), edge_distance: round(e), to: round(t), total: round(f + e + t) });+ }+ if (parts.length === 0) return undefined;+ return { worst: Math.max(...parts.map(p => p.total)), parts };+}++function round(n: number): number {+ return Math.round(n * 10_000) / 10_000;+}++/**+ * Score and reorder the relational arm in place, then keep the first+ * `keep` rows. Returns true when scoring ran.+ */+export async function applyTripletScoring(+ engine: BrainEngine,+ query: string,+ list: SearchResult[],+ opts: { queryEmbedding: Float32Array | null; column: string; keep: number; penalty: number },+): Promise<boolean> {+ if (list.length === 0) return false;+ try {+ const pageKeys = new Map<string, { source_id: string; slug: string }>();+ const edgeKeys = new Map<string, { source_id: string; from: string; type: string; to: string }>();+ for (const r of list) {+ const source = r.source_id ?? 'default';+ for (const edge of r.relational_path_edges ?? []) {+ const [from, type, to] = edge.split('|');+ if (!from || !type || !to) continue;+ pageKeys.set(`${source}:${from}`, { source_id: source, slug: from });+ pageKeys.set(`${source}:${to}`, { source_id: source, slug: to });+ edgeKeys.set(`${source}:${edge}`, { source_id: source, from, type, to });+ }+ }+ if (edgeKeys.size === 0) return false;+ const pages = [...pageKeys.values()];+ const chunkRows = await engine.executeRaw<{ source_id: string; slug: string; title: string; chunk_id: number | string | null }>(+ `SELECT p.source_id, p.slug, p.title,+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = p.id ORDER BY cc.chunk_index ASC LIMIT 1) AS chunk_id+ FROM pages p+ JOIN unnest($1::text[], $2::text[]) AS r(source_id, slug) ON p.source_id = r.source_id AND p.slug = r.slug+ WHERE p.deleted_at IS NULL`,+ [pages.map(p => p.source_id), pages.map(p => p.slug)],+ );+ const queryTerms = contentTerms(query);+ const pageDistance = new Map<string, number>();+ if (opts.queryEmbedding) {+ const ids = chunkRows.map(r => r.chunk_id).filter((id): id is number | string => id != null).map(Number);+ const vectors = ids.length > 0 ? await engine.getEmbeddingsByChunkIds(ids, opts.column) : new Map<number, Float32Array>();+ for (const r of chunkRows) {+ const v = r.chunk_id == null ? undefined : vectors.get(Number(r.chunk_id));+ if (v) pageDistance.set(`${r.source_id}:${r.slug}`, 1 - cosine(opts.queryEmbedding, v));+ }+ } else {+ for (const r of chunkRows) pageDistance.set(`${r.source_id}:${r.slug}`, 1 - termOverlap(queryTerms, `${r.title} ${r.slug.replace(/[/_-]+/g, ' ')}`));+ }+ const edges = [...edgeKeys.values()];+ const ctxRows = await engine.executeRaw<{ source_id: string; from_slug: string; link_type: string; to_slug: string; context: string }>(+ `SELECT fp.source_id, fp.slug AS from_slug, l.link_type, tp.slug AS to_slug, max(l.context) AS context+ FROM links l+ JOIN pages fp ON fp.id = l.from_page_id+ JOIN pages tp ON tp.id = l.to_page_id+ JOIN unnest($1::text[], $2::text[], $3::text[], $4::text[]) AS e(source_id, from_slug, link_type, to_slug)+ ON fp.source_id = e.source_id AND fp.slug = e.from_slug AND l.link_type = e.link_type AND tp.slug = e.to_slug+ GROUP BY fp.source_id, fp.slug, l.link_type, tp.slug`,+ [edges.map(e => e.source_id), edges.map(e => e.from), edges.map(e => e.type), edges.map(e => e.to)],+ );+ const edgeContext = new Map<string, string>();+ for (const r of ctxRows) edgeContext.set(`${r.source_id}:${r.from_slug}|${r.link_type}|${r.to_slug}`, r.context ?? '');++ const settings = await loadFeedbackSettings(engine);+ const influence = effectiveInfluence(settings);+ const toImportance = (w: number) => NEUTRAL_WEIGHT + influence * 2 * (w - NEUTRAL_WEIGHT);+ const pageImportance = new Map<string, number>();+ const edgeImportance = new Map<string, number>();+ if (influence > 0) {+ const pw = await readWeights(engine, 'page', pages.map(p => ({ source_id: p.source_id, key: p.slug })));+ for (const [k, w] of pw) pageImportance.set(k, toImportance(w));+ const ew = await readWeights(engine, 'link', edges.map(e => ({ source_id: e.source_id, key: `${e.from}|${e.type}|${e.to}` })));+ for (const [k, w] of ew) edgeImportance.set(k, toImportance(w));+ }++ const inputs: TripletInputs = { queryTerms, penalty: opts.penalty, pageDistance, edgeContext, pageImportance, edgeImportance };+ const scored = list.map((r, index) => {+ const t = scoreRow(r, inputs);+ if (t) r.triplet = t;+ return { r, index, score: t?.worst ?? Number.POSITIVE_INFINITY };+ });+ scored.sort((a, b) => (a.score - b.score) || (a.index - b.index));+ list.splice(0, list.length, ...scored.slice(0, Math.max(1, opts.keep)).map(s => s.r));+ return true;+ } catch {+ list.splice(opts.keep);+ return false;+ }+}diff --git a/src/core/types.ts b/src/core/types.tsindex 871ef35c23..faf30920f5 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1544,6 +1544,8 @@ export interface RelationalFanoutOpts extends PageReadPolicy {sourceIds?: string[];/** Hard cap on returned candidate nodes. Default 50. */limit?: number;+ /** Allow up to 400 candidates (triplet scoring re-ranks the wider set). */+ wide?: boolean;}// Timelinediff --git a/test/feedback-boost.test.ts b/test/feedback-boost.test.tsnew file mode 100644index 0000000000..6a102182ba--- /dev/null+++ b/test/feedback-boost.test.ts@@ -0,0 +1,116 @@+/**+ * The use-attributed feedback ranking stage: neutral weights are a no-op,+ * learned weights reorder within [1 - λ, 1 + λ] on the score that orders the+ * list (reranker score when it ran), raw scores stay untouched, and the stage+ * runs on the keyword-only hybrid path.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { applyFeedbackStage, feedbackMultiplier } from '../src/core/search/feedback-boost.ts';+import { hybridSearch } from '../src/core/search/hybrid.ts';+import { _resetFeedbackSettingsCacheForTests } from '../src/core/feedback/settings.ts';+import type { SearchResult } from '../src/core/types.ts';++let engine: PGLiteEngine;+const ids = new Map<string, number>();++async function setWeight(slug: string, weight: number): Promise<void> {+ const [p] = await engine.executeRaw<{ content_hash: string }>('SELECT content_hash FROM pages WHERE slug = $1', [slug]);+ await engine.executeRaw(+ `INSERT INTO retrieval_weights (source_id, element_kind, element_key, weight, content_hash, updates)+ VALUES ('default', 'page', $1, $2, $3, 1)+ ON CONFLICT (source_id, element_kind, element_key) DO UPDATE SET weight = EXCLUDED.weight, content_hash = EXCLUDED.content_hash`,+ [slug, weight, p!.content_hash],+ );+}++function result(slug: string, score: number, rerank?: number): SearchResult {+ return {+ slug, page_id: ids.get(slug)!, title: slug, type: 'note' as never, chunk_text: '', chunk_source: 'compiled_truth',+ chunk_id: 0, chunk_index: 0, score, stale: false, source_id: 'default', ...(rerank !== undefined ? { rerank_score: rerank } : {}),+ };+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const slug of ['notes/renewal-plan-a', 'notes/renewal-plan-b', 'notes/renewal-plan-c']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Renewal plan for the acme-example account (${slug}).` });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Renewal plan for the acme-example account.' }]);+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);+ ids.set(slug, Number(row!.id));+ }+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM retrieval_weights');+ await engine.executeRaw('DELETE FROM config WHERE key LIKE $1', ['feedback.%']);+ _resetFeedbackSettingsCacheForTests();+});++describe('applyFeedbackStage', () => {+ test('neutral weights keep order and scores exactly, and stamp content_hash', async () => {+ const list = [result('notes/renewal-plan-a', 0.9), result('notes/renewal-plan-b', 0.8)];+ const before = list.map(r => [r.slug, r.score]);+ const out = await applyFeedbackStage(engine, list, { reranked: false });+ expect(out.map(r => [r.slug, r.score])).toEqual(before);+ expect(out.every(r => typeof r.content_hash === 'string')).toBe(true);+ expect(out.some(r => r.feedback_boost !== undefined)).toBe(false);+ });++ test('a learned weight reorders within the bound and leaves raw scores alone', async () => {+ await setWeight('notes/renewal-plan-b', 1);+ const list = [result('notes/renewal-plan-a', 0.9), result('notes/renewal-plan-b', 0.85)];+ const out = await applyFeedbackStage(engine, list, { reranked: false });+ expect(out.map(r => r.slug)).toEqual(['notes/renewal-plan-b', 'notes/renewal-plan-a']);+ expect(out[0]!.score).toBe(0.85);+ expect(out[0]!.feedback_boost).toBeCloseTo(feedbackMultiplier(1, 0.1), 6);+ expect(feedbackMultiplier(1, 0.1)).toBeCloseTo(1.1, 6);+ expect(feedbackMultiplier(0, 0.1)).toBeCloseTo(0.9, 6);+ });++ test('a reranked list is ordered by rerank_score; unscored tail rows stay after', async () => {+ await setWeight('notes/renewal-plan-a', 0);+ const list = [+ result('notes/renewal-plan-a', 0.1, 0.9), result('notes/renewal-plan-b', 0.5, 0.85), result('notes/renewal-plan-c', 0.99),+ ];+ const out = await applyFeedbackStage(engine, list, { reranked: true });+ expect(out.map(r => r.slug)).toEqual(['notes/renewal-plan-b', 'notes/renewal-plan-a', 'notes/renewal-plan-c']);+ expect(out[1]!.rerank_score).toBe(0.9);+ });++ test('feedback off: no stamps, no reorder; influence 0: stamps hashes only', async () => {+ await setWeight('notes/renewal-plan-b', 1);+ await engine.setConfig('feedback.enabled', 'false');+ _resetFeedbackSettingsCacheForTests();+ const off = await applyFeedbackStage(engine, [result('notes/renewal-plan-a', 0.9), result('notes/renewal-plan-b', 0.85)], { reranked: false });+ expect(off.map(r => r.slug)).toEqual(['notes/renewal-plan-a', 'notes/renewal-plan-b']);+ expect(off[0]!.content_hash).toBeUndefined();+ await engine.setConfig('feedback.enabled', 'true');+ await engine.setConfig('feedback.influence', '0');+ _resetFeedbackSettingsCacheForTests();+ const zero = await applyFeedbackStage(engine, [result('notes/renewal-plan-a', 0.9), result('notes/renewal-plan-b', 0.85)], { reranked: false });+ expect(zero.map(r => r.slug)).toEqual(['notes/renewal-plan-a', 'notes/renewal-plan-b']);+ expect(typeof zero[0]!.content_hash).toBe('string');+ });+});++describe('hybridSearch keyword-only path', () => {+ test('a down-weighted page drops behind an equally matching one', async () => {+ const baseline = await hybridSearch(engine, 'renewal plan acme-example', { limit: 3 });+ expect(baseline.length).toBeGreaterThan(1);+ const top = baseline[0]!.slug;+ await setWeight(top, 0);+ await engine.setConfig('feedback.influence', '0.5');+ _resetFeedbackSettingsCacheForTests();+ const after = await hybridSearch(engine, 'renewal plan acme-example', { limit: 3 });+ expect(after[0]!.slug).not.toBe(top);+ expect(after.find(r => r.slug === top)!.feedback_boost).toBeCloseTo(0.5, 6);+ });+});diff --git a/test/triplet-score.test.ts b/test/triplet-score.test.tsnew file mode 100644index 0000000000..f791440d9c--- /dev/null+++ b/test/triplet-score.test.ts@@ -0,0 +1,102 @@+/**+ * Relational-arm triplet scoring: the pure scorer (summed, importance-scaled+ * distances, missing-part penalty, worst hop) and the end-to-end arm on PGLite+ * (path edges from the fanout, the wider fetch that reaches candidates past+ * the alphabetical cut, lexical fallback without a query vector).+ */+import { afterAll, beforeAll, describe, expect, test } 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 { applyTripletScoring, scoreRow, type TripletInputs } from '../src/core/search/triplet-score.ts';+import type { SearchResult } from '../src/core/types.ts';++function row(slug: string, edges: string[]): SearchResult {+ return {+ slug, page_id: 1, title: slug, type: 'person' as never, chunk_text: '', chunk_source: 'compiled_truth',+ chunk_id: 0, chunk_index: 0, score: 0, stale: false, source_id: 'default', relational_path_edges: edges,+ };+}++function inputs(over: Partial<TripletInputs> = {}): TripletInputs {+ return {+ queryTerms: new Set(['payment']), penalty: 3, pageDistance: new Map(), edgeContext: new Map(),+ pageImportance: new Map(), edgeImportance: new Map(), ...over,+ };+}++describe('scoreRow', () => {+ test('sums the three distances, each scaled by (2 - importance)', () => {+ const t = scoreRow(row('people/bo', ['people/bo|works_at|companies/acme']), inputs({+ pageDistance: new Map([['default:people/bo', 0.2], ['default:companies/acme', 0.4]]),+ edgeContext: new Map([['default:people/bo|works_at|companies/acme', 'Bo leads payments at Acme']]),+ }))!;+ expect(t.parts[0]!.from).toBeCloseTo(0.3, 4);+ expect(t.parts[0]!.edge_distance).toBeCloseTo(0, 4);+ expect(t.parts[0]!.to).toBeCloseTo(0.6, 4);+ expect(t.worst).toBeCloseTo(0.9, 4);+ });++ test('missing page vectors and empty edge context cost the penalty', () => {+ const t = scoreRow(row('people/bo', ['people/bo|works_at|companies/acme']), inputs({+ edgeContext: new Map([['default:people/bo|works_at|companies/acme', '']]),+ }))!;+ expect(t.worst).toBeCloseTo(3 * 1.5 * 3, 4);+ });++ test('higher importance lowers the score; the worst hop decides', () => {+ const base = inputs({+ pageDistance: new Map([['default:a', 0.1], ['default:b', 0.1], ['default:c', 1.5]]),+ edgeContext: new Map([['default:a|knows|b', 'payment'], ['default:b|knows|c', 'payment']]),+ });+ const t = scoreRow(row('c', ['a|knows|b', 'b|knows|c']), base)!;+ expect(t.worst).toBe(Math.max(...t.parts.map(p => p.total)));+ expect(t.worst).toBeCloseTo((0.1 + 0 + 1.5) * 1.5, 4);+ const trusted = scoreRow(row('c', ['b|knows|c']), { ...base, pageImportance: new Map([['default:c', 0.6]]) })!;+ expect(trusted.worst).toBeLessThan((0.1 + 1.5) * 1.5);+ });+});++describe('relational arm with triplet scoring [pglite]', () => {+ let eng: PGLiteEngine;++ beforeAll(async () => {+ eng = new PGLiteEngine();+ await eng.connect({});+ await eng.initSchema();+ await eng.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'A company.', timeline: '' });+ for (let i = 0; i < 60; i++) {+ const slug = `people/a${String(i).padStart(2, '0')}-example`;+ await eng.putPage(slug, { type: 'person', title: `Person ${i}`, compiled_truth: 'Works at Acme.', timeline: '' });+ await installFixtureChunks(eng, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Works at Acme.' }]);+ await eng.addLink(slug, 'companies/acme-example', 'on the sales team', 'works_at', 'manual');+ }+ await eng.putPage('people/zed-example', { type: 'person', title: 'Zed Example', compiled_truth: 'Payments engineer.', timeline: '' });+ await installFixtureChunks(eng, 'people/zed-example', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Payments engineer.' }]);+ await eng.addLink('people/zed-example', 'companies/acme-example', 'leads the payments platform', 'works_at', 'manual');+ }, 60_000);++ afterAll(async () => {+ await eng.disconnect();+ });++ test('fanout rows carry their stored-direction path edges', async () => {+ const list = await buildRelationalArm(eng, 'who works at acme-example', { limit: 5 });+ expect(list.length).toBeGreaterThan(0);+ for (const r of list) expect(r.relational_path_edges).toEqual([`${r.slug}|works_at|companies/acme-example`]);+ });++ test('without scoring the alphabetical cut drops the relevant person; the wide fetch plus scoring keeps it first', async () => {+ const narrow = await buildRelationalArm(eng, 'who works at acme-example', { limit: 10 });+ expect(narrow.map(r => r.slug)).not.toContain('people/zed-example');+ const wide = await buildRelationalArm(eng, 'who works at acme-example', { limit: 100, wide: true });+ expect(wide.map(r => r.slug)).toContain('people/zed-example');+ const ran = await applyTripletScoring(eng, 'who works on payments at acme-example', wide, {+ queryEmbedding: null, column: 'embedding', keep: 10, penalty: 3,+ });+ expect(ran).toBe(true);+ expect(wide).toHaveLength(10);+ expect(wide[0]!.slug).toBe('people/zed-example');+ expect(wide[0]!.triplet!.worst).toBeLessThan(wide[1]!.triplet!.worst);+ });+});