@modusensus/dsh-mneme 0.6.9 → 0.6.10

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 (139) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +468 -219
  3. package/{dsh-mneme/cordis.patch.yml → cordis.patch.yml} +15 -15
  4. package/{dsh-mneme/src → lib}/api.js +783 -783
  5. package/{dsh-mneme/lib → lib}/client.js +1754 -1757
  6. package/{dsh-mneme/src → lib}/commands.js +64 -64
  7. package/{dsh-mneme/lib → lib}/config.js +298 -298
  8. package/{dsh-mneme/lib → lib}/dream/clustering.js +118 -118
  9. package/{dsh-mneme/lib → lib}/dream/decisions.js +488 -488
  10. package/{dsh-mneme/lib → lib}/dream/sleep.js +561 -561
  11. package/{dsh-mneme/src → lib}/dream/tag-extractor.js +156 -156
  12. package/{dsh-mneme/lib → lib}/dream.js +958 -958
  13. package/{dsh-mneme/src → lib}/embedding.js +154 -154
  14. package/{dsh-mneme/src → lib}/entities/extractor.js +242 -242
  15. package/{dsh-mneme/lib → lib}/hot-memory.js +53 -53
  16. package/{dsh-mneme/lib → lib}/index.js +361 -361
  17. package/{dsh-mneme/src → lib}/inject.js +208 -208
  18. package/{dsh-mneme/lib → lib}/local-embedder.js +282 -282
  19. package/{dsh-mneme/lib → lib}/mirror.js +170 -170
  20. package/{dsh-mneme/lib → lib}/parser/tag.js +59 -59
  21. package/{dsh-mneme/lib → lib}/parser/wiki-link.js +38 -38
  22. package/{dsh-mneme/src → lib}/quality-filter.js +123 -123
  23. package/{dsh-mneme/lib → lib}/reranker.js +218 -218
  24. package/{dsh-mneme/src → lib}/search/adaptive.js +22 -22
  25. package/{dsh-mneme/src → lib}/search/bm25.js +96 -96
  26. package/{dsh-mneme/src → lib}/search/tag-boost.js +61 -61
  27. package/{dsh-mneme/src → lib}/service.js +1726 -1726
  28. package/{dsh-mneme/lib → lib}/settings.js +172 -172
  29. package/{dsh-mneme/src → lib}/store.js +2238 -2238
  30. package/{dsh-mneme/src → lib}/summarize.js +236 -236
  31. package/{dsh-mneme/lib → lib}/tools.js +290 -290
  32. package/{dsh-mneme/lib → lib}/vector-index.js +116 -116
  33. package/package.json +40 -18
  34. package/{dsh-mneme/scripts → scripts}/benchmark-embed.js +201 -201
  35. package/{dsh-mneme/scripts → scripts}/benchmark-recall.js +133 -133
  36. package/{dsh-mneme/scripts → scripts}/benchmark-rerank.js +166 -166
  37. package/{dsh-mneme/scripts → scripts}/e2e-dsh.js +218 -218
  38. package/{dsh-mneme/scripts → scripts}/stress-dsh.js +255 -255
  39. package/{dsh-mneme/scripts → scripts}/sync-lib.js +52 -52
  40. package/{dsh-mneme/lib → src}/api.js +783 -783
  41. package/{dsh-mneme/lib → src}/commands.js +64 -64
  42. package/{dsh-mneme/src → src}/config.js +298 -298
  43. package/{dsh-mneme/src → src}/dream/clustering.js +118 -118
  44. package/{dsh-mneme/src → src}/dream/decisions.js +488 -488
  45. package/{dsh-mneme/src → src}/dream/sleep.js +561 -561
  46. package/{dsh-mneme/lib → src}/dream/tag-extractor.js +156 -156
  47. package/{dsh-mneme/src → src}/dream.js +958 -958
  48. package/{dsh-mneme/lib → src}/embedding.js +154 -154
  49. package/{dsh-mneme/lib → src}/entities/extractor.js +242 -242
  50. package/{dsh-mneme/src → src}/hot-memory.js +53 -53
  51. package/{dsh-mneme/src → src}/index.js +361 -361
  52. package/{dsh-mneme/lib → src}/inject.js +208 -208
  53. package/{dsh-mneme/src → src}/local-embedder.js +282 -282
  54. package/{dsh-mneme/src → src}/mirror.js +170 -170
  55. package/{dsh-mneme/src → src}/parser/tag.js +59 -59
  56. package/{dsh-mneme/src → src}/parser/wiki-link.js +38 -38
  57. package/{dsh-mneme/lib → src}/quality-filter.js +123 -123
  58. package/{dsh-mneme/src → src}/reranker.js +218 -218
  59. package/{dsh-mneme/lib → src}/search/adaptive.js +22 -22
  60. package/{dsh-mneme/lib → src}/search/bm25.js +96 -96
  61. package/{dsh-mneme/lib → src}/search/tag-boost.js +61 -61
  62. package/{dsh-mneme/lib → src}/service.js +1726 -1726
  63. package/{dsh-mneme/src → src}/settings.js +172 -172
  64. package/{dsh-mneme/lib → src}/store.js +2238 -2238
  65. package/{dsh-mneme/lib → src}/summarize.js +236 -236
  66. package/{dsh-mneme/src → src}/tools.js +290 -290
  67. package/{dsh-mneme/src → src}/vector-index.js +116 -116
  68. package/{dsh-mneme/test → test}/api.test.js +594 -594
  69. package/{dsh-mneme/test → test}/audit.test.js +448 -448
  70. package/{dsh-mneme/test → test}/benchmark.test.js +35 -35
  71. package/{dsh-mneme/test → test}/boundary-v0625.test.js +82 -82
  72. package/{dsh-mneme/test → test}/client.test.js +368 -368
  73. package/{dsh-mneme/test → test}/clustering.test.js +100 -100
  74. package/{dsh-mneme/test → test}/commands.test.js +69 -69
  75. package/{dsh-mneme/test → test}/config.test.js +50 -50
  76. package/{dsh-mneme/test → test}/conflict-freeze.test.js +290 -290
  77. package/{dsh-mneme/test → test}/directory.test.js +134 -134
  78. package/{dsh-mneme/test → test}/dream.test.js +1060 -1060
  79. package/{dsh-mneme/test → test}/entities.test.js +522 -522
  80. package/{dsh-mneme/test → test}/epistemic.test.js +298 -298
  81. package/{dsh-mneme/test → test}/fnew-0112.test.js +311 -311
  82. package/{dsh-mneme/test → test}/fnew-03.test.js +422 -422
  83. package/{dsh-mneme/test → test}/graph-api.test.js +175 -175
  84. package/{dsh-mneme/test → test}/helpers/dream-mock.js +82 -82
  85. package/{dsh-mneme/test → test}/hot-memory.test.js +174 -174
  86. package/{dsh-mneme/test → test}/inject.test.js +103 -103
  87. package/{dsh-mneme/test → test}/llm-audit.test.js +279 -279
  88. package/{dsh-mneme/test → test}/local-embedder.test.js +227 -227
  89. package/{dsh-mneme/test → test}/mirror-dirty.test.js +424 -424
  90. package/{dsh-mneme/test → test}/mirror-edit-digest.test.js +187 -187
  91. package/{dsh-mneme/test → test}/mirror-generation.test.js +499 -499
  92. package/{dsh-mneme/test → test}/mirror.test.js +249 -249
  93. package/{dsh-mneme/test → test}/normalize-decisions.test.js +120 -120
  94. package/{dsh-mneme/test → test}/peer-blockers.test.js +190 -190
  95. package/{dsh-mneme/test → test}/policy-epoch.test.js +259 -259
  96. package/{dsh-mneme/test → test}/provenance.test.js +103 -103
  97. package/{dsh-mneme/test → test}/quality-filter.test.js +118 -118
  98. package/{dsh-mneme/test → test}/reasoning-effort.test.js +199 -199
  99. package/{dsh-mneme/test → test}/recall-evals.test.js +235 -235
  100. package/{dsh-mneme/test → test}/recall-layer.test.js +315 -315
  101. package/{dsh-mneme/test → test}/receipt-chain.test.js +451 -451
  102. package/{dsh-mneme/test → test}/reflection.test.js +226 -226
  103. package/{dsh-mneme/test → test}/reranker.test.js +240 -240
  104. package/{dsh-mneme/test → test}/search-fusion.test.js +90 -90
  105. package/{dsh-mneme/test → test}/semantic.test.js +124 -124
  106. package/{dsh-mneme/test → test}/service-search.test.js +199 -199
  107. package/{dsh-mneme/test → test}/service.test.js +435 -435
  108. package/{dsh-mneme/test → test}/settings.test.js +118 -118
  109. package/{dsh-mneme/test → test}/sleep.test.js +365 -365
  110. package/{dsh-mneme/test → test}/store.test.js +436 -436
  111. package/{dsh-mneme/test → test}/stress.test.js +209 -209
  112. package/{dsh-mneme/test → test}/summarize.test.js +191 -191
  113. package/{dsh-mneme/test → test}/tag-boost.test.js +125 -125
  114. package/{dsh-mneme/test → test}/tag.test.js +312 -312
  115. package/{dsh-mneme/test → test}/tools.test.js +285 -285
  116. package/{dsh-mneme/test → test}/vector-index.test.js +221 -221
  117. package/{dsh-mneme/test → test}/wiki-link.test.js +332 -332
  118. package/.github/workflows/test.yml +0 -32
  119. package/.release-notes-v0.6.9.md +0 -13
  120. package/CHANGELOG.md +0 -89
  121. package/SECURITY.md +0 -544
  122. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +0 -247
  123. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +0 -145
  124. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +0 -56
  125. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +0 -77
  126. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +0 -64
  127. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +0 -90
  128. package/dsh-mneme/CHANGELOG.md +0 -248
  129. package/dsh-mneme/LICENSE +0 -21
  130. package/dsh-mneme/README.md +0 -465
  131. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +0 -183
  132. package/dsh-mneme/docs/ENTITIES.md +0 -245
  133. package/dsh-mneme/docs/LOCAL_MODEL.md +0 -141
  134. package/dsh-mneme/docs/MIGRATION.md +0 -127
  135. package/dsh-mneme/docs/SEMANTIC.md +0 -256
  136. package/dsh-mneme/docs/SLEEP.md +0 -163
  137. package/dsh-mneme/package-lock.json +0 -1936
  138. package/dsh-mneme/package.json +0 -80
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,218 +1,218 @@
1
- import os from "node:os";
2
- import path from "node:path";
3
-
4
- // Cross-encoder re-ranker for dsh-mneme recall candidates. Uses
5
- // bge-reranker-base through transformers.js: tries the native `rerank` task
6
- // first, then the sequence-classification head (sigmoid on the logit delta),
7
- // and finally feature-extraction over concatenated query+passage (cosine).
8
- // Every strategy funnels into scorePair(query, passage) so tests can inject a
9
- // fake scorer and never download a model. Failures throw — the caller degrades
10
- // back to the original candidate order.
11
- function hashString(s) {
12
- let h = 5381;
13
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
14
- return h.toString(16);
15
- }
16
-
17
- /** Same provider#hash fingerprint convention as the embedders. */
18
- function modelHash(model) {
19
- return `${model}#${hashString(model)}`;
20
- }
21
-
22
- /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
- async function defaultPipelineLoader(task, model, options) {
24
- const { env, pipeline } = await import("@huggingface/transformers");
25
- // issue #13: mirror cache_dir onto env.cacheDir so the tokenizer pre-check
26
- // resolves locally too (same fix as local-embedder.js).
27
- if (options?.cache_dir) env.cacheDir = options.cache_dir;
28
- return pipeline(task, model, options);
29
- }
30
-
31
- /** Flatten a transformers.js Tensor [batch, seq, dim] into number[][] rows. */
32
- function tensorToRows(tensor) {
33
- const { data, dims } = tensor;
34
- const dim = dims[dims.length - 1] || 0;
35
- const rows = [];
36
- for (let i = 0; i < data.length; i += dim) rows.push(Array.from(data.subarray(i, i + dim)));
37
- if (rows.length === 0 && dim > 0) rows.push(Array.from(data));
38
- return rows;
39
- }
40
-
41
- function cosine(a, b) {
42
- let dot = 0;
43
- let na = 0;
44
- let nb = 0;
45
- for (let i = 0; i < a.length; i++) {
46
- dot += a[i] * b[i];
47
- na += a[i] * a[i];
48
- nb += b[i] * b[i];
49
- }
50
- if (na === 0 || nb === 0) return 0;
51
- return dot / Math.sqrt(na * nb);
52
- }
53
-
54
- function clamp01(x) {
55
- return Math.max(0, Math.min(1, x));
56
- }
57
-
58
- // Pipeline strategies, best to worst. `rerank` is unsupported by the bundled
59
- // transformers.js (v4.2.0) and rejects cheaply before any model download, so
60
- // the cascade normally lands on the classification head.
61
- const STRATEGIES = [
62
- ["rerank", "rerank"],
63
- ["text-classification", "tc"],
64
- ["feature-extraction", "fe"]
65
- ];
66
-
67
- export class LocalReranker {
68
- constructor(opts = {}) {
69
- this.model = opts.model || "Xenova/bge-reranker-base";
70
- this.batchSize = opts.batchSize || 8;
71
- this.maxCandidates = opts.maxCandidates || 30;
72
- this.scoreThreshold = opts.scoreThreshold ?? 0.1;
73
- this.device = opts.device || "cpu";
74
- this.cacheDir =
75
- String(opts.cacheDir ?? "").trim() ||
76
- path.join(os.homedir(), ".dsh", "mneme", "models");
77
- this.logger = opts.logger ?? null;
78
- this.engineFactory = opts.engineFactory || defaultPipelineLoader;
79
- // Injectable seam: async (query, passage) => number. When set, init()
80
- // skips model loading entirely so tests never hit the network.
81
- this.scorePair = opts.scorePair ?? null;
82
- this.pipeline = null;
83
- this._batchScorer = null;
84
- this._queryVec = null;
85
- this._queryKey = null;
86
- }
87
-
88
- /** Load the model; throws when no strategy can be bound. */
89
- async init() {
90
- if (this.scorePair) return this;
91
- let lastErr = null;
92
- for (const [task, strategy] of STRATEGIES) {
93
- try {
94
- this.pipeline = await this.engineFactory(task, this.model, this._engineOptions());
95
- this._bindBatchScorer(strategy);
96
- this.logger?.info?.(
97
- `[dsh-mneme] local reranker ready: ${this.model} (strategy=${strategy}, device=${this.device})`
98
- );
99
- return this;
100
- } catch (err) {
101
- lastErr = err;
102
- this.logger?.warn?.(
103
- `[dsh-mneme] reranker task "${task}" unavailable for ${this.model}: ${String(err?.message ?? err)}`
104
- );
105
- }
106
- }
107
- throw new Error(`LocalReranker failed to load ${this.model}: ${String(lastErr?.message ?? lastErr)}`);
108
- }
109
-
110
- _engineOptions() {
111
- const options = { device: this.device };
112
- if (this.cacheDir) options.cache_dir = this.cacheDir;
113
- return options;
114
- }
115
-
116
- /** Bind a batch scorer for the chosen strategy. */
117
- _bindBatchScorer(strategy) {
118
- if (strategy === "rerank") {
119
- // Native cross-encoder task (transformers.js >= 4.6): { query, documents }
120
- // returns one score per document.
121
- this._batchScorer = async (query, passages) => {
122
- const out = await this.pipeline({ query, documents: passages });
123
- if (!Array.isArray(out)) throw new Error("rerank pipeline returned unexpected output");
124
- return out.map((r) => clamp01(typeof r?.score === "number" ? r.score : 0));
125
- };
126
- } else if (strategy === "tc") {
127
- // Classification head: tokenize (query, passage) pairs, score with
128
- // sigmoid(l1 - l0) so relevance lands in [0, 1].
129
- this._batchScorer = async (query, passages) => {
130
- const { tokenizer, model } = this.pipeline;
131
- const inputs = tokenizer(passages.map(() => query), {
132
- text_pair: passages,
133
- padding: true,
134
- truncation: true
135
- });
136
- const logits = await model(inputs).then((o) => o.logits);
137
- const dims = logits.dims;
138
- const cols = dims[dims.length - 1] || 2;
139
- const rows = [];
140
- for (let i = 0; i < dims[0]; i++) {
141
- const base = i * cols;
142
- const l0 = logits.data[base];
143
- const l1 = cols > 1 ? logits.data[base + 1] : l0;
144
- // sigmoid(l1 - l0) == softmax probability of the positive class.
145
- rows.push(clamp01(1 / (1 + Math.exp(l0 - l1))));
146
- }
147
- return rows;
148
- };
149
- } else {
150
- // Feature extraction: mean-pool the concatenated pair and compare with
151
- // the query embedding via cosine. Degraded but model-agnostic.
152
- // The query vector is cached per query string, so a new query always
153
- // recomputes it instead of reusing a stale vector from the previous call.
154
- this._queryVec = null;
155
- this._queryKey = null;
156
- this._batchScorer = async (query, passages) => {
157
- if (this._queryKey !== query) {
158
- const t = await this.pipeline([query], { pooling: "mean", normalize: true });
159
- this._queryVec = tensorToRows(t)[0];
160
- this._queryKey = query;
161
- }
162
- const t = await this.pipeline(passages.map((p) => `${query}\n${p}`), {
163
- pooling: "mean",
164
- normalize: true
165
- });
166
- return tensorToRows(t).map((v) => clamp01(cosine(this._queryVec, v)));
167
- };
168
- }
169
- }
170
-
171
- /** Score one batch of passages; injected scorePair scores pair by pair. */
172
- async _scores(query, passages) {
173
- if (this._batchScorer) return this._batchScorer(query, passages);
174
- return Promise.all(passages.map((p) => (p ? this.scorePair(query, p) : 0)));
175
- }
176
-
177
- /**
178
- * Re-rank recall candidates. Returns [{ id, score }] filtered by
179
- * scoreThreshold and sorted by descending score. Throws on engine failure —
180
- * the caller degrades to the original candidate order.
181
- */
182
- async rerank(query, candidates) {
183
- if (!Array.isArray(candidates)) throw new TypeError("rerank expects an array of candidates");
184
- const list = candidates.slice(0, this.maxCandidates);
185
- if (!list.length) return [];
186
- const q = String(query ?? "");
187
- const results = [];
188
- for (let i = 0; i < list.length; i += this.batchSize) {
189
- const chunk = list.slice(i, i + this.batchSize);
190
- const passages = chunk.map((c) => [c.title, c.content].filter(Boolean).join("\n"));
191
- const scores = await this._scores(q, passages);
192
- if (!Array.isArray(scores) || scores.length !== chunk.length) {
193
- throw new Error("reranker scorer returned mismatched scores");
194
- }
195
- for (let j = 0; j < chunk.length; j++) {
196
- results.push({ id: chunk[j].id, score: clamp01(Number(scores[j]) || 0) });
197
- }
198
- }
199
- return results
200
- .filter((r) => r.score >= this.scoreThreshold)
201
- .sort((a, b) => b.score - a.score);
202
- }
203
-
204
- get modelHash() {
205
- return modelHash(this.model);
206
- }
207
-
208
- dispose() {
209
- try {
210
- this.pipeline?.dispose?.();
211
- } catch {
212
- // best-effort: some engines free resources on GC
213
- }
214
- this.pipeline = null;
215
- this._queryVec = null;
216
- this._queryKey = null;
217
- }
218
- }
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ // Cross-encoder re-ranker for dsh-mneme recall candidates. Uses
5
+ // bge-reranker-base through transformers.js: tries the native `rerank` task
6
+ // first, then the sequence-classification head (sigmoid on the logit delta),
7
+ // and finally feature-extraction over concatenated query+passage (cosine).
8
+ // Every strategy funnels into scorePair(query, passage) so tests can inject a
9
+ // fake scorer and never download a model. Failures throw — the caller degrades
10
+ // back to the original candidate order.
11
+ function hashString(s) {
12
+ let h = 5381;
13
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
14
+ return h.toString(16);
15
+ }
16
+
17
+ /** Same provider#hash fingerprint convention as the embedders. */
18
+ function modelHash(model) {
19
+ return `${model}#${hashString(model)}`;
20
+ }
21
+
22
+ /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
+ async function defaultPipelineLoader(task, model, options) {
24
+ const { env, pipeline } = await import("@huggingface/transformers");
25
+ // issue #13: mirror cache_dir onto env.cacheDir so the tokenizer pre-check
26
+ // resolves locally too (same fix as local-embedder.js).
27
+ if (options?.cache_dir) env.cacheDir = options.cache_dir;
28
+ return pipeline(task, model, options);
29
+ }
30
+
31
+ /** Flatten a transformers.js Tensor [batch, seq, dim] into number[][] rows. */
32
+ function tensorToRows(tensor) {
33
+ const { data, dims } = tensor;
34
+ const dim = dims[dims.length - 1] || 0;
35
+ const rows = [];
36
+ for (let i = 0; i < data.length; i += dim) rows.push(Array.from(data.subarray(i, i + dim)));
37
+ if (rows.length === 0 && dim > 0) rows.push(Array.from(data));
38
+ return rows;
39
+ }
40
+
41
+ function cosine(a, b) {
42
+ let dot = 0;
43
+ let na = 0;
44
+ let nb = 0;
45
+ for (let i = 0; i < a.length; i++) {
46
+ dot += a[i] * b[i];
47
+ na += a[i] * a[i];
48
+ nb += b[i] * b[i];
49
+ }
50
+ if (na === 0 || nb === 0) return 0;
51
+ return dot / Math.sqrt(na * nb);
52
+ }
53
+
54
+ function clamp01(x) {
55
+ return Math.max(0, Math.min(1, x));
56
+ }
57
+
58
+ // Pipeline strategies, best to worst. `rerank` is unsupported by the bundled
59
+ // transformers.js (v4.2.0) and rejects cheaply before any model download, so
60
+ // the cascade normally lands on the classification head.
61
+ const STRATEGIES = [
62
+ ["rerank", "rerank"],
63
+ ["text-classification", "tc"],
64
+ ["feature-extraction", "fe"]
65
+ ];
66
+
67
+ export class LocalReranker {
68
+ constructor(opts = {}) {
69
+ this.model = opts.model || "Xenova/bge-reranker-base";
70
+ this.batchSize = opts.batchSize || 8;
71
+ this.maxCandidates = opts.maxCandidates || 30;
72
+ this.scoreThreshold = opts.scoreThreshold ?? 0.1;
73
+ this.device = opts.device || "cpu";
74
+ this.cacheDir =
75
+ String(opts.cacheDir ?? "").trim() ||
76
+ path.join(os.homedir(), ".dsh", "mneme", "models");
77
+ this.logger = opts.logger ?? null;
78
+ this.engineFactory = opts.engineFactory || defaultPipelineLoader;
79
+ // Injectable seam: async (query, passage) => number. When set, init()
80
+ // skips model loading entirely so tests never hit the network.
81
+ this.scorePair = opts.scorePair ?? null;
82
+ this.pipeline = null;
83
+ this._batchScorer = null;
84
+ this._queryVec = null;
85
+ this._queryKey = null;
86
+ }
87
+
88
+ /** Load the model; throws when no strategy can be bound. */
89
+ async init() {
90
+ if (this.scorePair) return this;
91
+ let lastErr = null;
92
+ for (const [task, strategy] of STRATEGIES) {
93
+ try {
94
+ this.pipeline = await this.engineFactory(task, this.model, this._engineOptions());
95
+ this._bindBatchScorer(strategy);
96
+ this.logger?.info?.(
97
+ `[dsh-mneme] local reranker ready: ${this.model} (strategy=${strategy}, device=${this.device})`
98
+ );
99
+ return this;
100
+ } catch (err) {
101
+ lastErr = err;
102
+ this.logger?.warn?.(
103
+ `[dsh-mneme] reranker task "${task}" unavailable for ${this.model}: ${String(err?.message ?? err)}`
104
+ );
105
+ }
106
+ }
107
+ throw new Error(`LocalReranker failed to load ${this.model}: ${String(lastErr?.message ?? lastErr)}`);
108
+ }
109
+
110
+ _engineOptions() {
111
+ const options = { device: this.device };
112
+ if (this.cacheDir) options.cache_dir = this.cacheDir;
113
+ return options;
114
+ }
115
+
116
+ /** Bind a batch scorer for the chosen strategy. */
117
+ _bindBatchScorer(strategy) {
118
+ if (strategy === "rerank") {
119
+ // Native cross-encoder task (transformers.js >= 4.6): { query, documents }
120
+ // returns one score per document.
121
+ this._batchScorer = async (query, passages) => {
122
+ const out = await this.pipeline({ query, documents: passages });
123
+ if (!Array.isArray(out)) throw new Error("rerank pipeline returned unexpected output");
124
+ return out.map((r) => clamp01(typeof r?.score === "number" ? r.score : 0));
125
+ };
126
+ } else if (strategy === "tc") {
127
+ // Classification head: tokenize (query, passage) pairs, score with
128
+ // sigmoid(l1 - l0) so relevance lands in [0, 1].
129
+ this._batchScorer = async (query, passages) => {
130
+ const { tokenizer, model } = this.pipeline;
131
+ const inputs = tokenizer(passages.map(() => query), {
132
+ text_pair: passages,
133
+ padding: true,
134
+ truncation: true
135
+ });
136
+ const logits = await model(inputs).then((o) => o.logits);
137
+ const dims = logits.dims;
138
+ const cols = dims[dims.length - 1] || 2;
139
+ const rows = [];
140
+ for (let i = 0; i < dims[0]; i++) {
141
+ const base = i * cols;
142
+ const l0 = logits.data[base];
143
+ const l1 = cols > 1 ? logits.data[base + 1] : l0;
144
+ // sigmoid(l1 - l0) == softmax probability of the positive class.
145
+ rows.push(clamp01(1 / (1 + Math.exp(l0 - l1))));
146
+ }
147
+ return rows;
148
+ };
149
+ } else {
150
+ // Feature extraction: mean-pool the concatenated pair and compare with
151
+ // the query embedding via cosine. Degraded but model-agnostic.
152
+ // The query vector is cached per query string, so a new query always
153
+ // recomputes it instead of reusing a stale vector from the previous call.
154
+ this._queryVec = null;
155
+ this._queryKey = null;
156
+ this._batchScorer = async (query, passages) => {
157
+ if (this._queryKey !== query) {
158
+ const t = await this.pipeline([query], { pooling: "mean", normalize: true });
159
+ this._queryVec = tensorToRows(t)[0];
160
+ this._queryKey = query;
161
+ }
162
+ const t = await this.pipeline(passages.map((p) => `${query}\n${p}`), {
163
+ pooling: "mean",
164
+ normalize: true
165
+ });
166
+ return tensorToRows(t).map((v) => clamp01(cosine(this._queryVec, v)));
167
+ };
168
+ }
169
+ }
170
+
171
+ /** Score one batch of passages; injected scorePair scores pair by pair. */
172
+ async _scores(query, passages) {
173
+ if (this._batchScorer) return this._batchScorer(query, passages);
174
+ return Promise.all(passages.map((p) => (p ? this.scorePair(query, p) : 0)));
175
+ }
176
+
177
+ /**
178
+ * Re-rank recall candidates. Returns [{ id, score }] filtered by
179
+ * scoreThreshold and sorted by descending score. Throws on engine failure —
180
+ * the caller degrades to the original candidate order.
181
+ */
182
+ async rerank(query, candidates) {
183
+ if (!Array.isArray(candidates)) throw new TypeError("rerank expects an array of candidates");
184
+ const list = candidates.slice(0, this.maxCandidates);
185
+ if (!list.length) return [];
186
+ const q = String(query ?? "");
187
+ const results = [];
188
+ for (let i = 0; i < list.length; i += this.batchSize) {
189
+ const chunk = list.slice(i, i + this.batchSize);
190
+ const passages = chunk.map((c) => [c.title, c.content].filter(Boolean).join("\n"));
191
+ const scores = await this._scores(q, passages);
192
+ if (!Array.isArray(scores) || scores.length !== chunk.length) {
193
+ throw new Error("reranker scorer returned mismatched scores");
194
+ }
195
+ for (let j = 0; j < chunk.length; j++) {
196
+ results.push({ id: chunk[j].id, score: clamp01(Number(scores[j]) || 0) });
197
+ }
198
+ }
199
+ return results
200
+ .filter((r) => r.score >= this.scoreThreshold)
201
+ .sort((a, b) => b.score - a.score);
202
+ }
203
+
204
+ get modelHash() {
205
+ return modelHash(this.model);
206
+ }
207
+
208
+ dispose() {
209
+ try {
210
+ this.pipeline?.dispose?.();
211
+ } catch {
212
+ // best-effort: some engines free resources on GC
213
+ }
214
+ this.pipeline = null;
215
+ this._queryVec = null;
216
+ this._queryKey = null;
217
+ }
218
+ }
@@ -1,22 +1,22 @@
1
- // Adaptive vector threshold (v0.5.0 召回率优化 1.2): replaces the fixed
2
- // vectorSearchThreshold=0.65 with a query-aware cutoff.
3
- // entity:/attr: prefixes → 0.5 (entity recall is name-driven; loosen)
4
- // very short queries → 0.7 (<5 chars match almost anything; tighten)
5
- // very long queries → 0.6 (semantically specific; loosen a little)
6
- // head-gap rule → when the top-1 vs top-5 candidate gap exceeds
7
- // 0.3 the head is decisive — loosen to 0.5 so
8
- // the tail still reaches the reranker
9
- // otherwise → 0.65 (the legacy default)
10
- // Pure and total: same inputs, same cutoff, no store access.
11
- export function adaptiveThreshold(query, candidates = []) {
12
- const q = String(query ?? "");
13
- if (q.startsWith("entity:") || q.startsWith("attr:")) return 0.5;
14
- if (q.length > 0 && q.length < 5) return 0.7;
15
- if (q.length > 50) return 0.6;
16
- const scores = (Array.isArray(candidates) ? candidates : [])
17
- .map((c) => (typeof c?._score === "number" ? c._score : typeof c?.score === "number" ? c.score : 0))
18
- .filter((s) => s > 0)
19
- .sort((a, b) => b - a);
20
- if (scores.length >= 5 && scores[0] - scores[4] > 0.3) return 0.5;
21
- return 0.65;
22
- }
1
+ // Adaptive vector threshold (v0.5.0 召回率优化 1.2): replaces the fixed
2
+ // vectorSearchThreshold=0.65 with a query-aware cutoff.
3
+ // entity:/attr: prefixes → 0.5 (entity recall is name-driven; loosen)
4
+ // very short queries → 0.7 (<5 chars match almost anything; tighten)
5
+ // very long queries → 0.6 (semantically specific; loosen a little)
6
+ // head-gap rule → when the top-1 vs top-5 candidate gap exceeds
7
+ // 0.3 the head is decisive — loosen to 0.5 so
8
+ // the tail still reaches the reranker
9
+ // otherwise → 0.65 (the legacy default)
10
+ // Pure and total: same inputs, same cutoff, no store access.
11
+ export function adaptiveThreshold(query, candidates = []) {
12
+ const q = String(query ?? "");
13
+ if (q.startsWith("entity:") || q.startsWith("attr:")) return 0.5;
14
+ if (q.length > 0 && q.length < 5) return 0.7;
15
+ if (q.length > 50) return 0.6;
16
+ const scores = (Array.isArray(candidates) ? candidates : [])
17
+ .map((c) => (typeof c?._score === "number" ? c._score : typeof c?.score === "number" ? c.score : 0))
18
+ .filter((s) => s > 0)
19
+ .sort((a, b) => b - a);
20
+ if (scores.length >= 5 && scores[0] - scores[4] > 0.3) return 0.5;
21
+ return 0.65;
22
+ }