@modusensus/dsh-mneme 0.6.7 → 0.6.8

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 (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +463 -463
  3. package/cordis.patch.yml +15 -15
  4. package/lib/api.js +783 -783
  5. package/lib/client.js +1757 -1757
  6. package/lib/commands.js +64 -64
  7. package/lib/config.js +288 -288
  8. package/lib/dream/clustering.js +118 -118
  9. package/lib/dream/decisions.js +439 -439
  10. package/lib/dream/sleep.js +561 -554
  11. package/lib/dream/tag-extractor.js +156 -156
  12. package/lib/dream.js +935 -929
  13. package/lib/embedding.js +154 -154
  14. package/lib/entities/extractor.js +242 -242
  15. package/lib/hot-memory.js +53 -53
  16. package/lib/index.js +361 -361
  17. package/lib/inject.js +208 -208
  18. package/lib/local-embedder.js +282 -282
  19. package/lib/mirror.js +170 -170
  20. package/lib/parser/tag.js +59 -59
  21. package/lib/parser/wiki-link.js +38 -38
  22. package/lib/quality-filter.js +123 -123
  23. package/lib/reranker.js +218 -218
  24. package/lib/search/adaptive.js +22 -22
  25. package/lib/search/bm25.js +96 -96
  26. package/lib/search/tag-boost.js +61 -61
  27. package/lib/service.js +1726 -1726
  28. package/lib/settings.js +172 -172
  29. package/lib/store.js +2238 -2238
  30. package/lib/summarize.js +236 -236
  31. package/lib/tools.js +290 -290
  32. package/lib/vector-index.js +116 -116
  33. package/package.json +80 -80
  34. package/scripts/benchmark-embed.js +201 -201
  35. package/scripts/benchmark-recall.js +133 -133
  36. package/scripts/benchmark-rerank.js +166 -166
  37. package/scripts/e2e-dsh.js +218 -218
  38. package/scripts/stress-dsh.js +255 -255
  39. package/scripts/sync-lib.js +52 -52
  40. package/src/api.js +783 -783
  41. package/src/commands.js +64 -64
  42. package/src/config.js +288 -288
  43. package/src/dream/clustering.js +118 -118
  44. package/src/dream/decisions.js +439 -439
  45. package/src/dream/sleep.js +561 -554
  46. package/src/dream/tag-extractor.js +156 -156
  47. package/src/dream.js +935 -929
  48. package/src/embedding.js +154 -154
  49. package/src/entities/extractor.js +242 -242
  50. package/src/hot-memory.js +53 -53
  51. package/src/index.js +361 -361
  52. package/src/inject.js +208 -208
  53. package/src/local-embedder.js +282 -282
  54. package/src/mirror.js +170 -170
  55. package/src/parser/tag.js +59 -59
  56. package/src/parser/wiki-link.js +38 -38
  57. package/src/quality-filter.js +123 -123
  58. package/src/reranker.js +218 -218
  59. package/src/search/adaptive.js +22 -22
  60. package/src/search/bm25.js +96 -96
  61. package/src/search/tag-boost.js +61 -61
  62. package/src/service.js +1726 -1726
  63. package/src/settings.js +172 -172
  64. package/src/store.js +2238 -2238
  65. package/src/summarize.js +236 -236
  66. package/src/tools.js +290 -290
  67. package/src/vector-index.js +116 -116
  68. package/test/api.test.js +594 -594
  69. package/test/audit.test.js +448 -448
  70. package/test/benchmark.test.js +35 -35
  71. package/test/boundary-v0625.test.js +82 -82
  72. package/test/client.test.js +368 -368
  73. package/test/clustering.test.js +100 -100
  74. package/test/commands.test.js +69 -69
  75. package/test/config.test.js +50 -50
  76. package/test/conflict-freeze.test.js +290 -290
  77. package/test/directory.test.js +134 -134
  78. package/test/dream.test.js +903 -901
  79. package/test/entities.test.js +522 -522
  80. package/test/epistemic.test.js +298 -298
  81. package/test/fnew-0112.test.js +311 -311
  82. package/test/fnew-03.test.js +422 -422
  83. package/test/graph-api.test.js +175 -175
  84. package/test/helpers/dream-mock.js +82 -82
  85. package/test/hot-memory.test.js +174 -174
  86. package/test/inject.test.js +103 -103
  87. package/test/llm-audit.test.js +279 -279
  88. package/test/local-embedder.test.js +227 -227
  89. package/test/mirror-dirty.test.js +424 -424
  90. package/test/mirror-edit-digest.test.js +187 -187
  91. package/test/mirror-generation.test.js +499 -499
  92. package/test/mirror.test.js +249 -249
  93. package/test/normalize-decisions.test.js +120 -120
  94. package/test/peer-blockers.test.js +190 -190
  95. package/test/policy-epoch.test.js +259 -259
  96. package/test/provenance.test.js +103 -103
  97. package/test/quality-filter.test.js +118 -118
  98. package/test/reasoning-effort.test.js +199 -199
  99. package/test/recall-evals.test.js +235 -235
  100. package/test/recall-layer.test.js +315 -315
  101. package/test/receipt-chain.test.js +451 -451
  102. package/test/reflection.test.js +226 -226
  103. package/test/reranker.test.js +240 -240
  104. package/test/search-fusion.test.js +90 -90
  105. package/test/semantic.test.js +124 -124
  106. package/test/service-search.test.js +199 -199
  107. package/test/service.test.js +435 -435
  108. package/test/settings.test.js +118 -118
  109. package/test/sleep.test.js +365 -365
  110. package/test/store.test.js +436 -436
  111. package/test/stress.test.js +209 -209
  112. package/test/summarize.test.js +191 -191
  113. package/test/tag-boost.test.js +125 -125
  114. package/test/tag.test.js +312 -312
  115. package/test/tools.test.js +285 -285
  116. package/test/vector-index.test.js +221 -221
  117. package/test/wiki-link.test.js +332 -332
@@ -1,255 +1,255 @@
1
- // scripts/stress-dsh.js
2
- // 压测:沿着三条轴线检验 dsh-mneme 的 autoDream 与存储在长会话、冲突、
3
- // 并发压力下的表现。LLM 全部用确定性的 mock 决策,离线可跑、无需 API Key。
4
- //
5
- // 轴线 1 · 长会话检索:Recall@k(规范记忆能否被召回)与陈旧残留率
6
- // 轴线 2 · 冲突裁决:可重放仲裁集 —— 仲裁正确率、确定性、审计/回放
7
- // 轴线 3 · 多 Agent 并发:丢更新、重复合并、事务/崩溃恢复
8
- //
9
- // 运行:node scripts/stress-dsh.js
10
- import { mkdtempSync } from "node:fs";
11
- import { tmpdir } from "node:os";
12
- import { join } from "node:path";
13
- import { createStore } from "../src/store.js";
14
- import { createService } from "../src/service.js";
15
- import {
16
- createDreamScheduler,
17
- hashSnapshot,
18
- parseReceipt
19
- } from "../src/dream.js";
20
- import { applyDecisions } from "../src/dream/decisions.js";
21
- import {
22
- sessionDecisions,
23
- arbitrationDecisions,
24
- mockCtx
25
- } from "../test/helpers/dream-mock.js";
26
-
27
- const pass = (ok) => (ok ? "✅" : "❌");
28
-
29
- // ---------------------------------------------------------------- 轴线 1
30
-
31
- async function axis1LongSessionRetrieval() {
32
- console.log("【轴线 1】长会话检索:Recall@k 与陈旧残留率");
33
- const topics = 20;
34
- const rounds = 8;
35
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a1-"));
36
- const store = createStore(join(dir, "memory.db"));
37
- const service = createService({ store, mirror: null, config: {} });
38
- const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
39
- const ctx = mockCtx({ onConsolidation: sessionDecisions });
40
-
41
- // 每个主题一条规范记忆(ground truth,importance 5)
42
- const gt = [];
43
- for (let t = 1; t <= topics; t++) {
44
- const title = `主题${String(t).padStart(2, "0")}`;
45
- const { memory } = service.saveWithDedupe({ type: "project", title, content: `${title} 的规范内容`, importance: 5 });
46
- gt.push({ title, id: memory.id });
47
- }
48
- // 长会话:每轮追加同主题旧变体(importance 3)并触发一次 autoDream
49
- for (let round = 1; round <= rounds; round++) {
50
- for (let t = 1; t <= topics; t++) {
51
- service.saveWithDedupe({
52
- type: "project",
53
- title: `主题${String(t).padStart(2, "0")}·变体${round}`,
54
- content: `主题${t} 第${round}轮旧变体`,
55
- importance: 3
56
- });
57
- }
58
- await dream.runDream(ctx, service, {});
59
- }
60
-
61
- let hits5 = 0;
62
- let hits10 = 0;
63
- for (const { title, id } of gt) {
64
- const k5 = service.search(title, { limit: 5 });
65
- const k10 = service.search(title, { limit: 10 });
66
- if (k5.some((m) => m.id === id)) hits5++;
67
- if (k10.some((m) => m.id === id)) hits10++;
68
- }
69
- const recall5 = hits5 / topics;
70
- const recall10 = hits10 / topics;
71
-
72
- // 陈旧残留率 = 仍活跃的旧变体 / 全部旧变体(dream 应全部清掉 → 0)
73
- const all = store.all();
74
- const variants = all.filter((m) => m.type === "project" && m.title.includes("变体"));
75
- const staleResidual = variants.filter((m) => !m.archived).length / variants.length;
76
- const runs = store.listDreamRuns().length;
77
-
78
- console.log(` 主题 ${topics} 个 × 变体 ${rounds} 轮 = ${topics * rounds} 条旧记忆,autoDream 触发 ${runs} 次`);
79
- console.log(` ${pass(recall5 >= 0.95)} Recall@5 = ${(recall5 * 100).toFixed(1)}%(规范记忆 top5 召回)`);
80
- console.log(` ${pass(recall10 >= 0.95)} Recall@10 = ${(recall10 * 100).toFixed(1)}%`);
81
- console.log(` ${pass(staleResidual === 0)} 陈旧残留率 = ${(staleResidual * 100).toFixed(1)}%(理想 0%)`);
82
- store.close();
83
- return { recall5, recall10, staleResidual, runs };
84
- }
85
-
86
- // ---------------------------------------------------------------- 轴线 2
87
-
88
- async function axis2ConflictArbitration() {
89
- console.log("【轴线 2】冲突裁决:可重放仲裁集");
90
- const sets = [
91
- { key: "项目截止日期", winner: { type: "decision", title: "项目截止日期", content: "8月20日交付", importance: 5 }, loser: { type: "decision", title: "项目截止日期(旧)", content: "8月15日交付", importance: 3 } },
92
- { key: "语言偏好", winner: { type: "preference", title: "语言偏好", content: "使用简体中文", importance: 5 }, loser: { type: "preference", title: "语言偏好(旧)", content: "使用繁体中文", importance: 2 } },
93
- { key: "存储选型", winner: { type: "decision", title: "存储选型", content: "node:sqlite(零依赖)", importance: 5 }, loser: { type: "decision", title: "存储选型(旧)", content: "better-sqlite3(需编译)", importance: 3 } },
94
- { key: "部署环境", winner: { type: "project", title: "部署环境", content: "生产环境 Node 24 + Windows Server", importance: 4 }, loser: { type: "project", title: "部署环境(旧)", content: "生产环境 Node 20 + Linux", importance: 2 } }
95
- ];
96
-
97
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a2-"));
98
- const store = createStore(join(dir, "memory.db"));
99
- const service = createService({ store, mirror: null, config: {} });
100
- const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
101
- const ctx = mockCtx({ onConsolidation: arbitrationDecisions });
102
-
103
- // 仲裁集入库(先败者后胜者,模拟旧信息先存、新信息后到)
104
- for (const set of sets) {
105
- service.saveWithDedupe({ ...set.loser });
106
- service.saveWithDedupe({ ...set.winner });
107
- }
108
- const before = hashSnapshot(service.all().filter((m) => !m.archived && m.type !== "summary"));
109
-
110
- // 跑一次裁决 → 审计 + receipt
111
- const run1 = await dream.runDream(ctx, service, {});
112
- console.log(` 裁决运行:${pass(run1.ok)}(applied=${run1.applied},receipt=${run1.receipt.slice(0, 40)}…)`);
113
-
114
- // 正确性:胜者保留 + 败者归档 + 来源链注释
115
- let arbOk = 0;
116
- for (const set of sets) {
117
- const winner = service.list({ type: set.winner.type }).find((m) => m.title === set.winner.title);
118
- const loser = store.all().find((m) => m.title === set.loser.title);
119
- if (winner && loser && loser.archived && winner.content.includes("已否决旧信息")) arbOk++;
120
- }
121
- const arbRate = arbOk / sets.length;
122
- console.log(` ${pass(arbRate === 1)} 仲裁正确率 = ${(arbRate * 100).toFixed(0)}%(胜者保留 + 败者归档 + 来源链注释)`);
123
-
124
- // 确定性:同一输入快照 → 同一决策。重跑前先把败者"复活"为原始状态。
125
- const audit = store.getDreamRun(run1.runId);
126
- const receipt = parseReceipt(audit.receipt);
127
- console.log(` ${pass(!!receipt && receipt.status === "ok")} receipt 可解析,snapshot=${receipt.snapshotHash},输入 ${receipt.inputCount} 条`);
128
- console.log(` ${pass(audit.outcome && Object.keys(audit.outcome.byId).length === sets.length * 2)} 审计 outcome 覆盖全部 ${sets.length * 2} 个仲裁对象`);
129
-
130
- // 可重放:审计中的决策清单在同一 store 上重放 → 幂等(无副作用)
131
- const winnerBefore = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
132
- const replayed = applyDecisions(audit.decisions, service);
133
- const winnerAfter = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
134
- const idempotent = replayed.applied === 0 && winnerBefore === winnerAfter;
135
- console.log(` ${pass(idempotent)} 决策清单重放幂等(repeat 无副作用,来源链不重复追加)`);
136
- console.log(` ${pass(before.length === 64)} 快照哈希稳定(${before.length} hex 位)`);
137
-
138
- const runs = store.listDreamRuns().length;
139
- store.close();
140
- return { arbRate, runs, idempotent };
141
- }
142
-
143
- // ---------------------------------------------------------------- 轴线 3
144
-
145
- function bump(content) {
146
- const m = content.match(/count=(\d+)/);
147
- return `count=${m ? Number(m[1]) + 1 : 1}`;
148
- }
149
-
150
- async function axis3Concurrency() {
151
- console.log("【轴线 3】多 Agent 并发:丢更新 / 重复合并 / 事务恢复");
152
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a3-"));
153
- const path = join(dir, "memory.db");
154
-
155
- // --- 重复合并:20 个 agent 并发保存同标题 → 最终只 1 条活跃
156
- const sA = createStore(path);
157
- const svA = createService({ store: sA, mirror: null, config: {} });
158
- const agents = 20;
159
- const writes = [];
160
- for (let i = 0; i < agents; i++) {
161
- writes.push(Promise.resolve().then(() => svA.saveWithDedupe({ type: "preference", title: "并发任务", content: `agent-${i}` })));
162
- }
163
- await Promise.all(writes);
164
- const dupes = svA.list({ type: "preference", limit: 100 }).filter((m) => m.title === "并发任务");
165
- const noDupes = dupes.length === 1;
166
- console.log(` ${pass(noDupes)} 重复合并:${agents} 个 agent 同标题并发保存 → 活跃 ${dupes.length} 条(期望 1)`);
167
-
168
- // --- 丢更新:CAS 原子递增(硬断言:陈旧版本必须被拒,增量不得丢失)
169
- const sB = createStore(path);
170
- const svB = createService({ store: sB, mirror: null, config: {} });
171
- svA.saveWithDedupe({ type: "history", title: "计数器", content: "count=0", importance: 3 });
172
- const counterId = svA.list({ type: "history" })[0].id;
173
- svA.update(counterId, { content: "count=0" });
174
- const baseline = svA.getById(counterId); // updated_at=T, count=0
175
- // Agent A 持最新版本 → CAS 成功(count=1)
176
- const aOk = svA.compareAndUpdate(counterId, baseline.updated_at, { content: bump(baseline.content) });
177
- // Agent B 仍持过期版本 T → CAS 必须被拒;若被接受即丢更新
178
- const bStale = svB.compareAndUpdate(counterId, baseline.updated_at, { content: bump("count=0") });
179
- const casRejected = aOk !== undefined && bStale === undefined;
180
- // B 重读最新值重试 → 两个 +1 都落地
181
- if (bStale === undefined) {
182
- const cur = svB.getById(counterId);
183
- svB.compareAndUpdate(counterId, cur.updated_at, { content: bump(cur.content) });
184
- }
185
- const casResult = svB.getById(counterId).content;
186
- const noLostUpdate = casRejected && casResult === "count=2";
187
- console.log(` ${pass(noLostUpdate)} CAS 并发递增:陈旧版本被拒=${casRejected},重读重试后 → ${casResult}(期望 count=2,硬断言)`);
188
- // 串行化修复(无 CAS 时的人工约定):写前重读最新值
189
- svA.update(counterId, { content: "count=0" });
190
- svA.update(counterId, { content: bump(svA.getById(counterId).content) });
191
- svB.update(counterId, { content: bump(svB.getById(counterId).content) });
192
- const fixedResult = svB.getById(counterId).content;
193
- const fixed = fixedResult === "count=2";
194
- console.log(` ${pass(fixed)} 串行重读修复:写前重读最新 → ${fixedResult}(期望 count=2)`);
195
-
196
- // --- 多步原子性:事务中途抛错 → 全部回滚(硬断言,无半成品)
197
- let txThrew = false;
198
- try {
199
- svB.transaction(() => {
200
- svB.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
201
- svB.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
202
- throw new Error("boom");
203
- });
204
- } catch { txThrew = true; }
205
- const allNow = svB.all();
206
- const atomic = txThrew
207
- && !allNow.some((m) => m.title === "原子A")
208
- && !allNow.some((m) => m.title === "原子B");
209
- console.log(` ${pass(atomic)} 多步原子性:事务中途抛错 → 原子A/原子B 全部回滚(期望均不存在,硬断言)`);
210
-
211
- // --- 事务/崩溃恢复:已提交写入在异常后 + reopen 后完整保留
212
- const svC = createService({ store: sB, mirror: null, config: {} }); // 复用同一文件连接
213
- svC.saveWithDedupe({ type: "project", title: "已提交A", content: "x" });
214
- svC.saveWithDedupe({ type: "project", title: "已提交B", content: "y" });
215
- let threw = false;
216
- try {
217
- svC.update("nonexistent-id", { content: "boom" }); // store.update 对未知 id 抛错
218
- } catch {
219
- threw = true;
220
- }
221
- sA.close();
222
- sB.close();
223
- const sR = createStore(path); // 重新打开(模拟进程重启)
224
- const recovered = sR.all();
225
- const recoveryOk = threw
226
- && recovered.some((m) => m.title === "已提交A")
227
- && recovered.some((m) => m.title === "已提交B")
228
- && recovered.some((m) => m.title === "计数器");
229
- console.log(` ${pass(recoveryOk)} 事务恢复:中途异常后已提交写入不丢,reopen 后完整可读`);
230
- console.log(` ${pass(recovered.filter((m) => m.title === "已提交A").length === 1)} 无半成品残留(已提交A 仅 1 条)`);
231
-
232
- sR.close();
233
- return { noDupes, noLostUpdate, atomic, fixed, recoveryOk };
234
- }
235
-
236
- // ---------------------------------------------------------------- 汇总
237
-
238
- console.log("══════ dsh-mneme 压测:三条轴线 ══════");
239
- console.log("");
240
- const a1 = await axis1LongSessionRetrieval();
241
- console.log("");
242
- const a2 = await axis2ConflictArbitration();
243
- console.log("");
244
- const a3 = await axis3Concurrency();
245
- console.log("");
246
- console.log("══════ 压测汇总 ══════");
247
- console.log(` 轴线1 长会话检索:Recall@5=${(a1.recall5 * 100).toFixed(1)}% Recall@10=${(a1.recall10 * 100).toFixed(1)}% 陈旧残留=${(a1.staleResidual * 100).toFixed(1)}% (${a1.runs} 次 autoDream 全部入审计)`);
248
- console.log(` 轴线2 冲突裁决:仲裁正确率=${(a2.arbRate * 100).toFixed(0)}% 重放幂等=${a2.idempotent ? "是" : "否"}`);
249
- console.log(` 轴线3 多 Agent 并发:去重=${a3.noDupes ? "✅" : "❌"} CAS无丢更新=${a3.noLostUpdate ? "✅" : "❌"} 多步原子=${a3.atomic ? "✅" : "❌"} 串行修复=${a3.fixed ? "✅" : "❌"} 崩溃恢复=${a3.recoveryOk ? "✅" : "❌"}`);
250
- // 丢更新与多步原子性都是硬断言:任一失败 → 非零退出,绝不把风险标成通过
251
- const allOk = a1.recall5 >= 0.95 && a1.staleResidual === 0 && a2.arbRate === 1 && a2.idempotent
252
- && a3.noDupes && a3.noLostUpdate && a3.atomic && a3.fixed && a3.recoveryOk;
253
- console.log(` 结论:${allOk ? "全部通过 ✅" : "存在失败项 ❌"}`);
254
- console.log("══════ 压测结束 ══════");
255
- process.exit(allOk ? 0 : 1);
1
+ // scripts/stress-dsh.js
2
+ // 压测:沿着三条轴线检验 dsh-mneme 的 autoDream 与存储在长会话、冲突、
3
+ // 并发压力下的表现。LLM 全部用确定性的 mock 决策,离线可跑、无需 API Key。
4
+ //
5
+ // 轴线 1 · 长会话检索:Recall@k(规范记忆能否被召回)与陈旧残留率
6
+ // 轴线 2 · 冲突裁决:可重放仲裁集 —— 仲裁正确率、确定性、审计/回放
7
+ // 轴线 3 · 多 Agent 并发:丢更新、重复合并、事务/崩溃恢复
8
+ //
9
+ // 运行:node scripts/stress-dsh.js
10
+ import { mkdtempSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { createStore } from "../src/store.js";
14
+ import { createService } from "../src/service.js";
15
+ import {
16
+ createDreamScheduler,
17
+ hashSnapshot,
18
+ parseReceipt
19
+ } from "../src/dream.js";
20
+ import { applyDecisions } from "../src/dream/decisions.js";
21
+ import {
22
+ sessionDecisions,
23
+ arbitrationDecisions,
24
+ mockCtx
25
+ } from "../test/helpers/dream-mock.js";
26
+
27
+ const pass = (ok) => (ok ? "✅" : "❌");
28
+
29
+ // ---------------------------------------------------------------- 轴线 1
30
+
31
+ async function axis1LongSessionRetrieval() {
32
+ console.log("【轴线 1】长会话检索:Recall@k 与陈旧残留率");
33
+ const topics = 20;
34
+ const rounds = 8;
35
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a1-"));
36
+ const store = createStore(join(dir, "memory.db"));
37
+ const service = createService({ store, mirror: null, config: {} });
38
+ const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
39
+ const ctx = mockCtx({ onConsolidation: sessionDecisions });
40
+
41
+ // 每个主题一条规范记忆(ground truth,importance 5)
42
+ const gt = [];
43
+ for (let t = 1; t <= topics; t++) {
44
+ const title = `主题${String(t).padStart(2, "0")}`;
45
+ const { memory } = service.saveWithDedupe({ type: "project", title, content: `${title} 的规范内容`, importance: 5 });
46
+ gt.push({ title, id: memory.id });
47
+ }
48
+ // 长会话:每轮追加同主题旧变体(importance 3)并触发一次 autoDream
49
+ for (let round = 1; round <= rounds; round++) {
50
+ for (let t = 1; t <= topics; t++) {
51
+ service.saveWithDedupe({
52
+ type: "project",
53
+ title: `主题${String(t).padStart(2, "0")}·变体${round}`,
54
+ content: `主题${t} 第${round}轮旧变体`,
55
+ importance: 3
56
+ });
57
+ }
58
+ await dream.runDream(ctx, service, {});
59
+ }
60
+
61
+ let hits5 = 0;
62
+ let hits10 = 0;
63
+ for (const { title, id } of gt) {
64
+ const k5 = service.search(title, { limit: 5 });
65
+ const k10 = service.search(title, { limit: 10 });
66
+ if (k5.some((m) => m.id === id)) hits5++;
67
+ if (k10.some((m) => m.id === id)) hits10++;
68
+ }
69
+ const recall5 = hits5 / topics;
70
+ const recall10 = hits10 / topics;
71
+
72
+ // 陈旧残留率 = 仍活跃的旧变体 / 全部旧变体(dream 应全部清掉 → 0)
73
+ const all = store.all();
74
+ const variants = all.filter((m) => m.type === "project" && m.title.includes("变体"));
75
+ const staleResidual = variants.filter((m) => !m.archived).length / variants.length;
76
+ const runs = store.listDreamRuns().length;
77
+
78
+ console.log(` 主题 ${topics} 个 × 变体 ${rounds} 轮 = ${topics * rounds} 条旧记忆,autoDream 触发 ${runs} 次`);
79
+ console.log(` ${pass(recall5 >= 0.95)} Recall@5 = ${(recall5 * 100).toFixed(1)}%(规范记忆 top5 召回)`);
80
+ console.log(` ${pass(recall10 >= 0.95)} Recall@10 = ${(recall10 * 100).toFixed(1)}%`);
81
+ console.log(` ${pass(staleResidual === 0)} 陈旧残留率 = ${(staleResidual * 100).toFixed(1)}%(理想 0%)`);
82
+ store.close();
83
+ return { recall5, recall10, staleResidual, runs };
84
+ }
85
+
86
+ // ---------------------------------------------------------------- 轴线 2
87
+
88
+ async function axis2ConflictArbitration() {
89
+ console.log("【轴线 2】冲突裁决:可重放仲裁集");
90
+ const sets = [
91
+ { key: "项目截止日期", winner: { type: "decision", title: "项目截止日期", content: "8月20日交付", importance: 5 }, loser: { type: "decision", title: "项目截止日期(旧)", content: "8月15日交付", importance: 3 } },
92
+ { key: "语言偏好", winner: { type: "preference", title: "语言偏好", content: "使用简体中文", importance: 5 }, loser: { type: "preference", title: "语言偏好(旧)", content: "使用繁体中文", importance: 2 } },
93
+ { key: "存储选型", winner: { type: "decision", title: "存储选型", content: "node:sqlite(零依赖)", importance: 5 }, loser: { type: "decision", title: "存储选型(旧)", content: "better-sqlite3(需编译)", importance: 3 } },
94
+ { key: "部署环境", winner: { type: "project", title: "部署环境", content: "生产环境 Node 24 + Windows Server", importance: 4 }, loser: { type: "project", title: "部署环境(旧)", content: "生产环境 Node 20 + Linux", importance: 2 } }
95
+ ];
96
+
97
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a2-"));
98
+ const store = createStore(join(dir, "memory.db"));
99
+ const service = createService({ store, mirror: null, config: {} });
100
+ const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
101
+ const ctx = mockCtx({ onConsolidation: arbitrationDecisions });
102
+
103
+ // 仲裁集入库(先败者后胜者,模拟旧信息先存、新信息后到)
104
+ for (const set of sets) {
105
+ service.saveWithDedupe({ ...set.loser });
106
+ service.saveWithDedupe({ ...set.winner });
107
+ }
108
+ const before = hashSnapshot(service.all().filter((m) => !m.archived && m.type !== "summary"));
109
+
110
+ // 跑一次裁决 → 审计 + receipt
111
+ const run1 = await dream.runDream(ctx, service, {});
112
+ console.log(` 裁决运行:${pass(run1.ok)}(applied=${run1.applied},receipt=${run1.receipt.slice(0, 40)}…)`);
113
+
114
+ // 正确性:胜者保留 + 败者归档 + 来源链注释
115
+ let arbOk = 0;
116
+ for (const set of sets) {
117
+ const winner = service.list({ type: set.winner.type }).find((m) => m.title === set.winner.title);
118
+ const loser = store.all().find((m) => m.title === set.loser.title);
119
+ if (winner && loser && loser.archived && winner.content.includes("已否决旧信息")) arbOk++;
120
+ }
121
+ const arbRate = arbOk / sets.length;
122
+ console.log(` ${pass(arbRate === 1)} 仲裁正确率 = ${(arbRate * 100).toFixed(0)}%(胜者保留 + 败者归档 + 来源链注释)`);
123
+
124
+ // 确定性:同一输入快照 → 同一决策。重跑前先把败者"复活"为原始状态。
125
+ const audit = store.getDreamRun(run1.runId);
126
+ const receipt = parseReceipt(audit.receipt);
127
+ console.log(` ${pass(!!receipt && receipt.status === "ok")} receipt 可解析,snapshot=${receipt.snapshotHash},输入 ${receipt.inputCount} 条`);
128
+ console.log(` ${pass(audit.outcome && Object.keys(audit.outcome.byId).length === sets.length * 2)} 审计 outcome 覆盖全部 ${sets.length * 2} 个仲裁对象`);
129
+
130
+ // 可重放:审计中的决策清单在同一 store 上重放 → 幂等(无副作用)
131
+ const winnerBefore = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
132
+ const replayed = applyDecisions(audit.decisions, service);
133
+ const winnerAfter = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
134
+ const idempotent = replayed.applied === 0 && winnerBefore === winnerAfter;
135
+ console.log(` ${pass(idempotent)} 决策清单重放幂等(repeat 无副作用,来源链不重复追加)`);
136
+ console.log(` ${pass(before.length === 64)} 快照哈希稳定(${before.length} hex 位)`);
137
+
138
+ const runs = store.listDreamRuns().length;
139
+ store.close();
140
+ return { arbRate, runs, idempotent };
141
+ }
142
+
143
+ // ---------------------------------------------------------------- 轴线 3
144
+
145
+ function bump(content) {
146
+ const m = content.match(/count=(\d+)/);
147
+ return `count=${m ? Number(m[1]) + 1 : 1}`;
148
+ }
149
+
150
+ async function axis3Concurrency() {
151
+ console.log("【轴线 3】多 Agent 并发:丢更新 / 重复合并 / 事务恢复");
152
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a3-"));
153
+ const path = join(dir, "memory.db");
154
+
155
+ // --- 重复合并:20 个 agent 并发保存同标题 → 最终只 1 条活跃
156
+ const sA = createStore(path);
157
+ const svA = createService({ store: sA, mirror: null, config: {} });
158
+ const agents = 20;
159
+ const writes = [];
160
+ for (let i = 0; i < agents; i++) {
161
+ writes.push(Promise.resolve().then(() => svA.saveWithDedupe({ type: "preference", title: "并发任务", content: `agent-${i}` })));
162
+ }
163
+ await Promise.all(writes);
164
+ const dupes = svA.list({ type: "preference", limit: 100 }).filter((m) => m.title === "并发任务");
165
+ const noDupes = dupes.length === 1;
166
+ console.log(` ${pass(noDupes)} 重复合并:${agents} 个 agent 同标题并发保存 → 活跃 ${dupes.length} 条(期望 1)`);
167
+
168
+ // --- 丢更新:CAS 原子递增(硬断言:陈旧版本必须被拒,增量不得丢失)
169
+ const sB = createStore(path);
170
+ const svB = createService({ store: sB, mirror: null, config: {} });
171
+ svA.saveWithDedupe({ type: "history", title: "计数器", content: "count=0", importance: 3 });
172
+ const counterId = svA.list({ type: "history" })[0].id;
173
+ svA.update(counterId, { content: "count=0" });
174
+ const baseline = svA.getById(counterId); // updated_at=T, count=0
175
+ // Agent A 持最新版本 → CAS 成功(count=1)
176
+ const aOk = svA.compareAndUpdate(counterId, baseline.updated_at, { content: bump(baseline.content) });
177
+ // Agent B 仍持过期版本 T → CAS 必须被拒;若被接受即丢更新
178
+ const bStale = svB.compareAndUpdate(counterId, baseline.updated_at, { content: bump("count=0") });
179
+ const casRejected = aOk !== undefined && bStale === undefined;
180
+ // B 重读最新值重试 → 两个 +1 都落地
181
+ if (bStale === undefined) {
182
+ const cur = svB.getById(counterId);
183
+ svB.compareAndUpdate(counterId, cur.updated_at, { content: bump(cur.content) });
184
+ }
185
+ const casResult = svB.getById(counterId).content;
186
+ const noLostUpdate = casRejected && casResult === "count=2";
187
+ console.log(` ${pass(noLostUpdate)} CAS 并发递增:陈旧版本被拒=${casRejected},重读重试后 → ${casResult}(期望 count=2,硬断言)`);
188
+ // 串行化修复(无 CAS 时的人工约定):写前重读最新值
189
+ svA.update(counterId, { content: "count=0" });
190
+ svA.update(counterId, { content: bump(svA.getById(counterId).content) });
191
+ svB.update(counterId, { content: bump(svB.getById(counterId).content) });
192
+ const fixedResult = svB.getById(counterId).content;
193
+ const fixed = fixedResult === "count=2";
194
+ console.log(` ${pass(fixed)} 串行重读修复:写前重读最新 → ${fixedResult}(期望 count=2)`);
195
+
196
+ // --- 多步原子性:事务中途抛错 → 全部回滚(硬断言,无半成品)
197
+ let txThrew = false;
198
+ try {
199
+ svB.transaction(() => {
200
+ svB.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
201
+ svB.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
202
+ throw new Error("boom");
203
+ });
204
+ } catch { txThrew = true; }
205
+ const allNow = svB.all();
206
+ const atomic = txThrew
207
+ && !allNow.some((m) => m.title === "原子A")
208
+ && !allNow.some((m) => m.title === "原子B");
209
+ console.log(` ${pass(atomic)} 多步原子性:事务中途抛错 → 原子A/原子B 全部回滚(期望均不存在,硬断言)`);
210
+
211
+ // --- 事务/崩溃恢复:已提交写入在异常后 + reopen 后完整保留
212
+ const svC = createService({ store: sB, mirror: null, config: {} }); // 复用同一文件连接
213
+ svC.saveWithDedupe({ type: "project", title: "已提交A", content: "x" });
214
+ svC.saveWithDedupe({ type: "project", title: "已提交B", content: "y" });
215
+ let threw = false;
216
+ try {
217
+ svC.update("nonexistent-id", { content: "boom" }); // store.update 对未知 id 抛错
218
+ } catch {
219
+ threw = true;
220
+ }
221
+ sA.close();
222
+ sB.close();
223
+ const sR = createStore(path); // 重新打开(模拟进程重启)
224
+ const recovered = sR.all();
225
+ const recoveryOk = threw
226
+ && recovered.some((m) => m.title === "已提交A")
227
+ && recovered.some((m) => m.title === "已提交B")
228
+ && recovered.some((m) => m.title === "计数器");
229
+ console.log(` ${pass(recoveryOk)} 事务恢复:中途异常后已提交写入不丢,reopen 后完整可读`);
230
+ console.log(` ${pass(recovered.filter((m) => m.title === "已提交A").length === 1)} 无半成品残留(已提交A 仅 1 条)`);
231
+
232
+ sR.close();
233
+ return { noDupes, noLostUpdate, atomic, fixed, recoveryOk };
234
+ }
235
+
236
+ // ---------------------------------------------------------------- 汇总
237
+
238
+ console.log("══════ dsh-mneme 压测:三条轴线 ══════");
239
+ console.log("");
240
+ const a1 = await axis1LongSessionRetrieval();
241
+ console.log("");
242
+ const a2 = await axis2ConflictArbitration();
243
+ console.log("");
244
+ const a3 = await axis3Concurrency();
245
+ console.log("");
246
+ console.log("══════ 压测汇总 ══════");
247
+ console.log(` 轴线1 长会话检索:Recall@5=${(a1.recall5 * 100).toFixed(1)}% Recall@10=${(a1.recall10 * 100).toFixed(1)}% 陈旧残留=${(a1.staleResidual * 100).toFixed(1)}% (${a1.runs} 次 autoDream 全部入审计)`);
248
+ console.log(` 轴线2 冲突裁决:仲裁正确率=${(a2.arbRate * 100).toFixed(0)}% 重放幂等=${a2.idempotent ? "是" : "否"}`);
249
+ console.log(` 轴线3 多 Agent 并发:去重=${a3.noDupes ? "✅" : "❌"} CAS无丢更新=${a3.noLostUpdate ? "✅" : "❌"} 多步原子=${a3.atomic ? "✅" : "❌"} 串行修复=${a3.fixed ? "✅" : "❌"} 崩溃恢复=${a3.recoveryOk ? "✅" : "❌"}`);
250
+ // 丢更新与多步原子性都是硬断言:任一失败 → 非零退出,绝不把风险标成通过
251
+ const allOk = a1.recall5 >= 0.95 && a1.staleResidual === 0 && a2.arbRate === 1 && a2.idempotent
252
+ && a3.noDupes && a3.noLostUpdate && a3.atomic && a3.fixed && a3.recoveryOk;
253
+ console.log(` 结论:${allOk ? "全部通过 ✅" : "存在失败项 ❌"}`);
254
+ console.log("══════ 压测结束 ══════");
255
+ process.exit(allOk ? 0 : 1);
@@ -1,52 +1,52 @@
1
- // Sync the src/ tree into lib/ — the distributable consumed by DSH (package
2
- // main is lib/index.js). lib/client.js (the Web panel bundle) is authored
3
- // independently under lib/ and is left untouched: the sync only copies
4
- // src -> lib, it never prunes lib-only files.
5
- //
6
- // Usage: npm run sync (also run automatically by `npm pack`/`npm publish`
7
- // via the prepack hook, so a published tarball always ships a fresh lib/).
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";
14
- import { join, relative } from "node:path";
15
- import { fileURLToPath } from "node:url";
16
-
17
- const root = join(fileURLToPath(new URL("..", import.meta.url)));
18
- const srcDir = join(root, "src");
19
- const libDir = join(root, "lib");
20
-
21
- /** Recursively collect all files under a directory (sorted for stable output). */
22
- function walk(dir) {
23
- const out = [];
24
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
25
- const full = join(dir, entry.name);
26
- if (entry.isDirectory()) out.push(...walk(full));
27
- else if (entry.isFile()) out.push(full);
28
- }
29
- return out;
30
- }
31
-
32
- let copied = 0;
33
- mkdirSync(libDir, { recursive: true });
34
-
35
- for (const file of walk(srcDir)) {
36
- const rel = relative(srcDir, file);
37
- const dest = join(libDir, rel);
38
- mkdirSync(join(dest, ".."), { recursive: true });
39
- copyFileSync(file, dest);
40
- copied++;
41
- console.log(`synced ${rel}`);
42
- }
43
-
44
- // Report lib-only files (authored separately, e.g. client.js) so drift is
45
- // visible but never clobbered.
46
- for (const file of walk(libDir)) {
47
- const rel = relative(libDir, file);
48
- if (!existsSync(join(srcDir, rel))) console.log(`kept ${rel} (lib-only, not pruned)`);
49
- }
50
-
51
- console.log(`\nSynced ${copied} file(s) from src/ to lib/.`);
52
- if (!copied) process.exitCode = 1;
1
+ // Sync the src/ tree into lib/ — the distributable consumed by DSH (package
2
+ // main is lib/index.js). lib/client.js (the Web panel bundle) is authored
3
+ // independently under lib/ and is left untouched: the sync only copies
4
+ // src -> lib, it never prunes lib-only files.
5
+ //
6
+ // Usage: npm run sync (also run automatically by `npm pack`/`npm publish`
7
+ // via the prepack hook, so a published tarball always ships a fresh lib/).
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";
14
+ import { join, relative } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ const root = join(fileURLToPath(new URL("..", import.meta.url)));
18
+ const srcDir = join(root, "src");
19
+ const libDir = join(root, "lib");
20
+
21
+ /** Recursively collect all files under a directory (sorted for stable output). */
22
+ function walk(dir) {
23
+ const out = [];
24
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
25
+ const full = join(dir, entry.name);
26
+ if (entry.isDirectory()) out.push(...walk(full));
27
+ else if (entry.isFile()) out.push(full);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ let copied = 0;
33
+ mkdirSync(libDir, { recursive: true });
34
+
35
+ for (const file of walk(srcDir)) {
36
+ const rel = relative(srcDir, file);
37
+ const dest = join(libDir, rel);
38
+ mkdirSync(join(dest, ".."), { recursive: true });
39
+ copyFileSync(file, dest);
40
+ copied++;
41
+ console.log(`synced ${rel}`);
42
+ }
43
+
44
+ // Report lib-only files (authored separately, e.g. client.js) so drift is
45
+ // visible but never clobbered.
46
+ for (const file of walk(libDir)) {
47
+ const rel = relative(libDir, file);
48
+ if (!existsSync(join(srcDir, rel))) console.log(`kept ${rel} (lib-only, not pruned)`);
49
+ }
50
+
51
+ console.log(`\nSynced ${copied} file(s) from src/ to lib/.`);
52
+ if (!copied) process.exitCode = 1;