dsh-memu-memory 1.3.15 → 1.4.1

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 (73) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +49 -1
  3. package/README.md +4 -1
  4. package/README.zh.md +4 -1
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/host-adaptation.md +52 -36
  7. package/docs/host-versions.md +120 -0
  8. package/docs/memory-semantics.md +4 -2
  9. package/docs/pending-work.md +51 -0
  10. package/docs/troubleshooting.md +41 -2
  11. package/lib/auto-link/candidates.js +4 -1
  12. package/lib/auto-link/decide.js +1 -1
  13. package/lib/auto-link/normalize.js +2 -2
  14. package/lib/auto-link/terminology.js +31 -1
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +53 -6
  17. package/lib/consolidation-snapshot.js +7 -1
  18. package/lib/consolidation-worker.js +11 -3
  19. package/lib/curator.js +17 -5
  20. package/lib/cycle.js +75 -4
  21. package/lib/diagnostics.js +10 -0
  22. package/lib/entity-repair.js +285 -0
  23. package/lib/environment-check.js +72 -3
  24. package/lib/global-graph.js +11 -2
  25. package/lib/graph.js +32 -8
  26. package/lib/host-surface.js +30 -0
  27. package/lib/index.js +120 -3
  28. package/lib/inject.js +142 -8
  29. package/lib/memory.js +72 -0
  30. package/lib/private-links.js +12 -0
  31. package/lib/private.js +49 -13
  32. package/lib/prompts/private-consolidation.coding.md +3 -1
  33. package/lib/prompts/private-consolidation.md +2 -0
  34. package/lib/prompts/private-consolidation.mixed.md +2 -0
  35. package/lib/prompts/private-consolidation.rp.md +2 -0
  36. package/lib/prompts/system-guide.coding.md +8 -2
  37. package/lib/prompts/system-guide.md +6 -0
  38. package/lib/prompts/system-guide.mixed.md +11 -0
  39. package/lib/prompts/system-guide.rp.md +6 -0
  40. package/lib/rpc.js +48 -10
  41. package/lib/state.js +5 -1
  42. package/lib/turn-log.js +34 -11
  43. package/lib/worker-pool.js +11 -7
  44. package/package.json +16 -1
  45. package/scripts/chain-matrix.mjs +4 -0
  46. package/scripts/check-doc-drift.mjs +194 -0
  47. package/scripts/entity-dedupe.mjs +110 -0
  48. package/tests/auto-link-candidates.test.mjs +22 -9
  49. package/tests/auto-link-decide.test.mjs +59 -59
  50. package/tests/auto-link-migration.test.mjs +4 -4
  51. package/tests/client-render.test.mjs +112 -1
  52. package/tests/consolidation-fork.test.mjs +20 -1
  53. package/tests/curator-probe.test.mjs +19 -1
  54. package/tests/cycle.test.mjs +2 -2
  55. package/tests/diagnostics.test.mjs +21 -0
  56. package/tests/doc-drift.test.mjs +122 -2
  57. package/tests/entity-merge.test.mjs +17 -0
  58. package/tests/environment-check.test.mjs +28 -0
  59. package/tests/global-graph.test.mjs +16 -0
  60. package/tests/global-lifecycle.test.mjs +24 -4
  61. package/tests/graph-cascade.test.mjs +111 -0
  62. package/tests/hybrid-recall.test.mjs +1 -1
  63. package/tests/inject-guide.test.mjs +108 -1
  64. package/tests/managed-memory.test.mjs +7 -7
  65. package/tests/private-links.test.mjs +12 -0
  66. package/tests/prompts.test.mjs +30 -0
  67. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  68. package/tests/salience-domain.test.mjs +34 -0
  69. package/tests/settings-plumbing.test.mjs +2 -0
  70. package/tests/stale-maintenance.test.mjs +131 -0
  71. package/tests/tools.test.mjs +1 -1
  72. package/tests/turn-log.test.mjs +13 -0
  73. package/tests/webui-auth.test.mjs +58 -0
@@ -200,9 +200,129 @@ test('suite without any *.test.mjs fails loader/stub completeness', () => {
200
200
  assert.match(detailText(result), /tests\/: no \*\.test\.mjs file/)
201
201
  })
202
202
 
203
- test('runChecks returns the three gates in order', () => {
203
+ test('runChecks returns the four gates in order', () => {
204
204
  const root = makeFixture()
205
- assert.deepEqual(gate.runChecks(root).map((entry) => entry.label), ['rpc-method-count', 'test-tracking', 'loader-stubs'])
205
+ assert.deepEqual(gate.runChecks(root).map((entry) => entry.label),
206
+ ['rpc-method-count', 'test-tracking', 'loader-stubs', 'host-versions'])
207
+ })
208
+
209
+ // ---- Gate 4: the cross-version host ledger ----
210
+
211
+ const LEDGER_SURFACES = [
212
+ '| `rpcGuard` | RPC 入口守卫 | 存在性 | `lib/rpc.js:requestRejectionOf` | warn | requestRejection |',
213
+ '| `schedule` | 定时器 | edit | `lib/salient-wake.js:scheduleFlavor` | skip | global |',
214
+ '| `activation` | startActivation | rootOf | `lib/curator.js:activationUsesFlatSpec` | 换形 | nested |',
215
+ '| `coldLog` | 会话冷读 | 模块候选 | `lib/consolidation-snapshot.js:COLD_LOG_MODULES` | 活视图 | session-query |',
216
+ ].join('\n')
217
+
218
+ function ledgerRow(build, overrides = {}) {
219
+ const row = { commit: '66491b05e3', verdict: '源码', grade: 'exact', date: '2026-11-26', ...overrides }
220
+ return `| \`${build}\` | \`${row.commit}\` | ${row.verdict} | ${row.grade} | ${row.date} |`
221
+ + ' `rpcGuard=requestRejection;schedule=global;activation=nested;coldLog=session-query` | 桌面壳 |'
222
+ }
223
+
224
+ function makeHostFixture(options = {}) {
225
+ const root = tempDir()
226
+ write(root, 'lib/rpc.js', 'export function requestRejectionOf(connection, req) { return undefined }\n')
227
+ write(root, 'lib/salient-wake.js', 'export function scheduleFlavor(schedule) { return schedule ? \'global\' : null }\n')
228
+ write(root, 'lib/curator.js', 'export function activationUsesFlatSpec(subagents) { return Boolean(subagents) }\n')
229
+ write(root, 'lib/consolidation-snapshot.js', 'const COLD_LOG_MODULES = []\nexport const reconcile = 1\n')
230
+ if (options.package !== null) {
231
+ write(root, 'package.json', JSON.stringify(options.package
232
+ ?? { dsh: { compatibility: { dshReleases: ['0.2.2-rc.1'] } } }))
233
+ }
234
+ const rows = options.rows ?? [ledgerRow('0.2.2-rc.1')]
235
+ const surfaces = options.surfaces ?? LEDGER_SURFACES
236
+ write(root, 'docs/host-versions.md', '# 台账\n\n## 13.1 核对台账\n\n'
237
+ + '| 宿主构建 | commit | 核对方式 | 判定 | 日期 | 结构指纹 | 未覆盖面 |\n|---|---|---|---|---|---|---|\n'
238
+ + rows.join('\n') + '\n\n## 13.2 宿主面事实矩阵\n\n| 面ID | 宿主表面 | 探测判据 | 落点 | 降级 | 形状 |\n|---|---|---|---|---|---|\n'
239
+ + surfaces + '\n')
240
+ for (const [rel, body] of Object.entries(options.docs || {})) write(root, rel, body)
241
+ return root
242
+ }
243
+
244
+ const hostCheck = (root) => gate.checkHostVersions(root)
245
+
246
+ test('host-versions: a complete ledger passes', () => {
247
+ const result = hostCheck(makeHostFixture())
248
+ assert.equal(result.status, 'ok', JSON.stringify(result.details))
249
+ })
250
+
251
+ test('host-versions: a build named in another doc without a ledger row fails', () => {
252
+ const root = makeHostFixture({ docs: { 'docs/host-adaptation.md': '升到 `0.2.3-alpha.9` 后守卫变了。\n' } })
253
+ const result = hostCheck(root)
254
+ assert.equal(result.status, 'fail')
255
+ assert.ok(result.details.some((line) => line.includes('0.2.3-alpha.9') && line.includes('no row')), result.details.join('\n'))
256
+ })
257
+
258
+ test('host-versions: fenced code does not count as a build claim', () => {
259
+ const root = makeHostFixture({ docs: { 'docs/host-adaptation.md': '```bash\ngit tag dsh-v0.2.9-rc.7\n```\n' } })
260
+ assert.equal(hostCheck(root).status, 'ok')
261
+ })
262
+
263
+ test('host-versions: a renamed probe symbol fails until the ledger is updated', () => {
264
+ const root = makeHostFixture({ surfaces: LEDGER_SURFACES.replace('scheduleFlavor', 'flavourOfSchedule') })
265
+ const result = hostCheck(root)
266
+ assert.equal(result.status, 'fail')
267
+ assert.ok(result.details.some((line) => line.includes('schedule') && line.includes('not found')), result.details.join('\n'))
268
+ })
269
+
270
+ test('host-versions: a row must state how it was verified', () => {
271
+ const root = makeHostFixture({ rows: [ledgerRow('0.2.2-rc.1', { verdict: '大概可以' })] })
272
+ const result = hostCheck(root)
273
+ assert.equal(result.status, 'fail')
274
+ assert.ok(result.details.some((line) => line.includes('核对方式')), result.details.join('\n'))
275
+ })
276
+
277
+ test('host-versions: commit and date columns are checked', () => {
278
+ const root = makeHostFixture({ rows: [ledgerRow('0.2.2-rc.1', { commit: 'HEAD', date: '11-26' })] })
279
+ const result = hostCheck(root)
280
+ assert.equal(result.status, 'fail')
281
+ assert.ok(result.details.some((line) => line.includes('short sha')))
282
+ assert.ok(result.details.some((line) => line.includes('ISO')))
283
+ })
284
+
285
+ test('host-versions: a fingerprint key must be a registered surface', () => {
286
+ const root = makeHostFixture()
287
+ const docFile = path.join(root, 'docs', 'host-versions.md')
288
+ fs.writeFileSync(docFile, fs.readFileSync(docFile, 'utf8')
289
+ .replace('coldLog=session-query', 'cron=session-query'))
290
+ const result = hostCheck(root)
291
+ assert.equal(result.status, 'fail')
292
+ assert.ok(result.details.some((line) => line.includes('cron') && line.includes('not a surface')), result.details.join('\n'))
293
+ })
294
+
295
+ test('host-versions: a host version in running code fails, in a comment it does not', () => {
296
+ const root = makeHostFixture()
297
+ write(root, 'lib/versiongate.js', '// 0.2.3-alpha.1 起守卫换了形状\nexport const probed = true\n')
298
+ assert.equal(hostCheck(root).status, 'ok')
299
+ write(root, 'lib/versiongate.js', 'export const isAlpha = () => host === \'0.2.3-alpha.1\'\n')
300
+ const result = hostCheck(root)
301
+ assert.equal(result.status, 'fail')
302
+ assert.ok(result.details.some((line) => line.includes('versiongate.js') && line.includes('running code')), result.details.join('\n'))
303
+ })
304
+
305
+ test('host-versions: dshReleases must agree with the verified rows', () => {
306
+ const root = makeHostFixture({ rows: [ledgerRow('0.2.2-rc.1'), ledgerRow('0.2.2-rc.2')] })
307
+ const result = hostCheck(root)
308
+ assert.equal(result.status, 'fail')
309
+ assert.ok(result.details.some((line) => line.includes('dshReleases')), result.details.join('\n'))
310
+ const agreed = makeHostFixture({
311
+ rows: [ledgerRow('0.2.2-rc.1'), ledgerRow('0.2.2-rc.2')],
312
+ package: { dsh: { compatibility: { dshReleases: ['0.2.2-rc.1', '0.2.2-rc.2'] } } },
313
+ })
314
+ assert.equal(hostCheck(agreed).status, 'ok')
315
+ })
316
+
317
+ test('host-versions: an install directory without docs/ is skipped, not failed', () => {
318
+ const root = tempDir()
319
+ write(root, 'lib/rpc.js', 'export const shipped = true\n')
320
+ const result = hostCheck(root)
321
+ assert.equal(result.status, 'skipped', JSON.stringify(result))
322
+ })
323
+
324
+ test('host-versions: the shipped ledger itself passes the gate', () => {
325
+ assert.equal(hostCheck(REPO).status, 'ok', JSON.stringify(hostCheck(REPO).details))
206
326
  })
207
327
 
208
328
  test('CLI exits 1 and prints FAIL/skip when a gate fails', () => {
@@ -228,6 +228,23 @@ test('suggestEntityMerges: unrelated names yield an empty list', () => {
228
228
  assert.deepEqual(graph.suggestEntityMerges({ libraryId }).items, [])
229
229
  })
230
230
 
231
+ test('suggestEntityMerges: a full name, its nickname and a single-character call pair up as name-core', () => {
232
+ const libraryId = newLibrary('suggest-name-core')
233
+ const full = graph.createEntity({ libraryId, name: '顾清欢', kind: 'person' })
234
+ const pig = graph.createEntity({ libraryId, name: '欢欢', kind: 'person' })
235
+ const single = graph.createEntity({ libraryId, name: '欢', kind: 'person' })
236
+ const air = graph.createEntity({ libraryId, name: '空气', kind: 'thing' })
237
+ const climate = graph.createEntity({ libraryId, name: '气候', kind: 'thing' })
238
+ const { items } = graph.suggestEntityMerges({ libraryId })
239
+ const paired = (a, b) => items.find(item => [item.sourceId, item.targetId].includes(a.id)
240
+ && [item.sourceId, item.targetId].includes(b.id))
241
+ assert.ok(paired(full, pig), '全称与昵称共享一个名字核时给出候选')
242
+ assert.equal(paired(full, pig).reason, 'name-core')
243
+ assert.ok(paired(full, single), '单字称呼并入全称')
244
+ assert.ok(!paired(air, climate), '只是共用一个字的普通词不提议合并')
245
+ assert.ok(items.every(item => item.reason === 'containment' || item.reason === 'edit-distance' || item.reason === 'name-core'))
246
+ })
247
+
231
248
  test('suggestEntityMerges caps the list at 20 and never writes', () => {
232
249
  const libraryId = newLibrary('suggest-cap')
233
250
  for (let index = 0; index < 25; index += 1) {
@@ -132,6 +132,34 @@ test('every repair action has a label, so the page never shows a bare slug', ()
132
132
  }
133
133
  })
134
134
 
135
+ // ---------------------------------------------------------------- 实体碎片
136
+ test('the fragment finding reports, offers a confirmed-only repair, and is idempotent', async () => {
137
+ const state = await import('../lib/state.js')
138
+ const graph = await import('../lib/graph.js')
139
+ const libraryId = state.createLibrary({ name: 'envcheck-fragments', cwd: path.join(home, 'fragments') }).id
140
+ for (const name of ['南宫晚', '宫晚晴']) graph.createEntity({ libraryId, name, kind: 'person', status: 'confirmed' })
141
+ state.savePrivateIndex(libraryId, { entries: {
142
+ 'mem-1': { title: '南宫晚晴的午后', content: '南宫晚晴坐在窗边讲这件事。', status: 'active', visibility: 'shared', layer: 'long_term' },
143
+ } })
144
+
145
+ const report = env.runEnvironmentCheck()
146
+ const entry = report.items.find((row) => row.id === 'entity-fragments')
147
+ assert.ok(entry, 'the check reports the fragment finding instead of staying silent')
148
+ assert.equal(entry.repair, 'merge-entity-fragments')
149
+ assert.equal(entry.manual, true, 'merging entity identity is never an unattended auto-repair')
150
+ assert.equal(entry.auto, false)
151
+ assert.ok(!env.SAFE_REPAIRS.includes('merge-entity-fragments'), 'and it is absent from the safe list')
152
+
153
+ const outcome = await env.repairEnvironment({ actions: ['merge-entity-fragments'], confirmed: true })
154
+ assert.equal(outcome.results[0].ok, true, JSON.stringify(outcome.results[0]))
155
+ assert.match(outcome.results[0].detail, /合并 1 组/)
156
+ assert.ok(graph.listEntities({ libraryId }).items.some((entity) => entity.name === '南宫晚晴'))
157
+
158
+ const again = env.runEnvironmentCheck().items.find((row) => row.id === 'entity-fragments')
159
+ assert.equal(again.ok, true, 'after the repair the finding clears instead of nagging')
160
+ assert.equal(graph.listEntities({ libraryId }).items.length, 1)
161
+ })
162
+
135
163
  // ---------------------------------------------------------------- 运行时目录发现
136
164
 
137
165
  test('the managed runtime root is discovered where the service actually installs it', async () => {
@@ -88,3 +88,19 @@ test('an unknown global focus is rejected instead of returning an empty graph',
88
88
  seed()
89
89
  assert.throws(() => getGlobalGraph({ focusId: 'nonexistent' }), /unknown or inaccessible global graph focus/)
90
90
  })
91
+
92
+ test('a domain narrows the global graph but still reports every domain it holds', () => {
93
+ state.saveGlobalIndex({
94
+ entries: {
95
+ d1: { title: '发布窗口', domain: ' Coding ', status: 'active', links: [{ id: 'd_l1', to: 'd2', kind: 'related' }] },
96
+ d2: { title: '回滚规则', domain: 'CODING', status: 'active', links: [{ id: 'd_l1', to: 'd1', kind: 'related' }] },
97
+ d3: { title: '没有域标记', status: 'active', links: [{ id: 'd_l2', to: 'd1', kind: 'related' }] },
98
+ },
99
+ })
100
+ assert.deepEqual(getGlobalGraph({}).domains, ['coding', 'unknown'])
101
+ const filtered = getGlobalGraph({ domain: ' Coding ' })
102
+ assert.deepEqual(filtered.nodes.map((node) => node.id).sort(), ['d1', 'd2'])
103
+ assert.deepEqual(filtered.nodes.map((node) => node.domain).sort(), ['coding', 'coding'], 'nodes carry the normalized stamp')
104
+ assert.deepEqual(filtered.domains, ['coding', 'unknown'], 'the option list is never narrowed by the filter itself')
105
+ assert.equal(filtered.edges.length, 1, 'the edge reaching the other domain drops out')
106
+ })
@@ -39,22 +39,22 @@ const seed = (entries) => {
39
39
  const globalEntry = (id) => state.loadGlobalIndex().entries[id]
40
40
 
41
41
  test('global archive drops the entry from recall; restore brings it back', async () => {
42
- seed({ 'mem-g-visible': entry('zxquartzglobal 部署窗口'), 'mem-g-other': entry('unrelated filler') })
43
- const before = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
42
+ seed({ 'mem-g-visible': entry('zqneedleglobal 部署窗口'), 'mem-g-other': entry('unrelated filler') })
43
+ const before = await memory.globalRecall({ exec, query: 'zqneedleglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
44
44
  assert.deepEqual(before.files.map(f => f.name), ['mem-g-visible'])
45
45
  assert.equal(memory.isMemoryEligible(globalEntry('mem-g-visible'), { automatic: true }), true)
46
46
 
47
47
  const archived = await rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-visible' })
48
48
  assert.equal(archived.entry.status, 'archived')
49
49
  assert.equal(memory.isMemoryEligible(globalEntry('mem-g-visible'), { automatic: true }), false)
50
- const after = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
50
+ const after = await memory.globalRecall({ exec, query: 'zqneedleglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
51
51
  assert.deepEqual(after.files.map(f => f.name), [], 'archived global memory must not recall')
52
52
 
53
53
  // 幂等归档不报错;恢复走 updateMemory 的唯一全局补丁形状。
54
54
  await rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-visible' })
55
55
  const restored = await rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-visible', patch: { status: 'active' } })
56
56
  assert.equal(restored.entry.status, 'active')
57
- const back = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
57
+ const back = await memory.globalRecall({ exec, query: 'zqneedleglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
58
58
  assert.deepEqual(back.files.map(f => f.name), ['mem-g-visible'])
59
59
  })
60
60
 
@@ -127,4 +127,24 @@ test('management views still show archived global rows; private archive path is
127
127
  const archived = await rpc.dispatch({}, 'archiveMemory', { libraryId: lib.id, id: 'mem-p-row' })
128
128
  assert.equal(archived.entry.status, 'archived')
129
129
  assert.equal(state.loadPrivateIndex(lib.id).entries['mem-p-row'].status, 'archived')
130
+ })
131
+
132
+ test('the wall stamps every row with its domain and filters without shrinking the choices', async () => {
133
+ const lib = state.createLibrary({ name: 'global-lifecycle-domains', cwd: path.join(home, 'domain-wall') })
134
+ seed({ 'mem-g-rp': entry('顾清欢的约定', { domain: 'RP' }) })
135
+ state.updatePrivateIndex(lib.id, (index) => {
136
+ index.entries['mem-p-coding'] = entry('部署窗口', { domain: ' Coding ' })
137
+ index.entries['mem-p-legacy'] = { ...entry('没有域标记的旧条目'), domain: undefined }
138
+ })
139
+ const all = await rpc.dispatch({}, 'browseWall', { libraryId: lib.id, limit: 300 })
140
+ const byId = new Map(all.items.map(item => [item.id, item]))
141
+ assert.equal(byId.get('mem-p-coding').domain, 'coding', 'stamps normalize exactly like the graph filter does')
142
+ assert.equal(byId.get('mem-p-legacy').domain, 'general', 'an unstamped private row reads as general')
143
+ assert.equal(byId.get('mem-g-rp').domain, 'rp', 'global rows carry their own stamp')
144
+ assert.deepEqual(all.domains, ['coding', 'general', 'rp'])
145
+
146
+ const coding = await rpc.dispatch({}, 'browseWall', { libraryId: lib.id, limit: 300, domain: 'CODING' })
147
+ assert.deepEqual(coding.items.map(item => item.id), ['mem-p-coding'])
148
+ assert.equal(coding.total, 1, 'the count follows what the reader can actually see')
149
+ assert.deepEqual(coding.domains, all.domains, 'the option list is never narrowed by the filter itself')
130
150
  })
@@ -250,3 +250,114 @@ test('the linked flag tracks a refused delete through force, and cleanup drops t
250
250
  row = graph.listEntities({ libraryId }).items.find(entity => entity.id === kept.id)
251
251
  assert.equal(row, undefined, 'after the force delete the entity is gone from the listing too')
252
252
  })
253
+
254
+ // ---------------------------------------------------------------- 实体碎片修复
255
+ // 老版本把中文名的滑窗片段建成了独立节点。这里的不变量有两条:可证明的才自动合,
256
+ // 相似的绝不动;而且合并级联的全库清扫不能顺手删掉计划外的节点(硬规则 5)。
257
+ const repair = await import('../lib/entity-repair.js')
258
+ const repairLibrary = (name, entries, entities) => {
259
+ const id = state.createLibrary({ name, cwd: path.join(home, name) }).id
260
+ for (const entity of entities) graph.createEntity({ libraryId: id, name: entity, kind: 'person', status: 'confirmed' })
261
+ state.savePrivateIndex(id, { entries })
262
+ return id
263
+ }
264
+ const scene = (title, content) => ({ title, content, status: 'active', visibility: 'shared', layer: 'long_term' })
265
+
266
+ test('the fragment plan separates provable windows from merely similar names', () => {
267
+ const attestedRebuild = repairLibrary('repair-rebuild',
268
+ { 'mem-1': scene('南宫晚晴的午后', '南宫晚晴坐在窗边讲这件事。') },
269
+ ['南宫晚', '宫晚晴'])
270
+ const plan = repair.planLibraryRepair(attestedRebuild, { graph, loadPrivateIndex: state.loadPrivateIndex })
271
+ assert.equal(plan.groups.length, 1, 'the two windows rebuild into one provable group')
272
+ assert.equal(plan.groups[0].creates, true, 'no full-name node exists yet, so the reconstructed one is created')
273
+ assert.equal(plan.groups[0].target.name, '南宫晚晴')
274
+ assert.deepEqual(plan.ambiguous, [], 'nothing here rests on similarity alone')
275
+
276
+ const independent = repairLibrary('repair-independent',
277
+ { 'mem-1': scene('化学课', '今天讲化学,顺带写了化学式。') },
278
+ ['化学式', '化学'])
279
+ const second = repair.planLibraryRepair(independent, { graph, loadPrivateIndex: state.loadPrivateIndex })
280
+ assert.deepEqual(second.groups, [], 'a name that appears on its own is never treated as a window')
281
+ assert.equal(second.ambiguous.length, 1)
282
+ assert.equal(second.ambiguous[0].evidence, 'similar')
283
+
284
+ const lookalike = repairLibrary('repair-lookalike',
285
+ { 'mem-1': scene('两个称呼', '顾清欢也叫顾清悦,其实指的是不同的两只。') },
286
+ ['顾清欢', '顾清悦'])
287
+ const third = repair.planLibraryRepair(lookalike, { graph, loadPrivateIndex: state.loadPrivateIndex })
288
+ assert.deepEqual(third.groups, [], 'edit distance is not evidence: nothing is auto-merged')
289
+ assert.equal(third.ambiguous.length, 1, 'but the pair is still reported for a human decision')
290
+ })
291
+
292
+ test('applying the plan folds fragments into the reconstructed name and leaves memory bodies alone', () => {
293
+ const id = repairLibrary('repair-apply',
294
+ { 'mem-1': scene('南宫晚晴的午后', '南宫晚晴坐在窗边,南宫晚先到。') },
295
+ ['南宫晚', '宫晚晴'])
296
+ const before = Object.entries(state.loadPrivateIndex(id).entries)
297
+ .map(([key, entry]) => [key, entry.title, entry.content])
298
+ const plan = repair.planLibraryRepair(id, { graph, loadPrivateIndex: state.loadPrivateIndex })
299
+ const result = repair.applyRepairGroups(id, plan.groups, { graph })
300
+ assert.equal(result.merged, 1)
301
+ assert.equal(result.created, 1)
302
+ assert.deepEqual(result.failures, [])
303
+ assert.deepEqual(Object.entries(state.loadPrivateIndex(id).entries)
304
+ .map(([key, entry]) => [key, entry.title, entry.content]), before,
305
+ 'the repair never rewrites a memory title or body; it only re-points entity links')
306
+
307
+ const after = graph.listEntities({ libraryId: id }).items
308
+ assert.equal(after.length, 1, 'one surviving node: ' + after.map(entity => entity.name).join(','))
309
+ assert.equal(after[0].name, '南宫晚晴')
310
+ assert.deepEqual(after[0].aliases.sort(), ['南宫晚', '宫晚晴'])
311
+
312
+ // 幂等:合过之后再规划,没有可证明的组,也没有相似组。
313
+ const again = repair.planLibraryRepair(id, { graph, loadPrivateIndex: state.loadPrivateIndex })
314
+ assert.deepEqual(again.groups, [])
315
+ assert.deepEqual(again.ambiguous, [])
316
+ })
317
+
318
+ test('the merge cascade never deletes an entity the repair did not plan to touch', () => { const id = repairLibrary('repair-collateral',
319
+ { 'mem-1': scene('南宫晚晴与旁观者', '南宫晚晴坐在窗边,旁观者路过。') },
320
+ ['南宫晚', '宫晚晴', '旁观者'])
321
+ state.updatePrivateIndex(id, index => {
322
+ index.entries['mem-1'].links = [{ to: 'ent-unknown', kind: 'person', note: 'placeholder', confidence: 0.6 }]
323
+ })
324
+ const plan = repair.planLibraryRepair(id, { graph, loadPrivateIndex: state.loadPrivateIndex })
325
+ const result = repair.applyRepairGroups(id, plan.groups, { graph })
326
+ assert.equal(result.merged, 1)
327
+ assert.ok(result.restored >= 1, 'the unreferenced bystander was swept by pruneOrphanEntities and written back')
328
+ const names = graph.listEntities({ libraryId: id, }).items.map(entity => entity.name)
329
+ assert.ok(names.includes('南宫晚晴'), 'the repaired hub survives')
330
+ assert.ok(names.includes('旁观者'), 'an entity outside the plan is still there: ' + names.join(','))
331
+ })
332
+
333
+ test('the upgrade pass merges provable fragments once, leaves similar names for a human, and says so', async () => {
334
+ const { runEntityRepairPass } = await import('../lib/index.js')
335
+ const provable = repairLibrary('upgrade-provable',
336
+ { 'mem-1': scene('南宫晚晴的午后', '南宫晚晴坐在窗边讲这件事。') },
337
+ ['南宫晚', '宫晚晴'])
338
+ const similar = repairLibrary('upgrade-similar',
339
+ { 'mem-1': scene('两个称呼', '顾清欢也叫顾清悦,其实指的是不同的两只。') },
340
+ ['顾清欢', '顾清悦'])
341
+ const events = []
342
+ const first = await runEntityRepairPass({ diagnose: (row) => events.push(row) })
343
+ assert.equal(first.deferred, false, 'the backup is available here, so the pass is allowed to write')
344
+ assert.ok(first.merged >= 1, 'the provable pair is folded without asking: ' + JSON.stringify(first))
345
+ assert.ok(first.similar >= 1, 'similar pairs are counted, never merged: ' + JSON.stringify(first))
346
+ assert.ok(graph.listEntities({ libraryId: provable }).items.some((entity) => entity.name === '南宫晚晴'))
347
+ assert.equal(graph.listEntities({ libraryId: similar }).items.length, 2, 'similar names are left exactly as they were')
348
+ assert.ok(events.some((row) => row.code === 'ENTITY_FRAGMENT_REPAIRED'), 'what got folded is recorded, not silent')
349
+ assert.ok(events.some((row) => row.code === 'ENTITY_FRAGMENT_SUSPECTED' && row.manual === true),
350
+ 'the leftover is recorded as needing confirmation')
351
+ assert.ok(state.getCycleState().entityRepairVersion >= 1, 'the pass marks itself done so it never repeats')
352
+
353
+ const second = await runEntityRepairPass({ diagnose: (row) => events.push(row) })
354
+ assert.deepEqual(second, { skipped: 'done' }, 'one pass per install, no repeated writes on every start')
355
+
356
+ // 开关必须是可写且真起作用的:把标记抹掉、关掉开关,重跑就不能动任何数据。
357
+ const before = graph.listEntities({ libraryId: provable }).items.map((entity) => entity.name).join(',')
358
+ state.setCycleState({ entityRepairVersion: 0 })
359
+ state.updateSettings({ autoRepairEntityFragments: false })
360
+ const third = await runEntityRepairPass({ diagnose: () => {} })
361
+ assert.deepEqual(third, { skipped: 'setting' }, 'off means even the provable class waits for a human')
362
+ assert.equal(graph.listEntities({ libraryId: provable }).items.map((entity) => entity.name).join(','), before)
363
+ })
@@ -164,7 +164,7 @@ test('equal fused scores fall back to the best rank and then the canonical id',
164
164
  // 在场时,其余行的 share 按 max(1/(1+topLex/50), sqrt(lexical/topLex)) 折减,强命中保住头部。
165
165
  test('a dominant lexical hit keeps its seat; the rank-flattened near-tie cannot be exploited by biases', () => {
166
166
  const index = indexOf({
167
- 'mem-food': entry({ title: '主人是云南人,爱吃松茸菌子和过桥米线', createdAt: '2026-11-17T00:00:00.000Z', updatedAt: '2026-11-17T00:00:00.000Z', strength: 0.8 }),
167
+ 'mem-food': entry({ title: '主人是江南人,爱吃桂花糖糕和豆沙米糕', createdAt: '2026-11-17T00:00:00.000Z', updatedAt: '2026-11-17T00:00:00.000Z', strength: 0.8 }),
168
168
  'mem-meta': entry({ title: '运营值守安排', createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z', strength: 1 }),
169
169
  })
170
170
  const fused = memory.fuseRecallCandidates({
@@ -74,6 +74,7 @@ function makeTurn(sessionId, options = {}) {
74
74
  turn = 1,
75
75
  text = 'please continue with the earlier context of this task',
76
76
  history = [],
77
+ sessionCreatedAt = null,
77
78
  } = options
78
79
  const user = {
79
80
  id: sessionId + '-user-' + turn,
@@ -82,7 +83,9 @@ function makeTurn(sessionId, options = {}) {
82
83
  content: [{ type: 'text', text }],
83
84
  }
84
85
  const decision = { kind: 'enter', messages: [...history, user] }
85
- const agent = { session: { header: { id: sessionId, cwd, agentPreset, origin } } }
86
+ const session = { header: { id: sessionId, cwd, agentPreset, origin } }
87
+ if (sessionCreatedAt !== null) session.createdAt = sessionCreatedAt
88
+ const agent = { session }
86
89
  const payload = { agent, turn, step, signal: { aborted: false } }
87
90
  return { user, decision, payload }
88
91
  }
@@ -186,6 +189,78 @@ function textOf(messages) {
186
189
  return (messages || []).map((message) => String(message?.content?.[0]?.text || '')).join('\n')
187
190
  }
188
191
 
192
+ test('a recreated session object with the same id re-delivers the guide and the anchor', async () => {
193
+ const sessionId = 'guide-incarnation'
194
+ const cwd = path.join(home, 'project-guide-incarnation')
195
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
196
+ seedPinned(binding, 'mem-guide-incarnation', '重启后的锚点')
197
+ const mounted = mountGuide()
198
+
199
+ const first = makeTurn(sessionId, { cwd, sessionCreatedAt: 1_700_000_000_000 })
200
+ const firstOut = await mounted.run(first.payload, first.decision)
201
+ assert.equal(guideMessages(firstOut.messages).length, 1)
202
+ assert.equal(state.getSessionBinding(sessionId).sessionStamp, 'created:1700000000000')
203
+
204
+ const next = makeTurn(sessionId, { cwd, turn: 2, sessionCreatedAt: 1_700_000_000_000 })
205
+ const nextOut = await mounted.run(next.payload, next.decision)
206
+ assert.equal(guideMessages(nextOut.messages).length, 0, '同一会话对象不重发')
207
+
208
+ // 通道用确定性 id 重建同名会话:binding 还是旧的,转录从头开始。
209
+ const revived = makeTurn(sessionId, { cwd, turn: 1, sessionCreatedAt: 1_700_000_100_000 })
210
+ const revivedOut = await mounted.run(revived.payload, revived.decision)
211
+ const revivedGuides = guideMessages(revivedOut.messages)
212
+ assert.equal(revivedGuides.length, 1, '新会话对象必须重新拿到规则')
213
+ assert.ok(textOf(revivedOut.messages).includes('[mem-guide-incarnation]'), '锚点也重新投放')
214
+ const stamped = state.getSessionBinding(sessionId)
215
+ assert.equal(stamped.sessionStamp, 'created:1700000100000')
216
+ assert.equal(stamped.guideRulesKey, guideKey(revivedGuides[0]))
217
+ assert.equal(stamped.guideLost, false)
218
+ })
219
+
220
+ test('without a host createdAt, a first turn on a reused id resets one-shots exactly once', async () => {
221
+ const sessionId = 'guide-turn-reset'
222
+ const cwd = path.join(home, 'project-guide-turn-reset')
223
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
224
+ const mounted = mountGuide()
225
+
226
+ const first = makeTurn(sessionId, { cwd })
227
+ const firstOut = await mounted.run(first.payload, first.decision)
228
+ assert.equal(guideMessages(firstOut.messages).length, 1)
229
+ assert.equal(state.getSessionBinding(sessionId).sessionStamp, `turn1:${first.user.id}`)
230
+
231
+ const later = makeTurn(sessionId, { cwd, turn: 4 })
232
+ const laterOut = await mounted.run(later.payload, later.decision)
233
+ assert.equal(guideMessages(laterOut.messages).length, 0)
234
+
235
+ const revived = makeTurn(sessionId, { cwd, turn: 1, text: 'a brand new conversation' })
236
+ revived.user.id = 'guide-turn-reset-new-user'
237
+ revived.decision.messages = [revived.user]
238
+ const revivedOut = await mounted.run(revived.payload, revived.decision)
239
+ assert.equal(guideMessages(revivedOut.messages).length, 1, '回合号回到 1 → 重新投放')
240
+
241
+ // 宿主对同一首步重入:这一代的戳一致,不再重置、不再追加副本。
242
+ const reentry = makeTurn(sessionId, { cwd, turn: 1, text: 'a brand new conversation' })
243
+ reentry.user.id = 'guide-turn-reset-new-user'
244
+ reentry.decision.messages = [reentry.user]
245
+ const reentryOut = await mounted.run(reentry.payload, reentry.decision)
246
+ assert.equal(guideMessages(reentryOut.messages).length, 0)
247
+ })
248
+
249
+ test('a recall failure cannot swallow the rules message', async () => {
250
+ const sessionId = 'guide-failopen'
251
+ const cwd = path.join(home, 'project-guide-failopen')
252
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
253
+ const mounted = mountGuide()
254
+ const turn = makeTurn(sessionId, { cwd })
255
+ Object.defineProperty(turn.payload.agent.session.header, 'agentPreset', {
256
+ get() { throw new Error('inject boom') },
257
+ })
258
+ const out = await mounted.run(turn.payload, turn.decision)
259
+ assert.equal(guideMessages(out.messages).length, 1, 'guide 与召回解耦,召回故障时仍然投放')
260
+ assert.ok(mounted.logger.warnings.some((message) => message.includes('pre-step injection failed')))
261
+ assert.match(String(state.getSessionBinding(sessionId).lastRecallError || ''), /inject boom/)
262
+ })
263
+
189
264
  test('a domain change replaces the old guide with exactly one current version', async () => {
190
265
  const sessionId = 'guide-domain'
191
266
  const cwd = path.join(home, 'project-guide-domain')
@@ -209,6 +284,38 @@ test('a domain change replaces the old guide with exactly one current version',
209
284
  assert.equal(out.messages.includes(old), false, 'the old version is projected out of the model view')
210
285
  })
211
286
 
287
+ test('switching the memory domain re-delivers the guide and the domain-scoped one-shots', async () => {
288
+ const sessionId = 'guide-domain-switch'
289
+ const cwd = path.join(home, 'project-guide-domain-switch')
290
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
291
+ const mounted = mountGuide()
292
+
293
+ const first = makeTurn(sessionId, { cwd })
294
+ const firstOut = await mounted.run(first.payload, first.decision)
295
+ const oldKey = guideKey(guideMessages(firstOut.messages)[0])
296
+ assert.equal(state.getSessionBinding(sessionId).injectedDomain, 'coding')
297
+
298
+ // 这条记忆是上一轮之后才写下的:切域后锚点重投时必须重新出现。
299
+ seedPinned(binding, 'mem-domain-switch', '切域之后写下的记忆')
300
+ state.setSessionBinding(sessionId, {
301
+ anniversariesShown: { 'mem-anniv': '2026-11-26' },
302
+ openLoopRemindedAt: { 'mem-loop': new Date().toISOString() },
303
+ })
304
+ state.setSessionBinding(sessionId, { domainOverride: 'rp' })
305
+
306
+ const next = makeTurn(sessionId, { cwd, turn: 2 })
307
+ const out = await mounted.run(next.payload, next.decision)
308
+ const guides = guideMessages(out.messages)
309
+ assert.equal(guides.length, 1)
310
+ assert.match(String(guides[0].content[0].text), /关于记忆(角色扮演)/)
311
+ assert.notEqual(guideKey(guides[0]), oldKey)
312
+ assert.ok(textOf(out.messages).includes('[mem-domain-switch]'), '锚点随切域重投')
313
+ const after = state.getSessionBinding(sessionId)
314
+ assert.equal(after.injectedDomain, 'rp')
315
+ assert.deepEqual(after.anniversariesShown, {})
316
+ assert.deepEqual(after.openLoopRemindedAt, {})
317
+ })
318
+
212
319
  test('a prompt override changes the rendered body and the rules key', async () => {
213
320
  const sessionId = 'guide-override'
214
321
  const cwd = path.join(home, 'project-guide-override')
@@ -847,13 +847,13 @@ test('a dominant lexical hit cannot be buried by primacy/peak-end biases', async
847
847
  // meta:最早创建(primacy ×1.2)+ 高唤醒(peakEnd ×1.25)+ strength 1——偏置加成最大;
848
848
  // 正文含查询里的常见词元(有/没有),让它也进词法腿,制造名次归一的近平手。
849
849
  entries['mem-meta'] = entry('运营值守安排,没有什么特别的说明。', { createdAt: old, updatedAt: old, strength: 1, arousal: 0.9 })
850
- entries['mem-food'] = entry('主人是云南人,爱吃松茸菌子,在广州吃不到几家做菌子和过桥米线的馆子。', { strength: 0.8, arousal: 0.35 })
850
+ entries['mem-food'] = entry('主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。', { strength: 0.8, arousal: 0.35 })
851
851
  const f = fixture(entries)
852
852
  activate([f.libraryId])
853
853
  // 语义腿把 meta 排在 food 前面(模拟引擎 embedding 被查询样板带偏的形态):
854
854
  // 词法腿 food 满分,RRF 名次归一后两者 retrieval 近平手。
855
855
  retrieveHook = () => ({ files: [{ name: 'mem-meta' }, { name: 'mem-food' }], segments: [], resources: [] })
856
- const result = await memory.privateRecall({ exec: f.exec, query: '松茸的,我云南娃子喜欢吃菌子,还有过桥米线', topK: 5, relevanceThreshold: 0.4 })
856
+ const result = await memory.privateRecall({ exec: f.exec, query: '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕', topK: 5, relevanceThreshold: 0.4 })
857
857
  assert.equal(result.files[0]?.name, 'mem-food', 'the dominant lexical hit must rank first, got ' + result.files[0]?.name)
858
858
  assert.ok((result.files[0]?.fusion?.lexicalDominant ?? 0) >= 24, 'the dominance must be recorded in fusion metadata')
859
859
  assert.ok(!result.files.some((file) => file.name === 'mem-meta'), 'weak competitors fall below the relative threshold')
@@ -955,11 +955,11 @@ for (const [language, template, query] of [
955
955
  }
956
956
 
957
957
  const rankingWords = 'certificate expired renewal proxy restart connection handshake trust chain hostname issuer validity protocol cipher client server clock intermediate root authority verification transport security gateway service outage investigation diagnosis mitigation deployment recovery monitoring incident encryption authentication socket timeout negotiation alert endpoint configuration rotation revocation openssl pem browser response failure latency availability maintenance rollback'.split(' ')
958
- const foodQuery = '松茸的,我云南娃子喜欢吃菌子,还有过桥米线'
959
- const foodAnswer = '主人是云南人,爱吃松茸菌子,在广州吃不到几家做菌子和过桥米线的馆子。'
958
+ const foodQuery = '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕'
959
+ const foodAnswer = '主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。'
960
960
 
961
961
  test('real BM25 a weak 的 hit is no worse than zero evidence and preserves topical answer order', async () => {
962
- const topicQuery = '松茸 云南 菌子 过桥米线 广州 馆子'
962
+ const topicQuery = '桂花 江南 糖糕 豆沙米糕 杭州 铺子'
963
963
  const entries = {
964
964
  'mem-food': rankingEntry(foodAnswer, { peak: true, createdAt: new Date(Date.now() - 4 * 86_400_000).toISOString() }),
965
965
  'mem-semantic': rankingEntry('钢琴练习巴赫赋格。', { strength: 0.8 }),
@@ -1119,12 +1119,12 @@ test('real BM25 two tied genuinely strong topical hits both survive without corp
1119
1119
  })
1120
1120
 
1121
1121
  test('real BM25 QQ private-chat envelope and preference trailer preserve food as the top answer', async () => {
1122
- const query = '[私聊:1299772830]22:11 Kingxiao(1299772830)[主人] #-100705771 [@咱]:松茸的,我云南娃子喜欢吃菌子,还有过桥米线\n[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。\n【本会话是QQ私聊:1299772830。请用自然简洁的语气回答。】'
1122
+ const query = '[私聊:900000001]22:11 Linxiu(900000001)[主人] #-100000001 [@咱]:桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕\n[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。\n【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】'
1123
1123
  const now = Date.now()
1124
1124
  const recentCreatedAt = new Date(now - 2 * 86_400_000).toISOString()
1125
1125
  const f = fixture({
1126
1126
  'mem-food': rankingEntry(foodAnswer, { strength: 0.8, createdAt: recentCreatedAt }),
1127
- 'mem-template': rankingEntry('[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。【本会话是QQ私聊:1299772830。请用自然简洁的语气回答。】', { peak: true, createdAt: new Date(now - 4 * 86_400_000).toISOString() }),
1127
+ 'mem-template': rankingEntry('[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】', { peak: true, createdAt: new Date(now - 4 * 86_400_000).toISOString() }),
1128
1128
  'mem-piano': rankingEntry(pianoNotes[0], { createdAt: recentCreatedAt }),
1129
1129
  })
1130
1130
  activate([f.libraryId])
@@ -250,6 +250,18 @@ test('perEntry, total, maxCandidates and maxEntities caps hold', () => {
250
250
  assert.ok(capped.candidates[0].score >= capped.candidates[1].score, 'highest score is preferred')
251
251
  })
252
252
 
253
+ test('a sliding window of a repeated four-character name is not the entity name', () => {
254
+ const index = snapshot({
255
+ 'mem-w1': entry('南宫晚晴,午后', '她坐在窗边讲这件事,讲了很久。'),
256
+ 'mem-w2': entry('南宫晚晴,傍晚', '南宫晚晴先到了门口,带来了那把伞。'),
257
+ })
258
+ const result = suggestPrivateLinks({ index, ids: ['mem-w1'] })
259
+ const names = [...result.entityHubs.map(hub => hub.name), ...result.candidates.map(item => item.suggestedEntity?.name)]
260
+ assert.deepEqual(result.entityHubs.map(hub => hub.name), ['南宫晚晴'],
261
+ 'one hub for the whole surface, never one per window: ' + names.join(','))
262
+ for (const name of names) assert.ok(!['南宫晚', '宫晚晴'].includes(name), 'a window fragment is not a person: ' + name)
263
+ })
264
+
253
265
  // ---- 纯函数:不确定实体类型 / thing / kind 冲突 ----
254
266
 
255
267
  test('CJK name-like token without a person cue is an uncertain candidate, not a hub', () => {
@@ -283,3 +283,33 @@ test('local consolidation adds actual tools while the shared domain body stays b
283
283
  assert.equal(text.includes('你没有记忆工具'), false)
284
284
  }
285
285
  })
286
+
287
+ test('every memory guide ships the tool timing map, in all four domains', () => {
288
+ const vars = { mustRememberCap: 12, unpinBudget: 2, shortTermTtlHours: 72, anchorTokens: 800, turnTokens: 800 }
289
+ for (const domain of ['general', 'coding', 'rp', 'mixed']) {
290
+ const text = prompts.loadPromptForDomain('system-guide', vars, domain).text
291
+ for (const tool of ['memu_private_recall', 'memu_global_recall', 'memu_private_remember',
292
+ 'memu_private_update', 'memu_private_list', 'memu_status', 'memu_private_archive', 'memu_private_unpin']) {
293
+ assert.ok(text.includes(tool), `${domain}: the first-step guide must say when to use ${tool}`)
294
+ }
295
+ assert.match(text, /link|lexicon/, `${domain}: consolidation-only tools are fenced off`)
296
+ assert.match(text, /remember_batch/, `${domain}: several facts in one call are pointed at the batch tool`)
297
+ }
298
+ })
299
+
300
+ test('the consolidation brief switches to the engineering value order for coding', async () => {
301
+ const { buildWorkerBrief } = await import('../lib/consolidation-worker.js')
302
+ const snapshot = { fromSeq: 1, throughSeq: 2, eventCount: 2, hash: 'coding-brief' }
303
+ const coding = buildWorkerBrief({ snapshot, probe: null, contract: '', domain: 'coding' })
304
+ assert.match(coding, /根因与修复理由/)
305
+ assert.match(coding, /不受「普通事实最多 3 条」限制/)
306
+ assert.match(coding, /每窗最多新增 8 条/)
307
+ assert.match(coding, /150–350 字/)
308
+ assert.match(coding, /路径 \+ 符号/)
309
+ assert.doesNotMatch(coding, /只保留人物、地点、时间、事情、原话/)
310
+ for (const domain of ['rp', 'general', 'mixed']) {
311
+ const brief = buildWorkerBrief({ snapshot, probe: null, contract: '', domain })
312
+ assert.match(brief, /约定\/承诺 = 新人物首次出现/, `${domain}: the people-first order stays for non-coding domains`)
313
+ assert.match(brief, /content 写 50–150 字/, `${domain}: non-coding content length is unchanged`)
314
+ }
315
+ })