dsh-memu-memory 1.3.14 → 1.4.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 (59) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +50 -1
  3. package/docs/binding-lifecycle.md +1 -1
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/host-adaptation.md +58 -16
  6. package/docs/host-versions.md +120 -0
  7. package/docs/memory-semantics.md +4 -1
  8. package/docs/pending-work.md +51 -0
  9. package/docs/troubleshooting.md +16 -3
  10. package/lib/auto-link/candidates.js +4 -1
  11. package/lib/auto-link/decide.js +1 -1
  12. package/lib/auto-link/normalize.js +2 -2
  13. package/lib/auto-link/terminology.js +31 -1
  14. package/lib/binding-diagnostics.js +1 -1
  15. package/lib/client.js +53 -6
  16. package/lib/consolidation-snapshot.js +37 -1
  17. package/lib/curator.js +1 -1
  18. package/lib/cycle.js +5 -0
  19. package/lib/diagnostics.js +10 -0
  20. package/lib/entity-repair.js +285 -0
  21. package/lib/environment-check.js +72 -3
  22. package/lib/global-graph.js +11 -2
  23. package/lib/graph.js +32 -8
  24. package/lib/host-surface.js +30 -0
  25. package/lib/index.js +116 -1
  26. package/lib/inject.js +428 -32
  27. package/lib/private-links.js +12 -0
  28. package/lib/rpc.js +78 -11
  29. package/lib/state.js +78 -1
  30. package/package.json +16 -1
  31. package/scripts/chain-matrix.mjs +4 -0
  32. package/scripts/check-doc-drift.mjs +194 -0
  33. package/scripts/entity-dedupe.mjs +110 -0
  34. package/tests/auto-link-candidates.test.mjs +22 -9
  35. package/tests/auto-link-decide.test.mjs +59 -59
  36. package/tests/auto-link-migration.test.mjs +4 -4
  37. package/tests/client-render.test.mjs +112 -1
  38. package/tests/cue.test.mjs +2 -1
  39. package/tests/cycle.test.mjs +2 -2
  40. package/tests/diagnostics.test.mjs +21 -0
  41. package/tests/doc-drift.test.mjs +122 -2
  42. package/tests/entity-merge.test.mjs +17 -0
  43. package/tests/environment-check.test.mjs +28 -0
  44. package/tests/global-graph.test.mjs +16 -0
  45. package/tests/global-lifecycle.test.mjs +24 -4
  46. package/tests/graph-cascade.test.mjs +111 -0
  47. package/tests/hybrid-recall.test.mjs +1 -1
  48. package/tests/inject.test.mjs +7 -7
  49. package/tests/injection-chain.test.mjs +40 -2
  50. package/tests/injection-rollback.test.mjs +4 -3
  51. package/tests/managed-memory.test.mjs +7 -7
  52. package/tests/media.test.mjs +4 -1
  53. package/tests/memory-chain.test.mjs +4 -3
  54. package/tests/pending-injection.test.mjs +107 -0
  55. package/tests/private-links.test.mjs +12 -0
  56. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  57. package/tests/settings-plumbing.test.mjs +2 -0
  58. package/tests/tools.test.mjs +1 -1
  59. package/tests/webui-auth.test.mjs +58 -0
@@ -521,7 +521,7 @@ test('a session arriving at an archived library revives it through the fast path
521
521
  })
522
522
 
523
523
  test('a legacy archive with no recorded source is not revived just because an old binding exists', () => {
524
- // 本机实测:rp(14 个绑定)、ai中转站(4 个)都是「归档 + 还有旧绑定」,但 lastUsed 三周前。
524
+ // 本机实测:rp(14 个绑定)、另一个工作区库(4 个)都是「归档 + 还有旧绑定」,但 lastUsed 三周前。
525
525
  // 旧数据分不清是用户归档还是老扫描误归档,所以只复活「还热」的;冷的不动。
526
526
  const lib = state.createLibrary({ name: 'legacy-cold', cwd: path.join(home, 'legacy-cold') })
527
527
  const st = state.loadState()
@@ -553,7 +553,7 @@ test('a warm legacy archive (no source recorded, used minutes ago) is revived',
553
553
  })
554
554
 
555
555
  test('a cold legacy archive with an old binding can still be deleted', () => {
556
- // 本机 rp / ai中转站 形态:很久以前归档、仍留着旧绑定、lastUsed 三周前。
556
+ // 本机 rp / 另一个工作区库 形态:很久以前归档、仍留着旧绑定、lastUsed 三周前。
557
557
  // 它不是扫描误归档(那类会被自愈),也不该因为“有旧绑定”变成永远删不掉。
558
558
  const lib = state.createLibrary({ name: 'legacy-deletable', cwd: path.join(home, 'legacy-deletable') })
559
559
  const st = state.loadState()
@@ -255,3 +255,24 @@ test('rows on disk survive a restart, so the page is not empty after a reload',
255
255
  assert.equal(parsed.total >= 1, true, 'a fresh process must read the persisted rows')
256
256
  assert.equal(parsed.code, 'PERSISTED_ROW')
257
257
  })
258
+
259
+ // docs/host-versions.md §13.6:台账指纹的运行时对应物。它不判断、不比版本号,
260
+ // 只是把已经发生过的结构探测结果聚合成一行——所以断言盯着"记下了什么"。
261
+ test('host surface records probe verdicts and refuses unregistered keys', async () => {
262
+ const surface = await import('../lib/host-surface.js')
263
+ const before = surface.hostSurface()
264
+ assert.deepEqual(Object.keys(before).sort(), [...surface.HOST_SURFACES].sort())
265
+
266
+ surface.noteHostSurface('rpcGuard', 'admit')
267
+ assert.equal(surface.hostSurface().rpcGuard, 'admit')
268
+ surface.noteHostSurface('rpcGuard', '')
269
+ assert.equal(surface.hostSurface().rpcGuard, 'admit', 'an empty verdict never erases a known one')
270
+ surface.noteHostSurface('semver', '0.2.3-alpha.1')
271
+ assert.equal('semver' in surface.hostSurface(), false, 'a stale call site cannot invent a ledger key')
272
+
273
+ const line = surface.hostSurfaceLine()
274
+ assert.match(line, /rpcGuard=admit/)
275
+ assert.equal(line.split(' ').length, surface.HOST_SURFACES.length)
276
+ for (const part of line.split(' ')) assert.match(part, /^[a-zA-Z]+=\S+$/, 'every surface prints key=value: ' + line)
277
+ surface.noteHostSurface('rpcGuard', before.rpcGuard)
278
+ })
@@ -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({
@@ -159,7 +159,7 @@ test('with the same anchorTokens, title cards expose at least as many ids as ful
159
159
  `title cards exposed ${anchor.ids.length} ids, full text ${legacy.ids.length}`)
160
160
  })
161
161
 
162
- test('pre-step inserts a plugin message before the user message', async () => {
162
+ test('pre-step inserts a plugin message right after the user message', async () => {
163
163
  const cwd = path.join(home, 'project-step')
164
164
  const binding = state.ensureSession('inject-step', { cwd, agentPreset: 'coding' })
165
165
  const index = state.loadPrivateIndex(binding.libraryId)
@@ -199,13 +199,13 @@ test('pre-step inserts a plugin message before the user message', async () => {
199
199
  const agent = { session: { header: { id: 'inject-step', cwd, agentPreset: 'coding', origin: 'user' } } }
200
200
  const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false } })
201
201
  assert.equal(out.messages.length, 2)
202
- assert.equal(out.messages[0].role, 'user')
203
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
204
- assert.equal(out.messages[0].source.plugin, undefined)
205
- assert.equal(out.messages[0].source.form, 'recall')
206
- assert.equal(out.messages[1].source.kind, 'user')
202
+ assert.equal(out.messages[0].source.kind, 'user', 'the human message stays first')
203
+ assert.equal(out.messages[1].role, 'user')
204
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory')
205
+ assert.equal(out.messages[1].source.plugin, undefined)
206
+ assert.equal(out.messages[1].source.form, 'recall')
207
207
 
208
- const injected = out.messages[0].content[0].text
208
+ const injected = out.messages[1].content[0].text
209
209
  assert.ok(injected.includes('[mem-recall]'), 'per-turn recall must surface the matching entry by id')
210
210
  assert.ok(injected.includes('Deploy convention'), 'the title is what reaches the prompt')
211
211
  assert.equal(injected.includes('The deploy script lives in tools/deploy.ps1'), false,
@@ -281,8 +281,8 @@ test('the hint ships in the same plugin message as the recall block', async () =
281
281
  const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
282
282
 
283
283
  assert.equal(out.messages.length, 2)
284
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
285
- const text = out.messages[0].content[0].text
284
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory', 'memory follows the human turn')
285
+ const text = out.messages[1].content[0].text
286
286
  assert.ok(text.includes('[mem-fresh-message]'))
287
287
  assert.equal((text.match(/<memory-freshness>/g) || []).length, 1)
288
288
  assert.ok(text.indexOf('<memory-freshness>') > text.lastIndexOf('</memory-context>'))
@@ -402,3 +402,41 @@ test('typed cooldown follows content revisions, library identity and a new injec
402
402
  const reinjected = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 4, settings, exec, id)
403
403
  assert.ok(reinjected.ids.includes('mem-shared-id'))
404
404
  })
405
+
406
+ // ---------------------------------------------------------------- I: mid-turn recall
407
+ // 回合中途补充召回:只可能在非首步、批次无人类消息、inbound 没改动决策时出现;
408
+ // 门 = 步距 + 增量证据 + 每回合上限 + 冷却 + 空召回退避;midTurnRecall 必须是可写设置
409
+ // (1.3.15 审核修正:此前键未注册,updateSettings 会静默丢弃,「可关」是空头承诺)。
410
+
411
+ test('a long tool-only step gets one mid-turn hint card, gated by step distance', async () => {
412
+ const cwd = path.join(home, 'mid-turn')
413
+ state.ensureSession('mid-turn', { cwd, agentPreset: 'coding' })
414
+ const agent = { session: { header: { id: 'mid-turn', cwd, agentPreset: 'coding', origin: 'user' } } }
415
+ const toolMsgs = (n) => Array.from({ length: n }, (_, i) => ({
416
+ id: 'mid-tool-' + i, role: 'tool', source: { kind: 'tool' },
417
+ content: [{ type: 'text', text: 'x'.repeat(120) + ' #' + i }],
418
+ }))
419
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 11, step: 5, signal: { aborted: false } })
420
+ const plugin = out.messages.filter(m => m?.source?.kind === 'plugin:dsh-memu-memory')
421
+ .find(m => String(m?.content?.[0]?.text || '').includes('回合中途补充'))
422
+ assert.ok(plugin, 'step 5 with three distinct tool units earns the hint card')
423
+ const early = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 12, step: 2, signal: { aborted: false } })
424
+ assert.ok(!early.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'step 2 cannot clear the four-step gap')
425
+ })
426
+
427
+ test('midTurnRecall:false is a writable kill switch for mid-turn recall', async () => {
428
+ const cwd = path.join(home, 'mid-turn-off')
429
+ state.ensureSession('mid-turn-off', { cwd, agentPreset: 'coding' })
430
+ const agent = { session: { header: { id: 'mid-turn-off', cwd, agentPreset: 'coding', origin: 'user' } } }
431
+ const toolMsgs = Array.from({ length: 3 }, (_, i) => ({
432
+ id: 'off-tool-' + i, role: 'tool', source: { kind: 'tool' },
433
+ content: [{ type: 'text', text: 'y'.repeat(120) + ' #' + i }],
434
+ }))
435
+ const before = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 21, step: 6, signal: { aborted: false } })
436
+ assert.ok(before.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'default-on proves the fixture actually reaches the gate')
437
+ const saved = state.updateSettings({ midTurnRecall: false })
438
+ assert.equal(saved.midTurnRecall, false, 'the switch survives updateSettings validation (it is a registered key now)')
439
+ const after = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 22, step: 6, signal: { aborted: false } })
440
+ assert.ok(!after.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'the kill switch stops it')
441
+ state.updateSettings({ midTurnRecall: true })
442
+ })
@@ -314,18 +314,19 @@ for (const acceptedPart of ['guide', 'recall']) test(`partial ${acceptedPart} ad
314
314
  assert.deepEqual(facts(session.id), after, 'discarded partial sibling cannot commit late')
315
315
  })
316
316
 
317
- test('proposal reuse preserves pre-human ordering and missing human projection without duplicate IDs', async () => {
317
+ test('proposal reuse preserves post-human ordering and missing human projection without duplicate IDs', async () => {
318
318
  const session = makeSession('projection')
319
319
  const human = user('projection', '林眠的相机镜头修好了吗')
320
320
  const first = await step(session, 1, [human])
321
321
  const memory = first.find(message => ANCHOR_RE.test(textOf(message)))
322
322
  const second = await step(session, 1, [human])
323
323
  assert.equal(second.find(message => ANCHOR_RE.test(textOf(message))).id, memory.id)
324
- assert.ok(second.findIndex(message => message.id === memory.id) < second.findIndex(message => message.id === human.id))
324
+ assert.ok(second.findIndex(message => message.id === memory.id) > second.findIndex(message => message.id === human.id),
325
+ 'memory sits after the human turn')
325
326
  const missing = await step(session, 1, [])
326
327
  assert.equal(missing.filter(message => message.id === human.id).length, 1, 'retry carries the pending human too')
327
328
  assert.equal(missing.filter(message => message.id === memory.id).length, 1)
328
- assert.ok(missing.findIndex(message => message.id === memory.id) < missing.findIndex(message => message.id === human.id))
329
+ assert.ok(missing.findIndex(message => message.id === memory.id) > missing.findIndex(message => message.id === human.id))
329
330
  await accept(session, [human])
330
331
  const nativeAlready = await step(session, 1, [])
331
332
  assert.equal(nativeAlready.some(message => message.id === human.id), false, 'a Native-admitted human is not appended twice')
@@ -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])
@@ -42,7 +42,10 @@ test('image-only turns retrieve a saved image and expose the image count in stat
42
42
  const message = { id: 'image-only-native-user', role: 'user', ...event(4).data }
43
43
  const decision = await inject.injectForStep({ agent: exec.agent, decision: { kind: 'enter', messages: [message] }, turn: 2, step: 1 })
44
44
  assert.ok(decision.messages.length > 1)
45
- assert.ok(decision.messages[0].content[0].text.includes(saved.id))
45
+ const injectedText = decision.messages
46
+ .filter(message => message?.source?.kind === 'plugin:dsh-memu-memory')
47
+ .map(message => String(message?.content?.[0]?.text || '')).join('\n')
48
+ assert.ok(injectedText.includes(saved.id))
46
49
  assert.equal(state.getSessionBinding('images').recentQueries.at(-1).imageCount, 1)
47
50
  const tools = []
48
51
  registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } } })