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
@@ -110,9 +110,10 @@ test('the real tool → recall → injection chain is reachable and carries S1
110
110
  assert.match(datedText, /date=2026-11-07/, 'the resolved absolute date reaches the prompt')
111
111
  assert.match(datedText, /source=assistant_said/)
112
112
  assert.match(datedText, /speaker=assistant/)
113
- // The user message is untouched and the plugin message comes before it.
114
- assert.equal(dated.messages.at(-1).source.kind, 'user')
115
- assert.equal(dated.messages.at(-1).content[0].text, dateUser.content[0].text)
113
+ // The user message is untouched and the plugin message comes right after it.
114
+ assert.equal(dated.messages.at(-2).source.kind, 'user')
115
+ assert.equal(dated.messages.at(-2).content[0].text, dateUser.content[0].text)
116
+ assert.equal(dated.messages.at(-1).source.kind, 'plugin:dsh-memu-memory')
116
117
 
117
118
  const floorUser = {
118
119
  id: 'chain-u2', role: 'user', source: { kind: 'user' },
@@ -0,0 +1,107 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import crypto from 'node:crypto'
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-pending-'))
9
+ process.env.DSH_HOME = home
10
+ process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
12
+
13
+ const state = await import('../lib/state.js')
14
+ const inject = await import('../lib/inject.js')
15
+
16
+ test.after(() => {
17
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
18
+ })
19
+
20
+ const digestOf = (message) => crypto.createHash('sha256').update(JSON.stringify(message?.content ?? null)).digest('hex')
21
+ const NOW = () => new Date().toISOString()
22
+
23
+ function seed(sessionId, entryId) {
24
+ const cwd = path.join(home, sessionId)
25
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
26
+ const index = state.loadPrivateIndex(binding.libraryId)
27
+ index.entries[entryId] = {
28
+ track: 'memory', layer: 'long_term', title: '部署脚本', content: '部署脚本放在 tools/deploy.ps1。',
29
+ status: 'active', confidence: 0.9, createdAt: NOW(), updatedAt: NOW(),
30
+ }
31
+ state.savePrivateIndex(binding.libraryId, index)
32
+ const user = { id: 'u-' + sessionId, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: '部署脚本放在哪里?' }] }
33
+ const agent = { session: { header: { id: sessionId, cwd, agentPreset: 'coding', origin: 'user' } } }
34
+ return { agent, user }
35
+ }
36
+
37
+ test('a proposal leaves a digest credential so another process can still finish the admission', async () => {
38
+ const sessionId = 'pending-cred'
39
+ const { agent, user } = seed(sessionId, 'mem-cred')
40
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
41
+ const plugin = out.messages.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
42
+ assert.ok(plugin, 'a plugin message is proposed on the first step')
43
+ const credentials = state.getSessionBinding(sessionId).pendingInjections || []
44
+ assert.equal(credentials.length, 1, 'exactly one credential is persisted')
45
+ assert.equal(credentials[0].digest, digestOf(plugin))
46
+ assert.equal(state.findPendingInjection(sessionId, digestOf(plugin))?.messageId, plugin.id)
47
+ assert.ok(credentials[0].refs.length >= 1, 'the credential carries the refs needed to commit')
48
+ })
49
+
50
+ test('turn end invalidates the credential so a late identical message cannot revive a discarded proposal', async () => {
51
+ const sessionId = 'pending-drop'
52
+ const { agent, user } = seed(sessionId, 'mem-drop')
53
+ const handlers = new Map()
54
+ const ctx = { on (name, handler) { handlers.set(name, handler); return () => {} }, logger: { warn () {} }, inject () {} }
55
+ inject.registerInjection(ctx)
56
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
57
+ const plugin = out.messages.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
58
+ const digest = digestOf(plugin)
59
+ assert.ok(state.findPendingInjection(sessionId, digest), 'credential exists while the turn is open')
60
+ await handlers.get('session/event')({ header: { id: sessionId } }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })
61
+ assert.equal(state.findPendingInjection(sessionId, digest), null, 'a closed turn leaves nothing to revive')
62
+ assert.deepEqual(state.getSessionBinding(sessionId).pendingInjections ?? [], [])
63
+ })
64
+
65
+ test('digest credentials expire after the TTL and the freshest same-digest match wins', () => {
66
+ const sessionId = 'pending-ttl'
67
+ state.ensureSession(sessionId, { cwd: path.join(home, sessionId) })
68
+ const stale = { digest: 'd-1', messageId: 'm-stale', turn: 0, clock: 0, at: new Date(Date.now() - 31 * 60_000).toISOString() }
69
+ const old = { digest: 'd-1', messageId: 'm-old', turn: 1, clock: 1, at: new Date(Date.now() - 5 * 60_000).toISOString() }
70
+ const fresh = { digest: 'd-1', messageId: 'm-fresh', turn: 2, clock: 2, at: new Date().toISOString() }
71
+ state.setSessionBinding(sessionId, { pendingInjections: [stale, old, fresh] })
72
+ assert.equal(state.findPendingInjection(sessionId, 'd-1').messageId, 'm-fresh', 'the newest same-digest credential wins')
73
+ state.setSessionBinding(sessionId, { pendingInjections: [stale] })
74
+ assert.equal(state.findPendingInjection(sessionId, 'd-1'), null, 'a 31-minute credential is dead')
75
+ state.rememberPendingInjection(sessionId, { digest: 'd-2', messageId: 'm-new', turn: 9, clock: 9 })
76
+ const rows = state.getSessionBinding(sessionId).pendingInjections
77
+ assert.deepEqual(rows.map(row => row.messageId), ['m-new'], 'remembering prunes the expired credential')
78
+ })
79
+
80
+ test('a cross-process admission commits once, forgets its own credential, and re-observation is quiet', async () => {
81
+ const sessionId = 'pending-store-admit'
82
+ seed(sessionId, 'mem-store')
83
+ const binding = state.getSessionBinding(sessionId)
84
+ // 模拟另一个进程投出的同内容锚点:本进程 Map 里没有提案,只有落盘凭据。
85
+ const lateMessage = { id: 'late-1', role: 'user', source: { kind: 'plugin:dsh-memu-memory' },
86
+ content: [{ type: 'text', text: '===== memory anchor =====\nstore-path fixture' }] }
87
+ state.setSessionBinding(sessionId, { pendingInjections: [{
88
+ digest: digestOf(lateMessage), messageId: 'm-store-cred', turn: 42, clock: 3,
89
+ generation: Number(binding.scopeGeneration || 0), epoch: Number(binding.injectionEpoch || 0),
90
+ refs: [{ scope: 'private', libraryId: binding.libraryId, id: 'mem-store', revision: 'rev-1' }],
91
+ actions: { patch: {} }, at: new Date().toISOString(),
92
+ }] })
93
+ const warns = []
94
+ const handlers = new Map()
95
+ const ctx = { on (name, handler) { handlers.set(name, handler); return () => {} }, logger: { warn: (m) => warns.push(String(m)) }, inject () {} }
96
+ inject.registerInjection(ctx)
97
+ const session = { header: { id: sessionId } }
98
+ await handlers.get('session/event')(session, { type: 'user/message', data: lateMessage })
99
+ const admitted = state.getSessionBinding(sessionId).acceptedMemoryMessages || []
100
+ assert.equal(admitted.length, 1, 'the credential admission commits exactly once')
101
+ assert.equal(admitted[0].messageId, 'late-1')
102
+ assert.equal((state.getSessionBinding(sessionId).pendingInjections || []).length, 0,
103
+ 'the credential is forgotten by its own messageId, not the observed id')
104
+ await handlers.get('session/event')(session, { type: 'user/message', data: lateMessage })
105
+ assert.equal((state.getSessionBinding(sessionId).acceptedMemoryMessages || []).length, 1, 'the second observation neither re-commits')
106
+ assert.equal(warns.filter(w => w.includes('未被接纳')).length, 0, 'nor warns — an admitted message observed twice is a success')
107
+ })
@@ -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', () => {
@@ -26,16 +26,16 @@ for (const backend of ['agent', 'api', 'api-fallback']) {
26
26
  state.updateSettings({ memoryBackend: backend === 'agent' ? 'agent' : 'api', vectorSource: 'api', crossLibraryRecall: false })
27
27
  const entries = {}
28
28
  const entry = (title, extra = {}) => ({ title, content: title, layer: 'long_term', status: 'active', createdAt: new Date().toISOString(), ...extra })
29
- entries['mem-target'] = entry('zxquartz')
29
+ entries['mem-target'] = entry('zqneedle')
30
30
  for (let i = 0; i < 7; i++) entries['mem-filler-' + i] = entry('unrelated' + i)
31
31
  state.savePrivateIndex(libraryId, { entries })
32
32
  const exec = { agent: { session: { header: { id: sessionId } } } }
33
33
  // Empty semantic results exercise the production mixed recall lexical leg.
34
- const recall = (query = 'zxquartz', purpose = 'automatic') => privateRecall({ exec, query, purpose, topK: 5, relevanceThreshold: 0, retrieveImpl: async () => { if (backend === 'api-fallback') throw new Error('simulated vector outage'); return { files: [] } } })
34
+ const recall = (query = 'zqneedle', purpose = 'automatic') => privateRecall({ exec, query, purpose, topK: 5, relevanceThreshold: 0, retrieveImpl: async () => { if (backend === 'api-fallback') throw new Error('simulated vector outage'); return { files: [] } } })
35
35
  const before = await recall()
36
36
  assert.equal(before.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
37
37
  assert.deepEqual(before.files.map(f => f.name), ['mem-target'])
38
- for (let i = 0; i < 12; i++) entries['mem-hidden-' + i] = entry('zxquartz', hidden)
38
+ for (let i = 0; i < 12; i++) entries['mem-hidden-' + i] = entry('zqneedle', hidden)
39
39
  state.savePrivateIndex(libraryId, { entries })
40
40
  const after = await recall()
41
41
  assert.equal(after.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
@@ -27,6 +27,8 @@ const SAMPLE = {
27
27
  salientWake: 'schedule',
28
28
  salientWakeHour: '20:30',
29
29
  salientWakeTimeZone: 'Asia/Shanghai',
30
+ // 升级自愈的 kill switch:默认 true,这里必须能写成 false 才算「可关」不是空话。
31
+ autoRepairEntityFragments: false,
30
32
  }
31
33
 
32
34
  test('each new setting is writable through setSettings', async () => {
@@ -237,7 +237,7 @@ test('complete quoted and introduced names remain usable and existing aliases ar
237
237
  try {
238
238
  for (const [i, name, content] of [
239
239
  [0, '阿兰', '她叫阿兰,今天来送信。'],
240
- [1, '小柚', '「小柚」今天来送信。'],
240
+ [1, '小檀', '「小檀」今天来送信。'],
241
241
  [2, '主人一', '这个角色自称「主人一」,这是完整昵称。'],
242
242
  [3, 'Alice', 'Alice delivered the letter.'],
243
243
  [4, 'Old Zhou', 'Old Zhou delivered the letter.'],
@@ -903,3 +903,61 @@ test('standalone rpc wrapper surfaces the server error message instead of the st
903
903
  const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
904
904
  assert.match(client, /envelope\.error\?\.message \|\| \('Invalid RPC response: ' \+ response\.status\)/)
905
905
  })
906
+
907
+ // 0.2.3-alpha.1 起宿主把 connection.requestRejection 换成 connection.admit。
908
+ // 只探测前者(或只探测挂在模块而非服务上的 isTrustedApiRequest)的守卫在新宿主上会静默放行。
909
+ test('a host that only exposes connection.admit stays guarded', async () => {
910
+ const routes = []
911
+ const admit = { calls: 0, decision: undefined }
912
+ registerRpc({
913
+ inject: (_deps, build) => build({
914
+ effect: (fn) => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
915
+ webServer: { register: (spec) => { routes.push(spec); return () => {} } },
916
+ connection: { admit: () => { admit.calls += 1; return admit.decision } },
917
+ logger: {},
918
+ }),
919
+ })
920
+ const route = routes.find(spec => spec.path === '/dsh-memu-memory')
921
+ assert.ok(route, 'the admit-only host registered its RPC route')
922
+ const fire = async (decision) => {
923
+ admit.decision = decision
924
+ admit.calls = 0
925
+ resetProbe()
926
+ const chunks = []
927
+ let resolveDone
928
+ const done = new Promise((resolve) => { resolveDone = resolve })
929
+ const timer = setTimeout(() => resolveDone(new Error('response did not end')), 3000)
930
+ timer.unref?.()
931
+ const res = {
932
+ status: 0,
933
+ writeHead(code) { this.status = code; return this },
934
+ write() { return true },
935
+ end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); resolveDone() },
936
+ get text() { return Buffer.concat(chunks).toString('utf8') },
937
+ }
938
+ const req = {
939
+ method: 'POST', url: '/dsh-memu-memory', headers: {},
940
+ async *[Symbol.asyncIterator]() { chunks.push(Buffer.from('body read')) },
941
+ }
942
+ probe.active = true
943
+ try {
944
+ await route.handler(req, res)
945
+ await done
946
+ } finally { probe.active = false }
947
+ return { status: res.status, text: res.text, admitCalls: admit.calls, reads: [...probe.reads], writes: [...probe.writes] }
948
+ }
949
+
950
+ const refused = await fire({ rejection: 403 })
951
+ assert.equal(refused.status, 403, 'admit rejection becomes the HTTP status')
952
+ assert.equal(refused.admitCalls, 1, 'admit runs exactly once')
953
+ assert.equal(refused.text.includes('body read'), false, 'the body is not read before admission')
954
+ assert.deepEqual(refused.reads, [])
955
+ assert.deepEqual(refused.writes, [])
956
+
957
+ const admitted = await fire({ peer: {} })
958
+ assert.ok(admitted.status !== 403 && admitted.status !== 401, 'an admitted peer passes the guard')
959
+ assert.equal(admitted.admitCalls, 1)
960
+ // §13.6:这台宿主实际走了哪一级探测,要能在指纹里读到(台账核对用的就是这一行)。
961
+ const surface = await import('../lib/host-surface.js')
962
+ assert.equal(surface.hostSurface().rpcGuard, 'admit', 'the probe records which guard shape this host exposes')
963
+ })