@totalreclaw/mcp-server 1.0.0

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.
Files changed (86) hide show
  1. package/README.md +113 -0
  2. package/dist/cli/setup.d.ts +43 -0
  3. package/dist/cli/setup.d.ts.map +1 -0
  4. package/dist/cli/setup.js +276 -0
  5. package/dist/cli/setup.js.map +1 -0
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +700 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/prompts.d.ts +27 -0
  11. package/dist/prompts.d.ts.map +1 -0
  12. package/dist/prompts.js +219 -0
  13. package/dist/prompts.js.map +1 -0
  14. package/dist/resources/index.d.ts +2 -0
  15. package/dist/resources/index.d.ts.map +1 -0
  16. package/dist/resources/index.js +8 -0
  17. package/dist/resources/index.js.map +1 -0
  18. package/dist/resources/memory-context.d.ts +16 -0
  19. package/dist/resources/memory-context.d.ts.map +1 -0
  20. package/dist/resources/memory-context.js +111 -0
  21. package/dist/resources/memory-context.js.map +1 -0
  22. package/dist/server.d.ts +4 -0
  23. package/dist/server.d.ts.map +1 -0
  24. package/dist/server.js +25 -0
  25. package/dist/server.js.map +1 -0
  26. package/dist/subgraph/crypto.d.ts +106 -0
  27. package/dist/subgraph/crypto.d.ts.map +1 -0
  28. package/dist/subgraph/crypto.js +287 -0
  29. package/dist/subgraph/crypto.js.map +1 -0
  30. package/dist/subgraph/embedding.d.ts +47 -0
  31. package/dist/subgraph/embedding.d.ts.map +1 -0
  32. package/dist/subgraph/embedding.js +77 -0
  33. package/dist/subgraph/embedding.js.map +1 -0
  34. package/dist/subgraph/index.d.ts +7 -0
  35. package/dist/subgraph/index.d.ts.map +1 -0
  36. package/dist/subgraph/index.js +23 -0
  37. package/dist/subgraph/index.js.map +1 -0
  38. package/dist/subgraph/lsh.d.ts +95 -0
  39. package/dist/subgraph/lsh.d.ts.map +1 -0
  40. package/dist/subgraph/lsh.js +211 -0
  41. package/dist/subgraph/lsh.js.map +1 -0
  42. package/dist/subgraph/reranker.d.ts +157 -0
  43. package/dist/subgraph/reranker.d.ts.map +1 -0
  44. package/dist/subgraph/reranker.js +427 -0
  45. package/dist/subgraph/reranker.js.map +1 -0
  46. package/dist/subgraph/search.d.ts +62 -0
  47. package/dist/subgraph/search.d.ts.map +1 -0
  48. package/dist/subgraph/search.js +208 -0
  49. package/dist/subgraph/search.js.map +1 -0
  50. package/dist/subgraph/store.d.ts +97 -0
  51. package/dist/subgraph/store.d.ts.map +1 -0
  52. package/dist/subgraph/store.js +270 -0
  53. package/dist/subgraph/store.js.map +1 -0
  54. package/dist/tools/export.d.ts +48 -0
  55. package/dist/tools/export.d.ts.map +1 -0
  56. package/dist/tools/export.js +126 -0
  57. package/dist/tools/export.js.map +1 -0
  58. package/dist/tools/forget.d.ts +43 -0
  59. package/dist/tools/forget.d.ts.map +1 -0
  60. package/dist/tools/forget.js +96 -0
  61. package/dist/tools/forget.js.map +1 -0
  62. package/dist/tools/import.d.ts +73 -0
  63. package/dist/tools/import.d.ts.map +1 -0
  64. package/dist/tools/import.js +248 -0
  65. package/dist/tools/import.js.map +1 -0
  66. package/dist/tools/index.d.ts +8 -0
  67. package/dist/tools/index.d.ts.map +1 -0
  68. package/dist/tools/index.js +25 -0
  69. package/dist/tools/index.js.map +1 -0
  70. package/dist/tools/recall.d.ts +65 -0
  71. package/dist/tools/recall.d.ts.map +1 -0
  72. package/dist/tools/recall.js +113 -0
  73. package/dist/tools/recall.js.map +1 -0
  74. package/dist/tools/remember.d.ts +109 -0
  75. package/dist/tools/remember.d.ts.map +1 -0
  76. package/dist/tools/remember.js +227 -0
  77. package/dist/tools/remember.js.map +1 -0
  78. package/dist/tools/status.d.ts +43 -0
  79. package/dist/tools/status.d.ts.map +1 -0
  80. package/dist/tools/status.js +110 -0
  81. package/dist/tools/status.js.map +1 -0
  82. package/dist/tools/upgrade.d.ts +48 -0
  83. package/dist/tools/upgrade.d.ts.map +1 -0
  84. package/dist/tools/upgrade.js +122 -0
  85. package/dist/tools/upgrade.js.map +1 -0
  86. package/package.json +61 -0
@@ -0,0 +1,427 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP - Client-Side Re-Ranker
4
+ *
5
+ * Replaces the naive `textScore` word-overlap scorer with a proper ranking
6
+ * pipeline:
7
+ * 1. Okapi BM25 — term frequency / inverse document frequency
8
+ * 2. Cosine similarity — between query and fact embeddings
9
+ * 3. Importance — normalized importance score (0-1)
10
+ * 4. Recency — time-decay with 1-week half-life
11
+ * 5. Weighted RRF (Reciprocal Rank Fusion) — combines all ranking lists
12
+ * 6. MMR (Maximal Marginal Relevance) — promotes diversity in results
13
+ *
14
+ * All functions are pure TypeScript with zero external dependencies (except
15
+ * porter-stemmer for morphological normalization). This module runs
16
+ * CLIENT-SIDE after decrypting candidates from the server.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.INTENT_WEIGHTS = exports.DEFAULT_WEIGHTS = void 0;
20
+ exports.tokenize = tokenize;
21
+ exports.bm25Score = bm25Score;
22
+ exports.cosineSimilarity = cosineSimilarity;
23
+ exports.rrfFuse = rrfFuse;
24
+ exports.weightedRrfFuse = weightedRrfFuse;
25
+ exports.detectQueryIntent = detectQueryIntent;
26
+ exports.applyMMR = applyMMR;
27
+ exports.rerank = rerank;
28
+ const porter_stemmer_1 = require("porter-stemmer");
29
+ // ---------------------------------------------------------------------------
30
+ // Tokenization
31
+ // ---------------------------------------------------------------------------
32
+ /**
33
+ * Tokenize a text string for BM25 scoring.
34
+ *
35
+ * Matches the tokenization rules used for blind indices in crypto.ts:
36
+ * 1. Lowercase
37
+ * 2. Remove punctuation (keep Unicode letters, numbers, whitespace)
38
+ * 3. Split on whitespace
39
+ * 4. Filter tokens shorter than 2 characters
40
+ *
41
+ * Optionally removes common English stop words (enabled by default) to
42
+ * improve BM25 signal — stop words have low IDF and add noise.
43
+ */
44
+ const STOP_WORDS = new Set([
45
+ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'but', 'by', 'do', 'for',
46
+ 'from', 'had', 'has', 'have', 'he', 'her', 'him', 'his', 'how', 'if',
47
+ 'in', 'into', 'is', 'it', 'its', 'me', 'my', 'no', 'not', 'of', 'on',
48
+ 'or', 'our', 'out', 'she', 'so', 'than', 'that', 'the', 'their', 'them',
49
+ 'then', 'there', 'these', 'they', 'this', 'to', 'up', 'us', 'was', 'we',
50
+ 'were', 'what', 'when', 'where', 'which', 'who', 'whom', 'why', 'will',
51
+ 'with', 'you', 'your',
52
+ ]);
53
+ function tokenize(text, removeStopWords = true) {
54
+ let tokens = text
55
+ .toLowerCase()
56
+ .replace(/[^\p{L}\p{N}\s]/gu, ' ')
57
+ .split(/\s+/)
58
+ .filter((t) => t.length >= 2);
59
+ if (removeStopWords) {
60
+ tokens = tokens.filter((t) => !STOP_WORDS.has(t));
61
+ }
62
+ // Stem each token for morphological normalization.
63
+ // This ensures BM25 matches "gaming" with "games" (both stem to "game").
64
+ return tokens.map((t) => (0, porter_stemmer_1.stemmer)(t));
65
+ }
66
+ // ---------------------------------------------------------------------------
67
+ // BM25 Scoring (Okapi BM25)
68
+ // ---------------------------------------------------------------------------
69
+ /**
70
+ * Compute the Okapi BM25 score for a single document against a query.
71
+ *
72
+ * Formula:
73
+ * score = SUM_i IDF(qi) * (f(qi, D) * (k1 + 1)) / (f(qi, D) + k1 * (1 - b + b * |D| / avgdl))
74
+ *
75
+ * where:
76
+ * IDF(qi) = ln((N - n(qi) + 0.5) / (n(qi) + 0.5) + 1)
77
+ * f(qi, D) = frequency of term qi in document D
78
+ * |D| = length of document D (in tokens)
79
+ * avgdl = average document length across the corpus
80
+ * N = total number of documents
81
+ * n(qi) = number of documents containing term qi
82
+ *
83
+ * @param queryTerms - Tokenized query terms
84
+ * @param docTerms - Tokenized document terms
85
+ * @param avgDocLen - Average document length (in tokens) across the candidate corpus
86
+ * @param docCount - Total number of documents in the candidate corpus
87
+ * @param termDocFreqs - Map from term to number of documents containing that term
88
+ * @param k1 - BM25 k1 parameter (default 1.2)
89
+ * @param b - BM25 b parameter (default 0.75)
90
+ */
91
+ function bm25Score(queryTerms, docTerms, avgDocLen, docCount, termDocFreqs, k1 = 1.2, b = 0.75) {
92
+ if (docTerms.length === 0 || avgDocLen === 0 || docCount === 0)
93
+ return 0;
94
+ // Count term frequencies in this document.
95
+ const docTf = new Map();
96
+ for (const term of docTerms) {
97
+ docTf.set(term, (docTf.get(term) ?? 0) + 1);
98
+ }
99
+ const docLen = docTerms.length;
100
+ let score = 0;
101
+ for (const qi of queryTerms) {
102
+ const freq = docTf.get(qi) ?? 0;
103
+ if (freq === 0)
104
+ continue;
105
+ const nqi = termDocFreqs.get(qi) ?? 0;
106
+ // IDF with Robertson-Walker floor: ln((N - n + 0.5) / (n + 0.5) + 1)
107
+ // The +1 inside ln ensures IDF is always >= 0 even when n > N/2.
108
+ const idf = Math.log((docCount - nqi + 0.5) / (nqi + 0.5) + 1);
109
+ // TF saturation with length normalization.
110
+ const tfNorm = (freq * (k1 + 1)) / (freq + k1 * (1 - b + b * docLen / avgDocLen));
111
+ score += idf * tfNorm;
112
+ }
113
+ return score;
114
+ }
115
+ // ---------------------------------------------------------------------------
116
+ // Cosine Similarity
117
+ // ---------------------------------------------------------------------------
118
+ /**
119
+ * Compute cosine similarity between two vectors.
120
+ *
121
+ * Returns dot(a, b) / (||a|| * ||b||).
122
+ * Returns 0 if either vector has zero magnitude (avoids division by zero).
123
+ */
124
+ function cosineSimilarity(a, b) {
125
+ if (a.length === 0 || b.length === 0)
126
+ return 0;
127
+ const len = Math.min(a.length, b.length);
128
+ let dot = 0;
129
+ let normA = 0;
130
+ let normB = 0;
131
+ for (let i = 0; i < len; i++) {
132
+ dot += a[i] * b[i];
133
+ normA += a[i] * a[i];
134
+ normB += b[i] * b[i];
135
+ }
136
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
137
+ if (denom === 0)
138
+ return 0;
139
+ return dot / denom;
140
+ }
141
+ /**
142
+ * Fuse multiple ranking lists using Reciprocal Rank Fusion.
143
+ *
144
+ * For each document d appearing in any ranking list:
145
+ * rrfScore(d) = SUM_i 1 / (k + rank_i(d))
146
+ *
147
+ * where rank_i(d) is the 1-based rank of document d in the i-th list.
148
+ * Documents not present in a list are not penalized (they simply receive
149
+ * no contribution from that list).
150
+ *
151
+ * @param rankings - Array of ranking lists, each sorted by score descending.
152
+ * Each item has an `id` and a `score`.
153
+ * @param k - RRF smoothing constant (default 60, per the original paper).
154
+ * @returns - Fused ranking sorted by RRF score descending.
155
+ */
156
+ function rrfFuse(rankings, k = 60) {
157
+ const fusedScores = new Map();
158
+ for (const ranking of rankings) {
159
+ for (let rank = 0; rank < ranking.length; rank++) {
160
+ const item = ranking[rank];
161
+ const contribution = 1 / (k + rank + 1); // rank is 0-based, formula uses 1-based
162
+ fusedScores.set(item.id, (fusedScores.get(item.id) ?? 0) + contribution);
163
+ }
164
+ }
165
+ const fused = [];
166
+ for (const [id, score] of fusedScores) {
167
+ fused.push({ id, score });
168
+ }
169
+ fused.sort((a, b) => b.score - a.score);
170
+ return fused;
171
+ }
172
+ // ---------------------------------------------------------------------------
173
+ // Weighted Reciprocal Rank Fusion
174
+ // ---------------------------------------------------------------------------
175
+ /**
176
+ * Fuse multiple ranking lists using Weighted Reciprocal Rank Fusion.
177
+ *
178
+ * Like standard RRF, but each ranking list's contribution is multiplied by
179
+ * its weight, allowing callers to emphasize or de-emphasize specific signals.
180
+ *
181
+ * @param rankings - Array of ranking lists, each sorted by score descending.
182
+ * @param weights - Weight for each ranking list (same length as rankings).
183
+ * @param k - RRF smoothing constant (default 60).
184
+ * @returns - Fused ranking sorted by weighted RRF score descending.
185
+ */
186
+ function weightedRrfFuse(rankings, weights, k = 60) {
187
+ const fusedScores = new Map();
188
+ for (let r = 0; r < rankings.length; r++) {
189
+ const w = weights[r] ?? 1;
190
+ for (let rank = 0; rank < rankings[r].length; rank++) {
191
+ const item = rankings[r][rank];
192
+ const contribution = w * (1 / (k + rank + 1));
193
+ fusedScores.set(item.id, (fusedScores.get(item.id) ?? 0) + contribution);
194
+ }
195
+ }
196
+ const fused = [];
197
+ for (const [id, score] of fusedScores) {
198
+ fused.push({ id, score });
199
+ }
200
+ fused.sort((a, b) => b.score - a.score);
201
+ return fused;
202
+ }
203
+ exports.DEFAULT_WEIGHTS = {
204
+ bm25: 0.25,
205
+ cosine: 0.25,
206
+ importance: 0.25,
207
+ recency: 0.25,
208
+ };
209
+ const TEMPORAL_KEYWORDS = /\b(yesterday|today|last\s+week|last\s+month|recently|recent|latest|ago|when|this\s+week|this\s+month|earlier|before|after|since|during|tonight|morning|afternoon)\b/i;
210
+ const FACTUAL_PATTERNS = /^(what|who|where|which|how\s+many|how\s+much|is\s+|are\s+|does\s+|do\s+|did\s+|was\s+|were\s+)\b/i;
211
+ /** Ranking weights tuned for each query intent. */
212
+ exports.INTENT_WEIGHTS = {
213
+ factual: { bm25: 0.40, cosine: 0.20, importance: 0.25, recency: 0.15 },
214
+ temporal: { bm25: 0.15, cosine: 0.20, importance: 0.20, recency: 0.45 },
215
+ semantic: { bm25: 0.20, cosine: 0.35, importance: 0.25, recency: 0.20 },
216
+ };
217
+ /**
218
+ * Classify a query into one of three intent types using lightweight heuristics.
219
+ * Temporal is checked first so "What did we discuss yesterday?" -> temporal.
220
+ */
221
+ function detectQueryIntent(query) {
222
+ if (TEMPORAL_KEYWORDS.test(query))
223
+ return 'temporal';
224
+ if (FACTUAL_PATTERNS.test(query) && query.length < 80)
225
+ return 'factual';
226
+ return 'semantic';
227
+ }
228
+ // ---------------------------------------------------------------------------
229
+ // Recency Scoring
230
+ // ---------------------------------------------------------------------------
231
+ /**
232
+ * Compute a recency score with a 1-week half-life.
233
+ *
234
+ * Score = 1 / (1 + hours_since_creation / 168)
235
+ *
236
+ * A fact created just now scores ~1.0, one week ago scores 0.5,
237
+ * two weeks ago scores ~0.33, etc.
238
+ *
239
+ * @param createdAt - Unix timestamp in seconds
240
+ * @returns - Recency score in (0, 1]
241
+ */
242
+ function recencyScore(createdAt) {
243
+ const nowSeconds = Date.now() / 1000;
244
+ const hoursSince = (nowSeconds - createdAt) / 3600;
245
+ return 1 / (1 + hoursSince / 168);
246
+ }
247
+ // ---------------------------------------------------------------------------
248
+ // MMR (Maximal Marginal Relevance)
249
+ // ---------------------------------------------------------------------------
250
+ /**
251
+ * Apply Maximal Marginal Relevance to promote diversity in results.
252
+ *
253
+ * MMR re-orders a ranked list of candidates so that highly similar candidates
254
+ * are spread out. The algorithm greedily selects the candidate that maximizes:
255
+ *
256
+ * MMR(d) = lambda * relevance(d) - (1 - lambda) * max_sim(d, selected)
257
+ *
258
+ * where:
259
+ * - relevance(d) = position-based score (1.0 for first, linearly decreasing)
260
+ * - max_sim(d, selected) = max cosine similarity between d and any already
261
+ * selected candidate (0 if no embeddings available)
262
+ *
263
+ * @param candidates - Candidates in relevance order (best first)
264
+ * @param lambda - Trade-off between relevance and diversity (default 0.7)
265
+ * @param topK - Number of results to return (default 8)
266
+ * @returns - Re-ordered candidates with diversity
267
+ */
268
+ function applyMMR(candidates, lambda = 0.7, topK = 8) {
269
+ if (candidates.length === 0)
270
+ return [];
271
+ if (candidates.length <= 1)
272
+ return candidates.slice(0, topK);
273
+ const remaining = candidates.map((c, i) => ({ candidate: c, index: i }));
274
+ const selected = [];
275
+ const n = candidates.length;
276
+ while (selected.length < topK && remaining.length > 0) {
277
+ let bestIdx = -1;
278
+ let bestMMR = -Infinity;
279
+ for (let i = 0; i < remaining.length; i++) {
280
+ const { candidate, index } = remaining[i];
281
+ // Relevance: linear decay from 1.0 (first) to near 0 (last)
282
+ const relevance = 1.0 - index / n;
283
+ // Max similarity to any already-selected candidate
284
+ let maxSim = 0;
285
+ if (candidate.embedding && candidate.embedding.length > 0) {
286
+ for (const sel of selected) {
287
+ if (sel.embedding && sel.embedding.length > 0) {
288
+ const sim = cosineSimilarity(candidate.embedding, sel.embedding);
289
+ if (sim > maxSim)
290
+ maxSim = sim;
291
+ }
292
+ }
293
+ }
294
+ const mmr = lambda * relevance - (1 - lambda) * maxSim;
295
+ if (mmr > bestMMR) {
296
+ bestMMR = mmr;
297
+ bestIdx = i;
298
+ }
299
+ }
300
+ if (bestIdx >= 0) {
301
+ selected.push(remaining[bestIdx].candidate);
302
+ remaining.splice(bestIdx, 1);
303
+ }
304
+ else {
305
+ break;
306
+ }
307
+ }
308
+ return selected;
309
+ }
310
+ // ---------------------------------------------------------------------------
311
+ // Combined Re-Ranker
312
+ // ---------------------------------------------------------------------------
313
+ /**
314
+ * Re-rank decrypted candidates using BM25 + Cosine + Importance + Recency
315
+ * with Weighted RRF fusion and MMR diversity.
316
+ *
317
+ * Pipeline:
318
+ * 1. Tokenize query and all candidate texts
319
+ * 2. Build corpus statistics (term document frequencies, average doc length)
320
+ * 3. Score each candidate with BM25
321
+ * 4. Score each candidate with cosine similarity (if embedding available)
322
+ * 5. Score each candidate by importance
323
+ * 6. Score each candidate by recency
324
+ * 7. Fuse all 4 rankings with weighted RRF
325
+ * 8. Apply MMR for diversity
326
+ * 9. Return top-k candidates sorted by fused score
327
+ *
328
+ * Backward compatibility:
329
+ * - Candidates without embeddings get cosine score = 0 and are excluded
330
+ * from the cosine ranking list. They can still rank well via other signals.
331
+ * - If NO candidates have embeddings, cosine ranking is omitted.
332
+ * - Candidates without importance get neutral score (0.5).
333
+ * - Candidates without createdAt get neutral recency score (0.5).
334
+ * - topK defaults to 8, weights default to equal (0.25 each).
335
+ *
336
+ * @param query - The user's search query (plaintext)
337
+ * @param queryEmbedding - Embedding vector for the query
338
+ * @param candidates - Decrypted candidates with text and optional embeddings
339
+ * @param topK - Number of results to return (default 8)
340
+ * @param weights - Optional partial ranking weights (merged with defaults)
341
+ * @returns - Top-k candidates sorted by fused score, with scores attached
342
+ */
343
+ function rerank(query, queryEmbedding, candidates, topK = 8, weights) {
344
+ if (candidates.length === 0)
345
+ return [];
346
+ // Merge caller weights with defaults
347
+ const w = { ...exports.DEFAULT_WEIGHTS, ...weights };
348
+ // --- Step 1: Tokenize ---
349
+ const queryTerms = tokenize(query);
350
+ const candidateTerms = candidates.map((c) => tokenize(c.text));
351
+ // --- Step 2: Corpus statistics ---
352
+ const docCount = candidates.length;
353
+ let totalDocLen = 0;
354
+ // Count how many documents contain each term.
355
+ const termDocFreqs = new Map();
356
+ for (const terms of candidateTerms) {
357
+ totalDocLen += terms.length;
358
+ const uniqueTerms = new Set(terms);
359
+ for (const term of uniqueTerms) {
360
+ termDocFreqs.set(term, (termDocFreqs.get(term) ?? 0) + 1);
361
+ }
362
+ }
363
+ const avgDocLen = docCount > 0 ? totalDocLen / docCount : 0;
364
+ // --- Step 3: BM25 scores ---
365
+ const bm25Ranking = [];
366
+ for (let i = 0; i < candidates.length; i++) {
367
+ const score = bm25Score(queryTerms, candidateTerms[i], avgDocLen, docCount, termDocFreqs);
368
+ bm25Ranking.push({ id: candidates[i].id, score });
369
+ }
370
+ bm25Ranking.sort((a, b) => b.score - a.score);
371
+ // --- Step 4: Cosine similarity scores ---
372
+ const cosineScores = new Map();
373
+ const cosineRanking = [];
374
+ for (const candidate of candidates) {
375
+ if (candidate.embedding && candidate.embedding.length > 0) {
376
+ const score = cosineSimilarity(queryEmbedding, candidate.embedding);
377
+ cosineScores.set(candidate.id, score);
378
+ cosineRanking.push({ id: candidate.id, score });
379
+ }
380
+ }
381
+ cosineRanking.sort((a, b) => b.score - a.score);
382
+ // --- Step 5: Importance ranking ---
383
+ const importanceRanking = candidates.map((c) => ({
384
+ id: c.id,
385
+ score: c.importance ?? 0.5,
386
+ }));
387
+ importanceRanking.sort((a, b) => b.score - a.score);
388
+ // --- Step 6: Recency ranking ---
389
+ const recencyRanking = candidates.map((c) => ({
390
+ id: c.id,
391
+ score: c.createdAt != null ? recencyScore(c.createdAt) : 0.5,
392
+ }));
393
+ recencyRanking.sort((a, b) => b.score - a.score);
394
+ // --- Step 7: Weighted RRF fusion ---
395
+ const rankings = [bm25Ranking];
396
+ const rankWeights = [w.bm25];
397
+ if (cosineRanking.length > 0) {
398
+ rankings.push(cosineRanking);
399
+ rankWeights.push(w.cosine);
400
+ }
401
+ rankings.push(importanceRanking);
402
+ rankWeights.push(w.importance);
403
+ rankings.push(recencyRanking);
404
+ rankWeights.push(w.recency);
405
+ const fused = weightedRrfFuse(rankings, rankWeights);
406
+ // --- Step 8: Build result objects with scores ---
407
+ const candidateMap = new Map();
408
+ for (const c of candidates) {
409
+ candidateMap.set(c.id, c);
410
+ }
411
+ const rrfResults = [];
412
+ for (const item of fused) {
413
+ const candidate = candidateMap.get(item.id);
414
+ if (candidate) {
415
+ rrfResults.push({
416
+ ...candidate,
417
+ rrfScore: item.score,
418
+ cosineSimilarity: cosineScores.get(item.id),
419
+ });
420
+ }
421
+ }
422
+ // --- Step 9: Apply MMR for diversity, then return top-k ---
423
+ const mmrResults = applyMMR(rrfResults, 0.7, topK);
424
+ // Preserve rrfScore and cosineSimilarity through MMR
425
+ return mmrResults;
426
+ }
427
+ //# sourceMappingURL=reranker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reranker.js","sourceRoot":"","sources":["../../src/subgraph/reranker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA8BH,4BAcC;AA4BD,8BAqCC;AAYD,4CAkBC;AA0BD,0BAqBC;AAiBD,0CAuBC;AA0CD,8CAIC;AA0DD,4BAiDC;AAoCD,wBA0GC;AAvgBD,mDAAyC;AAEzC,8EAA8E;AAC9E,eAAe;AACf,8EAA8E;AAE9E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK;IACnE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IA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CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IAE/B,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC9B,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IAE5B,MAAM,KAAK,GAAG,eAAe,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IAErD,mDAAmD;IACnD,MAAM,YAAY,GAAG,IAAI,GAAG,EAA6B,CAAC;IAC1D,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;QAC3B,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,UAAU,GAAqB,EAAE,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC5C,IAAI,SAAS,EAAE,CAAC;YACd,UAAU,CAAC,IAAI,CAAC;gBACd,GAAG,SAAS;gBACZ,QAAQ,EAAE,IAAI,CAAC,KAAK;gBACpB,gBAAgB,EAAE,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;aAC5C,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,6DAA6D;IAC7D,MAAM,UAAU,GAAG,QAAQ,CAAC,UAAU,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAEnD,qDAAqD;IACrD,OAAO,UAA8B,CAAC;AACxC,CAAC"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * TotalReclaw MCP - Subgraph search path
3
+ *
4
+ * Queries facts via GraphQL hash_in through the relay server.
5
+ *
6
+ * Used when subgraph mode is enabled. Replaces the HTTP POST
7
+ * to /v1/search with a GraphQL query to the subgraph via the relay server.
8
+ *
9
+ * The relay server proxies GraphQL queries to Graph Studio with its own
10
+ * API key at `${relayUrl}/v1/subgraph`. Clients never need a subgraph endpoint.
11
+ *
12
+ * Adapted from skill/plugin/subgraph-search.ts for the MCP server context.
13
+ * Accepts relay URL as a parameter (not just env var) so the MCP server can
14
+ * pass its configured URL.
15
+ *
16
+ * Improvements (v3):
17
+ * A1: blindIndices -> blindIndexes (Graph Node pluralization)
18
+ * A2: Small parallel batches (5 trapdoors each) for recall
19
+ * A3: orderBy: id, orderDirection: desc (recency proxy)
20
+ * A4: Cursor-based pagination for saturated batches
21
+ * C4: globalStates for lightweight fact count
22
+ * T322: Index compaction — filter out inactive facts at query level
23
+ * (fact_: { isActive: true }) + client-side safety net
24
+ */
25
+ export interface SubgraphSearchFact {
26
+ id: string;
27
+ encryptedBlob: string;
28
+ encryptedEmbedding: string | null;
29
+ decayScore: string;
30
+ timestamp: string;
31
+ isActive: boolean;
32
+ }
33
+ /**
34
+ * Search the subgraph for facts matching the given trapdoors.
35
+ *
36
+ * Strategy:
37
+ * 1. Split trapdoors into small chunks (TRAPDOOR_BATCH_SIZE=5).
38
+ * 2. Fire all chunks in parallel via Promise.all.
39
+ * 3. If any chunk returns exactly PAGE_SIZE results (saturated),
40
+ * paginate that chunk using id_gt cursor until exhausted or
41
+ * maxCandidates reached.
42
+ * 4. Dedup across all chunks by fact id.
43
+ *
44
+ * @param owner - Smart Account address (hex)
45
+ * @param trapdoors - Blind index hashes to search for
46
+ * @param maxCandidates - Maximum number of candidate facts to return
47
+ * @param relayUrl - Optional relay URL override. If not provided,
48
+ * falls back to getSubgraphConfig().relayUrl.
49
+ */
50
+ export declare function searchSubgraph(owner: string, trapdoors: string[], maxCandidates: number, relayUrl?: string): Promise<SubgraphSearchFact[]>;
51
+ /**
52
+ * Get fact count from the subgraph for dynamic pool sizing.
53
+ * Uses the globalStates entity for a lightweight single-row lookup
54
+ * instead of fetching and counting individual fact IDs.
55
+ *
56
+ * @param owner - Smart Account address (hex) — currently unused by globalStates
57
+ * (which is aggregate), but kept for API consistency.
58
+ * @param relayUrl - Optional relay URL override. If not provided,
59
+ * falls back to getSubgraphConfig().relayUrl.
60
+ */
61
+ export declare function getSubgraphFactCount(owner: string, relayUrl?: string): Promise<number>;
62
+ //# sourceMappingURL=search.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/subgraph/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;CACnB;AA4FD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EAAE,EACnB,aAAa,EAAE,MAAM,EACrB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,EAAE,CAAC,CA2E/B;AAED;;;;;;;;;GASG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,MAAM,CAAC,CA0BjB"}