dsh-memu-memory 1.2.7 → 1.2.8

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 (49) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/memory-semantics.md +23 -3
  5. package/lib/backup.js +1 -1
  6. package/lib/budget.js +31 -0
  7. package/lib/commitment.js +138 -0
  8. package/lib/consolidation-receipt.js +2 -0
  9. package/lib/consolidation-worker.js +3 -0
  10. package/lib/freshness.js +24 -0
  11. package/lib/inject.js +117 -10
  12. package/lib/lexicon.js +1 -1
  13. package/lib/local-vector-service.js +4 -1
  14. package/lib/memory.js +565 -32
  15. package/lib/memu.js +4 -0
  16. package/lib/private.js +5 -3
  17. package/lib/prompts/private-consolidation.mixed.md +2 -2
  18. package/lib/prompts/private-consolidation.rp.md +6 -1
  19. package/lib/prompts/private-policy.rp.md +4 -0
  20. package/lib/prompts/system-guide.rp.md +3 -0
  21. package/lib/recall-cache.js +10 -2
  22. package/lib/rpc.js +9 -2
  23. package/lib/snippet.js +25 -0
  24. package/lib/temporal.js +329 -0
  25. package/lib/text-retrieval.js +71 -0
  26. package/lib/tools.js +81 -4
  27. package/package.json +1 -1
  28. package/scripts/bench-recall.mjs +2 -2
  29. package/scripts/check-seed-compat.mjs +1 -1
  30. package/tests/backup.test.mjs +2 -2
  31. package/tests/commitment.test.mjs +144 -0
  32. package/tests/consolidation-fork.test.mjs +3 -3
  33. package/tests/disclosure.test.mjs +34 -17
  34. package/tests/fact-version.test.mjs +128 -0
  35. package/tests/help-page.test.mjs +1 -1
  36. package/tests/inject-conflict.test.mjs +94 -0
  37. package/tests/inject-guide.test.mjs +5 -3
  38. package/tests/inject.test.mjs +2 -2
  39. package/tests/injection-intent-budget.test.mjs +92 -0
  40. package/tests/lexicon-frequency.test.mjs +1 -1
  41. package/tests/memory-chain.test.mjs +140 -0
  42. package/tests/memory-fields.test.mjs +134 -0
  43. package/tests/memu-resident.test.mjs +33 -0
  44. package/tests/prompt-semantics.test.mjs +51 -0
  45. package/tests/query-decompose.test.mjs +62 -0
  46. package/tests/recall-cache.test.mjs +4 -2
  47. package/tests/recall-intent.test.mjs +100 -0
  48. package/tests/speaker-provenance.test.mjs +120 -0
  49. package/tests/temporal.test.mjs +124 -0
@@ -0,0 +1,94 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-conflict-inject-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const { conflictCard } = await import('../lib/snippet.js')
14
+ const { estTokens } = await import('../lib/budget.js')
15
+
16
+ test.after(() => {
17
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
18
+ })
19
+
20
+ let seq = 0
21
+ function session(name) {
22
+ seq += 1
23
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
24
+ const sessionId = `${name}-${seq}`
25
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
26
+ return {
27
+ sessionId,
28
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
29
+ }
30
+ }
31
+
32
+ test('a recalled conflict brings both sides and one compact card', async () => {
33
+ const { exec, sessionId } = session('conflict-inject')
34
+ const left = await memory.privateRemember({
35
+ exec, title: '客厅地板是木色', content: '客厅地板是木色的,去年刚铺的。',
36
+ factKey: 'home:living_floor_color', absoluteDate: '2026-10-01',
37
+ })
38
+ const right = await memory.privateRemember({
39
+ exec, title: '客厅地板是灰色', content: '客厅地板不是木色,是灰色瓷砖。',
40
+ factKey: 'home:living_floor_color', absoluteDate: '2026-11-05',
41
+ })
42
+
43
+ const recalled = await memory.privateRecall({ exec, query: '客厅地板颜色是什么', topK: 1, relevanceThreshold: 0 })
44
+ const ids = recalled.files.map((file) => file.name)
45
+ assert.ok(ids.includes(left.id) && ids.includes(right.id), 'topK=1 still yields the pair, not half a contradiction')
46
+ assert.equal(recalled.conflictPairs.length, 1)
47
+
48
+ const binding = state.getSessionBinding(sessionId)
49
+ const build = await inject.buildRecall(binding, '客厅地板颜色是什么', 1, {
50
+ ...state.getSettings(), privateTopK: 1, relevanceThreshold: 0, turnTokens: 800,
51
+ }, exec, sessionId)
52
+ assert.deepEqual(build.errors, [])
53
+ assert.match(build.text, /冲突 · home:living_floor_color/)
54
+ assert.match(build.text, /未确认哪版为准/)
55
+ assert.ok(build.text.includes(`[${left.id}]`) && build.text.includes(`[${right.id}]`))
56
+ assert.ok(build.ids.includes(left.id) && build.ids.includes(right.id))
57
+ // The pair is rendered once as a card, not again as two ordinary title cards.
58
+ assert.equal(build.text.split(`[${left.id}]`).length - 1, 1)
59
+ assert.ok(estTokens(build.text) <= 800)
60
+ })
61
+
62
+ test('the card text stays under 200 characters even with long titles', () => {
63
+ const long = '很长的标题'.repeat(40)
64
+ const card = conflictCard({
65
+ factKey: 'home:living_floor_color',
66
+ left: { id: 'mem-a', entry: { title: long, absolute_date: '2026-10-01' } },
67
+ right: { id: 'mem-b', entry: { title: long, absolute_date: '2026-11-05' } },
68
+ })
69
+ assert.ok(card.length <= 200, `card length ${card.length}`)
70
+ assert.ok(card.includes('[mem-a]') && card.includes('[mem-b]'))
71
+ assert.equal(conflictCard({ left: null, right: null }), '')
72
+ })
73
+
74
+ test('a conflict card that cannot fit falls back to the ordinary title cards', async () => {
75
+ const { exec, sessionId } = session('conflict-budget')
76
+ const longTitle = '非常长的旅行目的地描述'.repeat(8)
77
+ const longKey = 'trip:' + 'x'.repeat(180)
78
+ const left = await memory.privateRemember({
79
+ exec, title: longTitle, content: '说好去冰岛。', factKey: longKey,
80
+ })
81
+ const right = await memory.privateRemember({
82
+ exec, title: longTitle + '乙', content: '说好不去冰岛,去挪威。', factKey: longKey,
83
+ })
84
+ const binding = state.getSessionBinding(sessionId)
85
+ // The card's fact_key + two long titles cannot fit; a one-line title card still can.
86
+ const build = await inject.buildRecall(binding, '旅行目的地', 1, {
87
+ ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 150,
88
+ }, exec, sessionId)
89
+ assert.deepEqual(build.errors, [])
90
+ assert.equal(build.text.includes('冲突 ·'), false)
91
+ assert.ok(build.text.length > 0)
92
+ assert.ok(build.ids.length >= 1)
93
+ assert.ok([left.id, right.id].some((id) => build.text.includes(`[${id}]`)))
94
+ })
@@ -372,7 +372,9 @@ test('standard and preset mounts render the same rules body', async () => {
372
372
  })
373
373
 
374
374
  test('the guide is included in injectionTotalTokens, not added on top of it', async () => {
375
- state.updateSettings({ injectionTotalTokens: 900, turnTokens: 800, randomCueChance: 0, habitsInjection: false })
375
+ // 1.2.8 的 RP guide 增加了时间/版本/来源三条规则,整段约 930 token;预算抬到 1000,
376
+ // 仍然是“guide 先落、锚点被裁”的同一条口径。
377
+ state.updateSettings({ injectionTotalTokens: 1000, turnTokens: 800, randomCueChance: 0, habitsInjection: false })
376
378
  const sessionId = 'guide-budget'
377
379
  const cwd = path.join(home, 'project-guide-budget')
378
380
  const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
@@ -387,6 +389,6 @@ test('the guide is included in injectionTotalTokens, not added on top of it', as
387
389
  const guides = guideMessages(out.messages)
388
390
  assert.equal(guides.length, 1, 'the guide still lands')
389
391
  const used = pluginMessages(out.messages).reduce((sum, message) => sum + budget.estTokens(messageTextOf(message)), 0)
390
- assert.ok(used <= 900, `guide + anchor must stay inside injectionTotalTokens, got ${used}`)
391
- assert.ok(used < 900 + 200, 'sanity: the anchor was clipped rather than the guide silently dropped')
392
+ assert.ok(used <= 1000, `guide + anchor must stay inside injectionTotalTokens, got ${used}`)
393
+ assert.ok(used < 1000 + 200, 'sanity: the anchor was clipped rather than the guide silently dropped')
392
394
  })
@@ -98,7 +98,7 @@ test('title-card lines keep source, disclosure, accuracy and the attachment coun
98
98
  title: '他编的那个故事',
99
99
  content: '他说那是真的,但那只是他想出来的。',
100
100
  source: 'imagined',
101
- disclosure: 'never_say',
101
+ disclosure: 'can_tell',
102
102
  accuracy: 0.3,
103
103
  confidence: 0.9,
104
104
  attachments: [
@@ -115,7 +115,7 @@ test('title-card lines keep source, disclosure, accuracy and the attachment coun
115
115
  const line = anchor.text.split('\n').find((row) => row.includes('[mem-labels]'))
116
116
  assert.ok(line, 'the title card exists')
117
117
  assert.ok(line.includes('source=imagined'), 'an imagined memory must not read as a fact')
118
- assert.ok(line.includes('记得,但别直接说出口'), 'never_say survives on a title card')
118
+ assert.equal(line.includes('别直接说出口'), false, 'can_tell carries no disclosure suffix')
119
119
  assert.ok(line.includes('细节未必准'), 'accuracy still rides on the line')
120
120
  assert.ok(line.includes('附件2'), 'attachments are counted')
121
121
  assert.equal(anchor.text.includes('CAPTION-MUST-NOT-EXPAND'), false, 'captions are expanded only by the full renderer')
@@ -0,0 +1,92 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-injection-intent-budget-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const { estTokens } = await import('../lib/budget.js')
14
+
15
+ test.after(() => {
16
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
17
+ })
18
+
19
+ let seq = 0
20
+ function session(name) {
21
+ seq += 1
22
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
23
+ const sessionId = `${name}-${seq}`
24
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
25
+ return {
26
+ sessionId,
27
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
28
+ }
29
+ }
30
+
31
+ test('a boundary question injects only_if_asked, never never_say, and stays inside turnTokens', async () => {
32
+ const { exec, sessionId } = session('budget-boundary')
33
+ const open = await memory.privateRemember({
34
+ exec, title: '账本放在书房', content: '账本放在书房第二个抽屉。',
35
+ })
36
+ const ask = await memory.privateRemember({
37
+ exec, title: '账本里有一笔旧账', content: '账本里记着一笔旧账。', disclosure: 'only_if_asked',
38
+ })
39
+ const never = await memory.privateRemember({
40
+ exec, title: '账本的来历', content: '账本是他父亲留下的。', disclosure: 'never_say',
41
+ })
42
+ const binding = state.getSessionBinding(sessionId)
43
+ const settings = { ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 180 }
44
+
45
+ const boundary = await inject.buildRecall(binding, '账本的秘密是什么', 1, settings, exec, sessionId)
46
+ assert.deepEqual(boundary.errors, [])
47
+ assert.ok(boundary.text.includes(`[${ask.id}]`), 'only_if_asked is released by a boundary question')
48
+ assert.equal(boundary.text.includes(never.id), false, 'never_say stays out of automatic injection')
49
+ assert.ok(boundary.text.includes(`[${open.id}]`))
50
+ assert.ok(estTokens(boundary.text) <= settings.turnTokens, 'the block respects its own budget')
51
+
52
+ const general = await inject.buildRecall(binding, '账本', 2, settings, exec, sessionId)
53
+ assert.ok(general.text.includes(`[${open.id}]`))
54
+ assert.equal(general.text.includes(ask.id), false, 'a general question does not release only_if_asked')
55
+ assert.equal(general.text.includes(never.id), false)
56
+ assert.ok(estTokens(general.text) <= settings.turnTokens)
57
+ })
58
+
59
+ test('a time question orders the injected timeline by absolute_date, newest first', async () => {
60
+ const { exec, sessionId } = session('budget-date-order')
61
+ const older = await memory.privateRemember({
62
+ exec, title: '旅行的旧计划', content: '旅行原计划十一月一号出发。', absoluteDate: '2026-11-01',
63
+ })
64
+ const newer = await memory.privateRemember({
65
+ exec, title: '旅行的新计划', content: '旅行改到十一月五号出发。', absoluteDate: '2026-11-05',
66
+ })
67
+ const binding = state.getSessionBinding(sessionId)
68
+ const recall = await inject.buildRecall(binding, '旅行什么时候出发', 1, {
69
+ ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 400,
70
+ }, exec, sessionId)
71
+ assert.deepEqual(recall.errors, [])
72
+ const olderAt = recall.text.indexOf(`[${older.id}]`)
73
+ const newerAt = recall.text.indexOf(`[${newer.id}]`)
74
+ assert.ok(olderAt >= 0 && newerAt >= 0, 'both plans are injected')
75
+ assert.ok(newerAt < olderAt, 'the most recent absolute date comes first')
76
+ assert.ok(estTokens(recall.text) <= 400)
77
+ })
78
+
79
+ test('a commitment question uses the commitment budget and keeps due commitments', async () => {
80
+ const { exec, sessionId } = session('budget-commitment')
81
+ const promised = await memory.privateRemember({
82
+ exec, title: '答应查机票', content: '答应明天帮他查机票。',
83
+ commitment: { counterparty: 'user', action: '查机票', due_at: '2026-11-07', status: 'open' },
84
+ })
85
+ const binding = state.getSessionBinding(sessionId)
86
+ const recall = await inject.buildRecall(binding, '你答应过什么时候查机票', 1, {
87
+ ...state.getSettings(), privateTopK: 3, relevanceThreshold: 0, turnTokens: 400,
88
+ }, exec, sessionId)
89
+ assert.deepEqual(recall.errors, [])
90
+ assert.ok(recall.text.includes(`[${promised.id}]`))
91
+ assert.ok(estTokens(recall.text) <= 400)
92
+ })
@@ -1,4 +1,4 @@
1
- // 词典频率先验(施工稿 §6.3 包 C):Wilson 下界、effective 因子进入 stableRank、
1
+ // 词典频率先验:Wilson 下界、effective 因子进入 stableRank、
2
2
  // hitCounts 写入 clamp、以及生命周期(active/archived)对频率证据的影响。所有断言
3
3
  // 只依赖落盘数据,不依赖当前时间——排序的确定性在这里与 lexicon-inject 各钉一遍。
4
4
  // 面板/卡片流(§2.4)的 UI 断言在 tests/lexicon-ui.test.mjs(G2b 重写),本文件只管
@@ -0,0 +1,140 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-chain-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const { registerTools } = await import('../lib/tools.js')
11
+ const state = await import('../lib/state.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const { dispatch } = await import('../lib/rpc.js')
14
+
15
+ test.after(() => {
16
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
17
+ })
18
+
19
+ function registeredTools() {
20
+ const tools = new Map()
21
+ registerTools({
22
+ tools: { register(tool) { tools.set(tool.name, tool); return () => {} } },
23
+ logger: { warn() {} },
24
+ })
25
+ return tools
26
+ }
27
+
28
+ function idsIn(text) {
29
+ return [...String(text || '').matchAll(/mem-[a-z0-9]+-[a-z0-9]+/gi)].map((match) => match[0])
30
+ }
31
+
32
+ test('the real tool → recall → injection chain is reachable and carries S1–S6 fields', async () => {
33
+ const tools = registeredTools()
34
+ for (const name of ['memu_private_remember', 'memu_private_recall', 'memu_private_update', 'memu_status']) {
35
+ assert.ok(tools.has(name), `missing tool ${name}`)
36
+ }
37
+
38
+ state.updateSettings({ randomCueChance: 0, habitsInjection: false, dedupeTurns: 0 })
39
+ const cwd = path.join(home, 'project-chain')
40
+ const sessionId = 'chain-session'
41
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
42
+ state.setSessionBinding(sessionId, { sceneTime: '2026-11-06T04:00:00.000Z' })
43
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } }
44
+
45
+ // 1. A user fact written through the actual model-facing tool.
46
+ const userReply = await tools.get('memu_private_remember').execute({
47
+ content: '明天下午三点在码头见面,别迟到。',
48
+ title: '明天码头见面',
49
+ source: 'user_said',
50
+ speaker_id: 'user',
51
+ }, exec)
52
+ const [userFactId] = idsIn(userReply)
53
+ assert.ok(userFactId, userReply)
54
+ const userEntry = state.loadPrivateIndex(state.getSessionBinding(sessionId).libraryId).entries[userFactId]
55
+ assert.equal(userEntry.absolute_date, '2026-11-07')
56
+ assert.equal(userEntry.speaker_id, 'user')
57
+ assert.equal(userEntry.source_kind, 'user_said')
58
+
59
+ // 2. An assistant promise, written as assistant_said with a commitment.
60
+ const promiseReply = await tools.get('memu_private_remember').execute({
61
+ content: '我答应明天提前去码头占位置。',
62
+ title: '答应提前去码头占位',
63
+ source_kind: 'assistant_said',
64
+ commitment: { counterparty: 'user', action: '提前去码头占位', due_at: '2026-11-07', status: 'open' },
65
+ }, exec)
66
+ const [promiseId] = idsIn(promiseReply)
67
+ assert.ok(promiseId, promiseReply)
68
+ const promiseEntry = state.loadPrivateIndex(state.getSessionBinding(sessionId).libraryId).entries[promiseId]
69
+ assert.equal(promiseEntry.source_kind, 'assistant_said')
70
+ assert.equal(promiseEntry.speaker_id, 'assistant')
71
+ assert.equal(promiseEntry.commitment.status, 'open')
72
+ assert.equal(promiseEntry.openLoop, true)
73
+
74
+ // 3. Two conflicting versions of one fact, then a conflict card in the real recall.
75
+ const floorA = idsIn(await tools.get('memu_private_remember').execute({
76
+ content: '客厅地板是木色的。', title: '客厅地板木色', fact_key: 'home:living_floor_color',
77
+ }, exec))[0]
78
+ const floorB = idsIn(await tools.get('memu_private_remember').execute({
79
+ content: '客厅地板不是木色,是灰色瓷砖。', title: '客厅地板灰色', fact_key: 'home:living_floor_color',
80
+ }, exec))[0]
81
+ assert.ok(floorA && floorB)
82
+
83
+ // 4. The explicit recall tool sees both the dated fact and the conflict pair.
84
+ const recallReply = await tools.get('memu_private_recall').execute({ query: '明天码头', topK: 10 }, exec)
85
+ assert.ok(recallReply.includes(userFactId), recallReply)
86
+ assert.ok(recallReply.includes(promiseId))
87
+ const floorReply = await tools.get('memu_private_recall').execute({ query: '客厅地板颜色', topK: 10 }, exec)
88
+ assert.ok(floorReply.includes(floorA) && floorReply.includes(floorB), floorReply)
89
+
90
+ // 5. The real pre-step injection path emits one plugin message carrying the fields
91
+ // the model needs to answer: resolved date, speaker and the conflict card.
92
+ const agent = { session: { header: { id: sessionId, cwd, agentPreset: 'rp', origin: 'user' } } }
93
+ const dateUser = {
94
+ id: 'chain-u1', role: 'user', source: { kind: 'user' },
95
+ content: [{ type: 'text', text: '明天下午我们在码头几点见面?' }],
96
+ }
97
+ const dated = await inject.injectForStep({
98
+ agent,
99
+ decision: { kind: 'enter', messages: [dateUser] },
100
+ turn: 1,
101
+ step: 1,
102
+ signal: { aborted: false },
103
+ })
104
+ const datedText = dated.messages
105
+ .filter((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
106
+ .map((message) => String(message?.content?.[0]?.text || ''))
107
+ .join('\n')
108
+ assert.ok(datedText.includes(userFactId), datedText)
109
+ assert.match(datedText, /date=2026-11-07/, 'the resolved absolute date reaches the prompt')
110
+ assert.match(datedText, /source=assistant_said/)
111
+ assert.match(datedText, /speaker=assistant/)
112
+ // The user message is untouched and the plugin message comes before it.
113
+ assert.equal(dated.messages.at(-1).source.kind, 'user')
114
+ assert.equal(dated.messages.at(-1).content[0].text, dateUser.content[0].text)
115
+
116
+ const floorUser = {
117
+ id: 'chain-u2', role: 'user', source: { kind: 'user' },
118
+ content: [{ type: 'text', text: '客厅地板到底是什么颜色,前后说法不一样。' }],
119
+ }
120
+ const conflicted = await inject.injectForStep({
121
+ agent,
122
+ decision: { kind: 'enter', messages: [floorUser] },
123
+ turn: 2,
124
+ step: 1,
125
+ signal: { aborted: false },
126
+ })
127
+ const conflictText = conflicted.messages
128
+ .filter((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
129
+ .map((message) => String(message?.content?.[0]?.text || ''))
130
+ .join('\n')
131
+ assert.match(conflictText, /冲突 · home:living_floor_color/, conflictText)
132
+ assert.ok(conflictText.includes(floorA) && conflictText.includes(floorB))
133
+
134
+ // 6. Observability: getState exposes the recall cache counters, including staleSkipped.
135
+ const view = await dispatch({}, 'getState', { sessionId })
136
+ assert.equal(typeof view.recallCache, 'object')
137
+ for (const key of ['hits', 'misses', 'evictions', 'errors', 'staleSkipped']) {
138
+ assert.equal(typeof view.recallCache[key], 'number', key)
139
+ }
140
+ })
@@ -0,0 +1,134 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-temporal-fields-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ let seq = 0
18
+ function session(name, sceneTime = '2026-11-06T04:00:00.000Z') {
19
+ seq += 1
20
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
21
+ const sessionId = `${name}-${seq}`
22
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
23
+ state.setSessionBinding(sessionId, { sceneTime })
24
+ return {
25
+ sessionId,
26
+ cwd,
27
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
28
+ }
29
+ }
30
+
31
+ function index(sessionId) {
32
+ const binding = state.getSessionBinding(sessionId)
33
+ return state.loadPrivateIndex(binding.libraryId)
34
+ }
35
+
36
+ test('a relative date is resolved against sceneTime and stored as fields', async () => {
37
+ const { exec, sessionId } = session('fields-relative')
38
+ const { id, entry } = await memory.privateRemember({
39
+ exec, title: '明天出门带伞', content: '她说 明天 去学校门口见面。',
40
+ })
41
+ assert.equal(entry.absolute_date, '2026-11-07')
42
+ assert.equal(entry.date_precision, 'day')
43
+ assert.equal(entry.date_source, 'relative')
44
+ assert.equal(entry.event_time, '2026-11-06T04:00:00.000Z')
45
+ assert.equal(entry.observed_at, '2026-11-06T04:00:00.000Z')
46
+ assert.equal(entry.content, '她说 明天 去学校门口见面。', 'the original wording is kept verbatim')
47
+ const onDisk = index(sessionId).entries[id]
48
+ assert.equal(onDisk.absolute_date, '2026-11-07', 'fields survive the index round trip')
49
+ })
50
+
51
+ test('context.occurredAt overrides sceneTime for the same write', async () => {
52
+ const { exec } = session('fields-occurred')
53
+ const { entry } = await memory.privateRemember({
54
+ exec, title: '后天交材料', content: '后天把材料交到教务处。',
55
+ context: { occurredAt: '2026-12-30T12:00:00+08:00' },
56
+ })
57
+ assert.equal(entry.absolute_date, '2027-01-01', 'crosses the year boundary in the scene time zone')
58
+ assert.equal(entry.observed_at, '2026-12-30T04:00:00.000Z')
59
+ })
60
+
61
+ test('month-end and unresolved relative wording are marked, not guessed', async () => {
62
+ const { exec } = session('fields-precision')
63
+ const monthEnd = await memory.privateRemember({ exec, title: '月底对账', content: '月底前把账对完。' })
64
+ assert.equal(monthEnd.entry.absolute_date, '2026-11-30')
65
+ assert.equal(monthEnd.entry.date_precision, 'month')
66
+
67
+ const fuzzy = await memory.privateRemember({ exec, title: '下周再说', content: '下周再讨论排期。' })
68
+ assert.equal(fuzzy.entry.absolute_date, undefined)
69
+ assert.equal(fuzzy.entry.date_precision, 'unknown')
70
+ assert.equal(fuzzy.entry.date_source, 'relative')
71
+
72
+ const none = await memory.privateRemember({ exec, title: '窗户开着', content: '窗外的雨停了。' })
73
+ assert.equal(none.entry.absolute_date, undefined)
74
+ assert.equal(none.entry.date_precision, undefined)
75
+ })
76
+
77
+ test('an explicit absolute_date overrides prose and an impossible date is refused', async () => {
78
+ const { exec } = session('fields-explicit')
79
+ const { entry } = await memory.privateRemember({
80
+ exec, title: '聚会', content: '她说 明天 见。', absoluteDate: '2026-11-20',
81
+ })
82
+ assert.equal(entry.absolute_date, '2026-11-20')
83
+ assert.equal(entry.date_source, 'explicit')
84
+ await assert.rejects(
85
+ () => memory.privateRemember({ exec, title: '错日期', content: '测试。', absoluteDate: '2026-02-30' }),
86
+ /absolute_date must be YYYY-MM-DD/,
87
+ )
88
+ })
89
+
90
+ test('valid_from / valid_to hide an entry outside its window and never hide old entries without them', async () => {
91
+ const { exec, sessionId } = session('fields-validity')
92
+ const expired = await memory.privateRemember({
93
+ exec, title: '旧地址', content: '她住在旧公寓。', absoluteDate: '2026-10-01', validTo: '2026-10-31',
94
+ })
95
+ const upcoming = await memory.privateRemember({
96
+ exec, title: '新地址', content: '她下个月搬去新公寓。', absoluteDate: '2026-12-01', validFrom: '2026-12-01',
97
+ })
98
+ const current = await memory.privateRemember({
99
+ exec, title: '当前住处', content: '她现在住在河边的房子。', absoluteDate: '2026-11-01', validFrom: '2026-11-01', validTo: '2026-11-30',
100
+ })
101
+ const legacy = await memory.privateRemember({ exec, title: '没有日期的旧条目', content: '窗户是朝东的。' })
102
+ assert.equal(expired.entry.valid_to, '2026-10-31')
103
+ assert.equal(upcoming.entry.valid_from, '2026-12-01')
104
+
105
+ const currentEligible = memory.isMemoryEligible(current.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') })
106
+ assert.equal(currentEligible, true)
107
+ assert.equal(memory.isMemoryEligible(expired.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
108
+ assert.equal(memory.isMemoryEligible(upcoming.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
109
+ assert.equal(memory.isMemoryEligible(legacy.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), true)
110
+
111
+ const recalled = await memory.privateRecall({ exec, query: '公寓 住处 窗户', topK: 10, relevanceThreshold: 0 })
112
+ const ids = recalled.files.map((file) => file.name)
113
+ assert.ok(ids.includes(current.id), 'a valid entry is recalled')
114
+ assert.ok(ids.includes(legacy.id), 'an entry without a window is not filtered')
115
+ assert.ok(!ids.includes(expired.id), 'a past valid_to is filtered')
116
+ assert.ok(!ids.includes(upcoming.id), 'a future valid_from is filtered')
117
+ assert.equal(index(sessionId).entries[expired.id].valid_to, '2026-10-31', 'filtering is read-only')
118
+ })
119
+
120
+ test('rewriting the text re-derives the date; the query resolves relative words too', async () => {
121
+ const { exec } = session('fields-query')
122
+ const dated = await memory.privateRemember({
123
+ exec, title: '带伞', content: '出门要带伞,午后有雨。', absoluteDate: '2026-11-07',
124
+ })
125
+ // The body never says "明天"; only the resolved date can connect the query to it.
126
+ const recalled = await memory.privateRecall({ exec, query: '明天天气怎么样', topK: 10, relevanceThreshold: 0 })
127
+ assert.ok(recalled.files.some((file) => file.name === dated.id), 'the query resolves 明天 to 2026-11-07')
128
+
129
+ const updated = await memory.privateUpdate({
130
+ exec, id: dated.id, content: '后天出门要带伞,午后有雨。',
131
+ })
132
+ assert.equal(updated.entry.absolute_date, '2026-11-08', 'a rewrite re-resolves the date')
133
+ assert.equal(updated.entry.content, '后天出门要带伞,午后有雨。')
134
+ })
@@ -0,0 +1,33 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-resident-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const memu = await import('../lib/memu.js')
11
+
12
+ test.after(() => {
13
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
14
+ })
15
+
16
+ test('the resident singleton is declared before its first executable use', () => {
17
+ const source = fs.readFileSync(new URL('../lib/memu.js', import.meta.url), 'utf8')
18
+ const declaration = /^let residentRecord = null$/m.exec(source)
19
+ assert.ok(declaration, 'lib/memu.js must declare `let residentRecord = null`')
20
+ // Comments may mention the name before the declaration; the first executable use
21
+ // (stopResident) must sit after it, or ESM strict mode throws ReferenceError.
22
+ const firstCodeUse = source.indexOf('residentRecord === record')
23
+ assert.ok(firstCodeUse > declaration.index, 'the first executable use must come after the declaration')
24
+ })
25
+
26
+ test('closing and prewarming the resident engine does not throw ReferenceError', async () => {
27
+ assert.equal(typeof memu.closeMemuResident, 'function')
28
+ assert.equal(memu.closeMemuResident(), 0, 'closing a non-existent resident is a no-op')
29
+ assert.equal(memu.closeMemuResident(), 0, 'close is idempotent')
30
+ // Default route is lexical, so prewarm returns false without spawning. The point is
31
+ // that the function body runs and the module-level singleton is reachable.
32
+ assert.equal(await memu.prewarmMemuResident(), false)
33
+ })
@@ -0,0 +1,51 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-prompt-128-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const prompts = await import('../lib/prompts.js')
11
+ const { buildWorkerBrief } = await import('../lib/consolidation-worker.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ const policyVars = { shortTermTtlHours: 72, mustRememberCap: 12, unpinBudget: 2, anchorTokens: 800 }
18
+ const guideVars = { mustRememberCap: 12, unpinBudget: 2, shortTermTtlHours: 72, anchorTokens: 800, turnTokens: 800 }
19
+
20
+ test('the RP guide asks for scene-time dates, two versions and speaker separation', () => {
21
+ const text = prompts.loadPromptForDomain('system-guide', guideVars, 'rp').text
22
+ assert.match(text, /相对日期先按这一轮的时间换算/)
23
+ assert.match(text, /记忆里有两版说法时/)
24
+ assert.match(text, /分清是谁说的/)
25
+ })
26
+
27
+ test('the RP policy teaches the S1–S4 write fields', () => {
28
+ const text = prompts.loadPromptForDomain('private-policy', policyVars, 'rp').text
29
+ assert.match(text, /absolute_date/)
30
+ assert.match(text, /date_precision=unknown/)
31
+ assert.match(text, /conflicts_with/)
32
+ assert.match(text, /supersedes/)
33
+ assert.match(text, /commitment/)
34
+ assert.match(text, /assistant_said/)
35
+ })
36
+
37
+ test('the consolidation page and worker brief carry the same field contract', () => {
38
+ const text = prompts.loadPromptForDomain('private-consolidation', {
39
+ libraryName: '测试库', domain: 'rp', mustRememberCap: 12,
40
+ }, 'rp').text
41
+ for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'commitment']) {
42
+ assert.ok(text.includes(needle), `consolidation prompt is missing ${needle}`)
43
+ }
44
+ const brief = buildWorkerBrief({
45
+ snapshot: { fromSeq: 1, throughSeq: 2, eventCount: 2, hash: 'prompt-128' },
46
+ probe: { tools: ['memu_private_remember', 'memu_private_update'] },
47
+ })
48
+ for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'supersedes', 'commitment', 'assistant_said', '每窗最多新增 10 条']) {
49
+ assert.ok(brief.includes(needle), `worker brief is missing ${needle}`)
50
+ }
51
+ })
@@ -0,0 +1,62 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { detectQueryIntent, decomposeQuery, extractQueryEntities } from '../lib/text-retrieval.js'
5
+ import { intentTopK, recallIntentBudget, RECALL_INTENT_TOPK } from '../lib/budget.js'
6
+
7
+ const NOW = new Date('2026-11-06T04:00:00Z')
8
+
9
+ test('intent detection covers the six recall strategies', () => {
10
+ assert.equal(detectQueryIntent('我们上次说的地板颜色到底哪个对'), 'conflict')
11
+ assert.equal(detectQueryIntent('你答应过我什么时候查机票'), 'commitment')
12
+ assert.equal(detectQueryIntent('那件事你别告诉别人'), 'boundary')
13
+ assert.equal(detectQueryIntent('下周三是几号'), 'date')
14
+ assert.equal(detectQueryIntent('今天有什么安排'), 'date')
15
+ assert.equal(detectQueryIntent('"林眠"住在哪里'), 'entity')
16
+ assert.equal(detectQueryIntent('窗外的雨停了'), 'general')
17
+ assert.equal(detectQueryIntent(''), 'general')
18
+ })
19
+
20
+ test('queries are decomposed into dates, entities and an expanded search string', () => {
21
+ const decomposed = decomposeQuery('下周三跟"林眠"约了几点', null, {
22
+ now: NOW, knownEntities: ['林眠', 'Yuike'],
23
+ })
24
+ assert.equal(decomposed.intent, 'date', 'a time word outranks the quoted entity')
25
+ assert.deepEqual(decomposed.dates, ['2026-11-11'])
26
+ assert.deepEqual(decomposed.entities, ['林眠'])
27
+ assert.match(decomposed.expanded, /2026-11-11/)
28
+ assert.match(decomposed.expanded, /林眠/)
29
+
30
+ const named = decomposeQuery('Yuike 上次提到的地点', null, { now: NOW, knownEntities: ['Yuike', '林眠'] })
31
+ assert.equal(named.intent, 'date', '上次 makes this a time question')
32
+ assert.deepEqual(named.entities, ['Yuike'])
33
+
34
+ const entity = decomposeQuery('"林眠"住在哪里', null, { now: NOW })
35
+ assert.equal(entity.intent, 'entity')
36
+ assert.deepEqual(entity.entities, ['林眠'])
37
+
38
+ assert.deepEqual(decomposeQuery('').dates, [])
39
+ assert.deepEqual(decomposeQuery('', null, { now: NOW }).entities, [])
40
+ })
41
+
42
+ test('entity extraction only trusts explicit markers or a known-entity table', () => {
43
+ assert.deepEqual(extractQueryEntities('“Yuike”和「林眠」都在'), ['Yuike', '林眠'])
44
+ assert.deepEqual(extractQueryEntities('@yuike 说了什么'), ['yuike'])
45
+ assert.deepEqual(extractQueryEntities('Yuike 说了什么', { knownEntities: ['Yuike'] }), ['Yuike'])
46
+ assert.deepEqual(extractQueryEntities('一个普通句子'), [])
47
+ assert.deepEqual(extractQueryEntities('“x”'), [], 'one character is not an entity handle')
48
+ })
49
+
50
+ test('intent budgets raise the candidate count without overriding a larger explicit topK', () => {
51
+ assert.deepEqual(RECALL_INTENT_TOPK, { general: 5, date: 8, entity: 8, conflict: 6, commitment: 5, boundary: 5 })
52
+ assert.equal(intentTopK('general', 3), 3)
53
+ assert.equal(intentTopK('general', 0), 5)
54
+ assert.equal(intentTopK('date', 3), 8)
55
+ assert.equal(intentTopK('entity', 5), 8)
56
+ assert.equal(intentTopK('conflict', 5), 6)
57
+ assert.equal(intentTopK('date', 10), 10, 'a deliberate larger request is kept')
58
+ assert.equal(intentTopK('date', 50), 20, 'but never unbounded')
59
+ assert.equal(intentTopK('unknown', 4), 4)
60
+ assert.deepEqual(recallIntentBudget('conflict', { privateTopK: 4 }), { intent: 'conflict', topK: 6 })
61
+ assert.deepEqual(recallIntentBudget('nope', { privateTopK: 2 }), { intent: 'general', topK: 2 })
62
+ })