dsh-memu-memory 1.2.5 → 1.2.6

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.
@@ -36,7 +36,7 @@ const backend = {
36
36
  }
37
37
 
38
38
  globalThis.__backendCompensationTest = backend
39
- const engineSource = 'const bridge = globalThis.__backendCompensationTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles;'
39
+ const engineSource = 'const bridge = globalThis.__backendCompensationTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
40
40
  const hooks = registerHooks({
41
41
  resolve(specifier, context, nextResolve) {
42
42
  if (specifier === './memu.js') {
@@ -9,7 +9,7 @@ process.env.DSH_MEMU_HOME = home
9
9
 
10
10
  const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
- const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY } = await import('../lib/private.js')
12
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow } = await import('../lib/private.js')
13
13
 
14
14
  test.after(() => {
15
15
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
@@ -100,9 +100,15 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
100
100
  rec.forkFollowups.push({ child: spec.sessionId, message })
101
101
  if (emitTurnEnd) {
102
102
  if (turnReason?.kind === 'completed') {
103
- const throughSeq = 2 + extraEvents.length + padding
103
+ // The worker receipt must match the window the fork was seeded
104
+ // with, not the whole parent transcript.
105
+ const child = state.getSessionBinding(spec.sessionId)
106
+ const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
107
+ const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq)
108
+ ? child.snapshotThroughSeq
109
+ : 2 + extraEvents.length + padding
104
110
  for (const handler of rec.sessionHandlers) {
105
- handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq: 0, throughSeq }, state.getSessionBinding(spec.sessionId)) }] } } })
111
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq, throughSeq }, child) }] } } })
106
112
  }
107
113
  }
108
114
  for (const handler of rec.sessionHandlers) {
@@ -213,7 +219,7 @@ test('a closed session inherits the last request/header event', async () => {
213
219
  const result = await requestPrivateConsolidation(ctx, 'fork-closed')
214
220
  assert.equal(result.ok, true)
215
221
  const spec = ctx.rec.created[0]
216
- assert.equal(spec.inheritedEventCount, 5, 'the header events are part of the inherited log')
222
+ assert.equal(spec.inheritedEventCount, 3, 'only conversation events are seeded; request/header is noise')
217
223
  assert.deepEqual(spec.agentOptions, { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 })
218
224
  })
219
225
 
@@ -349,9 +355,9 @@ test('a large transcript with nothing new since the cursor does not refork', asy
349
355
  const result = await requestPrivateConsolidation(ctx, 'fork-large-thin')
350
356
  assert.equal(result.ok, true)
351
357
  assert.equal(result.skipped, 'no-human-turn', 'the increment carries no human turn to consolidate')
352
- assert.equal(result.settled, false, 'nothing was consolidated, so the cursor must not move')
358
+ assert.equal(result.settled, true, 'a policy skip is terminal: the idle sweep stops re-reading the same greetings')
353
359
  assert.equal(ctx.rec.created.length, 0, 'no fork when the pending increment has no evidence')
354
- assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5905, 'the cursor must not advance')
360
+ assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5912, 'a terminal policy skip advances the coarse cursor so the same thin tail is not rescanned')
355
361
  })
356
362
 
357
363
  test('a large transcript that was never consolidated does fork, because the backlog is real', async () => {
@@ -365,6 +371,75 @@ test('a large transcript that was never consolidated does fork, because the back
365
371
  assert.equal(result.ok, true, 'the backlog bound lets this one through')
366
372
  assert.equal(ctx.rec.created.length, 1, 'a large unconsolidated backlog is worth exactly one fork')
367
373
  })
374
+ // ---------------------------------------------------------------- window & seed
375
+ test('the seed keeps conversation only, renumbers from zero, and strips replay/stream noise', () => {
376
+ const plugin = { seq: 0, type: 'user/message', data: { source: { kind: 'plugin:dsh-memu-memory', form: 'recall' }, content: [{ type: 'text', text: '旧召回' }] } }
377
+ const runtime = { seq: 1, type: 'user/message', data: { source: { kind: 'runtime-context', form: 'snapshot' }, content: [{ type: 'text', text: '运行时快照' }] } }
378
+ const header = { seq: 2, type: 'request/header', data: { header: {} } }
379
+ const user = { seq: 3, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '记住:我不吃香菜' }] } }
380
+ const assistant = { seq: 4, type: 'assistant/message', data: {
381
+ message: {
382
+ source: { provider: 'p', model: 'm', replayState: { huge: 'x'.repeat(400) } },
383
+ content: [{ type: 'reasoning', text: '思考过程' }, { type: 'text', text: '好的' }, { type: 'tool-call', name: 'read', arguments: 'x'.repeat(2000) }],
384
+ },
385
+ stream: { blob: 'y'.repeat(400) },
386
+ } }
387
+ const repeated = 'R'.repeat(4000)
388
+ const tool1 = { seq: 5, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
389
+ const tool2 = { seq: 6, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
390
+ const catalog = {
391
+ type: 'user/message', seq: 0, time: 1, surfaceOp: 'append',
392
+ data: { role: 'user', source: { kind: 'plugin:dsh-memu-memory', form: 'notice' }, content: [{ type: 'text', text: '已有记忆目录' }] },
393
+ }
394
+ const seed = compactSeedEvents([plugin, runtime, header, user, assistant, tool1, tool2], catalog)
395
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4], 'contiguous from zero, catalog at 0')
396
+ assert.match(seed[0].data.content[0].text, /已有记忆目录/)
397
+ assert.equal(seed[1].data.source.kind, 'user', 'only real user messages survive')
398
+ const msg = seed[2].data.message
399
+ assert.equal(msg.content.some(block => block.type === 'reasoning'), false, 'reasoning is not evidence')
400
+ assert.equal(msg.source.replayState, undefined, 'replay state duplicates the body')
401
+ assert.equal(seed[2].data.stream, undefined, 'the raw chunk log is not the message')
402
+ assert.match(msg.content.find(block => block.type === 'tool-call').arguments, /已截断/)
403
+ assert.match(seed[3].data.message.content[0].text, /已截断/)
404
+ assert.match(seed[4].data.message.content[0].text, /与前面相同的工具输出/, 'identical tool output is deduped')
405
+ })
406
+
407
+ test('a long tail is cut to one closed-turn window with a remainder', () => {
408
+ const events = Array.from({ length: CONSOLIDATION_WINDOW_EVENTS + 180 }, (_, seq) => ({ seq, type: 'todo/write', data: {} }))
409
+ const window = selectConsolidationWindow(events)
410
+ assert.equal(window.fromSeq, 0)
411
+ assert.ok(window.events.length <= CONSOLIDATION_WINDOW_EVENTS, 'the window stays bounded')
412
+ assert.ok(window.remaining > 0, 'the rest is left for the next sweep')
413
+ assert.ok(window.throughSeq < events.length - 1)
414
+ })
415
+
416
+ test('a manual re-check starts at a complete turn instead of mid-step', () => {
417
+ const events = [
418
+ { seq: 0, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '旧回答' }] } } },
419
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '最后一问' }] } },
420
+ { seq: 2, type: 'turn/start', data: { turn: 2 } },
421
+ { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '最后回答' }] } } },
422
+ { seq: 4, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } },
423
+ ]
424
+ const window = selectTailTurnWindow(events)
425
+ assert.equal(window.fromSeq, 1, 'the user message that opened the turn is included')
426
+ assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
427
+ })
428
+
429
+ test('the same failed snapshot stops re-forking after the failure cap', async () => {
430
+ state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
431
+ const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused' } } })
432
+ const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
433
+ const second = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
434
+ assert.equal(first.ok, false)
435
+ assert.equal(second.ok, false)
436
+ assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
437
+ const third = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
438
+ assert.equal(third.ok, true)
439
+ assert.equal(third.skipped, 'snapshot-failed')
440
+ assert.equal(ctx.rec.created.length, 2, 'the third call does not pay for the same snapshot again')
441
+ })
442
+
368
443
  // ---------------------------------------------------------------- PTC 兼容
369
444
  // 现场(2026-10-31,yuike-ptc 会话):PTC 模式下 request/header 的工具表只有 run_code,
370
445
  // probe 曾据此判 unavailable(worker-tools-ptc-only),PTC 会话永远不被整理。宿主的
@@ -51,7 +51,8 @@ globalThis.__curatorAbsorbTest = {
51
51
 
52
52
  const memuSource = 'const bridge = globalThis.__curatorAbsorbTest;'
53
53
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
54
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
54
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
55
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
55
56
  const hooks = registerHooks({
56
57
  resolve(specifier, context, nextResolve) {
57
58
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -24,7 +24,8 @@ globalThis.__curatorClusterTest = {
24
24
  }
25
25
  const memuSource = 'const bridge = globalThis.__curatorClusterTest;'
26
26
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
27
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
27
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
28
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
28
29
  const hooks = registerHooks({
29
30
  resolve(specifier, context, nextResolve) {
30
31
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -50,7 +50,8 @@ const realStateUrl = new URL('../lib/state.js', import.meta.url).href
50
50
  const realMemuUrl = new URL('../lib/memu.js', import.meta.url).href
51
51
  const memuSource = 'const bridge = globalThis.__curatorCommitTest;'
52
52
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
53
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
53
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
54
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
54
55
  const stateSource = [
55
56
  `import * as real from ${JSON.stringify(realStateUrl)}`,
56
57
  'const hook = globalThis.__curatorIndexHook',
@@ -22,7 +22,8 @@ globalThis.__curatorLinkTest = {
22
22
  }
23
23
  const memuSource = 'const bridge = globalThis.__curatorLinkTest;'
24
24
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
25
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
25
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
26
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
26
27
  const hooks = registerHooks({
27
28
  resolve(specifier, context, nextResolve) {
28
29
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -32,7 +32,8 @@ globalThis.__curatorReviewTest = {
32
32
 
33
33
  const memuSource = 'const bridge = globalThis.__curatorReviewTest;'
34
34
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
35
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
35
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
36
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
36
37
  const hooks = registerHooks({
37
38
  resolve(specifier, context, nextResolve) {
38
39
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -224,7 +224,7 @@ test('a conversation the host says is gone is marked once and never retried', as
224
224
  assert.equal(binding.sleepRetryAt, null, 'nothing to retry later')
225
225
  assert.ok(logs.some((m) => /no longer exists/.test(m)), 'explained once: ' + logs.join(' | '))
226
226
  const quiet = await cycle.runSleepPass(fakeCtx({ live: ['cycle-ghost'] }))
227
- assert.equal(quiet.considered, 0, 'the next sweep does not even read the transcript')
227
+ assert.equal(quiet.ran, 0, 'the next sweep does not consolidate a deleted session again')
228
228
  })
229
229
 
230
230
  test('a policy greeting skip does not claim a completed worker check', async () => {
@@ -238,7 +238,7 @@ test('a policy greeting skip does not claim a completed worker check', async ()
238
238
  const out = await cycle.runSleepPass(ctx)
239
239
  assert.equal(out.ran, 0, 'a policy skip is not a verified worker receipt')
240
240
  assert.equal(ctx.created.length, 0, 'no fork for small talk')
241
- assert.equal(state.getLastSleepAt('cycle-smalltalk'), null)
241
+ assert.ok(state.getLastSleepAt('cycle-smalltalk'), 'a terminal skip is recorded so the same greetings are not re-read every sweep')
242
242
  })
243
243
 
244
244
  test('auto curation stays off unless an interval is set', async () => {
@@ -48,7 +48,7 @@ globalThis.__managedMemoryTest = {
48
48
  },
49
49
  async listFiles() { throw new Error('unexpected list engine call') },
50
50
  }
51
- const engineSource = 'const bridge = globalThis.__managedMemoryTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles;'
51
+ const engineSource = 'const bridge = globalThis.__managedMemoryTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
52
52
  const hooks = registerHooks({
53
53
  resolve(specifier, context, nextResolve) {
54
54
  if (specifier === './memu.js') {
@@ -22,7 +22,7 @@ globalThis.__recallDedupTest = {
22
22
  async forget() { return { deleted: 1, segments: 1 } },
23
23
  async listFiles() { return { recall_files: [], resources: [], raw: null } },
24
24
  }
25
- const engineSource = 'const bridge = globalThis.__recallDedupTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles;'
25
+ const engineSource = 'const bridge = globalThis.__recallDedupTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
26
26
  const hooks = registerHooks({
27
27
  resolve(specifier, context, nextResolve) {
28
28
  if (specifier === './memu.js') {
@@ -10,7 +10,7 @@ process.env.DSH_MEMU_HOME = home
10
10
  const state = await import('../lib/state.js')
11
11
  const wake = await import('../lib/salient-wake.js')
12
12
  const activity = await import('../lib/activity-log.js')
13
- const { fakeScheduleService, wakeContext, scheduleError } = await import('./stubs/dsh-schedule.js')
13
+ const { fakeScheduleService, fakeSessionScheduleService, wakeContext, scheduleError } = await import('./stubs/dsh-schedule.js')
14
14
 
15
15
  test.after(() => {
16
16
  try { state.flushState() } catch {}
@@ -105,6 +105,33 @@ test('a host without a schedule service warns once and does not throw', async ()
105
105
  state.updateSettings({ salientWake: 'off' })
106
106
  })
107
107
 
108
+ test('a session-scoped schedule API is skipped with one warning, never called', async () => {
109
+ state.updateSettings({ salientWake: 'schedule' })
110
+ const { binding } = newSession('wake-session-api')
111
+ putEntry(binding.libraryId, 'mem-session-api', { salientDate: '2026-11-02' })
112
+ const schedule = fakeSessionScheduleService()
113
+ const logs = []
114
+ const log = (message) => logs.push(String(message))
115
+ assert.deepEqual(await run(schedule, local(2026, 11, 2), log), { skipped: 'schedule-api' })
116
+ assert.equal(schedule.calls.list.length, 0, 'the old list needs a sessionId; calling it with { limit } would be a wrong-shaped request')
117
+ assert.equal(schedule.calls.create.length, 0)
118
+ assert.equal(schedule.calls.delete.length, 0)
119
+ assert.equal(logs.length, 1)
120
+ assert.match(logs[0], /host-wide schedule API/)
121
+
122
+ const events = activity.listEvents({ limit: 50 })
123
+ assert.ok(events.some((event) => event.detail?.trigger === 'wake' && event.detail?.stage === 'schedule-api' && event.level === 'warn'))
124
+ state.updateSettings({ salientWake: 'off' })
125
+ })
126
+
127
+ test('scheduleFlavor distinguishes the host-wide and session-scoped APIs structurally', () => {
128
+ assert.equal(wake.scheduleFlavor(null), null)
129
+ assert.equal(wake.scheduleFlavor({}), null)
130
+ assert.equal(wake.scheduleFlavor({ create() {}, list() {} }), null)
131
+ assert.equal(wake.scheduleFlavor(fakeScheduleService()), 'global')
132
+ assert.equal(wake.scheduleFlavor(fakeSessionScheduleService()), 'session')
133
+ })
134
+
108
135
  test('today and tomorrow each get one task whose prompt is self-contained', async () => {
109
136
  state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00', salientWakeTimeZone: '' })
110
137
  const { sessionId, binding } = newSession('wake-main')
@@ -103,3 +103,38 @@ export function wakeContext(schedule) {
103
103
  },
104
104
  }
105
105
  }
106
+
107
+ /**
108
+ * The 0.2.0 / 0.2.1 session-scoped reminder API: every task belongs to one
109
+ * Session, `list` needs that Session, and there is no `edit` method. The wake
110
+ * pass probes for `edit` to tell this shape from the 0.2.2 host-wide task table,
111
+ * so this fake exists to pin that the old API is skipped instead of being
112
+ * called with the wrong argument shape.
113
+ */
114
+ export function fakeSessionScheduleService() {
115
+ const tasks = []
116
+ const calls = { create: [], list: [], delete: [] }
117
+ let seq = 0
118
+
119
+ return {
120
+ tasks,
121
+ calls,
122
+ async create(sessionId, request) {
123
+ calls.create.push({ sessionId, request })
124
+ const entry = { id: `sess-sched-${++seq}`, sessionId, title: request.title, status: 'active' }
125
+ tasks.push(entry)
126
+ return entry
127
+ },
128
+ async list(request) {
129
+ calls.list.push(request)
130
+ return tasks.filter((task) => task.sessionId === request.sessionId)
131
+ },
132
+ async delete(request) {
133
+ calls.delete.push(request)
134
+ const index = tasks.findIndex((task) => task.id === request.id && task.sessionId === request.sessionId)
135
+ if (index < 0) return { id: request.id, deleted: false }
136
+ tasks.splice(index, 1)
137
+ return { id: request.id, deleted: true }
138
+ },
139
+ }
140
+ }
@@ -49,7 +49,7 @@ test('the audited numeric fields are covered by that gate', () => {
49
49
  ['dedupeTurns', 16],
50
50
  ['globalEveryNTurns', 6],
51
51
  ['randomCueChance', 0.02],
52
- ['sleepAfterIdleMinutes', 3],
52
+ ['sleepAfterIdleMinutes', 2],
53
53
  ]) {
54
54
  assert.equal(fallbacks.get(key), expected, 'settings.' + key + ' fallback')
55
55
  assert.equal(state.DEFAULT_SETTINGS[key], expected, 'DEFAULT_SETTINGS.' + key)