dsh-memu-memory 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/graph.js CHANGED
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs'
1
2
  import path from 'node:path'
2
3
  import { indexDir, readJsonStrict, writeJson, withFileLock, stamp, warn } from './paths.js'
3
4
  import { loadPrivateIndex, updatePrivateIndex, newMemoryId, listLibraries } from './state.js'
@@ -696,6 +697,39 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
696
697
  return { nodes, edges: edges.filter(edge => selected.has(edge.from) && selected.has(edge.to)), limit: cap, truncated: selected.size >= cap, focusId }
697
698
  }
698
699
 
700
+ // D9:recallRelations 只需要「与这条记忆相连的边」,旧实现却每次全库扫
701
+ // entries × links。这里按索引文件 mtime/size 建一份内存倒排(任意 id → 与它相连
702
+ // 的行),索引没变时直接复用;文件读不到(纯内存索引)时本次构建、不缓存。
703
+ const relationInvertedCache = new Map()
704
+
705
+ function relationInvertedIndex(libraryId, index) {
706
+ let signature = null
707
+ try {
708
+ const stat = fs.statSync(path.join(indexDir(), `${libraryId}.json`))
709
+ signature = `${stat.mtimeMs}:${stat.size}`
710
+ } catch {}
711
+ const cached = relationInvertedCache.get(libraryId)
712
+ if (signature && cached && cached.signature === signature) return cached.inverted
713
+ const inverted = new Map()
714
+ const push = (key, row) => {
715
+ if (!key) return
716
+ let rows = inverted.get(key)
717
+ if (!rows) inverted.set(key, rows = [])
718
+ rows.push(row)
719
+ }
720
+ for (const [from, entry] of Object.entries(index?.entries || {})) {
721
+ for (const link of entry?.links || []) {
722
+ if (!link || !link.to) continue
723
+ const row = { from, link }
724
+ push(from, row)
725
+ // 自环(link.to === from)只存一份,避免查询看到同一行两次。
726
+ if (link.to !== from) push(link.to, row)
727
+ }
728
+ }
729
+ if (signature) relationInvertedCache.set(libraryId, { signature, inverted })
730
+ return inverted
731
+ }
732
+
699
733
  export function recallRelations(libraryId, index, id, sessionId) {
700
734
  const store = readEntities(libraryId)
701
735
  const entities = store.entities
@@ -713,28 +747,30 @@ export function recallRelations(libraryId, index, id, sessionId) {
713
747
  }
714
748
  }
715
749
  const out = []
716
- for (const [from, entry] of Object.entries(index.entries || {})) {
750
+ // 倒排只含与 id 相连的行(出边来自 id 自己,入边来自别的条目)。行顺序与旧实现
751
+ // 的 entries 遍历顺序一致:入边按来源条目顺序、出边在 id 自己的位置。
752
+ for (const { from, link } of relationInvertedIndex(libraryId, index).get(id) || []) {
753
+ if (from !== id && link.to !== id) continue
754
+ const entry = index.entries?.[from]
755
+ if (!entry) continue
717
756
  if (!isMemoryEligible(entry, { automatic: true }) || !visibleToSession(entry, sessionId)) continue
718
- for (const link of entry.links || []) {
719
- if (from !== id && link.to !== id) continue
720
- const to = from === id ? link.to : from
721
- const target = index.entries[to]
722
- if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
723
- // A dangling edge (entry and entity both gone) used to be dropped here
724
- // while getGraph rendered the same disk state as a [deleted] placeholder —
725
- // the two views disagreed. Both now report the edge and mark it `missing`;
726
- // the caller filters if it wants the old silence back.
727
- const missing = !target && !entities[to]
728
- out.push({
729
- id: to,
730
- title: target?.title || entities[to]?.name || '[deleted]',
731
- kind: link.kind,
732
- note: String(link.note || '').slice(0, 80),
733
- confidence: link.confidence ?? 0.7,
734
- missing,
735
- retention: target ? null : (retentionOf.has(to) ? retentionOf.get(to) : 1),
736
- })
737
- }
757
+ const to = from === id ? link.to : from
758
+ const target = index.entries[to]
759
+ if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
760
+ // A dangling edge (entry and entity both gone) used to be dropped here
761
+ // while getGraph rendered the same disk state as a [deleted] placeholder —
762
+ // the two views disagreed. Both now report the edge and mark it `missing`;
763
+ // the caller filters if it wants the old silence back.
764
+ const missing = !target && !entities[to]
765
+ out.push({
766
+ id: to,
767
+ title: target?.title || entities[to]?.name || '[deleted]',
768
+ kind: link.kind,
769
+ note: String(link.note || '').slice(0, 80),
770
+ confidence: link.confidence ?? 0.7,
771
+ missing,
772
+ retention: target ? null : (retentionOf.has(to) ? retentionOf.get(to) : 1),
773
+ })
738
774
  }
739
775
  // Confidence is the write-time claim; retention is how much of it survived. An
740
776
  // entity link pays both, a memory link only pays confidence.
package/lib/inject.js CHANGED
@@ -367,11 +367,16 @@ function speakerTag(entry) {
367
367
  // once (the card dropped `source`, so an `imagined` memory could be read as fact);
368
368
  // sharing the builder is what keeps them from drifting apart again.
369
369
  function privateHead(entry, id) {
370
- return `- [${id}] source=${entry.source || 'inferred'} · ${ownerPrefix(entry)}${entryTitle(entry)} · ${entry.layer || 'long_term'}${dateTag(entry)}${ageTag(entry)}${entry.marginalized ? ' · marginalized' : ''}${entry.openLoop ? ' · open_loop' : ''}${accuracyTag(entry)}${uncertaintyTag(entry)}${disclosureTag(entry)}${attachmentCountTag(entry)}${speakerTag(entry)}`
370
+ const source = entry.source || 'inferred'
371
+ const layer = entry.layer || 'long_term'
372
+ // A4:默认值不逐条重写(guide 已说明缺省口径)。非默认 source 必须保留 ——
373
+ // 丢掉 imagined / assistant_said 会把推测读成事实。
374
+ return `- [${id}]${source !== 'inferred' ? ` source=${source}` : ''} · ${ownerPrefix(entry)}${entryTitle(entry)}${layer !== 'long_term' ? ` · ${layer}` : ''}${dateTag(entry)}${ageTag(entry)}${entry.marginalized ? ' · marginalized' : ''}${entry.openLoop ? ' · open_loop' : ''}${accuracyTag(entry)}${uncertaintyTag(entry)}${disclosureTag(entry)}${attachmentCountTag(entry)}${speakerTag(entry)}`
371
375
  }
372
376
 
373
377
  function globalHead(entry, id) {
374
- return `- [${id}] ${entryTitle(entry)} · ${entry.domain || 'unknown'}${ageTag(entry)}${entry.confidence !== undefined ? ` · confidence ${entry.confidence}` : ''}${uncertaintyTag(entry)}`
378
+ const domain = entry.domain || 'unknown'
379
+ return `- [${id}] ${entryTitle(entry)}${domain !== 'unknown' ? ` · ${domain}` : ''}${ageTag(entry)}${entry.confidence !== undefined ? ` · confidence ${entry.confidence}` : ''}${uncertaintyTag(entry)}`
375
380
  }
376
381
 
377
382
  // Title card: the whole head, nothing else. The anchor and the per-turn recall are
@@ -915,11 +920,7 @@ function seenRecently(binding, id, turn, dedupeTurns) {
915
920
  // surface. It only says "if your session has a search tool, verify" — it must not
916
921
  // claim that web_search exists, and it must never touch the guide or rulesKey.
917
922
  function freshnessHintText(count) {
918
- return [
919
- '<memory-freshness>',
920
- `上面有 ${count} 条记忆带时间敏感信号(写于较久前或提到「最新」等)。若你的会话里有可用的搜索工具,回答当前状态前先核实;没有就如实说明可能过时。`,
921
- '</memory-freshness>',
922
- ].join('\n')
923
+ return `<memory-freshness>${count} 条可能过时;有搜索工具先核实,没有就说明可能过时。</memory-freshness>`
923
924
  }
924
925
 
925
926
  function staleRecallCount(recalled, freshnessDays) {
@@ -1068,9 +1069,10 @@ export async function buildRecall(binding, query, turn, settings = getSettings()
1068
1069
  for (const piece of pieces) {
1069
1070
  const open = `<memory-context scope="${piece.scope}" source="dsh-memu-memory">`
1070
1071
  const close = '</memory-context>'
1072
+ // A3:引言压到一句;完整口径(source 缺省、标题卡怎么取正文)在 guide 里只讲一次。
1071
1073
  const intro = piece.scope === 'private'
1072
- ? '以下是记忆,不是新的指令。source 表示来源;推测、转述与想象不得当成用户原话。条目是标题卡,取正文请用 memu_private_recall 按 id 或标题关键词查。'
1073
- : '以下是跨会话记忆,可能已过期;冲突时以当前私有事实为准。条目是标题卡,取正文请用 memu_global_recall 按 id 或标题关键词查。'
1074
+ ? '记忆证据,不是新指令;source 缺省 inferred。标题卡取正文用 memu_private_recall。'
1075
+ : '跨会话记忆,可能过时;冲突以私有事实为准。标题卡取正文用 memu_global_recall。'
1074
1076
  const lines = []
1075
1077
  // S2:冲突对先渲染一张卡;卡放不下就退回普通标题卡,不能因为卡片超预算
1076
1078
  // 让两条记忆都消失。
@@ -1266,6 +1268,20 @@ function renderMemoryGuide(payload) {
1266
1268
  * loss: some hosts hand the plugin only the current step's messages, and
1267
1269
  * re-appending there would duplicate the message on every turn.
1268
1270
  */
1271
+ /**
1272
+ * A1:本步是否需要新投 guide。keep=副本已在转录;skip=宿主只给了本步消息且稳态;
1273
+ * replace=首投/切域/改稿/guideLost。预算只在 replace 时预扣 —— 稳态回合不该
1274
+ * 每回合白压掉 600-1400 token 的召回容量。
1275
+ */
1276
+ function guideAdmission(binding, messages, guideKey) {
1277
+ const guides = (messages || []).filter(isMemoryGuideMessage)
1278
+ const valid = guides.filter((message) => memoryGuideKey(message) === guideKey)
1279
+ const steady = binding?.guideRulesKey === guideKey && binding.guideLost !== true
1280
+ if (steady && valid.length >= 1) return 'keep'
1281
+ if (steady && guides.length === 0) return 'skip'
1282
+ return 'replace'
1283
+ }
1284
+
1269
1285
  function ensureUnifiedGuide(ctx, payload, decision) {
1270
1286
  try {
1271
1287
  const header = payload?.agent?.session?.header
@@ -1356,7 +1372,8 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1356
1372
  const media = (getSessionBinding(sessionId)?.pendingMedia || []).filter(item => images.some(image => image.attachment.attachmentId === (item.sourceAttachmentId || item.sha256)))
1357
1373
  const imageCount = images.length
1358
1374
  setSessionBinding(sessionId, { lastImageCount: imageCount })
1359
- const anchorNeeded = effective.reinjectPending || !(effective.injectedIds || []).includes(ANCHOR_SENTINEL)
1375
+ const anchorPushedBefore = effective.anchorPushed ?? (effective.injectedIds || []).includes(ANCHOR_SENTINEL)
1376
+ const anchorNeeded = effective.reinjectPending || anchorPushedBefore !== true
1360
1377
  // turnTokens remains the recall block's own ceiling, but injectionTotalTokens is
1361
1378
  // the ceiling for the whole plugin message. The two must be applied together:
1362
1379
  // otherwise a 160-token total with an 800-token recall budget injects ~786.
@@ -1364,8 +1381,9 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1364
1381
  const totalBudget = Math.max(0, Number(settings.injectionTotalTokens ?? 2000))
1365
1382
  let guideReserve = 0
1366
1383
  try {
1367
- const guideTokens = estTokens(renderMemoryGuide({ agent }).text)
1368
- if (guideTokens <= totalBudget) guideReserve = guideTokens
1384
+ const guide = renderMemoryGuide({ agent })
1385
+ if (guideAdmission(getSessionBinding(sessionId), decision?.messages, guide.key) === 'replace'
1386
+ && guide.tokens <= totalBudget) guideReserve = guide.tokens
1369
1387
  } catch {}
1370
1388
  const effectiveTotalBudget = Math.max(0, totalBudget - guideReserve)
1371
1389
  const totalRoom = () => Math.max(0, effectiveTotalBudget - estTokens(parts.join('\n\n')) - (parts.length ? 2 : 0))
@@ -1540,7 +1558,8 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1540
1558
  setSessionBinding(sessionId, { lastImageCount: imageCount })
1541
1559
  const tooShort = !imageCount && query.length < Number(settings.minUserChars || 6)
1542
1560
  const reinject = binding.reinjectPending === true
1543
- const anchorNeeded = reinject || !(binding.injectedIds || []).includes(ANCHOR_SENTINEL)
1561
+ const anchorPushedAlready = binding.anchorPushed ?? (binding.injectedIds || []).includes(ANCHOR_SENTINEL)
1562
+ const anchorNeeded = reinject || anchorPushedAlready !== true
1544
1563
 
1545
1564
  // Read the present mood before retrieval so the recall ordering can use it.
1546
1565
  if (!reinject && !tooShort) setSessionMood(sessionId, readMood(query))
@@ -1559,8 +1578,9 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1559
1578
  // 预算时就为它预扣;guide 自身大于总预算时不预扣,并让 ensureUnifiedGuide 跳过它。
1560
1579
  let guideReserve = 0
1561
1580
  try {
1562
- const guideTokens = estTokens(renderMemoryGuide({ agent }).text)
1563
- if (guideTokens <= totalInjectionBudget) guideReserve = guideTokens
1581
+ const guide = renderMemoryGuide({ agent })
1582
+ if (guideAdmission(getSessionBinding(sessionId), decision?.messages, guide.key) === 'replace'
1583
+ && guide.tokens <= totalInjectionBudget) guideReserve = guide.tokens
1564
1584
  } catch {}
1565
1585
  const injectionBudget = Math.max(0, totalInjectionBudget - guideReserve)
1566
1586
  const totalRoom = () => Math.max(0, injectionBudget - estTokens(parts.join('\n\n')) - (parts.length ? 2 : 0))
package/lib/media.js CHANGED
@@ -269,6 +269,13 @@ export async function captionImage(libraryId, sha256) {
269
269
  if (linked.some(entry => entry.visibility === 'secret' || entry.disclosure === 'never_say')) return null
270
270
  const data = fs.readFileSync(blobFile(libraryId, sha256, blob.ext))
271
271
  if (data.length > FILE_LIMIT) return null
272
+ // C7:vision 请求前先缩放。原图最长边 1024px、JPEG q85;不做放大,动图取首帧。
273
+ // 配额、sha 去重与 max_tokens 都不变——只改发出去的字节。
274
+ const { default: sharp } = await import('sharp')
275
+ const prepared = await sharp(data, { limitInputPixels: 40_000_000, animated: false })
276
+ .resize({ width: 1024, height: 1024, fit: 'inside', withoutEnlargement: true })
277
+ .jpeg({ quality: 85 })
278
+ .toBuffer()
272
279
  const reserved = withFileLock(poolFile(libraryId), () => {
273
280
  const pool = loadPool(libraryId)
274
281
  const now = Date.now()
@@ -289,7 +296,7 @@ export async function captionImage(libraryId, sha256) {
289
296
  body: JSON.stringify({ model: config.model, max_tokens: 100, temperature: 0,
290
297
  messages: [{ role: 'user', content: [
291
298
  { type: 'text', text: loadPrompt('image-caption').text },
292
- { type: 'image_url', image_url: { url: `data:${blob.mime};base64,${data.toString('base64')}` } },
299
+ { type: 'image_url', image_url: { url: `data:image/jpeg;base64,${prepared.toString('base64')}` } },
293
300
  ] }] }),
294
301
  })
295
302
  if (!response.ok) throw new Error(`vision service returned HTTP ${response.status}`)
package/lib/memory.js CHANGED
@@ -2598,7 +2598,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2598
2598
  return scored
2599
2599
  }
2600
2600
 
2601
- export async function privateList({ exec, libraryId, preferIndex = false }) {
2601
+ async function privateListRaw({ exec, libraryId, preferIndex = false }) {
2602
2602
  const scope = resolveLibrary({ exec, libraryId, readOnly: true })
2603
2603
  if (scope.binding) assertScopeEnabled(scope.binding)
2604
2604
  const index = loadPrivateIndex(scope.libraryId)
@@ -2681,6 +2681,21 @@ export async function privateList({ exec, libraryId, preferIndex = false }) {
2681
2681
  }
2682
2682
  }
2683
2683
 
2684
+ /** 分页只切返回值;不传 limit 保持全量(现有 UI/RPC 调用方行为不变)。 */
2685
+ export async function privateList({ exec, libraryId, preferIndex = false, limit = null, offset = 0 }) {
2686
+ const result = await privateListRaw({ exec, libraryId, preferIndex })
2687
+ const files = Array.isArray(result.files) ? result.files : []
2688
+ const total = files.length
2689
+ const start = Math.max(0, Math.floor(Number(offset) || 0))
2690
+ const size = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.floor(Number(limit)) : null
2691
+ return {
2692
+ ...result,
2693
+ total,
2694
+ offset: start,
2695
+ files: size ? files.slice(start, start + size) : files,
2696
+ }
2697
+ }
2698
+
2684
2699
  // Everything a memory *is* stays editable, not only its words: `track`, `peak`, the
2685
2700
  // mood lens and the attachment list all change how an entry is scored, aggregated or
2686
2701
  // rendered, so a wrong value in any of them was a permanent mis-filing that could
package/lib/memu.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
+ import crypto from 'node:crypto'
3
4
  import { spawn } from 'node:child_process'
4
5
  import { dataDir, ensureDir, redactSecrets, warn, windowsSystemEnv } from './paths.js'
5
6
  import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
@@ -8,6 +9,9 @@ import { activeProfile, captureVectorGeneration, assertVectorGeneration, assertP
8
9
  import { embeddingWorkerManager } from './local-embedding-manager.js'
9
10
  import { modelIdForRole } from './local-embedding-protocol.js'
10
11
 
12
+ // 单次命令捕获上限:工具输出异常放大时不能把整个进程内存吃光;超限只标 truncated。
13
+ const MAX_CAPTURE_CHARS = 8 * 1024 * 1024
14
+
11
15
  // MemU's own storage mode. 'local' keeps every row in this plugin's sqlite files;
12
16
  // 'cloud' hands storage to MemU's backend and needs the vendor credentials in
13
17
  // ~/.memu/config.env. Read per call, never cached, so toggling it takes effect on
@@ -51,13 +55,21 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
51
55
  })
52
56
  let stdout = ''
53
57
  let stderr = ''
58
+ let truncated = false
54
59
  let timedOut = false
55
60
  const timer = setTimeout(() => {
56
61
  timedOut = true
57
62
  try { child.kill() } catch {}
58
63
  }, timeoutMs)
59
- child.stdout?.on('data', (d) => { stdout += d.toString() })
60
- child.stderr?.on('data', (d) => { stderr += d.toString() })
64
+ child.stdout?.on('data', (d) => {
65
+ const text = d.toString()
66
+ if (stdout.length + text.length > MAX_CAPTURE_CHARS) { truncated = true; return }
67
+ stdout += text
68
+ })
69
+ child.stderr?.on('data', (d) => {
70
+ if (stderr.length >= 64 * 1024) return
71
+ stderr += d.toString()
72
+ })
61
73
  child.on('error', (error) => {
62
74
  clearTimeout(timer)
63
75
  reject(new MemuError(`failed to start memu: ${error.message}`, 'MEMU_SPAWN_FAILED', { error }))
@@ -65,7 +77,7 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
65
77
  child.on('close', (code) => {
66
78
  clearTimeout(timer)
67
79
  if (code === 0) {
68
- resolve({ stdout, stderr, code })
80
+ resolve({ stdout, stderr, code, truncated })
69
81
  return
70
82
  }
71
83
  const secrets = Object.entries({ ...process.env, ...(env || {}) }).filter(([key]) => /(?:API_KEY|TOKEN|SECRET)$/.test(key)).map(([, value]) => value)
@@ -345,7 +357,7 @@ async function runResident(args, { env, timeoutMs = 90_000 } = {}) {
345
357
  const failure = new MemuError(
346
358
  `memu ${label} failed (timeout): the resident engine did not answer in ${Math.round(timeoutMs / 1000)}s`,
347
359
  'MEMU_COMMAND_FAILED',
348
- { code: null, stdout: '', stderr: '', timedOut: true },
360
+ { code: null, stdout: '', stderr: '', timedOut: true, killed: true },
349
361
  )
350
362
  reject(failure)
351
363
  // A Python command cannot be cancelled from the outside, so a stuck command
@@ -494,9 +506,10 @@ export async function listFiles({ db, provider, embedModel, baseUrl, apiKey, vec
494
506
 
495
507
  export async function commit({ payload, db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs = 180_000 }) {
496
508
  const tmpDir = ensureDir(path.join(dataDir(), 'tmp'))
497
- const file = path.join(tmpDir, `commit-${process.pid}-${Date.now()}.json`)
509
+ // 临时文件名不可预测(旧版 pid+Date.now 可被并行进程猜到),并收紧权限。
510
+ const file = path.join(tmpDir, `commit-${crypto.randomUUID()}.json`)
498
511
  try {
499
- fs.writeFileSync(file, JSON.stringify(payload, null, 2), 'utf8')
512
+ fs.writeFileSync(file, JSON.stringify(payload), { encoding: 'utf8', mode: 0o600 })
500
513
  const res = await runConfigured(['commit', file, '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs, role: 'document' })
501
514
  const data = parseJson(res.stdout)
502
515
  if (data === null) {
package/lib/private.js CHANGED
@@ -52,7 +52,7 @@ export function shortTermBrief(binding, { now = Date.now() } = {}) {
52
52
  '[short_term · 快到期了]',
53
53
  '下面这些是你近期记下的短期条目,到期会自己消失。逐条决定:',
54
54
  '值得留下的升级 —— memu_private_update id=<id> layer=long_term(要补充的正文这次一并写上);',
55
- '不重要的归档 —— memu_private_archive id=<id>;',
55
+ '不重要的归档 —— memu_private_update id=<id> status=archived;',
56
56
  '还说不清的别动,它自己会过期。',
57
57
  ...rows.map((row) => `- [${row.id}] ${row.title} · 约 ${row.left} 小时后过期`),
58
58
  ].join('\n')
@@ -167,14 +167,17 @@ export function assessConsolidationValue(events) {
167
167
  // tail, compact the noise, and leave the rest for the next window.
168
168
  export const CONSOLIDATION_BACKLOG_EVENTS = 200
169
169
  export const CONSOLIDATION_BACKLOG_TURNS = 10
170
+ // 小增量顺延:非手动整理时,少于 3 个真人回合的增量先不 fork。它不推进游标,
171
+ // 下一次触发会把顺延的事件一起带上;上限仍由上面的水位常量兜底,饥饿时放行。
172
+ export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
170
173
  // A checkpoint is measured in session events, and six of them are pure turn/step
171
174
  // wrappers. 300 events therefore bought only ~50 turns of transcript. 500 keeps
172
175
  // the same seed size in practice but cuts one fork for a 200-turn catch-up.
173
176
  export const CONSOLIDATION_WINDOW_EVENTS = 500
174
177
  export const CONSOLIDATION_PROBE_MINUTES = 15
175
178
  export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
176
- const SEED_TOOL_RESULT_CHARS = 1_200
177
- const SEED_TOOL_CALL_CHARS = 600
179
+ const SEED_TOOL_RESULT_CHARS = 1_100
180
+ const SEED_TOOL_CALL_CHARS = 500
178
181
  const SEED_TEXT_CHARS = 12_000
179
182
  const SEED_CATALOG_ENTRIES = 18
180
183
 
@@ -225,7 +228,11 @@ function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
225
228
  * Session's "contiguous from zero" rule holds. The optional catalog event takes
226
229
  * seq 0 and is the only synthetic message.
227
230
  */
228
- export function compactSeedEvents(events, catalogEvent = null) {
231
+ export function compactSeedEvents(events, prelude = null) {
232
+ const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
233
+ .filter((event) => event && typeof event === 'object')
234
+ .map((event, index) => ({ ...event, seq: index }))
235
+ const offset = preludeEvents.length
229
236
  const kept = []
230
237
  const seenToolText = new Set()
231
238
  for (const event of Array.isArray(events) ? events : []) {
@@ -266,10 +273,10 @@ export function compactSeedEvents(events, catalogEvent = null) {
266
273
  }
267
274
 
268
275
  const mapping = new Map()
269
- kept.forEach((event, index) => mapping.set(Number(event.seq), index + (catalogEvent ? 1 : 0)))
270
- const out = catalogEvent ? [{ ...catalogEvent, seq: 0 }] : []
276
+ kept.forEach((event, index) => mapping.set(Number(event.seq), index + offset))
277
+ const out = [...preludeEvents]
271
278
  kept.forEach((event, index) => {
272
- const next = { ...event, seq: index + (catalogEvent ? 1 : 0) }
279
+ const next = { ...event, seq: index + offset }
273
280
  if (Array.isArray(next.sourceEventSeqs)) {
274
281
  const mapped = [...new Set(next.sourceEventSeqs
275
282
  .map(value => mapping.get(Number(value)))
@@ -468,6 +475,62 @@ export function memoryCatalogEvent(binding, now = Date.now()) {
468
475
  }
469
476
  }
470
477
 
478
+ function recentUserText(events, limit = 6) {
479
+ const parts = []
480
+ for (const event of Array.isArray(events) ? events : []) {
481
+ if (event?.type !== 'user/message' || event.data?.source?.kind !== 'user') continue
482
+ for (const block of event.data?.content || []) {
483
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) parts.push(block.text.trim())
484
+ }
485
+ }
486
+ return parts.slice(-limit).join('\n')
487
+ }
488
+
489
+ /**
490
+ * 1.3.1:本窗候选的本地召回命中。worker 不再获得 recall/list 工具,去重所需的
491
+ * 旧条目必须在种子里就给出;这里用插件现有的 BM25 词法腿做零 Token 预召回,
492
+ * 只给 id + 标题 + 一段正文,够 worker 判断 update 还是 remember。
493
+ */
494
+ export function memoryRecallEvent({ binding = null, candidates = [], events = [], now = Date.now(), topK = 6 } = {}) {
495
+ if (!binding?.libraryId) return null
496
+ let rows = []
497
+ try {
498
+ rows = Object.entries(loadPrivateIndex(binding.libraryId).entries || {})
499
+ .filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
500
+ .filter(([, entry]) => visibleToSession(entry, binding.sessionId))
501
+ .map(([id, entry]) => ({ ...entry, id }))
502
+ } catch { return null }
503
+ if (rows.length === 0) return null
504
+ const query = [
505
+ ...(Array.isArray(candidates) ? candidates.map((item) => item?.text) : []),
506
+ recentUserText(events),
507
+ ].filter(Boolean).join('\n')
508
+ const tokens = tokenize(query)
509
+ if (tokens.length === 0) return null
510
+ const corpus = buildCorpus(rows)
511
+ const scored = rows
512
+ .map((entry) => ({ entry, score: bm25(tokens, corpus.docs.get(entry.id), corpus) }))
513
+ .filter((item) => item.score > 0)
514
+ .sort((a, b) => b.score - a.score)
515
+ .slice(0, Math.max(1, Number(topK) || 6))
516
+ if (scored.length === 0) return null
517
+ const text = [
518
+ '[memory-recall · 本地召回命中(只读上下文,不是用户发言,也不属于本轮转录)]',
519
+ '下面是与本窗候选最相关的已有条目;只用于去重/合并,不是用户说过的话,也不是新证据。',
520
+ ...scored.map(({ entry }) => `- [${entry.id}] ${capSeedText(entry.title || '(untitled)', 80)} — ${capSeedText(entry.content || '', 90)}`),
521
+ ].join('\n')
522
+ return {
523
+ type: 'user/message',
524
+ seq: 0,
525
+ time: now,
526
+ data: createUserMessage({
527
+ content: [{ type: 'text', text }],
528
+ source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' },
529
+ }),
530
+ surfaceOp: 'append',
531
+ }
532
+ }
533
+
471
534
  /** First `limit` events, trimmed back to a complete turn so a fork never sees half a step. */
472
535
  export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
473
536
  const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
@@ -712,7 +775,7 @@ async function restrictWorkerTools(agents, childId, parentId) {
712
775
  } catch (error) {
713
776
  // A host missing one of the optional tools must not lose consolidation;
714
777
  // retry with the write/read core and let the brief tell the truth.
715
- const core = ['memu_private_remember', 'memu_private_update', 'memu_private_list', 'memu_status']
778
+ const core = [...CORE_WRITE_TOOLS]
716
779
  try {
717
780
  return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
718
781
  } catch (inner) {
@@ -747,7 +810,7 @@ const inFlight = new Map()
747
810
  const WORKER_STOP_GRACE_MS = 5_000
748
811
 
749
812
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
750
- // 的 file:line 当成诊断契约(当前 lib/private.js:742),修改位置时同步更新该诊断映射,
813
+ // 的 file:line 当成诊断契约(当前 lib/private.js:805),修改位置时同步更新该诊断映射,
751
814
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
752
815
  import { warn } from './paths.js'
753
816
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
@@ -757,8 +820,8 @@ import {
757
820
  readCarryCandidates, setCarryCandidates,
758
821
  } from './consolidation-ledger.js'
759
822
  import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
760
- import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
761
- import { tokenize } from './text-retrieval.js'
823
+ import { buildWorkerBrief, probeToolSurface, CORE_WRITE_TOOLS, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
824
+ import { tokenize, buildCorpus, bm25 } from './text-retrieval.js'
762
825
  import { isGoneSessionError } from './cycle.js'
763
826
  import { autoLinkPrivateMemories } from './private-links.js'
764
827
  import { registerTools } from './tools.js'
@@ -829,6 +892,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
829
892
  inFlight.set(sessionId, abort)
830
893
  let handle = null
831
894
  let offSession = null
895
+ // N3:worker 工具循环的软/硬上限。软上限追加收尾提示,硬上限停掉 fork;
896
+ // 已经写入库的条目不会因为硬停被撤销(游标不推进,下一窗重试剩余范围)。
897
+ let workerToolRounds = 0
832
898
  let idle = null
833
899
  // Stopped once, callable twice: the timeout path and `finally` both need it.
834
900
  let stopped = false
@@ -996,6 +1062,17 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
996
1062
  // 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
997
1063
  const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
998
1064
  const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
1065
+ // 小增量顺延:不 fork、不推进游标;下一次触发把这段一起带上。
1066
+ // 首次整理(还没有成功游标)不受限,尽快建立记忆基线;饥饿(长时间空闲)
1067
+ // 仍然放行,保证收尾;force 手动路径不经过这里。
1068
+ const firstPass = !binding.lastSleepSeq
1069
+ if (!starved && !firstPass && Number(value.humanTurns) < CONSOLIDATION_MIN_HUMAN_TURNS) {
1070
+ return finish({
1071
+ ok: true, sessionId, skipped: 'below-min-turns', settled: false, deferred: true,
1072
+ reasonCode: 'below-min-turns', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1073
+ trigger: options.trigger,
1074
+ })
1075
+ }
999
1076
  const evidence = collectEvidence(candidateEvents)
1000
1077
  const wake = assessWake({
1001
1078
  evidence,
@@ -1024,7 +1101,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1024
1101
  }
1025
1102
 
1026
1103
  // One bounded window per run: the next sweep continues from the new cursor.
1027
- const window = selectConsolidationWindow(candidateEvents)
1104
+ // 失败重试(sleepAttempts>0)时窗口减半:同一游标反复超时不该每次都付整窗成本,
1105
+ // 前半段先结算,剩余留给下一次。
1106
+ const sleepAttempt = Number(binding.sleepAttempts || 0)
1107
+ const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
1108
+ const window = selectConsolidationWindow(candidateEvents, windowLimit)
1028
1109
  if (window.events.length === 0) {
1029
1110
  return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1030
1111
  }
@@ -1039,7 +1120,13 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1039
1120
  const snapshotMeta = snapshotMetaOf(windowSnapshot)
1040
1121
  // 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
1041
1122
  const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
1042
- const seedEvents = compactSeedEvents(candidateSeedEvents(window.events), memoryCatalogEvent({ ...binding, sessionId }))
1123
+ // 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
1124
+ const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1125
+ const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events))
1126
+ const seedEvents = compactSeedEvents(candidateSeedEvents(window.events), [
1127
+ memoryCatalogEvent({ ...binding, sessionId }),
1128
+ memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
1129
+ ])
1043
1130
  if (seedEvents.length === 0) {
1044
1131
  return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
1045
1132
  }
@@ -1110,6 +1197,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1110
1197
  const resolved = resolveConsolidationAgentOptions(settings, inherited)
1111
1198
  let agentOptions = resolved.options
1112
1199
  let modelMode = resolved.reason
1200
+ // 1.3.1:整理思考强度可独立于父会话;'inherit' 保持旧行为。
1201
+ const effort = settings.consolidationReasoningEffort
1202
+ if (agentOptions && effort && effort !== 'inherit') {
1203
+ agentOptions = { ...agentOptions, reasoningEffort: effort }
1204
+ }
1113
1205
  if (!agentOptions) {
1114
1206
  // no-inherited-route 与旧失败路径逐字节一致(inherit 模式语义不变);host/custom
1115
1207
  // 的坏配置各自带 reasonCode,整理提醒能直接说清是哪个配置面写错了。
@@ -1220,6 +1312,15 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1220
1312
  // 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
1221
1313
  if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
1222
1314
  revalidate('worker-write')
1315
+ workerToolRounds += 1
1316
+ if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
1317
+ try { abort.abort() } catch {}
1318
+ } else {
1319
+ const guidance = workerRoundGuidance(workerToolRounds)
1320
+ if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1321
+ try { handle?.agent?.followup?.(noticeMessage(guidance.text, '整理收尾提示')) } catch {}
1322
+ }
1323
+ }
1223
1324
  return
1224
1325
  }
1225
1326
  return
@@ -1270,9 +1371,17 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1270
1371
  })
1271
1372
  }
1272
1373
 
1273
- const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1274
- const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events))
1275
- const brief = buildWorkerBrief({ snapshot, probe, contract: receiptContractText({ jobId, snapshotHash: snapshot.hash }), reason: force ? 'manual' : 'auto', jobId, mustCover })
1374
+ const brief = buildWorkerBrief({
1375
+ snapshot,
1376
+ probe,
1377
+ contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1378
+ reason: force ? 'manual' : 'auto',
1379
+ jobId,
1380
+ mustCover,
1381
+ autoReceipt: true,
1382
+ // 上一轮 batch 参数 JSON 畸形:这一轮只让模型逐条 remember,降低再次整段失败的概率。
1383
+ singleOnly: Boolean(binding.consolidationSingleOnly),
1384
+ })
1276
1385
  handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
1277
1386
  // followup only queues. whenIdle says the driver stopped; turn/end says
1278
1387
  // whether that turn actually succeeded, so both are checked below.
@@ -1290,8 +1399,17 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1290
1399
  if (outcome === 'done') {
1291
1400
  const failure = turnEndFailure(turnEnd)
1292
1401
  if (failure) {
1293
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-turn-failed', error: failure }))
1294
- return finish({ ok: false, error: 'consolidation fork failed: ' + failure, sessionId, childId, settled: false, timedOut: false })
1402
+ // batch 参数的 JSON 畸形是模型生成问题,不是整理逻辑故障:标记下一次
1403
+ // 只用逐条 remember,并让重试路径接住(consolidateAll 已有 2 次重试)。
1404
+ const batchJsonInvalid = /memu_private_remember_batch/.test(String(failure))
1405
+ && /JSON|Expected ','|after array element/.test(String(failure))
1406
+ const reasonCode = batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
1407
+ if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
1408
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable: batchJsonInvalid, error: failure }))
1409
+ return finish({
1410
+ ok: false, error: 'consolidation fork failed: ' + failure, sessionId, childId,
1411
+ settled: false, timedOut: false, retryable: batchJsonInvalid, reasonCode,
1412
+ })
1295
1413
  }
1296
1414
  // 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。
1297
1415
  const generationNow = scopeGenerationOf(getSessionBinding(sessionId))
@@ -1314,7 +1432,16 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1314
1432
  try { index = loadPrivateIndex(binding.libraryId) } catch { index = null }
1315
1433
  // 完成不是"没报错":worker 的回执 + 库里的真实变化,两边对上才结算。
1316
1434
  const workerText = assistantTexts.join('\n')
1317
- decision = decideCompletion({ text: workerText, wrote, index, beforeIds, beforeEntries, expectedJobId: jobId, expectedSnapshotHash: snapshot.hash })
1435
+ decision = decideCompletion({
1436
+ text: workerText,
1437
+ wrote,
1438
+ index,
1439
+ beforeIds,
1440
+ beforeEntries,
1441
+ expectedJobId: jobId,
1442
+ expectedSnapshotHash: snapshot.hash,
1443
+ autoReceipt: { jobId, snapshotHash: snapshot.hash, checkedRange: { fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq } },
1444
+ })
1318
1445
 
1319
1446
  if (!decision.advance) {
1320
1447
  safeLedger(() => failJob({
@@ -1343,7 +1470,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1343
1470
  reasonCode: 'ledger-not-advanced', snapshot: snapshotMeta,
1344
1471
  error: 'the consolidation ledger could not verify the covered snapshot range' })
1345
1472
  }
1346
- setSessionBinding(sessionId, { lastSleepSeq: snapshot.throughSeq })
1473
+ setSessionBinding(sessionId, { lastSleepSeq: snapshot.throughSeq, consolidationSingleOnly: false })
1347
1474
  // 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
1348
1475
  // brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
1349
1476
  const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]