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
package/dist/src/config.js
CHANGED
|
@@ -81,3 +81,20 @@ export function memoryReviewCadence(band, baseInterval) {
|
|
|
81
81
|
default: return base;
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
// S57 RAG Suite feature flags — each maps to MEGACOMPACT_* env var, default OFF
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
function ragFlag(name) {
|
|
88
|
+
const v = process.env[name];
|
|
89
|
+
if (v === undefined)
|
|
90
|
+
return false;
|
|
91
|
+
return v === "true" || v === "1";
|
|
92
|
+
}
|
|
93
|
+
/** B1: Query reformulation (keyword expansion via embedding neighbors). */
|
|
94
|
+
export const RAG_QUERY_REFORMULATION = () => ragFlag("MEGACOMPACT_QUERY_REFORMULATION");
|
|
95
|
+
/** B2: Tiered recall router (L0 cache → L1 FTS5 → L2 HNSW). */
|
|
96
|
+
export const RAG_TIERED_ROUTER = () => ragFlag("MEGACOMPACT_TIERED_ROUTER");
|
|
97
|
+
/** B3: Recall quality metrics (precision/recall scoring + logging). */
|
|
98
|
+
export const RAG_RECALL_METRICS = () => ragFlag("MEGACOMPACT_RECALL_METRICS");
|
|
99
|
+
/** B4: Memory graph traversal (dashboard-oriented). */
|
|
100
|
+
export const RAG_MEMORY_GRAPH = () => ragFlag("MEGACOMPACT_MEMORY_GRAPH");
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memoryGraph.ts — S46 visual memory map: build a graph of graphs.
|
|
3
|
+
*
|
|
4
|
+
* Nodes = checkpoints (with optional RAPTOR level annotations).
|
|
5
|
+
* Edges = temporal adjacency, semantic similarity (cosine above threshold), and
|
|
6
|
+
* RAPTOR parent–child links.
|
|
7
|
+
*
|
|
8
|
+
* pi-agnostic (no pi runtime types). Zero network calls (PREVENT-PI-004).
|
|
9
|
+
* Synchronous read-only interface — non-fatal on store errors.
|
|
10
|
+
*
|
|
11
|
+
* Re-exports the public types as both MemoryGraph* and shorter aliases
|
|
12
|
+
* (GraphNode, GraphEdge, GraphMetadata) so dashboard api-contracts can import
|
|
13
|
+
* from the canonical source.
|
|
14
|
+
*/
|
|
15
|
+
import { getStateDir, normalizeSessionId } from "./store.js";
|
|
16
|
+
import { openStore, decodeEmbedding } from "./store/sqlite/utils.js";
|
|
17
|
+
import { listRaptorNodes } from "./store/sqlite/raptor.js";
|
|
18
|
+
import { Logger } from "./log.js";
|
|
19
|
+
const log = new Logger();
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// Defaults
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
const DEFAULT_SIMILARITY_THRESHOLD = 0.7;
|
|
24
|
+
const DEFAULT_MAX_EDGES_PER_NODE = 4;
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
// Public API
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
/**
|
|
29
|
+
* Build a memory graph from the store.
|
|
30
|
+
*
|
|
31
|
+
* Opens the SQLite store, reads all (or session-filtered) checkpoints,
|
|
32
|
+
* computes cosine similarity edges, temporal edges, and RAPTOR parent edges.
|
|
33
|
+
* Returns a MemoryGraph or an empty graph on failure (non-fatal).
|
|
34
|
+
*/
|
|
35
|
+
export function buildMemoryGraph(opts = {}) {
|
|
36
|
+
const { similarityThreshold = DEFAULT_SIMILARITY_THRESHOLD, maxEdgesPerNode = DEFAULT_MAX_EDGES_PER_NODE, sessionId, stateDir = getStateDir(), includeRaptorEdges = true, includeTemporalEdges = true, } = opts;
|
|
37
|
+
const builtAt = Date.now();
|
|
38
|
+
try {
|
|
39
|
+
const nodes = loadNodes(sessionId, stateDir);
|
|
40
|
+
const nodeIndex = buildNodeIndex(nodes);
|
|
41
|
+
const edges = [];
|
|
42
|
+
// Temporal edges: consecutive checkpoints within the same session
|
|
43
|
+
if (includeTemporalEdges) {
|
|
44
|
+
edges.push(...buildTemporalEdges(nodes));
|
|
45
|
+
}
|
|
46
|
+
// Semantic edges: cosine similarity above threshold
|
|
47
|
+
edges.push(...buildSemanticEdges(nodes, nodeIndex, similarityThreshold, maxEdgesPerNode));
|
|
48
|
+
// RAPTOR parent–child edges
|
|
49
|
+
if (includeRaptorEdges) {
|
|
50
|
+
edges.push(...buildRaptorEdges(nodes, sessionId, stateDir, nodeIndex));
|
|
51
|
+
}
|
|
52
|
+
// Deduplicate edges (keep highest weight for each source-target pair)
|
|
53
|
+
const dedupedEdges = deduplicateEdges(edges);
|
|
54
|
+
// Count sessions
|
|
55
|
+
const sessionSet = new Set();
|
|
56
|
+
for (const n of nodes) {
|
|
57
|
+
sessionSet.add(n.sessionId);
|
|
58
|
+
}
|
|
59
|
+
const meta = {
|
|
60
|
+
sessionCount: sessionSet.size,
|
|
61
|
+
totalCheckpoints: nodes.length,
|
|
62
|
+
totalEdges: dedupedEdges.length,
|
|
63
|
+
semanticEdgeCount: dedupedEdges.filter((e) => e.type === "semantic").length,
|
|
64
|
+
temporalEdgeCount: dedupedEdges.filter((e) => e.type === "temporal").length,
|
|
65
|
+
raptorEdgeCount: dedupedEdges.filter((e) => e.type === "raptor_parent").length,
|
|
66
|
+
similarityThresholdUsed: similarityThreshold,
|
|
67
|
+
builtAt,
|
|
68
|
+
};
|
|
69
|
+
return { nodes, edges: dedupedEdges, metadata: meta };
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
log.warn("buildMemoryGraph failed", { error: String(err) });
|
|
73
|
+
return {
|
|
74
|
+
nodes: [],
|
|
75
|
+
edges: [],
|
|
76
|
+
metadata: {
|
|
77
|
+
sessionCount: 0,
|
|
78
|
+
totalCheckpoints: 0,
|
|
79
|
+
totalEdges: 0,
|
|
80
|
+
semanticEdgeCount: 0,
|
|
81
|
+
temporalEdgeCount: 0,
|
|
82
|
+
raptorEdgeCount: 0,
|
|
83
|
+
similarityThresholdUsed: similarityThreshold,
|
|
84
|
+
builtAt,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
// Node loading
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
function loadNodes(sessionId, stateDir) {
|
|
93
|
+
const db = openStore(stateDir);
|
|
94
|
+
const sql = sessionId
|
|
95
|
+
? "SELECT * FROM context_chunks WHERE session_id = ? ORDER BY id ASC"
|
|
96
|
+
: "SELECT * FROM context_chunks ORDER BY session_id, id ASC";
|
|
97
|
+
const rows = sessionId
|
|
98
|
+
? db.prepare(sql).all(normalizeSessionId(sessionId))
|
|
99
|
+
: db.prepare(sql).all();
|
|
100
|
+
return rows.map(rowToGraphNode);
|
|
101
|
+
}
|
|
102
|
+
function rowToGraphNode(row) {
|
|
103
|
+
const summary = row.summary ?? "";
|
|
104
|
+
return {
|
|
105
|
+
id: row.id,
|
|
106
|
+
sessionId: row.session_id,
|
|
107
|
+
label: row.id,
|
|
108
|
+
summaryTruncated: summary.length > 200 ? summary.slice(0, 197) + "..." : summary,
|
|
109
|
+
tokenEstimate: row.token_estimate ?? 0,
|
|
110
|
+
timestamp: row.created_at ?? Date.now(),
|
|
111
|
+
dedupStatus: row.dedup_status ?? undefined,
|
|
112
|
+
raptorLevel: 0, // enriched below if RAPTOR data exists
|
|
113
|
+
topicSummary: row.topic_summary ?? undefined,
|
|
114
|
+
decisionCount: row.key_decisions
|
|
115
|
+
? safeJsonCount(row.key_decisions)
|
|
116
|
+
: 0,
|
|
117
|
+
textSnippet: summary.length > 200 ? summary.slice(0, 197) + "..." : summary,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Parse a JSON array stored in a text column and return its length. */
|
|
121
|
+
function safeJsonCount(raw) {
|
|
122
|
+
if (!raw)
|
|
123
|
+
return 0;
|
|
124
|
+
try {
|
|
125
|
+
const arr = JSON.parse(raw);
|
|
126
|
+
return Array.isArray(arr) ? arr.length : 0;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return 0;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// Node index building
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
function buildNodeIndex(nodes) {
|
|
136
|
+
const idx = new Map();
|
|
137
|
+
nodes.forEach((n, i) => idx.set(n.id, i));
|
|
138
|
+
return idx;
|
|
139
|
+
}
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
// Edges: temporal
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
function buildTemporalEdges(nodes) {
|
|
144
|
+
const edges = [];
|
|
145
|
+
if (nodes.length < 2)
|
|
146
|
+
return edges;
|
|
147
|
+
let prev = nodes[0];
|
|
148
|
+
for (let i = 1; i < nodes.length; i++) {
|
|
149
|
+
const cur = nodes[i];
|
|
150
|
+
if (cur.sessionId === prev.sessionId) {
|
|
151
|
+
edges.push({
|
|
152
|
+
source: prev.id,
|
|
153
|
+
target: cur.id,
|
|
154
|
+
weight: 1.0,
|
|
155
|
+
type: "temporal",
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
prev = cur;
|
|
159
|
+
}
|
|
160
|
+
return edges;
|
|
161
|
+
}
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
// Edges: semantic (cosine similarity)
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
function buildSemanticEdges(nodes, _nodeIndex, threshold, maxPerNode) {
|
|
166
|
+
if (nodes.length < 2)
|
|
167
|
+
return [];
|
|
168
|
+
const db = openStore();
|
|
169
|
+
// Retrieve embeddings from DB for each node
|
|
170
|
+
const embeddings = new Map();
|
|
171
|
+
const placeholders = nodes.map(() => "?").join(",");
|
|
172
|
+
const ids = nodes.map((n) => n.id);
|
|
173
|
+
const rows = db
|
|
174
|
+
.prepare(`SELECT id, embedding_blob FROM context_chunks WHERE id IN (${placeholders})`)
|
|
175
|
+
.all(...ids);
|
|
176
|
+
for (const row of rows) {
|
|
177
|
+
const emb = decodeEmbedding(row.embedding_blob);
|
|
178
|
+
if (emb.length > 0) {
|
|
179
|
+
embeddings.set(row.id, emb);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const edges = [];
|
|
183
|
+
for (const node of nodes) {
|
|
184
|
+
const aId = node.id;
|
|
185
|
+
const aEmb = embeddings.get(aId);
|
|
186
|
+
if (!aEmb)
|
|
187
|
+
continue;
|
|
188
|
+
const candidates = [];
|
|
189
|
+
for (const other of nodes) {
|
|
190
|
+
if (other.id === aId)
|
|
191
|
+
continue;
|
|
192
|
+
// Skip if already connected via temporal or raptor edge
|
|
193
|
+
const bEmb = embeddings.get(other.id);
|
|
194
|
+
if (!bEmb)
|
|
195
|
+
continue;
|
|
196
|
+
const sim = cosineSimilarity(aEmb, bEmb);
|
|
197
|
+
if (sim >= threshold) {
|
|
198
|
+
candidates.push({ target: other.id, weight: sim });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Keep top-K highest-weight semantic neighbors
|
|
202
|
+
candidates.sort((a, b) => b.weight - a.weight);
|
|
203
|
+
const top = candidates.slice(0, maxPerNode);
|
|
204
|
+
for (const c of top) {
|
|
205
|
+
edges.push({
|
|
206
|
+
source: aId,
|
|
207
|
+
target: c.target,
|
|
208
|
+
weight: c.weight,
|
|
209
|
+
type: "semantic",
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return edges;
|
|
214
|
+
}
|
|
215
|
+
// ---------------------------------------------------------------------------
|
|
216
|
+
// Edges: RAPTOR parent–child
|
|
217
|
+
// ---------------------------------------------------------------------------
|
|
218
|
+
function buildRaptorEdges(nodes, sessionId, stateDir, nodeIndex) {
|
|
219
|
+
const edges = [];
|
|
220
|
+
try {
|
|
221
|
+
if (sessionId) {
|
|
222
|
+
enrichRaptorForSession(sessionId, stateDir, nodeIndex, nodes, edges);
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
// Load all sessions from DB
|
|
226
|
+
const db = openStore(stateDir);
|
|
227
|
+
const sessionRows = db
|
|
228
|
+
.prepare("SELECT DISTINCT session_id FROM raptor_nodes ORDER BY session_id")
|
|
229
|
+
.all();
|
|
230
|
+
for (const row of sessionRows) {
|
|
231
|
+
enrichRaptorForSession(row.session_id, stateDir, nodeIndex, nodes, edges);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
log.warn("RAPTOR edge build failed (non-fatal)", { error: String(err) });
|
|
237
|
+
}
|
|
238
|
+
return edges;
|
|
239
|
+
}
|
|
240
|
+
function enrichRaptorForSession(sessId, stateDir, nodeIndex, nodes, edges) {
|
|
241
|
+
const raptorNodes = listRaptorNodes(sessId, stateDir);
|
|
242
|
+
for (const rn of raptorNodes) {
|
|
243
|
+
const idx = nodeIndex.get(rn.id);
|
|
244
|
+
if (idx !== undefined) {
|
|
245
|
+
// Annotate the graph node with the RAPTOR level
|
|
246
|
+
nodes[idx].raptorLevel = rn.level;
|
|
247
|
+
}
|
|
248
|
+
if (!rn.parentId)
|
|
249
|
+
continue;
|
|
250
|
+
// Only create edge if both nodes are in the graph
|
|
251
|
+
if (nodeIndex.has(rn.id) && nodeIndex.has(rn.parentId)) {
|
|
252
|
+
edges.push({
|
|
253
|
+
source: rn.id,
|
|
254
|
+
target: rn.parentId,
|
|
255
|
+
weight: Math.max(0.1, 1.0 - rn.level * 0.1), // higher levels = weaker link
|
|
256
|
+
type: "raptor_parent",
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
// Edge deduplication
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
function deduplicateEdges(edges) {
|
|
265
|
+
const seen = new Map();
|
|
266
|
+
for (const e of edges) {
|
|
267
|
+
const keyA = `${e.source}|${e.target}`;
|
|
268
|
+
const keyB = `${e.target}|${e.source}`;
|
|
269
|
+
const existing = seen.get(keyA) ?? seen.get(keyB);
|
|
270
|
+
if (!existing) {
|
|
271
|
+
seen.set(keyA, e);
|
|
272
|
+
}
|
|
273
|
+
else if (e.weight > existing.weight) {
|
|
274
|
+
// Replace with higher-weight edge
|
|
275
|
+
seen.delete(keyA);
|
|
276
|
+
seen.delete(keyB);
|
|
277
|
+
seen.set(keyA, e);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return Array.from(seen.values());
|
|
281
|
+
}
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
// Cosine similarity
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
function cosineSimilarity(a, b) {
|
|
286
|
+
const len = Math.min(a.length, b.length);
|
|
287
|
+
if (len === 0)
|
|
288
|
+
return 0;
|
|
289
|
+
let dot = 0;
|
|
290
|
+
let normA = 0;
|
|
291
|
+
let normB = 0;
|
|
292
|
+
for (let i = 0; i < len; i++) {
|
|
293
|
+
dot += a[i] * b[i];
|
|
294
|
+
normA += a[i] * a[i];
|
|
295
|
+
normB += b[i] * b[i];
|
|
296
|
+
}
|
|
297
|
+
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
298
|
+
return denom === 0 ? 0 : dot / denom;
|
|
299
|
+
}
|
package/dist/src/monitoring.js
CHANGED
|
@@ -129,3 +129,16 @@ export function defaultMetricsPath(stateDir = STATE_DIR_DEFAULT) {
|
|
|
129
129
|
export function defaultEventsPath(stateDir = STATE_DIR_DEFAULT) {
|
|
130
130
|
return join(stateDir, "events.log");
|
|
131
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* Append a RecallQualityEvent to events.log (best-effort, non-fatal).
|
|
134
|
+
* Follows the same append-one-JSON-line pattern as logDecision.
|
|
135
|
+
*/
|
|
136
|
+
export function logRecallQuality(path, ev) {
|
|
137
|
+
try {
|
|
138
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
139
|
+
appendFileSync(path, JSON.stringify(ev) + "\n", "utf-8");
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
/* best-effort — never break the extension */
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* queryExpansion.ts — S45 CRAG query expansion via embedding neighbors.
|
|
3
|
+
*
|
|
4
|
+
* Expands a query with synonym/related-term variants by finding embedding-
|
|
5
|
+
* similar checkpoints and extracting their discriminative terms. Fully local:
|
|
6
|
+
* uses the TrigramEmbedder (shipped default, zero network) and in-process
|
|
7
|
+
* cosine scan — no LLM call, no external API. PREVENT-PI-004 compliant.
|
|
8
|
+
*
|
|
9
|
+
* Pi-agnostic: no pi runtime types or imports from `src/`.
|
|
10
|
+
*/
|
|
11
|
+
import { cosineSimilarity, defaultEmbedder } from "./embedder.js";
|
|
12
|
+
import { listCheckpoints } from "./store/sqlite.js";
|
|
13
|
+
const DEFAULT_MAX_TERMS = 5;
|
|
14
|
+
const DEFAULT_MIN_SIM = 0.3;
|
|
15
|
+
/**
|
|
16
|
+
* Tokenize text into lowercased alphanumeric terms, filtering stop words.
|
|
17
|
+
* Internal helper — no export needed outside this module.
|
|
18
|
+
*/
|
|
19
|
+
function tokenizeTerms(text) {
|
|
20
|
+
const STOP_WORDS = new Set([
|
|
21
|
+
"a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for",
|
|
22
|
+
"of", "with", "by", "from", "as", "is", "was", "are", "were", "be",
|
|
23
|
+
"been", "has", "have", "had", "do", "does", "did", "will", "would",
|
|
24
|
+
"could", "should", "may", "might", "shall", "can", "not", "no", "nor",
|
|
25
|
+
"so", "if", "then", "than", "that", "this", "these", "those", "it",
|
|
26
|
+
"its", "i", "me", "my", "we", "our", "you", "your", "he", "she",
|
|
27
|
+
"they", "them", "their", "what", "which", "who", "whom", "when",
|
|
28
|
+
"where", "why", "how", "all", "each", "every", "both", "few", "more",
|
|
29
|
+
"most", "other", "some", "such", "only", "own", "same", "so", "than",
|
|
30
|
+
"too", "very", "just", "about", "above", "after", "again", "against",
|
|
31
|
+
"because", "before", "between", "down", "during", "out", "over",
|
|
32
|
+
"through", "under", "up", "also", "into", "off", "onto", "upon",
|
|
33
|
+
]);
|
|
34
|
+
// Split on non-alphanumeric, lowercase, filter empties and stop words.
|
|
35
|
+
return text
|
|
36
|
+
.toLowerCase()
|
|
37
|
+
.split(/[^a-z0-9]+/)
|
|
38
|
+
.filter((t) => t.length >= 3 && !STOP_WORDS.has(t));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Compute TF-IDF-like term importance scores for a set of documents.
|
|
42
|
+
* Returns a Map from term to score (log-frequency within doc * IDF).
|
|
43
|
+
*/
|
|
44
|
+
function termScores(docs) {
|
|
45
|
+
const docCount = docs.length;
|
|
46
|
+
if (docCount === 0)
|
|
47
|
+
return new Map();
|
|
48
|
+
// Document frequency: how many docs each term appears in.
|
|
49
|
+
const df = new Map();
|
|
50
|
+
const docTerms = docs.map((d) => {
|
|
51
|
+
const terms = tokenizeTerms(d);
|
|
52
|
+
const unique = new Set(terms);
|
|
53
|
+
for (const t of unique) {
|
|
54
|
+
df.set(t, (df.get(t) ?? 0) + 1);
|
|
55
|
+
}
|
|
56
|
+
return terms;
|
|
57
|
+
});
|
|
58
|
+
// Compute TF-IDF score for each term across all docs:
|
|
59
|
+
// score = sum over docs of (tf * idf)
|
|
60
|
+
// tf = term frequency within doc (log-smooth)
|
|
61
|
+
// idf = log(1 + docCount / (1 + docFreq))
|
|
62
|
+
const scores = new Map();
|
|
63
|
+
for (let i = 0; i < docTerms.length; i++) {
|
|
64
|
+
const terms = docTerms[i];
|
|
65
|
+
const tf = new Map();
|
|
66
|
+
for (const t of terms)
|
|
67
|
+
tf.set(t, (tf.get(t) ?? 0) + 1);
|
|
68
|
+
for (const [t, count] of tf) {
|
|
69
|
+
const tfVal = 1 + Math.log10(count);
|
|
70
|
+
const docFreq = df.get(t) ?? 1;
|
|
71
|
+
const idf = Math.log10(1 + docCount / (1 + docFreq));
|
|
72
|
+
scores.set(t, (scores.get(t) ?? 0) + tfVal * idf);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return scores;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Expand a query with related terms discovered from embedding-neighbor
|
|
79
|
+
* checkpoints. Uses TF-IDF term extraction from the most similar checkpoints
|
|
80
|
+
* to find novel, discriminative terms not already in the query.
|
|
81
|
+
*
|
|
82
|
+
* @param query The original search query.
|
|
83
|
+
* @param store VectorStore instance (for checkpoint access + embedder).
|
|
84
|
+
* @returns Array of expansion terms (lowercased, max `maxTerms`).
|
|
85
|
+
*/
|
|
86
|
+
export function expandQuery(query, store, opts = {}) {
|
|
87
|
+
const maxTerms = opts.maxTerms ?? DEFAULT_MAX_TERMS;
|
|
88
|
+
const minSim = opts.minSimilarity ?? DEFAULT_MIN_SIM;
|
|
89
|
+
const embedder = opts.embedder ?? store.embedder ?? defaultEmbedder();
|
|
90
|
+
// Embed the query and scan all checkpoints for nearest neighbors.
|
|
91
|
+
const qv = embedder.embed(query);
|
|
92
|
+
const candidates = [];
|
|
93
|
+
const allSessions = collectSessionIds(store.stateDir);
|
|
94
|
+
const seen = new Set();
|
|
95
|
+
for (const sid of allSessions) {
|
|
96
|
+
const cps = listCheckpoints(sid, store.stateDir);
|
|
97
|
+
for (const cp of cps) {
|
|
98
|
+
if (!cp.summary || seen.has(cp.checkpointId))
|
|
99
|
+
continue;
|
|
100
|
+
seen.add(cp.checkpointId);
|
|
101
|
+
const sim = cosineSimilarity(qv, cp.embedding);
|
|
102
|
+
if (sim >= minSim) {
|
|
103
|
+
candidates.push({ summary: cp.summary, score: sim });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (candidates.length === 0)
|
|
108
|
+
return [];
|
|
109
|
+
// Sort by similarity descending, take the top 20 for term extraction.
|
|
110
|
+
const topCandidates = candidates
|
|
111
|
+
.sort((a, b) => b.score - a.score)
|
|
112
|
+
.slice(0, 20);
|
|
113
|
+
// Compute TF-IDF scores across the candidate summaries.
|
|
114
|
+
const docTexts = topCandidates.map((c) => c.summary);
|
|
115
|
+
const scores = termScores(docTexts);
|
|
116
|
+
// Filter out query terms: we want NOVEL terms, not the ones already in the query.
|
|
117
|
+
const queryTerms = new Set(tokenizeTerms(query));
|
|
118
|
+
// Sort terms by score descending, filter query terms and short/noise terms.
|
|
119
|
+
const ranked = [...scores.entries()]
|
|
120
|
+
.filter(([term]) => !queryTerms.has(term))
|
|
121
|
+
.sort((a, b) => b[1] - a[1])
|
|
122
|
+
.slice(0, maxTerms)
|
|
123
|
+
.map(([term]) => term);
|
|
124
|
+
return ranked;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Collect unique session IDs that have at least one checkpoint in the store.
|
|
128
|
+
* Scans the SQLite checkpoint table. Returns an empty array on any error
|
|
129
|
+
* (non-fatal — query expansion degrades gracefully).
|
|
130
|
+
*/
|
|
131
|
+
function collectSessionIds(stateDir) {
|
|
132
|
+
try {
|
|
133
|
+
// We import listCheckpoints per session dynamically. A simpler approach:
|
|
134
|
+
// scan via a direct SQL query rather than reading every session.
|
|
135
|
+
// Reuse store/sqlite.ts functions — we can read the sessions table.
|
|
136
|
+
// Fallback: try listing checkpoints for all known session IDs via
|
|
137
|
+
// the sessions table.
|
|
138
|
+
const { db } = loadDb(stateDir);
|
|
139
|
+
const rows = db
|
|
140
|
+
.prepare("SELECT DISTINCT session_id FROM checkpoint_epochs ORDER BY session_id")
|
|
141
|
+
.all();
|
|
142
|
+
return rows.map((r) => r.session_id);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return [];
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Lazy-load the SQLite database handle for a given stateDir.
|
|
150
|
+
* Cached per stateDir to avoid re-opening the file on every call.
|
|
151
|
+
*/
|
|
152
|
+
const _dbCache = new Map();
|
|
153
|
+
function loadDb(stateDir) {
|
|
154
|
+
const cached = _dbCache.get(stateDir);
|
|
155
|
+
if (cached)
|
|
156
|
+
return cached;
|
|
157
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
158
|
+
const { join } = require("node:path");
|
|
159
|
+
const db = new DatabaseSync(join(stateDir, "mega-compact.db"));
|
|
160
|
+
db.exec("PRAGMA journal_mode=WAL");
|
|
161
|
+
_dbCache.set(stateDir, { db });
|
|
162
|
+
return { db };
|
|
163
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
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
|
+
// Env-Overridable Defaults (sourced from the main file's constants)
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
function envNum(name, def) {
|
|
11
|
+
const v = process.env[name];
|
|
12
|
+
if (v === undefined)
|
|
13
|
+
return def;
|
|
14
|
+
const n = Number(v);
|
|
15
|
+
return Number.isFinite(n) ? n : def;
|
|
16
|
+
}
|
|
17
|
+
export const RRF_K = envNum("MEGACOMPACT_RRF_K", 60);
|
|
18
|
+
export const EXPANSION_NEIGHBOR_COUNT = envNum("MEGACOMPACT_EXPANSION_NEIGHBOR_COUNT", 5);
|
|
19
|
+
export const EXPANSION_TOP_TERMS = envNum("MEGACOMPACT_EXPANSION_TOP_TERMS", 5);
|
|
20
|
+
export const VAGUE_MIN_WORDS = envNum("MEGACOMPACT_VAGUE_MIN_WORDS", 3);
|
|
21
|
+
export const VAGUE_VERY_SHORT_WORDS = envNum("MEGACOMPACT_VAGUE_VERY_SHORT_WORDS", 2);
|
|
22
|
+
export const QUERY_REFORM_CACHE_TTL_SECONDS = envNum("MEGACOMPACT_QUERY_REFORM_CACHE_TTL_SECONDS", 300);
|
|
23
|
+
export const CACHE_MAX_SIZE = envNum("MEGACOMPACT_QUERY_REFORM_CACHE_SIZE", 100);
|
|
24
|
+
const CACHE_STATS_INTERVAL = envNum("MEGACOMPACT_CACHE_STATS_INTERVAL", 100);
|
|
25
|
+
/** Which constant names are uncalibrated (not backed by a paper/benchmark). */
|
|
26
|
+
const UNCALIBRATED_NAMES = new Set([
|
|
27
|
+
"EXPANSION_NEIGHBOR_COUNT",
|
|
28
|
+
"EXPANSION_TOP_TERMS",
|
|
29
|
+
"VAGUE_MIN_WORDS",
|
|
30
|
+
"VAGUE_VERY_SHORT_WORDS",
|
|
31
|
+
"QUERY_REFORM_CACHE_TTL_SECONDS",
|
|
32
|
+
]);
|
|
33
|
+
export function computeUncalibrated(opts) {
|
|
34
|
+
const out = [];
|
|
35
|
+
if (opts.neighborCount === EXPANSION_NEIGHBOR_COUNT && UNCALIBRATED_NAMES.has("EXPANSION_NEIGHBOR_COUNT")) {
|
|
36
|
+
out.push("EXPANSION_NEIGHBOR_COUNT");
|
|
37
|
+
}
|
|
38
|
+
if (opts.topTerms === EXPANSION_TOP_TERMS && UNCALIBRATED_NAMES.has("EXPANSION_TOP_TERMS")) {
|
|
39
|
+
out.push("EXPANSION_TOP_TERMS");
|
|
40
|
+
}
|
|
41
|
+
if (opts.vagueMinWords === VAGUE_MIN_WORDS && UNCALIBRATED_NAMES.has("VAGUE_MIN_WORDS")) {
|
|
42
|
+
out.push("VAGUE_MIN_WORDS");
|
|
43
|
+
}
|
|
44
|
+
if (opts.vagueVeryShortWords === VAGUE_VERY_SHORT_WORDS && UNCALIBRATED_NAMES.has("VAGUE_VERY_SHORT_WORDS")) {
|
|
45
|
+
out.push("VAGUE_VERY_SHORT_WORDS");
|
|
46
|
+
}
|
|
47
|
+
if (opts.cacheTtlSeconds === QUERY_REFORM_CACHE_TTL_SECONDS && UNCALIBRATED_NAMES.has("QUERY_REFORM_CACHE_TTL_SECONDS")) {
|
|
48
|
+
out.push("QUERY_REFORM_CACHE_TTL_SECONDS");
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
const QUERY_CACHE = new Map();
|
|
53
|
+
let cacheHits = 0;
|
|
54
|
+
let cacheMisses = 0;
|
|
55
|
+
let cacheEvictions = 0;
|
|
56
|
+
let cacheCounterAtLastLog = 0;
|
|
57
|
+
/** Read (and reset) cache stats. Used by the logger for periodic reporting. */
|
|
58
|
+
export function readCacheStats() {
|
|
59
|
+
const out = { hits: cacheHits, misses: cacheMisses, evictions: cacheEvictions };
|
|
60
|
+
// Prevent unbounded growth of the delta-tracking state
|
|
61
|
+
cacheHits = 0;
|
|
62
|
+
cacheMisses = 0;
|
|
63
|
+
cacheEvictions = 0;
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
export function cacheGet(query, ttlMs) {
|
|
67
|
+
const entry = QUERY_CACHE.get(query);
|
|
68
|
+
if (!entry) {
|
|
69
|
+
cacheMisses++;
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
if (Date.now() - entry.cachedAt > ttlMs) {
|
|
73
|
+
QUERY_CACHE.delete(query);
|
|
74
|
+
cacheEvictions++;
|
|
75
|
+
cacheMisses++;
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
cacheHits++;
|
|
79
|
+
return { ...entry.result, fromCache: true };
|
|
80
|
+
}
|
|
81
|
+
export function cacheSet(query, result) {
|
|
82
|
+
// Evict oldest if over capacity
|
|
83
|
+
if (QUERY_CACHE.size >= CACHE_MAX_SIZE) {
|
|
84
|
+
let oldestKey;
|
|
85
|
+
let oldestTime = Infinity;
|
|
86
|
+
for (const [key, entry] of QUERY_CACHE) {
|
|
87
|
+
if (entry.cachedAt < oldestTime) {
|
|
88
|
+
oldestTime = entry.cachedAt;
|
|
89
|
+
oldestKey = key;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (oldestKey) {
|
|
93
|
+
QUERY_CACHE.delete(oldestKey);
|
|
94
|
+
cacheEvictions++;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
QUERY_CACHE.set(query, {
|
|
98
|
+
result: { ...result, fromCache: false },
|
|
99
|
+
cachedAt: Date.now(),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function logCacheStats(log) {
|
|
103
|
+
// Use the stable readCacheStats + reset
|
|
104
|
+
const stats = readCacheStats();
|
|
105
|
+
const total = stats.hits + stats.misses;
|
|
106
|
+
if (total === 0)
|
|
107
|
+
return;
|
|
108
|
+
log.info("query_reformulation_cache_stats", {
|
|
109
|
+
hits: stats.hits,
|
|
110
|
+
misses: stats.misses,
|
|
111
|
+
evictions: stats.evictions,
|
|
112
|
+
hitRate: total > 0 ? stats.hits / total : 0,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
export function maybeLogCacheStats(log) {
|
|
116
|
+
if (!log)
|
|
117
|
+
return;
|
|
118
|
+
const total = cacheHits + cacheMisses;
|
|
119
|
+
if (total - cacheCounterAtLastLog < CACHE_STATS_INTERVAL)
|
|
120
|
+
return;
|
|
121
|
+
cacheCounterAtLastLog = total;
|
|
122
|
+
logCacheStats(log);
|
|
123
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
* Reciprocal Rank Fusion — merge multiple ranked lists into a single score.
|
|
13
|
+
* Uses the standard RRF formula: score(id) = sum(1 / (k + rank_i(id))).
|
|
14
|
+
*
|
|
15
|
+
* k defaults to 60 — the canonical value from Cormack et al. 2009.
|
|
16
|
+
* Higher k reduces the impact of high rankings; lower k gives more weight to
|
|
17
|
+
* top-ranked items.
|
|
18
|
+
*/
|
|
19
|
+
export function reciprocalRankFusion(lists, k = 60) {
|
|
20
|
+
const scores = new Map();
|
|
21
|
+
for (const list of lists) {
|
|
22
|
+
for (const item of list) {
|
|
23
|
+
scores.set(item.id, (scores.get(item.id) ?? 0) + 1 / (k + item.rank));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return [...scores.entries()]
|
|
27
|
+
.map(([id, score]) => ({ id, score }))
|
|
28
|
+
.sort((a, b) => b.score - a.score);
|
|
29
|
+
}
|