@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,211 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP - LSH Hasher (Locality-Sensitive Hashing)
4
+ *
5
+ * Pure TypeScript implementation of Random Hyperplane LSH for zero-knowledge
6
+ * semantic search. Generates deterministic hyperplane matrices from a seed
7
+ * derived from the user's master key, so the same embedding always hashes to
8
+ * the same buckets across sessions.
9
+ *
10
+ * Architecture overview:
11
+ * 1. Seed (32 bytes from HKDF) -> HKDF per table -> random bytes
12
+ * 2. Random bytes -> Box-Muller transform -> Gaussian-distributed hyperplanes
13
+ * 3. Embedding dot hyperplane -> sign bit -> N-bit signature per table
14
+ * 4. Signature -> `lsh_t{table}_{signature}` -> SHA-256 -> blind hash
15
+ *
16
+ * The blind hashes are merged with the existing blind word indices in the
17
+ * `blind_indices` array. The server never knows which hashes are word-based
18
+ * and which are LSH-based.
19
+ *
20
+ * Default parameters:
21
+ * - 32 bits per table (balanced discrimination vs. recall)
22
+ * - 20 tables (moderate table count for good coverage)
23
+ * - Middle ground between 64-bit x 12 (too strict) and 12-bit x 28 (too loose)
24
+ *
25
+ * Dependencies: @noble/hashes only (already in project).
26
+ */
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.LSHHasher = void 0;
29
+ const hkdf_js_1 = require("@noble/hashes/hkdf.js");
30
+ const sha2_js_1 = require("@noble/hashes/sha2.js");
31
+ // ---------------------------------------------------------------------------
32
+ // Constants
33
+ // ---------------------------------------------------------------------------
34
+ /** Default number of independent hash tables. */
35
+ const DEFAULT_N_TABLES = 20;
36
+ /** Default number of bits (hyperplanes) per table. */
37
+ const DEFAULT_N_BITS = 32;
38
+ /** Number of bytes needed per Gaussian float via Box-Muller (2 x uint32 = 8 bytes). */
39
+ const BYTES_PER_FLOAT = 8;
40
+ // ---------------------------------------------------------------------------
41
+ // LSHHasher
42
+ // ---------------------------------------------------------------------------
43
+ /**
44
+ * Random Hyperplane LSH hasher.
45
+ *
46
+ * All state is deterministic from the seed -- no randomness at hash time.
47
+ * Construct once per session; call `hash()` for every store/search operation.
48
+ */
49
+ class LSHHasher {
50
+ /**
51
+ * Flat hyperplane storage.
52
+ *
53
+ * `hyperplanes[t]` is a Float64Array of length `dims * nBits` containing the
54
+ * hyperplane matrix for table `t`. The hyperplane for bit `b` starts at
55
+ * offset `b * dims`.
56
+ */
57
+ hyperplanes;
58
+ /** Embedding dimensionality. */
59
+ dims;
60
+ /** Number of independent hash tables. */
61
+ nTables;
62
+ /** Number of bits (hyperplanes) per table. */
63
+ nBits;
64
+ /**
65
+ * Create a new LSH hasher.
66
+ *
67
+ * @param seed - 32-byte seed from `deriveLshSeed()` in crypto.ts.
68
+ * @param dims - Embedding dimensionality (e.g. 1536 for text-embedding-3-small).
69
+ * @param nTables - Number of independent hash tables (default 20).
70
+ * @param nBits - Number of bits per table (default 32).
71
+ */
72
+ constructor(seed, dims, nTables = DEFAULT_N_TABLES, nBits = DEFAULT_N_BITS) {
73
+ if (seed.length < 16) {
74
+ throw new Error(`LSH seed too short: expected >= 16 bytes, got ${seed.length}`);
75
+ }
76
+ if (dims < 1) {
77
+ throw new Error(`dims must be positive, got ${dims}`);
78
+ }
79
+ if (nTables < 1) {
80
+ throw new Error(`nTables must be positive, got ${nTables}`);
81
+ }
82
+ if (nBits < 1) {
83
+ throw new Error(`nBits must be positive, got ${nBits}`);
84
+ }
85
+ this.dims = dims;
86
+ this.nTables = nTables;
87
+ this.nBits = nBits;
88
+ this.hyperplanes = new Array(nTables);
89
+ // Generate hyperplane matrices deterministically from the seed.
90
+ for (let t = 0; t < nTables; t++) {
91
+ this.hyperplanes[t] = this.generateTableHyperplanes(seed, t);
92
+ }
93
+ }
94
+ // -------------------------------------------------------------------------
95
+ // Hyperplane generation (deterministic from seed)
96
+ // -------------------------------------------------------------------------
97
+ /**
98
+ * Generate the hyperplane matrix for a single table.
99
+ *
100
+ * Each table gets a unique HKDF-derived byte stream. We consume 8 bytes
101
+ * per Gaussian sample (Box-Muller uses two uniform uint32 values).
102
+ *
103
+ * The hyperplanes are NOT normalised to unit length. Normalisation is
104
+ * unnecessary because we only care about the sign of the dot product,
105
+ * which is scale-invariant.
106
+ */
107
+ generateTableHyperplanes(seed, tableIndex) {
108
+ const totalFloats = this.dims * this.nBits;
109
+ const totalBytes = totalFloats * BYTES_PER_FLOAT;
110
+ // Derive enough random bytes for this table.
111
+ // HKDF can produce up to 255 * HashLen bytes (255 * 32 = 8,160 for SHA-256).
112
+ // For large dims (e.g. 1536 * 64 * 8 = 786,432 bytes) we need multiple
113
+ // HKDF calls with sub-block indexing.
114
+ const randomBytes = this.deriveRandomBytes(seed, `lsh_table_${tableIndex}`, totalBytes);
115
+ // Convert the random bytes to Gaussian-distributed floats via Box-Muller.
116
+ const hyperplaneMatrix = new Float64Array(totalFloats);
117
+ const view = new DataView(randomBytes.buffer, randomBytes.byteOffset, randomBytes.byteLength);
118
+ for (let i = 0; i < totalFloats; i++) {
119
+ const offset = i * BYTES_PER_FLOAT;
120
+ // Two uint32 values -> two uniform [0,1) samples -> one Gaussian via Box-Muller.
121
+ const u1Raw = view.getUint32(offset, true);
122
+ const u2Raw = view.getUint32(offset + 4, true);
123
+ // Map to (0, 1] -- avoid exactly 0 for the log in Box-Muller.
124
+ const u1 = (u1Raw + 1) / (0xFFFFFFFF + 2);
125
+ const u2 = (u2Raw + 1) / (0xFFFFFFFF + 2);
126
+ // Box-Muller transform (we only need one of the two outputs).
127
+ hyperplaneMatrix[i] = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
128
+ }
129
+ return hyperplaneMatrix;
130
+ }
131
+ /**
132
+ * Derive `length` pseudo-random bytes from the seed using HKDF with
133
+ * chunked sub-blocks.
134
+ *
135
+ * A single HKDF-SHA256 call can output at most 255 * 32 = 8,160 bytes.
136
+ * For large embedding dimensions we need more, so we iterate over
137
+ * sub-block indices as part of the info string.
138
+ */
139
+ deriveRandomBytes(seed, baseInfo, length) {
140
+ const MAX_HKDF_OUTPUT = 255 * 32; // SHA-256 hash length = 32
141
+ const result = new Uint8Array(length);
142
+ let offset = 0;
143
+ let blockIndex = 0;
144
+ while (offset < length) {
145
+ const remaining = length - offset;
146
+ const chunkLen = Math.min(remaining, MAX_HKDF_OUTPUT);
147
+ const info = Buffer.from(`${baseInfo}_block_${blockIndex}`, 'utf8');
148
+ const chunk = (0, hkdf_js_1.hkdf)(sha2_js_1.sha256, seed, new Uint8Array(0), info, chunkLen);
149
+ result.set(new Uint8Array(chunk), offset);
150
+ offset += chunkLen;
151
+ blockIndex++;
152
+ }
153
+ return result;
154
+ }
155
+ // -------------------------------------------------------------------------
156
+ // Hash function
157
+ // -------------------------------------------------------------------------
158
+ /**
159
+ * Hash an embedding vector to an array of blind-hashed bucket IDs.
160
+ *
161
+ * For each table:
162
+ * 1. Compute the 64-bit signature (sign of dot product with each hyperplane).
163
+ * 2. Build the bucket string: `lsh_t{tableIndex}_{binarySignature}`.
164
+ * 3. SHA-256 the bucket string to produce a blind hash (hex).
165
+ *
166
+ * @param embedding - The embedding vector (must have `dims` elements).
167
+ * @returns Array of `nTables` hex strings (one blind hash per table).
168
+ */
169
+ hash(embedding) {
170
+ if (embedding.length !== this.dims) {
171
+ throw new Error(`Embedding dimension mismatch: expected ${this.dims}, got ${embedding.length}`);
172
+ }
173
+ const results = new Array(this.nTables);
174
+ for (let t = 0; t < this.nTables; t++) {
175
+ const matrix = this.hyperplanes[t];
176
+ // Build the binary signature.
177
+ const bits = new Array(this.nBits);
178
+ for (let b = 0; b < this.nBits; b++) {
179
+ const baseOffset = b * this.dims;
180
+ let dot = 0;
181
+ for (let d = 0; d < this.dims; d++) {
182
+ dot += matrix[baseOffset + d] * embedding[d];
183
+ }
184
+ bits[b] = dot >= 0 ? '1' : '0';
185
+ }
186
+ const signature = bits.join('');
187
+ const bucketId = `lsh_t${t}_${signature}`;
188
+ // Blind-hash the bucket ID with SHA-256.
189
+ const hashBytes = (0, sha2_js_1.sha256)(Buffer.from(bucketId, 'utf8'));
190
+ results[t] = Buffer.from(hashBytes).toString('hex');
191
+ }
192
+ return results;
193
+ }
194
+ // -------------------------------------------------------------------------
195
+ // Accessors
196
+ // -------------------------------------------------------------------------
197
+ /** Number of hash tables. */
198
+ get tables() {
199
+ return this.nTables;
200
+ }
201
+ /** Number of bits per table. */
202
+ get bits() {
203
+ return this.nBits;
204
+ }
205
+ /** Embedding dimensionality. */
206
+ get dimensions() {
207
+ return this.dims;
208
+ }
209
+ }
210
+ exports.LSHHasher = LSHHasher;
211
+ //# sourceMappingURL=lsh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lsh.js","sourceRoot":"","sources":["../../src/subgraph/lsh.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;;;AAEH,mDAA6C;AAC7C,mDAA+C;AAE/C,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,iDAAiD;AACjD,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,sDAAsD;AACtD,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,uFAAuF;AACvF,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E;;;;;GAKG;AACH,MAAa,SAAS;IACpB;;;;;;OAMG;IACK,WAAW,CAAiB;IAEpC,gCAAgC;IACf,IAAI,CAAS;IAE9B,yCAAyC;IACxB,OAAO,CAAS;IAEjC,8CAA8C;IAC7B,KAAK,CAAS;IAE/B;;;;;;;OAOG;IACH,YACE,IAAgB,EAChB,IAAY,EACZ,UAAkB,gBAAgB,EAClC,QAAgB,cAAc;QAE9B,IAAI,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,iDAAiD,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QAClF,CAAC;QACD,IAAI,IAAI,G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aces the naive `textScore` word-overlap scorer with a proper ranking
5
+ * pipeline:
6
+ * 1. Okapi BM25 — term frequency / inverse document frequency
7
+ * 2. Cosine similarity — between query and fact embeddings
8
+ * 3. Importance — normalized importance score (0-1)
9
+ * 4. Recency — time-decay with 1-week half-life
10
+ * 5. Weighted RRF (Reciprocal Rank Fusion) — combines all ranking lists
11
+ * 6. MMR (Maximal Marginal Relevance) — promotes diversity in results
12
+ *
13
+ * All functions are pure TypeScript with zero external dependencies (except
14
+ * porter-stemmer for morphological normalization). This module runs
15
+ * CLIENT-SIDE after decrypting candidates from the server.
16
+ */
17
+ export declare function tokenize(text: string, removeStopWords?: boolean): string[];
18
+ /**
19
+ * Compute the Okapi BM25 score for a single document against a query.
20
+ *
21
+ * Formula:
22
+ * score = SUM_i IDF(qi) * (f(qi, D) * (k1 + 1)) / (f(qi, D) + k1 * (1 - b + b * |D| / avgdl))
23
+ *
24
+ * where:
25
+ * IDF(qi) = ln((N - n(qi) + 0.5) / (n(qi) + 0.5) + 1)
26
+ * f(qi, D) = frequency of term qi in document D
27
+ * |D| = length of document D (in tokens)
28
+ * avgdl = average document length across the corpus
29
+ * N = total number of documents
30
+ * n(qi) = number of documents containing term qi
31
+ *
32
+ * @param queryTerms - Tokenized query terms
33
+ * @param docTerms - Tokenized document terms
34
+ * @param avgDocLen - Average document length (in tokens) across the candidate corpus
35
+ * @param docCount - Total number of documents in the candidate corpus
36
+ * @param termDocFreqs - Map from term to number of documents containing that term
37
+ * @param k1 - BM25 k1 parameter (default 1.2)
38
+ * @param b - BM25 b parameter (default 0.75)
39
+ */
40
+ export declare function bm25Score(queryTerms: string[], docTerms: string[], avgDocLen: number, docCount: number, termDocFreqs: Map<string, number>, k1?: number, b?: number): number;
41
+ /**
42
+ * Compute cosine similarity between two vectors.
43
+ *
44
+ * Returns dot(a, b) / (||a|| * ||b||).
45
+ * Returns 0 if either vector has zero magnitude (avoids division by zero).
46
+ */
47
+ export declare function cosineSimilarity(a: number[], b: number[]): number;
48
+ export interface RankedItem {
49
+ id: string;
50
+ score: number;
51
+ }
52
+ /**
53
+ * Fuse multiple ranking lists using Reciprocal Rank Fusion.
54
+ *
55
+ * For each document d appearing in any ranking list:
56
+ * rrfScore(d) = SUM_i 1 / (k + rank_i(d))
57
+ *
58
+ * where rank_i(d) is the 1-based rank of document d in the i-th list.
59
+ * Documents not present in a list are not penalized (they simply receive
60
+ * no contribution from that list).
61
+ *
62
+ * @param rankings - Array of ranking lists, each sorted by score descending.
63
+ * Each item has an `id` and a `score`.
64
+ * @param k - RRF smoothing constant (default 60, per the original paper).
65
+ * @returns - Fused ranking sorted by RRF score descending.
66
+ */
67
+ export declare function rrfFuse(rankings: RankedItem[][], k?: number): RankedItem[];
68
+ /**
69
+ * Fuse multiple ranking lists using Weighted Reciprocal Rank Fusion.
70
+ *
71
+ * Like standard RRF, but each ranking list's contribution is multiplied by
72
+ * its weight, allowing callers to emphasize or de-emphasize specific signals.
73
+ *
74
+ * @param rankings - Array of ranking lists, each sorted by score descending.
75
+ * @param weights - Weight for each ranking list (same length as rankings).
76
+ * @param k - RRF smoothing constant (default 60).
77
+ * @returns - Fused ranking sorted by weighted RRF score descending.
78
+ */
79
+ export declare function weightedRrfFuse(rankings: RankedItem[][], weights: number[], k?: number): RankedItem[];
80
+ export interface RankingWeights {
81
+ bm25: number;
82
+ cosine: number;
83
+ importance: number;
84
+ recency: number;
85
+ }
86
+ export declare const DEFAULT_WEIGHTS: RankingWeights;
87
+ /** The detected intent of a user query. */
88
+ export type QueryIntent = 'factual' | 'temporal' | 'semantic';
89
+ /** Ranking weights tuned for each query intent. */
90
+ export declare const INTENT_WEIGHTS: Record<QueryIntent, RankingWeights>;
91
+ /**
92
+ * Classify a query into one of three intent types using lightweight heuristics.
93
+ * Temporal is checked first so "What did we discuss yesterday?" -> temporal.
94
+ */
95
+ export declare function detectQueryIntent(query: string): QueryIntent;
96
+ export interface RerankerCandidate {
97
+ id: string;
98
+ text: string;
99
+ embedding?: number[];
100
+ importance?: number;
101
+ createdAt?: number;
102
+ }
103
+ export interface RerankerResult extends RerankerCandidate {
104
+ rrfScore: number;
105
+ cosineSimilarity?: number;
106
+ }
107
+ /**
108
+ * Apply Maximal Marginal Relevance to promote diversity in results.
109
+ *
110
+ * MMR re-orders a ranked list of candidates so that highly similar candidates
111
+ * are spread out. The algorithm greedily selects the candidate that maximizes:
112
+ *
113
+ * MMR(d) = lambda * relevance(d) - (1 - lambda) * max_sim(d, selected)
114
+ *
115
+ * where:
116
+ * - relevance(d) = position-based score (1.0 for first, linearly decreasing)
117
+ * - max_sim(d, selected) = max cosine similarity between d and any already
118
+ * selected candidate (0 if no embeddings available)
119
+ *
120
+ * @param candidates - Candidates in relevance order (best first)
121
+ * @param lambda - Trade-off between relevance and diversity (default 0.7)
122
+ * @param topK - Number of results to return (default 8)
123
+ * @returns - Re-ordered candidates with diversity
124
+ */
125
+ export declare function applyMMR(candidates: RerankerCandidate[], lambda?: number, topK?: number): RerankerCandidate[];
126
+ /**
127
+ * Re-rank decrypted candidates using BM25 + Cosine + Importance + Recency
128
+ * with Weighted RRF fusion and MMR diversity.
129
+ *
130
+ * Pipeline:
131
+ * 1. Tokenize query and all candidate texts
132
+ * 2. Build corpus statistics (term document frequencies, average doc length)
133
+ * 3. Score each candidate with BM25
134
+ * 4. Score each candidate with cosine similarity (if embedding available)
135
+ * 5. Score each candidate by importance
136
+ * 6. Score each candidate by recency
137
+ * 7. Fuse all 4 rankings with weighted RRF
138
+ * 8. Apply MMR for diversity
139
+ * 9. Return top-k candidates sorted by fused score
140
+ *
141
+ * Backward compatibility:
142
+ * - Candidates without embeddings get cosine score = 0 and are excluded
143
+ * from the cosine ranking list. They can still rank well via other signals.
144
+ * - If NO candidates have embeddings, cosine ranking is omitted.
145
+ * - Candidates without importance get neutral score (0.5).
146
+ * - Candidates without createdAt get neutral recency score (0.5).
147
+ * - topK defaults to 8, weights default to equal (0.25 each).
148
+ *
149
+ * @param query - The user's search query (plaintext)
150
+ * @param queryEmbedding - Embedding vector for the query
151
+ * @param candidates - Decrypted candidates with text and optional embeddings
152
+ * @param topK - Number of results to return (default 8)
153
+ * @param weights - Optional partial ranking weights (merged with defaults)
154
+ * @returns - Top-k candidates sorted by fused score, with scores attached
155
+ */
156
+ export declare function rerank(query: string, queryEmbedding: number[], candidates: RerankerCandidate[], topK?: number, weights?: Partial<RankingWeights>): RerankerResult[];
157
+ //# sourceMappingURL=reranker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reranker.d.ts","sourceRoot":"","sources":["../../src/subgraph/reranker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA8BH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,eAAe,GAAE,OAAc,GAAG,MAAM,EAAE,CAchF;AAMD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,SAAS,CACvB,UAAU,EAAE,MAAM,EAAE,EACpB,QAAQ,EAAE,MAAM,EAAE,EAClB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EACjC,EAAE,GAAE,MAAY,EAChB,CAAC,GAAE,MAAa,GACf,MAAM,CA6BR;AAMD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAkBjE;AAMD,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,UAAU,EAAE,EAAE,EACxB,CAAC,GAAE,MAAW,GACb,UAAU,EAAE,CAkBd;AAMD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,UAAU,EAAE,EAAE,EACxB,OAAO,EAAE,MAAM,EAAE,EACj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