dsh-memu-memory 1.3.15 → 1.4.1

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 (73) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +49 -1
  3. package/README.md +4 -1
  4. package/README.zh.md +4 -1
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/host-adaptation.md +52 -36
  7. package/docs/host-versions.md +120 -0
  8. package/docs/memory-semantics.md +4 -2
  9. package/docs/pending-work.md +51 -0
  10. package/docs/troubleshooting.md +41 -2
  11. package/lib/auto-link/candidates.js +4 -1
  12. package/lib/auto-link/decide.js +1 -1
  13. package/lib/auto-link/normalize.js +2 -2
  14. package/lib/auto-link/terminology.js +31 -1
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +53 -6
  17. package/lib/consolidation-snapshot.js +7 -1
  18. package/lib/consolidation-worker.js +11 -3
  19. package/lib/curator.js +17 -5
  20. package/lib/cycle.js +75 -4
  21. package/lib/diagnostics.js +10 -0
  22. package/lib/entity-repair.js +285 -0
  23. package/lib/environment-check.js +72 -3
  24. package/lib/global-graph.js +11 -2
  25. package/lib/graph.js +32 -8
  26. package/lib/host-surface.js +30 -0
  27. package/lib/index.js +120 -3
  28. package/lib/inject.js +142 -8
  29. package/lib/memory.js +72 -0
  30. package/lib/private-links.js +12 -0
  31. package/lib/private.js +49 -13
  32. package/lib/prompts/private-consolidation.coding.md +3 -1
  33. package/lib/prompts/private-consolidation.md +2 -0
  34. package/lib/prompts/private-consolidation.mixed.md +2 -0
  35. package/lib/prompts/private-consolidation.rp.md +2 -0
  36. package/lib/prompts/system-guide.coding.md +8 -2
  37. package/lib/prompts/system-guide.md +6 -0
  38. package/lib/prompts/system-guide.mixed.md +11 -0
  39. package/lib/prompts/system-guide.rp.md +6 -0
  40. package/lib/rpc.js +48 -10
  41. package/lib/state.js +5 -1
  42. package/lib/turn-log.js +34 -11
  43. package/lib/worker-pool.js +11 -7
  44. package/package.json +16 -1
  45. package/scripts/chain-matrix.mjs +4 -0
  46. package/scripts/check-doc-drift.mjs +194 -0
  47. package/scripts/entity-dedupe.mjs +110 -0
  48. package/tests/auto-link-candidates.test.mjs +22 -9
  49. package/tests/auto-link-decide.test.mjs +59 -59
  50. package/tests/auto-link-migration.test.mjs +4 -4
  51. package/tests/client-render.test.mjs +112 -1
  52. package/tests/consolidation-fork.test.mjs +20 -1
  53. package/tests/curator-probe.test.mjs +19 -1
  54. package/tests/cycle.test.mjs +2 -2
  55. package/tests/diagnostics.test.mjs +21 -0
  56. package/tests/doc-drift.test.mjs +122 -2
  57. package/tests/entity-merge.test.mjs +17 -0
  58. package/tests/environment-check.test.mjs +28 -0
  59. package/tests/global-graph.test.mjs +16 -0
  60. package/tests/global-lifecycle.test.mjs +24 -4
  61. package/tests/graph-cascade.test.mjs +111 -0
  62. package/tests/hybrid-recall.test.mjs +1 -1
  63. package/tests/inject-guide.test.mjs +108 -1
  64. package/tests/managed-memory.test.mjs +7 -7
  65. package/tests/private-links.test.mjs +12 -0
  66. package/tests/prompts.test.mjs +30 -0
  67. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  68. package/tests/salience-domain.test.mjs +34 -0
  69. package/tests/settings-plumbing.test.mjs +2 -0
  70. package/tests/stale-maintenance.test.mjs +131 -0
  71. package/tests/tools.test.mjs +1 -1
  72. package/tests/turn-log.test.mjs +13 -0
  73. package/tests/webui-auth.test.mjs +58 -0
@@ -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')
@@ -137,3 +137,37 @@ test('candidateSeedEvents honours domain without changing defaults', () => {
137
137
  const coding = candidateSeedEvents(events, { domain: 'coding' })
138
138
  assert.deepEqual(coding.map((event) => event.seq), [0, 1, 2, 3, 4, 5, 6, 7, 8], 'coding keeps the English turn and its neighbours')
139
139
  })
140
+
141
+ test('coding seed selection keeps tool turns and weak signals; general keeps neither', () => {
142
+ const group = (base, text, withTool) => {
143
+ const events = [
144
+ { type: 'turn/start', seq: base, data: { turn: base } },
145
+ { type: 'user/message', seq: base + 1, data: { source: { kind: 'user' }, content: [{ type: 'text', text }] } },
146
+ ]
147
+ if (withTool) events.push({ type: 'tool/call', seq: base + 2, data: { callId: 'c' + base, name: 'edit', arguments: '{}' } })
148
+ events.push({ type: 'turn/end', seq: base + 3, data: { turn: base, reason: { kind: 'completed' } } })
149
+ return events
150
+ }
151
+ const events = [
152
+ ...group(0, '改一下那个函数', true),
153
+ ...group(10, '闲聊而已', false),
154
+ ...group(20, '我答应月底之前把伞还给你', false),
155
+ ...group(30, '第 0 段普通的记录', false),
156
+ ...group(40, '第 1 段普通的记录', false),
157
+ ...group(50, '第 2 段普通的记录', false),
158
+ ...group(60, '重构一下这段', false),
159
+ ...group(70, '第 3 段普通的记录', false),
160
+ ...group(80, '第 4 段普通的记录', false),
161
+ ...group(90, '第 5 段普通的记录', false),
162
+ ...group(100, '第 6 段普通的记录', false),
163
+ ]
164
+ const seqs = (list) => new Set(list.map((event) => event.seq))
165
+ const coding = seqs(candidateSeedEvents(events, { domain: 'coding' }))
166
+ const general = seqs(candidateSeedEvents(events, { domain: 'general' }))
167
+ assert.ok(coding.has(1), 'coding keeps a turn whose only evidence is a tool call')
168
+ assert.ok(coding.has(61), 'coding keeps a single weak signal (one point)')
169
+ assert.ok(coding.has(11), 'the neighbour of a kept turn stays')
170
+ assert.equal(general.has(1), false, 'general still drops the tool-only turn')
171
+ assert.equal(general.has(61), false, 'general still needs two points')
172
+ assert.ok(general.has(21), 'a strong signal keeps the turn for general too')
173
+ })
@@ -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 () => {
@@ -0,0 +1,131 @@
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
+ // 逾期与过时的收尾:过期草稿的保留期归档、逾期承诺的周期提示,
8
+ // 以及整理任务书里的欠账清单。三者都只做"标出来",不替人裁决事实。
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-stale-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+
13
+ const state = await import('../lib/state.js')
14
+ const memory = await import('../lib/memory.js')
15
+ const cycle = await import('../lib/cycle.js')
16
+ const activity = await import('../lib/activity-log.js')
17
+ const privateMod = await import('../lib/private.js')
18
+
19
+ test.after(() => {
20
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
21
+ })
22
+
23
+ function dayKey(offsetDays) {
24
+ const date = new Date()
25
+ date.setDate(date.getDate() + offsetDays)
26
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
27
+ }
28
+
29
+ function isoDaysAgo(days) {
30
+ return new Date(Date.now() - days * 86_400_000).toISOString()
31
+ }
32
+
33
+ function bindingFor(sessionId, folder) {
34
+ return state.ensureSession(sessionId, { cwd: path.join(home, folder), agentPreset: 'coding' })
35
+ }
36
+
37
+ function putEntry(binding, id, patch = {}) {
38
+ const index = state.loadPrivateIndex(binding.libraryId)
39
+ index.entries[id] = {
40
+ track: 'memory',
41
+ layer: 'long_term',
42
+ title: id,
43
+ content: 'body of ' + id,
44
+ status: 'active',
45
+ createdAt: isoDaysAgo(20),
46
+ updatedAt: isoDaysAgo(20),
47
+ ...patch,
48
+ }
49
+ state.savePrivateIndex(binding.libraryId, index)
50
+ }
51
+
52
+ function entryOf(binding, id) {
53
+ return state.loadPrivateIndex(binding.libraryId).entries[id]
54
+ }
55
+
56
+ test('expired drafts are archived after the retention window, never deleted', () => {
57
+ const binding = bindingFor('stale-archive', 'proj-archive')
58
+ putEntry(binding, 'draft-old', { layer: 'short_term', status: 'expired', expiredAt: isoDaysAgo(40), expiresAt: isoDaysAgo(40) })
59
+ putEntry(binding, 'draft-legacy', { layer: 'short_term', status: 'expired', expiresAt: isoDaysAgo(45) })
60
+ putEntry(binding, 'draft-fresh', { layer: 'short_term', status: 'expired', expiredAt: isoDaysAgo(5), expiresAt: isoDaysAgo(5) })
61
+ putEntry(binding, 'still-active', { layer: 'short_term', expiresAt: isoDaysAgo(1) })
62
+
63
+ const sweep = memory.archiveExpiredDrafts()
64
+ const archived = new Set(sweep.archived.map((row) => row.id))
65
+ assert.ok(archived.has('draft-old'), 'past the retention window → archived')
66
+ assert.ok(archived.has('draft-legacy'), 'legacy expired rows fall back to expiresAt')
67
+ assert.equal(archived.has('draft-fresh'), false, 'inside the retention window → left for promotion')
68
+ assert.equal(archived.has('still-active'), false, 'a live draft is not touched')
69
+
70
+ const old = entryOf(binding, 'draft-old')
71
+ assert.equal(old.status, 'archived')
72
+ assert.ok(old.archivedAt)
73
+ assert.ok(old.content.includes('body of draft-old'), 'archiving keeps the text')
74
+ assert.equal(entryOf(binding, 'draft-fresh').status, 'expired', 'status is unchanged while inside the window')
75
+ })
76
+
77
+ test('overdueOpenCommitments only returns open commitments past due by the threshold', () => {
78
+ const binding = bindingFor('stale-overdue', 'proj-overdue')
79
+ putEntry(binding, 'owes-10d', { commitment: { action: '陪复习', counterparty: '主人', due_at: dayKey(-10), status: 'open' } })
80
+ putEntry(binding, 'owes-2d', { commitment: { action: '买猫粮', due_at: dayKey(-2), status: 'open' } })
81
+ putEntry(binding, 'due-tomorrow', { commitment: { action: '交周报', due_at: dayKey(1), status: 'open' } })
82
+ putEntry(binding, 'already-done', { commitment: { action: '回消息', due_at: dayKey(-9), status: 'done' } })
83
+ putEntry(binding, 'marginal', { marginalized: true, commitment: { action: '旧账', due_at: dayKey(-9), status: 'open' } })
84
+
85
+ const rows = memory.overdueOpenCommitments({ libraryId: binding.libraryId, minOverdueDays: 7 })
86
+ const ids = rows.map((row) => row.id)
87
+ assert.deepEqual(ids, ['owes-10d'])
88
+ assert.equal(rows[0].daysOverdue, 10)
89
+
90
+ const loose = memory.overdueOpenCommitments({ libraryId: binding.libraryId, minOverdueDays: 0 }).map((row) => row.id)
91
+ assert.ok(loose.includes('owes-2d'), 'minOverdueDays=0 lists every overdue promise')
92
+ assert.equal(loose.includes('due-tomorrow'), false)
93
+ assert.equal(loose.includes('already-done'), false)
94
+ assert.equal(loose.includes('marginal'), false)
95
+ })
96
+
97
+ test('the cycle notes overdue promises once per week and never closes them itself', () => {
98
+ const binding = bindingFor('stale-pass', 'proj-pass')
99
+ putEntry(binding, 'promise-1', { title: '陪主人复习', commitment: { action: '陪复习', counterparty: '主人', due_at: dayKey(-12), status: 'open' } })
100
+ putEntry(binding, 'promise-2', { title: '寄相册', commitment: { action: '寄相册', due_at: dayKey(-8), status: 'open' } })
101
+
102
+ const first = cycle.runOverdueReviewPass(null, { now: Date.now() })
103
+ assert.ok(first.noted >= 2, 'both promises are past the threshold')
104
+ const entry = activity.listEvents({ kind: 'check', limit: 50 }).find((row) => String(row.message).includes('欠账待结案'))
105
+ assert.ok(entry, 'a check entry is written to the activity log')
106
+ assert.ok(entry.detail.ids.includes('promise-1'))
107
+
108
+ const second = cycle.runOverdueReviewPass(null, { now: Date.now() })
109
+ assert.equal(second.noted, 0, 'the same week must not repeat the note')
110
+
111
+ const later = cycle.runOverdueReviewPass(null, { now: Date.now() + 8 * 86_400_000 })
112
+ assert.ok(later.noted >= 2, 'after the repeat window it comes back')
113
+
114
+ assert.equal(entryOf(binding, 'promise-1').commitment.status, 'open', 'status is evidence-driven, never auto-closed')
115
+ })
116
+
117
+ test('the consolidation catalog lists overdue promises so the worker can close them with evidence', () => {
118
+ const binding = bindingFor('stale-catalog', 'proj-catalog')
119
+ putEntry(binding, 'catalog-owe', {
120
+ title: '答应陪主人复习',
121
+ commitment: { action: '陪复习', counterparty: '主人', due_at: dayKey(-5), status: 'open' },
122
+ })
123
+ const event = privateMod.memoryCatalogEvent({ ...binding, sessionId: 'stale-catalog' })
124
+ assert.ok(event, 'the catalog event is produced')
125
+ const text = String(event.data?.content?.[0]?.text || '')
126
+ assert.ok(text.includes('欠账'), 'the catalog carries an overdue section')
127
+ assert.ok(text.includes('[catalog-owe]'))
128
+ assert.ok(text.includes('已逾期 5 天'))
129
+ assert.ok(text.includes('对 主人:陪复习'))
130
+ assert.ok(text.includes('done'), 'the instruction names the closing statuses')
131
+ })
@@ -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.'],
@@ -472,3 +472,16 @@ test('a deleted session (sessionGone) loses its log on session/disposed', () =>
472
472
  assert.ok(fs.existsSync(turnLog.turnLogPath('rec-alive')))
473
473
  dispose()
474
474
  })
475
+
476
+ test('coding tool lines keep 600 chars of arguments and error text instead of 160', () => {
477
+ const args = '{"cmd":"npm test -- --grep memory","pad":"' + 'a'.repeat(400) + '"}'
478
+ const tools = [['c1', 'bash', args, 'E'.repeat(800), true]]
479
+ const plain = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary' })[0].tools[0]
480
+ const coding = turnLog.buildTurnRecords(oneTurn({ user: '跑测试', tools }), { tools: 'summary', ...turnLog.turnLogLimits('coding') })[0].tools[0]
481
+ assert.ok(plain.length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
482
+ assert.ok(coding.length > turnLog.TURNLOG_TOOL_LINE_CHARS, 'the coding cap is wider than the default')
483
+ assert.ok(coding.length <= turnLog.TURNLOG_TOOL_LINE_CHARS_CODING + 1)
484
+ assert.ok(coding.includes('npm test'), 'the command survives in coding mode')
485
+ assert.ok(coding.includes('E'.repeat(20)), 'the error output tail survives in coding mode')
486
+ assert.equal(turnLog.turnLogLimits('rp').toolLineChars, turnLog.TURNLOG_TOOL_LINE_CHARS)
487
+ })
@@ -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
+ })