Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
search: hub dampening of backlink and graph-signal lifts behind search.hub_dampening (default off)
garrytanaa48d8f51ae5
diff --git a/src/core/config.ts b/src/core/config.tsindex 098aff1f81..8f2ed7308e 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1370,6 +1370,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.keyword_arm_confidence_floor',// Ranker wave (Phase E3): metadata boost gate — `lexical` skips post-fusion metadata boosts when the vector arm was the only voter (mode.ts reads; `always` | `lexical`).'search.metadata_boost_gate',+ 'search.hub_dampening','search.crag_escalation','search.crag_think',// Evidence delivery (search/evidence-delivery.ts): default unit (auto),diff --git a/src/core/search/graph-signals.ts b/src/core/search/graph-signals.tsindex ecde80683e..8a1793bec0 100644--- a/src/core/search/graph-signals.ts+++ b/src/core/search/graph-signals.ts@@ -43,6 +43,7 @@ import type { AdjacencyRow } from '../types.ts';import type { BrainEngine } from '../engine.ts';import { hasReadPolicy } from './read-policy-sql.ts';import { createAuditWriter } from '../audit/audit-writer.ts';+import { dampenBoost, hubWeight, type HubDampening } from './hub-dampening.ts';// ===========================================================================// Constants (D14=B halved magnitudes; the score-distribution probe feeds the@@ -120,6 +121,16 @@ export interface GraphSignalsOpts extends PageReadPolicy {onMeta?: (meta: GraphSignalsMeta) => void;/** Observability sink — called once per invocation with score stats. */onScoreDistribution?: (dist: ScoreDistribution) => void;+ /**+ * Hub dampening (hub-dampening.ts): half degree H. When set together with+ * `degrees`, each boost's excess over 1.0 is scaled by+ * hubWeight(caller-visible inbound degree, H). Undefined → undampened.+ */+ hubHalfDegree?: HubDampening;+ /** Caller-scoped inbound degree per page id (readBacklinkCounts). */+ degrees?: Map<number, number>;+ /** Called once with the number of results whose graph boost was reduced. */+ onHubDampened?: (count: number) => void;}// ===========================================================================@@ -351,6 +362,8 @@ export async function applyGraphSignals(}const floorThreshold = opts.floorThreshold;+ const halfDegree = opts.degrees ? opts.hubHalfDegree : undefined;+ let hubDampened = 0;for (const r of topK) {// Floor-gate: D1=A inheritance. Below-floor results don't accumulate@@ -360,19 +373,29 @@ export async function applyGraphSignals(if (floorThreshold !== undefined && !(r.score >= floorThreshold)) continue;const row = adjacency.get(r.page_id);if (!row) continue;+ const fires = row.hits >= ADJACENCY_MIN_HITS || row.cross_source_hits >= CROSS_SOURCE_MIN_HITS;+ const degree = opts.degrees?.get(r.page_id) ?? 0;+ const weight = fires ? hubWeight(degree, halfDegree) : 1;if (row.hits >= ADJACENCY_MIN_HITS) {- r.score *= ADJACENCY_BOOST;+ const factor = dampenBoost(ADJACENCY_BOOST, degree, halfDegree);+ r.score *= factor;r.graph_adjacency_hits = row.hits;- r.graph_adjacency_boost = ADJACENCY_BOOST;+ r.graph_adjacency_boost = factor;meta.adjacency_fires++;}if (row.cross_source_hits >= CROSS_SOURCE_MIN_HITS) {- r.score *= CROSS_SOURCE_BOOST;+ const factor = dampenBoost(CROSS_SOURCE_BOOST, degree, halfDegree);+ r.score *= factor;r.graph_cross_source_hits = row.cross_source_hits;- r.graph_cross_source_boost = CROSS_SOURCE_BOOST;+ r.graph_cross_source_boost = factor;meta.cross_source_fires++;}+ if (weight < 1) {+ r.graph_hub_weight = weight;+ hubDampened++;+ }}+ opts.onHubDampened?.(hubDampened);// ---- Session diversification (D9 single-pass Map, D11=B DEMOTE) ----// Only fires when sessionPrefix detects a session-like patterndiff --git a/src/core/search/hub-dampening.ts b/src/core/search/hub-dampening.tsindex cc77c4d559..88758841eb 100644--- a/src/core/search/hub-dampening.ts+++ b/src/core/search/hub-dampening.ts@@ -1,27 +1,97 @@/**- * Hub dampening: a node linked to many others carries less signal per link.+ * hub-dampening.ts — degree-aware weight for graph-derived ranking boosts.*- * `hubWeight(n, H) = 1 / (1 + ((max(n, 1) - 1) / H)^2)`, where H is the degree- * at which a boost is halved. Feed it the caller-visible degree (what the- * caller may read), never a global count. `'off'` or an unset H means no- * dampening (weight 1).+ * WHY. A page linked from thousands of other pages (the owner's own page, a+ * company every meeting mentions) collects graph boosts merely for being+ * popular: the backlink boost grows with ln(1 + inbound) and the adjacency /+ * cross-source signals fire whenever several top-K pages link to it, which a+ * hub satisfies by chance. The Cat 13 E1 receipt (metadata-boost-gate.ts)+ * measured exactly that intrusion. Hub dampening scales each graph boost's+ * EXCESS over 1.0 by+ *+ * hubWeight(n, H) = 1 / (1 + ((n - 1) / H)^2)+ *+ * where n is the page's caller-visible inbound degree and H is the half+ * degree: the degree at which the boost is halved. n <= 1 keeps the full+ * boost; n = H + 1 halves it; n = 3H + 1 keeps 10%. Parameterising by H (a+ * degree, not a bare coefficient c = 1/H^2) keeps the knob readable.+ *+ * Measured degree shape the candidate H values come from: a 285k-article+ * wiki-linked corpus has inbound p50 5, p90 93, p95 193, p99 607, max 35,681+ * (the top 1% of pages receive 25% of links); the shipped eval corpora top out+ * at 12. The eval tries H in {32, 100, 200, 600} against "boost removed" and+ * "boost capped" controls; `off` (no dampening) is the default until a sealed+ * held-out verdict sets it.+ *+ * Shared API (P7's relational planner imports `hubWeight`): pure, no IO.+ * Parse contract in ONE place: `normalizeHubDampening` (per-call opts and the+ * `search.hub_dampening` config key both route through it).*/++/** `off` = no dampening; a positive number = the half degree H. */export type HubDampening = 'off' | number;-export function hubWeight(degree: number, h: HubDampening | undefined): number {- if (h === undefined || h === 'off' || !(h > 0) || !Number.isFinite(degree)) return 1;- const x = (Math.max(degree, 1) - 1) / h;+/** Default until the held-out eval verdict sets one (D3: build with features off). */+export const DEFAULT_HUB_DAMPENING: HubDampening = 'off';++/** Inclusive bounds for a numeric half degree. */+export const HUB_HALF_DEGREE_MIN = 1;+export const HUB_HALF_DEGREE_MAX = 1_000_000;++/**+ * Weight in (0, 1] for a node with `degree` links. `halfDegree` undefined,+ * `off`, or invalid → 1 (no dampening). Non-finite or negative degrees are+ * treated as 0.+ */+export function hubWeight(degree: number, halfDegree: HubDampening | undefined): number {+ if (typeof halfDegree !== 'number' || !Number.isFinite(halfDegree) || halfDegree <= 0) return 1;+ const n = Number.isFinite(degree) && degree > 1 ? degree : 1;+ const x = (n - 1) / halfDegree;return 1 / (1 + x * x);}-/** Shrink a multiplicative boost toward 1 by the hub weight of its node. */-export function dampenBoost(factor: number, degree: number, h: HubDampening | undefined): number {- return 1 + (factor - 1) * hubWeight(degree, h);+/**+ * Scale a multiplicative boost's excess by the hub weight:+ * `1 + (factor - 1) * hubWeight(degree, H)`. A factor <= 1 (a demotion) is+ * returned unchanged — dampening only shrinks lifts.+ */+export function dampenBoost(factor: number, degree: number, halfDegree: HubDampening | undefined): number {+ if (!(factor > 1)) return factor;+ return 1 + (factor - 1) * hubWeight(degree, halfDegree);}-/** `'off'`/false/null → 'off'; a positive number (or numeric string) → H; anything else → undefined (fall through). */+/**+ * The ONE parse contract for `search.hub_dampening` and the per-call seam:+ * - `off` / `none` / `false` (any case) → 'off'+ * - finite number (or numeric string) in [1, 1e6] → that number+ * - anything else (0, negatives, NaN, garbage) → undefined (unset: fall+ * through to the next resolution tier — config → bundle)+ */export function normalizeHubDampening(v: unknown): HubDampening | undefined {- if (v === 'off' || v === false || v === null) return 'off';- const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;- return Number.isFinite(n) && n > 0 ? n : undefined;+ if (typeof v === 'string') {+ const lit = v.trim().toLowerCase();+ if (lit === 'off' || lit === 'none' || lit === 'false') return 'off';+ if (lit === '') return undefined;+ return normalizeHubDampening(Number(lit));+ }+ if (v === false) return 'off';+ if (typeof v === 'number' && Number.isFinite(v) && v >= HUB_HALF_DEGREE_MIN && v <= HUB_HALF_DEGREE_MAX) return v;+ return undefined;+}++/** knobsHash part value: `off` or the half degree with fixed precision. */+export function hubDampeningHashPart(v: HubDampening | undefined): string {+ return typeof v === 'number' ? v.toFixed(3) : 'off';+}++/** Per-search observability stamp (`HybridSearchMeta.hub_dampening`). */+export interface HubDampeningMeta {+ /** The resolved half degree, or `off`. */+ half_degree: HubDampening;+ /** Results whose backlink boost was reduced. */+ backlink_dampened: number;+ /** Results whose adjacency or cross-source boost was reduced. */+ graph_dampened: number;+ /** True when the degree read failed and boosts ran undampened. */+ errored: boolean;}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 7a8602f190..db8503c216 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -39,6 +39,7 @@ import {type FusionListEntry,} from './fusion-lists.ts';import { type MetadataBoostGate } from './metadata-boost-gate.ts';+import { type HubDampening, type HubDampeningMeta, hubWeight } from './hub-dampening.ts';import { enforceTokenBudget } from './token-budget.ts';import {semanticResultCacheAvailable,@@ -274,18 +275,25 @@ export function applyBacklinkBoost(results: SearchResult[],counts: Map<number, number>,floorThreshold?: number,+ halfDegree?: HubDampening,): void {for (const r of results) {if (!Number.isFinite(r.score)) continue;if (floorThreshold !== undefined && r.score < floorThreshold) continue;const count = counts.get(r.page_id) ?? 0;if (count > 0) {- const factor = 1.0 + BACKLINK_BOOST_COEF * Math.log(1 + count);+ // Hub dampening (hub-dampening.ts): the log-popularity lift shrinks for+ // pages whose inbound degree is far above the half degree H. `off` /+ // undefined → weight 1, byte-identical to the undampened factor.+ const weight = hubWeight(count, halfDegree);+ const factor = 1.0 + BACKLINK_BOOST_COEF * Math.log(1 + count) * weight;r.score *= factor;// v0.40.4 attribution stamp (D12=A) — formatter reads this for// --explain output. Stays undefined when count == 0 so the// formatter can render "no boosts applied" honestly.r.backlink_boost = factor;+ r.backlink_count = count;+ if (weight < 1) r.backlink_hub_weight = weight;}}}@@ -528,6 +536,14 @@ export interface PostFusionOpts extends PageReadPolicy {* downrank (correctness) still run. Undefined / false → every stage as before.*/skipMetadataBoosts?: boolean;+ /**+ * Hub dampening (hub-dampening.ts): the half degree H, or `off`. Scales the+ * backlink boost and the graph-signal boosts by the result's caller-visible+ * inbound degree. Resolved from ModeBundle.hub_dampening.+ */+ hubDampening?: HubDampening;+ /** Observability sink for the hub-dampening decision (always called when the metadata stages run). */+ onHubDampening?: (meta: HubDampeningMeta) => void;}export async function runPostFusionStages(@@ -557,14 +573,23 @@ export async function runPostFusionStages(// Phase E3 — metadata-axis stages gated as ONE block (see PostFusionOpts).const metadata = opts.skipMetadataBoosts !== true;+ // Hub dampening — one caller-scoped degree map shared by the backlink and+ // graph-signal stages (readBacklinkCounts authorizes targets, contributors+ // and edge origins, so hidden links never move visible rankings).+ const hubDampening: HubDampening = opts.hubDampening ?? 'off';+ const hubMeta: HubDampeningMeta = { half_degree: hubDampening, backlink_dampened: 0, graph_dampened: 0, errored: false };+ let degrees: Map<number, number> | undefined;+// Backlink stage (existing behavior, preserved).if (metadata && opts.applyBacklinks) {try {const pageIds = Array.from(new Set(results.map(r => r.page_id)));- const counts = await engine.getBacklinkCounts(pageIds, policy);- applyBacklinkBoost(results, counts, floorThreshold);+ degrees = await engine.getBacklinkCounts(pageIds, policy);+ applyBacklinkBoost(results, degrees, floorThreshold, hubDampening);+ hubMeta.backlink_dampened = results.filter(r => r.backlink_hub_weight !== undefined).length;} catch {// Non-fatal; preserves the existing pre-v0.29.1 contract.+ if (hubDampening !== 'off') hubMeta.errored = true;}}@@ -636,17 +661,30 @@ export async function runPostFusionStages(if (metadata && opts.graphSignalsEnabled) {try {const { applyGraphSignals } = await import('./graph-signals.ts');+ // Dampening needs degrees; when the backlink stage did not fetch them,+ // fetch once here. A failed read fails open (undampened boosts).+ if (hubDampening !== 'off' && degrees === undefined) {+ try {+ degrees = await engine.getBacklinkCounts(Array.from(new Set(results.map(r => r.page_id))), policy);+ } catch {+ hubMeta.errored = true;+ }+ }await applyGraphSignals(results, engine, {...policy,enabled: true,floorThreshold,onMeta: opts.onGraphMeta,onScoreDistribution: opts.onScoreDistribution,+ ...(hubDampening !== 'off' && degrees ? { hubHalfDegree: hubDampening, degrees, onHubDampened: (n: number) => { hubMeta.graph_dampened = n; } } : {}),});} catch {// Non-fatal; preserves the per-stage contract.}}+ if (metadata) {+ try { opts.onHubDampening?.(hubMeta); } catch { /* meta must never break search */ }+ }// v0.42 (T19, plan D6) — alias_resolved stage (5th post-fusion stage).// Runs LAST so its 1.05x multiplier stacks on top of every other boost.@@ -900,6 +938,14 @@ export interface HybridSearchOpts extends SearchOpts {* resolver (knobs hash `mbg=`); eval A/B runs drive it here.*/metadataBoostGate?: MetadataBoostGate;+ /**+ * Per-call override for `search.hub_dampening` (hub-dampening.ts): `off` or+ * the half degree H. `undefined` → config/bundle; anything else is unset via+ * the ONE contract `normalizeHubDampening`. Threaded through+ * resolveSearchMode in BOTH the inner search and the cache resolver (knobs+ * hash `hd=`); eval A/B runs drive it here.+ */+ hubDampening?: HubDampening | string;/** Override default RRF K constant (default: 60). Lower values boost top-ranked results more. */rrfK?: number;/** Override dedup pipeline parameters. */@@ -1115,7 +1161,7 @@ export async function hybridSearch(return searchVectorFallback(req, lexical, relationalList, postFusionOpts);}- const { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate } = await fuseArms(req, {+ const { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate, hubDampening } = await fuseArms(req, {vectorArms, keywordResults: lexical.keywordResults, titleResults: lexical.titleResults, relationalList,effectiveModality, queryEmbedding, imageQueryEmbedding, unifiedDone, postFusionOpts,});@@ -1142,7 +1188,7 @@ export async function hybridSearch(});return finalizeHybridResults(req, returnPool, {relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision,- relationalRerankPin, keywordArmConfidence, metadataBoostGate,+ relationalRerankPin, keywordArmConfidence, metadataBoostGate, hubDampening,});}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex 25fba1a107..3c760c1e10 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -155,6 +155,8 @@ export function buildPostFusionOpts(req: HybridRequest): PostFusionOpts {// The raw query drives the matcher; default factor when the knob is unset.query,titleBoost: resolvedMode.title_boost,+ // Hub dampening (hub-dampening.ts) threaded from the resolved mode.+ hubDampening: resolvedMode.hub_dampening,};return postFusionOpts;}diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.tsindex ccd2ce7f97..9055e80b17 100644--- a/src/core/search/hybrid/cache-stages.ts+++ b/src/core/search/hybrid/cache-stages.ts@@ -19,6 +19,7 @@ import { loadConfigWithEngine } from '../../config.ts';import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';+import { normalizeHubDampening } from '../hub-dampening.ts';import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';import { recordSearchTelemetry } from '../telemetry.ts';import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';@@ -90,6 +91,8 @@ export async function resolveCacheSearchMode(engine: BrainEngine, opts: HybridSekeyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),// Ranker wave (Phase E3) — threaded here too so knobsHash's `mbg=` part reflects the per-call gate.metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),+ // Hub dampening per-call thread-through (eval A/B); same normalizer in both resolutions.+ hub_dampening: normalizeHubDampening(opts?.hubDampening),},});return { modeInputForCache, resolvedForCache, knobsHash };diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.tsindex f49e14ecf6..3341af3181 100644--- a/src/core/search/hybrid/keyword-only.ts+++ b/src/core/search/hybrid/keyword-only.ts@@ -9,6 +9,7 @@ import { applyFeedbackStage } from '../feedback-boost.ts';import { type PostFusionOpts, RRF_K, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions } from '../hybrid.ts';import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';import type { SearchResult } from '../../types.ts';+import type { HubDampeningMeta } from '../hub-dampening.ts';import { applyAliasHop } from '../alias-hop.ts';import { applyExactLookupTier } from '../exact-lookup.ts';import { dedupResults } from '../dedup.ts';@@ -36,6 +37,7 @@ export async function searchWithoutEmbeddings(// boost skips them (flag survives fusion's result spread).await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);let noEmbedResults = keywordResults;+ let hubDampening: HubDampeningMeta | undefined;if (relationalList.length > 0 || titleResults.length > 0) {const fk = opts?.rrfK ?? RRF_K;const noEmbedLists = [{ list: keywordResults, k: fk }];@@ -44,7 +46,7 @@ export async function searchWithoutEmbeddings(noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost);}if (noEmbedResults.length > 0) {- await runPostFusionStages(engine, noEmbedResults, postFusionOpts);+ await runPostFusionStages(engine, noEmbedResults, { ...postFusionOpts, onHubDampening: (m) => { hubDampening = m; } });await applyIdentityBoosts(req, noEmbedResults);noEmbedResults.sort((a, b) => b.score - a.score);noEmbedResults = await applyFeedbackStage(engine, noEmbedResults, { reranked: false });@@ -117,6 +119,7 @@ export async function searchWithoutEmbeddings(? { token_budget: noEmbedBudgetMeta }: {}),...(noEmbedRelSlot ? { relational_evidence_slot: noEmbedRelSlot } : {}),+ ...(hubDampening ? { hub_dampening: hubDampening } : {}),});return noEmbedBudgeted;}@@ -140,6 +143,7 @@ export async function searchVectorFallback(// no-embedding-provider path for rationale).await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);let fallbackResults = keywordResults;+ let hubDampening: HubDampeningMeta | undefined;if (relationalList.length > 0 || titleResults.length > 0) {const fk = opts?.rrfK ?? RRF_K;const fallbackLists = [{ list: keywordResults, k: fk }];@@ -148,7 +152,7 @@ export async function searchVectorFallback(fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost);}if (fallbackResults.length > 0) {- await runPostFusionStages(engine, fallbackResults, postFusionOpts);+ await runPostFusionStages(engine, fallbackResults, { ...postFusionOpts, onHubDampening: (m) => { hubDampening = m; } });await applyIdentityBoosts(req, fallbackResults);fallbackResults.sort((a, b) => b.score - a.score);fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });@@ -194,6 +198,7 @@ export async function searchVectorFallback(? { token_budget: kwBudgetMeta }: {}),...(kwRelSlot ? { relational_evidence_slot: kwRelSlot } : {}),+ ...(hubDampening ? { hub_dampening: hubDampening } : {}),});return kwBudgeted;}diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 2a2fd696e8..0e751806aa 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -11,6 +11,7 @@ import { type FusionListEntry, type VectorArm, composeFusionLists } from '../fusimport { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';import type { KeywordArmConfidenceDecision } from '../arm-confidence.ts';import { type MetadataBoostGateDecision, decideMetadataBoosts, lexicalArmsVoted } from '../metadata-boost-gate.ts';+import type { HubDampeningMeta } from '../hub-dampening.ts';import { type PostFusionOpts, RRF_K, cosineReScore, resolveWalkDedupCap, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions, textVectorArmNonEmpty } from '../hybrid.ts';import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';import { type RelationalRerankPinDecision, pinRelationalRows } from '../relational-rerank-pin.ts';@@ -151,6 +152,7 @@ export async function fuseArms(// Phase E3 (Cat 13): metadata boost gate — decided from the SAME lexical// lists composeFusionLists just fused (post relaxed-row demotion); image// modality never skips (no lexical arm ran); stamped on meta even under `always`.+ let hubDampening: HubDampeningMeta | undefined;const metadataBoostGate = decideMetadataBoosts({gate: resolvedMode.metadata_boost_gate, modality: effectiveModality,lexicalVoted: lexicalArmsVoted({@@ -165,13 +167,14 @@ export async function fuseArms(if (fused.length > 0) {await runPostFusionStages(engine, fused, {...postFusionOpts, skipMetadataBoosts: !metadataBoostGate.boosts_applied,+ onHubDampening: (m) => { hubDampening = m; },});// v0.32.x search-lite: intent exact-match boost (entity/event intents).// No-op when boost factor is 1.0 (general intent or weighting disabled).await applyIdentityBoosts(req, fused);fused.sort((a, b) => b.score - a.score);}- return { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate };+ return { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate, hubDampening };}/** A2 two-pass structural expansion (default off); grows `fused` in place and returns the dedup options. */@@ -430,7 +433,7 @@ export async function sizeReturnPool(export async function finalizeHybridResults(req: HybridRequest,returnPool: SearchResult[],- { relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision, relationalRerankPin, keywordArmConfidence, metadataBoostGate }: {+ { relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision, relationalRerankPin, keywordArmConfidence, metadataBoostGate, hubDampening }: {relaxedDropped: number;adaptiveDecision: AdaptiveReturnDecision | undefined;autocutDecision: AutocutDecision | undefined;@@ -438,6 +441,7 @@ export async function finalizeHybridResults(relationalRerankPin: RelationalRerankPinDecision | undefined;keywordArmConfidence: KeywordArmConfidenceDecision | undefined;metadataBoostGate: MetadataBoostGateDecision;+ hubDampening?: HubDampeningMeta;},): Promise<SearchResult[]> {const { engine, opts, resolvedMode, resolvedCol, limit, offset, suggestions, detailResolved, degraded } = req;@@ -471,6 +475,7 @@ export async function finalizeHybridResults(...(relationalRerankPin ? { relational_rerank_pin: relationalRerankPin } : {}),...(keywordArmConfidence ? { keyword_arm_confidence: keywordArmConfidence } : {}),metadata_boost_gate: metadataBoostGate,+ ...(hubDampening ? { hub_dampening: hubDampening } : {}),});return budgeted;}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex 298231d95b..fa3f844cb8 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -16,6 +16,7 @@ import type { ResolveSearchModeInput, ResolvedSearchKnobs } from '../mode.ts';import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';+import { normalizeHubDampening } from '../hub-dampening.ts';import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';import { isRelationalQuery } from '../relational-plan.ts';import { pushDegraded } from './degraded.ts';@@ -135,6 +136,8 @@ export async function resolveHybridRequest(keyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),// Ranker wave (Phase E3) — metadata boost gate per-call thread-through (eval A/B).metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),+ // Hub dampening per-call thread-through (eval A/B); same normalizer in both resolutions.+ hub_dampening: normalizeHubDampening(opts?.hubDampening),},});diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 3f326e6187..be2adfed76 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -37,6 +37,7 @@ import { DEFAULT_RERANKER_MODEL } from '../ai/defaults.ts';import { normalizeExpansionVariantBudget } from './fusion-lists.ts';import { DEFAULT_RELATIONAL_RERANK_PIN, normalizeRelationalRerankPin } from './relational-rerank-pin.ts';import { normalizeKeywordArmConfidenceFloor } from './arm-confidence.ts';+import { DEFAULT_HUB_DAMPENING, hubDampeningHashPart, normalizeHubDampening, type HubDampening } from './hub-dampening.ts';import {DEFAULT_METADATA_BOOST_GATE,normalizeMetadataBoostGate,@@ -422,6 +423,15 @@ export interface ModeBundle {* HybridSearchOpts.metadataBoostGate → `search.metadata_boost_gate` config → bundle. knobsHash part `mbg=`.*/metadata_boost_gate: MetadataBoostGate;+ /**+ * Hub dampening (hub-dampening.ts): `off`, or the half degree H at which the+ * backlink and graph-signal lifts are halved for high-degree pages. Every+ * bundle is `off` until a sealed held-out verdict sets a default.+ * Parse contract in ONE place: `normalizeHubDampening`. Override: per-call+ * HybridSearchOpts.hubDampening → `search.hub_dampening` config → bundle.+ * knobsHash part `hd=` (emitted only when not `off`).+ */+ hub_dampening: HubDampening;}/**@@ -490,6 +500,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =keyword_arm_confidence_floor: null,// Phase E3 — metadata boost gate `lexical` (flipped on the Cat 13 held-out receipt); `always` restores the pre-wave pipeline.metadata_boost_gate: 'lexical',+ hub_dampening: DEFAULT_HUB_DAMPENING,}),balanced: Object.freeze({cache_enabled: true,@@ -556,6 +567,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =keyword_arm_confidence_floor: null,// Phase E3 — metadata boost gate `lexical` (flipped on the Cat 13 held-out receipt); `always` restores the pre-wave pipeline.metadata_boost_gate: 'lexical',+ hub_dampening: DEFAULT_HUB_DAMPENING,}),tokenmax: Object.freeze({cache_enabled: true,@@ -622,6 +634,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =keyword_arm_confidence_floor: null,// Phase E3 — metadata boost gate `lexical` (flipped on the Cat 13 held-out receipt); `always` restores the pre-wave pipeline.metadata_boost_gate: 'lexical',+ hub_dampening: DEFAULT_HUB_DAMPENING,}),});@@ -687,6 +700,8 @@ export interface SearchKeyOverrides {keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate override (`always` | `lexical`).metadata_boost_gate?: MetadataBoostGate;+ // Hub dampening override (`off` | half degree).+ hub_dampening?: HubDampening;autocut_jump?: number;autocut_min_top?: number;autocut_min_keep?: number;@@ -754,6 +769,8 @@ export interface SearchPerCallOpts {keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate per-call override (`always` | `lexical`).metadata_boost_gate?: MetadataBoostGate;+ // Hub dampening per-call override (`off` | half degree).+ hub_dampening?: HubDampening;}/**@@ -860,6 +877,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchrelational_chain_slots: pick('relational_chain_slots'),keyword_arm_confidence_floor: pick('keyword_arm_confidence_floor'),metadata_boost_gate: pick('metadata_boost_gate'),+ hub_dampening: pick('hub_dampening'),resolved_mode,mode_valid: valid,};@@ -1204,6 +1222,9 @@ export function knobsHash(...(knobs.relational_planner ? ['rp=1'] : []),...(knobs.relational_orient_onehop ?? knobs.relational_planner ? ['ro=1'] : []),...(knobs.relational_planner && knobs.relational_chain_slots ? [`rcs=${knobs.relational_chain_slots}`] : []),+ // Hub dampening (append-only, emitted only when not `off`, so every+ // existing key is unchanged and needs no version bump).+ ...(typeof knobs.hub_dampening === 'number' ? [`hd=${hubDampeningHashPart(knobs.hub_dampening)}`] : []),];// #5691 (append-only, no version bump): only a non-empty query prefix adds// a part, so every row written without one keeps its key.@@ -1456,6 +1477,13 @@ export function loadOverridesFromConfig(const g = normalizeMetadataBoostGate(mbg);if (g !== undefined) out.metadata_boost_gate = g;}+ // Hub dampening: `off` or a half degree; anything else falls through to the+ // bundle. ONE parse contract: normalizeHubDampening (hub-dampening.ts).+ const hd = get('search.hub_dampening');+ if (hd !== undefined) {+ const h = normalizeHubDampening(hd);+ if (h !== undefined) out.hub_dampening = h;+ }return out;}@@ -1510,6 +1538,7 @@ export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Objecrelational_chain_slots: 'search.relational_chain_slots',keyword_arm_confidence_floor: 'search.keyword_arm_confidence_floor',metadata_boost_gate: 'search.metadata_boost_gate',+ hub_dampening: 'search.hub_dampening',});/** The full list of config keys this module reads. Used by `gbrain search modes --reset`. */diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex bb7ebbfa2e..b168068b0f 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -67,6 +67,7 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {keyword_arm_confidence_floor: 'Keyword-arm confidence floor: below this margin ratio the keyword + title lists fuse at half weight (null = off; (0, 1])',// Ranker wave (Phase E3) metadata boost gatemetadata_boost_gate: 'Post-fusion metadata boosts (backlink/salience/recency/graph/alias): always, or lexical = only when a keyword/title/relational row fused',+ hub_dampening: 'Hub dampening of backlink/graph lifts: off, or the inbound degree at which a high-degree page keeps half its lift',};/**diff --git a/src/core/types.ts b/src/core/types.tsindex 0c73f75d02..8c9b7bfe4b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -960,6 +960,12 @@ export interface SearchResult {feedback_boost?: number;/** The page's content_hash when this result was retrieved (stamped while retrieval feedback is enabled). */content_hash?: string | null;+ /** Caller-visible inbound linking pages behind backlink_boost (stamped with it). */+ backlink_count?: number;+ /** Hub-dampening weight (0, 1) applied to the backlink lift; absent when undampened. */+ backlink_hub_weight?: number;+ /** Hub-dampening weight (0, 1) applied to the adjacency / cross-source lifts; absent when undampened. */+ graph_hub_weight?: number;/** Multiplier applied by applySalienceBoost. */salience_boost?: number;/** Multiplier applied by applyRecencyBoost. */@@ -2116,6 +2122,13 @@ export interface HybridSearchMeta {* recall there; the gate is never consulted).*/metadata_boost_gate?: import('./search/metadata-boost-gate.ts').MetadataBoostGateDecision;+ /**+ * Hub dampening (`search.hub_dampening`): the half degree in force and how+ * many results had a graph-derived lift reduced. Stamped whenever the+ * metadata stages ran, even with dampening `off`, so operators can see the+ * resolved setting.+ */+ hub_dampening?: import('./search/hub-dampening.ts').HubDampeningMeta;/*** v0.32.x (search-lite): token budget enforcement metadata. Omitted when* no budget was applied (backward-compatible with pre-search-litediff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 63fed5035f..69e6948470 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -95,6 +95,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).metadata_boost_gate: 'lexical',+ hub_dampening: 'off',});});@@ -141,6 +142,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).metadata_boost_gate: 'lexical',+ hub_dampening: 'off',});});@@ -185,6 +187,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).metadata_boost_gate: 'lexical',+ hub_dampening: 'off',});});diff --git a/test/search/hub-dampening.test.ts b/test/search/hub-dampening.test.tsnew file mode 100644index 0000000000..885f5fefde--- /dev/null+++ b/test/search/hub-dampening.test.ts@@ -0,0 +1,214 @@+/**+ * Hub dampening — pure weight, parse contract, backlink + graph-signal sites,+ * and the hybridSearch wire (PGLite, keyless).+ *+ * Pinned contracts:+ * - hubWeight(1, H) = 1; hubWeight(H + 1, H) = 0.5; `off` / undefined = 1+ * - normalizeHubDampening is the ONE parse contract (config + per-call)+ * - applyBacklinkBoost with `off` is byte-identical to the undampened factor+ * - dampening shrinks only lifts (factor > 1), never demotions+ * - graph-signal lifts scale by the caller-visible degree map+ * - hybridSearch threads `hubDampening` and stamps meta.hub_dampening+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import type { SearchResult, AdjacencyRow, HybridSearchMeta } from '../../src/core/types.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import {+ dampenBoost,+ hubDampeningHashPart,+ hubWeight,+ normalizeHubDampening,+} from '../../src/core/search/hub-dampening.ts';+import { applyBacklinkBoost, hybridSearch } from '../../src/core/search/hybrid.ts';+import { applyGraphSignals, ADJACENCY_BOOST, CROSS_SOURCE_BOOST } from '../../src/core/search/graph-signals.ts';+import { knobsHash, resolveSearchMode, loadOverridesFromConfig } from '../../src/core/search/mode.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';++function row(slug: string, score: number, page_id: number): SearchResult {+ return {+ slug, page_id, title: slug, type: 'note' as const, chunk_text: slug,+ chunk_source: 'compiled_truth', chunk_id: page_id * 1000, chunk_index: 0, score, stale: false, source_id: 'default',+ };+}++describe('hubWeight', () => {+ test('degree <= 1 keeps the full lift; H + 1 halves it; 3H + 1 keeps 10%', () => {+ expect(hubWeight(0, 100)).toBe(1);+ expect(hubWeight(1, 100)).toBe(1);+ expect(hubWeight(101, 100)).toBeCloseTo(0.5, 12);+ expect(hubWeight(301, 100)).toBeCloseTo(0.1, 12);+ });++ test('off, undefined and invalid half degrees mean no dampening', () => {+ expect(hubWeight(10_000, 'off')).toBe(1);+ expect(hubWeight(10_000, undefined)).toBe(1);+ expect(hubWeight(10_000, Number.NaN)).toBe(1);+ expect(hubWeight(10_000, -5)).toBe(1);+ });++ test('non-finite degrees are treated as no links', () => {+ expect(hubWeight(Number.NaN, 10)).toBe(1);+ expect(hubWeight(Number.POSITIVE_INFINITY, 10)).toBe(1);+ });++ test('the c = 0.001 setting corresponds to H ≈ 31.6', () => {+ const H = 1 / Math.sqrt(0.001);+ for (const n of [1, 11, 33, 101, 1001]) {+ expect(hubWeight(n, H)).toBeCloseTo(1 / (1 + 0.001 * (n - 1) ** 2), 12);+ }+ });+});++describe('dampenBoost', () => {+ test('scales the excess over 1.0', () => {+ expect(dampenBoost(1.1, 101, 100)).toBeCloseTo(1.05, 12);+ expect(dampenBoost(1.1, 1, 100)).toBe(1.1);+ });+ test('never touches a demotion or a neutral factor', () => {+ expect(dampenBoost(0.95, 10_000, 10)).toBe(0.95);+ expect(dampenBoost(1, 10_000, 10)).toBe(1);+ });+});++describe('normalizeHubDampening', () => {+ test('accepts off spellings and in-range numbers', () => {+ expect(normalizeHubDampening('off')).toBe('off');+ expect(normalizeHubDampening('OFF')).toBe('off');+ expect(normalizeHubDampening('none')).toBe('off');+ expect(normalizeHubDampening(false)).toBe('off');+ expect(normalizeHubDampening(200)).toBe(200);+ expect(normalizeHubDampening('600')).toBe(600);+ });+ test('rejects everything else as unset', () => {+ for (const v of [0, -1, 0.5, 2_000_000, Number.NaN, Number.POSITIVE_INFINITY, '', 'abc', null, undefined, {}, true]) {+ expect(normalizeHubDampening(v)).toBeUndefined();+ }+ });+ test('hash part is stable', () => {+ expect(hubDampeningHashPart('off')).toBe('off');+ expect(hubDampeningHashPart(200)).toBe('200.000');+ });+});++describe('applyBacklinkBoost with hub dampening', () => {+ test('off is byte-identical to the undampened factor and stamps the count', () => {+ const a = [row('a', 1, 1)];+ const b = [row('a', 1, 1)];+ const counts = new Map([[1, 5000]]);+ applyBacklinkBoost(a, counts);+ applyBacklinkBoost(b, counts, undefined, 'off');+ expect(b[0].score).toBe(a[0].score);+ expect(b[0].backlink_boost).toBe(a[0].backlink_boost);+ expect(b[0].backlink_count).toBe(5000);+ expect(b[0].backlink_hub_weight).toBeUndefined();+ });++ test('a hub loses most of its lift; a low-degree page keeps it', () => {+ const results = [row('hub', 1, 1), row('leaf', 1, 2)];+ const counts = new Map([[1, 20_000], [2, 3]]);+ applyBacklinkBoost(results, counts, undefined, 100);+ const [hub, leaf] = results;+ expect(hub.backlink_hub_weight).toBeLessThan(0.001);+ expect(hub.score).toBeLessThan(1.001);+ expect(leaf.backlink_hub_weight).toBeCloseTo(hubWeight(3, 100), 12);+ expect(leaf.score).toBeCloseTo(1 + 0.05 * Math.log(4) * hubWeight(3, 100), 12);+ expect(leaf.score).toBeGreaterThan(hub.score);+ });+});++describe('applyGraphSignals with hub dampening', () => {+ const ENGINE_STUB = {} as BrainEngine;+ test('adjacency and cross-source lifts scale by the degree weight', async () => {+ const results = [row('people/a', 10, 1), row('companies/hub', 9, 2), row('companies/leaf', 8, 3)];+ const adjacency = new Map<number, AdjacencyRow>([+ [2, { hits: 3, cross_source_hits: 2 }],+ [3, { hits: 3, cross_source_hits: 0 }],+ ]);+ let dampened = -1;+ await applyGraphSignals(results, ENGINE_STUB, {+ enabled: true,+ adjacencyFn: async () => adjacency,+ hubHalfDegree: 100,+ degrees: new Map([[2, 101], [3, 1]]),+ onHubDampened: (n) => { dampened = n; },+ });+ const hub = results.find(r => r.slug === 'companies/hub')!;+ const leaf = results.find(r => r.slug === 'companies/leaf')!;+ expect(hub.graph_adjacency_boost).toBeCloseTo(1 + (ADJACENCY_BOOST - 1) * 0.5, 12);+ expect(hub.graph_cross_source_boost).toBeCloseTo(1 + (CROSS_SOURCE_BOOST - 1) * 0.5, 12);+ expect(hub.graph_hub_weight).toBeCloseTo(0.5, 12);+ expect(hub.score).toBeCloseTo(9 * hub.graph_adjacency_boost! * hub.graph_cross_source_boost!, 10);+ expect(leaf.graph_adjacency_boost).toBe(ADJACENCY_BOOST);+ expect(leaf.graph_hub_weight).toBeUndefined();+ expect(dampened).toBe(1);+ });++ test('without a degree map the lifts are undampened', async () => {+ const results = [row('people/a', 10, 1), row('companies/hub', 9, 2)];+ await applyGraphSignals(results, ENGINE_STUB, {+ enabled: true,+ adjacencyFn: async () => new Map<number, AdjacencyRow>([[2, { hits: 3, cross_source_hits: 0 }]]),+ hubHalfDegree: 10,+ });+ expect(results[1].graph_adjacency_boost).toBe(ADJACENCY_BOOST);+ });+});++describe('search.hub_dampening knob resolution', () => {+ test('config key parses through the one contract; bundles default off', () => {+ expect(resolveSearchMode({ mode: 'balanced' }).hub_dampening).toBe('off');+ const overrides = loadOverridesFromConfig({ 'search.hub_dampening': '200' });+ expect(overrides.hub_dampening).toBe(200);+ expect(loadOverridesFromConfig({ 'search.hub_dampening': 'garbage' }).hub_dampening).toBeUndefined();+ expect(resolveSearchMode({ mode: 'balanced', overrides }).hub_dampening).toBe(200);+ expect(resolveSearchMode({ mode: 'balanced', overrides, perCall: { hub_dampening: 'off' } }).hub_dampening).toBe('off');+ });++ test('off keeps every existing cache key; a half degree changes it', () => {+ const off = resolveSearchMode({ mode: 'balanced' });+ const on = resolveSearchMode({ mode: 'balanced', perCall: { hub_dampening: 200 } });+ const { hub_dampening: _drop, ...legacy } = off;+ expect(knobsHash(off)).toBe(knobsHash(legacy as typeof off));+ expect(knobsHash(on)).not.toBe(knobsHash(off));+ });+});++describe('hybridSearch wire (PGLite, keyless)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ await importFromContent(engine, 'companies/hubco', 'hubco widget platform overview widget', { noEmbed: true });+ await importFromContent(engine, 'concepts/widget-pricing', 'widget pricing notes widget widget', { noEmbed: true });+ const links = [];+ for (let i = 0; i < 40; i++) {+ await importFromContent(engine, `meetings/m-${i}`, `routine sync ${i}`, { noEmbed: true });+ links.push({ from_slug: `meetings/m-${i}`, to_slug: 'companies/hubco', link_type: 'mentions_company' });+ }+ await engine.addLinksBatch(links);+ });+ afterAll(async () => { if (engine) await engine.disconnect(); });++ async function run(hubDampening: 'off' | number) {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearch(engine, 'widget', { limit: 5, hubDampening, onMeta: (m: HybridSearchMeta) => { meta = m; } } as never);+ return { results, meta };+ }++ test('dampening reduces the hub page backlink lift and stamps meta', async () => {+ const off = await run('off');+ const on = await run(10);+ const hubOff = off.results.find(r => r.slug === 'companies/hubco')!;+ const hubOn = on.results.find(r => r.slug === 'companies/hubco')!;+ expect(hubOff.backlink_count).toBe(40);+ expect(hubOn.backlink_hub_weight).toBeCloseTo(hubWeight(40, 10), 12);+ expect(hubOn.backlink_boost!).toBeLessThan(hubOff.backlink_boost!);+ expect(off.meta?.hub_dampening?.half_degree).toBe('off');+ expect(off.meta?.hub_dampening?.backlink_dampened).toBe(0);+ expect(on.meta?.hub_dampening?.half_degree).toBe(10);+ expect(on.meta?.hub_dampening?.backlink_dampened).toBeGreaterThan(0);+ });+});