@modusensus/dsh-mneme 0.9.4 → 0.10.0

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 (126) hide show
  1. package/README.md +57 -10
  2. package/bin/cli.mjs +215 -2
  3. package/docs/CONFIGURATION.md +25 -2
  4. package/docs/DAEMON.md +13 -2
  5. package/docs/DISTILL.md +150 -4
  6. package/docs/SHARE.md +552 -0
  7. package/docs/SLEEP.md +21 -7
  8. package/docs/STORAGE.md +2 -1
  9. package/lib/api-standalone.js +294 -8
  10. package/lib/api.js +217 -3
  11. package/lib/client.js +919 -39
  12. package/lib/config.js +33 -1
  13. package/lib/continuity.js +11 -3
  14. package/lib/document.js +15 -2
  15. package/lib/dream/decisions.js +176 -30
  16. package/lib/dream/sleep.js +530 -94
  17. package/lib/dream.js +174 -21
  18. package/lib/fence.js +24 -0
  19. package/lib/index.js +15 -6
  20. package/lib/inject.js +9 -4
  21. package/lib/lang.js +38 -16
  22. package/lib/memory-source.js +9 -0
  23. package/lib/organize.js +5 -1
  24. package/lib/pipeline-nudge-auto.js +3 -0
  25. package/lib/pipeline-nudge.js +41 -8
  26. package/lib/pipeline-runner.js +15 -0
  27. package/lib/pipeline.js +62 -1
  28. package/lib/pre-inject-gate.js +14 -0
  29. package/lib/profile-extract.js +4 -1
  30. package/lib/provenance-http.js +251 -0
  31. package/lib/serve.js +13 -0
  32. package/lib/service.js +97 -4
  33. package/lib/session-gate.js +91 -0
  34. package/lib/settings.js +13 -1
  35. package/lib/share-http.js +281 -0
  36. package/lib/share-import.js +234 -0
  37. package/lib/share.js +335 -0
  38. package/lib/store.js +797 -28
  39. package/lib/summarize.js +209 -23
  40. package/lib/tools.js +26 -6
  41. package/package.json +4 -2
  42. package/src/api-standalone.js +294 -8
  43. package/src/api.js +217 -3
  44. package/src/config.js +33 -1
  45. package/src/continuity.js +11 -3
  46. package/src/document.js +15 -2
  47. package/src/dream/decisions.js +176 -30
  48. package/src/dream/sleep.js +530 -94
  49. package/src/dream.js +174 -21
  50. package/src/fence.js +24 -0
  51. package/src/index.js +15 -6
  52. package/src/inject.js +9 -4
  53. package/src/lang.js +38 -16
  54. package/src/memory-source.js +9 -0
  55. package/src/organize.js +5 -1
  56. package/src/pipeline-nudge-auto.js +3 -0
  57. package/src/pipeline-nudge.js +41 -8
  58. package/src/pipeline-runner.js +15 -0
  59. package/src/pipeline.js +62 -1
  60. package/src/pre-inject-gate.js +14 -0
  61. package/src/profile-extract.js +4 -1
  62. package/src/provenance-http.js +251 -0
  63. package/src/serve.js +13 -0
  64. package/src/service.js +97 -4
  65. package/src/session-gate.js +91 -0
  66. package/src/settings.js +13 -1
  67. package/src/share-http.js +281 -0
  68. package/src/share-import.js +234 -0
  69. package/src/share.js +335 -0
  70. package/src/store.js +797 -28
  71. package/src/summarize.js +209 -23
  72. package/src/tools.js +26 -6
  73. package/test/api.test.js +523 -6
  74. package/test/audit.test.js +2 -2
  75. package/test/cli-receive.test.js +390 -0
  76. package/test/cli-share.test.js +437 -0
  77. package/test/client-share.test.js +225 -0
  78. package/test/client.test.js +354 -0
  79. package/test/config.test.js +8 -0
  80. package/test/conflict-reviewed.test.js +79 -0
  81. package/test/continuity.test.js +29 -1
  82. package/test/dedupe-candidate-window.test.js +180 -0
  83. package/test/dependency-overrides.test.js +78 -0
  84. package/test/differentiate-feedback.test.js +248 -0
  85. package/test/dream-candidate-hybrid.test.js +2 -2
  86. package/test/dream-decision-evidence.test.js +314 -0
  87. package/test/dream-fence.test.js +207 -0
  88. package/test/dream.test.js +87 -5
  89. package/test/helpers/dream-mock.js +6 -2
  90. package/test/inject-pools.test.js +2 -1
  91. package/test/llm-message-source.test.js +1 -1
  92. package/test/mint-source.test.js +84 -1
  93. package/test/pipeline-nudge-auto.test.js +26 -2
  94. package/test/pipeline-nudge.test.js +87 -0
  95. package/test/pipeline-r1r2.test.js +129 -0
  96. package/test/pipeline-runner.test.js +26 -0
  97. package/test/policy-epoch.test.js +2 -2
  98. package/test/prompt-stance.test.js +128 -0
  99. package/test/provenance-http.test.js +367 -0
  100. package/test/readme-claims.test.js +45 -0
  101. package/test/reasoning-effort.test.js +10 -10
  102. package/test/release-docs.test.js +7 -1
  103. package/test/scope-candidates.test.js +7 -4
  104. package/test/scope-state.test.js +130 -1
  105. package/test/security-doc.test.js +43 -4
  106. package/test/serve.test.js +62 -0
  107. package/test/session-gate.test.js +264 -0
  108. package/test/settings.test.js +4 -0
  109. package/test/share-foreign-rows.test.js +144 -0
  110. package/test/share-http.test.js +144 -0
  111. package/test/share-import.test.js +577 -0
  112. package/test/share-imported-guard.test.js +311 -0
  113. package/test/share-imported-identity.test.js +111 -0
  114. package/test/share-pack.test.js +511 -0
  115. package/test/share-receive-http.test.js +756 -0
  116. package/test/share-routes.test.js +337 -0
  117. package/test/share-store.test.js +133 -0
  118. package/test/share-validate.test.js +101 -0
  119. package/test/sleep-action-set.test.js +16 -11
  120. package/test/sleep-catchup.test.js +315 -0
  121. package/test/sleep-failure-backoff.test.js +156 -0
  122. package/test/sleep.test.js +293 -0
  123. package/test/standalone-api.test.js +574 -5
  124. package/test/store.test.js +220 -0
  125. package/test/summarize-parse-diagnostics.test.js +75 -0
  126. package/test/summarize.test.js +187 -2
@@ -0,0 +1,311 @@
1
+ // 「外来记忆不被改写」的行为锁 + 静态锁。
2
+ // 行为锁盯汇流口:saveWithDedupe 是 appendContent 改写的总入口(蒸馏路径与
3
+ // _mergeInto 显式目标都从这过),堵在这里等于在所有写入侧同时封口。
4
+ // 静态锁盯池子:巩固/降级读的是各自的行池,堵了汇流口不等于堵了它们——
5
+ // 池子里还有 setArchived / demoteToSummary 这些不经 saveWithDedupe 的动作。
6
+ // 静态锁也盯汇流口本身(下方 SERVICE_SITES):池子清单归 B2,service.js 不在它那九处里。
7
+ // 行为锁也盯整理动作面(B3):那里唯一能归档别人行的通道是「dryRun 点名 → apply 执行」,
8
+ // 执行那一半不经汇流口,所以必须在报告那一半就把外来行挡在可点名集之外。
9
+ import test from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { readFileSync } from "node:fs";
15
+ import { dirname, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { createStore } from "../src/store.js";
18
+ import { createService } from "../src/service.js";
19
+ import { createOrganizer } from "../src/organize.js";
20
+ import { IMPORTED_SOURCE, isImportedRow } from "../src/memory-source.js";
21
+
22
+ const here = dirname(fileURLToPath(import.meta.url));
23
+
24
+ test("the predicate is the only definition of foreign-ness", () => {
25
+ assert.equal(IMPORTED_SOURCE, "imported");
26
+ assert.equal(isImportedRow({ source: "imported" }), true);
27
+ assert.equal(isImportedRow({ source: "dream" }), false);
28
+ assert.equal(isImportedRow(null), false);
29
+ assert.equal(isImportedRow({ source: "Imported" }), false); // 精确匹配,不做大小写魔法
30
+ });
31
+
32
+ test("saveWithDedupe never merges into an imported row", () => {
33
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-guard-"));
34
+ const store = createStore(join(dir, "memory.db"));
35
+ try {
36
+ const service = createService({ store, mirror: null, config: {} });
37
+ const foreign = store.save({ type: "decision", title: "选 SQLite", content: "对方的原文", tags: [], source: IMPORTED_SOURCE });
38
+ const before = store.getById(foreign.id);
39
+ const out = service.saveWithDedupe({ type: "decision", title: "选 SQLite", content: "我自己的新结论", tags: [] });
40
+ assert.equal(out.action, "created", "same title+scope must NOT physically merge into a foreign row");
41
+ assert.notEqual(out.memory.id, foreign.id);
42
+ const after = store.getById(foreign.id);
43
+ assert.equal(after.content, before.content);
44
+ assert.equal(after.updated_at, before.updated_at, "a foreign row's updated_at must not move");
45
+ assert.equal((after.content_history ?? []).length, (before.content_history ?? []).length,
46
+ "merging into a foreign row would also push its content_history");
47
+ } finally {
48
+ try { store.close(); } catch { /* closed */ }
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ });
52
+
53
+ // 第二条闸门(显式目标 _mergeInto):调用方点名要并入哪一行,(type, title) 候选集那条
54
+ // 路根本不参与。今天生产里唯一点名它的是蒸馏去重(#127,src/summarize.js 找候选时按
55
+ // source 过滤,点不到 imported 行),工具面 / 面板 / standalone 三条口各自重建字段表,
56
+ // organize 的载荷被 normalizeCandidate 白名单剥掉(#231 的锁)——这道闸门现在是惰性的,
57
+ // 它守的是「任何能报出行 id 的调用方」这条契约,不是给某条现有路径打补丁。
58
+ // 标题故意与外来行不同(语义近重复本来就不同题,同形状见 test/scope-storage.test.js 的
59
+ // 显式目标用例):摘掉候选集那道闸门时本用例仍绿,摘掉显式目标这道才红——两条行为锁
60
+ // 各咬一处,红了就能直接定位是哪道闸门被改坏。
61
+ test("saveWithDedupe never merges into an imported row named by _mergeInto", () => {
62
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-merge-into-"));
63
+ const store = createStore(join(dir, "memory.db"));
64
+ try {
65
+ const service = createService({ store, mirror: null, config: {} });
66
+ const foreign = store.save({ type: "decision", title: "选 SQLite", content: "对方的原文", tags: [], source: IMPORTED_SOURCE });
67
+ const before = store.getById(foreign.id);
68
+ const out = service.saveWithDedupe({
69
+ type: "decision",
70
+ title: "SQLite 的并发写入够用",
71
+ content: "我自己的新结论",
72
+ tags: [],
73
+ _mergeInto: foreign.id
74
+ });
75
+ assert.equal(out.action, "created", "an explicit _mergeInto at a foreign row must degrade to a miss");
76
+ assert.notEqual(out.memory.id, foreign.id);
77
+ assert.equal(out.memory.content, "我自己的新结论", "the new row carries only our own content");
78
+ const after = store.getById(foreign.id);
79
+ assert.equal(after.content, before.content, "a foreign row's content must not be appended to");
80
+ assert.equal(after.updated_at, before.updated_at, "a foreign row's updated_at must not move");
81
+ assert.equal((after.content_history ?? []).length, (before.content_history ?? []).length,
82
+ "merging into a foreign row would also push its content_history");
83
+ } finally {
84
+ try { store.close(); } catch { /* closed */ }
85
+ rmSync(dir, { recursive: true, force: true });
86
+ }
87
+ });
88
+
89
+ // 字面量锁:钉死汇流口两处闸门的形状。有效性不用它证明——上面两条行为锁各咬一道闸门
90
+ // (摘掉候选集那条只有第一条转红,摘掉显式目标那条只有第二条转红,两处都实测过)。
91
+ // 本锁补的是行为测试看不见的那一类回归:闸门被改名、被挪进别的文件、或两条并成一条
92
+ // ——代码照旧跑对,但「这里有两道、缺一不可」这个事实消失了,而契约正靠这两道分头
93
+ // 守同题合并与点名并入。它锁字面量,所以谓词变量改名 / 参数名换掉也算红:那是
94
+ // 「实现漂了,锁跟着走」,不是误报(改的人必须知道自己动的是哪两处)。
95
+ const SERVICE_SITES = [
96
+ ["src/service.js", ".filter((m) => !isImportedRow(m))"],
97
+ ["src/service.js", "!isImportedRow(explicitCandidate)"],
98
+ ];
99
+
100
+ test("the saveWithDedupe choke point keeps both guard sites", () => {
101
+ for (const [file, needle] of SERVICE_SITES) {
102
+ assert.ok(readFileSync(resolve(here, "..", file), "utf8").includes(needle),
103
+ `${file} must keep the imported-row guard at the choke point: ${needle}`);
104
+ }
105
+ });
106
+
107
+ // 池子清单(B2)。巩固、sleep 降级、模式扫描、关系补全、整理并入读的是各自的**行池**,
108
+ // 不经过汇流口,而且池子里就有 setArchived / demoteToSummary 这种不经 saveWithDedupe
109
+ // 的直接改行动作——堵了汇流口不等于堵了它们,所以每处都要单独挂守卫、也要单独锁住。
110
+ // 为什么用字面量清单而不是给九个池子各写一条行为用例:多数池子挂在 LLM 路由后面
111
+ // (dream/sleep 主流程要全套打桩才跑得起来),而行为用例永远测不到「将来新增的第十处」——
112
+ // 清单是死的,加池子必须在这里加一行,漏挂当场红。代价是它也会为行为等价的改写转红
113
+ // (谓词挪进 helper、变量改名),那是「实现漂了,锁跟着走」,不是误报(AGENTS.md 自查 8)。
114
+ // service.js 不在清单里:汇流口那两处由上面的 SERVICE_SITES 锁,同一文件不该有两份清单。
115
+ //
116
+ // 清单里两条 needle 的形状不同,是刻意的:八处池子挂的是谓词调用 `!isImportedRow(m)`,
117
+ // 模式扫描那一处(sleep.js 的 phasePatterns)挂的是查询旗标 `excludeImported: true`——
118
+ // 它的外来行判据下推进了 store.list 的 WHERE,留在 LIMIT 之后过滤的话,被丢掉的外来行
119
+ // 照样吃掉窗口名额(池子会饿到 sleepPatternMinMemories 以下而静默跳过,见 #230/#471 的
120
+ // 同一取舍)。旗标背后是同一个 IMPORTED_SOURCE(store.js 从 memory-source.js import,
121
+ // 不自己写字面量),所以守卫没有变松:谓词只有一份定义,只是这一处的**位置**换了。
122
+ // 位置对不对这件事字面量锁证明不了,由文件末尾那条窗口用例(行为锁)证明。
123
+ const POOL_SITES = [
124
+ ["src/dream.js", "const memories = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && m.type !== \"summary\" && m.type !== \"document\"));"],
125
+ ["src/dream.js", "const inputs = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && !m.forgotten && m.type !== \"summary\" && m.type !== \"document\"));"],
126
+ ["src/dream.js", "let memories = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && m.type !== \"summary\" && m.type !== \"document\"));"],
127
+ ["src/dream.js", "const summaryAll = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && m.type !== \"summary\" && m.type !== \"document\"));"],
128
+ ["src/dream/sleep.js", "const memories = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && !m.forgotten && m.type !== \"summary\" && m.type !== \"document\"));"],
129
+ ["src/dream/sleep.js", "for (const m of withoutPaused(service, service.all().filter((m) => !isImportedRow(m)))) {"],
130
+ ["src/dream/sleep.js", "excludeImported: true"],
131
+ ["src/dream/sleep.js", "const memories = withoutPaused(service, service.all().filter((m) => !isImportedRow(m) && !m.archived && !m.forgotten));"],
132
+ ["src/organize.js", "store.list({ type: candidate.type, limit: null }).filter((m) => !isImportedRow(m) && !m.archived && scopeMatches(m, candidate))"]
133
+ ];
134
+
135
+ test("every row pool that can rewrite or archive is guarded", () => {
136
+ for (const [file, needle] of POOL_SITES) {
137
+ assert.ok(readFileSync(resolve(here, "..", file), "utf8").includes(needle),
138
+ `${file} must guard its row pool against imported rows (predicate or query flag): ${needle.slice(0, 60)}`);
139
+ }
140
+ });
141
+
142
+ // 第二条比清单粗但更耐改写:不锁整句形状,只锁「dream.js 里出现 service.all() 的那行
143
+ // 要么带谓词、要么按 source 取行」。它对换行、缩进、条件顺序都不敏感,只对「新增一处
144
+ // 没挂谓词的池子」和「谓词改名」敏感;它给 dream.js 兜底是因为这里的池子清一色是
145
+ // service.all(),而 sleep.js(多行 service.list)与 organize.js(store.list)取行 API
146
+ // 不同,要扩就先按各自的 API 写判据,别把这条当万能。
147
+ test("dream.js has no unguarded service.all() pool left", () => {
148
+ const text = readFileSync(resolve(here, "../src/dream.js"), "utf8");
149
+ const offenders = text.split("\n")
150
+ .map((line, i) => [i + 1, line])
151
+ .filter(([ , line]) => line.includes("service.all()") && !line.includes("isImportedRow") && !line.includes("m.source === \"dream\""));
152
+ assert.deepEqual(offenders, [], `unguarded pools at ${offenders.map(([n]) => n).join(", ")}`);
153
+ });
154
+
155
+ // 本用例是 POOL_SITES 里 organize 那一行的行为对偶,放在清单之后是刻意的:清单锁得住
156
+ // 「那句过滤还在」,锁不住「它真的改变了比对结果」,而 organize 恰好是九处里唯一后面接着
157
+ // 一个真改归档面动作的——apply 只认 dryRun 报告点名过的 id(src/organize.js 硬规则 3b),
158
+ // 执行那一步走 store.setArchived,全程不经 saveWithDedupe,汇流口那两道闸门到这里都管不到。
159
+ // 报告点错一次名,就等于我们在替别人决定他那条记忆还活不活跃。
160
+ // 两条候选各管一个方向,缺一不可:
161
+ // ① 「同题的本方行照旧命中」——外来行 importance 更高(5 vs 3),摘掉谓词时它在
162
+ // store.list 的默认排序(`importance DESC, updated_at DESC, id`)里排在前面,
163
+ // 会被精确层的 rows.find 截胡;这条要防的是「守卫过宽,把自己人的命中也挡了」。
164
+ // 它**不**能单独证明守卫不惰性:那条命中依赖排序,而排序是实现细节。
165
+ // ② 「外来行单独占一个标题」——比对池里除了它没有别的同题行,于是「摘掉谓词 → 这条
166
+ // 被点名」与排序无关:pool 里只有一条候选行,find 到的必然是它。非惰性这件事现在
167
+ // 由这条独立证明,① 的 importance 差只是让两条用例顺带覆盖「抢位」那一种形态。
168
+ test("organize never names an imported row as an archive target", async () => {
169
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-organize-"));
170
+ const store = createStore(join(dir, "memory.db"));
171
+ try {
172
+ const service = createService({ store, mirror: null, config: {} });
173
+ // 向量档给「无信号」:命中只能来自精确层,红了能立刻知道是哪一层出的问题。
174
+ const { organize } = createOrganizer({
175
+ store,
176
+ embedQuery: async () => null,
177
+ saveWithDedupe: service.saveWithDedupe,
178
+ transaction: service.transaction,
179
+ finalize: () => {}
180
+ });
181
+ const foreign = store.save({ type: "preference", title: "写库先用 SQLite", content: "对方库里的原文", importance: 5, tags: [], source: IMPORTED_SOURCE });
182
+ const mine = store.save({ type: "preference", title: "写库先用 SQLite", content: "我自己的记录", importance: 3, tags: [] });
183
+ const lonely = store.save({ type: "preference", title: "只有外来行有这个标题", content: "对面写的原文", importance: 1, tags: [], source: IMPORTED_SOURCE });
184
+
185
+ const report = await organize({
186
+ mode: "dryRun",
187
+ candidates: [
188
+ { type: "preference", title: "写库先用 SQLite", content: "同一标题的新说法" },
189
+ { type: "preference", title: "只有外来行有这个标题", content: "同一标题的新说法" }
190
+ ]
191
+ });
192
+ const named = report.items.map((item) => item.match?.id).filter(Boolean);
193
+ assert.ok(!named.includes(foreign.id),
194
+ "a foreign row must never reach the report: the report is apply's only archive licence");
195
+ // 守卫的口径是「不许替别人决定」,不是「比对池干脆谁都看不见」——本方同题行必须照旧命中。
196
+ assert.equal(report.items[0].verdict, "exact", "our own same-title row must still be reported");
197
+ assert.equal(report.items[0].match.id, mine.id);
198
+ // ②:这一格里比对池除了那条外来行没有别人,守卫摘掉后它必然被点名——不借排序的力。
199
+ assert.equal(report.items[1].verdict, "new", "a lone imported row must not become a match either");
200
+ assert.equal(report.items[1].match, null);
201
+ assert.ok(!named.includes(lonely.id), "the lone foreign row leaked into the report");
202
+
203
+ // 报告没点过名 → apply 连「调用方自己报出外来行 id」这条越权路也拒掉:整条链上
204
+ // 外来行既进不了比对池,也拿不到归档许可。
205
+ const outcome = await organize({
206
+ mode: "apply",
207
+ run_id: report.run_id,
208
+ decisions: [{ action: "archive", id: foreign.id }, { action: "archive", id: lonely.id }]
209
+ });
210
+ assert.equal(outcome.archived, 0);
211
+ assert.match(outcome.skipped[0].error, /not flagged as a match/);
212
+ assert.ok(!store.getById(foreign.id).archived, "the foreign row's archive bit stays where the owner left it");
213
+ assert.ok(!store.getById(lonely.id).archived, "same for the lone one");
214
+ } finally {
215
+ try { store.close(); } catch { /* closed */ }
216
+ rmSync(dir, { recursive: true, force: true });
217
+ }
218
+ });
219
+
220
+ // 车道 C8(spec §15 一):registerDocument 的 evidence 吸收是九池静态锁看不见的那条旁路——
221
+ // 它不走任何 service.all() 行池,证据 id 直接来自调用方,循环里的 store.setArchived 是
222
+ // 机器发起的批量归档,正是决策 2 要禁的动作。两条断言方向相反、缺一不可:
223
+ // ① 外来引用行不归档——摘掉谓词时这一条转红(RED 的本体);
224
+ // ② 本方引用行照旧归档——防「把整条吸收关掉」冒充守卫通过;
225
+ // ③ skipped 计数可见——静默跳过等于报告里看不出这条文档替别人撤过哪几行。
226
+ test("registerDocument's evidence absorb never archives a foreign row", async () => {
227
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-doc-absorb-"));
228
+ const store = createStore(join(dir, "memory.db"));
229
+ try {
230
+ const service = createService({ store, mirror: null, config: { documentMemoryEnabled: true } });
231
+ const docFile = join(dir, "x.md");
232
+ writeFileSync(docFile, "# Doc\n\n正文正文", "utf8");
233
+ const foreign = store.save({ type: "pattern", title: "别人的模式", content: "正文正文正文", tags: [], source: IMPORTED_SOURCE });
234
+ const own = store.save({ type: "pattern", title: "我的模式", content: "正文正文正文", tags: [] });
235
+ const out = await service.registerDocument({
236
+ path: docFile, title: "文档", summary: "摘要句子。", evidence: [foreign.id, own.id]
237
+ });
238
+ assert.equal(out.action, "created");
239
+ assert.equal(store.getById(foreign.id).archived, false, "a machine-driven absorb must not archive someone else's memory");
240
+ assert.equal(store.getById(own.id).archived, true, "own evidence still absorbs");
241
+ assert.equal(out.evidence_kept, 2, "the citation itself stays honest: the foreign id remains cited by the document");
242
+ assert.equal(out.evidence_skipped, 1, "the skipped count must be visible, not silently dropped");
243
+ assert.equal(out.evidence_archived, 1, "exactly the one own row got absorbed");
244
+ } finally {
245
+ try { store.close(); } catch { /* closed */ }
246
+ rmSync(dir, { recursive: true, force: true });
247
+ }
248
+ });
249
+
250
+ // 模式扫描池的行为锁(本文件唯一一条「窗口」用例,与 POOL_SITES 那条是两件事)。
251
+ // 清单锁得住「谓词挂在这一处」,锁不住「谓词站在 LIMIT 的哪一侧」:旧写法
252
+ // `service.list({ limit: 200 }).filter((m) => !isImportedRow(m) …)` 先截断后丢弃,
253
+ // 被丢掉的外来行照样吃掉窗口名额。外来行比本方行新时,整扇窗口能被它们占满——
254
+ // 池子饿到 sleepPatternMinMemories 以下,模式扫描**静默跳过**(不报错、不留痕),
255
+ // 而这恰好是导入过包的那些库的常态。下推到查询层之后名额才真正留给会被扫的行
256
+ // (同一取舍:#230 的 document 轴、#471 的暂停轴、src/service.js:2247 的镜像闸)。
257
+ // 摘掉 store 的 excludeImported 那一条 clause,或把过滤退回 .slice 之后,本条当场红。
258
+ test("the pattern-scan pool drops foreign rows before the LIMIT, not after", () => {
259
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-window-"));
260
+ const store = createStore(join(dir, "memory.db"));
261
+ try {
262
+ const service = createService({ store, mirror: null, config: {} });
263
+ // 落行顺序就是时间顺序:store.js 的 nowIso() 单调递增(同毫秒也 +1ms),所以后落的
264
+ // 那批必然更新。list 的默认序是 importance DESC → updated_at DESC,两边同权 3,
265
+ // 于是外来行整体顶在窗口最前面。这就是「窗口被占满」那台机器,不用人为调时钟。
266
+ const mine = [
267
+ store.save({ type: "decision", title: "我们自己的决定甲", content: "本方正文甲", tags: [] }),
268
+ store.save({ type: "decision", title: "我们自己的决定乙", content: "本方正文乙", tags: [] }),
269
+ store.save({ type: "preference", title: "我们自己的偏好", content: "本方正文丙", tags: [] })
270
+ ];
271
+ const ownIds = new Set(mine.map((m) => m.id));
272
+ const FOREIGN = 8;
273
+ const foreignIds = new Set();
274
+ for (let i = 0; i < FOREIGN; i++) {
275
+ const f = store.save({
276
+ type: "decision", title: `对面的决定 ${i}`, content: "对面的原文", tags: [],
277
+ source: IMPORTED_SOURCE, share_pack_id: "pack-window", share_external_id: `window-ext-${i}`
278
+ });
279
+ foreignIds.add(f.id);
280
+ }
281
+
282
+ // 修复前的形状先在这里饿死:窗口 3 格全被外来行占掉,过滤后是空池。
283
+ // 这条断言不是在测新代码,是把「静默跳过」那一幕钉成看得见的失败——没有它,
284
+ // 下面那条绿只证明「旗标能用」,不证明「不加旗标真的会饿」。
285
+ const starved = service.list({ limit: 3, includeForgotten: false })
286
+ .filter((m) => !isImportedRow(m) && !m.archived && m.type !== "summary" && m.type !== "pattern");
287
+ assert.equal(starved.length, 0, "precondition: after-LIMIT filtering leaves the pattern pool empty");
288
+
289
+ // 查询层口径(sleep phasePatterns 现在用的形状):名额一个都不给外来行。
290
+ const pool = service.list({ limit: 3, includeForgotten: false, excludeImported: true });
291
+ assert.equal(pool.length, 3, "the window is full of our own rows: no foreign row consumed a slot");
292
+ assert.ok(pool.every((m) => ownIds.has(m.id)), "every slot in the window is ours");
293
+ // 本方行 source 恒为 NULL(store.save 不写该格),所以 clause 必须是
294
+ // `(source IS NULL OR source <> ?)`:漏掉 IS NULL 那一支,SQLite 里 NULL <> 'imported'
295
+ // 求值为 NULL → 本方行整批消失,池子中门全空。上面两条断言一起把这一支钉住。
296
+ assert.ok(pool.every((m) => m.source === null || m.source === undefined),
297
+ "the kept rows are the NULL-source ones: the clause must not rely on source <> alone");
298
+
299
+ // 旗标是 opt-in:不给的时候默认口径逐字节不变(其余调用方照旧看得见外来行)。
300
+ const unflagged = service.list({ limit: 3, includeForgotten: false });
301
+ assert.ok(unflagged.some((m) => foreignIds.has(m.id)),
302
+ "without the flag foreign rows stay visible — the option must not leak into the default path");
303
+ assert.equal(service.list({ limit: null }).length, mine.length + FOREIGN,
304
+ "default full scan still returns every row, imported included");
305
+ assert.equal(service.list({ limit: null, excludeImported: true }).length, mine.length,
306
+ "with the flag only our own rows remain");
307
+ } finally {
308
+ try { store.close(); } catch { /* closed */ }
309
+ rmSync(dir, { recursive: true, force: true });
310
+ }
311
+ });
@@ -0,0 +1,111 @@
1
+ // spec §15 二(车道 C9):镜像里手改一条外来记忆是**允许**的——那是接收方自己磁盘上的字,
2
+ // 把刚打进去的内容静默改回去是比「改写」更糟的失效(他会以为编辑生效了,而文件下一次同步又被抹平)。
3
+ // 这里锁的不是「改不了」,而是改完之后身份还在:source 仍是 imported、两个 scope 仍是 NULL、
4
+ // share 两列原样。车道 B 的九个行池与汇流口全按 source 认外来行——若「编辑一次正文」能顺手改
5
+ // 归属,「改一下正文再摘掉守卫」就成了绕开整套契约的合法手段。
6
+ //
7
+ // 为什么这条锁今天就该是绿的、绿了仍然有价值:store.update 的 SET 白名单**含** source 与两个
8
+ // scope(src/store.js:1353——patch 显式携带该键才改写,否则保留既有),share_pack_id /
9
+ // share_external_id 则压根不在 UPDATE 语句里(身份两件套只由 save 铸造)。所以本锁防的回归
10
+ // 不是列的意外,而是有人给「人改回填」的 patch 加「按内容重归属/清 scope」这类便利——
11
+ // spec 裁定二点名不许做的事。两条用例各咬一条回填路线,缺一不可:
12
+ // ① mergeHumanEdits——启动回灌与 /import 走的显式合并;
13
+ // ② reconcileHumanEdits——每次 syncMirror 都跑的三方合并,专收两次业务写之间的手改。
14
+ // 只锁 ① 的话,② 随时可以在无人察觉时长出口子(它今天是照改外来行正文的,这是裁定)。
15
+ import test from "node:test";
16
+ import assert from "node:assert/strict";
17
+ import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { createStore } from "../src/store.js";
21
+ import { createService } from "../src/service.js";
22
+ import { IMPORTED_SOURCE } from "../src/memory-source.js";
23
+ import { parseHumanEdits, renderMirrorText, createMirror } from "../src/mirror.js";
24
+
25
+ const FOREIGN_PACK_ID = "f0f0f0f0f0f0f0f0";
26
+ const FOREIGN_EXTERNAL_ID = "deadbeef00000099";
27
+
28
+ function seedForeignRow(store) {
29
+ return store.save({
30
+ type: "preference",
31
+ title: "别人的偏好",
32
+ content: "对方的原文初稿",
33
+ tags: [],
34
+ source: IMPORTED_SOURCE,
35
+ share_pack_id: FOREIGN_PACK_ID,
36
+ share_external_id: FOREIGN_EXTERNAL_ID
37
+ });
38
+ }
39
+
40
+ // 断言全部走「身份四件套 + 归档位」这一组:正文改了是**预期**(裁定一),这些没动才是本锁。
41
+ function assertIdentityIntact(after, where) {
42
+ assert.equal(after.source, IMPORTED_SOURCE, `editing the body must not demote the row out of the foreign set (${where})`);
43
+ assert.equal(after.agent_scope, undefined, `a hand edit must not mint a scope onto a foreign row (${where})`);
44
+ assert.equal(after.workspace_scope, undefined, `same for the workspace axis (${where})`);
45
+ assert.equal(after.share_pack_id, FOREIGN_PACK_ID, `the pack addressing key is minted by save and must survive (${where})`);
46
+ assert.equal(after.share_external_id, FOREIGN_EXTERNAL_ID, `the idempotency key likewise (${where})`);
47
+ assert.equal(after.archived, false, `a hand edit is not an archive action (${where})`);
48
+ }
49
+
50
+ test("mergeHumanEdits rewrites a foreign row's body but never its guard identity", () => {
51
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-identity-"));
52
+ const store = createStore(join(dir, "memory.db"));
53
+ try {
54
+ const service = createService({ store, mirror: null, config: {} });
55
+ const foreign = seedForeignRow(store);
56
+
57
+ // 条目块由真渲染器(renderMirrorText → renderMemory)生成,测试只手改正文那一段。
58
+ // 手写中文字段标签会跟 STR.mirrorLabel 漂移,而漂移的失败形态是 parseHumanEdits
59
+ // 解析出 0 条——测试会空转着绿(假通过)。下面两条前置断言就是防这个的。
60
+ const rendered = renderMirrorText("preference", [store.getById(foreign.id)], "zh");
61
+ const markdown = rendered.replace("对方的原文初稿", "我改过的正文");
62
+ assert.notEqual(markdown, rendered, "the human edit must actually land in the mirror text");
63
+
64
+ const edits = parseHumanEdits(markdown);
65
+ assert.equal(edits.length, 1, "the edited block must parse as exactly one entry, or this test is vacuous");
66
+ assert.equal(edits[0].id, foreign.id);
67
+ assert.equal(edits[0].content, "我改过的正文", "parse must see the edited body, not the machine metadata run");
68
+
69
+ assert.equal(service.mergeHumanEdits("preference", edits), 1, "the edit must be applied, not silently discarded");
70
+
71
+ const after = store.getById(foreign.id);
72
+ assert.equal(after.content, "我改过的正文", "the hand edit lands — silently reverting it is the worse failure (spec §15 二)");
73
+ assert.equal(after.title, "别人的偏好", "title untouched by this edit stays put");
74
+ assertIdentityIntact(after, "mergeHumanEdits");
75
+ } finally {
76
+ try { store.close(); } catch { /* closed */ }
77
+ rmSync(dir, { recursive: true, force: true });
78
+ }
79
+ });
80
+
81
+ test("reconcileHumanEdits (the syncMirror re-ingest route) rewrites the body and keeps the identity too", () => {
82
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-imported-identity-sync-"));
83
+ const store = createStore(join(dir, "memory.db"));
84
+ try {
85
+ const mirror = createMirror(join(dir, "mirror"));
86
+ const service = createService({ store, mirror, config: {} });
87
+ const foreign = seedForeignRow(store);
88
+
89
+ // 业务写触发 syncMirror:外来行第一次落到 preferences.md(渲染器写出的 digest 是
90
+ // 渲染时正文的哈希——人工改完正文它就失配,这正是 reconcile 认「有人动过」的判据)。
91
+ service.saveWithDedupe({ type: "decision", title: "我自己的决定", content: "本机写入", tags: [] });
92
+ const file = mirror.filePath("preference");
93
+ assert.ok(existsSync(file), "the mirror must have rendered the foreign row to disk");
94
+
95
+ const text = readFileSync(file, "utf8");
96
+ const edited = text.replace("对方的原文初稿", "同步间隙里改的正文");
97
+ assert.notEqual(edited, text, "the human edit must land in the file on disk");
98
+ writeFileSync(file, edited, "utf8");
99
+
100
+ // 第二次业务写:syncMirror 先跑 reconcileHumanEdits,把这份「两次写之间」的手改
101
+ // 三方合并回库——本用例锁的就是这条路线改完之后身份还在。
102
+ service.saveWithDedupe({ type: "decision", title: "另一个本机决定", content: "又是本机写入", tags: [] });
103
+
104
+ const after = store.getById(foreign.id);
105
+ assert.equal(after.content, "同步间隙里改的正文", "the edit survives the re-ingest route; it is not machine-washed");
106
+ assertIdentityIntact(after, "reconcileHumanEdits");
107
+ } finally {
108
+ try { store.close(); } catch { /* closed */ }
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
111
+ });