@modusensus/dsh-mneme 0.8.15 → 0.8.16

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 (56) hide show
  1. package/README.md +8 -3
  2. package/bin/cli.mjs +4 -2
  3. package/docs/CONFIGURATION.md +14 -2
  4. package/docs/DISTILL.md +162 -0
  5. package/docs/STORAGE.md +11 -2
  6. package/lib/api-standalone.js +22 -39
  7. package/lib/api.js +171 -3
  8. package/lib/client.js +1065 -156
  9. package/lib/config.js +68 -1
  10. package/lib/dream/decisions.js +20 -0
  11. package/lib/dream.js +2 -0
  12. package/lib/hot-memory.js +62 -0
  13. package/lib/index.js +24 -7
  14. package/lib/inject.js +27 -63
  15. package/lib/maintenance.js +25 -5
  16. package/lib/recall-stats.js +22 -7
  17. package/lib/reclaim-http.js +150 -0
  18. package/lib/safe-slice.js +18 -0
  19. package/lib/service.js +27 -2
  20. package/lib/settings.js +13 -2
  21. package/lib/store.js +196 -7
  22. package/lib/summarize.js +208 -60
  23. package/package.json +1 -1
  24. package/src/api-standalone.js +22 -39
  25. package/src/api.js +171 -3
  26. package/src/config.js +68 -1
  27. package/src/dream/decisions.js +20 -0
  28. package/src/dream.js +2 -0
  29. package/src/hot-memory.js +62 -0
  30. package/src/index.js +24 -7
  31. package/src/inject.js +27 -63
  32. package/src/maintenance.js +25 -5
  33. package/src/recall-stats.js +22 -7
  34. package/src/reclaim-http.js +150 -0
  35. package/src/safe-slice.js +18 -0
  36. package/src/service.js +27 -2
  37. package/src/settings.js +13 -2
  38. package/src/store.js +196 -7
  39. package/src/summarize.js +208 -60
  40. package/test/api-routes-gaps.test.js +681 -0
  41. package/test/api.test.js +25 -2
  42. package/test/client.test.js +354 -2
  43. package/test/contrast.test.js +314 -0
  44. package/test/dream-merge-guardrail.test.js +219 -0
  45. package/test/hot-memory.test.js +67 -1
  46. package/test/inject-recall.test.js +39 -0
  47. package/test/inject.test.js +23 -0
  48. package/test/llm-audit.test.js +98 -0
  49. package/test/maintenance.test.js +112 -2
  50. package/test/pre-inject-gate.test.js +10 -0
  51. package/test/recall-stats.test.js +89 -4
  52. package/test/reclaim-http.test.js +209 -0
  53. package/test/service.test.js +7 -2
  54. package/test/settings.test.js +8 -0
  55. package/test/store.test.js +108 -0
  56. package/test/summarize.test.js +174 -0
@@ -0,0 +1,314 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ // #178 的回归锁:面板正文色的对比度。
8
+ //
9
+ // 为什么是硬编码快照而不是现场读宿主:CI runner 上没有 DSH 安装(没有
10
+ // app.asar),宿主 token 表根本读不到;而这条锁要在 CI 上拦住「面板又用回了
11
+ // 一个低对比度的宿主 token」。所以把面板实际引用到的宿主 token 浅/深取值抄成
12
+ // 快照(2026-10 取自 DSH app.asar 的 token 表:body = 浅色、
13
+ // body[data-ds-dark-theme] = 深色、:root = 两主题同值),锁的是**面板自己的
14
+ // 用法**,宿主改色不会让这条锁变红。
15
+ //
16
+ // 面板的坑有两层,这条锁两层都咬:
17
+ // ① 宿主 token 在浅色下给正文只有 1.26–4.49 的对比度(label-tertiary 50 处、
18
+ // label-dimmed 4 处),照抄宿主名就等于照抄不合规——注意这两个名字**都是
19
+ // 真实存在的**宿主 token,只是宿主把它们定位成分隔线/占位符的低对比层;
20
+ // ② 面板还长期引用 5 个**根本不存在的**宿主名(--dsw-alias-state-error /
21
+ // -warning / -success / -warn / --dsw-alias-border),
22
+ // 于是吃的一直是写在 fallback 里的硬编码色。所以除了比值,还要锁「引用到的
23
+ // 宿主名必须真实存在」。
24
+ //
25
+ // 修法是面板自有的语义色层(--mneme-*,定义在 .mneme-x 等四个渲染根上),
26
+ // 混色基准仍是宿主 token,宿主换肤时跟着走。见 lib/client.js 里那段注释。
27
+
28
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
29
+ const clientSource = readFileSync(join(root, "lib/client.js"), "utf8");
30
+
31
+ const HOST_TOKENS = {
32
+ "--dsw-alias-label-primary": { light: "#0f1115", dark: "#f9fafb" },
33
+ "--dsw-alias-label-secondary": { light: "#61666b", dark: "#cfd3d6" },
34
+ "--dsw-alias-label-tertiary": { light: "#81858c", dark: "#adb2b8" },
35
+ // 真名,不是幻影:宿主确有 --dsw-alias-label-dimmed(指向 static-neutral-bluish-200
36
+ // / -750)。它留在快照里是为了让存在性锁**不**把它当幻影报错——该拦的是「拿它当
37
+ // 正文/图形色」的用法,那由上面的比值锁负责。
38
+ "--dsw-alias-label-dimmed": { light: "#e1e5ee", dark: "#43454a" },
39
+ "--dsw-alias-state-business-primary": { light: "#4176e6", dark: "#7aaaff" },
40
+ "--dsw-alias-state-error-primary": { light: "#ec1313", dark: "#f25a5a" },
41
+ "--dsw-alias-bg-layer-1": { light: "#ffffff", dark: "#232324" },
42
+ "--dsw-alias-bg-layer-2": { light: "#ffffff", dark: "#2c2c2e" },
43
+ "--dsw-alias-bg-base": { light: "#ffffff", dark: "#151517" },
44
+ "--dsw-alias-button-elevated-fill": { light: "#ffffff", dark: "#43454a" },
45
+ "--dsw-alias-border-l1": { light: "#0000000a", dark: "#ffffff0f" },
46
+ "--dsw-alias-border-l2": { light: "#0000001a", dark: "#ffffff1f" },
47
+ "--dsw-alias-interactive-bg-hover": { light: "#2631480f", dark: "#ffffff14" },
48
+ "--dsw-alias-interactive-bg-active": { light: "#2631481a", dark: "#ffffff24" },
49
+ "--dsw-alias-scrollbar-bg-l2": { light: "#e5e5e5", dark: "#545557" },
50
+ "--dsw-alias-scrollbar-hover-l2": { light: "#d4d4d4", dark: "#65676b" },
51
+ "--dsw-static-amber-600": { light: "#dd8629", dark: "#dd8629" },
52
+ "--dsw-static-green-500": { light: "#22c55e", dark: "#22c55e" },
53
+ // 真实存在但**不是颜色**的宿主 token:只参与上面的「名字必须存在」检查。
54
+ "--dsw-radius-md": { light: null, dark: null },
55
+ "--dsw-focus-ring-width": { light: null, dark: null },
56
+ "--dsw-focus-ring-color": { light: "transparent", dark: "transparent" }
57
+ };
58
+
59
+ /* ---------- 从面板产物里切出 CSS 块 ---------- */
60
+ const cssStart = clientSource.indexOf("const css = [");
61
+ const cssEnd = clientSource.indexOf('].join("\\n");', cssStart);
62
+ assert.ok(cssStart > 0 && cssEnd > cssStart, "lib/client.js 里找不到 CSS 数组(切片锚点变了?)");
63
+ const cssBlock = clientSource.slice(cssStart, cssEnd);
64
+
65
+ const rules = [];
66
+ for (const m of cssBlock.matchAll(/"((?:[^"\\]|\\.)*)"/g)) {
67
+ const s = m[1].replace(/\\"/g, '"');
68
+ if (!s.includes("{")) continue;
69
+ const rm = /^([^{]+)\{([^}]*)\}$/.exec(s.trim());
70
+ if (rm) rules.push({ sel: rm[1].trim(), body: rm[2] });
71
+ }
72
+
73
+ /* ---------- 颜色数学(alpha 合成,不是「和白底混」) ---------- */
74
+ function parseColor(c) {
75
+ let m;
76
+ if ((m = /^#([0-9a-fA-F]{3,8})$/.exec(String(c).trim()))) {
77
+ let s = m[1];
78
+ if (s.length === 3 || s.length === 4) s = s.split("").map((x) => x + x).join("");
79
+ return [
80
+ parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16),
81
+ s.length === 8 ? parseInt(s.slice(6, 8), 16) / 255 : 1
82
+ ];
83
+ }
84
+ if ((m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/.exec(String(c).trim()))) {
85
+ const a = m[4] === undefined ? 1 : m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4]);
86
+ return [+m[1], +m[2], +m[3], a];
87
+ }
88
+ return null;
89
+ }
90
+ // 半透明前景必须真的叠到底色上再算比值:早期审计脚本拿「和白底混」量深色主题,
91
+ // 把 --dsw-alias-label-primary 60% 算成 15.36 的假高分(真实值 6.30)。
92
+ function composite(top, bottom) {
93
+ const a = top[3] + bottom[3] * (1 - top[3]);
94
+ const f = (i) => (top[i] * top[3] + bottom[i] * bottom[3] * (1 - top[3])) / (a || 1);
95
+ return [f(0), f(1), f(2), a];
96
+ }
97
+ function luminance([r, g, b]) {
98
+ const [x, y, z] = [r, g, b].map((v) => {
99
+ const s = v / 255;
100
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
101
+ });
102
+ return 0.2126 * x + 0.7152 * y + 0.0722 * z;
103
+ }
104
+ function contrast(fg, bg) {
105
+ const a = luminance(composite(fg, bg));
106
+ const b = luminance(bg);
107
+ const [hi, lo] = [a, b].sort((p, q) => q - p);
108
+ return (hi + 0.05) / (lo + 0.05);
109
+ }
110
+
111
+ /* ---------- 解析:宿主快照 + 面板自己的语义色层 ---------- */
112
+ const TOKENS = new Map();
113
+ for (const [name, v] of Object.entries(HOST_TOKENS)) TOKENS.set(name, v);
114
+
115
+ // 面板语义色层是一条由多个字符串字面量拼起来的规则,不出现在上面的 rules 里,
116
+ // 所以按拼好的文本再读一次。
117
+ const joined = [...cssBlock.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1].replace(/\\"/g, '"')).join("");
118
+ const layerM = /([^{}]*)\{[^{}]*--mneme-fg-dim\s*:[^{}]*\}/.exec(joined);
119
+ assert.ok(layerM, "找不到面板语义色层(--mneme-* 定义),四个渲染根那条规则被删了?");
120
+ const layer = { sel: layerM[1].split("}").pop().trim(), body: layerM[0].slice(layerM[0].indexOf("{")) };
121
+ for (const g of layer.body.matchAll(/(--mneme-[a-z0-9-]+)\s*:\s*([^;}]+)/g)) {
122
+ TOKENS.set(g[1], { light: g[2].trim(), dark: g[2].trim() });
123
+ }
124
+
125
+ // 先把 var()/color-mix() 逐层折成字符串,再交给 colorOf 解析成 RGBA。
126
+ // 之所以不用「一个递归函数同时返回数组和字符串」:字符串替换里塞数组会被打散。
127
+ function resolveValue(raw, theme) {
128
+ let v = String(raw).trim().replace(/!important$/, "").trim();
129
+ let changed = true;
130
+ for (let guard = 0; changed && guard < 20; guard++) {
131
+ changed = false;
132
+ v = v.replace(/var\(\s*(--[a-z0-9-]+)\s*(?:,\s*([^()]*(?:\([^()]*\)[^()]*)*))?\)/g, (_, tok, fb) => {
133
+ const e = TOKENS.get(tok);
134
+ const inner = e ? resolveValue(e[theme], theme) : null;
135
+ if (inner) { changed = true; return inner; }
136
+ if (fb) { changed = true; return fb.trim(); }
137
+ return "\u00acMISSING\u00ac";
138
+ });
139
+ }
140
+ return v.includes("\u00acMISSING\u00ac") ? null : v.trim();
141
+ }
142
+ function colorOf(raw, theme) {
143
+ const v = resolveValue(raw, theme);
144
+ if (v === null) return null;
145
+ let m = /^color-mix\(\s*in\s+srgb\s*,\s*(.+?)\s+([\d.]+)%\s*,\s*transparent\s*\)$/.exec(v);
146
+ if (m) {
147
+ const base = colorOf(m[1], theme);
148
+ if (!base) return null;
149
+ return [...base.slice(0, 3), base[3] * (parseFloat(m[2]) / 100)];
150
+ }
151
+ m = /^color-mix\(\s*in\s+srgb\s*,\s*(.+?)\s+([\d.]+)%\s*,\s*(.+?)\s*\)$/.exec(v);
152
+ if (m) {
153
+ const a = colorOf(m[1], theme);
154
+ const b = colorOf(m[3], theme);
155
+ if (!a || !b) return null;
156
+ const p = parseFloat(m[2]) / 100;
157
+ return [...a.slice(0, 3).map((x, i) => x * p + b[i] * (1 - p)), a[3] * p + b[3] * (1 - p)];
158
+ }
159
+ return parseColor(v);
160
+ }
161
+
162
+ /* ---------- 底色:按类名找它自己的 background ---------- */
163
+ const BG_BY_CLASS = new Map();
164
+ for (const r of rules) {
165
+ const bg = /(?:^|;)\s*background(?:-color)?\s*:\s*([^;]+)/.exec(r.body);
166
+ if (!bg) continue;
167
+ for (const c of r.sel.matchAll(/\.([a-z0-9-]+)/gi)) {
168
+ const k = c[1].toLowerCase();
169
+ if (!BG_BY_CLASS.has(k)) BG_BY_CLASS.set(k, []);
170
+ BG_BY_CLASS.get(k).push({ val: bg[1].trim(), sel: r.sel });
171
+ }
172
+ }
173
+ const THEME_BG = { light: "#ffffff", dark: "#232324" }; // --dsw-alias-bg-layer-1
174
+ function backgroundOf(sel, theme) {
175
+ const base = parseColor(THEME_BG[theme]);
176
+ const own = [];
177
+ for (const c of sel.matchAll(/\.([a-z0-9-]+)/gi)) {
178
+ for (const e of BG_BY_CLASS.get(c[1].toLowerCase()) ?? []) {
179
+ if (!/hover|active|focus|disabled/.test(e.sel)) own.push(e);
180
+ }
181
+ }
182
+ for (const e of own) {
183
+ const v = colorOf(e.val, theme);
184
+ if (v) return v[3] < 1 ? composite(v, base) : v;
185
+ }
186
+ return base;
187
+ }
188
+
189
+ /* ---------- 逐条算 ---------- */
190
+ const failures = [];
191
+ let audited = 0;
192
+ for (const r of rules) {
193
+ const colM = /(?:^|;)\s*color\s*:\s*([^;]+)/.exec(r.body);
194
+ if (!colM) continue;
195
+ if (/::(before|after)/.test(r.sel)) continue;
196
+ const fsM = /font-size\s*:\s*([\d.]+)px/.exec(r.body);
197
+ const fwM = /font-weight\s*:\s*([\d]+|bold|normal)/.exec(r.body);
198
+ const fs = fsM ? +fsM[1] : 13;
199
+ const fw = fwM ? (/bold/.test(fwM[1]) ? 700 : fwM[1] === "normal" ? 400 : +fwM[1]) : 400;
200
+ const need = fs >= 24 || (fs >= 18.66 && fw >= 700) ? 3 : 4.5;
201
+ for (const theme of ["light", "dark"]) {
202
+ const fg = colorOf(colM[1], theme);
203
+ // 解析不出来**不算通过**:面板 CSS 块里的 color 全是 hex/rgb/var/color-mix
204
+ // (没有 inherit/currentColor 之类的关键字),所以 null 只可能意味着引用了
205
+ // 不存在的 token 或写了个解析器不认识的值——那正是要拦的东西。若在这里
206
+ // `continue`,把一条声明改成 `color:var(--mneme-unknown)` 就能静默溜过,
207
+ // 剩下的声明仍然够 audited >= 200。
208
+ if (!fg) {
209
+ failures.push(`${theme} ${r.sel} 颜色解析失败:${colM[1].trim()}`);
210
+ continue;
211
+ }
212
+ audited++;
213
+ const cr = contrast(fg, backgroundOf(r.sel, theme));
214
+ if (cr < need) {
215
+ failures.push(`${theme} ${r.sel} ${fs}px/${fw} = ${cr.toFixed(2)} < ${need}(${colM[1].trim()})`);
216
+ }
217
+ }
218
+ }
219
+
220
+ test("面板每个 color 声明在浅/深两主题下都达到 WCAG AA(#178 主锁)", () => {
221
+ assert.ok(audited >= 200, `审计到的 color 声明太少(${audited}),CSS 切片或解析器可能失效了`);
222
+ assert.deepEqual(failures, [], "以下声明对比度不足:\n" + failures.join("\n"));
223
+ });
224
+
225
+ // 幻影 token 的回归锁:面板曾经引用 5 个宿主里不存在的名字,于是长年吃 fallback
226
+ // 里的硬编码色(换肤不跟随、深色主题翻车)。这条锁不看比值、只看名字是否存在,
227
+ // 因此将来任何「顺手写个听起来合理的 --dsw-* 名」都会被拦下。
228
+ test("面板引用的宿主 token 必须真实存在(幻影 token 回归锁)", () => {
229
+ // 只扫真实声明:CSS 数组里夹着 JS 注释,注释里会提到被修掉的旧名。
230
+ const declared = cssBlock.split("\n").filter((l) => !/^\s*\/\//.test(l)).join("\n");
231
+ const referenced = new Set([...declared.matchAll(/--dsw-[a-z0-9-]+/g)].map((m) => m[0]));
232
+ const unknown = [...referenced].filter((n) => !(n in HOST_TOKENS));
233
+ assert.deepEqual(unknown, [], "面板引用了宿主快照里没有的 token(幻影名或快照过期):" + unknown.join(", "));
234
+ });
235
+
236
+ // 变量层必须挂满四个渲染根:面板不只长在 .mneme-x 下——记忆库 sheet portal 到
237
+ // body(.mneme-overlay)、侧边栏入口在宿主插槽(.mneme-triggerwrap)、顶部入口
238
+ // portal 到宿主侧边栏(.mneme-topentry)。少挂一个,那个根下的文字就退回宿主的
239
+ // 低对比度 token,而且上面的主锁**照样全绿**(主锁只算颜色,不知道变量有没有继承到)。
240
+ test("面板语义色层覆盖四个渲染根", () => {
241
+ const sel = layer.sel;
242
+ assert.equal(sel, ".mneme-x,.mneme-overlay,.mneme-triggerwrap,.mneme-topentry");
243
+ });
244
+
245
+ // 图形色的对比度(WCAG 1.4.11,非文字 3:1)。上面那条主锁只看 `color:`,
246
+ // 而「颜色就是信息」的地方用的是 `background:` / `stroke:`——热度条、热度点、
247
+ // 打卡点、关系图连线。它们此前用宿主的 label-dimmed(浅 1.26 / 深 1.45),
248
+ // 等于把三档热度画成同一个看不见的灰。谁把它们改回去,主锁不会响,这条会。
249
+ const GRAPHICS = [
250
+ { sel: ".mneme-heatbar--hot", prop: "background" },
251
+ { sel: ".mneme-heatbar--warm", prop: "background" },
252
+ { sel: ".mneme-heatbar--cold", prop: "background" },
253
+ { sel: ".mneme-heatdot--hot", prop: "background" },
254
+ { sel: ".mneme-heatdot--warm", prop: "background" },
255
+ { sel: ".mneme-heatdot--cold", prop: "background" },
256
+ { sel: ".mneme-wbdot", prop: "background" },
257
+ { sel: ".mneme-wbdot--err", prop: "background" },
258
+ { sel: ".mneme-gedge", prop: "stroke" },
259
+ // Token 去向三屏(2026-10):donut 弧(stroke)、图例色点与 7 天柱(background)
260
+ // 都是「颜色就是信息」的图形——弧长/点位承载比例语义,掉回浅灰等于白画。
261
+ // 零值热力格(interactive-bg-hover 轨道)与 heatbar 同理不在此列。
262
+ { sel: ".mneme-seg--1", prop: "stroke" },
263
+ { sel: ".mneme-seg--2", prop: "stroke" },
264
+ { sel: ".mneme-seg--3", prop: "stroke" },
265
+ { sel: ".mneme-seg--4", prop: "stroke" },
266
+ { sel: ".mneme-seg--5", prop: "stroke" },
267
+ { sel: ".mneme-seg--6", prop: "stroke" },
268
+ { sel: ".mneme-dot--1", prop: "background" },
269
+ { sel: ".mneme-dot--2", prop: "background" },
270
+ { sel: ".mneme-dot--3", prop: "background" },
271
+ { sel: ".mneme-dot--4", prop: "background" },
272
+ { sel: ".mneme-dot--5", prop: "background" },
273
+ { sel: ".mneme-dot--6", prop: "background" },
274
+ { sel: ".mneme-bar", prop: "background" },
275
+ { sel: ".mneme-heatcell.l1", prop: "background" },
276
+ { sel: ".mneme-heatcell.l2", prop: "background" },
277
+ { sel: ".mneme-heatcell.l3", prop: "background" },
278
+ { sel: ".mneme-heatcell.l4", prop: "background" }
279
+ ];
280
+ test("图形色(热度/打卡/连线)在浅深两主题下都达到 3:1", () => {
281
+ const bySel = new Map(rules.map((r) => [r.sel, r]));
282
+ const problems = [];
283
+ for (const g of GRAPHICS) {
284
+ const r = bySel.get(g.sel);
285
+ if (!r) { problems.push(`${g.sel} 规则没了`); continue; }
286
+ const m = new RegExp(`(?:^|;)\\s*${g.prop}\\s*:\\s*([^;]+)`).exec(r.body);
287
+ if (!m) { problems.push(`${g.sel} 没有 ${g.prop}`); continue; }
288
+ for (const theme of ["light", "dark"]) {
289
+ const fg = colorOf(m[1], theme);
290
+ if (!fg) { problems.push(`${g.sel} 解析不出颜色:${m[1]}`); continue; }
291
+ // 热度条画在它自己的轨道(interactive-bg-hover)上,其余直接压在画布上。
292
+ let bg = parseColor(THEME_BG[theme]);
293
+ if (/heatbar/.test(g.sel)) {
294
+ const track = colorOf("var(--dsw-alias-interactive-bg-hover)", theme);
295
+ if (track) bg = composite(track, bg);
296
+ }
297
+ const cr = contrast(fg, bg);
298
+ if (cr < 3) problems.push(`${theme} ${g.sel} ${cr.toFixed(2)} < 3(${m[1].trim()})`);
299
+ }
300
+ }
301
+ assert.deepEqual(problems, [], "图形色对比度不足:\n" + problems.join("\n"));
302
+ });
303
+
304
+ // 虚线关系边曾经在 .mneme-gedge-dashed 上再叠一层 opacity:.7,把已经只有 50% 的
305
+ // 描边压到浅色 2.28(低于图形 3:1)。上面那条图形锁只读单条规则自己的 stroke,
306
+ // 看不到「同一条边同时命中两条规则、其中一条在降透明度」这种叠加,所以单独锁一层:
307
+ // 虚线态只允许用 dash 图案区分,不许再动透明度。
308
+ test("虚线关系边不得靠降低不透明度区分", () => {
309
+ const dashed = rules.find((r) => r.sel === ".mneme-gedge-dashed");
310
+ assert.ok(dashed, ".mneme-gedge-dashed 规则没了(虚线态怎么区分无 memory_id 的边?)");
311
+ const op = /(?:^|;)\s*opacity\s*:\s*([^;]+)/.exec(dashed.body);
312
+ assert.equal(op, null, `虚线边又叠了 opacity(${op?.[1].trim()}):50% 描边乘上它会在浅色画布跌破 3:1`);
313
+ assert.match(dashed.body, /stroke-dasharray/, "虚线态丢了 dash 图案,就和实线边分不出来了");
314
+ });
@@ -0,0 +1,219 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+ import { Config } from "../src/config.js";
6
+ import { createSettings } from "../src/settings.js";
7
+ import { createDreamScheduler, validateDecisions } from "../src/dream.js";
8
+ import { mockCtx } from "./helpers/dream-mock.js";
9
+
10
+ // 回归(#135 成本审计派生):merge 决策的单轮数量闸 dreamMaxMergePerRun。
11
+ //
12
+ // 为什么需要这道闸:merge 是巩固里唯一**回吐正文**的动作——每条 merge 都要求模型
13
+ // 重新写出合并后的 content(实测 2113 条 merge 平均 550 字符/条),而 keep /
14
+ // archive / conflict 都不带正文。单轮 merge 数因此是「输出里正文占比」唯一可控的
15
+ // 杠杆。此前 update(2) / create(5) / archive(8) 都有上限,唯独 merge 没有。
16
+ //
17
+ // 闸门形态与现有三道**完全一致**:全局信号,skipInvalid 也不豁免,超限整单拒绝。
18
+ // 这一点是本文件的锁点之一——若有人把 merge 闸改成「逐条跳过」,就与另外三道闸
19
+ // 的语义分叉了,而超限(模型一轮要合并几十条)恰恰是整体失控信号,必须整单拒绝。
20
+ //
21
+ // 默认值 40 的校准依据(只读探针:全库 246 轮 / 近 10 天 88 轮 dream_runs.decisions):
22
+ // 每轮 merge 数 全库 p50 7 / p90 15 / p99 28 / max 39
23
+ // 近 10 天 p50 9 / p90 20 / p99 39 / max 39
24
+ // 取 40 = 观测分布上沿(历史命中 0/246),与 archive 闸默认 8 恰为其 p90=max 同
25
+ // 一校准法:面向未来的尾险护栏,不是成本削减工具。刻意保守的理由是代价不对称:
26
+ // 整单拒绝 = run 记 failed = 调度器不刷新 baseline(src/dream.js:905-915)=
27
+ // 下一次写入用同一批输入重跑,一次误伤约等于该轮成本 ×2。
28
+ //
29
+ // 相关但**不是**本闸目标的实测事实(防后人误用本闸去省 token):dream_consolidate
30
+ // 的输出 token 里只有约 11.8% 是决策正文,其余是推理与 JSON 骨架,那部分由
31
+ // dreamReasoningEffort / 模型选择决定,调 merge 上限影响不到。
32
+
33
+ function snap(entries) {
34
+ return new Map(
35
+ entries.map(([id, type]) => [
36
+ id,
37
+ { id, type, title: `t-${id}`, content: `c-${id}`, importance: 3, archived: false, forgotten: false }
38
+ ])
39
+ );
40
+ }
41
+
42
+ /** 造 n 条互不相干的普通类型记忆,配对成 merge(每条 merge 需要 title+content)。 */
43
+ function mergeDecisions(n) {
44
+ const entries = Array.from({ length: n * 2 }, (_, i) => [`m${i}`, "project"]);
45
+ const decisions = [];
46
+ for (let i = 0; i < n; i += 1) {
47
+ decisions.push({
48
+ action: "merge",
49
+ ids: [`m${2 * i}`, `m${2 * i + 1}`],
50
+ title: `merged-${i}`,
51
+ content: `合并后的正文 ${i}`,
52
+ keepSource: `m${2 * i}`
53
+ });
54
+ }
55
+ return { entries, decisions };
56
+ }
57
+
58
+ // ---------------------------------------------------------- 数量闸(纯函数)
59
+
60
+ test("#135-cost: merge count above the cap rejects the whole batch (global gate)", () => {
61
+ const { entries, decisions } = mergeDecisions(41);
62
+ const s = snap(entries);
63
+ const { ok, errors } = validateDecisions(decisions, s, { skipInvalid: true });
64
+ assert.equal(ok, false, "41 merges > default cap 40 → reject even under skipInvalid");
65
+ assert.ok(
66
+ errors.some((e) => e.includes("too many merge decisions")),
67
+ `cap error present, got: ${errors.join("; ")}`
68
+ );
69
+ });
70
+
71
+ test("#135-cost: merge count at the cap passes (boundary is inclusive)", () => {
72
+ const { entries, decisions } = mergeDecisions(40);
73
+ const s = snap(entries);
74
+ const { ok, errors } = validateDecisions(decisions, s, { skipInvalid: true });
75
+ assert.equal(ok, true, `exactly 40 merges is allowed, got: ${errors.join("; ")}`);
76
+ });
77
+
78
+ test("#135-cost: merge cap is configurable and defaults to the observed upper bound (40)", () => {
79
+ const { entries, decisions } = mergeDecisions(41);
80
+ const s = snap(entries);
81
+ // 默认值本身是本次改动的契约:实测分布上沿 39 → 闸门取 40。
82
+ const raised = validateDecisions(structuredClone(decisions), s, { skipInvalid: true, maxMergePerRun: 60 });
83
+ assert.equal(raised.ok, true, `raised cap lets the batch through, got: ${raised.errors.join("; ")}`);
84
+ const lowered = validateDecisions(structuredClone(decisions), s, { skipInvalid: true, maxMergePerRun: 20 });
85
+ assert.equal(lowered.ok, false, "lowered cap catches the same batch");
86
+ });
87
+
88
+ test("#135-cost: merge cap does not fire on ordinary runs (calibrated to the tail, not the median)", () => {
89
+ // p90 = 15、p99 = 28:常态与「偏大但正常」的轮都不该被拦。若有人把默认值调到
90
+ // p90 附近(用覆盖换成本),这条用例会红——这是刻意的:默认值必须落在尾险区。
91
+ for (const n of [7, 15, 28, 39]) {
92
+ const { entries, decisions } = mergeDecisions(n);
93
+ const { ok, errors } = validateDecisions(decisions, snap(entries), { skipInvalid: true });
94
+ assert.equal(ok, true, `${n} merges (within observed distribution) must pass, got: ${errors.join("; ")}`);
95
+ }
96
+ });
97
+
98
+ test("#135-cost: merge cap is independent of the other three caps", () => {
99
+ // 31 条 merge + 1 条 update + 1 条 archive:三道老闸都在限内,只有 merge 超限时
100
+ // 才应该报 merge 的错——确认新闸不是被别的计数顺带触发的。
101
+ const { entries, decisions } = mergeDecisions(41);
102
+ const s = snap([...entries, ["u1", "project"], ["a1", "decision"]]);
103
+ const all = [
104
+ ...decisions,
105
+ { action: "update", ids: ["u1"], changes: { title: "改标题" } },
106
+ { action: "archive", ids: ["a1"], reason: "重复或过时" }
107
+ ];
108
+ const { ok, errors } = validateDecisions(all, s, { skipInvalid: true });
109
+ assert.equal(ok, false);
110
+ assert.ok(errors.some((e) => e.includes("too many merge decisions")));
111
+ assert.equal(errors.some((e) => e.includes("too many update decisions")), false, "update cap must not fire");
112
+ assert.equal(errors.some((e) => e.includes("too many archive decisions")), false, "archive cap must not fire");
113
+ });
114
+
115
+ // ---------------------------------------------------------- 配置面(schema + 白名单成对)
116
+
117
+ test("#135-cost: dreamMaxMergePerRun defaults to 40 and clamps to [1, 200]", () => {
118
+ assert.equal(Config({}).dreamMaxMergePerRun, 40, "default = observed upper bound of merge-per-run distribution");
119
+ assert.equal(Config({ dreamMaxMergePerRun: 1 }).dreamMaxMergePerRun, 1, "lower bound accepted");
120
+ assert.equal(Config({ dreamMaxMergePerRun: 200 }).dreamMaxMergePerRun, 200, "upper bound accepted");
121
+ assert.throws(() => Config({ dreamMaxMergePerRun: 0 }), "zero rejected");
122
+ assert.throws(() => Config({ dreamMaxMergePerRun: 201 }), "above max rejected");
123
+ });
124
+
125
+ test("#135-cost: dreamMaxMergePerRun is in the settings whitelist with the same bounds as the schema", () => {
126
+ // 新配置键必须 config.js schema 与 settings.js 白名单成对出现(AGENTS.md 自查清单 2)。
127
+ // 走公开的 setFeatureFlags 路径:validateFlag 是 settings.js 的模块内私有函数,
128
+ // 而「键不在白名单 → 静默丢弃、不报错」正是这条用例要防的失败模式。
129
+ const store = createStore(":memory:");
130
+ const settings = createSettings(store.db);
131
+ assert.deepEqual(settings.getFeatureFlags(), {}, "nothing stored initially");
132
+ assert.equal(settings.setFeatureFlags({ dreamMaxMergePerRun: 40 }).dreamMaxMergePerRun, 40, "whitelisted");
133
+ assert.equal(settings.getFeatureFlags().dreamMaxMergePerRun, 40, "persisted and re-read");
134
+ assert.throws(
135
+ () => settings.setFeatureFlags({ dreamMaxMergePerRun: 0 }),
136
+ /must be an integer in \[1, 200\]/
137
+ );
138
+ assert.throws(
139
+ () => settings.setFeatureFlags({ dreamMaxMergePerRun: 201 }),
140
+ /must be an integer in \[1, 200\]/
141
+ );
142
+ assert.throws(() => settings.setFeatureFlags({ dreamMaxMergePerRun: 1.5 }), /must be an integer/);
143
+ // 越界被拒后不得留下脏值。
144
+ assert.equal(settings.getFeatureFlags().dreamMaxMergePerRun, 40, "rejected write did not corrupt the stored value");
145
+ store.close();
146
+ });
147
+
148
+ // ---------------------------------------------------------- 端到端(runDream)
149
+
150
+ test("#135-cost: runDream rejects a runaway merge batch and leaves the memories untouched", async () => {
151
+ const store = createStore(":memory:");
152
+ const service = createService({ store, mirror: null, config: {} });
153
+ // 84 条普通记忆 → 42 对 merge,超过默认闸 40。
154
+ for (let i = 0; i < 84; i += 1) {
155
+ service.saveWithDedupe({ type: "project", title: `记忆 ${i}`, content: `正文 ${i}`, importance: 3 });
156
+ }
157
+ const ctx = mockCtx({
158
+ onConsolidation: (listText) => {
159
+ const ids = [...listText.matchAll(/id=([^\s|]+)/g)].map((m) => m[1]);
160
+ const decisions = [];
161
+ for (let i = 0; i + 1 < ids.length; i += 2) {
162
+ decisions.push({
163
+ action: "merge",
164
+ ids: [ids[i], ids[i + 1]],
165
+ title: `合并 ${i}`,
166
+ content: `合并后的正文 ${i}`,
167
+ keepSource: ids[i]
168
+ });
169
+ }
170
+ return JSON.stringify(decisions);
171
+ }
172
+ });
173
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
174
+ const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
175
+ assert.equal(result.ok, false, "42 merges > cap 40 → run fails as a whole");
176
+ assert.match(result.error, /invalid decisions/);
177
+ // 整单拒绝 = 一条都没落:merge 不得半途生效(这正是「全局闸门」与「逐条跳过」的区别)。
178
+ // 注意 service.all() 含已归档行,所以必须数「未归档」的条数:merge 生效会把 source
179
+ // 置 archived,84 条里若有任何一条落了,未归档数就会掉下来。
180
+ assert.equal(service.all().filter((m) => !m.archived).length, 84, "no memory was merged away");
181
+ const audit = store.listDreamRuns().at(-1);
182
+ assert.equal(audit.status, "failed");
183
+ // decisions 是 store 层已 JSON.parse 的列,序列化后查错误串(_validationFailed 哨兵)。
184
+ assert.match(JSON.stringify(audit.decisions), /too many merge decisions/);
185
+ store.close();
186
+ });
187
+
188
+ test("#135-cost: runDream lands a merge batch below the cap", async () => {
189
+ const store = createStore(":memory:");
190
+ const service = createService({ store, mirror: null, config: {} });
191
+ for (let i = 0; i < 20; i += 1) {
192
+ service.saveWithDedupe({ type: "project", title: `记忆 ${i}`, content: `正文 ${i}`, importance: 3 });
193
+ }
194
+ const ctx = mockCtx({
195
+ onConsolidation: (listText) => {
196
+ const ids = [...listText.matchAll(/id=([^\s|]+)/g)].map((m) => m[1]);
197
+ const decisions = [];
198
+ for (let i = 0; i + 1 < ids.length; i += 2) {
199
+ decisions.push({
200
+ action: "merge",
201
+ ids: [ids[i], ids[i + 1]],
202
+ title: `合并 ${i}`,
203
+ content: `合并后的正文 ${i}`,
204
+ keepSource: ids[i]
205
+ });
206
+ }
207
+ return JSON.stringify(decisions);
208
+ }
209
+ });
210
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
211
+ const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
212
+ assert.equal(result.status, "ok", `10 merges must pass, got: ${result.error ?? ""}`);
213
+ // 10 对 merge → 10 个 keeper 留下,其余 10 条被归档;再加上本轮落库的 summary
214
+ // 记忆(未归档),未归档数应为 11。这条断言同时证明「闸门放行」与「merge 真的
215
+ // 生效了」——只断言 notEqual(failed) 会被「什么都没做」蒙混过去。
216
+ assert.equal(service.all().filter((m) => !m.archived).length, 11, "10 keepers + 1 summary survived");
217
+ assert.equal(result.applied, 10, "all 10 merges committed");
218
+ store.close();
219
+ });
@@ -1,6 +1,6 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { createHotMemory, estimateTokens } from "../src/hot-memory.js";
3
+ import { createHotMemory, estimateTokens, roundsFromEvents } from "../src/hot-memory.js";
4
4
  import { createStore } from "../src/store.js";
5
5
  import { createService } from "../src/service.js";
6
6
  import { createVectorIndex } from "../src/vector-index.js";
@@ -143,3 +143,69 @@ test("selective injection re-orders candidates by query similarity", () => {
143
143
  assert.equal(picked[0].id, thesis.id);
144
144
  assert.ok(picked.some((m) => m.id === plugin.id));
145
145
  });
146
+
147
+ // --- roundsFromEvents:surface 投影(rewind 撤回内容不得回流热记忆) ---
148
+
149
+ function userEvent(seq, text, kind) {
150
+ return { seq, type: "user/message", data: { source: kind ? { kind } : undefined, content: [text] } };
151
+ }
152
+ function assistantEvent(seq, text) {
153
+ return { seq, type: "assistant/message", data: { message: { content: [{ type: "text", text }] } } };
154
+ }
155
+
156
+ test("roundsFromEvents pairs user/assistant rounds and keeps the trailing pending query", () => {
157
+ const events = [
158
+ userEvent(1, "第一问"),
159
+ assistantEvent(2, "第一答"),
160
+ userEvent(3, "第二问")
161
+ ];
162
+ const rounds = roundsFromEvents(events, 5);
163
+ assert.equal(rounds.length, 2);
164
+ assert.equal(rounds[0].query, "第一问");
165
+ assert.equal(rounds[0].response, "第一答");
166
+ assert.equal(rounds[1].query, "第二问");
167
+ assert.equal(rounds[1].response, "");
168
+ });
169
+
170
+ test("roundsFromEvents excludes events shadowed off the surface (rewind/compact)", () => {
171
+ // append-only 日志里被撤回的轮次仍在,但 surface 只剩可见 seq——
172
+ // 热记忆必须与模型同源,被遮蔽的轮次不得回流。
173
+ const events = [
174
+ userEvent(1, "已被撤回的问题"),
175
+ assistantEvent(2, "已被撤回的回答"),
176
+ { seq: 3, type: "user/message", data: { source: { kind: "dsh-rewind" }, content: [""] } },
177
+ userEvent(4, "撤回后的新问题"),
178
+ assistantEvent(5, "撤回后的新回答")
179
+ ];
180
+ const visible = new Set([3, 4, 5]);
181
+ const rounds = roundsFromEvents(events, 5, visible);
182
+ assert.equal(rounds.length, 1);
183
+ assert.equal(rounds[0].query, "撤回后的新问题");
184
+ assert.equal(rounds[0].response, "撤回后的新回答");
185
+ assert.ok(!JSON.stringify(rounds).includes("已被撤回"));
186
+ });
187
+
188
+ test("roundsFromEvents with no surface info keeps the legacy full-log behavior", () => {
189
+ const events = [userEvent(1, "旧宿主问题"), assistantEvent(2, "旧宿主回答")];
190
+ const rounds = roundsFromEvents(events, 5, null);
191
+ assert.equal(rounds.length, 1);
192
+ assert.equal(rounds[0].query, "旧宿主问题");
193
+ assert.equal(rounds[0].response, "旧宿主回答");
194
+ });
195
+
196
+ test("roundsFromEvents skips rewind markers as queries even when on the surface", () => {
197
+ const events = [
198
+ { seq: 1, type: "user/message", data: { source: { kind: "dsh-rewind" }, content: [""] } },
199
+ userEvent(2, "标记后的第一问"),
200
+ assistantEvent(3, "标记后的第一答")
201
+ ];
202
+ const visible = new Set([1, 2, 3]);
203
+ const rounds = roundsFromEvents(events, 5, visible);
204
+ assert.equal(rounds.length, 1);
205
+ assert.equal(rounds[0].query, "标记后的第一问");
206
+ });
207
+
208
+ test("roundsFromEvents with an empty surface yields no rounds (model sees nothing)", () => {
209
+ const events = [userEvent(1, "问题"), assistantEvent(2, "回答")];
210
+ assert.equal(roundsFromEvents(events, 5, new Set()).length, 0);
211
+ });
@@ -103,3 +103,42 @@ test("slotFillRate = 注入条数 / (轮数 × 槽位数)", () => {
103
103
  assert.equal(stats.injection.slotFillRate, 3 / 4);
104
104
  store.close();
105
105
  });
106
+
107
+ // #369:history 曾被注入白名单挡在门外(蒸馏产得出、注入收不进)。这两条断言分
108
+ // 别锁「收编生效」与「重要度闸门对 history 不豁免」——后者一旦失效,短流水账会
109
+ // 直接挤掉决策类条目,那才是这个改动真正的风险面。
110
+ test("#369: history 进注入候选池", () => {
111
+ const { service } = setup();
112
+ service.saveWithDedupe({ type: "history", title: "切到暗色主题", content: "用户本次会话把界面切成暗色主题", importance: 4 });
113
+ const titles = service.injectCandidates({ maxItems: 5 }).map((m) => m.title);
114
+ assert.ok(titles.includes("切到暗色主题"), "importance>=3 的 history 应进注入候选");
115
+ });
116
+
117
+ test("#369: 低于重要度闸门的 history 不得例外放行", () => {
118
+ const { service } = setup();
119
+ service.saveWithDedupe({ type: "history", title: "打开过一次终端", content: "用户中途打开过一次终端", importance: 2 });
120
+ const titles = service.injectCandidates({ maxItems: 5 }).map((m) => m.title);
121
+ assert.ok(!titles.includes("打开过一次终端"), "history 不是 summary/preference,闸门照样生效");
122
+ });
123
+
124
+ // pattern 只由手工写入,却已被 dreamMergeGuard 列为长保留受保护类型——巩固层当资产
125
+ // 护住、注入面一次不给看是同一条口径的两头不一致。这条锁它进池。
126
+ test("#369: 手写的 pattern 进注入候选池", () => {
127
+ const { service } = setup();
128
+ service.saveWithDedupe({ type: "pattern", title: "重复字符串先抽共用模块", content: "多处重复的截断逻辑先收拢成共用模块,再改调用方", importance: 5 });
129
+ const titles = service.injectCandidates({ maxItems: 5 }).map((m) => m.title);
130
+ assert.ok(titles.includes("重复字符串先抽共用模块"), "importance>=3 的 pattern 应进注入候选");
131
+ });
132
+
133
+ // CodeRabbit on PR #404:语义缓存回填分支曾独漏重要度门槛(向量路与 BM25 路都带)。
134
+ // 一正一反:反向锁「低于闸门的行走缓存也不许进池」,正向锁「达标的照常进池」,
135
+ // 免得断言退化成常量真;缓存没被灌进来时正向那条会先红,用例不会空压。
136
+ test("#369: 语义缓存回填同样受重要度闸门约束", async () => {
137
+ const { service } = setup();
138
+ const low = service.saveWithDedupe({ type: "history", title: "终端开了一次", content: "用户中途打开过一次终端做检查", importance: 2 });
139
+ const high = service.saveWithDedupe({ type: "history", title: "终端方案定案", content: "用户终端接入方案已定案并验证", importance: 4 });
140
+ await service.searchMemories("终端", { mode: "keyword", useRerank: false, recordRecall: false });
141
+ const ids = service.injectCandidates({ query: "终端", maxItems: 5 }).map((m) => m.id);
142
+ assert.ok(ids.includes(high.memory.id), "i4 的 history 应经缓存回填进池(正向对照)");
143
+ assert.equal(ids.includes(low.memory.id), false, "低于闸门的行不得借语义缓存绕开门槛");
144
+ });