dsh-memu-memory 1.2.7 → 1.2.9

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 (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. package/tests/webui.test.mjs +27 -0
@@ -0,0 +1,146 @@
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-fact-version-'))
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
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
27
+ }
28
+ }
29
+
30
+ function entries(sessionId) {
31
+ const binding = state.getSessionBinding(sessionId)
32
+ return state.loadPrivateIndex(binding.libraryId).entries
33
+ }
34
+
35
+ test('two statements about one fact coexist, cross-linked, with both bodies intact', async () => {
36
+ const { exec, sessionId } = session('fact-conflict')
37
+ const first = await memory.privateRemember({
38
+ exec, title: '客厅地板颜色', content: '客厅地板是木色的,去年刚铺的。',
39
+ factKey: 'home:living_floor_color',
40
+ })
41
+ assert.equal(first.entry.fact_key, 'home:living_floor_color')
42
+ assert.equal(first.entry.version, 1)
43
+
44
+ const second = await memory.privateRemember({
45
+ exec, title: '客厅地板颜色改口', content: '客厅地板不是木色,是灰色瓷砖。',
46
+ factKey: 'home:living_floor_color',
47
+ })
48
+ assert.equal(second.entry.status, 'active', 'a conflict pair is not held for review')
49
+ assert.equal(second.entry.version, 2)
50
+ assert.equal(second.entry.conflicts_with, first.id)
51
+ assert.equal(second.conflictsWith, first.id)
52
+
53
+ const stored = entries(sessionId)
54
+ assert.equal(stored[first.id].status, 'active')
55
+ assert.equal(stored[first.id].conflicts_with, second.id, 'the pair points both ways')
56
+ assert.equal(stored[first.id].content, '客厅地板是木色的,去年刚铺的。', 'the old claim keeps its exact wording')
57
+ assert.equal(stored[second.id].content, '客厅地板不是木色,是灰色瓷砖。')
58
+ })
59
+
60
+ test('explicit supersede retires the old row without deleting its text', async () => {
61
+ const { exec, sessionId } = session('fact-supersede')
62
+ const first = await memory.privateRemember({
63
+ exec, title: '缴费日', content: '物业费每月5号缴。', factKey: 'home:fee_day',
64
+ })
65
+ const second = await memory.privateRemember({
66
+ exec, title: '缴费日补充', content: '物业费每月5号缴,遇节假日顺延。', factKey: 'home:fee_day',
67
+ })
68
+ // The second statement conflicting with the first creates v2; then an explicit
69
+ // correction supersedes v2.
70
+ const third = await memory.privateRemember({
71
+ exec, title: '缴费日最终确认', content: '物业费改成每月10号缴。',
72
+ factKey: 'home:fee_day', supersedes: second.id,
73
+ })
74
+ assert.equal(third.entry.status, 'active')
75
+ assert.equal(third.entry.version, 3)
76
+ assert.equal(third.entry.supersedes, second.id)
77
+ assert.equal(third.supersedes, second.id)
78
+
79
+ const stored = entries(sessionId)
80
+ assert.equal(stored[second.id].status, 'superseded')
81
+ assert.equal(stored[second.id].content, '物业费每月5号缴,遇节假日顺延。', 'the superseded body is still there')
82
+ assert.equal(stored[second.id].valid_to, '2026-11-06')
83
+ assert.equal(stored[second.id].supersededBy, third.id)
84
+ assert.equal(stored[first.id].content, '物业费每月5号缴。')
85
+
86
+ const recalled = await memory.privateRecall({ exec, query: '物业费缴费日', topK: 10, relevanceThreshold: 0 })
87
+ const ids = recalled.files.map((file) => file.name)
88
+ assert.ok(ids.includes(third.id), 'the current version is recallable')
89
+ assert.ok(!ids.includes(second.id), 'the superseded version is not recalled as current truth')
90
+ assert.ok(ids.includes(first.id), 'the earliest version is kept unless it was superseded too')
91
+ })
92
+
93
+ test('a compatible supplement updates the same id and does not create a version', async () => {
94
+ const { exec } = session('fact-supplement')
95
+ const first = await memory.privateRemember({
96
+ exec, title: '咖啡口味', content: '他只喝黑咖啡。', factKey: 'user:coffee',
97
+ })
98
+ const before = entries(exec.agent.session.header.id)[first.id]
99
+ const updated = await memory.privateUpdate({
100
+ exec, id: first.id, content: '他只喝黑咖啡,不加糖也不加奶。',
101
+ })
102
+ assert.equal(updated.id, first.id)
103
+ assert.equal(updated.entry.version, before.version, 'a compatible supplement is not a new version')
104
+ assert.equal(updated.entry.fact_key, 'user:coffee')
105
+ })
106
+
107
+ test('relation targets must exist, be active and share the scope', async () => {
108
+ const { exec, sessionId } = session('fact-targets')
109
+ const active = await memory.privateRemember({ exec, title: '在用的条目', content: '这条还在用。' })
110
+ await assert.rejects(
111
+ () => memory.privateRemember({ exec, title: '坏目标', content: '测试。', conflictsWith: 'mem-nope' }),
112
+ /unknown memory/,
113
+ )
114
+ await memory.privateUpdate({ exec, id: active.id, status: 'archived' })
115
+ await assert.rejects(
116
+ () => memory.privateRemember({ exec, title: '归档目标', content: '测试。', conflictsWith: active.id }),
117
+ /only an active memory/,
118
+ )
119
+ const stored = entries(sessionId)
120
+ assert.ok(!Object.values(stored).some((entry) => entry.title === '坏目标'), 'nothing is written when the target is invalid')
121
+ })
122
+
123
+ test('explicit provenance derives local authority and evidence without extra card text', async () => {
124
+ const { exec } = session('fact-authority')
125
+ const quoted = await memory.privateRemember({
126
+ exec, title: '报价确认', content: '他确认报价是三十万。',
127
+ source: 'user_said', quoteSpan: { seq: 8, turn: 2, textHash: 'abc' },
128
+ })
129
+ assert.equal(quoted.entry.fact_authority, 3)
130
+ assert.deepEqual(quoted.entry.fact_evidence, { seq: 8, turn: 2, textHash: 'abc' })
131
+
132
+ const guessed = await memory.privateRemember({
133
+ exec, title: '报价猜测', content: '我猜报价大概是三十万。',
134
+ })
135
+ assert.equal(guessed.entry.fact_authority, 1)
136
+
137
+ const corrected = await memory.privateUpdate({ exec, id: guessed.id, source: 'user_said' })
138
+ assert.equal(corrected.entry.fact_authority, 3, 'correcting provenance re-derives authority')
139
+ })
140
+
141
+ test('a derived fact_key is stored even without an explicit key', async () => {
142
+ const { exec } = session('fact-derived')
143
+ const { entry } = await memory.privateRemember({ exec, title: '窗台的绿萝', content: '窗台有一盆绿萝。' })
144
+ assert.match(entry.fact_key, /^me:窗台的绿萝$/)
145
+ assert.equal(entry.version, 1)
146
+ })
@@ -0,0 +1,27 @@
1
+ // 分词器的测试场景清单。
2
+ //
3
+ // 这些是测试语料,不是分词器的能力,所以它们住在 tests/ 而不是 lib/:
4
+ // 生产模块导出一份永远只有测试用的常量,等于给打包产物塞了一份无人使用的
5
+ // 字符串表,也让「lib 里每个 export 都有业务调用方」这条自查失效。
6
+
7
+ /**
8
+ * Test cases for different scenarios
9
+ */
10
+ export const TEST_CASES = [
11
+ {
12
+ input: '人工智能是一种技术',
13
+ description: '纯中文短句',
14
+ },
15
+ {
16
+ input: '2026-11-05 AI 技术在快速发展',
17
+ description: '混合日期、英文缩写和中文',
18
+ },
19
+ {
20
+ input: 'Qwen3-Embedding 在 2026 年发布',
21
+ description: '混合产品名、年份和中文',
22
+ },
23
+ {
24
+ input: 'user@example.com 访问 https://example.com',
25
+ description: '邮箱和 URL',
26
+ },
27
+ ]
@@ -81,6 +81,35 @@ test('deleteEntity deletes an unreferenced entity and refuses a referenced one u
81
81
  assert.equal(readStore().entities[kept.id], undefined)
82
82
  })
83
83
 
84
+ test('deleteEntity tolerates a corrupt relationship key and never loses a readable snapshot', () => {
85
+ const target = graph.createEntity({ libraryId, name: 'CorruptTarget' })
86
+ const other = graph.createEntity({ libraryId, name: 'CorruptOther' })
87
+ const outsider = graph.createEntity({ libraryId, name: 'CorruptOutsider' })
88
+ const targetKey = JSON.stringify([target.id, other.id])
89
+ const unrelatedKey = JSON.stringify([other.id, outsider.id])
90
+ const corruptKey = 'not-json\u0000relationship'
91
+ const store = readStore()
92
+ store.relationships[targetKey] = { fromId: target.id, toId: other.id, state: { trust: 0.5 }, history: [], evidenceIds: ['mem-free'] }
93
+ store.relationships[unrelatedKey] = { fromId: other.id, toId: outsider.id, state: { trust: 0.4 }, history: [], evidenceIds: ['mem-free'] }
94
+ store.relationships[corruptKey] = { fromId: 'x', toId: 'y', state: {}, history: [], evidenceIds: [] }
95
+ fs.writeFileSync(entitiesFile, JSON.stringify(store))
96
+ // 未 force:损坏 key 只是读不懂的历史,不能把「仍被引用」的拒绝变成 SyntaxError。
97
+ assert.throws(() => graph.deleteEntity({ libraryId, entityId: target.id }), /relationship snapshot/)
98
+ // force:只删除可读且真的指向 target 的快照;损坏 key 与无关好边原样保留。
99
+ const forced = graph.deleteEntity({ libraryId, entityId: target.id, force: true })
100
+ assert.equal(forced.removedRelationships, 1)
101
+ const after = readStore()
102
+ assert.equal(after.relationships[targetKey], undefined, 'the readable edge to the target is gone')
103
+ assert.ok(after.relationships[unrelatedKey], 'an unrelated readable edge is never silently dropped')
104
+ assert.ok(after.relationships[corruptKey], 'the corrupt key is preserved, not deleted as a side effect')
105
+ // 清理,避免坏 key 影响本文件后续的 prune/list 断言。
106
+ delete after.relationships[unrelatedKey]
107
+ delete after.relationships[corruptKey]
108
+ delete after.entities[other.id]
109
+ delete after.entities[outsider.id]
110
+ fs.writeFileSync(entitiesFile, JSON.stringify(after))
111
+ })
112
+
84
113
  test('force-delete drops relationship snapshots with the entity, and the freed endpoint is collectable', () => {
85
114
  const p = graph.createEntity({ libraryId, name: 'P' })
86
115
  const q = graph.createEntity({ libraryId, name: 'Q' })
@@ -114,6 +114,51 @@ test('relationship snapshots preserve unknowns, evidence, boundaries and previou
114
114
  assert.throws(() => graph.updateRelationship({ libraryId, fromId: a.id, toId: b.id, state: {}, evidenceIds: [], reason: 'no evidence' }), /evidence/)
115
115
  })
116
116
 
117
+ test('relationship history is capped while the current snapshot and evidence stay', () => {
118
+ const a = graph.createEntity({ libraryId, name: 'History A' })
119
+ const b = graph.createEntity({ libraryId, name: 'History B' })
120
+ for (let i = 0; i < 55; i += 1) {
121
+ graph.updateRelationship({
122
+ libraryId, fromId: a.id, toId: b.id,
123
+ state: { trust: 0.5, callbacks: [`callback ${i}`] },
124
+ evidenceIds: ['mem-2'], reason: `Evidence-backed revision ${i} is explicit.`,
125
+ })
126
+ }
127
+ const relation = graph.getRelationship({ libraryId, fromId: a.id, toId: b.id }).relationship
128
+ assert.equal(relation.history.length, 50, 'old revisions are capped')
129
+ assert.equal(relation.revision, 55)
130
+ assert.deepEqual(relation.state.callbacks, ['callback 54'])
131
+ assert.deepEqual(relation.evidenceIds, ['mem-2'])
132
+ })
133
+
134
+ test('relationship retention is a pure wall-clock decay with access reinforcement', () => {
135
+ assert.equal(graph.relationshipRetentionAt(1, 24), 0.5)
136
+ assert.equal(graph.relationshipRetentionAt(1, 48), 0.25)
137
+ assert.equal(graph.relationshipRetentionAt(1, -5), 1, 'clock rollback never boosts retention')
138
+ const accessed = graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: null })
139
+ assert.ok(accessed > 0.5 && accessed < 1)
140
+ assert.equal(graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: new Date(10_000_000 - 1000).toISOString() }), 0.5, 'cooldown blocks a second bump')
141
+ })
142
+
143
+ test('relationship snapshots persist retention, last access and next review', () => {
144
+ const a = graph.createEntity({ libraryId, name: 'Lifecycle A' })
145
+ const b = graph.createEntity({ libraryId, name: 'Lifecycle B' })
146
+ const created = graph.updateRelationship({
147
+ libraryId, fromId: a.id, toId: b.id,
148
+ state: { trust: 0.6 }, evidenceIds: ['mem-2'], reason: 'First explicit evidence for this relation.',
149
+ }).relationship
150
+ assert.equal(created.retention_strength, 1)
151
+ assert.ok(created.last_access_at)
152
+ assert.ok(created.next_review_at)
153
+ const next = graph.updateRelationship({
154
+ libraryId, fromId: a.id, toId: b.id,
155
+ state: { trust: 0.7 }, evidenceIds: ['mem-2'], reason: 'Second explicit evidence for this relation.',
156
+ }).relationship
157
+ assert.ok(next.retention_strength > 0 && next.retention_strength <= 1)
158
+ assert.ok(next.last_access_at >= created.last_access_at)
159
+ assert.equal(next.history[0].retention_strength, 1)
160
+ })
161
+
117
162
  test('a dangling edge is reported as missing, matching the graph view placeholder', () => {
118
163
  // mem-1 was deleted from the index in an earlier test; its inbound edge from
119
164
  // mem-0 remains. getGraph renders a [deleted] placeholder for it, so recall
@@ -1,4 +1,4 @@
1
- // 帮助页与首次安装引导(施工稿 §6.5 包 E)+ 实体孤立分组的渲染断言(§6.4 包 D 第 5 条)。
1
+ // 帮助页与首次安装引导 + 实体孤立分组的渲染断言。
2
2
  // 沿用 client-render.test.mjs 的最小 React 运行时:一个在渲染期 throw 的页面块就是
3
3
  // 白屏,必须在构建期失败而不是静默白板。每一页都渲染,因为块只在选中该页时挂载。
4
4
  import test from 'node:test'
@@ -0,0 +1,112 @@
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('the card orders sides by local authority and observed time', () => {
75
+ const card = conflictCard({
76
+ factKey: 'home:living_floor_color',
77
+ left: { id: 'mem-inferred', entry: { title: '木色', source_kind: 'inferred' } },
78
+ right: { id: 'mem-user', entry: { title: '灰色', source_kind: 'user_said' } },
79
+ })
80
+ assert.match(card, /- A \[mem-user\]/, 'a direct quote is shown first')
81
+ assert.match(card, /- B \[mem-inferred\]/)
82
+ assert.ok(card.length <= 200)
83
+
84
+ const newer = conflictCard({
85
+ factKey: 'x',
86
+ left: { id: 'mem-old', entry: { title: '旧', fact_authority: 1, observed_at: '2026-11-01' } },
87
+ right: { id: 'mem-new', entry: { title: '新', fact_authority: 1, observed_at: '2026-11-05' } },
88
+ })
89
+ assert.match(newer, /- A \[mem-new\]/, 'equal authority falls back to the newer observation')
90
+ })
91
+
92
+ test('a conflict card that cannot fit falls back to the ordinary title cards', async () => {
93
+ const { exec, sessionId } = session('conflict-budget')
94
+ const longTitle = '非常长的旅行目的地描述'.repeat(8)
95
+ const longKey = 'trip:' + 'x'.repeat(180)
96
+ const left = await memory.privateRemember({
97
+ exec, title: longTitle, content: '说好去冰岛。', factKey: longKey,
98
+ })
99
+ const right = await memory.privateRemember({
100
+ exec, title: longTitle + '乙', content: '说好不去冰岛,去挪威。', factKey: longKey,
101
+ })
102
+ const binding = state.getSessionBinding(sessionId)
103
+ // The card's fact_key + two long titles cannot fit; a one-line title card still can.
104
+ const build = await inject.buildRecall(binding, '旅行目的地', 1, {
105
+ ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 150,
106
+ }, exec, sessionId)
107
+ assert.deepEqual(build.errors, [])
108
+ assert.equal(build.text.includes('冲突 ·'), false)
109
+ assert.ok(build.text.length > 0)
110
+ assert.ok(build.ids.length >= 1)
111
+ assert.ok([left.id, right.id].some((id) => build.text.includes(`[${id}]`)))
112
+ })
@@ -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
+ })