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.
package/lib/private.js CHANGED
@@ -140,6 +140,187 @@ export function assessConsolidationValue(events) {
140
140
  return { worth: true, reason: 'substantive', ...facts }
141
141
  }
142
142
 
143
+ // ---- incremental consolidation window --------------------------------------
144
+ // A consolidation fork used to seed the whole transcript up to the snapshot cut,
145
+ // so every run re-read the same old tool logs and the model's attention spread
146
+ // thinner as the conversation grew (the 56-turn QQ session was re-read 6-10
147
+ // times). The policy below keeps each fork bounded: seed only the unconsolidated
148
+ // tail, compact the noise, and leave the rest for the next window.
149
+ export const CONSOLIDATION_BACKLOG_EVENTS = 200
150
+ export const CONSOLIDATION_BACKLOG_TURNS = 10
151
+ export const CONSOLIDATION_WINDOW_EVENTS = 300
152
+ export const CONSOLIDATION_PROBE_MINUTES = 15
153
+ export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
154
+ const SEED_TOOL_RESULT_CHARS = 1_600
155
+ const SEED_TOOL_CALL_CHARS = 800
156
+ const SEED_TEXT_CHARS = 20_000
157
+ const SEED_CATALOG_ENTRIES = 60
158
+
159
+ // Types that carry conversation, plus the structural events a seeded Session
160
+ // replays. Everything else is host bookkeeping: request headers, permissions,
161
+ // runtime snapshots and the plugin's own recall messages. Feeding those to the
162
+ // summarizer is how a memory ends up citing its own earlier injection as a user
163
+ // fact, so they never enter the seed.
164
+ const SEED_EVENT_TYPES = new Set([
165
+ 'user/message', 'assistant/message', 'tool/call', 'tool/result',
166
+ 'turn/start', 'turn/end', 'step/start', 'step/end',
167
+ ])
168
+
169
+ function capSeedText(value, limit = SEED_TEXT_CHARS) {
170
+ const text = String(value ?? '')
171
+ return text.length > limit ? text.slice(0, limit) + '…[已截断]' : text
172
+ }
173
+
174
+ function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
175
+ const textCap = Number(caps.text) > 0 ? Number(caps.text) : SEED_TEXT_CHARS
176
+ const toolCap = Number(caps.tool) > 0 ? Number(caps.tool) : SEED_TOOL_CALL_CHARS
177
+ const out = []
178
+ for (const block of Array.isArray(blocks) ? blocks : []) {
179
+ if (!block || typeof block !== 'object') continue
180
+ if (block.type === 'reasoning') continue
181
+ if (block.type === 'image') { out.push({ type: 'text', text: '[图片/附件]' }); continue }
182
+ if (block.type !== 'text' && block.type !== 'tool-call') { out.push(block); continue }
183
+ if (block.type === 'tool-call') {
184
+ out.push({ ...block, arguments: capSeedText(block.arguments, toolCap) })
185
+ continue
186
+ }
187
+ const text = String(block.text || '')
188
+ // Role cards, emoji catalogs and full unread snapshots repeat verbatim across
189
+ // turns; one copy is enough to summarise what the tool returned.
190
+ if (seenToolText && text && seenToolText.has(text)) {
191
+ out.push({ ...block, text: '[与前面相同的工具输出,已省略]' })
192
+ continue
193
+ }
194
+ if (seenToolText && text) seenToolText.add(text)
195
+ out.push({ ...block, text: capSeedText(text, textCap) })
196
+ }
197
+ return out
198
+ }
199
+
200
+ /**
201
+ * Build the seed body for one window: only conversation events, with reasoning /
202
+ * replay state / repeated tool output removed, then renumbered seq 0..n so
203
+ * Session's "contiguous from zero" rule holds. The optional catalog event takes
204
+ * seq 0 and is the only synthetic message.
205
+ */
206
+ export function compactSeedEvents(events, catalogEvent = null) {
207
+ const kept = []
208
+ const seenToolText = new Set()
209
+ for (const event of Array.isArray(events) ? events : []) {
210
+ if (!event || typeof event !== 'object' || !SEED_EVENT_TYPES.has(event.type)) continue
211
+ if (event.type === 'user/message' && event.data?.source?.kind !== 'user') continue
212
+ const clone = { ...event, data: { ...(event.data || {}) } }
213
+ if (event.type === 'assistant/message') {
214
+ const message = { ...(event.data?.message || {}) }
215
+ const source = { ...(message.source || {}) }
216
+ // The replay state duplicates the response body; it is not conversation.
217
+ delete source.replayState
218
+ message.source = source
219
+ message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: SEED_TOOL_CALL_CHARS })
220
+ if (message.content.length === 0) message.content = [{ type: 'text', text: '(本轮没有可读的正文)' }]
221
+ clone.data.message = message
222
+ // data.stream is the raw chunk log, not the message the model saw.
223
+ delete clone.data.stream
224
+ } else if (event.type === 'tool/result') {
225
+ const message = { ...(event.data?.message || {}) }
226
+ message.content = cloneSeedBlocks(message.content, { text: SEED_TOOL_RESULT_CHARS, tool: SEED_TOOL_CALL_CHARS }, seenToolText)
227
+ if (message.content.length === 0) message.content = [{ type: 'text', text: '[空工具输出]' }]
228
+ clone.data.message = message
229
+ } else if (event.type === 'tool/call') {
230
+ clone.data.arguments = capSeedText(event.data?.arguments, SEED_TOOL_CALL_CHARS)
231
+ } else if (event.type === 'user/message') {
232
+ clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
233
+ }
234
+ kept.push(clone)
235
+ }
236
+
237
+ const mapping = new Map()
238
+ kept.forEach((event, index) => mapping.set(Number(event.seq), index + (catalogEvent ? 1 : 0)))
239
+ const out = catalogEvent ? [{ ...catalogEvent, seq: 0 }] : []
240
+ kept.forEach((event, index) => {
241
+ const next = { ...event, seq: index + (catalogEvent ? 1 : 0) }
242
+ if (Array.isArray(next.sourceEventSeqs)) {
243
+ const mapped = [...new Set(next.sourceEventSeqs
244
+ .map(value => mapping.get(Number(value)))
245
+ .filter(value => Number.isInteger(value) && value < next.seq))]
246
+ .sort((a, b) => a - b)
247
+ if (mapped.length) next.sourceEventSeqs = mapped
248
+ else delete next.sourceEventSeqs
249
+ }
250
+ // A surface replace cites the nodes it shadows; if any citation was dropped
251
+ // with the noise filter, replaying it would fail validation. Dropping the
252
+ // whole patch is the safe choice — the seed is evidence, not state.
253
+ if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.sourceEventSeqs)) return
254
+ out.push(next)
255
+ })
256
+ return out
257
+ }
258
+
259
+ /** Existing entries, compact, for dedupe/update instead of duplicate writes. */
260
+ export function memoryCatalogEvent(binding, now = Date.now()) {
261
+ if (!binding?.libraryId) return null
262
+ let entries = []
263
+ try { entries = Object.entries(loadPrivateIndex(binding.libraryId).entries || {}) } catch { return null }
264
+ const rows = entries
265
+ .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
266
+ .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
267
+ .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || '')))
268
+ .slice(0, SEED_CATALOG_ENTRIES)
269
+ .map(([id, entry]) => `- [${id}] ${capSeedText(entry.title || '(untitled)', 120)} · ${entry.layer || 'long_term'} · ${entry.status || 'active'}`)
270
+ if (rows.length === 0) return null
271
+ const text = [
272
+ '[memory-catalog · 已有记忆目录(只读上下文,不是用户发言,也不属于本轮转录)]',
273
+ '下面这些是本次整理之前已经写入本库的条目。不要当作用户说过的话,也不要重复创建;同一事实用 memu_private_update id=<id> 合并,真正新增的内容才用 memu_private_remember。',
274
+ ...rows,
275
+ ].join('\n')
276
+ return {
277
+ type: 'user/message',
278
+ seq: 0,
279
+ time: now,
280
+ data: createUserMessage({
281
+ content: [{ type: 'text', text }],
282
+ source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' },
283
+ }),
284
+ surfaceOp: 'append',
285
+ }
286
+ }
287
+
288
+ /** First `limit` events, trimmed back to a complete turn so a fork never sees half a step. */
289
+ export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
290
+ const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
291
+ if (list.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
292
+ if (list.length <= limit) return { events: list, fromSeq: eventSeq(list[0]), throughSeq: eventSeq(list[list.length - 1]), remaining: 0 }
293
+ const cutSeq = eventSeq(list[Math.max(0, limit - 1)])
294
+ const sliced = list.filter(event => eventSeq(event) <= cutSeq)
295
+ const safe = safePrefix(sliced, { requireClosedTurn: false })
296
+ const window = safe.ok && safe.events.length > 0 ? safe.events : sliced
297
+ const throughSeq = eventSeq(window[window.length - 1])
298
+ return {
299
+ events: window,
300
+ fromSeq: eventSeq(window[0]),
301
+ throughSeq,
302
+ remaining: list.filter(event => eventSeq(event) > throughSeq).length,
303
+ }
304
+ }
305
+
306
+ /** Last complete turn window, for a manual re-check when the cursor is already at the end. */
307
+ export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
308
+ const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
309
+ const slice = list.slice(-limit)
310
+ if (slice.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
311
+ let start = slice.findIndex(event => event.type === 'turn/start')
312
+ if (start < 0) start = slice.findIndex(event => event.type === 'user/message')
313
+ if (start < 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
314
+ for (let i = start - 1; i >= 0; i -= 1) {
315
+ if (slice[i].type === 'user/message' && slice[i].data?.source?.kind === 'user') { start = i; break }
316
+ if (slice[i].type === 'turn/end' || slice[i].type === 'turn/start') break
317
+ }
318
+ const window = slice.slice(start)
319
+ const safe = safePrefix(window, { requireClosedTurn: false })
320
+ const chosen = safe.ok && safe.events.length > 0 ? safe.events : window
321
+ return { events: chosen, fromSeq: eventSeq(chosen[0]), throughSeq: eventSeq(chosen[chosen.length - 1]), remaining: 0 }
322
+ }
323
+
143
324
  export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
144
325
  const binding = getSessionBinding(sessionId)
145
326
  if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
@@ -347,13 +528,13 @@ function workerToolsMeta(workerTools) {
347
528
  const inFlight = new Map()
348
529
 
349
530
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
350
- // 的 file:line 当成诊断契约(当前 lib/private.js:336),修改位置时同步更新该诊断映射,
531
+ // 的 file:line 当成诊断契约(当前 lib/private.js:528),修改位置时同步更新该诊断映射,
351
532
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
352
533
  import { warn } from './paths.js'
353
- import { captureSessionSnapshot } from './consolidation-snapshot.js'
534
+ import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
354
535
  import {
355
536
  beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey,
356
- recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState,
537
+ recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
357
538
  } from './consolidation-ledger.js'
358
539
  import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
359
540
  import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS } from './consolidation-worker.js'
@@ -410,7 +591,8 @@ export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_
410
591
  return Math.min(policy.maxMs, Math.max(policy.minMs, raw))
411
592
  }
412
593
 
413
- export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs = null, force = false } = {}) {
594
+ export async function requestHistoricalConsolidation(ctx, sessionId, options = {}) {
595
+ const { maxWaitMs = null, force = false, trigger = null } = options
414
596
  const binding = getSessionBinding(sessionId)
415
597
  if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
416
598
  if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
@@ -434,6 +616,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
434
616
  const finish = (result) => {
435
617
  const ok = result?.ok === true
436
618
  const skipped = Boolean(result?.skipped)
619
+ const skipText = !skipped
620
+ ? ''
621
+ : (['small-talk', 'no-human-turn', 'no-value', 'no-new-events'].includes(result.skipped)
622
+ ? '跳过(没有值得记的内容)'
623
+ : '跳过 · ' + result.skipped)
437
624
  record({
438
625
  kind: 'consolidate',
439
626
  scope: 'private',
@@ -441,8 +628,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
441
628
  libraryId: binding.libraryId || null,
442
629
  ok,
443
630
  level: ok ? 'info' : (result?.timedOut ? 'warn' : 'error'),
444
- message: '整理' + (ok ? (skipped ? '跳过(没有值得记的内容)' : '完成') : (result?.timedOut ? '超时' : '失败'))
445
- + (force ? ' · 手动' : ' · 空闲')
631
+ message: '整理' + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
632
+ + (force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
446
633
  + (result?.childId ? ' · fork ' + result.childId.slice(-8) : '')
447
634
  + (result?.reasonCode ? ' · ' + result.reasonCode : '')
448
635
  + (result?.error ? ':' + String(result.error) : '')
@@ -507,66 +694,118 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
507
694
  retryable: captured.retryable === true, error: captured.error,
508
695
  })
509
696
  }
510
- const snapshot = captured.snapshot
697
+ const fullSnapshot = captured.snapshot
511
698
  const events = captured.events
512
- const snapshotMeta = snapshotMetaOf(snapshot)
513
- // 范围大小决定等多久:显式给了就听调用方的,没给按这段转录的事件数推。
514
- const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(events.length)
699
+ const fresh = unconsolidatedEvents(binding, events)
700
+ if (events.length === 0) return finish({ ok: false, sessionId, reasonCode: 'empty-snapshot', settled: false, error: 'this session has no content to consolidate' })
701
+ // A manual click on an already-settled session still re-checks the tail instead
702
+ // of replaying megabytes; automatic runs only look at what the cursor has not
703
+ // covered. Either way the fork gets one bounded window, not the whole log.
704
+ const candidateEvents = force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
705
+ if (candidateEvents.length === 0) {
706
+ return finish({ ok: true, sessionId, skipped: 'no-new-events', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
707
+ }
515
708
  const generationAtStart = scopeGenerationOf(binding)
516
709
  // 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
517
- safeLedger(() => noteEvidence({ sessionId, fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq }))
518
- if (events.length === 0) return finish({ ok: false, sessionId, reasonCode: 'empty-snapshot', settled: false, error: 'this session has no content to consolidate' })
710
+ safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
519
711
 
520
- // The scheduler asks "is this conversation idle", which is not the same as
521
- // "did anything happen that deserves a memory". Answer the second question
522
- // before paying for a fork; a manual consolidation passes force and skips it.
712
+ let value = null
523
713
  if (!force) {
524
- const fresh = unconsolidatedEvents(binding, events)
525
- const value = assessConsolidationValue(fresh)
714
+ value = assessConsolidationValue(candidateEvents)
526
715
  // 这一批里没有真人回合、或只有一句「好的继续」:这一段确实没什么可整理的,
527
- // 是终态而不是 deferral——否则空闲扫描会为同一句寒暄一直重扫。
528
- // 没有真人回合、或只有一句「谢谢」:这一段确实没有可整理的证据,是终态而不是 deferral。
529
- // 写成 deferred 会让空闲扫描为同一句寒暄每轮重扫(tests/cycle.test.mjs 的寒暄用例钉住这一点)。
530
- if (!value.worth) return finish({ ok: true, sessionId, skipped: value.reason, settled: false, deferred: true, reasonCode: value.reason, assessment: value, snapshot: snapshotMeta })
531
- // 加权判定:短空闲要求分数达标,长空闲(饥饿阈值)无条件放行;
532
- // 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
716
+ // 是终态而不是 deferral——写入完成边界由 cycle 落到 lastSleepAt,下一次真人
717
+ // 消息到达前不再重扫同一个寒暄窗口。
718
+ if (!value.worth) {
719
+ // A terminal policy skip advances the coarse cursor and checked range:
720
+ // otherwise the same greetings stay pending forever and the sweep keeps
721
+ // treating them as a real backlog.
722
+ safeLedger(() => skipRange({ sessionId, snapshot: fullSnapshot, reasonCode: value.reason }))
723
+ setSessionBinding(sessionId, { lastSleepSeq: fullSnapshot.throughSeq })
724
+ return finish({
725
+ ok: true, sessionId, skipped: value.reason, settled: true, deferred: false,
726
+ reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
727
+ })
728
+ }
533
729
  const settings = getSettings()
534
- const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
535
- const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
536
- const evidence = collectEvidence(fresh)
537
- const wake = assessWake({
538
- evidence,
539
- starved,
540
- transcriptEvents: events.length,
541
- // 「待整理区间有多大」是守卫唯一该看的规模信号:守卫要躲的是为一句轻话重种
542
- // 整段转录,而不是把一个从没整理过的大会话永远挡在门外。
543
- pendingEvents: fresh.length,
544
- policy: { ...ACTIVE_MEMORY_POLICY, minScore: Number(settings.activeMemoryMinScore ?? ACTIVE_MEMORY_POLICY.minScore) },
545
- })
546
- record({
547
- kind: 'check',
548
- scope: 'private',
549
- sessionId,
550
- libraryId: binding.libraryId || null,
551
- ok: wake.wake,
552
- message: (wake.wake ? '主动检查触发' : '主动检查跳过')
553
- + ' · score ' + wake.score
554
- + ' · ' + wake.reason
555
- + ' · 空闲 ' + (Number.isFinite(idleMinutes) ? Math.round(idleMinutes) + ' 分钟' : '未知')
556
- + ' · 会话 ' + events.length + ' 事件'
557
- + ' · 快照 ' + snapshot.hash,
558
- detail: { trigger: 'auto', reason: wake.reason, score: wake.score, parts: wake.parts, starved, transcriptEvents: events.length, snapshot: snapshotMeta },
559
- })
560
- if (!wake.wake) return finish({ ok: true, sessionId, skipped: 'low-score', settled: false, assessment: value, score: wake.score, parts: wake.parts, snapshot: snapshotMeta })
730
+ // 事件/回合水位:积压到一定规模就直接整理,不再等评分。它和空闲触发是
731
+ // 两条腿:空闲保证收尾,水位保证一场持续几小时的会话不会攒到几千条才动。
732
+ const backlog = candidateEvents.length >= CONSOLIDATION_BACKLOG_EVENTS
733
+ || Number(value.humanTurns) >= CONSOLIDATION_BACKLOG_TURNS
734
+ if (options.trigger === 'backlog' && !backlog) {
735
+ return finish({
736
+ ok: true, sessionId, skipped: 'backlog-below-threshold', settled: false, deferred: true,
737
+ reasonCode: 'backlog-below-threshold', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
738
+ trigger: options.trigger,
739
+ })
740
+ }
741
+ if (!backlog) {
742
+ // 加权判定:短空闲要求分数达标,长空闲(饥饿阈值)无条件放行;
743
+ // 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
744
+ const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
745
+ const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
746
+ const evidence = collectEvidence(candidateEvents)
747
+ const wake = assessWake({
748
+ evidence,
749
+ starved,
750
+ transcriptEvents: events.length,
751
+ pendingEvents: candidateEvents.length,
752
+ policy: { ...ACTIVE_MEMORY_POLICY, minScore: Number(settings.activeMemoryMinScore ?? ACTIVE_MEMORY_POLICY.minScore) },
753
+ })
754
+ record({
755
+ kind: 'check',
756
+ scope: 'private',
757
+ sessionId,
758
+ libraryId: binding.libraryId || null,
759
+ ok: wake.wake,
760
+ message: (wake.wake ? '主动检查触发' : '主动检查跳过')
761
+ + ' · score ' + wake.score
762
+ + ' · ' + wake.reason
763
+ + ' · 空闲 ' + (Number.isFinite(idleMinutes) ? Math.round(idleMinutes) + ' 分钟' : '未知')
764
+ + ' · 会话 ' + events.length + ' 事件'
765
+ + ' · 待整理 ' + candidateEvents.length + ' 事件'
766
+ + ' · 快照 ' + fullSnapshot.hash,
767
+ detail: { trigger: options.trigger || 'idle', reason: wake.reason, score: wake.score, parts: wake.parts, starved, transcriptEvents: events.length, pendingEvents: candidateEvents.length, snapshot: snapshotMetaOf(fullSnapshot) },
768
+ })
769
+ if (!wake.wake) return finish({ ok: true, sessionId, skipped: 'low-score', settled: false, assessment: value, score: wake.score, parts: wake.parts, snapshot: snapshotMetaOf(fullSnapshot) })
770
+ }
771
+ }
772
+
773
+ // One bounded window per run: the next sweep continues from the new cursor.
774
+ const window = selectConsolidationWindow(candidateEvents)
775
+ if (window.events.length === 0) {
776
+ return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
777
+ }
778
+ const windowSnapshot = {
779
+ ...fullSnapshot,
780
+ fromSeq: window.fromSeq,
781
+ throughSeq: window.throughSeq,
782
+ eventCount: window.events.length,
783
+ hash: snapshotHash(window.events, window.fromSeq, window.throughSeq),
784
+ }
785
+ const snapshot = windowSnapshot
786
+ const snapshotMeta = snapshotMetaOf(windowSnapshot)
787
+ // 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
788
+ const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
789
+ const seedEvents = compactSeedEvents(window.events, memoryCatalogEvent({ ...binding, sessionId }))
790
+ if (seedEvents.length === 0) {
791
+ return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
561
792
  }
562
793
 
563
794
  // 幂等:同一份固定快照已经结算过就不再 fork 一次(失败的部分写入靠操作键判同再试,
564
795
  // 而不是靠"同一个主题就跳过")。
565
- const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: snapshot.hash, scopeGeneration: generationAtStart })
796
+ const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart })
566
797
  const previous = safeLedger(() => findOperation(sessionId, opKey))
567
798
  if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
568
799
  return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
569
800
  }
801
+ // 同一份快照连续失败到上限就不再重跑:窗口已经很小,重试成本可控,但
802
+ // 没有新事件的同一段转录不值得无限重试。新消息会改变快照哈希,重新获得机会。
803
+ if (previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
804
+ return finish({
805
+ ok: true, sessionId, skipped: 'snapshot-failed', settled: true, reasonCode: 'snapshot-failed-too-many',
806
+ snapshot: snapshotMeta, failures: Number(previous.failures) || 0,
807
+ })
808
+ }
570
809
 
571
810
  // 工具面必须可验证:父会话这一轮真实发给模型的工具表里若没有记忆写工具,
572
811
  // fork 同样不会有——那就不 fork,明确 unavailable(C 包第 3 条)。
@@ -597,7 +836,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
597
836
  const header = captured.header || {}
598
837
  // 每次整理都留"看了多少、新的多少、真正写了几条",否则"0 记忆"无法定位是
599
838
  // 没触发、被门挡住还是提取空转。
600
- const freshCount = unconsolidatedEvents(binding, events).length
839
+ const freshCount = fresh.length
601
840
  let beforeIds = null
602
841
  let beforeEntries = null
603
842
  try {
@@ -613,15 +852,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
613
852
  }
614
853
 
615
854
  childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
616
- // `inheritedEventCount` is a TOP-LEVEL CreateAgentOptions field, NOT session
617
- // metadata: SessionStore.prepare() rebuilds the header from a fixed meta
618
- // whitelist (version, id, createdAt, cwd, parentSession, isSeeded, origin,
619
- // delegationDepth, agentPreset), so a count placed in `meta` is silently
620
- // dropped and Session's constructor then refuses the seeded session with
621
- // "seeded session requires an inherited event count". Every fork died there.
622
- //
623
- // 种子只种到快照的 throughSeq:worker 看到的世界就是它要对账的那一段,
624
- // 快照之后新发生的事件留给下一批。
855
+ // 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
856
+ // 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
857
+ // 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
625
858
  handle = await agents.create({
626
859
  sessionId: childId,
627
860
  meta: {
@@ -633,8 +866,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
633
866
  origin: 'subagent',
634
867
  agentPreset: header.agentPreset,
635
868
  },
636
- inheritedEventCount: snapshot.throughSeq + 1,
637
- seed: buildForkSeed(events, snapshot.throughSeq),
869
+ inheritedEventCount: seedEvents.length,
870
+ seed: buildForkSeed(seedEvents, seedEvents.length - 1),
638
871
  agentOptions,
639
872
  signal: abort.signal,
640
873
  })
@@ -654,8 +887,12 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
654
887
  sessionId,
655
888
  libraryId: binding.libraryId || null,
656
889
  ok: true,
657
- message: '整理已开始 · ' + (force ? '手动' : '空闲') + ' · fork ' + childId.slice(-8) + ' · ' + events.length + ' 条事件 · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
658
- detail: { childId, jobId, force, events: events.length, budgetMs, phase: 'started', snapshot: snapshotMeta,
890
+ message: '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲'))
891
+ + ' · fork ' + childId.slice(-8)
892
+ + ' · 窗口 ' + window.events.length + ' 条事件(父会话 ' + events.length + ' 条 / 新 ' + freshCount + ' 条)'
893
+ + (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
894
+ + ' · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
895
+ detail: { childId, jobId, force, trigger: options.trigger || 'idle', events: window.events.length, transcriptEvents: events.length, fresh: freshCount, remaining: window.remaining, budgetMs, phase: 'started', snapshot: snapshotMeta,
659
896
  probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
660
897
  ...workerToolsMeta(workerTools) },
661
898
  })
@@ -718,6 +955,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
718
955
  parentSessionId: sessionId,
719
956
  parentScopeGeneration: generationAtStart,
720
957
  snapshotHash: snapshot.hash,
958
+ // 调试/测试用:worker 的回执范围必须和这两项一致,否则 completeJob 不会推进。
959
+ snapshotFromSeq: snapshot.fromSeq,
960
+ snapshotThroughSeq: snapshot.throughSeq,
961
+ snapshotEventCount: snapshot.eventCount,
721
962
  jobId,
722
963
  scopeKey: binding.scopeKey,
723
964
  memoryOwnerSessionId: binding.memoryOwnerSessionId || sessionId,
@@ -839,7 +1080,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
839
1080
  settled: false,
840
1081
  timedOut: true,
841
1082
  reasonCode: 'timeout',
842
- error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + events.length + ' events; the fork was stopped (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
1083
+ error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
843
1084
  })
844
1085
  }
845
1086
  return finish({
@@ -860,8 +1101,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
860
1101
  : null,
861
1102
  credential: completion?.checked ? { checked: completion.checked, pending: completion.pending } : null,
862
1103
  snapshot: snapshotMeta,
863
- scanned: events.length,
1104
+ scanned: window.events.length,
864
1105
  fresh: freshCount,
1106
+ remaining: window.remaining,
1107
+ window: { fromSeq: window.fromSeq, throughSeq: window.throughSeq },
865
1108
  wrote,
866
1109
  })
867
1110
  } catch (error) {
package/lib/rpc.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  backupDatabases, listBackups, restoreBackup, deleteBackup, globalDbPath, normalizeCwd, getWorkspacePolicy, listWorkspacePolicies, setWorkspacePolicy,
8
8
  storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
9
9
  } from './state.js'
10
- import { commit } from './memu.js'
10
+ import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
11
11
  import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
@@ -1744,6 +1744,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1744
1744
  case 'setup': {
1745
1745
  const status = engineStatus()
1746
1746
  if (status.status !== 'installing') {
1747
+ // A reinstall may replace the venv the resident interpreter is running from;
1748
+ // stop it first so Windows can rename/delete the old engine directory.
1749
+ closeMemuResident()
1747
1750
  void ensureEngine({ force: payload?.force === true, beforeSwitch: backupDatabases }).catch(() => {})
1748
1751
  }
1749
1752
  return { started: true, engine: engineView() }
@@ -1751,6 +1754,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1751
1754
  case 'switchEngine': {
1752
1755
  const version = String(payload?.version || '')
1753
1756
  if (!version) throw new Error('version is required')
1757
+ closeMemuResident()
1754
1758
  const result = await switchEngineVersion(version, {
1755
1759
  beforeSwitch: backupDatabases,
1756
1760
  force: payload?.force === true,
@@ -1813,8 +1817,14 @@ async function dispatch(ctx, endpoint, payload = {}) {
1813
1817
  }
1814
1818
  case 'getMemuConfig':
1815
1819
  return getMemuConfig()
1816
- case 'setEmbeddingSource':
1817
- return setEmbeddingSource(String(payload?.source || ''))
1820
+ case 'setEmbeddingSource': {
1821
+ const config = setEmbeddingSource(String(payload?.source || ''))
1822
+ // Local mode is the resident route: warm it as soon as the switch flips, and
1823
+ // release it when the user goes back to the remote API route.
1824
+ if (config?.source === 'local') void prewarmMemuResident()
1825
+ else closeMemuResident()
1826
+ return config
1827
+ }
1818
1828
  case 'saveMemuConfig':
1819
1829
  return saveMemuConfig({
1820
1830
  provider: payload?.provider,
@@ -13,7 +13,7 @@
13
13
  // 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
14
14
  //
15
15
  // 返回值有两种形状,调用方要同时接受:
16
- // - 整个 pass 没跑:`{ skipped: '<off|service|timezone|time>' }`
16
+ // - 整个 pass 没跑:`{ skipped: '<off|service|schedule-api|timezone|time>' }`
17
17
  // - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
18
18
  import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
19
19
  import {
@@ -38,9 +38,32 @@ const KNOWN_CODES = [
38
38
 
39
39
  // "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
40
40
  let serviceWarned = false
41
+ // 0.2.0/0.2.1 的 schedule 是会话级 API;本 pass 用的是 0.2.2 起的宿主级任务表。
42
+ // 这是能力差异,不是每次 sweep 的故障,同样只提醒一次。
43
+ let sessionScopedWarned = false
41
44
  // 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
42
45
  let zoneWarnedFor = null
43
46
 
47
+ /**
48
+ * Which schedule API a host exposes.
49
+ *
50
+ * - `global`: 0.2.2+ creates a host-wide task from one request
51
+ * (`create(request)`, `list(request) -> { items }`, `edit({ id, action })`).
52
+ * - `session`: 0.2.0/0.2.1 binds every reminder to one session
53
+ * (`create(sessionId, request)`, `list({ sessionId }) -> array`, `delete({ sessionId, id })`).
54
+ *
55
+ * The pass only implements the host-wide shape. Probing structurally (instead of
56
+ * comparing versions) keeps this working when a host backports or renames the
57
+ * service, and lets an old host skip with one readable line instead of failing
58
+ * the same `list` call every sweep.
59
+ */
60
+ export function scheduleFlavor(schedule) {
61
+ if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') return null
62
+ if (typeof schedule.edit === 'function') return 'global'
63
+ if (typeof schedule.delete === 'function') return 'session'
64
+ return null
65
+ }
66
+
44
67
  function pad2(value) {
45
68
  return String(value).padStart(2, '0')
46
69
  }
@@ -218,7 +241,8 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
218
241
 
219
242
  let schedule = null
220
243
  try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
221
- if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') {
244
+ const flavor = scheduleFlavor(schedule)
245
+ if (flavor === null) {
222
246
  if (!serviceWarned) {
223
247
  serviceWarned = true
224
248
  notify('salient wake is enabled but this host exposes no schedule service; skipping')
@@ -230,6 +254,18 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
230
254
  }
231
255
  return { skipped: 'service' }
232
256
  }
257
+ if (flavor === 'session') {
258
+ if (!sessionScopedWarned) {
259
+ sessionScopedWarned = true
260
+ notify('salient wake needs the host-wide schedule API (0.2.2+); this host exposes session-scoped reminders, skipping')
261
+ record({
262
+ kind: 'wake', level: 'warn', ok: false,
263
+ message: '日期唤醒需要宿主级 schedule API(0.2.2+);当前宿主只有会话级提醒,本轮跳过',
264
+ detail: { trigger: 'wake', stage: 'schedule-api' },
265
+ })
266
+ }
267
+ return { skipped: 'schedule-api' }
268
+ }
233
269
 
234
270
  const when = now instanceof Date ? now : new Date(now)
235
271
  if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
package/lib/state.js CHANGED
@@ -99,11 +99,9 @@ export const DEFAULT_SETTINGS = {
99
99
  // These stay ordinary switches, and an existing saved choice is preserved.
100
100
  sleepConsolidation: true,
101
101
  // Group chat arrives in bursts, but a burst is seconds apart and the per-turn
102
- // timestamps already cover that. Three idle minutes is long enough that an
103
- // ordinary pause (reading a diff, thinking about the next question) is not
104
- // "gone", and short enough that a conversation which ended gets tidied in the
105
- // same sitting instead of waiting for a quiet hour that may never arrive.
106
- sleepAfterIdleMinutes: 3,
102
+ // timestamps already cover that. Two idle minutes still separates "reading a
103
+ // diff / thinking" from "gone", and keeps the per-run window small.
104
+ sleepAfterIdleMinutes: 2,
107
105
  // 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
108
106
  // 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
109
107
  activeMemoryMinScore: 0.8,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.2.5",
4
+ "version": "1.2.6",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -48,7 +48,8 @@ globalThis.__curatorAbsorbReviewTest = {
48
48
 
49
49
  const memuSource = 'const bridge = globalThis.__curatorAbsorbReviewTest;'
50
50
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
51
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
51
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
52
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
52
53
  const hooks = registerHooks({
53
54
  resolve(specifier, context, nextResolve) {
54
55
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }