dsh-memu-memory 1.3.15 → 1.4.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.
Files changed (73) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +49 -1
  3. package/README.md +4 -1
  4. package/README.zh.md +4 -1
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/host-adaptation.md +52 -36
  7. package/docs/host-versions.md +120 -0
  8. package/docs/memory-semantics.md +4 -2
  9. package/docs/pending-work.md +51 -0
  10. package/docs/troubleshooting.md +41 -2
  11. package/lib/auto-link/candidates.js +4 -1
  12. package/lib/auto-link/decide.js +1 -1
  13. package/lib/auto-link/normalize.js +2 -2
  14. package/lib/auto-link/terminology.js +31 -1
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +53 -6
  17. package/lib/consolidation-snapshot.js +7 -1
  18. package/lib/consolidation-worker.js +11 -3
  19. package/lib/curator.js +17 -5
  20. package/lib/cycle.js +75 -4
  21. package/lib/diagnostics.js +10 -0
  22. package/lib/entity-repair.js +285 -0
  23. package/lib/environment-check.js +72 -3
  24. package/lib/global-graph.js +11 -2
  25. package/lib/graph.js +32 -8
  26. package/lib/host-surface.js +30 -0
  27. package/lib/index.js +120 -3
  28. package/lib/inject.js +142 -8
  29. package/lib/memory.js +72 -0
  30. package/lib/private-links.js +12 -0
  31. package/lib/private.js +49 -13
  32. package/lib/prompts/private-consolidation.coding.md +3 -1
  33. package/lib/prompts/private-consolidation.md +2 -0
  34. package/lib/prompts/private-consolidation.mixed.md +2 -0
  35. package/lib/prompts/private-consolidation.rp.md +2 -0
  36. package/lib/prompts/system-guide.coding.md +8 -2
  37. package/lib/prompts/system-guide.md +6 -0
  38. package/lib/prompts/system-guide.mixed.md +11 -0
  39. package/lib/prompts/system-guide.rp.md +6 -0
  40. package/lib/rpc.js +48 -10
  41. package/lib/state.js +5 -1
  42. package/lib/turn-log.js +34 -11
  43. package/lib/worker-pool.js +11 -7
  44. package/package.json +16 -1
  45. package/scripts/chain-matrix.mjs +4 -0
  46. package/scripts/check-doc-drift.mjs +194 -0
  47. package/scripts/entity-dedupe.mjs +110 -0
  48. package/tests/auto-link-candidates.test.mjs +22 -9
  49. package/tests/auto-link-decide.test.mjs +59 -59
  50. package/tests/auto-link-migration.test.mjs +4 -4
  51. package/tests/client-render.test.mjs +112 -1
  52. package/tests/consolidation-fork.test.mjs +20 -1
  53. package/tests/curator-probe.test.mjs +19 -1
  54. package/tests/cycle.test.mjs +2 -2
  55. package/tests/diagnostics.test.mjs +21 -0
  56. package/tests/doc-drift.test.mjs +122 -2
  57. package/tests/entity-merge.test.mjs +17 -0
  58. package/tests/environment-check.test.mjs +28 -0
  59. package/tests/global-graph.test.mjs +16 -0
  60. package/tests/global-lifecycle.test.mjs +24 -4
  61. package/tests/graph-cascade.test.mjs +111 -0
  62. package/tests/hybrid-recall.test.mjs +1 -1
  63. package/tests/inject-guide.test.mjs +108 -1
  64. package/tests/managed-memory.test.mjs +7 -7
  65. package/tests/private-links.test.mjs +12 -0
  66. package/tests/prompts.test.mjs +30 -0
  67. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  68. package/tests/salience-domain.test.mjs +34 -0
  69. package/tests/settings-plumbing.test.mjs +2 -0
  70. package/tests/stale-maintenance.test.mjs +131 -0
  71. package/tests/tools.test.mjs +1 -1
  72. package/tests/turn-log.test.mjs +13 -0
  73. package/tests/webui-auth.test.mjs +58 -0
package/lib/index.js CHANGED
@@ -5,8 +5,8 @@ import { registerRpc } from './rpc.js'
5
5
  import { registerCycle } from './cycle.js'
6
6
  import { syncPromptDefaults } from './prompts.js'
7
7
  import { ensureEngine, engineStatus, ENGINE_VERSION } from './engine.js'
8
- import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibraries, getSessionBinding } from './state.js'
9
- import { buildTurnRecords, recordTurn, deleteTurnLog } from './turn-log.js'
8
+ import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibraries, getSessionBinding, getCycleState, setCycleState, loadPrivateIndex } from './state.js'
9
+ import { buildTurnRecords, recordTurn, deleteTurnLog, turnLogLimits } from './turn-log.js'
10
10
  import { pruneOrphanEntitiesAll } from './graph.js'
11
11
  import { pruneDeletedStores } from './memory.js'
12
12
  import { closeEmbeddingWorkers, setEmbeddingFailureSink } from './local-embedding-manager.js'
@@ -16,6 +16,7 @@ import { vectorStatus } from './vector-profile.js'
16
16
  import { setWarnSink, warn } from './paths.js'
17
17
  import { recordDiagnostic, recordErrorDiagnostic } from './diagnostics.js'
18
18
  import { autoRepairEnvironment, runEnvironmentCheck } from './environment-check.js'
19
+ import { planAllRepairs, applyRepairGroups } from './entity-repair.js'
19
20
 
20
21
  export const name = 'dsh-memu-memory'
21
22
  // `timer` backs ctx.interval, used by the idle/auto-curation sweep. Reading an
@@ -139,6 +140,119 @@ function startOrphanEntitySweep(ctx) {
139
140
  }
140
141
  }
141
142
 
143
+ // 一次性实体碎片修复(docs/pending-work.md §14.2 P7):老版本把 n-gram 滑窗的窗口片段当成
144
+ // 人名建了节点(`南宫晚` / `宫晚晴` 其实是 `南宫晚晴`)。提名侧已修,但已落盘的碎片不会自己合,
145
+ // 也不会因为升级就变干净——所以新版本启动后自动跑一次。
146
+ //
147
+ // 界线(本函数唯一需要守住的):
148
+ // · attested(可证明)——窗口首尾重叠重建出的完整名**在正文里出现过**,或短名在全库正文里
149
+ // 从未独立于某个更长名字出现 → 自动合并。
150
+ // · similar(只是相似)——编辑距离 ≤2 或名字核重合(`顾清欢` 与 `顾清悦` 就是这么撞上的)→
151
+ // **一律不动**,只在诊断页报数并给一个「需确认」的修复按钮(environment-check 的 MANUAL 面)。
152
+ //
153
+ // 只跑一次:标记写进 `state.cycle.entityRepairVersion`(与 lastCurateAt 同族,不新造机制)。
154
+ // 幂等:合过的库第二次规划不出 attested 组;no-op 时一个字节都不写。
155
+ // 写入前先备份(合并级联不改记忆正文,但撤销要靠这份快照)。任何失败只 warn/记诊断,
156
+ // 加载绝不能被它绊住(硬规则 10:降级必须留可见信号)。
157
+ const ENTITY_REPAIR_VERSION = 1
158
+
159
+ /**
160
+ * 升级自愈的执行体。单独导出是为了让测试能不开定时器、不装假 ctx 就直接跑同一段代码
161
+ * (startEntityRepairPass 只负责"延迟 5 秒 + 只跑一次"这两件事)。
162
+ */
163
+ export async function runEntityRepairPass({ note = () => {}, warn = () => {}, diagnose = () => {} } = {}) {
164
+ let settings = null
165
+ try { settings = getSettings() } catch {}
166
+ let cycle = null
167
+ try { cycle = getCycleState() } catch {}
168
+ if (Number(cycle?.entityRepairVersion || 0) >= ENTITY_REPAIR_VERSION) return { skipped: 'done' }
169
+ if (settings?.autoRepairEntityFragments === false) {
170
+ note('entity repair skipped (autoRepairEntityFragments=off)')
171
+ return { skipped: 'setting' }
172
+ }
173
+ const plan = planAllRepairs({ listLibraries, loadPrivateIndex })
174
+ if (!plan.attested && !plan.similar && !plan.failures.length) {
175
+ setCycleState({ entityRepairVersion: ENTITY_REPAIR_VERSION, entityRepairAt: new Date().toISOString() })
176
+ return { skipped: 'clean', plan }
177
+ }
178
+ const results = []
179
+ let deferred = false
180
+ if (plan.attested > 0) {
181
+ // 备份失败就一个字节都不写:合并级联会改实体指向,没有可撤销的快照就不许动手。
182
+ // 标记此时保持未写,下次启动再试一次。
183
+ let backedUp = true
184
+ try {
185
+ await backupDatabases({ label: 'entity-repair' })
186
+ } catch (error) {
187
+ backedUp = false
188
+ deferred = true
189
+ warn(`entity repair deferred: no backup available (${error?.code || error?.message || error})`)
190
+ diagnose({
191
+ level: 'warn', scope: 'graph', code: 'ENTITY_REPAIR_DEFERRED', alert: false,
192
+ message: '实体碎片修复顺延:图备份没成功',
193
+ hint: '备份可用后(下一次启动,或诊断页手动触发)再合并;本次没有写入任何改动。',
194
+ detail: { attested: plan.attested, similar: plan.similar },
195
+ source: 'entity-repair',
196
+ })
197
+ }
198
+ if (backedUp) {
199
+ for (const entry of plan.plans) {
200
+ if (!entry.groups.length) continue
201
+ results.push(applyRepairGroups(entry.libraryId, entry.groups))
202
+ }
203
+ }
204
+ }
205
+ const merged = results.reduce((total, row) => total + row.merged, 0)
206
+ const created = results.reduce((total, row) => total + row.created, 0)
207
+ const protectedRows = results.reduce((total, row) => total + row.restored, 0)
208
+ const failures = [...plan.failures, ...results.flatMap((row) => row.failures || [])]
209
+ if (!deferred) {
210
+ setCycleState({
211
+ entityRepairVersion: ENTITY_REPAIR_VERSION,
212
+ entityRepairAt: new Date().toISOString(),
213
+ entityRepairMerged: merged,
214
+ entityRepairPending: plan.similar,
215
+ })
216
+ }
217
+ if (merged || created) {
218
+ note(`entity repair merged ${merged} group(s), created ${created} reconstructed node(s)`)
219
+ diagnose({
220
+ level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_REPAIRED', alert: true,
221
+ message: `升级后自动合并了 ${merged} 组名字碎片(其中 ${created} 组新建了正文里出现过的完整名)`,
222
+ hint: '原图已先行备份;记忆正文与条目本身没有被修改,只改了实体指向。',
223
+ detail: { merged, created, protectedRows, libraries: results.map((row) => row.libraryId) },
224
+ source: 'entity-repair',
225
+ })
226
+ }
227
+ if (plan.similar > 0) {
228
+ diagnose({
229
+ level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_SUSPECTED', alert: true, manual: true,
230
+ repair: 'merge-entity-fragments',
231
+ message: `另有 ${plan.similar} 组实体只是名字相似,未自动合并`,
232
+ hint: '相似不等于同一人:请到「设置 · 诊断」核对候选,确认后手动触发合并。',
233
+ detail: { similar: plan.similar, libraries: plan.plans.filter((entry) => entry.ambiguous.length).length },
234
+ source: 'entity-repair',
235
+ })
236
+ }
237
+ for (const failure of failures) warn(`entity repair skipped ${failure.libraryId || ''} ${failure.group || ''}: ${failure.error}`)
238
+ return { merged, created, protectedRows, similar: plan.similar, failures, deferred }
239
+ }
240
+
241
+ function startEntityRepairPass(ctx) {
242
+ try {
243
+ return scheduleStartup(ctx, 5000, 'entity repair pass', () => {
244
+ void runEntityRepairPass({
245
+ note: (message) => { try { ctx.logger?.info?.(`dsh-memu-memory: ${message}`) } catch {} },
246
+ warn: (message) => { try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {} },
247
+ diagnose: recordDiagnostic,
248
+ }).catch((error) => { recordErrorDiagnostic(error, { source: 'entity-repair' }) })
249
+ })
250
+ } catch (error) {
251
+ try { ctx.logger?.warn?.(`dsh-memu-memory: entity repair pass skipped: ${error?.message || error}`) } catch {}
252
+ return null
253
+ }
254
+ }
255
+
142
256
  // T0 构件 1(设计文档 §3.2):增量回合日志的订阅接线。纯旁路记录器——任何失败只
143
257
  // warn,绝不改变或阻断现有整理行为;正确性永远由宿主转录 + 缺口重建兜底。
144
258
  //
@@ -182,7 +296,9 @@ export function registerTurnLogRecorder(ctx) {
182
296
  buffers.delete(sessionId)
183
297
  if (!buffer || !turnLogAdmitted(session)) return
184
298
  buffer.push(event)
185
- for (const record of buildTurnRecords(buffer)) recordTurn(sessionId, record)
299
+ const binding = getSessionBinding(sessionId)
300
+ const limits = turnLogLimits(binding?.domainOverride || binding?.domain || 'general')
301
+ for (const record of buildTurnRecords(buffer, limits)) recordTurn(sessionId, record)
186
302
  return
187
303
  }
188
304
  const buffer = buffers.get(sessionId)
@@ -337,6 +453,7 @@ export function apply(ctx, config) {
337
453
  startEngineBootstrap(ctx),
338
454
  startLocalVectorBootstrap(ctx),
339
455
  startOrphanEntitySweep(ctx),
456
+ startEntityRepairPass(ctx),
340
457
  startEnvironmentHealthCheck(ctx),
341
458
  ].filter(Boolean)
342
459
  if (typeof ctx.effect === 'function') {
package/lib/inject.js CHANGED
@@ -1634,6 +1634,132 @@ function guideAdmission(binding, messages, guideKey) {
1634
1634
  return 'replace'
1635
1635
  }
1636
1636
 
1637
+ // 通道会话(dsh-channel 等)用确定性 id(`qq-dm-<uid>`)。宿主重建同名新会话后,
1638
+ // 转录里没有旧的一次性投放,binding 上却还留着 guideRulesKey / anchorPushed,
1639
+ // 稳态判据于是把 guide 与锚点永久跳过(实测 qq-dm 会话首 24 回合没有规则消息)。
1640
+ // 会话身份优先用宿主暴露的 createdAt;拿不到时退回「回合号回到 1」,
1641
+ // 并用首条消息 id 做这一代的戳,避免同一代被重复重置。
1642
+ function sessionStampOf(payload) {
1643
+ const session = payload?.agent?.session
1644
+ const raw = session?.createdAt ?? session?.header?.createdAt
1645
+ if (raw === undefined || raw === null || raw === '') return null
1646
+ const time = typeof raw === 'number' ? raw : Date.parse(raw)
1647
+ return 'created:' + (Number.isFinite(time) ? String(time) : String(raw))
1648
+ }
1649
+
1650
+ function firstTurnStamp(decision) {
1651
+ const messages = Array.isArray(decision?.messages) ? decision.messages : []
1652
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
1653
+ const message = messages[i]
1654
+ if (message?.role === 'user' && message?.id) return `turn1:${message.id}`
1655
+ }
1656
+ return null
1657
+ }
1658
+
1659
+ function resetSessionOneShots(sessionId, stamp, reason) {
1660
+ const binding = getSessionBinding(sessionId)
1661
+ if (!binding) return
1662
+ setSessionBinding(sessionId, {
1663
+ sessionStamp: stamp,
1664
+ reinjectPending: true,
1665
+ guideRulesKey: undefined,
1666
+ guideMessageAt: undefined,
1667
+ guideLost: false,
1668
+ anchorPushed: undefined,
1669
+ lastInjectedUserMessageId: undefined,
1670
+ })
1671
+ clearInjectionSeen(sessionId)
1672
+ record({
1673
+ kind: 'system',
1674
+ scope: 'private',
1675
+ sessionId,
1676
+ libraryId: binding.libraryId || null,
1677
+ ok: true,
1678
+ message: '同名新会话:一次性投放已重置(规则/锚点/首条去重)',
1679
+ detail: { reason, previousStamp: binding.sessionStamp || null },
1680
+ })
1681
+ }
1682
+
1683
+ function syncSessionIncarnation(payload, decision) {
1684
+ try {
1685
+ const sessionId = payload?.agent?.session?.header?.id
1686
+ if (!sessionId) return
1687
+ const binding = getSessionBinding(sessionId)
1688
+ if (!binding) return
1689
+ const created = sessionStampOf(payload)
1690
+ if (created) {
1691
+ if (!binding.sessionStamp) {
1692
+ setSessionBinding(sessionId, { sessionStamp: created })
1693
+ return
1694
+ }
1695
+ if (binding.sessionStamp === created) return
1696
+ if (binding.sessionStamp.startsWith('created:')) {
1697
+ resetSessionOneShots(sessionId, created, 'session-stamp-changed')
1698
+ return
1699
+ }
1700
+ // 兜底戳不拿来和 createdAt 比:宿主开始暴露 createdAt 时只升级记录。
1701
+ if (Number(payload?.turn) === 1) {
1702
+ const current = firstTurnStamp(decision)
1703
+ if (current && current !== binding.sessionStamp) {
1704
+ resetSessionOneShots(sessionId, created, 'session-stamp-changed')
1705
+ return
1706
+ }
1707
+ }
1708
+ setSessionBinding(sessionId, { sessionStamp: created })
1709
+ return
1710
+ }
1711
+ if (Number(payload?.turn) !== 1) return
1712
+ const fallback = firstTurnStamp(decision)
1713
+ if (!fallback) return
1714
+ if (binding.sessionStamp?.startsWith('turn1:')) {
1715
+ if (binding.sessionStamp !== fallback) resetSessionOneShots(sessionId, fallback, 'turn-restarted')
1716
+ return
1717
+ }
1718
+ if (binding.sessionStamp) return
1719
+ // 旧版 binding 没有会话戳:回合号回到 1 且已有过往注入,说明转录换代了。
1720
+ if (Number(binding.lastInjectedTurn || 0) > 1) resetSessionOneShots(sessionId, fallback, 'turn-restarted')
1721
+ else setSessionBinding(sessionId, { sessionStamp: fallback })
1722
+ } catch {}
1723
+ }
1724
+
1725
+ // 切域改变参与召回的记忆集合,也让 guide 变体不同。guide 原本靠 rulesKey 替换,
1726
+ // 但锚点与按域过滤的一次性提醒(纪念日/未了之事/时段氛围)都是「一会话一次」,
1727
+ // 记账还在旧领域上——所以切域要显式清一遍,让新一代重新投。
1728
+ function syncDomainDelivery(sessionId) {
1729
+ try {
1730
+ if (!sessionId) return
1731
+ const binding = getSessionBinding(sessionId)
1732
+ if (!binding) return
1733
+ const domain = domainOf(binding)
1734
+ if (!binding.injectedDomain) {
1735
+ setSessionBinding(sessionId, { injectedDomain: domain })
1736
+ return
1737
+ }
1738
+ if (binding.injectedDomain === domain) return
1739
+ setSessionBinding(sessionId, {
1740
+ injectedDomain: domain,
1741
+ guideRulesKey: undefined,
1742
+ guideMessageAt: undefined,
1743
+ guideLost: false,
1744
+ anchorPushed: undefined,
1745
+ anniversariesShown: {},
1746
+ openLoopRemindedAt: {},
1747
+ textureKey: undefined,
1748
+ })
1749
+ markReinjectPending(sessionId)
1750
+ clearInjectionSeen(sessionId)
1751
+ record({
1752
+ kind: 'system',
1753
+ scope: 'private',
1754
+ sessionId,
1755
+ libraryId: binding.libraryId || null,
1756
+ ok: true,
1757
+ message: '记忆领域切换:一次性投放已重置(规则/锚点/纪念日/未了之事)',
1758
+ detail: { from: binding.injectedDomain, to: domain },
1759
+ })
1760
+ } catch {}
1761
+ }
1762
+
1637
1763
  function ensureUnifiedGuide(ctx, payload, decision) {
1638
1764
  try {
1639
1765
  const header = payload?.agent?.session?.header
@@ -2350,6 +2476,10 @@ export function registerInjection(ctx) {
2350
2476
  const offPre = ctx.on('agent/pre-step', async (payload, next) => {
2351
2477
  const closure = turnClosure(payload?.agent?.session?.header?.id, payload?.turn)
2352
2478
  const decision = await next()
2479
+ // 同名新会话(通道重建 transcript)必须先清掉旧代的一次性记账,再让下面的
2480
+ // 注入与 guide 按新一代重新投放;切域同样要重投(锚点与按域过滤的提醒)。
2481
+ syncSessionIncarnation(payload, decision)
2482
+ syncDomainDelivery(payload?.agent?.session?.header?.id)
2353
2483
  // 宿主会在同一轮里对同一条真实用户消息给出两次 enter 决策(0.2.2-rc.1 实测:
2354
2484
  // turn 号成对跳 221→222、223→224)。第二次会重新走一遍召回,候选又全被去重,
2355
2485
  // 结果是 0 条注入的纯空跑,还会把 memoryClock 多推一格。按真实用户消息 id 幂等:
@@ -2365,8 +2495,9 @@ export function registerInjection(ctx) {
2365
2495
  stepSessionId && stepLastUser?.id && stepBinding?.reinjectPending !== true
2366
2496
  && stepBinding?.lastInjectedUserMessageId === stepLastUser.id && !hasPendingInbound(stepSessionId),
2367
2497
  )
2498
+ let injected = decision
2368
2499
  try {
2369
- const injected = duplicateStep
2500
+ injected = duplicateStep
2370
2501
  ? decision
2371
2502
  : await injectForStep({
2372
2503
  ...payload,
@@ -2374,18 +2505,21 @@ export function registerInjection(ctx) {
2374
2505
  ctx,
2375
2506
  log: (message) => { try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {} },
2376
2507
  })
2377
- if (turnClosure(stepSessionId, payload?.turn) !== closure) {
2378
- for (const [id, proposal] of injectionAdmissions.get(stepSessionId) || []) {
2379
- if (proposal.turn === Number(payload?.turn) && proposal.status === 'proposed') injectionAdmissions.get(stepSessionId).delete(id)
2380
- }
2381
- return decision
2382
- }
2383
- return ensureUnifiedGuide(ctx, payload, injected)
2384
2508
  } catch (error) {
2385
2509
  try { setRecallError(payload?.agent?.session?.header?.id, `injection failed: ${error?.message || error}`) } catch {}
2386
2510
  try { ctx.logger?.warn?.(`dsh-memu-memory: pre-step injection failed (fail-open): ${error?.stack || error}`) } catch {}
2511
+ // 召回/入站故障不该把规则消息一起带走:guide 是独立 plugin 消息,照常尝试。
2512
+ // 但回合已被关闭/替换时不能给旧回合提新提案,闭包判据与成功路径一致。
2513
+ if (turnClosure(stepSessionId, payload?.turn) !== closure) return decision
2514
+ return ensureUnifiedGuide(ctx, payload, decision)
2515
+ }
2516
+ if (turnClosure(stepSessionId, payload?.turn) !== closure) {
2517
+ for (const [id, proposal] of injectionAdmissions.get(stepSessionId) || []) {
2518
+ if (proposal.turn === Number(payload?.turn) && proposal.status === 'proposed') injectionAdmissions.get(stepSessionId).delete(id)
2519
+ }
2387
2520
  return decision
2388
2521
  }
2522
+ return ensureUnifiedGuide(ctx, payload, injected)
2389
2523
  }, { prepend: true })
2390
2524
  disposers.push(offPre)
2391
2525
 
package/lib/memory.js CHANGED
@@ -3819,6 +3819,78 @@ export function expireShortTerm({ now = Date.now() } = {}) {
3819
3819
  return { expired, libraries, skipped }
3820
3820
  }
3821
3821
 
3822
+ // 过期草稿只退出检索,正文留着供归档视图升级;但这个"第二机会"不能没有期限,
3823
+ // 否则索引无限膨胀、UI 永远清不完。超过保留期改标 archived(仍不删除),
3824
+ // 归档与 expired 一样可被人工永久删除。
3825
+ export const EXPIRED_DRAFT_RETENTION_DAYS = 30
3826
+
3827
+ export function archiveExpiredDrafts({ now = Date.now(), retentionDays = EXPIRED_DRAFT_RETENTION_DAYS } = {}) {
3828
+ const days = Number(retentionDays)
3829
+ if (!(days > 0)) return { archived: [], libraries: [], skipped: 0 }
3830
+ const cutoff = now - days * 86_400_000
3831
+ const archived = []
3832
+ const libraries = []
3833
+ let skipped = 0
3834
+ for (const lib of listLibrariesAll()) {
3835
+ if (lib.archived === true) continue
3836
+ let index = null
3837
+ try { index = loadPrivateIndex(lib.id) } catch { skipped += 1; continue }
3838
+ let changed = false
3839
+ for (const [id, entry] of Object.entries(index.entries || {})) {
3840
+ if (!entry || entry.status !== 'expired') continue
3841
+ // 没有过期时刻就不猜:宁可留在归档视图里等人处理,也不按写入时间装作知道。
3842
+ const at = Date.parse(entry.expiredAt || entry.expiresAt || '') || 0
3843
+ if (!at || at > cutoff) continue
3844
+ entry.status = 'archived'
3845
+ entry.archivedAt = stamp()
3846
+ entry.updatedAt = stamp()
3847
+ changed = true
3848
+ archived.push({ libraryId: lib.id, id })
3849
+ }
3850
+ if (changed) {
3851
+ try {
3852
+ savePrivateIndex(lib.id, index)
3853
+ libraries.push(lib.id)
3854
+ } catch {
3855
+ skipped += 1
3856
+ }
3857
+ }
3858
+ }
3859
+ return { archived, libraries, skipped }
3860
+ }
3861
+
3862
+ /**
3863
+ * 逾期未结案的承诺:open 且过了 due_at 至少 `minOverdueDays` 天。
3864
+ *
3865
+ * 只读、不裁决。整理任务书用它把欠账列给 worker;周期扫描用它提醒"该结案了"。
3866
+ * 状态只能由证据推动(done / cancelled / expired),这里永远不改 status——
3867
+ * 承诺有没有兑现是事实问题,不是清理策略能替人回答的。
3868
+ */
3869
+ export function overdueOpenCommitments({ libraryId, now = Date.now(), minOverdueDays = 7, limit = 20 } = {}) {
3870
+ if (!libraryId) return []
3871
+ let index = null
3872
+ try { index = loadPrivateIndex(libraryId) } catch { return [] }
3873
+ const minDays = Math.max(0, Number(minOverdueDays) || 0)
3874
+ const rows = []
3875
+ for (const [id, entry] of Object.entries(index.entries || {})) {
3876
+ if (!entry || entry.marginalized) continue
3877
+ if (!entry.commitment || typeof entry.commitment !== 'object') continue
3878
+ const commitment = commitmentOf(entry)
3879
+ if (!commitment || commitment.status !== 'open') continue
3880
+ if (!isMemoryEligible(entry, { automatic: true, now })) continue
3881
+ const due = commitmentDueState(commitment, { now })
3882
+ if (!due.overdue || due.daysUntil === null) continue
3883
+ const daysOverdue = -due.daysUntil
3884
+ if (daysOverdue < minDays) continue
3885
+ rows.push({ id, entry, commitment, dueAt: due.dueAt, daysOverdue })
3886
+ }
3887
+ rows.sort((a, b) => b.daysOverdue - a.daysOverdue
3888
+ || String(a.dueAt || '').localeCompare(String(b.dueAt || ''))
3889
+ || String(a.entry.updatedAt || a.entry.createdAt || '').localeCompare(String(b.entry.updatedAt || b.entry.createdAt || ''))
3890
+ || a.id.localeCompare(b.id))
3891
+ return rows.slice(0, Math.max(0, Number(limit) || 0))
3892
+ }
3893
+
3822
3894
  export function privateArchive({ exec, libraryId, id }) {
3823
3895
  const scope = resolveLibrary({ exec, libraryId })
3824
3896
  if (scope.binding) assertScopeEnabled(scope.binding)
@@ -286,7 +286,19 @@ export function suggestPrivateLinks({
286
286
  }
287
287
  }
288
288
  const analyses = new Map()
289
+ // A sliding window must not name an entity while the longer window it lives in
290
+ // groups at least as many memories: `南宫晚` and `宫晚晴` point at exactly the same
291
+ // pair as `南宫晚晴`, and only the 4-char form is a name. `星港` survives because the
292
+ // longer `星港夜班` appears in a single memory.
293
+ const hubGroups = [...groups.values()]
294
+ const subsumed = new Set(hubGroups
295
+ .filter(group => hubGroups.some(other => other !== group
296
+ && other.token.length > group.token.length
297
+ && other.entries.length >= group.entries.length
298
+ && other.token.includes(group.token)))
299
+ .map(group => group.token))
289
300
  for (const [key, group] of groups) {
301
+ if (subsumed.has(group.token)) continue
290
302
  if (group.entries.length < 2) continue
291
303
  if (!group.entries.some(item => wantedSet.has(item.id))) continue
292
304
  const kind = inferEntityKind(group.entries.map(item => item.entry), group.token)
package/lib/private.js CHANGED
@@ -3,10 +3,10 @@ import crypto from 'node:crypto'
3
3
  import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
  import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
6
- import { domainOf, privateRemember, isMemoryEligible, visibleToSession } from './memory.js'
6
+ import { domainOf, privateRemember, isMemoryEligible, visibleToSession, overdueOpenCommitments } from './memory.js'
7
7
  import { loadPromptForDomain, CONSOLIDATION_CONTRACTS } from './prompts.js'
8
8
  import { summarizeRemote } from './remote-summary.js'
9
- import { condenseEvents, readSessionSnapshot } from './curator.js'
9
+ import { condenseEvents, condenseLimitsFor, readSessionSnapshot } from './curator.js'
10
10
  import { record } from './activity-log.js'
11
11
  import { ACTIVE_MEMORY_POLICY, assessWake, collectEvidence } from './active-memory.js'
12
12
  import { entryFingerprint } from './consolidation-receipt.js'
@@ -205,9 +205,19 @@ export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
205
205
  export const CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS = 6 * 60 * 60 * 1000
206
206
  const SEED_TOOL_RESULT_CHARS = 1_100
207
207
  const SEED_TOOL_CALL_CHARS = 500
208
+ // 编码域的修改重点就在工具结果与调用参数(diff、错误签名、编译输出)里;
209
+ // 1.1k/0.5k 只够留下开头。放宽后整窗仍有 ≤500 事件与 12k 文本/条的上限兜着。
210
+ const SEED_TOOL_RESULT_CHARS_CODING = 2_200
211
+ const SEED_TOOL_CALL_CHARS_CODING = 1_000
208
212
  const SEED_TEXT_CHARS = 12_000
209
213
  const SEED_CATALOG_ENTRIES = 18
210
214
 
215
+ export function seedLimitsFor(domain) {
216
+ return String(domain) === 'coding'
217
+ ? { toolResultChars: SEED_TOOL_RESULT_CHARS_CODING, toolCallChars: SEED_TOOL_CALL_CHARS_CODING }
218
+ : { toolResultChars: SEED_TOOL_RESULT_CHARS, toolCallChars: SEED_TOOL_CALL_CHARS }
219
+ }
220
+
211
221
  // Types that carry conversation, plus the structural events a seeded Session
212
222
  // replays. Everything else is host bookkeeping: request headers, permissions,
213
223
  // runtime snapshots and the plugin's own recall messages. Feeding those to the
@@ -341,7 +351,9 @@ function seedSurfaceIssues(events) {
341
351
  * against the surviving events, drop the ones that cannot be replayed, and only
342
352
  * renumber once the survivor set is stable.
343
353
  */
344
- export function compactSeedEvents(events, prelude = null) {
354
+ export function compactSeedEvents(events, prelude = null, options = {}) {
355
+ const toolResultChars = Number(options.toolResultChars) > 0 ? Number(options.toolResultChars) : SEED_TOOL_RESULT_CHARS
356
+ const toolCallChars = Number(options.toolCallChars) > 0 ? Number(options.toolCallChars) : SEED_TOOL_CALL_CHARS
345
357
  const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
346
358
  .filter((event) => event && typeof event === 'object')
347
359
  .map((event, index) => {
@@ -364,7 +376,7 @@ export function compactSeedEvents(events, prelude = null) {
364
376
  // The replay state duplicates the response body; it is not conversation.
365
377
  delete source.replayState
366
378
  message.source = source
367
- message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: SEED_TOOL_CALL_CHARS })
379
+ message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: toolCallChars })
368
380
  if (message.content.length === 0) message.content = [{ type: 'text', text: '(本轮没有可读的正文)' }]
369
381
  clone.data.message = message
370
382
  // data.stream is the raw chunk log, not the message the model saw. It must
@@ -378,11 +390,11 @@ export function compactSeedEvents(events, prelude = null) {
378
390
  clone.data.stream = []
379
391
  } else if (event.type === 'tool/result') {
380
392
  const message = { ...(event.data?.message || {}) }
381
- message.content = cloneSeedBlocks(message.content, { text: SEED_TOOL_RESULT_CHARS, tool: SEED_TOOL_CALL_CHARS }, seenToolText)
393
+ message.content = cloneSeedBlocks(message.content, { text: toolResultChars, tool: toolCallChars }, seenToolText)
382
394
  if (message.content.length === 0) message.content = [{ type: 'text', text: '[空工具输出]' }]
383
395
  clone.data.message = message
384
396
  } else if (event.type === 'tool/call') {
385
- clone.data.arguments = capSeedText(event.data?.arguments, SEED_TOOL_CALL_CHARS)
397
+ clone.data.arguments = capSeedText(event.data?.arguments, toolCallChars)
386
398
  } else if (event.type === 'user/message') {
387
399
  clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
388
400
  const timeLabel = eventTimeLabel(event)
@@ -485,8 +497,18 @@ export function salienceScore(text, domain = 'general') {
485
497
  return strong * 2 + weak
486
498
  }
487
499
 
488
- /** Keep salient complete turns and one neighbour on each side. */
500
+ /**
501
+ * Keep salient complete turns and one neighbour on each side. Coding keeps more:
502
+ * weak signals, every turn that touched a tool, and a doubled turn cap — the
503
+ * change itself lives in the tool calls, not in the prose around them.
504
+ */
489
505
  export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general' } = {}) {
506
+ const coding = String(domain) === 'coding'
507
+ // 编码域的改动发生在工具调用里,正文常常只有一句「改这个函数」;salience 词表
508
+ // 命中不了就整回合丢掉,种子只剩关键词最多的闲聊。coding 因此放宽:弱词也算数,
509
+ // 带工具调用的回合一律保留,回合上限翻倍。
510
+ const threshold = coding ? 1 : 2
511
+ const cap = coding ? Math.max(Number(maxTurns) || 0, 120) : maxTurns
490
512
  const groups = []
491
513
  let current = null
492
514
  for (const event of Array.isArray(events) ? events : []) {
@@ -499,7 +521,9 @@ export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general'
499
521
  }
500
522
  const kept = new Set()
501
523
  groups.forEach((group, index) => {
502
- if (salienceScore(turnText(group), domain) >= 2) kept.add(index)
524
+ const scored = salienceScore(turnText(group), domain) >= threshold
525
+ const worked = coding && group.some((event) => event?.type === 'tool/call')
526
+ if (scored || worked) kept.add(index)
503
527
  })
504
528
  if (kept.size === 0) return Array.isArray(events) ? [...events] : []
505
529
  const expanded = new Set(kept)
@@ -507,7 +531,7 @@ export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general'
507
531
  if (index > 0) expanded.add(index - 1)
508
532
  if (index + 1 < groups.length) expanded.add(index + 1)
509
533
  }
510
- const selected = [...expanded].sort((a, b) => a - b).slice(0, maxTurns)
534
+ const selected = [...expanded].sort((a, b) => a - b).slice(0, cap)
511
535
  const covered = selected.reduce((sum, index) => sum + groups[index].length, 0)
512
536
  if (covered >= events.length * 0.8) return [...events]
513
537
  return selected.flatMap((index) => groups[index])
@@ -636,11 +660,22 @@ export function memoryCatalogEvent(binding, now = Date.now()) {
636
660
  .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || '')))
637
661
  .slice(0, SEED_CATALOG_ENTRIES)
638
662
  .map(([id, entry]) => `- [${id}] ${capSeedText(entry.title || '(untitled)', 120)} · ${entry.layer || 'long_term'} · ${entry.status || 'active'}`)
639
- if (rows.length === 0) return null
663
+ // 欠账单列:目录按更新时间截断,逾期的承诺很可能不在前 N 条里,而整理必须看见它。
664
+ const overdueRows = overdueOpenCommitments({ libraryId: binding.libraryId, now, minOverdueDays: 0, limit: 8 })
665
+ .filter(({ entry }) => visibleToSession(entry, binding.sessionId))
666
+ .map(({ id, entry, commitment, dueAt, daysOverdue }) => {
667
+ const who = commitment.counterparty ? `对 ${capSeedText(commitment.counterparty, 40)}:` : ''
668
+ return `- [${id}] ${capSeedText(entry.title || '(untitled)', 80)} · due=${dueAt} · 已逾期 ${daysOverdue} 天 · ${who}${capSeedText(commitment.action, 120)}`
669
+ })
670
+ if (rows.length === 0 && overdueRows.length === 0) return null
640
671
  const text = [
641
672
  '[memory-catalog · 已有记忆目录(只读上下文,不是用户发言,也不属于本轮转录)]',
642
673
  '下面这些是本次整理之前已经写入本库的条目。不要当作用户说过的话,也不要重复创建;同一事实用 memu_private_update id=<id> 合并,真正新增的内容才用 memu_private_remember。',
643
674
  ...rows,
675
+ ...(overdueRows.length > 0
676
+ ? ['欠账(status=open 且已过 due_at):整理时按本轮转录证据结案——兑现写 done、明确取消写 cancelled、确实作废写 expired;没有证据就保留 open,并在正文写明仍欠着谁。',
677
+ ...overdueRows]
678
+ : []),
644
679
  ].join('\n')
645
680
  return {
646
681
  type: 'user/message',
@@ -892,7 +927,7 @@ export async function requestRemoteConsolidation(ctx, sessionId, { signal, timeo
892
927
  const value = assessConsolidationValue(fresh)
893
928
  if (!value.worth) return { ok: true, sessionId, backend: 'api', count: 0, skipped: value.reason, assessment: value }
894
929
  }
895
- const transcript = condenseEvents(fresh, 60_000)
930
+ const transcript = condenseEvents(fresh, 60_000, condenseLimitsFor(domainOf(binding)))
896
931
  const library = binding.libraryId ? getLibrary(binding.libraryId) : null
897
932
  const memories = await summarizeRemote({
898
933
  transcript,
@@ -1507,7 +1542,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1507
1542
  const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1508
1543
  memoryCatalogEvent({ ...binding, sessionId }),
1509
1544
  memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
1510
- ])
1545
+ ], seedLimitsFor(domain))
1511
1546
  if (!workerMode && seedEvents.length === 0) {
1512
1547
  return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
1513
1548
  }
@@ -1692,6 +1727,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1692
1727
  incrementRecords: workerIncrement.records,
1693
1728
  incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1694
1729
  digest: workerIncrement.digest, catalog: memoryCatalogEvent(workerBinding),
1730
+ domain,
1695
1731
  sceneTime: current.sceneTime || binding.sceneTime || null,
1696
1732
  pendingNote: Boolean(current.consolidationPending), pendingHash: current.consolidationPending?.snapshotHash || null,
1697
1733
  carry: mustCover, lastSleepSeq: binding.lastSleepSeq ?? null,
@@ -1791,7 +1827,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1791
1827
  if (!workerMode) {
1792
1828
  accounting = createConsolidationMeasurement('fork', { sessionId: childId })
1793
1829
  const brief = buildWorkerBrief({
1794
- snapshot, probe, jobId, mustCover, autoReceipt: true,
1830
+ snapshot, probe, jobId, mustCover, autoReceipt: true, domain,
1795
1831
  contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1796
1832
  reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
1797
1833
  })
@@ -13,8 +13,10 @@
13
13
  2. 优先:需求/验收、接口契约、数据流/调用链、不变量、算法与边界、并发/幂等、根因与修复理由、被否决方案的失败条件、环境约束与测试缺口。区分用户要求、提议、已实现和已验证。
14
14
  3. 划掉:常规日志、源码整页复制、凭据与 token、逐步调试流水账。关键错误签名、最小复现或不能从源码找回的片段可保留,必须足以保持代码语义。
15
15
  4. 只根据实际提供或成功检索到的旧条目去重,不声称查过不存在的索引。兼容内容可合并;矛盾结论保留证据与时间供复核,不以整理为名覆盖旧正文或自行宣布取代。
16
+ 5. 先清欠账:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据写 `done`/`cancelled`/`expired`;没有证据就保留 open 并写明仍欠着谁。
17
+ 6. 再查过时:`valid_to` 已过或已被明确证据取代的旧条目,把 `status` 改成 `archived` 或补正有效窗口,旧正文保留。
16
18
 
17
- 最多新增 3 条。宁可少写一条,也不要写一条未来会被自己当成噪音的。
19
+ 每窗最多新增 8 条,按价值排序:根因与修复理由 = 接口/不变量变化 = 环境与版本约束 = 被否决方案及其失败条件 > 验证结论与测试范围 > 需求/验收变化 > 工作偏好 > 其余明确事实。前两类必须写,不得因为已经写了几条就省略;条数不能靠少写省掉,「少写」只指单条精准。
18
20
 
19
21
  每条的形状:
20
22
  - title:8–40 字,结论不是主题——读标题就该知道答案,并且要写具体事实(模块、符号、命令、错误签名、结论的关键词)。
@@ -12,6 +12,8 @@
12
12
  - 优先写具体的东西:一句原话、一个决定和它的理由、一次踩过的坑。
13
13
  - 可以写有后续影响的关系、感受或限制,但要有具体事件与来源;一次礼貌或情绪不推导稳定人格,不按轮数增加亲密度。只有明确的叙事内容才用角色口吻。
14
14
  - 只与实际提供或成功检索到的旧记忆去重:兼容可合并,矛盾保留来源、时间与条件供复核,不抹旧正文或自行宣布取代。**最多新增 8 条,按价值排序**:约定/承诺 > 日期/改口/冲突 > 身份/称呼/边界/第三方人物与变化 > 偏好/计划 > 其他明确事实;普通日常流水、打招呼、重复对话不写,没有值得留的就不写。
15
+ - 先清欠账:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据更新 `commitment.status`(兑现→`done`,明确取消→`cancelled`,确实作废→`expired`);没有证据就保留 open,并在正文写明仍欠着谁,不猜。
16
+ - 再查过时:`valid_to` 已过、或已被明确证据取代的旧条目,把它的 `status` 改成 `archived`,或补正有效窗口;旧正文不删除、不改写成新事实。
15
17
 
16
18
  字段:
17
19
  - title:8–40 字,写具体事实(人名、物名、事件、结论的关键词)。锚点与召回只显示标题、不显示正文,所以标题就是目录项;
@@ -14,6 +14,8 @@
14
14
  - 两边都出现时分成两条,不要混成一条。
15
15
  - 技术侧用中性工程笔记,人物侧用角色自己的话,不打关系分、不写抒情流水账;OOC 写作偏好和剧情经历分开。
16
16
  - 仅按实际提供或成功检索到的旧条目去重;兼容内容可合并,矛盾留证据与时间供复核,不抹旧事实或自行宣布取代。同一件事前后有两种说法时,两种说法必须各自成条(写清轮次或时间和说话人),不得合并;用户先前说过的话不能记成助手说的,也不能因后面改口删掉先前那条。
17
+ - 先清欠账:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据更新 `commitment.status`(done/cancelled/expired);没有证据就保留 open 并写明仍欠着谁。
18
+ - 再查过时:`valid_to` 已过或已被明确证据取代的旧条目,把 `status` 改成 `archived` 或补正有效窗口,旧正文保留。
17
19
  - tags 可标 coding/rp/ooc 辅助检索,不代替说话人、角色、世界线、分支与 knownBy 边界。工具 waiting/sleep 不算人物经历,角色喜好不推导现实用户属性。
18
20
  - 最多新增 10 条。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)即使琐碎也要独立写入;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。
19
21
 
@@ -15,6 +15,8 @@
15
15
  - 写库前先落 `speaker_id`、`source_kind`、`absolute_date`;相对日期不能只留原文。
16
16
  - 同一件事有两种说法:各写一条,`conflicts_with` 互指;不要合并成一条,也不要自行裁决。
17
17
  - 承诺/约定写 `commitment`(对谁/做什么/`due_at`/`status`);梦、假设、转述标 `source_kind`。
18
+ - 先清欠账:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据结案(兑现→`done`,明确取消→`cancelled`,确实作废→`expired`);没有证据就保留 open,并在正文写明仍欠着谁,不猜。
19
+ - 再查过时:`valid_to` 已过或已被明确证据取代的旧条目,把 `status` 改成 `archived` 或补正有效窗口;旧正文不删除、不改写成新事实。
18
20
  - 助手说过的承诺和计划同样要写;不要只收用户消息。
19
21
  - 每窗最多新增 8 条。按价值排序:约定/承诺 = 新人物首次出现/换人接手/称呼变化 > 日期/改口/冲突 > 身份/边界/第三方人物 > 偏好/计划 > 其他明确事实。前两类必须写,不得因为已经写了几条就省略。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)也要各自成条;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。条数不能靠少写省掉;「少写」只指单条正文精准。
20
22
  - 人物首次出现、换人接手或称呼变化必须单独成一条,写清先后(谁先、谁后来接手)与发生轮次;这类事实不并入生活流水,也不因为主体是第三方就不写。