@modusensus/dsh-mneme 0.6.7 → 0.6.9

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/.github/workflows/test.yml +32 -0
  2. package/.release-notes-v0.6.9.md +13 -0
  3. package/CHANGELOG.md +89 -0
  4. package/LICENSE +21 -21
  5. package/README.md +219 -463
  6. package/SECURITY.md +544 -0
  7. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +247 -0
  8. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +145 -0
  9. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +56 -0
  10. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +77 -0
  11. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +64 -0
  12. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +90 -0
  13. package/dsh-mneme/CHANGELOG.md +248 -0
  14. package/dsh-mneme/LICENSE +21 -0
  15. package/dsh-mneme/README.md +465 -0
  16. package/{cordis.patch.yml → dsh-mneme/cordis.patch.yml} +15 -15
  17. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +183 -0
  18. package/dsh-mneme/docs/ENTITIES.md +245 -0
  19. package/dsh-mneme/docs/LOCAL_MODEL.md +141 -0
  20. package/dsh-mneme/docs/MIGRATION.md +127 -0
  21. package/dsh-mneme/docs/SEMANTIC.md +256 -0
  22. package/dsh-mneme/docs/SLEEP.md +163 -0
  23. package/{lib → dsh-mneme/lib}/api.js +783 -783
  24. package/{lib → dsh-mneme/lib}/client.js +1757 -1757
  25. package/{src → dsh-mneme/lib}/commands.js +64 -64
  26. package/{lib → dsh-mneme/lib}/config.js +298 -288
  27. package/{lib → dsh-mneme/lib}/dream/clustering.js +118 -118
  28. package/{src → dsh-mneme/lib}/dream/decisions.js +488 -439
  29. package/{lib → dsh-mneme/lib}/dream/sleep.js +561 -554
  30. package/{src → dsh-mneme/lib}/dream/tag-extractor.js +156 -156
  31. package/{lib → dsh-mneme/lib}/dream.js +958 -929
  32. package/{src → dsh-mneme/lib}/embedding.js +154 -154
  33. package/{src → dsh-mneme/lib}/entities/extractor.js +242 -242
  34. package/{src → dsh-mneme/lib}/hot-memory.js +53 -53
  35. package/{lib → dsh-mneme/lib}/index.js +361 -361
  36. package/{src → dsh-mneme/lib}/inject.js +208 -208
  37. package/{lib → dsh-mneme/lib}/local-embedder.js +282 -282
  38. package/{lib → dsh-mneme/lib}/mirror.js +170 -170
  39. package/{lib → dsh-mneme/lib}/parser/tag.js +59 -59
  40. package/{lib → dsh-mneme/lib}/parser/wiki-link.js +38 -38
  41. package/{src → dsh-mneme/lib}/quality-filter.js +123 -123
  42. package/{lib → dsh-mneme/lib}/reranker.js +218 -218
  43. package/{lib → dsh-mneme/lib}/search/adaptive.js +22 -22
  44. package/{lib → dsh-mneme/lib}/search/bm25.js +96 -96
  45. package/{src → dsh-mneme/lib}/search/tag-boost.js +61 -61
  46. package/{src → dsh-mneme/lib}/service.js +1726 -1726
  47. package/{lib → dsh-mneme/lib}/settings.js +172 -172
  48. package/{lib → dsh-mneme/lib}/store.js +2238 -2238
  49. package/{lib → dsh-mneme/lib}/summarize.js +236 -236
  50. package/{lib → dsh-mneme/lib}/tools.js +290 -290
  51. package/{lib → dsh-mneme/lib}/vector-index.js +116 -116
  52. package/dsh-mneme/package-lock.json +1936 -0
  53. package/dsh-mneme/package.json +80 -0
  54. package/{scripts → dsh-mneme/scripts}/benchmark-embed.js +201 -201
  55. package/{scripts → dsh-mneme/scripts}/benchmark-recall.js +133 -133
  56. package/{scripts → dsh-mneme/scripts}/benchmark-rerank.js +166 -166
  57. package/{scripts → dsh-mneme/scripts}/e2e-dsh.js +218 -218
  58. package/{scripts → dsh-mneme/scripts}/stress-dsh.js +255 -255
  59. package/{scripts → dsh-mneme/scripts}/sync-lib.js +52 -52
  60. package/{src → dsh-mneme/src}/api.js +783 -783
  61. package/{lib → dsh-mneme/src}/commands.js +64 -64
  62. package/{src → dsh-mneme/src}/config.js +298 -288
  63. package/{src → dsh-mneme/src}/dream/clustering.js +118 -118
  64. package/{lib → dsh-mneme/src}/dream/decisions.js +488 -439
  65. package/{src → dsh-mneme/src}/dream/sleep.js +561 -554
  66. package/{lib → dsh-mneme/src}/dream/tag-extractor.js +156 -156
  67. package/{src → dsh-mneme/src}/dream.js +958 -929
  68. package/{lib → dsh-mneme/src}/embedding.js +154 -154
  69. package/{lib → dsh-mneme/src}/entities/extractor.js +242 -242
  70. package/{lib → dsh-mneme/src}/hot-memory.js +53 -53
  71. package/{src → dsh-mneme/src}/index.js +361 -361
  72. package/{lib → dsh-mneme/src}/inject.js +208 -208
  73. package/{src → dsh-mneme/src}/local-embedder.js +282 -282
  74. package/{src → dsh-mneme/src}/mirror.js +170 -170
  75. package/{src → dsh-mneme/src}/parser/tag.js +59 -59
  76. package/{src → dsh-mneme/src}/parser/wiki-link.js +38 -38
  77. package/{lib → dsh-mneme/src}/quality-filter.js +123 -123
  78. package/{src → dsh-mneme/src}/reranker.js +218 -218
  79. package/{src → dsh-mneme/src}/search/adaptive.js +22 -22
  80. package/{src → dsh-mneme/src}/search/bm25.js +96 -96
  81. package/{lib → dsh-mneme/src}/search/tag-boost.js +61 -61
  82. package/{lib → dsh-mneme/src}/service.js +1726 -1726
  83. package/{src → dsh-mneme/src}/settings.js +172 -172
  84. package/{src → dsh-mneme/src}/store.js +2238 -2238
  85. package/{src → dsh-mneme/src}/summarize.js +236 -236
  86. package/{src → dsh-mneme/src}/tools.js +290 -290
  87. package/{src → dsh-mneme/src}/vector-index.js +116 -116
  88. package/{test → dsh-mneme/test}/api.test.js +594 -594
  89. package/{test → dsh-mneme/test}/audit.test.js +448 -448
  90. package/{test → dsh-mneme/test}/benchmark.test.js +35 -35
  91. package/{test → dsh-mneme/test}/boundary-v0625.test.js +82 -82
  92. package/{test → dsh-mneme/test}/client.test.js +368 -368
  93. package/{test → dsh-mneme/test}/clustering.test.js +100 -100
  94. package/{test → dsh-mneme/test}/commands.test.js +69 -69
  95. package/{test → dsh-mneme/test}/config.test.js +50 -50
  96. package/{test → dsh-mneme/test}/conflict-freeze.test.js +290 -290
  97. package/{test → dsh-mneme/test}/directory.test.js +134 -134
  98. package/{test → dsh-mneme/test}/dream.test.js +1060 -901
  99. package/{test → dsh-mneme/test}/entities.test.js +522 -522
  100. package/{test → dsh-mneme/test}/epistemic.test.js +298 -298
  101. package/{test → dsh-mneme/test}/fnew-0112.test.js +311 -311
  102. package/{test → dsh-mneme/test}/fnew-03.test.js +422 -422
  103. package/{test → dsh-mneme/test}/graph-api.test.js +175 -175
  104. package/{test → dsh-mneme/test}/helpers/dream-mock.js +82 -82
  105. package/{test → dsh-mneme/test}/hot-memory.test.js +174 -174
  106. package/{test → dsh-mneme/test}/inject.test.js +103 -103
  107. package/{test → dsh-mneme/test}/llm-audit.test.js +279 -279
  108. package/{test → dsh-mneme/test}/local-embedder.test.js +227 -227
  109. package/{test → dsh-mneme/test}/mirror-dirty.test.js +424 -424
  110. package/{test → dsh-mneme/test}/mirror-edit-digest.test.js +187 -187
  111. package/{test → dsh-mneme/test}/mirror-generation.test.js +499 -499
  112. package/{test → dsh-mneme/test}/mirror.test.js +249 -249
  113. package/{test → dsh-mneme/test}/normalize-decisions.test.js +120 -120
  114. package/{test → dsh-mneme/test}/peer-blockers.test.js +190 -190
  115. package/{test → dsh-mneme/test}/policy-epoch.test.js +259 -259
  116. package/{test → dsh-mneme/test}/provenance.test.js +103 -103
  117. package/{test → dsh-mneme/test}/quality-filter.test.js +118 -118
  118. package/{test → dsh-mneme/test}/reasoning-effort.test.js +199 -199
  119. package/{test → dsh-mneme/test}/recall-evals.test.js +235 -235
  120. package/{test → dsh-mneme/test}/recall-layer.test.js +315 -315
  121. package/{test → dsh-mneme/test}/receipt-chain.test.js +451 -451
  122. package/{test → dsh-mneme/test}/reflection.test.js +226 -226
  123. package/{test → dsh-mneme/test}/reranker.test.js +240 -240
  124. package/{test → dsh-mneme/test}/search-fusion.test.js +90 -90
  125. package/{test → dsh-mneme/test}/semantic.test.js +124 -124
  126. package/{test → dsh-mneme/test}/service-search.test.js +199 -199
  127. package/{test → dsh-mneme/test}/service.test.js +435 -435
  128. package/{test → dsh-mneme/test}/settings.test.js +118 -118
  129. package/{test → dsh-mneme/test}/sleep.test.js +365 -365
  130. package/{test → dsh-mneme/test}/store.test.js +436 -436
  131. package/{test → dsh-mneme/test}/stress.test.js +209 -209
  132. package/{test → dsh-mneme/test}/summarize.test.js +191 -191
  133. package/{test → dsh-mneme/test}/tag-boost.test.js +125 -125
  134. package/{test → dsh-mneme/test}/tag.test.js +312 -312
  135. package/{test → dsh-mneme/test}/tools.test.js +285 -285
  136. package/{test → dsh-mneme/test}/vector-index.test.js +221 -221
  137. package/{test → dsh-mneme/test}/wiki-link.test.js +332 -332
  138. package/package.json +18 -40
  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
+ }