@modusensus/dsh-mneme 0.8.1 → 0.8.3

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 (58) hide show
  1. package/README.md +14 -3
  2. package/lib/api-standalone.js +12 -0
  3. package/lib/api.js +12 -2
  4. package/lib/client.js +5 -1
  5. package/lib/config.js +18 -0
  6. package/lib/dream/decisions.js +55 -8
  7. package/lib/dream/sleep.js +36 -5
  8. package/lib/dream.js +18 -7
  9. package/lib/entities/extractor.js +2 -2
  10. package/lib/index.js +8 -0
  11. package/lib/inject.js +43 -1
  12. package/lib/lang.js +2 -2
  13. package/lib/local-embedder.js +21 -1
  14. package/lib/reranker.js +47 -8
  15. package/lib/runtime/model-fetch.js +361 -0
  16. package/lib/service.js +37 -5
  17. package/lib/settings.js +1 -0
  18. package/lib/store.js +85 -25
  19. package/lib/summarize.js +2 -2
  20. package/lib/tools.js +6 -19
  21. package/lib/vector-index.js +2 -8
  22. package/package.json +2 -1
  23. package/scripts/sync-test-badge.mjs +61 -0
  24. package/src/api-standalone.js +12 -0
  25. package/src/api.js +12 -2
  26. package/src/config.js +18 -0
  27. package/src/dream/decisions.js +55 -8
  28. package/src/dream/sleep.js +36 -5
  29. package/src/dream.js +18 -7
  30. package/src/entities/extractor.js +2 -2
  31. package/src/index.js +8 -0
  32. package/src/inject.js +43 -1
  33. package/src/lang.js +2 -2
  34. package/src/local-embedder.js +21 -1
  35. package/src/reranker.js +47 -8
  36. package/src/runtime/model-fetch.js +361 -0
  37. package/src/service.js +37 -5
  38. package/src/settings.js +1 -0
  39. package/src/store.js +85 -25
  40. package/src/summarize.js +2 -2
  41. package/src/tools.js +6 -19
  42. package/src/vector-index.js +2 -8
  43. package/test/api.test.js +10 -4
  44. package/test/dream-archive-guardrail.test.js +116 -0
  45. package/test/dream-coverage-degrade.test.js +86 -0
  46. package/test/dream.test.js +15 -11
  47. package/test/inject-first-round-bm25.test.js +89 -0
  48. package/test/inject-rotation.test.js +161 -0
  49. package/test/llm-message-source.test.js +177 -0
  50. package/test/local-embedder.test.js +20 -0
  51. package/test/reranker-single-logit.test.js +73 -0
  52. package/test/runtime-model-fetch.test.js +348 -0
  53. package/test/skip-invalid-restore.test.js +7 -5
  54. package/test/sleep-scheduler-rearm.test.js +89 -0
  55. package/test/sleep.test.js +2 -2
  56. package/test/standalone-api.test.js +34 -1
  57. package/test/store-vector-cache.test.js +98 -0
  58. package/test/tools-memory-get-schema.test.js +65 -0
@@ -0,0 +1,361 @@
1
+ // 模型文件取件(issue #194)
2
+ //
3
+ // transformers.js 下载模型文件(如 model.onnx,约 1GB)走它自己的 env.fetch;undici
4
+ // socket 中途被重置(TypeError: terminated)时整份下载作废重来。4.2.0 的 env.fetch 是
5
+ // 官方文档化的可替换面(env.js: `fetch: DEFAULT_FETCH`),所以韧性做在这一层:对
6
+ // transformers.js 而言这仍然是一个普通的 fetch,成功路径的语义一点没变;变化只发生在
7
+ // 失败路径 —— 已收的字节落在磁盘 .part 里,重试(包括换一次进程)从断点继续。
8
+ //
9
+ // 硬规矩(与 runtime/download.js 的取件层同一套直觉):
10
+ // 1. 交给下游的响应永远是规范的 200 + 完整 content-length。hub.js 把非 200 一律当
11
+ // 失败处理,206 直接透传反而会破坏下游;断点拼接是我们内部的事,不能漏出去。
12
+ // 2. 续传前带 If-Range:断点对应的内容若在服务端被换过,服务器会回 200(全量)。
13
+ // 旧断点拼新内容是一份静默损坏的模型 —— 宁可整份重来,不可拼错。
14
+ // 3. 同一 URL 的 .part 同一时刻只允许一个写者。两个进程并发追加同一份字节是写损坏;
15
+ // 抢不到锁就按现状直接转发(裸 fetch),让持锁的那份去落盘。
16
+ //
17
+ // @module dsh-mneme/runtime/model-fetch
18
+ import { createHash } from "node:crypto";
19
+ import { closeSync, createReadStream, existsSync, futimesSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
20
+ import { Readable } from "node:stream";
21
+ import { join } from "node:path";
22
+ import { defaultModelCacheDir } from "./layout.js";
23
+
24
+ const DEFAULT_ATTEMPTS = 3;
25
+ const DEFAULT_RETRY_DELAY_MS = 1000;
26
+ const DEFAULT_MAX_RETRY_DELAY_MS = 15000;
27
+ // 看门狗是「连续无字节」上限而不是总时长上限:几百 MB~1GB 的文件在慢网下合法地要下
28
+ // 几十分钟,总时长上限会掐死健康但慢的下载;连续这么久一个字节都没有才是 socket 僵死。
29
+ const DEFAULT_IDLE_TIMEOUT_MS = 120000;
30
+ // 锁的 mtime 超过这么久没刷新 = 持锁方已死(活着的话每个进度节拍都会刷新),可以抢。
31
+ const STALE_LOCK_MS = 30 * 60 * 1000;
32
+ // 进度事件节流:1GB 按 64KB 一块是一万多个事件,逐个发出去日志没法看。
33
+ const PROGRESS_EMIT_INTERVAL_MS = 500;
34
+
35
+ /** URL → 稳定文件名。断点文件要跨进程、跨重启可复用,所以用内容寻址而不是 pid。 */
36
+ function partName(url) {
37
+ return createHash("sha256").update(url).digest("hex");
38
+ }
39
+
40
+ function readMeta(metaPath) {
41
+ try {
42
+ return readFileSync(metaPath, "utf8").trim();
43
+ } catch {
44
+ return "";
45
+ }
46
+ }
47
+
48
+ function writeMeta(metaPath, etag) {
49
+ writeFileSync(metaPath, `${etag}\n`, "utf8");
50
+ }
51
+
52
+ /** 断点不可信(比源文件还大 / 内容对不上)时整体作废,而不是试着修剪。 */
53
+ function resetPart(partPath, metaPath) {
54
+ rmSync(partPath, { force: true });
55
+ rmSync(metaPath, { force: true });
56
+ }
57
+
58
+ /**
59
+ * 拿 .part 的写锁。返回 fd(持有着,供流式期间刷新 mtime)或 null(别人在写)。
60
+ * 只尝试偷一次过期锁:再抢不到就放弃,调用方按现状裸转发。
61
+ */
62
+ function acquireLock(lockPath, staleLockMs) {
63
+ for (let i = 0; i < 2; i++) {
64
+ try {
65
+ const fd = openSync(lockPath, "wx");
66
+ writeSync(fd, String(process.pid));
67
+ return fd;
68
+ } catch {
69
+ let age = Infinity;
70
+ try {
71
+ age = Date.now() - statSync(lockPath).mtimeMs;
72
+ } catch {}
73
+ if (age > staleLockMs) {
74
+ rmSync(lockPath, { force: true });
75
+ continue;
76
+ }
77
+ return null;
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+
83
+ function releaseLock(lockPath, lockFd) {
84
+ if (lockFd === null) return;
85
+ try {
86
+ closeSync(lockFd);
87
+ } catch {}
88
+ rmSync(lockPath, { force: true });
89
+ }
90
+
91
+ /** 进度事件的百分数。total 未知时给 null,让日志退化为「已收字节数」。 */
92
+ function percentOf(received, total) {
93
+ return Number.isFinite(total) && total > 0 ? Math.floor((received / total) * 100) : null;
94
+ }
95
+
96
+ /**
97
+ * 造一个「带断点续传的 fetch」。
98
+ * @param {object} opts - 选项。
99
+ * @param {Function} [opts.fetchImpl] - 底层 fetch,测试注入。
100
+ * @param {string} opts.partDir - 断点文件目录(应与模型缓存同盘)。
101
+ * @param {number} [opts.attempts] - 含首次在内的总尝试次数。
102
+ * @param {number} [opts.retryDelayMs] - 退避基数:1s → 2s → 4s,封顶 maxRetryDelayMs。
103
+ * @param {number} [opts.idleTimeoutMs] - 连续无字节的看门狗上限。
104
+ * @param {Function} [opts.onEvent] - resume / progress / restart / fail 事件回调。
105
+ * @param {Function} [opts.hash] - URL → 断点文件名,测试注入。
106
+ * @returns {Function} 与全局 fetch 同签名的函数。
107
+ */
108
+ export function createResilientFetch({
109
+ fetchImpl = fetch,
110
+ partDir,
111
+ attempts = DEFAULT_ATTEMPTS,
112
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
113
+ maxRetryDelayMs = DEFAULT_MAX_RETRY_DELAY_MS,
114
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
115
+ onEvent = null,
116
+ hash = partName
117
+ } = {}) {
118
+ if (typeof partDir !== "string" || partDir === "") {
119
+ throw new TypeError("createResilientFetch:partDir 是必填的(.part 断点文件落在这里)");
120
+ }
121
+ mkdirSync(partDir, { recursive: true });
122
+ const emit = (event) => {
123
+ try {
124
+ onEvent?.(event);
125
+ } catch {
126
+ // 进度回调的异常不该打断下载本身。
127
+ }
128
+ };
129
+
130
+ return async function resilientFetch(input, init = undefined) {
131
+ const url = typeof input === "string" ? input : String(input?.url ?? input);
132
+ const method = String(init?.method ?? "GET").toUpperCase();
133
+ // 非 GET(HEAD 元数据预检等)与带 body 的请求不落盘:原样转发,语义与裸 fetch 一致。
134
+ if (method !== "GET" || init?.body != null) return fetchImpl(input, init);
135
+
136
+ const partPath = join(partDir, hash(url));
137
+ const metaPath = `${partPath}.meta`;
138
+ const lockPath = `${partPath}.lock`;
139
+ const lockFd = acquireLock(lockPath, STALE_LOCK_MS);
140
+ if (lockFd === null) {
141
+ // 另一个进程正在下同一个文件。并发追加同一份 .part 是写损坏,所以这边不参与落盘,
142
+ // 按改动前的行为裸转发一次 —— 持锁方会正常下完,之后的加载会命中缓存。
143
+ return fetchImpl(input, init);
144
+ }
145
+
146
+ try {
147
+ return await downloadWithResume(url, init, {
148
+ fetchImpl,
149
+ partPath,
150
+ metaPath,
151
+ lockPath,
152
+ lockFd,
153
+ attempts,
154
+ retryDelayMs,
155
+ maxRetryDelayMs,
156
+ idleTimeoutMs,
157
+ emit
158
+ });
159
+ } catch (error) {
160
+ // 失败路径锁在这里释放;成功路径的锁随断点文件一起在响应体流关闭后清理 ——
161
+ // 若在返回响应时就放锁,另一个进程会在「.part 仍被下游流读着」的窗口里动它。
162
+ releaseLock(lockPath, lockFd);
163
+ throw error;
164
+ }
165
+ };
166
+ }
167
+
168
+ async function downloadWithResume(url, init, ctx) {
169
+ const { fetchImpl, partPath, metaPath, lockPath, lockFd, attempts, retryDelayMs, maxRetryDelayMs, idleTimeoutMs, emit } = ctx;
170
+ let lastError = null;
171
+ let lastPercent = null;
172
+ let lastReceived = 0;
173
+
174
+ for (let attempt = 1; attempt <= attempts; attempt++) {
175
+ let offset = 0;
176
+ if (existsSync(partPath)) {
177
+ offset = statSync(partPath).size;
178
+ if (offset > 0) {
179
+ emit({ type: "resume", url, offset, attempt });
180
+ }
181
+ }
182
+
183
+ const headers = new Headers(init?.headers);
184
+ if (offset > 0) {
185
+ headers.set("Range", `bytes=${offset}-`);
186
+ // If-Range:断点对应的内容在服务端被换过时,服务器回 200(全量)而不是 206 ——
187
+ // 那就整份重来。没有它,旧断点 + 新内容会拼出一份静默损坏的模型。
188
+ const storedEtag = readMeta(metaPath);
189
+ if (storedEtag) headers.set("If-Range", storedEtag);
190
+ }
191
+
192
+ const controller = new AbortController();
193
+ const onCallerAbort = () => controller.abort(init?.signal?.reason);
194
+ init?.signal?.addEventListener("abort", onCallerAbort, { once: true });
195
+ let idleTimer = null;
196
+ const armIdle = () => {
197
+ if (!(idleTimeoutMs > 0)) return;
198
+ if (idleTimer !== null) clearTimeout(idleTimer);
199
+ idleTimer = setTimeout(
200
+ () => controller.abort(new Error(`连接空闲超过 ${Math.round(idleTimeoutMs / 1000)}s 无数据`)),
201
+ idleTimeoutMs
202
+ );
203
+ };
204
+ armIdle();
205
+
206
+ let fd = -1;
207
+ let received = 0;
208
+ let total = null;
209
+ let lastEmitAt = 0;
210
+ const reportProgress = (force = false) => {
211
+ const now = Date.now();
212
+ if (!force && now - lastEmitAt < PROGRESS_EMIT_INTERVAL_MS) return;
213
+ lastEmitAt = now;
214
+ lastReceived = offset + received;
215
+ lastPercent = percentOf(lastReceived, total);
216
+ futimesSync(lockFd, new Date(), new Date()); // 锁的活着证明与进度同节拍刷新。
217
+ emit({ type: "progress", url, received: lastReceived, total, percent: lastPercent, attempt });
218
+ };
219
+
220
+ try {
221
+ const res = await fetchImpl(url, { ...init, headers, signal: controller.signal });
222
+
223
+ // Range 起点越过源文件末尾(断点比源还大,通常断点来自被替换前的旧文件):
224
+ // 断点不可信 —— 清掉,这次尝试作废,下一次从 0 开始。不处理的话会在 416 上
225
+ // 把重试次数全部烧完,报一条用户看不懂的错。
226
+ if (res.status === 416) {
227
+ emit({ type: "restart", url, offset, attempt, reason: "range-not-satisfiable" });
228
+ resetPart(partPath, metaPath);
229
+ lastError = new Error("HTTP 416(断点已重置)");
230
+ continue;
231
+ }
232
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
233
+
234
+ if (offset > 0 && res.status === 200) {
235
+ // 服务器无视了 Range,或 If-Range 判定内容已变:整份重来。
236
+ emit({ type: "restart", url, offset, attempt, reason: "range-rejected" });
237
+ resetPart(partPath, metaPath);
238
+ offset = 0;
239
+ }
240
+ if (res.status === 206) {
241
+ const cr = /bytes (\d+)-(\d+)\/(\d+)/.exec(res.headers.get("content-range") ?? "");
242
+ if (cr === null) throw new Error("206 响应缺少 Content-Range");
243
+ total = Number(cr[3]);
244
+ if (Number(cr[1]) !== offset) {
245
+ // 服务器续的位置和断点对不上:不猜(拼错的字节比下载失败更糟),清掉重来。
246
+ emit({ type: "restart", url, offset, attempt, reason: "offset-mismatch" });
247
+ resetPart(partPath, metaPath);
248
+ throw new Error(`断点偏移不一致(本地 ${offset},服务器 ${cr[1]}),断点已重置`);
249
+ }
250
+ } else {
251
+ total = Number(res.headers.get("content-length")) || null;
252
+ }
253
+ const etag = res.headers.get("etag");
254
+ if (etag) writeMeta(metaPath, etag);
255
+
256
+ fd = openSync(partPath, "a");
257
+ if (res.body !== null) {
258
+ const reader = res.body.getReader();
259
+ for (;;) {
260
+ const { done, value } = await reader.read();
261
+ if (done) break;
262
+ writeSync(fd, value);
263
+ received += value.length;
264
+ armIdle();
265
+ reportProgress();
266
+ }
267
+ }
268
+ // 服务端"干净地"提前关流(不抛错、但字节没给够)也是断流的一种,必须查出来。
269
+ if (total !== null && offset + received !== total) {
270
+ throw new Error(`下载不完整:收到 ${offset + received}/${total} 字节`);
271
+ }
272
+ clearTimeout(idleTimer);
273
+ idleTimer = null;
274
+ reportProgress(true);
275
+ return partResponse(partPath, metaPath, lockPath, lockFd, offset + received, etag);
276
+ } catch (error) {
277
+ lastError = error;
278
+ lastReceived = offset + received;
279
+ lastPercent = percentOf(lastReceived, total);
280
+ emit({ type: "fail", url, received: lastReceived, total, percent: lastPercent, attempt, error: String(error?.message ?? error) });
281
+ } finally {
282
+ if (fd >= 0) closeSync(fd);
283
+ if (idleTimer !== null) clearTimeout(idleTimer);
284
+ init?.signal?.removeEventListener("abort", onCallerAbort);
285
+ }
286
+
287
+ if (attempt < attempts) {
288
+ // 退避:1s → 2s → 4s,封顶 maxRetryDelayMs。
289
+ await new Promise((resolve) => setTimeout(resolve, Math.min(retryDelayMs * 2 ** (attempt - 1), maxRetryDelayMs)));
290
+ }
291
+ }
292
+
293
+ // 最终失败的错误必须带中断位置(issue #194 的第 3 项):用户要能区分是网络断了
294
+ // 还是磁盘满了,而不是看到一句干巴巴的 TypeError: terminated。
295
+ const where = lastPercent !== null ? `中断于 ${lastPercent}%(${lastReceived} 字节)` : `已收 ${lastReceived} 字节`;
296
+ throw new Error(`模型文件下载失败(试了 ${attempts} 次,${where}):${lastError?.message ?? lastError}`);
297
+ }
298
+
299
+ /**
300
+ * 把完成的断点文件包装成给下游的响应:规范的 200 + 完整 content-length,body 从磁盘
301
+ * 流式读出(1GB 不进内存)。流关闭即清理断点文件 —— 它给下游(FileCache.put /
302
+ * arrayBuffer)供字节的使命结束了,不清的话一个 1GB 的副本会一直躺在缓存旁边。
303
+ */
304
+ function partResponse(partPath, metaPath, lockPath, lockFd, size, etag) {
305
+ const nodeStream = createReadStream(partPath);
306
+ const cleanup = () => {
307
+ try {
308
+ rmSync(partPath, { force: true });
309
+ rmSync(metaPath, { force: true });
310
+ releaseLock(lockPath, lockFd);
311
+ } catch {}
312
+ };
313
+ nodeStream.on("close", cleanup);
314
+ nodeStream.on("error", cleanup);
315
+ return new Response(Readable.toWeb(nodeStream), {
316
+ status: 200,
317
+ headers: {
318
+ "content-type": "application/octet-stream",
319
+ "content-length": String(size),
320
+ ...(etag ? { etag } : {})
321
+ }
322
+ });
323
+ }
324
+
325
+ /** 把事件映射成日志。只发人该看的行:续传、重来、每次失败的位置 —— 不刷进度条。 */
326
+ export function logModelFetchEvent(logger, event) {
327
+ const kb = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)}MB` : `${Math.round(n / 1024)}KB`);
328
+ const where = (e) => (e.percent !== null && e.percent !== undefined ? `${e.percent}%(${kb(e.received)}${e.total ? `/${kb(e.total)}` : ""})` : kb(e.received ?? 0));
329
+ switch (event.type) {
330
+ case "resume":
331
+ logger?.info?.(`[dsh-mneme] 模型下载带断点续传:已有 ${kb(event.offset)},第 ${event.attempt} 次尝试`);
332
+ break;
333
+ case "restart":
334
+ logger?.warn?.(`[dsh-mneme] 断点不可用(${event.reason}),模型下载从头再来`);
335
+ break;
336
+ case "fail":
337
+ logger?.warn?.(`[dsh-mneme] 模型下载中断于 ${where(event)},第 ${event.attempt} 次尝试失败:${event.error}`);
338
+ break;
339
+ default:
340
+ break;
341
+ }
342
+ }
343
+
344
+ /**
345
+ * 把弹性 fetch 装到 transformers.js 的 env 上(embedder / reranker 共用这一个入口)。
346
+ * @param {object} env - transformers.js 的 env(至少支持赋值 fetch)。
347
+ * @param {object} opts - 选项。
348
+ * @param {boolean} [opts.enabled] - 开关;关 = 完全不动 env(默认保持现状的出口)。
349
+ * @param {string} [opts.cacheDir] - 模型缓存目录,断点文件落在它的 .mneme-partial 下。
350
+ * @param {object} [opts.logger] - 接收下载进度日志的 logger。
351
+ * @param {object} [opts.rest] - 透传给 createResilientFetch 的其余选项(测试注入)。
352
+ * @returns {boolean} 是否实际安装。
353
+ */
354
+ export function installResilientFetch(env, { enabled = true, cacheDir = "", logger = null, ...rest } = {}) {
355
+ if (!enabled || !env) return false;
356
+ const root = String(cacheDir ?? "").trim() || defaultModelCacheDir();
357
+ const partDir = join(root, ".mneme-partial");
358
+ mkdirSync(partDir, { recursive: true });
359
+ env.fetch = createResilientFetch({ partDir, onEvent: (event) => logModelFetchEvent(logger, event), ...rest });
360
+ return true;
361
+ }
package/src/service.js CHANGED
@@ -1235,7 +1235,7 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1235
1235
  * fills + dedupes the remaining slots. Empty query / no cached recall /
1236
1236
  * hybridInject off → pure legacy rule-based selection.
1237
1237
  */
1238
- function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector, scope = null } = {}) {
1238
+ function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector, scope = null, rotate = null, rotateWindow = 0 } = {}) {
1239
1239
  const q = String(query ?? "").trim();
1240
1240
  // codingRetrospect 读取侧门控:编码记忆(rejected_solution / pitfall /
1241
1241
  // constraint)只在编码任务时注入,防噪声污染其他业务;编码任务时按
@@ -1246,7 +1246,15 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1246
1246
  // (quality_score null) count as 100 (weight 1), so legacy stores keep their
1247
1247
  // exact summary>preference>importance ordering.
1248
1248
  const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
1249
- const items = store.list({ limit: 200, includeForgotten: false })
1249
+ // Issue #205 补测:候选池必须比轮换窗口大——窗口 N 需要 maxItems×(N+1) 张
1250
+ // 不同的牌,池子只有 maxItems×2 时窗口一开就被吃光、只剩回填(重复率的
1251
+ // 结构性下限由池子大小决定)。无轮换时保持既有 maxItems×2 不变;规则路
1252
+ // 的 200 条上限同样给轮换让路(上限翻倍也只是多读一次 SQL LIMIT)。
1253
+ const rotateWindowN = Number.isInteger(rotateWindow) && rotateWindow > 0 ? rotateWindow : 0;
1254
+ const poolSize = rotateWindowN > 0
1255
+ ? Math.max(maxItems * 2, maxItems * (rotateWindowN + 1))
1256
+ : maxItems * 2;
1257
+ const items = store.list({ limit: Math.max(200, poolSize), includeForgotten: false })
1250
1258
  .filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1251
1259
  codingGate(m) &&
1252
1260
  (m.type === "summary" || m.type === "preference" || m.importance >= threshold))
@@ -1277,7 +1285,7 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1277
1285
  const semanticItems = [];
1278
1286
  if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
1279
1287
  try {
1280
- const hits = vectorIndex.search(queryVector, { limit: maxItems * 2, threshold: 0 });
1288
+ const hits = vectorIndex.search(queryVector, { limit: poolSize, threshold: 0 });
1281
1289
  for (const m of hits) {
1282
1290
  if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1283
1291
  codingGate(m) &&
@@ -1292,6 +1300,22 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1292
1300
  if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten && codingGate(m)) semanticItems.push(m);
1293
1301
  }
1294
1302
  }
1303
+ // Issue #198:首轮(无向量、无缓存召回)的同步兜底——BM25 词法召回领位。
1304
+ // 注入渲染是同步的(宿主 systemPrompt 的 contexts 不支持异步 text),
1305
+ // 查询向量只能异步 prefetch 给下一轮,首轮必 miss;此时纯静态排序会让
1306
+ // 老的高重要性 summary/preference 占满槽位,当前话题的 decision/project
1307
+ // 进不来。查询文本本身就在手上,BM25 是纯进程内同步计算,词法相关性
1308
+ // 足以把当前话题顶到前排;门控与向量路径一致(含 importance 阈值)。
1309
+ // 语义向量命中时本分支不参与,行为不变。
1310
+ if (!semanticItems.length) {
1311
+ for (const hit of bm25Recall(q, poolSize)) {
1312
+ if (hit && !hit.archived && INJECT_TYPES.has(hit.type) && !hit.forgotten &&
1313
+ codingGate(hit) &&
1314
+ (hit.type === "summary" || hit.type === "preference" || hit.importance >= threshold)) {
1315
+ semanticItems.push(hit);
1316
+ }
1317
+ }
1318
+ }
1295
1319
  if (semanticItems.length) {
1296
1320
  const seen = new Set();
1297
1321
  const merged = [];
@@ -1302,10 +1326,10 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1302
1326
  };
1303
1327
  for (const m of semanticItems) {
1304
1328
  push(m);
1305
- if (merged.length >= maxItems * 2) break;
1329
+ if (merged.length >= poolSize) break;
1306
1330
  }
1307
1331
  for (const m of items) {
1308
- if (merged.length >= maxItems * 2) break;
1332
+ if (merged.length >= poolSize) break;
1309
1333
  push(m);
1310
1334
  }
1311
1335
  candidates = merged;
@@ -1330,6 +1354,14 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1330
1354
  if (config?.strictScope === true && scope) {
1331
1355
  candidates = candidates.filter((m) => isVisibleInScope(m, scope));
1332
1356
  }
1357
+ // Issue #205:注入位跨轮轮换。rotate = 最近 N 轮注入过的 id 集合(由注入层
1358
+ // 按会话维护并传入):这些条目本轮不再优先——新鲜者前置(各自内部相对次序
1359
+ // 保持),不足时按原序回填,槽位数与 touchRecall 语义均不变。rotate 为空时
1360
+ // 行为与既有排序完全一致。
1361
+ if (rotate && rotate.size > 0 && candidates.length > 0) {
1362
+ const fresh = candidates.filter((m) => !rotate.has(m.id));
1363
+ if (fresh.length > 0) candidates = [...fresh, ...candidates.filter((m) => rotate.has(m.id))];
1364
+ }
1333
1365
  const selected = candidates.slice(0, maxItems);
1334
1366
  touchRecalled(selected);
1335
1367
  return selected;
package/src/settings.js CHANGED
@@ -52,6 +52,7 @@ const FEATURE_FLAG_BOOLEANS = [
52
52
  "selectiveInjectEnabled",
53
53
  "searchSemanticDedup",
54
54
  "rerankEnabled",
55
+ "resilientModelDownload",
55
56
  "adaptiveThresholdEnabled",
56
57
  "reflectionUpdateEnabled",
57
58
  "reflectionFailureTracking",
package/src/store.js CHANGED
@@ -22,6 +22,9 @@ CREATE TABLE IF NOT EXISTS memories (
22
22
  );
23
23
  CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(type);
24
24
  CREATE INDEX IF NOT EXISTS idx_memories_importance ON memories(importance);
25
+ -- Issue #202:all()/list() 按 updated_at 排序,无索引时走临时 B 树全表排序
26
+ -- (5k 行实测 all() 231ms → 135ms)。IF NOT EXISTS 幂等,存量库启动即建。
27
+ CREATE INDEX IF NOT EXISTS idx_memories_updated ON memories(updated_at);
25
28
 
26
29
  -- autoDream audit trail: one row per consolidation run, capturing the exact
27
30
  -- input snapshot digest + the LLM decision list + per-id outcome + a compact
@@ -717,11 +720,51 @@ export function createStore(path) {
717
720
  }
718
721
  }
719
722
 
723
+ // Issue #202:embedding 解析缓存。检索路径此前每次调用都对全部带向量行
724
+ // JSON.parse(993 × 512 维 ≈ 48 ms/次,且 SQL 拖着 10 MB 的 TEXT),余弦本身
725
+ // 只占 3%。向量只经 setEmbedding 写入(单一失效点),把解析结果按 id 缓存,
726
+ // 命中即零解析;上限 FIFO 驱逐防大库内存无界(4000 × 512 维 double ≈ 16 MB)。
727
+ const embeddingCache = new Map();
728
+ const EMBEDDING_CACHE_MAX = 4000;
729
+
730
+ function cacheEmbedding(id, vector) {
731
+ if (embeddingCache.size >= EMBEDDING_CACHE_MAX && !embeddingCache.has(id)) {
732
+ const oldest = embeddingCache.keys().next().value;
733
+ embeddingCache.delete(oldest);
734
+ }
735
+ embeddingCache.set(id, vector);
736
+ }
737
+
738
+ /** Parsed embedding for one id (cache-first); undefined when none/parse
739
+ * failure. Single read path shared by searchVector / getEmbedding(s). */
740
+ function getParsedEmbedding(id) {
741
+ const cached = embeddingCache.get(id);
742
+ if (cached) return cached;
743
+ const row = db.prepare("SELECT embedding FROM memories WHERE id = ?").get(id);
744
+ if (!row?.embedding) return undefined;
745
+ try {
746
+ const v = JSON.parse(row.embedding);
747
+ if (Array.isArray(v) && v.length) {
748
+ cacheEmbedding(id, v);
749
+ return v;
750
+ }
751
+ } catch { /* corrupt embedding text: treated as absent */ }
752
+ return undefined;
753
+ }
754
+
755
+ // all()/list() 的显式列清单:从实际 schema 派生(迁移后),只排除 embedding
756
+ // 列——consolidation/sleep/inject 的消费方都不读向量,而它是全表里最重的一列
757
+ // (5k 行库 ≈ 9.4 MB TEXT),每次全表调用都白搬。经 PRAGMA 派生而非硬编码,
758
+ // schema 演进时自动跟随。
759
+ const memoryColumns = db.prepare("PRAGMA table_info(memories)").all()
760
+ .map((c) => c.name)
761
+ .filter((n) => n !== "embedding");
762
+ const memoryColumnList = memoryColumns.join(", ");
763
+
720
764
  // Per-instance monotonic timestamp guard: consecutive writes within the same
721
765
  // millisecond must still produce strictly increasing timestamps (test asserts
722
766
  // updated_at != created_at). State lives in the store closure, not module scope.
723
- let lastTs = "";
724
- function nowIso() {
767
+ let lastTs = ""; function nowIso() {
725
768
  let ts = new Date().toISOString();
726
769
  if (lastTs && ts <= lastTs) {
727
770
  const d = new Date(lastTs);
@@ -925,6 +968,10 @@ export function createStore(path) {
925
968
  now,
926
969
  id
927
970
  );
971
+ // Issue #202:update 可直写 embedding(patch.embedding),缓存条目失效,
972
+ // 下次读取按库值重解析。宁滥勿缺——即便本 patch 未含 embedding,丢一条
973
+ // 缓存只多一次点查重解析。
974
+ embeddingCache.delete(id);
928
975
  // Desired generation bumped in the same transaction as the update (peer
929
976
  // blocker 1: crash between write and sync must still be recoverable).
930
977
  incrementGeneration();
@@ -995,6 +1042,8 @@ export function createStore(path) {
995
1042
  expectedUpdatedAt
996
1043
  );
997
1044
  if (result.changes === 0) return; // CAS miss: a concurrent write won
1045
+ // Issue #202:同 update——CAS 命中即可能改写 embedding,失效缓存条目。
1046
+ embeddingCache.delete(id);
998
1047
  // Only bump desired generation on a successful CAS — a miss writes nothing.
999
1048
  incrementGeneration();
1000
1049
  applied = true;
@@ -1177,7 +1226,9 @@ export function createStore(path) {
1177
1226
  }
1178
1227
 
1179
1228
  function all() {
1180
- const rows = db.prepare("SELECT * FROM memories ORDER BY updated_at DESC").all();
1229
+ // Issue #202:显式列清单排除 embedding——toRow 本就不输出向量,SELECT *
1230
+ // 纯属把全表最重的列(9.4 MB TEXT/5k 行)拖进内存再丢弃。
1231
+ const rows = db.prepare(`SELECT ${memoryColumnList} FROM memories ORDER BY updated_at DESC`).all();
1181
1232
  return rows.map(toRow);
1182
1233
  }
1183
1234
 
@@ -1185,6 +1236,17 @@ export function createStore(path) {
1185
1236
  function setEmbedding(id, vector) {
1186
1237
  const json = Array.isArray(vector) && vector.length ? JSON.stringify(vector) : null;
1187
1238
  db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run(json, id);
1239
+ // Issue #202:单一写入口即单一失效点——重写缓存条目(向量在手上不必重解析),
1240
+ // 清空则移除,删除过的 id 不会被下一次 searchVector 的 id 集合选中。
1241
+ if (json) {
1242
+ try {
1243
+ const parsed = JSON.parse(json);
1244
+ if (Array.isArray(parsed) && parsed.length) cacheEmbedding(id, parsed);
1245
+ else embeddingCache.delete(id);
1246
+ } catch { embeddingCache.delete(id); }
1247
+ } else {
1248
+ embeddingCache.delete(id);
1249
+ }
1188
1250
  }
1189
1251
 
1190
1252
  /** Batch fetch stored embeddings by id (v0.5.0 search-time semantic dedup).
@@ -1193,19 +1255,10 @@ export function createStore(path) {
1193
1255
  function getEmbeddings(ids) {
1194
1256
  const out = new Map();
1195
1257
  const list = (Array.isArray(ids) ? ids : []).filter(Boolean);
1196
- for (let i = 0; i < list.length; i += 100) {
1197
- const chunk = list.slice(i, i + 100);
1198
- const rows = db.prepare(
1199
- `SELECT id, embedding FROM memories
1200
- WHERE embedding IS NOT NULL AND embedding != ''
1201
- AND id IN (${chunk.map(() => "?").join(",")})`
1202
- ).all(...chunk);
1203
- for (const row of rows) {
1204
- try {
1205
- const vec = JSON.parse(row.embedding);
1206
- if (Array.isArray(vec) && vec.length) out.set(row.id, vec);
1207
- } catch { /* corrupt row: skip */ }
1208
- }
1258
+ for (const id of list) {
1259
+ // Issue #202:走同一解析缓存(语义去重的批量读也免重复 parse)。
1260
+ const vec = getParsedEmbedding(id);
1261
+ if (vec) out.set(id, vec);
1209
1262
  }
1210
1263
  return out;
1211
1264
  }
@@ -1280,24 +1333,30 @@ export function createStore(path) {
1280
1333
  function searchVector(vector, { limit = 20, includeArchived = false, threshold = 0 } = {}) {
1281
1334
  if (!Array.isArray(vector) || !vector.length) return [];
1282
1335
  const archivedFilter = includeArchived ? "" : "archived = 0 AND ";
1336
+ // Issue #202:只取 id 列(~40 KB)而非 SELECT *(~11 MB)——向量从缓存取,
1337
+ // 缓存未命中时按 id 点查 embedding 再解析回填。SQL 里保留 embedding 的
1338
+ // IS NOT NULL 过滤,保证「有向量的行」集合始终以库为准(删除/清空即时生效)。
1283
1339
  const rows = db.prepare(
1284
- `SELECT * FROM memories
1340
+ `SELECT id FROM memories
1285
1341
  WHERE ${archivedFilter}forgotten = 0 AND embedding IS NOT NULL AND embedding != ''`
1286
1342
  ).all();
1287
1343
  const scored = [];
1288
1344
  for (const row of rows) {
1289
- let v;
1290
- try {
1291
- v = JSON.parse(row.embedding);
1292
- } catch {
1293
- continue;
1294
- }
1345
+ const v = getParsedEmbedding(row.id);
1346
+ if (!v) continue;
1295
1347
  const score = cosine(vector, v);
1296
- if (score >= threshold) scored.push({ row, score });
1348
+ if (score >= threshold) scored.push({ row: { id: row.id }, score });
1297
1349
  }
1298
1350
  scored.sort((a, b) => b.score - a.score);
1299
1351
  const { limit: lim } = sanitizePage(limit, 0, 20);
1300
- return scored.slice(0, lim).map(({ row, score }) => ({ ...toRow(row), score }));
1352
+ // Top-N 回表:只对入选行取完整字段(主键点查 ≤ lim 行),评分别拖着正文走。
1353
+ const getFull = db.prepare("SELECT * FROM memories WHERE id = ?");
1354
+ const out = [];
1355
+ for (const { row, score } of scored.slice(0, lim)) {
1356
+ const full = getFull.get(row.id);
1357
+ if (full) out.push({ ...toRow(full), score });
1358
+ }
1359
+ return out;
1301
1360
  }
1302
1361
 
1303
1362
  // --- autoDream audit trail ----------------------------------------------
@@ -2245,6 +2304,7 @@ export function createStore(path) {
2245
2304
  search,
2246
2305
  setEmbedding,
2247
2306
  getEmbeddings,
2307
+ getParsedEmbedding,
2248
2308
  embeddedCount,
2249
2309
  needsEmbedding,
2250
2310
  searchVector,
package/src/summarize.js CHANGED
@@ -144,7 +144,7 @@ function collectMessages(session, maxChars = 8000, language = "zh") {
144
144
  break;
145
145
  }
146
146
  }
147
- return lines.length ? [createUserMessage({ content: [{ type: "text", text: trim(lines.join("\n"), maxChars) }] })] : [];
147
+ return lines.length ? [createUserMessage({ content: [{ type: "text", text: trim(lines.join("\n"), maxChars) }], source: { kind: "plugin", plugin: "dsh-mneme" } })] : [];
148
148
  }
149
149
 
150
150
  // ── 智能调速器(429 保护)─────────────────────────────────────────────
@@ -265,7 +265,7 @@ export function createSummarizer(ctx, service, config) {
265
265
  model: route.model,
266
266
  purpose: "summarization",
267
267
  messages: [
268
- { role: "system", content: [{ type: "text", text: config.codingRetrospect ? STR.prompts.codingSummary[langOf(config)] : STR.prompts.summary[langOf(config)] }] },
268
+ { role: "system", content: [{ type: "text", text: config.codingRetrospect ? STR.prompts.codingSummary[langOf(config)] : STR.prompts.summary[langOf(config)] }], source: { kind: "plugin", plugin: "dsh-mneme" } },
269
269
  ...messages
270
270
  ],
271
271
  signal: controller.signal