@modusensus/dsh-mneme 0.5.0 → 0.5.1

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.
@@ -1,282 +1,282 @@
1
- // Fully-local embedding backends for dsh-mneme: ONNX via transformers.js,
2
- // Ollama's HTTP API, and the OpenAI-compatible HTTP API (extracted from the
3
- // old embedding.js logic). All classes share one interface so the orchestrator
4
- // can pick a backend by provider name and degrade gracefully on failure.
5
- // Methods throw on error — the caller decides the fallback chain.
6
- import os from "node:os";
7
- import path from "node:path";
8
-
9
- const DEFAULT_TIMEOUT_MS = 15000;
10
-
11
- /** djb2 — stable, fast fingerprint for a provider/model string. */
12
- function hashString(s) {
13
- let h = 5381;
14
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
15
- return h.toString(16);
16
- }
17
-
18
- /** Full provider+model fingerprint used for index-consistency checks. */
19
- function modelHash(model) {
20
- return `${model}#${hashString(model)}`;
21
- }
22
-
23
- /** Lazy default loader: dynamic import keeps module load cheap. */
24
- async function defaultPipelineLoader(task, model, options) {
25
- const { env, pipeline } = await import("@huggingface/transformers");
26
- // issue #13: transformers.js's get_tokenizer_files() drops the caller's
27
- // cache_dir when it pre-checks tokenizer_config.json metadata, so the HEAD
28
- // request falls back to env.cacheDir and hits the network even when the
29
- // model is fully cached locally. Mirroring the cache_dir onto env.cacheDir
30
- // makes that pre-check resolve locally too — fully offline loading.
31
- if (options?.cache_dir) env.cacheDir = options.cache_dir;
32
- return pipeline(task, model, options);
33
- }
34
-
35
- /** Flatten a transformers.js Tensor [batch, dim] into number[][]. */
36
- function tensorToRows(tensor) {
37
- const { data, dims } = tensor;
38
- const rowLen = dims[dims.length - 1] || 0;
39
- const rows = [];
40
- for (let i = 0; i < data.length; i += rowLen) {
41
- rows.push(Array.from(data.subarray(i, i + rowLen)));
42
- }
43
- // Single-text input may come back without the batch axis.
44
- if (rows.length === 0 && rowLen > 0) rows.push(Array.from(data));
45
- return rows;
46
- }
47
-
48
- /**
49
- * ONNX text embedder backed by transformers.js (onnxruntime-node underneath).
50
- * Runs fully offline with mean pooling + L2 normalization for BERT-style
51
- * models like bge-small-zh. `engineFactory` is injectable for tests.
52
- */
53
- export class LocalEmbedder {
54
- constructor(opts = {}) {
55
- this.model = opts.model || "Xenova/bge-small-zh-v1.5";
56
- this._dimension = opts.dimension || 512;
57
- this.device = opts.device || "cpu";
58
- this.batchSize = opts.batchSize || 8;
59
- this.cacheDir =
60
- String(opts.cacheDir ?? "").trim() ||
61
- path.join(os.homedir(), ".dsh", "mneme", "models");
62
- this.useDtype = opts.useDtype || "q8";
63
- this.logger = opts.logger ?? null;
64
- // Test hook: replace the pipeline factory without touching modules.
65
- this.engineFactory = opts.engineFactory || defaultPipelineLoader;
66
- this.extractor = null;
67
- // issue #6: readiness flag for the service's scheduleEmbed gate. False until
68
- // init() succeeds, so "ready" in embedder is observable even pre-init.
69
- this.ready = false;
70
- }
71
-
72
- /** Load the model; throws when it cannot be loaded. Idempotent. */
73
- async init() {
74
- if (this.extractor) return this; // already initialized: no-op
75
- const options = {
76
- dtype: this.useDtype,
77
- device: this.device
78
- };
79
- if (this.cacheDir) options.cache_dir = this.cacheDir;
80
- this.extractor = await this.engineFactory("feature-extraction", this.model, options);
81
- this.ready = true; // service reads this to flush queued re-embeds
82
- this.logger?.info?.(
83
- `[dsh-mneme] local embedder ready: ${this.model} (dim=${this._dimension}, device=${this.device})`
84
- );
85
- return this;
86
- }
87
-
88
- /** Embed many texts with mean pooling; chunks at batchSize. */
89
- async embed(texts) {
90
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
91
- if (!this.extractor) throw new Error("LocalEmbedder not initialized");
92
- const out = [];
93
- for (let i = 0; i < texts.length; i += this.batchSize) {
94
- const chunk = texts.slice(i, i + this.batchSize);
95
- const tensor = await this.extractor(chunk, { pooling: "mean", normalize: true });
96
- out.push(...tensorToRows(tensor));
97
- }
98
- return out;
99
- }
100
-
101
- async embedSingle(text) {
102
- const rows = await this.embed([String(text)]);
103
- return rows[0];
104
- }
105
-
106
- get dimension() {
107
- return this._dimension;
108
- }
109
-
110
- get modelHash() {
111
- return modelHash(this.model);
112
- }
113
-
114
- dispose() {
115
- try {
116
- this.extractor?.dispose?.();
117
- } catch {
118
- // best-effort: some engines free resources on GC
119
- }
120
- this.extractor = null;
121
- this.ready = false;
122
- }
123
- }
124
-
125
- /** Chunk texts into batches of at most `size`. */
126
- function chunk(texts, size) {
127
- const out = [];
128
- for (let i = 0; i < texts.length; i += size) out.push(texts.slice(i, i + size));
129
- return out;
130
- }
131
-
132
- /**
133
- * Ollama embedder over its native HTTP API. `dimension` is inferred from the
134
- * first response. init() verifies reachability and that the model exists.
135
- */
136
- export class OllamaEmbedder {
137
- constructor(opts = {}) {
138
- this.baseUrl = String(opts.baseUrl ?? "http://localhost:11434").trim().replace(/\/+$/, "");
139
- this.model = String(opts.model ?? "nomic-embed-text").trim();
140
- this.logger = opts.logger ?? null;
141
- this._dimension = null;
142
- }
143
-
144
- async _post(body) {
145
- return fetch(`${this.baseUrl}/api/embeddings`, {
146
- method: "POST",
147
- headers: { "Content-Type": "application/json" },
148
- body: JSON.stringify(body),
149
- signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
150
- });
151
- }
152
-
153
- /** Probe the server with a tiny prompt; throws when unreachable/missing. */
154
- async init() {
155
- const res = await this._post({ model: this.model, prompt: "ping" });
156
- if (!res.ok) throw new Error(`Ollama ${this.model} unavailable: HTTP ${res.status}`);
157
- const body = await res.json();
158
- if (!Array.isArray(body?.embedding)) throw new Error(`Ollama ${this.model} returned no embedding`);
159
- this._dimension = body.embedding.length;
160
- this.logger?.info?.(
161
- `[dsh-mneme] ollama embedder ready: ${this.model} (dim=${this._dimension})`
162
- );
163
- return this;
164
- }
165
-
166
- async embed(texts) {
167
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
168
- const out = [];
169
- for (const text of texts) out.push(await this.embedSingle(text));
170
- return out;
171
- }
172
-
173
- async embedSingle(text) {
174
- const res = await this._post({ model: this.model, prompt: String(text).slice(0, 8000) });
175
- if (!res.ok) throw new Error(`Ollama embed failed: HTTP ${res.status}`);
176
- const body = await res.json();
177
- const vec = body?.embedding;
178
- if (!Array.isArray(vec) || !vec.length) throw new Error("Ollama returned no embedding");
179
- if (this._dimension == null) this._dimension = vec.length;
180
- return Array.from(vec);
181
- }
182
-
183
- get dimension() {
184
- return this._dimension ?? 0;
185
- }
186
-
187
- get modelHash() {
188
- return modelHash(this.model);
189
- }
190
-
191
- dispose() {
192
- this._dimension = null;
193
- }
194
- }
195
-
196
- /**
197
- * OpenAI-compatible embedder (OpenAI, SiliconFlow, Zhipu, local proxies).
198
- * Backward-compatible behavior lifted from embedding.js, but batchable and
199
- * throwing on failure instead of returning null.
200
- */
201
- export class OpenAIEmbedder {
202
- constructor(opts = {}) {
203
- this.baseUrl = String(opts.baseUrl ?? "").trim().replace(/\/+$/, "");
204
- this.apiKey = String(opts.apiKey ?? "").trim();
205
- this.model = String(opts.model ?? "").trim();
206
- this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
207
- this.logger = opts.logger ?? null;
208
- this._dimension = null;
209
- // Accept both "https://host/v1" and a full path ending in /embeddings.
210
- this._url = /\/embeddings$/i.test(this.baseUrl)
211
- ? this.baseUrl
212
- : this.baseUrl ? `${this.baseUrl}/embeddings` : "";
213
- }
214
-
215
- async init() {
216
- if (!this._url || !this.apiKey || !this.model) {
217
- throw new Error("OpenAI embedder requires baseUrl, apiKey and model");
218
- }
219
- this.logger?.info?.(`[dsh-mneme] openai embedder ready: ${this.model}`);
220
- return this;
221
- }
222
-
223
- async embed(texts) {
224
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
225
- const out = [];
226
- for (const batch of chunk(texts, 32)) {
227
- const res = await fetch(this._url, {
228
- method: "POST",
229
- headers: {
230
- "Content-Type": "application/json",
231
- "Authorization": `Bearer ${this.apiKey}`
232
- },
233
- body: JSON.stringify({ model: this.model, input: batch.map((t) => String(t).slice(0, 8000)) }),
234
- signal: AbortSignal.timeout(this.timeoutMs)
235
- });
236
- if (!res.ok) throw new Error(`Embedding API failed: HTTP ${res.status}`);
237
- const body = await res.json();
238
- const list = body?.data;
239
- if (!Array.isArray(list) || list.length !== batch.length) {
240
- throw new Error("Embedding API returned unexpected payload");
241
- }
242
- for (const item of list) {
243
- const vec = item?.embedding;
244
- if (!Array.isArray(vec) || !vec.length) throw new Error("Embedding API returned empty vector");
245
- if (this._dimension == null) this._dimension = vec.length;
246
- out.push(Array.from(vec));
247
- }
248
- }
249
- return out;
250
- }
251
-
252
- async embedSingle(text) {
253
- const rows = await this.embed([String(text)]);
254
- return rows[0];
255
- }
256
-
257
- get dimension() {
258
- return this._dimension ?? 0;
259
- }
260
-
261
- get modelHash() {
262
- return modelHash(this.model);
263
- }
264
-
265
- dispose() {
266
- this._dimension = null;
267
- }
268
- }
269
-
270
- /** Pick a backend instance by provider name. Throws on unknown providers. */
271
- export function createEmbedderByProvider(provider, opts) {
272
- switch (String(provider ?? "").toLowerCase()) {
273
- case "local":
274
- return new LocalEmbedder(opts);
275
- case "ollama":
276
- return new OllamaEmbedder(opts);
277
- case "openai":
278
- return new OpenAIEmbedder(opts);
279
- default:
280
- throw new Error(`Unknown embedding provider: ${provider}`);
281
- }
282
- }
1
+ // Fully-local embedding backends for dsh-mneme: ONNX via transformers.js,
2
+ // Ollama's HTTP API, and the OpenAI-compatible HTTP API (extracted from the
3
+ // old embedding.js logic). All classes share one interface so the orchestrator
4
+ // can pick a backend by provider name and degrade gracefully on failure.
5
+ // Methods throw on error — the caller decides the fallback chain.
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ const DEFAULT_TIMEOUT_MS = 15000;
10
+
11
+ /** djb2 — stable, fast fingerprint for a provider/model string. */
12
+ function hashString(s) {
13
+ let h = 5381;
14
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
15
+ return h.toString(16);
16
+ }
17
+
18
+ /** Full provider+model fingerprint used for index-consistency checks. */
19
+ function modelHash(model) {
20
+ return `${model}#${hashString(model)}`;
21
+ }
22
+
23
+ /** Lazy default loader: dynamic import keeps module load cheap. */
24
+ async function defaultPipelineLoader(task, model, options) {
25
+ const { env, pipeline } = await import("@huggingface/transformers");
26
+ // issue #13: transformers.js's get_tokenizer_files() drops the caller's
27
+ // cache_dir when it pre-checks tokenizer_config.json metadata, so the HEAD
28
+ // request falls back to env.cacheDir and hits the network even when the
29
+ // model is fully cached locally. Mirroring the cache_dir onto env.cacheDir
30
+ // makes that pre-check resolve locally too — fully offline loading.
31
+ if (options?.cache_dir) env.cacheDir = options.cache_dir;
32
+ return pipeline(task, model, options);
33
+ }
34
+
35
+ /** Flatten a transformers.js Tensor [batch, dim] into number[][]. */
36
+ function tensorToRows(tensor) {
37
+ const { data, dims } = tensor;
38
+ const rowLen = dims[dims.length - 1] || 0;
39
+ const rows = [];
40
+ for (let i = 0; i < data.length; i += rowLen) {
41
+ rows.push(Array.from(data.subarray(i, i + rowLen)));
42
+ }
43
+ // Single-text input may come back without the batch axis.
44
+ if (rows.length === 0 && rowLen > 0) rows.push(Array.from(data));
45
+ return rows;
46
+ }
47
+
48
+ /**
49
+ * ONNX text embedder backed by transformers.js (onnxruntime-node underneath).
50
+ * Runs fully offline with mean pooling + L2 normalization for BERT-style
51
+ * models like bge-small-zh. `engineFactory` is injectable for tests.
52
+ */
53
+ export class LocalEmbedder {
54
+ constructor(opts = {}) {
55
+ this.model = opts.model || "Xenova/bge-small-zh-v1.5";
56
+ this._dimension = opts.dimension || 512;
57
+ this.device = opts.device || "cpu";
58
+ this.batchSize = opts.batchSize || 8;
59
+ this.cacheDir =
60
+ String(opts.cacheDir ?? "").trim() ||
61
+ path.join(os.homedir(), ".dsh", "mneme", "models");
62
+ this.useDtype = opts.useDtype || "q8";
63
+ this.logger = opts.logger ?? null;
64
+ // Test hook: replace the pipeline factory without touching modules.
65
+ this.engineFactory = opts.engineFactory || defaultPipelineLoader;
66
+ this.extractor = null;
67
+ // issue #6: readiness flag for the service's scheduleEmbed gate. False until
68
+ // init() succeeds, so "ready" in embedder is observable even pre-init.
69
+ this.ready = false;
70
+ }
71
+
72
+ /** Load the model; throws when it cannot be loaded. Idempotent. */
73
+ async init() {
74
+ if (this.extractor) return this; // already initialized: no-op
75
+ const options = {
76
+ dtype: this.useDtype,
77
+ device: this.device
78
+ };
79
+ if (this.cacheDir) options.cache_dir = this.cacheDir;
80
+ this.extractor = await this.engineFactory("feature-extraction", this.model, options);
81
+ this.ready = true; // service reads this to flush queued re-embeds
82
+ this.logger?.info?.(
83
+ `[dsh-mneme] local embedder ready: ${this.model} (dim=${this._dimension}, device=${this.device})`
84
+ );
85
+ return this;
86
+ }
87
+
88
+ /** Embed many texts with mean pooling; chunks at batchSize. */
89
+ async embed(texts) {
90
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
91
+ if (!this.extractor) throw new Error("LocalEmbedder not initialized");
92
+ const out = [];
93
+ for (let i = 0; i < texts.length; i += this.batchSize) {
94
+ const chunk = texts.slice(i, i + this.batchSize);
95
+ const tensor = await this.extractor(chunk, { pooling: "mean", normalize: true });
96
+ out.push(...tensorToRows(tensor));
97
+ }
98
+ return out;
99
+ }
100
+
101
+ async embedSingle(text) {
102
+ const rows = await this.embed([String(text)]);
103
+ return rows[0];
104
+ }
105
+
106
+ get dimension() {
107
+ return this._dimension;
108
+ }
109
+
110
+ get modelHash() {
111
+ return modelHash(this.model);
112
+ }
113
+
114
+ dispose() {
115
+ try {
116
+ this.extractor?.dispose?.();
117
+ } catch {
118
+ // best-effort: some engines free resources on GC
119
+ }
120
+ this.extractor = null;
121
+ this.ready = false;
122
+ }
123
+ }
124
+
125
+ /** Chunk texts into batches of at most `size`. */
126
+ function chunk(texts, size) {
127
+ const out = [];
128
+ for (let i = 0; i < texts.length; i += size) out.push(texts.slice(i, i + size));
129
+ return out;
130
+ }
131
+
132
+ /**
133
+ * Ollama embedder over its native HTTP API. `dimension` is inferred from the
134
+ * first response. init() verifies reachability and that the model exists.
135
+ */
136
+ export class OllamaEmbedder {
137
+ constructor(opts = {}) {
138
+ this.baseUrl = String(opts.baseUrl ?? "http://localhost:11434").trim().replace(/\/+$/, "");
139
+ this.model = String(opts.model ?? "nomic-embed-text").trim();
140
+ this.logger = opts.logger ?? null;
141
+ this._dimension = null;
142
+ }
143
+
144
+ async _post(body) {
145
+ return fetch(`${this.baseUrl}/api/embeddings`, {
146
+ method: "POST",
147
+ headers: { "Content-Type": "application/json" },
148
+ body: JSON.stringify(body),
149
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
150
+ });
151
+ }
152
+
153
+ /** Probe the server with a tiny prompt; throws when unreachable/missing. */
154
+ async init() {
155
+ const res = await this._post({ model: this.model, prompt: "ping" });
156
+ if (!res.ok) throw new Error(`Ollama ${this.model} unavailable: HTTP ${res.status}`);
157
+ const body = await res.json();
158
+ if (!Array.isArray(body?.embedding)) throw new Error(`Ollama ${this.model} returned no embedding`);
159
+ this._dimension = body.embedding.length;
160
+ this.logger?.info?.(
161
+ `[dsh-mneme] ollama embedder ready: ${this.model} (dim=${this._dimension})`
162
+ );
163
+ return this;
164
+ }
165
+
166
+ async embed(texts) {
167
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
168
+ const out = [];
169
+ for (const text of texts) out.push(await this.embedSingle(text));
170
+ return out;
171
+ }
172
+
173
+ async embedSingle(text) {
174
+ const res = await this._post({ model: this.model, prompt: String(text).slice(0, 8000) });
175
+ if (!res.ok) throw new Error(`Ollama embed failed: HTTP ${res.status}`);
176
+ const body = await res.json();
177
+ const vec = body?.embedding;
178
+ if (!Array.isArray(vec) || !vec.length) throw new Error("Ollama returned no embedding");
179
+ if (this._dimension == null) this._dimension = vec.length;
180
+ return Array.from(vec);
181
+ }
182
+
183
+ get dimension() {
184
+ return this._dimension ?? 0;
185
+ }
186
+
187
+ get modelHash() {
188
+ return modelHash(this.model);
189
+ }
190
+
191
+ dispose() {
192
+ this._dimension = null;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * OpenAI-compatible embedder (OpenAI, SiliconFlow, Zhipu, local proxies).
198
+ * Backward-compatible behavior lifted from embedding.js, but batchable and
199
+ * throwing on failure instead of returning null.
200
+ */
201
+ export class OpenAIEmbedder {
202
+ constructor(opts = {}) {
203
+ this.baseUrl = String(opts.baseUrl ?? "").trim().replace(/\/+$/, "");
204
+ this.apiKey = String(opts.apiKey ?? "").trim();
205
+ this.model = String(opts.model ?? "").trim();
206
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
207
+ this.logger = opts.logger ?? null;
208
+ this._dimension = null;
209
+ // Accept both "https://host/v1" and a full path ending in /embeddings.
210
+ this._url = /\/embeddings$/i.test(this.baseUrl)
211
+ ? this.baseUrl
212
+ : this.baseUrl ? `${this.baseUrl}/embeddings` : "";
213
+ }
214
+
215
+ async init() {
216
+ if (!this._url || !this.apiKey || !this.model) {
217
+ throw new Error("OpenAI embedder requires baseUrl, apiKey and model");
218
+ }
219
+ this.logger?.info?.(`[dsh-mneme] openai embedder ready: ${this.model}`);
220
+ return this;
221
+ }
222
+
223
+ async embed(texts) {
224
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
225
+ const out = [];
226
+ for (const batch of chunk(texts, 32)) {
227
+ const res = await fetch(this._url, {
228
+ method: "POST",
229
+ headers: {
230
+ "Content-Type": "application/json",
231
+ "Authorization": `Bearer ${this.apiKey}`
232
+ },
233
+ body: JSON.stringify({ model: this.model, input: batch.map((t) => String(t).slice(0, 8000)) }),
234
+ signal: AbortSignal.timeout(this.timeoutMs)
235
+ });
236
+ if (!res.ok) throw new Error(`Embedding API failed: HTTP ${res.status}`);
237
+ const body = await res.json();
238
+ const list = body?.data;
239
+ if (!Array.isArray(list) || list.length !== batch.length) {
240
+ throw new Error("Embedding API returned unexpected payload");
241
+ }
242
+ for (const item of list) {
243
+ const vec = item?.embedding;
244
+ if (!Array.isArray(vec) || !vec.length) throw new Error("Embedding API returned empty vector");
245
+ if (this._dimension == null) this._dimension = vec.length;
246
+ out.push(Array.from(vec));
247
+ }
248
+ }
249
+ return out;
250
+ }
251
+
252
+ async embedSingle(text) {
253
+ const rows = await this.embed([String(text)]);
254
+ return rows[0];
255
+ }
256
+
257
+ get dimension() {
258
+ return this._dimension ?? 0;
259
+ }
260
+
261
+ get modelHash() {
262
+ return modelHash(this.model);
263
+ }
264
+
265
+ dispose() {
266
+ this._dimension = null;
267
+ }
268
+ }
269
+
270
+ /** Pick a backend instance by provider name. Throws on unknown providers. */
271
+ export function createEmbedderByProvider(provider, opts) {
272
+ switch (String(provider ?? "").toLowerCase()) {
273
+ case "local":
274
+ return new LocalEmbedder(opts);
275
+ case "ollama":
276
+ return new OllamaEmbedder(opts);
277
+ case "openai":
278
+ return new OpenAIEmbedder(opts);
279
+ default:
280
+ throw new Error(`Unknown embedding provider: ${provider}`);
281
+ }
282
+ }
package/lib/reranker.js CHANGED
@@ -21,7 +21,10 @@ function modelHash(model) {
21
21
 
22
22
  /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
23
  async function defaultPipelineLoader(task, model, options) {
24
- const { pipeline } = await import("@huggingface/transformers");
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;
25
28
  return pipeline(task, model, options);
26
29
  }
27
30
 
package/lib/service.js CHANGED
@@ -505,7 +505,9 @@ export function createService({ store, mirror, config, onWrite, logger }) {
505
505
  byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
506
506
  }
507
507
  }
508
- const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
508
+ const ranked = [...byId.values()]
509
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
510
+ .map((r) => ({ ...r, score: Math.max(0, Math.min(1, r.score ?? 0)) }));
509
511
  merged = ranked.slice(0, lim);
510
512
  if (merged.length < lim && !merged.length) {
511
513
  // Vector unavailable entirely: fall back to plain keyword.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 7 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.5.0",
4
+ "version": "0.5.1",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -5,7 +5,12 @@
5
5
  //
6
6
  // Usage: npm run sync (also run automatically by `npm pack`/`npm publish`
7
7
  // via the prepack hook, so a published tarball always ships a fresh lib/).
8
- import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
8
+ //
9
+ // Note: copyFileSync (not cpSync) is used on purpose — cpSync removes the
10
+ // destination first, which fails with EPERM/unlink on Windows when the path
11
+ // is long enough to trigger the \\?\ extended-prefix (observed on publish).
12
+ // copyFileSync truncates and rewrites in place, so it survives long paths.
13
+ import { copyFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
9
14
  import { join, relative } from "node:path";
10
15
  import { fileURLToPath } from "node:url";
11
16
 
@@ -31,7 +36,7 @@ for (const file of walk(srcDir)) {
31
36
  const rel = relative(srcDir, file);
32
37
  const dest = join(libDir, rel);
33
38
  mkdirSync(join(dest, ".."), { recursive: true });
34
- cpSync(file, dest);
39
+ copyFileSync(file, dest);
35
40
  copied++;
36
41
  console.log(`synced ${rel}`);
37
42
  }
package/src/hot-memory.js CHANGED
@@ -21,6 +21,13 @@ export function estimateTokens(text) {
21
21
  * rounds(): Array, clear(): void}}
22
22
  */
23
23
  export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
24
+ // Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
25
+ // null, "2") would make the eviction while-loop unbounded — the buffer can
26
+ // never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
27
+ // Fall back to the defaults so a hostile/buggy caller can never wedge the
28
+ // hot-memory buffer in an infinite loop.
29
+ maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
30
+ maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
24
31
  const buffer = [];
25
32
 
26
33
  function totalTokens() {
package/src/reranker.js CHANGED
@@ -21,7 +21,10 @@ function modelHash(model) {
21
21
 
22
22
  /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
23
  async function defaultPipelineLoader(task, model, options) {
24
- const { pipeline } = await import("@huggingface/transformers");
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;
25
28
  return pipeline(task, model, options);
26
29
  }
27
30
 
package/src/service.js CHANGED
@@ -505,7 +505,9 @@ export function createService({ store, mirror, config, onWrite, logger }) {
505
505
  byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
506
506
  }
507
507
  }
508
- const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
508
+ const ranked = [...byId.values()]
509
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
510
+ .map((r) => ({ ...r, score: Math.max(0, Math.min(1, r.score ?? 0)) }));
509
511
  merged = ranked.slice(0, lim);
510
512
  if (merged.length < lim && !merged.length) {
511
513
  // Vector unavailable entirely: fall back to plain keyword.