dsh-memu-memory 1.2.1 → 1.2.3

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 (105) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +23 -8
  3. package/README.zh.md +16 -6
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/contributing.md +18 -4
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +20 -0
  8. package/docs/host-api.md +22 -1
  9. package/docs/memory-semantics.md +30 -2
  10. package/docs/troubleshooting.md +76 -5
  11. package/lib/activity-log.js +1 -1
  12. package/lib/backup.js +24 -2
  13. package/lib/binding-diagnostics.js +2 -2
  14. package/lib/client.js +1511 -153
  15. package/lib/consolidation-worker.js +30 -8
  16. package/lib/curator-evidence.js +131 -0
  17. package/lib/curator-policy.js +81 -0
  18. package/lib/curator.js +1252 -91
  19. package/lib/cycle.js +12 -1
  20. package/lib/embedding-download.js +39 -4
  21. package/lib/engine.js +6 -3
  22. package/lib/freshness.js +97 -0
  23. package/lib/global-graph.js +282 -0
  24. package/lib/graph.js +295 -11
  25. package/lib/inbound.js +19 -0
  26. package/lib/inject.js +396 -25
  27. package/lib/lexicon.js +1115 -0
  28. package/lib/local-vector-service.js +8 -6
  29. package/lib/managed-runtime.js +33 -2
  30. package/lib/memory.js +365 -34
  31. package/lib/memu.js +2 -2
  32. package/lib/migrate.js +83 -2
  33. package/lib/private-links.js +587 -0
  34. package/lib/private.js +32 -3
  35. package/lib/prompts/global-curator.md +76 -19
  36. package/lib/prompts/private-consolidation.coding.md +4 -1
  37. package/lib/prompts/private-consolidation.md +3 -1
  38. package/lib/prompts/private-consolidation.mixed.md +3 -1
  39. package/lib/prompts/private-consolidation.rp.md +3 -1
  40. package/lib/prompts.js +1 -1
  41. package/lib/rpc.js +589 -10
  42. package/lib/salient-wake.js +402 -0
  43. package/lib/state.js +95 -1
  44. package/lib/text-retrieval.js +661 -0
  45. package/lib/text-similarity.js +36 -18
  46. package/lib/tools.js +168 -10
  47. package/lib/webui/standalone.css +17 -0
  48. package/lib/webui/standalone.js +2 -0
  49. package/package.json +1 -1
  50. package/scripts/acceptance-local.mjs +8 -5
  51. package/scripts/curator-pair-calibrate.mjs +259 -0
  52. package/scripts/drive-session.mjs +853 -0
  53. package/scripts/lexicon-calibrate.mjs +230 -0
  54. package/scripts/lexicon-dedupe.mjs +318 -0
  55. package/scripts/mock-llm.mjs +903 -0
  56. package/tests/absorb-review.test.mjs +353 -0
  57. package/tests/appendix-b2.test.mjs +2 -2
  58. package/tests/client-export.test.mjs +520 -0
  59. package/tests/client-render.test.mjs +32 -4
  60. package/tests/consolidation-fork.test.mjs +14 -12
  61. package/tests/consolidation-snapshot.test.mjs +39 -0
  62. package/tests/curator-absorb.test.mjs +443 -0
  63. package/tests/curator-calibrate.test.mjs +173 -0
  64. package/tests/curator-clusters.test.mjs +281 -0
  65. package/tests/curator-commit.test.mjs +52 -5
  66. package/tests/curator-evidence.test.mjs +102 -0
  67. package/tests/curator-link.test.mjs +316 -0
  68. package/tests/curator-pairing.test.mjs +252 -0
  69. package/tests/curator-probe.test.mjs +15 -6
  70. package/tests/curator-review-mode.test.mjs +314 -0
  71. package/tests/disclosure.test.mjs +2 -1
  72. package/tests/entity-merge.test.mjs +261 -0
  73. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
  74. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
  75. package/tests/fixtures/lexicon-stub.mjs +284 -0
  76. package/tests/fixtures/mock-llm/reply.txt +1 -0
  77. package/tests/freshness.test.mjs +140 -0
  78. package/tests/graph-cascade.test.mjs +35 -2
  79. package/tests/graph.test.mjs +96 -0
  80. package/tests/help-page.test.mjs +415 -0
  81. package/tests/inbound.test.mjs +6 -3
  82. package/tests/inject-guide.test.mjs +28 -0
  83. package/tests/inject.test.mjs +157 -5
  84. package/tests/injection-chain.test.mjs +176 -0
  85. package/tests/lexicon-calibrate.test.mjs +48 -0
  86. package/tests/lexicon-dedupe.test.mjs +171 -0
  87. package/tests/lexicon-frequency.test.mjs +179 -0
  88. package/tests/lexicon-inject.test.mjs +410 -0
  89. package/tests/lexicon-perf.test.mjs +436 -0
  90. package/tests/lexicon-ui.test.mjs +547 -0
  91. package/tests/lexicon.test.mjs +922 -0
  92. package/tests/managed-runtime.test.mjs +32 -0
  93. package/tests/mock-llm.test.mjs +225 -0
  94. package/tests/open-loop-date.test.mjs +406 -0
  95. package/tests/private-links.test.mjs +445 -0
  96. package/tests/prompts.test.mjs +35 -0
  97. package/tests/recall-dedup.test.mjs +33 -4
  98. package/tests/salient-wake.test.mjs +362 -0
  99. package/tests/settings-plumbing.test.mjs +76 -0
  100. package/tests/sidebar.test.mjs +5 -1
  101. package/tests/stubs/dsh-schedule.js +105 -0
  102. package/tests/tool-schema.test.mjs +1 -1
  103. package/tests/tools.test.mjs +112 -3
  104. package/tests/webui-auth.test.mjs +352 -2
  105. package/tests/webui.test.mjs +188 -0
@@ -0,0 +1,362 @@
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-salient-wake-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const wake = await import('../lib/salient-wake.js')
12
+ const activity = await import('../lib/activity-log.js')
13
+ const { fakeScheduleService, wakeContext, scheduleError } = await import('./stubs/dsh-schedule.js')
14
+
15
+ test.after(() => {
16
+ try { state.flushState() } catch {}
17
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
18
+ })
19
+
20
+ // The pass sweeps *every* binding, so a leftover conversation from an earlier test
21
+ // would be armed again under this test's schedule and skew the counts. Each test
22
+ // starts with no conversations and the shipped defaults.
23
+ test.afterEach(() => {
24
+ for (const binding of state.listSessionBindings()) state.deleteSessionBinding(binding.sessionId)
25
+ state.updateSettings({ salientWake: 'off', salientWakeHour: '09:00', salientWakeTimeZone: '' })
26
+ })
27
+
28
+ const local = (y, m, d, h = 8, min = 0) => new Date(y, m - 1, d, h, min, 0, 0)
29
+
30
+ function newSession(id) {
31
+ const binding = state.ensureSession(id, { cwd: path.join(home, 'proj-' + id), agentPreset: 'coding' })
32
+ return { sessionId: id, binding }
33
+ }
34
+
35
+ // Entries go straight into the index: this file tests the wake pass, not the write path.
36
+ function putEntry(libraryId, id, patch = {}) {
37
+ const index = state.loadPrivateIndex(libraryId)
38
+ index.entries[id] = {
39
+ track: 'memory',
40
+ layer: 'long_term',
41
+ title: id,
42
+ content: `body of ${id} — must not reach the prompt`,
43
+ status: 'active',
44
+ createdAt: local(2026, 10, 1, 12).toISOString(),
45
+ updatedAt: local(2026, 10, 1, 12).toISOString(),
46
+ ...patch,
47
+ }
48
+ state.savePrivateIndex(libraryId, index)
49
+ return index.entries[id]
50
+ }
51
+
52
+ const run = (schedule, now, log = () => {}) => wake.runSalientWakePass(wakeContext(schedule), { now, log })
53
+ const titles = (schedule) => schedule.calls.create.map((call) => call.title)
54
+
55
+ test('the settings gate accepts the documented shapes and nothing else', () => {
56
+ assert.equal(state.DEFAULT_SETTINGS.salientWake, 'off')
57
+ assert.equal(state.DEFAULT_SETTINGS.salientWakeHour, '09:00')
58
+ assert.equal(state.DEFAULT_SETTINGS.salientWakeTimeZone, '')
59
+ assert.equal(state.getSettings().salientWake, 'off', 'a fresh install never wakes a conversation')
60
+
61
+ assert.equal(state.updateSettings({ salientWake: 'schedule' }).salientWake, 'schedule')
62
+ assert.throws(() => state.updateSettings({ salientWake: 'on' }), /invalid setting salientWake/)
63
+
64
+ assert.equal(state.updateSettings({ salientWakeHour: '07:05' }).salientWakeHour, '07:05')
65
+ assert.equal(state.updateSettings({ salientWakeHour: '00:00' }).salientWakeHour, '00:00')
66
+ assert.equal(state.updateSettings({ salientWakeHour: '23:59' }).salientWakeHour, '23:59')
67
+ assert.throws(() => state.updateSettings({ salientWakeHour: '7:05' }), /HH:mm/)
68
+ assert.throws(() => state.updateSettings({ salientWakeHour: '24:00' }), /HH:mm/)
69
+ assert.throws(() => state.updateSettings({ salientWakeHour: 9 }), /HH:mm/)
70
+
71
+ assert.equal(state.updateSettings({ salientWakeTimeZone: 'Asia/Shanghai' }).salientWakeTimeZone, 'Asia/Shanghai')
72
+ assert.equal(state.updateSettings({ salientWakeTimeZone: '' }).salientWakeTimeZone, '', 'empty means "follow the system"')
73
+ assert.equal(state.updateSettings({ salientWakeTimeZone: ' ' }).salientWakeTimeZone, '', 'whitespace is empty, not a zone')
74
+ assert.throws(() => state.updateSettings({ salientWakeTimeZone: 'Mars/Olympus' }), /invalid salientWakeTimeZone/)
75
+
76
+ state.updateSettings({ salientWake: 'off', salientWakeHour: '09:00', salientWakeTimeZone: '' })
77
+ })
78
+
79
+ test('off by default: a sweep creates nothing and never asks the host', async () => {
80
+ const { binding } = newSession('wake-off')
81
+ putEntry(binding.libraryId, 'mem-off', { salientDate: '2026-11-02' })
82
+ const schedule = fakeScheduleService()
83
+ const result = await run(schedule, local(2026, 11, 2))
84
+ assert.deepEqual(result, { skipped: 'off' })
85
+ assert.equal(schedule.calls.list.length, 0)
86
+ assert.equal(schedule.calls.create.length, 0)
87
+ assert.equal(schedule.calls.edit.length, 0)
88
+ })
89
+
90
+ test('a host without a schedule service warns once and does not throw', async () => {
91
+ state.updateSettings({ salientWake: 'schedule' })
92
+ const logs = []
93
+ const log = (message) => logs.push(String(message))
94
+ assert.deepEqual(await wake.runSalientWakePass({ get: () => undefined }, { now: local(2026, 11, 2), log }), { skipped: 'service' })
95
+ assert.equal(logs.length, 1)
96
+ assert.match(logs[0], /schedule service/)
97
+
98
+ // A second sweep, and a ctx whose probe itself throws, are both still just a skip.
99
+ assert.deepEqual(await wake.runSalientWakePass({ get: () => undefined }, { now: local(2026, 11, 2), log }), { skipped: 'service' })
100
+ assert.deepEqual(await wake.runSalientWakePass({ get: () => { throw new Error('service "schedule" is not injected') } }, { now: local(2026, 11, 2), log }), { skipped: 'service' })
101
+ assert.equal(logs.length, 1, 'reported once per process, not every five minutes')
102
+
103
+ const events = activity.listEvents({ limit: 50 })
104
+ assert.ok(events.some((event) => event.detail?.trigger === 'wake' && event.detail?.stage === 'service' && event.level === 'warn'))
105
+ state.updateSettings({ salientWake: 'off' })
106
+ })
107
+
108
+ test('today and tomorrow each get one task whose prompt is self-contained', async () => {
109
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00', salientWakeTimeZone: '' })
110
+ const { sessionId, binding } = newSession('wake-main')
111
+ putEntry(binding.libraryId, 'mem-today', { title: '回电话', salientDate: '2026-11-02', openLoop: true })
112
+ putEntry(binding.libraryId, 'mem-tomorrow', { title: '考驾照', salientDate: '2026-11-03' })
113
+ putEntry(binding.libraryId, 'mem-annual', { title: '一起看海', salientDate: '11-02' })
114
+ const schedule = fakeScheduleService()
115
+ const result = await run(schedule, local(2026, 11, 2, 8))
116
+
117
+ assert.deepEqual(result, { created: 2, cleaned: 0, skipped: 0, errors: 0 })
118
+ assert.deepEqual(titles(schedule).sort(), [
119
+ `memu:due:${sessionId}:2026-11-02`,
120
+ `memu:due:${sessionId}:2026-11-03`,
121
+ ])
122
+
123
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
124
+ const today = schedule.calls.create.find((call) => call.title.endsWith(':2026-11-02'))
125
+ assert.deepEqual(today.timing, { kind: 'at', at: { date: '2026-11-02', time: '09:00', time_zone: zone } })
126
+ assert.deepEqual(today.target, { kind: 'session', sessionId })
127
+
128
+ assert.match(today.prompt, /^\[dsh-memu-memory 日期提醒\]/)
129
+ assert.ok(today.prompt.includes('2026-11-02'), 'the delivery day is stated')
130
+ assert.ok(today.prompt.includes('回电话'))
131
+ assert.match(today.prompt, /今天:你之前答应过的「回电话」,就是今天(2026-11-02)/, 'a promise keeps the promise wording')
132
+ assert.match(today.prompt, /明天:考驾照(2026-11-03)/, 'the lead day is shown on the previous day')
133
+ assert.match(today.prompt, /今天:一起看海(每年 11-02)/, 'an annual date says it recurs')
134
+ assert.ok(today.prompt.includes('memu_private_recall'), 'a schedule turn gets no injection, so the prompt points at recall')
135
+ assert.ok(today.prompt.includes('不要重复'))
136
+ assert.ok(!today.prompt.includes('must not reach the prompt'), 'the memory body never lands in the prompt')
137
+
138
+ const tomorrow = schedule.calls.create.find((call) => call.title.endsWith(':2026-11-03'))
139
+ assert.deepEqual(tomorrow.timing.at, { date: '2026-11-03', time: '09:00', time_zone: zone })
140
+ assert.match(tomorrow.prompt, /今天:考驾照(2026-11-03)/, "tomorrow's own task reads from tomorrow's calendar")
141
+ assert.ok(!tomorrow.prompt.includes('回电话'), 'a date that already passed relative to that day is not repeated')
142
+ })
143
+
144
+ test('a second sweep of the same day is idempotent', async () => {
145
+ state.updateSettings({ salientWake: 'schedule' })
146
+ const { sessionId, binding } = newSession('wake-again')
147
+ putEntry(binding.libraryId, 'mem-again', { salientDate: '2026-11-02' })
148
+ const schedule = fakeScheduleService()
149
+ assert.equal((await run(schedule, local(2026, 11, 2, 8))).created, 1)
150
+ const created = schedule.calls.create.length
151
+ const second = await run(schedule, local(2026, 11, 2, 8))
152
+ assert.equal(second.created, 0)
153
+ assert.equal(second.skipped, 1, 'the armed task is the proof, not a reason to arm another')
154
+ assert.equal(schedule.calls.create.length, created)
155
+ assert.equal(schedule.calls.edit.length, 0)
156
+ assert.equal(schedule.tasks.filter((task) => task.title === `memu:due:${sessionId}:2026-11-02`).length, 1)
157
+ })
158
+
159
+ test('an ended task is cleaned up and not re-armed for a slot that has passed', async () => {
160
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00' })
161
+ const { sessionId, binding } = newSession('wake-ended')
162
+ putEntry(binding.libraryId, 'mem-ended', { salientDate: '2026-11-02' })
163
+ const schedule = fakeScheduleService()
164
+ const now = local(2026, 11, 2, 10)
165
+ const title = `memu:due:${sessionId}:2026-11-02`
166
+ const ended = schedule.seed({ title, status: 'ended' })
167
+
168
+ const result = await run(schedule, now)
169
+ assert.equal(result.cleaned, 1)
170
+ assert.equal(result.created, 0, 'ended means this date already delivered; do not arm it twice')
171
+ assert.equal(schedule.taskByTitle(title), null)
172
+ assert.deepEqual(schedule.calls.edit, [{ id: ended.id, action: 'delete' }])
173
+
174
+ const again = await run(schedule, now)
175
+ assert.equal(again.created, 0)
176
+ assert.equal(again.skipped, 1, 'the 09:00 slot is in the past, so cleanup is final')
177
+ })
178
+
179
+ test('a paused task is neither rebuilt nor resumed', async () => {
180
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00' })
181
+ const { sessionId, binding } = newSession('wake-paused')
182
+ putEntry(binding.libraryId, 'mem-paused', { salientDate: '2026-11-02' })
183
+ const schedule = fakeScheduleService()
184
+ const title = `memu:due:${sessionId}:2026-11-02`
185
+ const paused = schedule.seed({ title, status: 'paused' })
186
+
187
+ const result = await run(schedule, local(2026, 11, 2, 8))
188
+ assert.equal(result.created, 0)
189
+ assert.equal(result.skipped, 1)
190
+ assert.equal(result.cleaned, 0)
191
+ assert.equal(schedule.calls.create.length, 0)
192
+ assert.equal(schedule.calls.edit.length, 0, 'the sweep does not touch a paused task at all')
193
+ assert.equal(schedule.taskByTitle(title).status, 'paused', 'a user pause is not the sweep’s to undo')
194
+ assert.equal(paused.status, 'paused')
195
+ })
196
+
197
+ test('archived, secret, pending, superseded, expired, undated and hidden memories arm nothing', async () => {
198
+ state.updateSettings({ salientWake: 'schedule' })
199
+ const { binding } = newSession('wake-filters')
200
+ putEntry(binding.libraryId, 'mem-archived', { salientDate: '2026-11-02', status: 'archived' })
201
+ putEntry(binding.libraryId, 'mem-secret', { salientDate: '2026-11-02', visibility: 'secret' })
202
+ putEntry(binding.libraryId, 'mem-pending', { salientDate: '2026-11-02', status: 'pending_review' })
203
+ putEntry(binding.libraryId, 'mem-superseded', { salientDate: '2026-11-02', status: 'superseded' })
204
+ putEntry(binding.libraryId, 'mem-expired', { salientDate: '2026-11-02', status: 'expired' })
205
+ putEntry(binding.libraryId, 'mem-plain', { title: '普通记忆' })
206
+ putEntry(binding.libraryId, 'mem-far', { salientDate: '2026-12-24' })
207
+ putEntry(binding.libraryId, 'mem-hidden', { salientDate: '2026-11-02', context: { characterId: 'someone-else' } })
208
+
209
+ const schedule = fakeScheduleService()
210
+ const result = await run(schedule, local(2026, 11, 2, 8))
211
+ assert.equal(result.created, 0)
212
+ assert.equal(schedule.calls.create.length, 0)
213
+ assert.equal(schedule.calls.list.length, 0, 'nothing qualified, so the host is not asked for its task table')
214
+
215
+ // A conversation with its private library switched off is not a delivery target either.
216
+ const other = newSession('wake-switched-off')
217
+ putEntry(other.binding.libraryId, 'mem-off-switch', { salientDate: '2026-11-02' })
218
+ state.setSessionBinding('wake-switched-off', { useLibrary: false })
219
+ const after = await run(schedule, local(2026, 11, 2, 8))
220
+ assert.equal(after.created, 0)
221
+ assert.deepEqual(titles(schedule), [])
222
+ })
223
+
224
+ test('an annual MM-DD date fires on its own day, not before', async () => {
225
+ state.updateSettings({ salientWake: 'schedule' })
226
+ const { sessionId, binding } = newSession('wake-annual')
227
+ putEntry(binding.libraryId, 'mem-birthday', { title: '生日', salientDate: '11-03' })
228
+ const schedule = fakeScheduleService()
229
+ const result = await run(schedule, local(2026, 11, 2, 8))
230
+ assert.equal(result.created, 1, 'only tomorrow’s task qualifies: an annual date has no lead day')
231
+ assert.deepEqual(titles(schedule), [`memu:due:${sessionId}:2026-11-03`])
232
+ assert.match(schedule.calls.create[0].prompt, /今天:生日(每年 11-03)/)
233
+ })
234
+
235
+ test('a slot that already passed today skips today but still arms tomorrow', async () => {
236
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00' })
237
+ const { sessionId, binding } = newSession('wake-late')
238
+ putEntry(binding.libraryId, 'mem-late-today', { salientDate: '2026-11-02' })
239
+ putEntry(binding.libraryId, 'mem-late-tomorrow', { salientDate: '2026-11-03' })
240
+ const schedule = fakeScheduleService()
241
+ const result = await run(schedule, local(2026, 11, 2, 10))
242
+ assert.equal(result.created, 1)
243
+ assert.equal(result.skipped, 1)
244
+ assert.deepEqual(titles(schedule), [`memu:due:${sessionId}:2026-11-03`], 'today is past 09:00; the passive injection still covers it')
245
+ })
246
+
247
+ test('an unusable time zone warns once, skips, and does not throw', async () => {
248
+ state.updateSettings({ salientWake: 'schedule', salientWakeTimeZone: '' })
249
+ const { binding } = newSession('wake-zone')
250
+ putEntry(binding.libraryId, 'mem-zone', { salientDate: '2026-11-02' })
251
+
252
+ // Straight into state.json: updateSettings refuses this value, but a hand-edited
253
+ // file (or a future host with no resolved zone) must not crash the sweep.
254
+ state.flushState()
255
+ const file = path.join(home, 'state.json')
256
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
257
+ raw.settings.salientWakeTimeZone = 'Mars/Olympus'
258
+ fs.writeFileSync(file, JSON.stringify(raw), 'utf8')
259
+ state.clearCaches()
260
+
261
+ const schedule = fakeScheduleService()
262
+ const logs = []
263
+ const log = (message) => logs.push(String(message))
264
+ assert.deepEqual(await run(schedule, local(2026, 11, 2, 8), log), { skipped: 'timezone' })
265
+ assert.equal(schedule.calls.list.length, 0, 'nothing is asked of the host without a usable zone')
266
+ assert.equal(schedule.calls.create.length, 0)
267
+ assert.ok(logs.some((line) => /time zone/.test(line)))
268
+ assert.equal(logs.filter((line) => /time zone/.test(line)).length, 1)
269
+
270
+ await run(schedule, local(2026, 11, 2, 8), log)
271
+ assert.equal(logs.filter((line) => /time zone/.test(line)).length, 1, 'the same bad value is reported once')
272
+
273
+ state.updateSettings({ salientWakeTimeZone: '' })
274
+ assert.equal(state.getSettings().salientWakeTimeZone, '')
275
+ })
276
+
277
+ test('refused targets are skipped, real failures are recorded, other sessions continue', async () => {
278
+ state.updateSettings({ salientWake: 'schedule', salientWakeTimeZone: '' })
279
+ const now = local(2026, 11, 2, 8)
280
+ const subagent = newSession('wake-subagent')
281
+ putEntry(subagent.binding.libraryId, 'mem-sub', { salientDate: '2026-11-02' })
282
+ const archived = newSession('wake-archived')
283
+ putEntry(archived.binding.libraryId, 'mem-arch', { salientDate: '2026-11-02' })
284
+ const broken = newSession('wake-broken')
285
+ putEntry(broken.binding.libraryId, 'mem-broken', { salientDate: '2026-11-02' })
286
+ const healthy = newSession('wake-healthy')
287
+ putEntry(healthy.binding.libraryId, 'mem-healthy', { salientDate: '2026-11-02' })
288
+
289
+ const schedule = fakeScheduleService({
290
+ createError: (request) => {
291
+ if (request.title.includes('wake-subagent')) return scheduleError('subagent_session', 'This Session belongs to subagent routing, which never receives reminder delivery.')
292
+ if (request.title.includes('wake-archived')) return scheduleError('invalid_rule', 'target Session "wake-archived" is archived.')
293
+ if (request.title.includes('wake-broken')) throw new Error('schedule domain is closed')
294
+ return null
295
+ },
296
+ })
297
+ const result = await run(schedule, now)
298
+ assert.equal(result.created, 1)
299
+ assert.equal(result.skipped, 2)
300
+ assert.equal(result.errors, 1)
301
+ assert.equal(schedule.calls.create.length, 4, 'every conversation got its own attempt')
302
+ assert.ok(schedule.taskByTitle('memu:due:wake-healthy:2026-11-02'), 'the healthy session still got its task')
303
+ assert.equal(schedule.taskByTitle('memu:due:wake-subagent:2026-11-02'), null)
304
+
305
+ const events = activity.listEvents({ limit: 100 })
306
+ assert.ok(events.some((event) => event.sessionId === 'wake-broken' && event.ok === false && event.detail?.stage === 'create'))
307
+ assert.ok(events.some((event) => event.detail?.code === 'subagent_session' && event.detail?.trigger === 'wake'))
308
+ assert.ok(events.some((event) => event.detail?.code === 'invalid_rule' && event.detail?.trigger === 'wake'))
309
+ })
310
+
311
+ test('a failing list is recorded and reported, not thrown', async () => {
312
+ state.updateSettings({ salientWake: 'schedule' })
313
+ const { binding } = newSession('wake-list-fails')
314
+ putEntry(binding.libraryId, 'mem-list-fails', { salientDate: '2026-11-02' })
315
+ const schedule = fakeScheduleService({ listError: new Error('storage domain is closed') })
316
+ const logs = []
317
+ const result = await run(schedule, local(2026, 11, 2, 8), (message) => logs.push(String(message)))
318
+ assert.deepEqual(result, { created: 0, cleaned: 0, skipped: 0, errors: 1 })
319
+ assert.ok(logs.some((line) => /schedule\.list failed/.test(line)))
320
+ const events = activity.listEvents({ limit: 50 })
321
+ assert.ok(events.some((event) => event.detail?.stage === 'list' && event.ok === false))
322
+ })
323
+
324
+ // 投递按 `at.time_zone` 解释日期与时分,所以「今天是哪天」和「这一刻过去了吗」都必须按那个
325
+ // 时区算。曾按系统墙钟算:配置 UTC 而机器在上海时,今天被算成次日,或把还没到的 09:00(UTC)
326
+ // 当成已过而静默不排。以下三条与时区无关(断言的是绝对瞬间与配置时区的日历日)。
327
+ test('the scheduled instant is the wall clock in the delivery zone, not the machine zone', () => {
328
+ assert.equal(wake.instantInZone('2026-11-01', '09:00', 'UTC'), Date.UTC(2026, 10, 1, 9, 0, 0, 0))
329
+ assert.equal(wake.instantInZone('2026-11-01', '09:00', 'Asia/Shanghai'), Date.UTC(2026, 10, 1, 1, 0, 0, 0))
330
+ // 夏令时:柏林 7 月是 UTC+2、1 月是 UTC+1,同一个 HH:mm 落在不同的绝对瞬间。
331
+ assert.equal(wake.instantInZone('2026-07-15', '09:00', 'Europe/Berlin'), Date.UTC(2026, 6, 15, 7, 0, 0, 0))
332
+ assert.equal(wake.instantInZone('2026-01-15', '09:00', 'Europe/Berlin'), Date.UTC(2026, 0, 15, 8, 0, 0, 0))
333
+ })
334
+
335
+ test('the swept calendar day belongs to the delivery zone', () => {
336
+ const at = Date.UTC(2026, 9, 31, 20, 0, 0, 0)
337
+ assert.equal(wake.dayInZone(at, 'UTC', 0).date, '2026-10-31')
338
+ assert.equal(wake.dayInZone(at, 'UTC', 1).date, '2026-11-01')
339
+ assert.equal(wake.dayInZone(at, 'Asia/Shanghai', 0).date, '2026-11-01', 'the same instant is already the next day there')
340
+ })
341
+
342
+ test('a delivery zone other than the machine still arms today there', async () => {
343
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '21:00', salientWakeTimeZone: 'UTC' })
344
+ const { sessionId, binding } = newSession('wake-zone-utc-today')
345
+ putEntry(binding.libraryId, 'mem-utc-today', { title: '交周报', salientDate: '2026-10-31' })
346
+ const schedule = fakeScheduleService()
347
+ const result = await run(schedule, new Date(Date.UTC(2026, 9, 31, 20, 0, 0, 0)))
348
+ assert.equal(result.created, 1, '21:00 UTC is still ahead, so the day must be armed')
349
+ assert.ok(schedule.taskByTitle(`memu:due:${sessionId}:2026-10-31`), 'the task date is today in the configured zone')
350
+ const created = schedule.calls.create.find((call) => call.title.endsWith(':2026-10-31'))
351
+ assert.deepEqual(created.timing, { kind: 'at', at: { date: '2026-10-31', time: '21:00', time_zone: 'UTC' } })
352
+ })
353
+
354
+ test('a slot already past in the delivery zone is skipped, not sent for rejection', async () => {
355
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '19:00', salientWakeTimeZone: 'UTC' })
356
+ const { binding } = newSession('wake-zone-utc-past')
357
+ putEntry(binding.libraryId, 'mem-utc-past', { title: '交周报', salientDate: '2026-10-31' })
358
+ const schedule = fakeScheduleService()
359
+ const result = await run(schedule, new Date(Date.UTC(2026, 9, 31, 20, 0, 0, 0)))
360
+ assert.equal(result.created, 0, '19:00 UTC on 10-31 already passed; passive injection still covers it')
361
+ assert.equal(result.skipped, 1)
362
+ })
@@ -0,0 +1,76 @@
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
+ // lib/rpc.js 的 setSettings 是 allowlist:没登记的 key 会被静默丢掉,设置页就成了死控件
8
+ // (写了、点了保存、什么也没发生)。resetSettings 另有一份 key 表,两处都得跟着新设置走。
9
+ // 工单 C/D/E 各加了设置项,这条测试就是盯这个失败模式的。
10
+
11
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-settings-plumbing-'))
12
+ process.env.DSH_MEMU_HOME = home
13
+
14
+ const rpc = await import('../lib/rpc.js')
15
+ const state = await import('../lib/state.js')
16
+
17
+ test.after(() => {
18
+ state.flushState()
19
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ const SAMPLE = {
23
+ openLoopRemindDays: 14,
24
+ freshnessHint: false,
25
+ freshnessDays: 90,
26
+ salientWake: 'schedule',
27
+ salientWakeHour: '20:30',
28
+ salientWakeTimeZone: 'Asia/Shanghai',
29
+ }
30
+
31
+ test('each new setting is writable through setSettings', async () => {
32
+ for (const [key, value] of Object.entries(SAMPLE)) {
33
+ const saved = await rpc.dispatch({}, 'setSettings', { patch: { [key]: value } })
34
+ assert.equal(saved[key], value, key + ' must survive the setSettings allowlist')
35
+ }
36
+ })
37
+
38
+ test('the numeric settings clamp to their documented domain instead of vanishing', async () => {
39
+ const low = await rpc.dispatch({}, 'setSettings', { patch: { openLoopRemindDays: 0 } })
40
+ assert.equal(low.openLoopRemindDays, 1)
41
+ const high = await rpc.dispatch({}, 'setSettings', { patch: { freshnessDays: 999999 } })
42
+ assert.equal(high.freshnessDays, 3650)
43
+ })
44
+
45
+ test('resetSettings restores the new defaults, not last release\u2019s tuning', async () => {
46
+ await rpc.dispatch({}, 'setSettings', { patch: SAMPLE })
47
+ const reset = await rpc.dispatch({}, 'resetSettings', {})
48
+ for (const key of Object.keys(SAMPLE)) {
49
+ assert.deepEqual(reset[key], state.DEFAULT_SETTINGS[key], key + ' must be in the reset key list')
50
+ }
51
+ })
52
+
53
+ test('invalid wake configuration is rejected loudly rather than stored', async () => {
54
+ await assert.rejects(
55
+ rpc.dispatch({}, 'setSettings', { patch: { salientWake: 'always' } }),
56
+ /invalid setting salientWake/,
57
+ )
58
+ await assert.rejects(
59
+ rpc.dispatch({}, 'setSettings', { patch: { salientWakeHour: '9:00' } }),
60
+ /salientWakeHour must be HH:mm/,
61
+ )
62
+ await assert.rejects(
63
+ rpc.dispatch({}, 'setSettings', { patch: { salientWakeTimeZone: 'Not/A Zone' } }),
64
+ /invalid salientWakeTimeZone/,
65
+ )
66
+ // 留空是合法配置:跟随系统时区。
67
+ const empty = await rpc.dispatch({}, 'setSettings', { patch: { salientWakeTimeZone: '' } })
68
+ assert.equal(empty.salientWakeTimeZone, '')
69
+ })
70
+
71
+ test('the client settings page exposes a control for every new setting', () => {
72
+ const source = fs.readFileSync(path.resolve(import.meta.dirname, '..', 'lib', 'client.js'), 'utf8')
73
+ for (const key of Object.keys(SAMPLE)) {
74
+ assert.match(source, new RegExp("setSetting\\('" + key + "'"), key + ' has no settings control')
75
+ }
76
+ })
@@ -64,7 +64,11 @@ test('a large library still returns a bounded first screen', async () => {
64
64
  const started = Date.now()
65
65
  const view = await dispatch({}, 'getSidebarState', { sessionId: 'sidebar-2', limit: 100 })
66
66
  const elapsed = Date.now() - started
67
- assert.ok(elapsed < 500, `500-entry library took ${elapsed}ms`)
67
+ // 1500ms,不是 500ms:这条守的是「首屏不能退化成列会话 / 全量扫描」那种**秒级**形状
68
+ // (原始投诉就是打开侧边栏要几秒),不是精细性能基线。同一份代码在本机空载单跑 378–448ms,
69
+ // `npm test` 并行整包跑过 1286–1808ms——500 的预算测的是当时那台机器的空闲程度,
70
+ // 会在别人的机器和更大的测试集上闪红。真正 O(n²) 的实现远超这里,仍然拦得住。
71
+ assert.ok(elapsed < 1500, `500-entry library took ${elapsed}ms`)
68
72
  assert.equal(view.private.active, 500)
69
73
  assert.equal(view.private.items.length, 100, 'the payload is capped, the count is not')
70
74
  })
@@ -0,0 +1,105 @@
1
+ // A fake Host schedule service for work order E. The real service lives in
2
+ // packages/schedule/schedule/src (types.ts / index.ts): `create` returns a catalog
3
+ // entry, `list` returns a *page object* (`{items,shown,total,limit,offset}`, not an
4
+ // array), and `edit({id,action:'delete'})` removes a task. Every call is recorded so
5
+ // a test can assert both the request shape and the number of mutations.
6
+ //
7
+ // Errors are injected per call: pass a function to fail only some requests (the
8
+ // pass handles one conversation at a time, so a test needs "this session throws
9
+ // subagent_session, that one throws internal_error, the third succeeds").
10
+ function maybeThrow(source, request) {
11
+ const error = typeof source === 'function' ? source(request) : source
12
+ if (error) throw error
13
+ return undefined
14
+ }
15
+
16
+ export function scheduleError(code, message = code) {
17
+ const error = new Error(message)
18
+ error.code = code
19
+ return error
20
+ }
21
+
22
+ export function fakeScheduleService({ createError = null, listError = null, editError = null } = {}) {
23
+ const tasks = []
24
+ const calls = { create: [], list: [], edit: [] }
25
+ let seq = 0
26
+
27
+ return {
28
+ tasks,
29
+ calls,
30
+ /** Seeds a task the sweep should discover (active/paused/ended). */
31
+ seed(task) {
32
+ const entry = {
33
+ id: task.id || `sched-seed-${++seq}`,
34
+ title: task.title,
35
+ prompt: task.prompt || '',
36
+ status: task.status || 'active',
37
+ target: task.target || { kind: 'session', sessionId: 'seed' },
38
+ kind: 'at',
39
+ createdAt: new Date().toISOString(),
40
+ }
41
+ tasks.push(entry)
42
+ return entry
43
+ },
44
+ /** Flips a stored task's status, the way a delivery or a user pause would. */
45
+ setStatus(id, status) {
46
+ const task = tasks.find((item) => item.id === id)
47
+ if (!task) throw new Error(`no such task ${id}`)
48
+ task.status = status
49
+ return task
50
+ },
51
+ taskByTitle(title) {
52
+ return tasks.find((item) => item.title === title) || null
53
+ },
54
+ async create(request) {
55
+ calls.create.push(request)
56
+ maybeThrow(createError, request)
57
+ const entry = {
58
+ id: `sched-${++seq}`,
59
+ title: request.title,
60
+ prompt: request.prompt,
61
+ status: 'active',
62
+ kind: request.timing?.kind || null,
63
+ target: request.target || null,
64
+ createdAt: new Date().toISOString(),
65
+ updatedAt: new Date().toISOString(),
66
+ }
67
+ tasks.push(entry)
68
+ return entry
69
+ },
70
+ async list(request = {}) {
71
+ calls.list.push(request)
72
+ maybeThrow(listError, request)
73
+ const limit = Number(request.limit) || 100
74
+ const offset = Number(request.offset) || 0
75
+ const matching = tasks.filter((item) => request.active === undefined || (item.status === 'active') === request.active)
76
+ const items = matching.slice(offset, offset + limit)
77
+ return { items, shown: items.length, total: matching.length, limit, offset }
78
+ },
79
+ async edit(request) {
80
+ calls.edit.push(request)
81
+ maybeThrow(editError, request)
82
+ const index = tasks.findIndex((item) => item.id === request.id)
83
+ if (index < 0) return { id: request.id, code: 'schedule_not_found' }
84
+ if (request.action === 'delete') {
85
+ tasks.splice(index, 1)
86
+ return { id: request.id, deleted: true }
87
+ }
88
+ const task = tasks[index]
89
+ if (request.patch?.title !== undefined) task.title = request.patch.title
90
+ if (request.patch?.prompt !== undefined) task.prompt = request.patch.prompt
91
+ if (request.patch?.active === false) task.status = 'paused'
92
+ if (request.patch?.active === true) task.status = 'active'
93
+ return { ...task }
94
+ },
95
+ }
96
+ }
97
+
98
+ /** A cordis-shaped context whose only service is the fake schedule. */
99
+ export function wakeContext(schedule) {
100
+ return {
101
+ get(name) {
102
+ return name === 'schedule' ? schedule : undefined
103
+ },
104
+ }
105
+ }
@@ -68,6 +68,6 @@ test('the shipped tool surface compiles under the host rules', async () => {
68
68
  tools: { register: (tool) => { registered.push(tool.name); return () => {} } },
69
69
  logger: { warn: (message) => { throw new Error(`unexpected registration warning: ${message}`) } },
70
70
  })
71
- assert.equal(registered.length, 10, `registered ${registered.join(', ')}`)
71
+ assert.equal(registered.length, 13, `registered ${registered.join(', ')}`)
72
72
  dispose()
73
73
  })