dsh-memu-memory 1.3.13 → 1.3.15

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.
@@ -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
+ })