dsh-memu-memory 1.2.4 → 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.
Files changed (57) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +9 -9
  3. package/README.zh.md +6 -6
  4. package/docs/binding-lifecycle.md +1 -1
  5. package/docs/env-and-commands.md +4 -1
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +45 -9
  9. package/docs/troubleshooting.md +27 -8
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +246 -56
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/cycle.js +51 -17
  15. package/lib/embedding-catalog.js +14 -0
  16. package/lib/embedding-runtime.js +202 -25
  17. package/lib/global-graph.js +99 -1
  18. package/lib/index.js +8 -0
  19. package/lib/inject.js +71 -33
  20. package/lib/lexicon-scope.js +143 -0
  21. package/lib/lexicon.js +31 -4
  22. package/lib/local-vector-service.js +82 -6
  23. package/lib/memory.js +186 -12
  24. package/lib/memu.js +318 -3
  25. package/lib/private.js +310 -67
  26. package/lib/rpc.js +183 -23
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +7 -5
  29. package/lib/tools.js +40 -17
  30. package/lib/vector-migration.js +13 -1
  31. package/lib/webui/graph-view.bundle.js +1 -1
  32. package/lib/webui/graph-view.js +4 -1
  33. package/package.json +1 -1
  34. package/tests/absorb-review.test.mjs +2 -1
  35. package/tests/backend-compensation.test.mjs +1 -1
  36. package/tests/browser.test.mjs +58 -1
  37. package/tests/client-render.test.mjs +39 -0
  38. package/tests/consolidation-fork.test.mjs +81 -6
  39. package/tests/cross-library-recall.test.mjs +113 -0
  40. package/tests/curator-absorb.test.mjs +2 -1
  41. package/tests/curator-clusters.test.mjs +2 -1
  42. package/tests/curator-commit.test.mjs +2 -1
  43. package/tests/curator-link.test.mjs +2 -1
  44. package/tests/curator-review-mode.test.mjs +2 -1
  45. package/tests/cycle.test.mjs +2 -2
  46. package/tests/embedding-runtime.test.mjs +53 -1
  47. package/tests/global-graph.test.mjs +90 -0
  48. package/tests/lexicon-scope.test.mjs +256 -0
  49. package/tests/lexicon-ui.test.mjs +23 -0
  50. package/tests/managed-memory.test.mjs +1 -1
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/settings-plumbing.test.mjs +1 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/ui-defaults.test.mjs +1 -1
  56. package/tests/vector-migration.test.mjs +20 -0
  57. package/tests/webui-auth.test.mjs +28 -0
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) {