pi-mega-compact 0.11.5 → 0.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/extensions/dashboard-server/api-contracts/cache-stripes.js +8 -0
- package/dist/extensions/dashboard-server/api-contracts/endpoints.js +13 -0
- package/dist/extensions/dashboard-server/api-contracts/memory-map.js +1 -0
- package/dist/extensions/dashboard-server/routes-cache.js +28 -0
- package/dist/extensions/dashboard-server/routes-game.js +3 -0
- package/dist/extensions/dashboard-server/routes-memory-map.js +50 -0
- package/dist/extensions/dashboard-server/routes-setup.js +105 -0
- package/dist/extensions/dashboard-server/routes.js +3 -1
- package/dist/extensions/dashboard-server/server.js +7 -1
- package/dist/extensions/mega-compact.js +5 -0
- package/dist/extensions/mega-config.js +5 -0
- package/dist/extensions/mega-events/context-handler.js +10 -2
- package/dist/extensions/mega-events/perf-handler.js +83 -1
- package/dist/extensions/mega-events/separated-prompt.js +248 -0
- package/dist/extensions/mega-runtime/env-loader.js +56 -0
- package/dist/extensions/mega-runtime/reset-runtime.js +1 -0
- package/dist/extensions/mega-runtime/runtime-snapshot.js +1 -0
- package/dist/extensions/mega-runtime/runtime.js +1 -0
- package/dist/extensions/mega-runtime/snapshot.js +1 -0
- package/dist/extensions/mega-runtime/widget.js +5 -0
- package/dist/src/cache-stripe-impl.js +288 -0
- package/dist/src/cache-stripe.js +11 -0
- package/dist/src/config/stopwords.js +24 -0
- package/dist/src/config.js +17 -0
- package/dist/src/memoryGraph.js +299 -0
- package/dist/src/monitoring.js +13 -0
- package/dist/src/queryExpansion.js +163 -0
- package/dist/src/queryReformulation/cache.js +123 -0
- package/dist/src/queryReformulation/rrf.js +29 -0
- package/dist/src/queryReformulation/tfidf.js +61 -0
- package/dist/src/queryReformulation/vagueness.js +33 -0
- package/dist/src/queryReformulation.js +225 -0
- package/dist/src/recallMetrics.js +258 -0
- package/dist/src/store/sqlite/cache-stripes.js +133 -0
- package/dist/src/store/sqlite/fts5-search.js +68 -0
- package/dist/src/store/sqlite/perf-samples.js +1 -0
- package/dist/src/store/sqlite/schema.js +60 -1
- package/dist/src/store/sqlite.js +1 -0
- package/dist/src/store/vectorIndex.js +29 -5
- package/dist/src/tiered-router/types.js +18 -0
- package/dist/src/tieredRouter.js +421 -0
- package/dist/src/vectorStore.js +8 -6
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-BoL7qBOJ.js → AchievementTiles-DR9cLGDL.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-BoL7qBOJ.js.map → AchievementTiles-DR9cLGDL.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-BFDE3HYc.js → AchievementsTab-svNUgJ1e.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-BFDE3HYc.js.map → AchievementsTab-svNUgJ1e.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js +2 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{ConfigTab-DDFE-ckA.js → ConfigTab-CmmWheuW.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ConfigTab-DDFE-ckA.js.map → ConfigTab-CmmWheuW.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-B6UxZ7PM.js → EventsTab-CFE7jLsa.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-B6UxZ7PM.js.map → EventsTab-CFE7jLsa.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/GameTab-CJAX_th_.js +2 -0
- package/extensions/dashboard-client/dist/assets/{GameTab-DehUX-KE.js.map → GameTab-CJAX_th_.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-0GWRt4wn.js → MaintenanceTab-P4SUsvMf.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-0GWRt4wn.js.map → MaintenanceTab-P4SUsvMf.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js +2 -0
- package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{MetricsTab-C3rwMVsN.js → MetricsTab-CHQscixy.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-C3rwMVsN.js.map → MetricsTab-CHQscixy.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-39O9_x5j.js → OverviewTab-DBs4DJdd.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-39O9_x5j.js.map → OverviewTab-DBs4DJdd.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ReposTab-Cfj6Q5sH.js → ReposTab-DeFz76L5.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ReposTab-Cfj6Q5sH.js.map → ReposTab-DeFz76L5.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DXDTCi3r.js → SessionsTab-BWNsj1OB.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DXDTCi3r.js.map → SessionsTab-BWNsj1OB.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js +2 -0
- package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Cw1dJ4e9.js → TimeSavedCard-CiqCOQuL.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Cw1dJ4e9.js.map → TimeSavedCard-CiqCOQuL.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TopicsTab-BAw972BV.js → TopicsTab-BWWQxltv.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TopicsTab-BAw972BV.js.map → TopicsTab-BWWQxltv.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-Cf5mGIdl.js → TurnsTab-CVz4f4-o.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-Cf5mGIdl.js.map → TurnsTab-CVz4f4-o.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/index-CUNn22iV.css +1 -0
- package/extensions/dashboard-client/dist/assets/{index-4gQ7auad.js → index-DrktNOoT.js} +11 -11
- package/extensions/dashboard-client/dist/assets/index-DrktNOoT.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{useSSE-DNgMuyP6.js → useSSE-Bf5LOLSi.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-DNgMuyP6.js.map → useSSE-Bf5LOLSi.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +2 -2
- package/extensions/dashboard-client/src/App.tsx +24 -8
- package/extensions/dashboard-client/src/api/client.ts +15 -0
- package/extensions/dashboard-client/src/components/CacheHitRateTrendCard.tsx +100 -0
- package/extensions/dashboard-client/src/components/StripeDistributionCard.tsx +110 -0
- package/extensions/dashboard-client/src/components/TabBar.tsx +49 -4
- package/extensions/dashboard-client/src/main.tsx +1 -0
- package/extensions/dashboard-client/src/styles/base.css +30 -0
- package/extensions/dashboard-client/src/styles/cache.css +167 -0
- package/extensions/dashboard-client/src/tabs/CacheTab.tsx +75 -13
- package/extensions/dashboard-client/src/tabs/MemoryMapTab.tsx +440 -0
- package/extensions/dashboard-client/src/tabs/SetupTab.tsx +65 -2
- package/extensions/dashboard-server/api-contracts/cache-stripes.ts +49 -0
- package/extensions/dashboard-server/api-contracts/endpoints.ts +31 -1
- package/extensions/dashboard-server/api-contracts/index.ts +16 -1
- package/extensions/dashboard-server/api-contracts/memory-map.ts +50 -0
- package/extensions/dashboard-server/api-contracts/setup.ts +22 -0
- package/extensions/dashboard-server/routes-cache.ts +36 -1
- package/extensions/dashboard-server/routes-game.ts +3 -0
- package/extensions/dashboard-server/routes-memory-map.ts +105 -0
- package/extensions/dashboard-server/routes-setup.ts +112 -0
- package/extensions/dashboard-server/routes.ts +3 -1
- package/extensions/dashboard-server/server.ts +6 -0
- package/extensions/mega-compact.ts +5 -0
- package/extensions/mega-config.ts +17 -0
- package/extensions/mega-events/context-handler.ts +10 -2
- package/extensions/mega-events/perf-handler.ts +111 -1
- package/extensions/mega-events/separated-prompt.ts +329 -0
- package/extensions/mega-runtime/env-loader.ts +55 -0
- package/extensions/mega-runtime/helpers.ts +2 -0
- package/extensions/mega-runtime/reset-runtime.ts +1 -0
- package/extensions/mega-runtime/runtime-snapshot.ts +1 -0
- package/extensions/mega-runtime/runtime.ts +1 -0
- package/extensions/mega-runtime/snapshot.ts +6 -0
- package/extensions/mega-runtime/widget-types.ts +3 -0
- package/extensions/mega-runtime/widget.ts +5 -0
- package/package.json +1 -1
- package/src/cache-stripe-impl.ts +385 -0
- package/src/cache-stripe.ts +18 -0
- package/src/config/stopwords.ts +25 -0
- package/src/config.ts +26 -0
- package/src/memoryGraph.ts +438 -0
- package/src/monitoring.ts +35 -0
- package/src/queryExpansion.ts +206 -0
- package/src/queryReformulation/cache.ts +169 -0
- package/src/queryReformulation/rrf.ts +51 -0
- package/src/queryReformulation/tfidf.ts +79 -0
- package/src/queryReformulation/vagueness.ts +38 -0
- package/src/queryReformulation.ts +355 -0
- package/src/recallMetrics.ts +388 -0
- package/src/store/sqlite/cache-stripes.ts +196 -0
- package/src/store/sqlite/fts5-search.ts +90 -0
- package/src/store/sqlite/perf-samples.ts +3 -1
- package/src/store/sqlite/schema.ts +60 -1
- package/src/store/sqlite.ts +1 -0
- package/src/store/vectorIndex.ts +38 -7
- package/src/tiered-router/types.ts +64 -0
- package/src/tieredRouter.ts +489 -0
- package/src/vectorStore.ts +9 -5
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/GameTab-DehUX-KE.js +0 -2
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js +0 -2
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-4gQ7auad.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +0 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cache.ts — in-memory LRU cache with TTL for query reformulation results (S43A-8).
|
|
3
|
+
*
|
|
4
|
+
* Kept in a separate file to keep queryReformulation.ts under file limits.
|
|
5
|
+
* Also holds the env-constant defaults and the uncalibrated-constant bookkeeping.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// Env-Overridable Defaults (sourced from the main file's constants)
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
function envNum(name: string, def: number): number {
|
|
13
|
+
const v = process.env[name];
|
|
14
|
+
if (v === undefined) return def;
|
|
15
|
+
const n = Number(v);
|
|
16
|
+
return Number.isFinite(n) ? n : def;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const RRF_K = envNum("MEGACOMPACT_RRF_K", 60);
|
|
20
|
+
export const EXPANSION_NEIGHBOR_COUNT = envNum("MEGACOMPACT_EXPANSION_NEIGHBOR_COUNT", 5);
|
|
21
|
+
export const EXPANSION_TOP_TERMS = envNum("MEGACOMPACT_EXPANSION_TOP_TERMS", 5);
|
|
22
|
+
export const VAGUE_MIN_WORDS = envNum("MEGACOMPACT_VAGUE_MIN_WORDS", 3);
|
|
23
|
+
export const VAGUE_VERY_SHORT_WORDS = envNum("MEGACOMPACT_VAGUE_VERY_SHORT_WORDS", 2);
|
|
24
|
+
export const QUERY_REFORM_CACHE_TTL_SECONDS = envNum("MEGACOMPACT_QUERY_REFORM_CACHE_TTL_SECONDS", 300);
|
|
25
|
+
export const CACHE_MAX_SIZE = envNum("MEGACOMPACT_QUERY_REFORM_CACHE_SIZE", 100);
|
|
26
|
+
const CACHE_STATS_INTERVAL = envNum("MEGACOMPACT_CACHE_STATS_INTERVAL", 100);
|
|
27
|
+
|
|
28
|
+
/** Which constant names are uncalibrated (not backed by a paper/benchmark). */
|
|
29
|
+
const UNCALIBRATED_NAMES: ReadonlySet<string> = new Set([
|
|
30
|
+
"EXPANSION_NEIGHBOR_COUNT",
|
|
31
|
+
"EXPANSION_TOP_TERMS",
|
|
32
|
+
"VAGUE_MIN_WORDS",
|
|
33
|
+
"VAGUE_VERY_SHORT_WORDS",
|
|
34
|
+
"QUERY_REFORM_CACHE_TTL_SECONDS",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Which calibrated defaults are at their fallback (uncalibrated set)
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
export interface ReformulationConfig {
|
|
42
|
+
neighborCount: number;
|
|
43
|
+
topTerms: number;
|
|
44
|
+
vagueMinWords: number;
|
|
45
|
+
vagueVeryShortWords: number;
|
|
46
|
+
cacheTtlSeconds: number;
|
|
47
|
+
rrfK: number;
|
|
48
|
+
searchLimit: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function computeUncalibrated(opts: ReformulationConfig): string[] {
|
|
52
|
+
const out: string[] = [];
|
|
53
|
+
|
|
54
|
+
if (opts.neighborCount === EXPANSION_NEIGHBOR_COUNT && UNCALIBRATED_NAMES.has("EXPANSION_NEIGHBOR_COUNT")) {
|
|
55
|
+
out.push("EXPANSION_NEIGHBOR_COUNT");
|
|
56
|
+
}
|
|
57
|
+
if (opts.topTerms === EXPANSION_TOP_TERMS && UNCALIBRATED_NAMES.has("EXPANSION_TOP_TERMS")) {
|
|
58
|
+
out.push("EXPANSION_TOP_TERMS");
|
|
59
|
+
}
|
|
60
|
+
if (opts.vagueMinWords === VAGUE_MIN_WORDS && UNCALIBRATED_NAMES.has("VAGUE_MIN_WORDS")) {
|
|
61
|
+
out.push("VAGUE_MIN_WORDS");
|
|
62
|
+
}
|
|
63
|
+
if (opts.vagueVeryShortWords === VAGUE_VERY_SHORT_WORDS && UNCALIBRATED_NAMES.has("VAGUE_VERY_SHORT_WORDS")) {
|
|
64
|
+
out.push("VAGUE_VERY_SHORT_WORDS");
|
|
65
|
+
}
|
|
66
|
+
if (opts.cacheTtlSeconds === QUERY_REFORM_CACHE_TTL_SECONDS && UNCALIBRATED_NAMES.has("QUERY_REFORM_CACHE_TTL_SECONDS")) {
|
|
67
|
+
out.push("QUERY_REFORM_CACHE_TTL_SECONDS");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// Cache (in-memory LRU + TTL)
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
interface ReformulationResult {
|
|
78
|
+
expanded: string;
|
|
79
|
+
original: string;
|
|
80
|
+
neighbors: Array<{ id: string; score: number }>;
|
|
81
|
+
terms: Array<{ term: string; tfIdf: number; df: number }>;
|
|
82
|
+
rrfApplied: boolean;
|
|
83
|
+
fromCache: boolean;
|
|
84
|
+
uncalibrated: string[];
|
|
85
|
+
skipReason?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface CacheEntry {
|
|
89
|
+
result: ReformulationResult;
|
|
90
|
+
cachedAt: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const QUERY_CACHE = new Map<string, CacheEntry>();
|
|
94
|
+
let cacheHits = 0;
|
|
95
|
+
let cacheMisses = 0;
|
|
96
|
+
let cacheEvictions = 0;
|
|
97
|
+
let cacheCounterAtLastLog = 0;
|
|
98
|
+
|
|
99
|
+
/** Read (and reset) cache stats. Used by the logger for periodic reporting. */
|
|
100
|
+
export function readCacheStats(): { hits: number; misses: number; evictions: number } {
|
|
101
|
+
const out = { hits: cacheHits, misses: cacheMisses, evictions: cacheEvictions };
|
|
102
|
+
// Prevent unbounded growth of the delta-tracking state
|
|
103
|
+
cacheHits = 0;
|
|
104
|
+
cacheMisses = 0;
|
|
105
|
+
cacheEvictions = 0;
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function cacheGet(query: string, ttlMs: number): ReformulationResult | undefined {
|
|
110
|
+
const entry = QUERY_CACHE.get(query);
|
|
111
|
+
if (!entry) {
|
|
112
|
+
cacheMisses++;
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
if (Date.now() - entry.cachedAt > ttlMs) {
|
|
116
|
+
QUERY_CACHE.delete(query);
|
|
117
|
+
cacheEvictions++;
|
|
118
|
+
cacheMisses++;
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
cacheHits++;
|
|
122
|
+
return { ...entry.result, fromCache: true };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function cacheSet(query: string, result: ReformulationResult): void {
|
|
126
|
+
// Evict oldest if over capacity
|
|
127
|
+
if (QUERY_CACHE.size >= CACHE_MAX_SIZE) {
|
|
128
|
+
let oldestKey: string | undefined;
|
|
129
|
+
let oldestTime = Infinity;
|
|
130
|
+
for (const [key, entry] of QUERY_CACHE) {
|
|
131
|
+
if (entry.cachedAt < oldestTime) {
|
|
132
|
+
oldestTime = entry.cachedAt;
|
|
133
|
+
oldestKey = key;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (oldestKey) {
|
|
137
|
+
QUERY_CACHE.delete(oldestKey);
|
|
138
|
+
cacheEvictions++;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
QUERY_CACHE.set(query, {
|
|
143
|
+
result: { ...result, fromCache: false },
|
|
144
|
+
cachedAt: Date.now(),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function logCacheStats(log: { info: (event: string, fields?: Record<string, unknown>) => void }): void {
|
|
149
|
+
// Use the stable readCacheStats + reset
|
|
150
|
+
const stats = readCacheStats();
|
|
151
|
+
const total = stats.hits + stats.misses;
|
|
152
|
+
if (total === 0) return;
|
|
153
|
+
log.info("query_reformulation_cache_stats", {
|
|
154
|
+
hits: stats.hits,
|
|
155
|
+
misses: stats.misses,
|
|
156
|
+
evictions: stats.evictions,
|
|
157
|
+
hitRate: total > 0 ? stats.hits / total : 0,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function maybeLogCacheStats(
|
|
162
|
+
log?: { info: (event: string, fields?: Record<string, unknown>) => void },
|
|
163
|
+
): void {
|
|
164
|
+
if (!log) return;
|
|
165
|
+
const total = cacheHits + cacheMisses;
|
|
166
|
+
if (total - cacheCounterAtLastLog < CACHE_STATS_INTERVAL) return;
|
|
167
|
+
cacheCounterAtLastLog = total;
|
|
168
|
+
logCacheStats(log);
|
|
169
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rrf.ts — Reciprocal Rank Fusion (RRF) for merging ranked lists (S43A-7).
|
|
3
|
+
*
|
|
4
|
+
* Pure function: takes multiple ranked lists and returns a single fused ranking
|
|
5
|
+
* using the standard RRF formula.
|
|
6
|
+
*
|
|
7
|
+
* Reference: Cormack, G.V., Clarke, C.L.A., Buettcher, S. "Reciprocal Rank
|
|
8
|
+
* Fusion Outperforms Condorcet and Individual Rank Learning Methods."
|
|
9
|
+
* SIGIR 2009.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Items with their original rank position (1-based).
|
|
14
|
+
*/
|
|
15
|
+
export interface RankedItem {
|
|
16
|
+
id: string;
|
|
17
|
+
rank: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Items with fused RRF score.
|
|
22
|
+
*/
|
|
23
|
+
export interface FusedItem {
|
|
24
|
+
id: string;
|
|
25
|
+
score: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Reciprocal Rank Fusion — merge multiple ranked lists into a single score.
|
|
30
|
+
* Uses the standard RRF formula: score(id) = sum(1 / (k + rank_i(id))).
|
|
31
|
+
*
|
|
32
|
+
* k defaults to 60 — the canonical value from Cormack et al. 2009.
|
|
33
|
+
* Higher k reduces the impact of high rankings; lower k gives more weight to
|
|
34
|
+
* top-ranked items.
|
|
35
|
+
*/
|
|
36
|
+
export function reciprocalRankFusion(
|
|
37
|
+
lists: RankedItem[][],
|
|
38
|
+
k: number = 60,
|
|
39
|
+
): FusedItem[] {
|
|
40
|
+
const scores = new Map<string, number>();
|
|
41
|
+
|
|
42
|
+
for (const list of lists) {
|
|
43
|
+
for (const item of list) {
|
|
44
|
+
scores.set(item.id, (scores.get(item.id) ?? 0) + 1 / (k + item.rank));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return [...scores.entries()]
|
|
49
|
+
.map(([id, score]) => ({ id, score }))
|
|
50
|
+
.sort((a, b) => b.score - a.score);
|
|
51
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tfidf.ts — TF-IDF term extraction from neighbor documents (S43A-6).
|
|
3
|
+
*
|
|
4
|
+
* Extracts the highest-IDF-weighted terms from a set of neighbor documents
|
|
5
|
+
* for query expansion.
|
|
6
|
+
*
|
|
7
|
+
* Term frequency = raw count of the term in the neighbor document (normalized
|
|
8
|
+
* by document length for cross-doc comparability).
|
|
9
|
+
* Inverse document frequency = log(N / df) where N = total docs in corpus.
|
|
10
|
+
*
|
|
11
|
+
* This is NOT a stopword list: frequent terms like "the" naturally get a low
|
|
12
|
+
* IDF and rank below rare terms like "jwt" even when both have similar TF.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export interface CorpusStats {
|
|
16
|
+
totalDocs: number;
|
|
17
|
+
docFreq: (term: string) => number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface NeighborText {
|
|
21
|
+
id: string;
|
|
22
|
+
text: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Extract the top-N terms by TF-IDF weight from the given neighbor documents.
|
|
27
|
+
*
|
|
28
|
+
* Returns an empty array when:
|
|
29
|
+
* - neighbors list is empty
|
|
30
|
+
* - totalDocs <= 0
|
|
31
|
+
* - no terms survive filtering (all numeric, all single-char, etc.)
|
|
32
|
+
*/
|
|
33
|
+
export function extractExpansionTerms(
|
|
34
|
+
neighbors: NeighborText[],
|
|
35
|
+
corpus: CorpusStats,
|
|
36
|
+
topTerms: number,
|
|
37
|
+
): Array<{ term: string; tfIdf: number; df: number }> {
|
|
38
|
+
if (neighbors.length === 0) return [];
|
|
39
|
+
const { totalDocs, docFreq } = corpus;
|
|
40
|
+
if (totalDocs <= 0) return [];
|
|
41
|
+
|
|
42
|
+
// Aggregate term frequency across all neighbor documents
|
|
43
|
+
const termTf = new Map<string, number>();
|
|
44
|
+
|
|
45
|
+
for (const neighbor of neighbors) {
|
|
46
|
+
const words = neighbor.text.toLowerCase().split(/\W+/).filter(Boolean);
|
|
47
|
+
if (words.length === 0) continue;
|
|
48
|
+
|
|
49
|
+
// Normalize TF by document length so longer docs don't dominate
|
|
50
|
+
const lenNorm = words.length;
|
|
51
|
+
|
|
52
|
+
for (const word of words) {
|
|
53
|
+
// Skip pure number tokens (short numbers)
|
|
54
|
+
if (/^\d+$/.test(word) && word.length <= 4) continue;
|
|
55
|
+
// Skip single characters
|
|
56
|
+
if (word.length < 2) continue;
|
|
57
|
+
|
|
58
|
+
// Accumulate across neighbors (multiple docs amplify a term's importance)
|
|
59
|
+
termTf.set(word, (termTf.get(word) ?? 0) + (1 / lenNorm));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Compute TF-IDF for each term
|
|
64
|
+
const scored: Array<{ term: string; tfIdf: number; df: number }> = [];
|
|
65
|
+
|
|
66
|
+
for (const [term, tf] of termTf) {
|
|
67
|
+
const df = docFreq(term);
|
|
68
|
+
// IDF = ln(1 + (N - df + 0.5) / (df + 0.5)) — smooth version
|
|
69
|
+
const idf = Math.log(1 + (totalDocs - df + 0.5) / (df + 0.5));
|
|
70
|
+
const tfIdf = tf * idf;
|
|
71
|
+
if (tfIdf > 0) {
|
|
72
|
+
scored.push({ term, tfIdf, df });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Sort by TF-IDF descending, take top N
|
|
77
|
+
scored.sort((a, b) => b.tfIdf - a.tfIdf);
|
|
78
|
+
return scored.slice(0, topTerms);
|
|
79
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vagueness.ts — heuristic vagueness detection for S43 query reformulation.
|
|
3
|
+
*
|
|
4
|
+
* Detects whether a query is "vague" enough to benefit from reformulation.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Heuristic: is this query "vague" enough to benefit from reformulation?
|
|
9
|
+
* Returns true if the query is short, question-like, or lacks specific terms.
|
|
10
|
+
*
|
|
11
|
+
* ANY match -> vague:
|
|
12
|
+
* a) Total words <= `vagueMinWords` (e.g. "what about auth")
|
|
13
|
+
* b) Contains a question word AND total words <= `vagueVeryShortWords`
|
|
14
|
+
*
|
|
15
|
+
* NOTE: Misclassification is low-cost: a specific query that's wrongly expanded
|
|
16
|
+
* just gets a slightly broader search; a vague query that's wrongly skipped
|
|
17
|
+
* just gets the raw-query search (today's behavior).
|
|
18
|
+
*/
|
|
19
|
+
export function isVagueQuery(
|
|
20
|
+
query: string,
|
|
21
|
+
opts: { vagueMinWords: number; vagueVeryShortWords: number },
|
|
22
|
+
): boolean {
|
|
23
|
+
const cleaned = query.replace(/[^\w\s]/g, "").trim();
|
|
24
|
+
if (!cleaned) return true; // empty or punctuation-only query is vague
|
|
25
|
+
|
|
26
|
+
const words = cleaned.split(/\s+/).filter(Boolean);
|
|
27
|
+
const wordCount = words.length;
|
|
28
|
+
|
|
29
|
+
// Rule a: very short query
|
|
30
|
+
if (wordCount <= opts.vagueMinWords) return true;
|
|
31
|
+
|
|
32
|
+
// Rule b: contains a question word AND is short-ish
|
|
33
|
+
const questionWords = /^(what|why|how|when|where|who|which|does|did|is|are|was|were|can|could|would|should)\b/i;
|
|
34
|
+
const hasQuestionWord = words.some((w) => questionWords.test(w));
|
|
35
|
+
if (hasQuestionWord && wordCount <= opts.vagueVeryShortWords) return true;
|
|
36
|
+
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* queryReformulation.ts — fully local, zero-LLM query reformulation for vague
|
|
3
|
+
* recall queries (S43).
|
|
4
|
+
*
|
|
5
|
+
* Shell: delegates TF-IDF extraction to queryReformulation/tfidf.ts and
|
|
6
|
+
* vagueness detection to queryReformulation/vagueness.ts. Orchestrates the
|
|
7
|
+
* pipeline here.
|
|
8
|
+
*
|
|
9
|
+
* Pipeline:
|
|
10
|
+
* 1. Embed the raw query via the project's default TrigramEmbedder.
|
|
11
|
+
* 2. Linear-scan the real `context_chunks` store for top-N cosine neighbors.
|
|
12
|
+
* 3. Extract high-IDF terms from those neighbors (real TF-IDF, no stopword
|
|
13
|
+
* list — high-frequency terms naturally get low IDF).
|
|
14
|
+
* 4. Expand the query with the top-IDF terms.
|
|
15
|
+
* 5. Re-embed the expanded query and fuse both ranked lists via RRF.
|
|
16
|
+
*
|
|
17
|
+
* Pi-agnostic: no pi runtime types. Pure src/ module.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { isVagueQuery } from "./queryReformulation/vagueness.js";
|
|
21
|
+
import { extractExpansionTerms } from "./queryReformulation/tfidf.js";
|
|
22
|
+
import { reciprocalRankFusion } from "./queryReformulation/rrf.js";
|
|
23
|
+
import {
|
|
24
|
+
cacheGet,
|
|
25
|
+
cacheSet,
|
|
26
|
+
maybeLogCacheStats,
|
|
27
|
+
computeUncalibrated,
|
|
28
|
+
QUERY_REFORM_CACHE_TTL_SECONDS,
|
|
29
|
+
EXPANSION_NEIGHBOR_COUNT,
|
|
30
|
+
EXPANSION_TOP_TERMS,
|
|
31
|
+
VAGUE_MIN_WORDS,
|
|
32
|
+
VAGUE_VERY_SHORT_WORDS,
|
|
33
|
+
RRF_K,
|
|
34
|
+
} from "./queryReformulation/cache.js";
|
|
35
|
+
import type { ReformulationConfig } from "./queryReformulation/cache.js";
|
|
36
|
+
import type { Vector } from "./embedder.js";
|
|
37
|
+
|
|
38
|
+
export { isVagueQuery } from "./queryReformulation/vagueness.js";
|
|
39
|
+
export { extractExpansionTerms } from "./queryReformulation/tfidf.js";
|
|
40
|
+
export { reciprocalRankFusion, type RankedItem } from "./queryReformulation/rrf.js";
|
|
41
|
+
export { readCacheStats } from "./queryReformulation/cache.js";
|
|
42
|
+
export type { FusedItem } from "./queryReformulation/rrf.js";
|
|
43
|
+
export type { ReformulationConfig } from "./queryReformulation/cache.js";
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// Public Types
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
export interface ReformulationResult {
|
|
50
|
+
/** The expanded query string (equals `original` when no expansion happened). */
|
|
51
|
+
expanded: string;
|
|
52
|
+
/** The original query (always preserved). */
|
|
53
|
+
original: string;
|
|
54
|
+
/** Neighbor chunks that contributed expansion terms (empty when skipped). */
|
|
55
|
+
neighbors: Array<{ id: string; score: number }>;
|
|
56
|
+
/** Top weighted terms from TF-IDF over neighbors (empty when skipped). */
|
|
57
|
+
terms: Array<{ term: string; tfIdf: number; df: number }>;
|
|
58
|
+
/** Whether RRF fusion was applied (false = raw-query-only path). */
|
|
59
|
+
rrfApplied: boolean;
|
|
60
|
+
/** Whether this result came from the in-memory cache. */
|
|
61
|
+
fromCache: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* List of config-constant names that were at their default (uncalibrated)
|
|
64
|
+
* values when this reformulation ran. Never includes RRF_K.
|
|
65
|
+
*/
|
|
66
|
+
uncalibrated: string[];
|
|
67
|
+
/** Reasoning label when skipped ("not_vague", "empty_corpus", "thin_corpus"). */
|
|
68
|
+
skipReason?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface CorpusStats {
|
|
72
|
+
totalDocs: number;
|
|
73
|
+
docFreq: (term: string) => number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface EmbedderLike {
|
|
77
|
+
readonly dim: number;
|
|
78
|
+
embed(text: string): Vector;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Scanner: given an embedding vector, return top-N nearest neighbor ids + scores. */
|
|
82
|
+
export type NeighborScanner = (
|
|
83
|
+
embedding: Vector,
|
|
84
|
+
limit: number,
|
|
85
|
+
) => Array<{ id: string; score: number }>;
|
|
86
|
+
|
|
87
|
+
/** Simple search: run a query, return id+score pairs. */
|
|
88
|
+
export type SimpleSearch = (
|
|
89
|
+
query: string,
|
|
90
|
+
limit: number,
|
|
91
|
+
) => Array<{ id: string; score: number }>;
|
|
92
|
+
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// Embedding Neighbor Finder (S43A-5)
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Find the top-N nearest neighbor chunks by real cosine similarity over the
|
|
99
|
+
* real `context_chunks` store. Uses the provided embedder + scan function.
|
|
100
|
+
*/
|
|
101
|
+
export function findExpansionNeighbors(
|
|
102
|
+
query: string,
|
|
103
|
+
embedder: EmbedderLike,
|
|
104
|
+
scan: NeighborScanner,
|
|
105
|
+
neighborCount: number,
|
|
106
|
+
): Array<{ id: string; score: number }> {
|
|
107
|
+
const embedding = embedder.embed(query);
|
|
108
|
+
if (embedding.length === 0) return [];
|
|
109
|
+
return scan(embedding, neighborCount);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// Build Expanded Query
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Build an expanded query by appending the top IDF-weighted terms from the
|
|
118
|
+
* expansion neighbors to the original query. Simple concatenation: the
|
|
119
|
+
* expanded string is `"originalQuery topTerm1 topTerm2 ..."`.
|
|
120
|
+
*/
|
|
121
|
+
export function buildExpandedQuery(
|
|
122
|
+
original: string,
|
|
123
|
+
terms: Array<{ term: string }>,
|
|
124
|
+
maxTerms: number = EXPANSION_TOP_TERMS,
|
|
125
|
+
): string {
|
|
126
|
+
if (terms.length === 0) return original;
|
|
127
|
+
const extra = terms.slice(0, maxTerms).map((t) => t.term).join(" ");
|
|
128
|
+
return `${original} ${extra}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// Public API: reformulateQuery (S43A-9)
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Reformulate a query using the fully local pipeline:
|
|
137
|
+
* 1. Check cache (TTL-gated)
|
|
138
|
+
* 2. Check vagueness — skip if not vague
|
|
139
|
+
* 3. Find embedding neighbors
|
|
140
|
+
* 4. Extract TF-IDF terms from neighbor texts
|
|
141
|
+
* 5. Build expanded query
|
|
142
|
+
* 6. Optionally re-embed and search (caller handles RRF fusion)
|
|
143
|
+
*
|
|
144
|
+
* Error contract:
|
|
145
|
+
* - If the embedder throws OR the scan fails: the error propagates to the
|
|
146
|
+
* caller (NOT caught here). The caller is responsible for the
|
|
147
|
+
* `query_reformulation_failed` event + fallback to raw query.
|
|
148
|
+
* - If the corpus is empty: returns raw query with rrfApplied: false and
|
|
149
|
+
* skipReason: "empty_corpus".
|
|
150
|
+
* - If the corpus is too thin (< 2 neighbors): returns raw query with
|
|
151
|
+
* rrfApplied: false and skipReason: "thin_corpus".
|
|
152
|
+
* - If the query is not vague: returns raw query with rrfApplied: false and
|
|
153
|
+
* skipReason: "not_vague".
|
|
154
|
+
*/
|
|
155
|
+
export function reformulateQuery(
|
|
156
|
+
query: string,
|
|
157
|
+
embedder: EmbedderLike,
|
|
158
|
+
scan: NeighborScanner,
|
|
159
|
+
corpus: CorpusStats,
|
|
160
|
+
neighborTexts: (ids: string[]) => Array<{ id: string; text: string }>,
|
|
161
|
+
opts: Partial<ReformulationConfig> = {},
|
|
162
|
+
log?: { info: (event: string, fields?: Record<string, unknown>) => void; warn: (event: string, fields?: Record<string, unknown>) => void; error: (event: string, fields?: Record<string, unknown>) => void },
|
|
163
|
+
): { result: ReformulationResult; rawNeighbors: Array<{ id: string; score: number }>; rawTerms: Array<{ id: string; text: string }> } {
|
|
164
|
+
const config: ReformulationConfig = {
|
|
165
|
+
neighborCount: opts.neighborCount ?? EXPANSION_NEIGHBOR_COUNT,
|
|
166
|
+
topTerms: opts.topTerms ?? EXPANSION_TOP_TERMS,
|
|
167
|
+
vagueMinWords: opts.vagueMinWords ?? VAGUE_MIN_WORDS,
|
|
168
|
+
vagueVeryShortWords: opts.vagueVeryShortWords ?? VAGUE_VERY_SHORT_WORDS,
|
|
169
|
+
cacheTtlSeconds: opts.cacheTtlSeconds ?? QUERY_REFORM_CACHE_TTL_SECONDS,
|
|
170
|
+
rrfK: opts.rrfK ?? RRF_K,
|
|
171
|
+
searchLimit: opts.searchLimit ?? 5,
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const ttlMs = config.cacheTtlSeconds * 1000;
|
|
175
|
+
|
|
176
|
+
// 0. Check cache
|
|
177
|
+
const cached = cacheGet(query, ttlMs);
|
|
178
|
+
if (cached) {
|
|
179
|
+
maybeLogCacheStats(log);
|
|
180
|
+
return {
|
|
181
|
+
result: cached,
|
|
182
|
+
rawNeighbors: cached.neighbors,
|
|
183
|
+
rawTerms: cached.neighbors.map((n) => ({ id: n.id, text: "" })),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 1. Vagueness check
|
|
188
|
+
if (!isVagueQuery(query, { vagueMinWords: config.vagueMinWords, vagueVeryShortWords: config.vagueVeryShortWords })) {
|
|
189
|
+
const result: ReformulationResult = {
|
|
190
|
+
expanded: query,
|
|
191
|
+
original: query,
|
|
192
|
+
neighbors: [],
|
|
193
|
+
terms: [],
|
|
194
|
+
rrfApplied: false,
|
|
195
|
+
fromCache: false,
|
|
196
|
+
uncalibrated: computeUncalibrated(config),
|
|
197
|
+
skipReason: "not_vague",
|
|
198
|
+
};
|
|
199
|
+
cacheSet(query, result);
|
|
200
|
+
maybeLogCacheStats(log);
|
|
201
|
+
log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "not_vague" });
|
|
202
|
+
return { result, rawNeighbors: [], rawTerms: [] };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 2. Corpus check
|
|
206
|
+
if (corpus.totalDocs <= 0) {
|
|
207
|
+
const result: ReformulationResult = {
|
|
208
|
+
expanded: query,
|
|
209
|
+
original: query,
|
|
210
|
+
neighbors: [],
|
|
211
|
+
terms: [],
|
|
212
|
+
rrfApplied: false,
|
|
213
|
+
fromCache: false,
|
|
214
|
+
uncalibrated: computeUncalibrated(config),
|
|
215
|
+
skipReason: "empty_corpus",
|
|
216
|
+
};
|
|
217
|
+
cacheSet(query, result);
|
|
218
|
+
maybeLogCacheStats(log);
|
|
219
|
+
log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "empty_corpus" });
|
|
220
|
+
return { result, rawNeighbors: [], rawTerms: [] };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// 3. Find embedding neighbors
|
|
224
|
+
const neighbors = findExpansionNeighbors(query, embedder, scan, config.neighborCount);
|
|
225
|
+
if (neighbors.length < 2) {
|
|
226
|
+
const result: ReformulationResult = {
|
|
227
|
+
expanded: query,
|
|
228
|
+
original: query,
|
|
229
|
+
neighbors,
|
|
230
|
+
terms: [],
|
|
231
|
+
rrfApplied: false,
|
|
232
|
+
fromCache: false,
|
|
233
|
+
uncalibrated: computeUncalibrated(config),
|
|
234
|
+
skipReason: "thin_corpus",
|
|
235
|
+
};
|
|
236
|
+
cacheSet(query, result);
|
|
237
|
+
maybeLogCacheStats(log);
|
|
238
|
+
log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "thin_corpus" });
|
|
239
|
+
return { result, rawNeighbors: neighbors, rawTerms: [] };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 4. Fetch neighbor texts for TF-IDF
|
|
243
|
+
const neighborIds = neighbors.map((n) => n.id);
|
|
244
|
+
const rawTerms = neighborTexts(neighborIds);
|
|
245
|
+
|
|
246
|
+
// 5. Extract expansion terms via TF-IDF
|
|
247
|
+
const expansionTerms = extractExpansionTerms(rawTerms, corpus, config.topTerms);
|
|
248
|
+
if (expansionTerms.length === 0) {
|
|
249
|
+
const result: ReformulationResult = {
|
|
250
|
+
expanded: query,
|
|
251
|
+
original: query,
|
|
252
|
+
neighbors,
|
|
253
|
+
terms: [],
|
|
254
|
+
rrfApplied: false,
|
|
255
|
+
fromCache: false,
|
|
256
|
+
uncalibrated: computeUncalibrated(config),
|
|
257
|
+
skipReason: "thin_corpus",
|
|
258
|
+
};
|
|
259
|
+
cacheSet(query, result);
|
|
260
|
+
maybeLogCacheStats(log);
|
|
261
|
+
log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "thin_corpus" });
|
|
262
|
+
return { result, rawNeighbors: neighbors, rawTerms };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// 6. Build expanded query
|
|
266
|
+
const expanded = buildExpandedQuery(query, expansionTerms, config.topTerms);
|
|
267
|
+
const uncalibrated = computeUncalibrated(config);
|
|
268
|
+
|
|
269
|
+
const result: ReformulationResult = {
|
|
270
|
+
expanded,
|
|
271
|
+
original: query,
|
|
272
|
+
neighbors: neighbors.map((n) => ({ id: n.id, score: n.score })),
|
|
273
|
+
terms: expansionTerms,
|
|
274
|
+
rrfApplied: true,
|
|
275
|
+
fromCache: false,
|
|
276
|
+
uncalibrated,
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
cacheSet(query, result);
|
|
280
|
+
maybeLogCacheStats(log);
|
|
281
|
+
|
|
282
|
+
log?.info("query_reformulation", {
|
|
283
|
+
query: query.slice(0, 80),
|
|
284
|
+
expanded: expanded.slice(0, 120),
|
|
285
|
+
neighborCount: neighbors.length,
|
|
286
|
+
topTerms: expansionTerms.slice(0, 5).map((t) => t.term),
|
|
287
|
+
rrfApplied: true,
|
|
288
|
+
fromCache: false,
|
|
289
|
+
uncalibrated,
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
return { result, rawNeighbors: neighbors, rawTerms };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ---------------------------------------------------------------------------
|
|
296
|
+
// Public API: reformulationSearch (S43A-9b)
|
|
297
|
+
// ---------------------------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
export interface ReformulationSearchResult {
|
|
300
|
+
/** Fused search results (RRF-merged or raw-query-only). */
|
|
301
|
+
fused: Array<{ id: string; score: number }>;
|
|
302
|
+
/** Reformulation metadata. */
|
|
303
|
+
reformulation: ReformulationResult;
|
|
304
|
+
/** Raw-query-only search results (for the S41 quality gate). */
|
|
305
|
+
rawSearchResults: Array<{ id: string; score: number }>;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Full reformulation search pipeline:
|
|
310
|
+
* 1. Reformulate the query (embedding neighbors -> TF-IDF -> expansion).
|
|
311
|
+
* 2. If RRF was applied: run BOTH raw + expanded queries and fuse via RRF.
|
|
312
|
+
* 3. If no RRF: return raw-query results only.
|
|
313
|
+
*/
|
|
314
|
+
export function reformulationSearch(
|
|
315
|
+
query: string,
|
|
316
|
+
embedder: EmbedderLike,
|
|
317
|
+
scan: NeighborScanner,
|
|
318
|
+
corpus: CorpusStats,
|
|
319
|
+
neighborTexts: (ids: string[]) => Array<{ id: string; text: string }>,
|
|
320
|
+
search: SimpleSearch,
|
|
321
|
+
opts: Partial<ReformulationConfig> = {},
|
|
322
|
+
log?: { info: (event: string, fields?: Record<string, unknown>) => void; warn: (event: string, fields?: Record<string, unknown>) => void; error: (event: string, fields?: Record<string, unknown>) => void },
|
|
323
|
+
): ReformulationSearchResult {
|
|
324
|
+
const config: ReformulationConfig = {
|
|
325
|
+
neighborCount: opts.neighborCount ?? EXPANSION_NEIGHBOR_COUNT,
|
|
326
|
+
topTerms: opts.topTerms ?? EXPANSION_TOP_TERMS,
|
|
327
|
+
vagueMinWords: opts.vagueMinWords ?? VAGUE_MIN_WORDS,
|
|
328
|
+
vagueVeryShortWords: opts.vagueVeryShortWords ?? VAGUE_VERY_SHORT_WORDS,
|
|
329
|
+
cacheTtlSeconds: opts.cacheTtlSeconds ?? QUERY_REFORM_CACHE_TTL_SECONDS,
|
|
330
|
+
rrfK: opts.rrfK ?? RRF_K,
|
|
331
|
+
searchLimit: opts.searchLimit ?? 5,
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const { result: reformulation } = reformulateQuery(
|
|
335
|
+
query, embedder, scan, corpus, neighborTexts, opts, log,
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
// Always run the raw query search (needed for the S41 quality gate and as
|
|
339
|
+
// a fallback when RRF is not applied).
|
|
340
|
+
const rawSearchResults = search(query, config.searchLimit);
|
|
341
|
+
|
|
342
|
+
if (!reformulation.rrfApplied) {
|
|
343
|
+
return { fused: rawSearchResults, reformulation, rawSearchResults };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// RRF path: run expanded query search and fuse
|
|
347
|
+
const expandedResults = search(reformulation.expanded, config.searchLimit);
|
|
348
|
+
|
|
349
|
+
const rawRanked = rawSearchResults.map((r, i) => ({ id: r.id, rank: i + 1 }));
|
|
350
|
+
const expandedRanked = expandedResults.map((r, i) => ({ id: r.id, rank: i + 1 }));
|
|
351
|
+
|
|
352
|
+
const fused = reciprocalRankFusion([rawRanked, expandedRanked], config.rrfK);
|
|
353
|
+
|
|
354
|
+
return { fused, reformulation, rawSearchResults };
|
|
355
|
+
}
|