@modusensus/dsh-mneme 0.2.9 → 0.2.10

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.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
7
7
  [![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
8
- [![tests](https://img.shields.io/badge/tests-355%20passed-success)](https://github.com/modusensus/dsh-mneme)
8
+ [![tests](https://img.shields.io/badge/tests-363%20passed-success)](https://github.com/modusensus/dsh-mneme)
9
9
 
10
10
  > 给 DeepSeek Harness 的跨会话记忆插件:让 Agent 记住你、记住项目、自动整理记忆。**Mneme**(Μνήμη)——希腊记忆女神 Mnemosyne 之名,掌管记忆与梦境,正如 autoDream 在后台巩固记忆。
11
11
 
@@ -225,7 +225,7 @@ src/
225
225
  lib/
226
226
  ├── client.js # Web 面板(手写 ModuleLoader bundle)
227
227
  └── *.js # src 的同步分发产物
228
- test/ # 355 个 node:test 测试(含审计与三轴线压测不变量)
228
+ test/ # 363 个 node:test 测试(含审计与三轴线压测不变量)
229
229
  scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步
230
230
  ```
231
231
 
@@ -234,7 +234,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
234
234
  ```bash
235
235
  cd dsh-mneme
236
236
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
237
- npm test # 运行 355 个测试
237
+ npm test # 运行 363 个测试
238
238
  npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
239
239
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
240
240
  ```
package/lib/mirror.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
2
3
  import { join } from "node:path";
3
4
 
4
5
  export const TYPE_FILE = {
@@ -21,6 +22,13 @@ function unescape(text) {
21
22
  }
22
23
 
23
24
  function renderMemory(m) {
25
+ // last-rendered digest baseline: sha256(title \x00 content). service.js
26
+ // compares the file hash against this to tell "untouched by a human" (machine
27
+ // write wins) apart from a real human edit, so a not-yet-re-rendered store
28
+ // update is not misread as a concurrent human edit.
29
+ const digest = createHash("sha256")
30
+ .update(`${m.title}\x00${m.content}`)
31
+ .digest("hex");
24
32
  const lines = [];
25
33
  lines.push(`## ${esc(m.title)}`);
26
34
  lines.push("");
@@ -31,6 +39,7 @@ function renderMemory(m) {
31
39
  lines.push(`- **更新时间**: ${m.updated_at}`);
32
40
  if (m.source) lines.push(`- **来源**: ${esc(m.source)}`);
33
41
  lines.push("");
42
+ lines.push(`<!-- mirror-digest: ${digest} -->`);
34
43
  lines.push(m.content);
35
44
  lines.push("");
36
45
  lines.push("---");
@@ -86,7 +95,8 @@ export function createMirror(dir) {
86
95
  let body = text
87
96
  .slice(blockStart, blockEnd)
88
97
  .replace(/^- \*\*ID\*\*: `[^`]+`\n?/, "")
89
- .replace(/^(- \*\*(类型|重要性|标签|更新时间|来源)\*\*:.*\n?)+/, "");
98
+ .replace(/^(- \*\*(类型|重要性|标签|更新时间|来源)\*\*:.*\n?)+/, "")
99
+ .replace(/^<!-- mirror-digest: [a-f0-9]+ -->\n?/m, "");
90
100
  const separators = [...body.matchAll(/^---\s*$/gm)];
91
101
  const lastSep = separators[separators.length - 1];
92
102
  if (lastSep) body = body.slice(0, lastSep.index);
@@ -97,11 +107,13 @@ export function createMirror(dir) {
97
107
  // during a three-way merge of human edits (see service.syncMirror).
98
108
  const block = text.slice(blockStart, blockEnd);
99
109
  const updatedMatch = block.match(/- \*\*更新时间\*\*: ([^\n]+)/);
110
+ const digestMatch = block.match(/<!-- mirror-digest: ([a-f0-9]+) -->/);
100
111
  edits.push({
101
112
  id: anchor[1],
102
113
  title: titleMatch ? unescape(titleMatch[1]).trim() : undefined,
103
114
  content: body,
104
- updated_at: updatedMatch ? updatedMatch[1].trim() : undefined
115
+ updated_at: updatedMatch ? updatedMatch[1].trim() : undefined,
116
+ digest: digestMatch ? digestMatch[1] : undefined
105
117
  });
106
118
 
107
119
  const lineEnd = text.indexOf("\n", blockStart);
package/lib/service.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { TYPE_FILE } from "./mirror.js";
3
3
 
4
4
  const INJECT_TYPES = new Set(["preference", "project", "decision", "summary"]);
@@ -349,8 +349,21 @@ export function createService({ store, mirror, config, onWrite }) {
349
349
  const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
350
350
  || (typeof edit.content === "string" && edit.content !== m.content);
351
351
  if (!humanChanged) { result.push(m); continue; }
352
- // Store changed since the file was last rendered (file records the
353
- // store's updated_at at render time) AND the file was hand-edited.
352
+ // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
353
+ // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
354
+ // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
355
+ // 并发人工编辑导致机器写丢失 + 伪冲突标记。
356
+ const digestMatches = typeof edit.digest === "string"
357
+ && typeof edit.title === "string"
358
+ && typeof edit.content === "string"
359
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
360
+ if (digestMatches) {
361
+ // 无人触碰,机器 wins,走原样
362
+ result.push(m);
363
+ continue;
364
+ }
365
+ // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
366
+ // (保留现有 storeChanged 逻辑)
354
367
  const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
355
368
  if (storeChanged) {
356
369
  const marker = `\n\n> ⚠️ 并发冲突:人工编辑 vs 记忆库并发更新(${m.updated_at})\n> 记忆库版本:${m.content}`;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 6 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.2.9",
4
+ "version": "0.2.10",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
package/src/mirror.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
2
3
  import { join } from "node:path";
3
4
 
4
5
  export const TYPE_FILE = {
@@ -21,6 +22,13 @@ function unescape(text) {
21
22
  }
22
23
 
23
24
  function renderMemory(m) {
25
+ // last-rendered digest baseline: sha256(title \x00 content). service.js
26
+ // compares the file hash against this to tell "untouched by a human" (machine
27
+ // write wins) apart from a real human edit, so a not-yet-re-rendered store
28
+ // update is not misread as a concurrent human edit.
29
+ const digest = createHash("sha256")
30
+ .update(`${m.title}\x00${m.content}`)
31
+ .digest("hex");
24
32
  const lines = [];
25
33
  lines.push(`## ${esc(m.title)}`);
26
34
  lines.push("");
@@ -31,6 +39,7 @@ function renderMemory(m) {
31
39
  lines.push(`- **更新时间**: ${m.updated_at}`);
32
40
  if (m.source) lines.push(`- **来源**: ${esc(m.source)}`);
33
41
  lines.push("");
42
+ lines.push(`<!-- mirror-digest: ${digest} -->`);
34
43
  lines.push(m.content);
35
44
  lines.push("");
36
45
  lines.push("---");
@@ -86,7 +95,8 @@ export function createMirror(dir) {
86
95
  let body = text
87
96
  .slice(blockStart, blockEnd)
88
97
  .replace(/^- \*\*ID\*\*: `[^`]+`\n?/, "")
89
- .replace(/^(- \*\*(类型|重要性|标签|更新时间|来源)\*\*:.*\n?)+/, "");
98
+ .replace(/^(- \*\*(类型|重要性|标签|更新时间|来源)\*\*:.*\n?)+/, "")
99
+ .replace(/^<!-- mirror-digest: [a-f0-9]+ -->\n?/m, "");
90
100
  const separators = [...body.matchAll(/^---\s*$/gm)];
91
101
  const lastSep = separators[separators.length - 1];
92
102
  if (lastSep) body = body.slice(0, lastSep.index);
@@ -97,11 +107,13 @@ export function createMirror(dir) {
97
107
  // during a three-way merge of human edits (see service.syncMirror).
98
108
  const block = text.slice(blockStart, blockEnd);
99
109
  const updatedMatch = block.match(/- \*\*更新时间\*\*: ([^\n]+)/);
110
+ const digestMatch = block.match(/<!-- mirror-digest: ([a-f0-9]+) -->/);
100
111
  edits.push({
101
112
  id: anchor[1],
102
113
  title: titleMatch ? unescape(titleMatch[1]).trim() : undefined,
103
114
  content: body,
104
- updated_at: updatedMatch ? updatedMatch[1].trim() : undefined
115
+ updated_at: updatedMatch ? updatedMatch[1].trim() : undefined,
116
+ digest: digestMatch ? digestMatch[1] : undefined
105
117
  });
106
118
 
107
119
  const lineEnd = text.indexOf("\n", blockStart);
package/src/service.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { TYPE_FILE } from "./mirror.js";
3
3
 
4
4
  const INJECT_TYPES = new Set(["preference", "project", "decision", "summary"]);
@@ -349,8 +349,21 @@ export function createService({ store, mirror, config, onWrite }) {
349
349
  const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
350
350
  || (typeof edit.content === "string" && edit.content !== m.content);
351
351
  if (!humanChanged) { result.push(m); continue; }
352
- // Store changed since the file was last rendered (file records the
353
- // store's updated_at at render time) AND the file was hand-edited.
352
+ // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
353
+ // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
354
+ // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
355
+ // 并发人工编辑导致机器写丢失 + 伪冲突标记。
356
+ const digestMatches = typeof edit.digest === "string"
357
+ && typeof edit.title === "string"
358
+ && typeof edit.content === "string"
359
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
360
+ if (digestMatches) {
361
+ // 无人触碰,机器 wins,走原样
362
+ result.push(m);
363
+ continue;
364
+ }
365
+ // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
366
+ // (保留现有 storeChanged 逻辑)
354
367
  const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
355
368
  if (storeChanged) {
356
369
  const marker = `\n\n> ⚠️ 并发冲突:人工编辑 vs 记忆库并发更新(${m.updated_at})\n> 记忆库版本:${m.content}`;
@@ -0,0 +1,185 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { createStore } from "../src/store.js";
8
+ import { createMirror } from "../src/mirror.js";
9
+ import { createService } from "../src/service.js";
10
+ import { applyDecisions } from "../src/dream.js";
11
+
12
+ const CONFLICT_MARKER = "并发冲突";
13
+
14
+ /**
15
+ * Regression tests for the mirror-digest fix: a machine store write that has
16
+ * not yet been re-rendered to the mirror must NOT be misread as a concurrent
17
+ * human edit (which lost the machine write and planted a fake conflict marker).
18
+ * Each machine-write path runs against a stale mirror file (the pre-transaction
19
+ * render), exactly like the audited reproductions.
20
+ */
21
+ function setup() {
22
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-digest-"));
23
+ const store = createStore(":memory:");
24
+ const mirror = createMirror(dir);
25
+ const service = createService({ store, mirror, config: {} });
26
+ return { dir, store, mirror, service };
27
+ }
28
+
29
+ function mirrorFile(dir, type) {
30
+ return join(dir, { preference: "preferences.md", project: "projects.md", decision: "decisions.md", history: "history.md" }[type]);
31
+ }
32
+
33
+ function digestOf(title, content) {
34
+ return createHash("sha256").update(`${title}\x00${content}`).digest("hex");
35
+ }
36
+
37
+ test("digest 匹配:直接 update 后机器写落地、无伪冲突 marker", () => {
38
+ const { dir, store, service } = setup();
39
+ try {
40
+ const { memory: m } = service.saveWithDedupe({ type: "project", title: "直接更新", content: "v1", importance: 3 });
41
+ service.update(m.id, { content: "v2" });
42
+ // 镜像此时还是 v1 的旧渲染;digest 仍匹配 → 机器 wins
43
+ assert.equal(store.getById(m.id).content, "v2", "机器新值必须落地");
44
+ assert.ok(!store.getById(m.id).content.includes(CONFLICT_MARKER), "不得出现伪冲突 marker");
45
+ const file = readFileSync(mirrorFile(dir, "project"), "utf8");
46
+ assert.match(file, /v2/, "镜像已重渲染为新值");
47
+ assert.ok(!file.includes(CONFLICT_MARKER), "镜像不得包含伪冲突 marker");
48
+ } finally {
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ });
52
+
53
+ test("digest 匹配:事务内 update 后机器写落地、无伪冲突 marker", () => {
54
+ const { dir, store, service } = setup();
55
+ try {
56
+ const { memory: m } = service.saveWithDedupe({ type: "project", title: "事务更新", content: "tx v1", importance: 3 });
57
+ service.transaction(() => {
58
+ service.update(m.id, { content: "tx v2" });
59
+ });
60
+ assert.equal(store.getById(m.id).content, "tx v2", "事务内机器新值必须落地");
61
+ assert.ok(!store.getById(m.id).content.includes(CONFLICT_MARKER), "不得出现伪冲突 marker");
62
+ const file = readFileSync(mirrorFile(dir, "project"), "utf8");
63
+ assert.match(file, /tx v2/, "镜像已重渲染为新值");
64
+ assert.ok(!file.includes(CONFLICT_MARKER), "镜像不得包含伪冲突 marker");
65
+ } finally {
66
+ rmSync(dir, { recursive: true, force: true });
67
+ }
68
+ });
69
+
70
+ test("digest 匹配:saveWithDedupe 同标题 merge 后新值落地、无伪冲突 marker", () => {
71
+ const { dir, store, service } = setup();
72
+ try {
73
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "旧内容", importance: 3 });
74
+ const result = service.saveWithDedupe({ type: "preference", title: "语言", content: "新内容", importance: 5 });
75
+ assert.equal(result.action, "merged");
76
+ assert.equal(store.count(), 1, "同标题合并不新增条目");
77
+ const m = service.getById(result.memory.id);
78
+ assert.equal(m.content, "新内容", "合并后新值必须落地");
79
+ assert.ok(!m.content.includes(CONFLICT_MARKER), "不得出现伪冲突 marker");
80
+ const file = readFileSync(mirrorFile(dir, "preference"), "utf8");
81
+ assert.match(file, /新内容/, "镜像已重渲染为新值");
82
+ assert.ok(!file.includes(CONFLICT_MARKER), "镜像不得包含伪冲突 marker");
83
+ } finally {
84
+ rmSync(dir, { recursive: true, force: true });
85
+ }
86
+ });
87
+
88
+ test("digest 匹配:Dream merge 后 keeper 是新值、无伪冲突、source 归档", () => {
89
+ const { dir, store, service } = setup();
90
+ try {
91
+ const a = service.saveWithDedupe({ type: "project", title: "DreamKeeper", content: "keep old", importance: 3 });
92
+ const b = service.saveWithDedupe({ type: "project", title: "DreamSource", content: "src old", importance: 3 });
93
+ // 真实 applyDecisions 路径:keeper 更新 + source 归档在同一事务里,
94
+ // 提交时 syncMirror 读到的是事务前渲染的旧镜像 → 修复前会误判为人工编辑。
95
+ const { applied, failures } = applyDecisions(
96
+ [{ action: "merge", ids: [a.memory.id, b.memory.id], keepSource: a.memory.id, title: "DreamKeeper", content: "keeper new", importance: 5 }],
97
+ service,
98
+ null,
99
+ null
100
+ );
101
+ assert.equal(applied, 1);
102
+ assert.equal(failures.length, 0);
103
+ const keeper = store.getById(a.memory.id);
104
+ assert.equal(keeper.content, "keeper new", "keeper 必须是合并后的新值");
105
+ assert.equal(keeper.title, "DreamKeeper");
106
+ assert.ok(!keeper.content.includes(CONFLICT_MARKER), "keeper 不得出现伪冲突 marker");
107
+ assert.equal(store.getById(b.memory.id).archived, true, "source 必须归档");
108
+ const file = readFileSync(mirrorFile(dir, "project"), "utf8");
109
+ assert.match(file, /keeper new/, "镜像已重渲染为新值");
110
+ assert.ok(!file.includes(CONFLICT_MARKER), "镜像不得包含伪冲突 marker");
111
+ } finally {
112
+ rmSync(dir, { recursive: true, force: true });
113
+ }
114
+ });
115
+
116
+ test("真实人工编辑控制组:只改文件 → 人工 wins、无 marker(store 未变)", () => {
117
+ const { dir, store, service } = setup();
118
+ try {
119
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容", importance: 3 });
120
+ // 人工改文件内容,但保留 digest 注释行(digest 已不匹配)
121
+ const file = mirrorFile(dir, "preference");
122
+ writeFileSync(file, readFileSync(file, "utf8").replace("机器内容", "人类编辑内容"), "utf8");
123
+ // 下一次无关 store 写触发 syncMirror → 必须合并人工编辑回 store
124
+ service.saveWithDedupe({ type: "project", title: "无关", content: "x", importance: 3 });
125
+ const m = service.list({ type: "preference", includeArchived: true }).find((p) => p.title === "语言");
126
+ assert.equal(m.content, "人类编辑内容", "人工编辑必须合并回 store");
127
+ assert.ok(!m.content.includes(CONFLICT_MARKER), "store 未变时不得出现冲突 marker");
128
+ } finally {
129
+ rmSync(dir, { recursive: true, force: true });
130
+ }
131
+ });
132
+
133
+ test("真实人工编辑控制组:文件与 store 同时变更 → 三方合并保留双方 + marker", () => {
134
+ const { dir, store, service } = setup();
135
+ try {
136
+ const { memory: m } = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容", importance: 3 });
137
+ // 人工改文件(digest 行保留但内容已变)
138
+ const file = mirrorFile(dir, "preference");
139
+ writeFileSync(file, readFileSync(file, "utf8").replace("机器内容", "人类编辑内容"), "utf8");
140
+ // 机器并发改 store → 下一次 sync 必须三方合并,保留双方 + marker
141
+ service.update(m.id, { content: "并发机器版本" });
142
+ const updated = service.getById(m.id);
143
+ assert.ok(updated.content.includes("人类编辑内容"), "人工版本必须保留为头部");
144
+ assert.ok(updated.content.includes("并发机器版本"), "store 并发版本必须保留");
145
+ assert.ok(updated.content.includes(CONFLICT_MARKER), "必须出现真正的冲突 marker");
146
+ } finally {
147
+ rmSync(dir, { recursive: true, force: true });
148
+ }
149
+ });
150
+
151
+ test("老文件无 digest → 保守走三方合并(保留双方 + marker)", () => {
152
+ const { dir, store, service } = setup();
153
+ try {
154
+ const { memory: m } = service.saveWithDedupe({ type: "history", title: "旧", content: "旧内容", importance: 3 });
155
+ // 模拟修复前渲染的老文件:去掉 digest 注释行,但内容仍是旧内容
156
+ const file = mirrorFile(dir, "history");
157
+ const rendered = readFileSync(file, "utf8");
158
+ writeFileSync(file, rendered.replace(/<!--\s*mirror-digest: [a-f0-9]+ -->\n?/g, ""), "utf8");
159
+ // 机器更新 → 无 digest 必须保守视为人工动过 → 三方合并
160
+ service.update(m.id, { content: "新机器内容" });
161
+ const updated = service.getById(m.id);
162
+ assert.ok(updated.content.includes("旧内容"), "老文件内容必须被保留");
163
+ assert.ok(updated.content.includes("新机器内容"), "机器新版本必须被保留");
164
+ assert.ok(updated.content.includes(CONFLICT_MARKER), "必须出现冲突 marker");
165
+ } finally {
166
+ rmSync(dir, { recursive: true, force: true });
167
+ }
168
+ });
169
+
170
+ test("digest 从 body 剥除:读回的 content 不含 digest 注释,digest 字段正确", () => {
171
+ const { dir, mirror, service } = setup();
172
+ try {
173
+ const { memory: m } = service.saveWithDedupe({ type: "decision", title: "剥离", content: "line1\nline2", importance: 3 });
174
+ const edits = mirror.readHumanEdits("decision");
175
+ const edit = edits.find((e) => e.id === m.id);
176
+ assert.ok(edit, "读到该条目");
177
+ assert.equal(edit.title, "剥离");
178
+ assert.equal(edit.content, "line1\nline2", "正文必须不含结构字段");
179
+ assert.ok(!edit.content.includes("mirror-digest"), "content 不得包含 digest 注释");
180
+ assert.ok(!edit.content.includes("<!--"), "content 不得包含任何 HTML 注释");
181
+ assert.equal(edit.digest, digestOf("剥离", "line1\nline2"), "digest 字段暴露给 reconcile 使用");
182
+ } finally {
183
+ rmSync(dir, { recursive: true, force: true });
184
+ }
185
+ });