dsh-memu-memory 1.4.4 → 1.4.5

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 (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -1,17 +1,20 @@
1
1
  // 移植适配器的稳定入口(`package.json` exports: "./port")。
2
2
  //
3
3
  // 为什么单独一个文件:MCP server / 脚本 / 其它宿主只需要「工具规格 + 记忆读写 +
4
- // 库与索引」,不该为了这三样去读 tools.js 里三十段内联闭包,也不该依赖
4
+ // 库路由」,不该为了这三样去读 tools.js 里三十段内联闭包,也不该依赖
5
5
  // lib/index.js——那是宿主插件入口,注册的是 ctx 服务、注入钩子和 RPC。
6
6
  //
7
7
  // 无会话调用方(MCP server、CLI):
8
8
  // const specs = collectToolSpecs() // 30 个 { name, description, parameters, execute }
9
9
  // await privateRecall({ libraryId, query, topK }) // 显式库,不需要会话
10
10
  // await privateRemember({ libraryId, content, title })
11
- // listLibraries() / loadPrivateIndex(libraryId)
11
+ // listLibraries() / privateList({ libraryId })
12
+ // Raw index loaders and destructive lifecycle functions are intentionally not
13
+ // exported: indexes bypass identity filtering; deletion requires the RPC safety
14
+ // confirmation and a fresh backup.
12
15
  //
13
- // 有会话调用方照旧传 exec({ agent: { session: { header: { id, cwd } } } }),行为与
14
- // 插件内部完全一致。
16
+ // 有会话调用方照旧传 exec({ agent: { session: { header: { id, cwd } } } }),沿用
17
+ // 宿主会话身份与读取资格;返回值仍使用 port 的受限投影。
15
18
  //
16
19
  // 两条必须知道的边界(都是刻意的):
17
20
  // 1. 无会话的 privateRecall 只读显式指定的那个库:跨库聚合、情绪、场景时间全部
@@ -19,9 +22,8 @@
19
22
  // 2. 没有会话就没有 memoryContext,所以带 channelId/characterId 等边界的记忆对
20
23
  // 无会话调用方不可见(context.js 的 contextVisible)。这是安全默认,不是 bug。
21
24
  //
22
- // 本文件只做 re-export,不含逻辑;不要在这里加会改变内部状态的东西。
23
- // 例外只有 toInputSchema:它是纯函数,存在的唯一目的是把宿主 schema 方言翻译成
24
- // MCP / JSON Schema,避免每个适配器各写一遍、各错一遍。
25
+ // 本文件的包装层固定受限读取与返回投影;内部 RPC 管理列表保持原有语义。
26
+ // toInputSchema 是纯函数,把宿主 schema 方言翻译成 MCP / JSON Schema。
25
27
 
26
28
  export { collectToolSpecs } from './tools.js'
27
29
 
@@ -69,14 +71,97 @@ function convertNode(node) {
69
71
  return out
70
72
  }
71
73
 
74
+ import * as memory from './memory.js'
75
+ import { loadPrivateIndex } from './state.js'
76
+
72
77
  export {
73
- privateRecall, privateList, privateRemember, privateUpdate, privateArchive, privateDelete,
74
- previewDelete, restoreDeleted, globalList, globalRecall, globalSetStatus, globalDelete,
75
- importMemories, domainOf, decayStrength, appliesToDomain, visibleToSession, isMemoryEligible,
78
+ importMemories, domainOf, decayStrength, appliesToDomain,
79
+ visibleToSession, isMemoryEligible,
76
80
  } from './memory.js'
77
81
 
82
+ // Port reads are always restricted, even when the caller supplies admin-like
83
+ // options. Internal RPC management calls keep their existing list semantics.
84
+ export async function privateList(args = {}) {
85
+ return portReadResult(await memory.privateList({ ...args, restricted: true, preferIndex: true }))
86
+ }
87
+
88
+ export async function globalList(args = {}) {
89
+ return portReadResult(await memory.globalList({ ...args, restricted: true, preferIndex: true }))
90
+ }
91
+
92
+ export async function privateRecall(args = {}) {
93
+ return portReadResult(await memory.privateRecall(args))
94
+ }
95
+
96
+ export async function globalRecall(args = {}) {
97
+ return portReadResult(await memory.globalRecall(args))
98
+ }
99
+
100
+ function portReadResult(result) {
101
+ // Port exposes visible memory data, not engine dumps, candidate traces or raw
102
+ // graph records (which can contain ids of inaccessible conflict versions).
103
+ const files = (result.files || []).map(file => {
104
+ const related = (file.related || []).filter(item => item.available !== false && !item.missing)
105
+ const disclosed = new Set(related.map(item => item.id))
106
+ const clean = { ...file, related }
107
+ for (const key of ['groupKey', 'groupRevision', 'conflictPair', 'conflictComplete', 'ref']) delete clean[key]
108
+ if (!file.entry) return clean
109
+ const entry = { ...file.entry }
110
+ // These are internal undo/review/runtime records, not user memory fields.
111
+ for (const key of ['absorbSnapshot', 'pendingAbsorb', 'vector', 'reviewReason', 'maintenance', 'maintenanceReview', 'maintenanceSnapshot', 'audit', 'auditTrail']) delete entry[key]
112
+ if (entry.links) entry.links = entry.links.filter(link => disclosed.has(link.to))
113
+ if (Array.isArray(entry.absorbedFrom)) entry.absorbedFrom = entry.absorbedFrom.filter(id => disclosed.has(id))
114
+ for (const key of ['conflictingWith', 'conflicts_with', 'supersedes', 'supersededBy', 'absorbedBy', 'absorbedInto', 'representativeId']) {
115
+ if (entry[key] && !disclosed.has(entry[key])) delete entry[key]
116
+ }
117
+ return { ...clean, entry, related }
118
+ })
119
+ const output = { files, raw: null }
120
+ for (const key of ['libraryId', 'domain', 'source', 'warning', 'total', 'offset', 'recallRoute']) {
121
+ if (result[key] !== undefined) output[key] = result[key]
122
+ }
123
+ return output
124
+ }
125
+
126
+ function portWriteResult(result, exec) {
127
+ if (!result?.entry) return result
128
+ const readable = memory.visibleToSession(result.entry, memory.sessionIdOf(exec))
129
+ return {
130
+ id: result.id,
131
+ entry: readable ? portReadResult({ files: [{ entry: result.entry }] }).files[0].entry : null,
132
+ }
133
+ }
134
+
135
+ export async function privateRemember(args = {}) {
136
+ return portWriteResult(await memory.privateRemember(args), args.exec)
137
+ }
138
+
139
+ function readableTarget(args) {
140
+ const scope = memory.resolveLibrary(args)
141
+ const index = loadPrivateIndex(scope.libraryId)
142
+ // Resolve prefixes against visible entries only, so an ambiguity error cannot
143
+ // enumerate hidden ids. Exact-id checks avoid scanning the library.
144
+ const sessionId = memory.sessionIdOf(args.exec)
145
+ const allowed = entry => entry && memory.isMemoryEligible(entry)
146
+ && memory.visibleToSession(entry, sessionId)
147
+ const clean = String(args.id || '').trim().replace(/\.md$/, '')
148
+ const exact = index.entries?.[clean]
149
+ const visible = exact
150
+ ? (allowed(exact) ? { [clean]: exact } : {})
151
+ : Object.fromEntries(Object.entries(index.entries || {}).filter(([id, entry]) => id.startsWith(clean) && allowed(entry)))
152
+ const id = memory.resolveEntryId({ entries: visible }, args.id)
153
+ return { ...args, libraryId: scope.libraryId, id }
154
+ }
155
+
156
+ export async function privateUpdate(args = {}) {
157
+ return portWriteResult(await memory.privateUpdate(readableTarget(args)), args.exec)
158
+ }
159
+
160
+ export function privateArchive(args = {}) {
161
+ return portWriteResult(memory.privateArchive(readableTarget(args)), args.exec)
162
+ }
163
+
78
164
  export {
79
165
  listLibraries, listLibrariesAll, getLibrary, createLibrary, ensureLibraryForCwd,
80
166
  getSessionBinding, ensureSession, effectiveScope,
81
- loadPrivateIndex, loadGlobalIndex,
82
167
  } from './state.js'
package/lib/private.js CHANGED
@@ -1073,12 +1073,13 @@ const WORKER_STOP_GRACE_MS = 5_000
1073
1073
  import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
1074
1074
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
1075
1075
  import {
1076
- beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey, sessionState,
1076
+ beginJob, completeJob, failJob, releaseEntityReviewJob, findOperation, noteEvidence, operationKey, sessionState,
1077
1077
  recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
1078
1078
  readCarryCandidates, setCarryCandidates,
1079
1079
  } from './consolidation-ledger.js'
1080
1080
  import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
1081
- import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
1081
+ import { buildWorkerBrief, buildEntityReviewBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
1082
+ import { pendingEntityReviewPairs } from './graph.js'
1082
1083
  // worker-pool.js owns worker acquisition, retirement, epoch tracking, package assembly,
1083
1084
  // and tool mounting; the 'fork' path uses the same tool-mount implementation.
1084
1085
  import {
@@ -1260,6 +1261,8 @@ export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_
1260
1261
 
1261
1262
  export async function requestHistoricalConsolidation(ctx, sessionId, options = {}) {
1262
1263
  const { maxWaitMs = null, force = false, trigger = null } = options
1264
+ const entityReviewOnly = options.entityReviewOnly === true
1265
+ const entityReviewPairs = entityReviewOnly ? (options.entityReviewPairs || []).slice(0, 20) : []
1263
1266
  const binding = getSessionBinding(sessionId)
1264
1267
  if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
1265
1268
  if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
@@ -1336,8 +1339,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1336
1339
  libraryId: binding.libraryId || null,
1337
1340
  ok,
1338
1341
  level: ok ? 'info' : (result?.timedOut ? 'warn' : 'error'),
1339
- message: '整理' + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
1340
- + (force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
1342
+ message: (entityReviewOnly ? '实体自动裁决' : '整理') + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
1343
+ + (entityReviewOnly ? '' : force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
1341
1344
  + (result?.childId ? ' · fork ' + result.childId.slice(-8) : '')
1342
1345
  + (result?.reasonCode ? ' · ' + result.reasonCode : '')
1343
1346
  + (result?.error ? ':' + String(result.error) : '')
@@ -1350,7 +1353,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1350
1353
  return result
1351
1354
  }
1352
1355
  try {
1353
- const settings = getSettings()
1356
+ const settings = entityReviewOnly ? { ...getSettings(), consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' } : getSettings()
1354
1357
  workerMode = settings.consolidationRunner === 'worker'
1355
1358
  accounting = createConsolidationMeasurement(workerMode ? 'worker' : 'fork')
1356
1359
  // 僵尸租约先回收:进程被杀之后 inflight 会留在账本里,不能让一条死记录永久挡住这个会话。
@@ -1413,16 +1416,16 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1413
1416
  // A manual click on an already-settled session still re-checks the tail instead
1414
1417
  // of replaying megabytes; automatic runs only look at what the cursor has not
1415
1418
  // covered. Either way the fork gets one bounded window, not the whole log.
1416
- const candidateEvents = force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
1419
+ const candidateEvents = entityReviewOnly || force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
1417
1420
  if (candidateEvents.length === 0) {
1418
1421
  return finish({ ok: true, sessionId, skipped: 'no-new-events', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
1419
1422
  }
1420
1423
  const generationAtStart = scopeGenerationOf(binding)
1421
1424
  // 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
1422
- safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
1425
+ if (!entityReviewOnly) safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
1423
1426
 
1424
1427
  let value = null
1425
- if (!force) {
1428
+ if (!force && !entityReviewOnly) {
1426
1429
  value = assessConsolidationValue(candidateEvents)
1427
1430
  // 这一批里没有真人回合、或只有一句「好的继续」:这一段确实没什么可整理的,
1428
1431
  // 是终态而不是 deferral——写入完成边界由 cycle 落到 lastSleepAt,下一次真人
@@ -1520,7 +1523,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1520
1523
  // 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
1521
1524
  const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1522
1525
  const domain = domainOf(binding)
1523
- const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
1526
+ const mustCover = entityReviewOnly ? [] : mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
1524
1527
  const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1525
1528
  memoryCatalogEvent({ ...binding, sessionId }),
1526
1529
  memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
@@ -1531,8 +1534,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1531
1534
 
1532
1535
  // 幂等:同一份固定快照已经结算过就不再 fork 一次(失败的部分写入靠操作键判同再试,
1533
1536
  // 而不是靠"同一个主题就跳过")。
1534
- const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart })
1535
- const previous = safeLedger(() => findOperation(sessionId, opKey))
1537
+ const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart,
1538
+ kind: entityReviewOnly ? 'entity-review' : 'consolidate' })
1539
+ const previous = entityReviewOnly ? null : safeLedger(() => findOperation(sessionId, opKey))
1536
1540
  if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
1537
1541
  return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
1538
1542
  }
@@ -1604,7 +1608,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1604
1608
  // 走不到超时路径就死的任务(插件重启 / fork 被外力杀掉)不会调 failJob,
1605
1609
  // 固定 15 分钟租约让该会话的重试一直撞 lease-held;预算封顶 600s,
1606
1610
  // 租约最迟在真死后 ~90s 由 recoverStaleJobs 回收,而不是再等 9 分钟。
1607
- const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000 }))
1611
+ const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000,
1612
+ kind: entityReviewOnly ? 'entity-review' : 'consolidate' }))
1608
1613
  if (!begun) {
1609
1614
  return finish({
1610
1615
  ok: false, sessionId, settled: false, retryable: true, reasonCode: 'ledger-unavailable',
@@ -1695,7 +1700,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1695
1700
  let dispatchKind = 'fork'
1696
1701
  if (workerMode) {
1697
1702
  const workerBinding = { ...binding, sessionId }
1698
- workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
1703
+ workerIncrement = entityReviewOnly ? { records: [], text: '实体候选证据由工具读取。' }
1704
+ : loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
1699
1705
  if (!workerIncrement.text.trim()) {
1700
1706
  safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'empty-increment', retryable: true }))
1701
1707
  return finish({ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'empty-increment', error: 'no readable worker increment; the range stays pending' })
@@ -1716,6 +1722,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1716
1722
  }
1717
1723
  const buildPacket = (acquired) => {
1718
1724
  dispatchKind = acquired.birth ? 'handoff' : 'increment'
1725
+ if (entityReviewOnly) return [acquired.birth ? privatePrompt : '',
1726
+ acquired.birth ? buildHandoffPack({ ...common, mustCover: [], contract: '', includeTail: false, writtenRows: [],
1727
+ incrementRecords: [], incrementText: '本轮仅裁决实体候选,转录整理将另行投递。' }) : '',
1728
+ acquired.birth ? '后续普通整理任务将另发任务书;下面的范围限制仅适用于本轮。' : '',
1729
+ buildEntityReviewBrief({ pairs: entityReviewPairs })].filter(Boolean).join('\n')
1719
1730
  const pack = acquired.birth ? buildHandoffPack({
1720
1731
  ...common, includeTail: acquired.handoff !== false, writtenRows: acquired.handoff === false ? [] : null,
1721
1732
  }) : buildIncrementPack(common)
@@ -1820,7 +1831,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1820
1831
  contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1821
1832
  reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
1822
1833
  })
1823
- dispatchText = [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
1834
+ dispatchText = entityReviewOnly ? buildEntityReviewBrief({ pairs: entityReviewPairs })
1835
+ : [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
1824
1836
  }
1825
1837
  accounting.measurement.packet = measurePacket(dispatchText, dispatchKind)
1826
1838
 
@@ -1832,7 +1844,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1832
1844
  sessionId,
1833
1845
  libraryId: binding.libraryId || null,
1834
1846
  ok: true,
1835
- message: '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲'))
1847
+ message: (entityReviewOnly ? '实体自动裁决已开始' : '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲')))
1836
1848
  + ' · fork ' + childId.slice(-8)
1837
1849
  + ' · 窗口 ' + window.events.length + ' 条事件(父会话 ' + events.length + ' 条 / 新 ' + freshCount + ' 条)'
1838
1850
  + (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
@@ -1883,17 +1895,19 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1883
1895
  if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
1884
1896
  revalidate('worker-write')
1885
1897
  workerToolRounds += 1
1886
- if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
1898
+ const hardStopRounds = entityReviewOnly ? Math.max(WORKER_HARD_STOP_ROUND, (entityReviewPairs.length + 1) * 4) : WORKER_HARD_STOP_ROUND
1899
+ if (workerToolRounds >= hardStopRounds) {
1887
1900
  // worker 模式 abort 的是绑在生命周期上的 epoch 控制器,硬停才真正生效;
1888
1901
  // 回合以 aborted 收尾 → turnEndFailure → 退役。fork 模式仍 abort 窗口 signal。
1889
1902
  try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
1890
1903
  } else {
1891
1904
  const guidance = workerRoundGuidance(workerToolRounds)
1892
- if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1905
+ if (!entityReviewOnly && guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1893
1906
  try {
1894
1907
  const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
1895
- accounting.dispatch(guidance.text, 'wrapup')
1896
- Promise.resolve(queued).catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
1908
+ Promise.resolve(queued)
1909
+ .then(() => accounting.dispatch(guidance.text, 'wrapup'))
1910
+ .catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
1897
1911
  } catch (error) { warn('consolidation wrapup followup failed: ' + describeError(error)) }
1898
1912
  }
1899
1913
  }
@@ -1912,6 +1926,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1912
1926
  setSessionBinding(childId, {
1913
1927
  libraryId: binding.libraryId,
1914
1928
  consolidationFork: true,
1929
+ entityReviewOnly,
1930
+ entityReviewPairs: entityReviewOnly ? entityReviewPairs : null,
1915
1931
  // 整理发生在几小时后,父会话此刻的心境不是这段转录里那件事的情绪,所以 fork
1916
1932
  // 不继承 mood。显式写 null 而不是留空:缺字段和「这一刻是中性」在写入时都走
1917
1933
  // 同一条兜底,但只有 null 能把「后台 worker 没有当下心境」说清楚。
@@ -1958,7 +1974,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1958
1974
  }
1959
1975
 
1960
1976
  // Measure exactly the final followup text, including all separators/briefs.
1961
- handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
1977
+ await handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
1962
1978
  accounting.dispatch(dispatchText, dispatchKind)
1963
1979
  // followup only queues. whenIdle says the driver stopped; turn/end says
1964
1980
  // whether that turn actually succeeded, so both are checked below.
@@ -2028,6 +2044,15 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
2028
2044
  }
2029
2045
  // 兼容字段 lastSleepSeq 只能跟着凭证走:没有对账过的结果就不算整理过,
2030
2046
  // Otherwise the legacy cursor could mark failed work as completed.
2047
+ if (entityReviewOnly) {
2048
+ const pending = pendingEntityReviewPairs({ exec: { agent: { session: { header: { id: sessionId } } } },
2049
+ libraryId: binding.libraryId, pairs: entityReviewPairs })
2050
+ if (workerMode && !pending.length) recordEpochProgress({ sessionId }, { settled: true, progress: false })
2051
+ safeLedger(() => releaseEntityReviewJob({ sessionId, jobId }))
2052
+ return finish({ ok: pending.length === 0, sessionId, childId, entityReviewOnly: true,
2053
+ settled: pending.length === 0, processed: entityReviewPairs.length - pending.length, pending: pending.length,
2054
+ ...(pending.length ? { reasonCode: 'entity-review-not-settled', error: 'some entity candidates have no persisted decision; retry with backoff' } : {}) })
2055
+ }
2031
2056
  if (beforeIds) {
2032
2057
  try {
2033
2058
  const afterIds = Object.keys(loadPrivateIndex(binding.libraryId).entries)
@@ -2118,7 +2143,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
2118
2143
  // 「上窗未结算」核对说明(consolidationPending 标记)。连续 2 次超时升级退役
2119
2144
  // (防反复卡死吃窗口),退役允许交接——worker 上下文没坏,只是慢。
2120
2145
  workerEpochRecord = recordEpochProgress({ sessionId }, { timeout: true, progress: false }) || workerEpochRecord
2121
- setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
2146
+ if (!entityReviewOnly) setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
2122
2147
  if ((Number(workerEpochRecord?.timeouts) || 0) >= WORKER_TIMEOUT_LIMIT) {
2123
2148
  try { await retireWorker(ctx, childId, 'timeout-x2', { handoff: true }) } catch {}
2124
2149
  }
@@ -2179,6 +2204,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
2179
2204
  if (jobId) safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'exception', error: String(error?.message || error) }))
2180
2205
  return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
2181
2206
  } finally {
2207
+ if (entityReviewOnly && jobId) safeLedger(() => releaseEntityReviewJob({ sessionId, jobId }))
2182
2208
  inFlight.delete(sessionId)
2183
2209
  if (workerMode) {
2184
2210
  // 持久 worker(§15.2 改动点 6):每窗 finally 只清 inFlight 与本轮局部资源——
@@ -15,6 +15,8 @@
15
15
  // 通过 onError 回调(setErrorHandler,由 memory.js 接 warn)和 stats() 的
16
16
  // errors/lastError 把真实故障暴露给调用方,绝不静默吞掉。
17
17
 
18
+ import { createBoundedCache, cacheDiagnostics } from './bounded-cache.js'
19
+
18
20
  const SEP = '\u0000'
19
21
 
20
22
  function cloneValue(value) {
@@ -24,11 +26,13 @@ function cloneValue(value) {
24
26
  return structuredClone(value)
25
27
  }
26
28
 
27
- export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.now(), onError = null } = {}) {
29
+ export function createRecallCache({ max = 256, maxBytes = 16 * 1024 * 1024, ttlMs = 120000, now = () => Date.now(), onError = null, name = null } = {}) {
28
30
  const limit = Math.max(1, Math.floor(Number(max)) || 1)
29
31
  const ttl = Math.max(0, Math.floor(Number(ttlMs)) || 0)
30
32
  const clock = typeof now === 'function' ? now : () => Date.now()
31
- const map = new Map() // key: gen + SEP + key → { value, expiresAt, query, gen }
33
+ const map = createBoundedCache({ name, maxBytes, maxEntries: limit, ttlMs: ttl, now: clock,
34
+ onEvict: (_key, _value, reason) => { evictions++; if (reason === 'ttl') staleSkipped++ },
35
+ })
32
36
  const inflight = new Map() // key: gen + SEP + key → Promise(同 key 在途合并,防击穿)
33
37
  let gen = 0
34
38
  let hits = 0
@@ -47,31 +51,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
47
51
 
48
52
  const ckey = (key) => gen + SEP + String(key)
49
53
 
50
- // 过期即删即逐出(计入 evictions),不参与命中。
51
- const expired = (entry) => clock() >= entry.expiresAt
52
-
53
- const peek = (ck) => {
54
- const entry = map.get(ck)
55
- if (!entry) return null
56
- if (expired(entry)) {
57
- map.delete(ck)
58
- evictions += 1
59
- staleSkipped += 1
60
- return null
61
- }
62
- // LRU 新鲜度:命中即挪到 Map 尾部(删除再插入)。
63
- map.delete(ck)
64
- map.set(ck, entry)
65
- return entry
66
- }
67
-
68
- const evictOverflow = () => {
69
- while (map.size > limit) {
70
- const oldest = map.keys().next().value
71
- map.delete(oldest)
72
- evictions += 1
73
- }
74
- }
54
+ const peek = (ck) => map.get(ck) || null
75
55
 
76
56
  const store = (ck, value) => {
77
57
  if (value === undefined) return // undefined 视为「没有结果」,不缓存
@@ -79,8 +59,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
79
59
  map.delete(ck)
80
60
  // 条目归属的代数取自复合键前缀:在途 producer 在 bump 之后落地时,仍记旧代,
81
61
  // 下一次 bump 会被清理,也永远不会被新代命中。
82
- map.set(ck, { value: snapshot, expiresAt: clock() + ttl, gen: Number(ck.slice(0, ck.indexOf(SEP))) })
83
- evictOverflow()
62
+ map.set(ck, { value: snapshot, gen: Number(ck.slice(0, ck.indexOf(SEP))) })
84
63
  }
85
64
 
86
65
  const cache = {
@@ -148,7 +127,12 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
148
127
  } catch (error) { fail('wrap.get', error, key) }
149
128
  if (ck !== null) {
150
129
  const pending = inflight.get(ck)
151
- if (pending) { hits += 1; return pending } // 在途合并:与命中同计
130
+ if (pending) {
131
+ hits += 1
132
+ return pending.then(value => {
133
+ try { return cloneValue(value) } catch (error) { fail('wrap.clone', error, key); return value }
134
+ })
135
+ } // 在途合并计算,但每个调用方拿到独立结果;与命中同计
152
136
  }
153
137
  misses += 1
154
138
  const run = (async () => {
@@ -163,10 +147,12 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
163
147
  const settle = () => { inflight.delete(ck) }
164
148
  run.then(settle, settle)
165
149
  }
166
- return run
150
+ return run.then(value => {
151
+ try { return cloneValue(value) } catch (error) { fail('wrap.clone', error, key); return value }
152
+ })
167
153
  },
168
154
  stats() {
169
- return { size: map.size, hits, misses, evictions, staleSkipped, generations: gen, errors, lastError, inflight: inflight.size }
155
+ return { ...map.stats(), size: map.size, hits, misses, evictions, staleSkipped, generations: gen, errors, lastError, inflight: inflight.size }
170
156
  },
171
157
  /** 接错误观察者(memory.js 接 warn,规则 10 的可观测信号)。 */
172
158
  setErrorHandler(handler) {
@@ -204,9 +190,9 @@ export function recallCacheKey({ query, topK, libraryId, byId, route, generation
204
190
  }
205
191
 
206
192
  /** 模块级默认单例:memory.js 直接使用。 */
207
- export const recallCache = createRecallCache()
193
+ export const recallCache = createRecallCache({ name: 'recall' })
208
194
 
209
195
  /** S10:只读统计快照(RPC/运维用);调用方不持有缓存内部状态。 */
210
196
  export function recallCacheStats() {
211
- return recallCache.stats()
197
+ return { ...recallCache.stats(), caches: cacheDiagnostics() }
212
198
  }
@@ -0,0 +1,173 @@
1
+ import { getSettings, listSessionBindings, pruneSessionBindings } from './state.js'
2
+ import { gcTurnLogs, listOrphanTurnLogs, deleteOrphanTurnLog } from './turn-log.js'
3
+ import { pruneSettledMaintenanceItems } from './maintenance-ledger.js'
4
+ import { sessionState, clearSessionState } from './consolidation-ledger.js'
5
+ import { pruneVectorArtifacts } from './vector-profile.js'
6
+ import { pruneRtArtifacts } from './rt-index-retention.js'
7
+ import path from 'node:path'
8
+ import { dataDir, readFailure } from './paths.js'
9
+
10
+ const DAY = 86_400_000
11
+
12
+ function notify(log, text) {
13
+ try { log?.(text) } catch {}
14
+ }
15
+
16
+ function disabled(reason = 'disabled') {
17
+ return { skipped: reason, candidates: [], removed: [] }
18
+ }
19
+
20
+ function busySession(ctx, sessionId, now) {
21
+ try {
22
+ const ledger = sessionState(sessionId)
23
+ if ((Number(ledger?.inflight?.leaseUntil) || 0) > now) return true
24
+ } catch {
25
+ return true
26
+ }
27
+ // If the host agent registry is unavailable, liveness is unknown; fail safe.
28
+ let agents
29
+ try { agents = ctx?.get?.('agents') } catch { return true }
30
+ if (!agents || typeof agents.get !== 'function') return true
31
+ try { return Boolean(agents.get(sessionId)) } catch { return true }
32
+ }
33
+
34
+ function runStep(name, fn, errors, log) {
35
+ try { return fn() } catch (error) {
36
+ const message = String(error?.message || error)
37
+ errors.push({ step: name, error: message })
38
+ notify(log, `retention ${name} failed: ${message}`)
39
+ return { error: message, candidates: [], removed: [] }
40
+ }
41
+ }
42
+
43
+ function reliableBindings() {
44
+ const bindings = listSessionBindings()
45
+ if (readFailure(path.join(dataDir(), 'state.json')) || !Array.isArray(bindings)) {
46
+ throw new Error('session registry could not be read reliably')
47
+ }
48
+ return bindings
49
+ }
50
+
51
+ /**
52
+ * Read-only by default. No memory entry is ever deleted by this pass.
53
+ * Applying any cleanup requires retentionDryRun=false; orphan turn logs additionally
54
+ * require retentionOrphanTurnLogsEnabled=true. Session bindings are rechecked under
55
+ * the state lock and carry a host-agent + consolidation-lease liveness veto.
56
+ */
57
+ export function runRetentionPass(ctx, { now = Date.now(), log = () => {} } = {}) {
58
+ const nowMs = now instanceof Date ? now.getTime() : Number(now)
59
+ const errors = []
60
+ if (!Number.isFinite(nowMs)) return { dryRun: true, errors: [{ step: 'pass', error: 'invalid now' }] }
61
+ let settings
62
+ try { settings = getSettings() } catch (error) {
63
+ return { dryRun: true, errors: [{ step: 'settings', error: String(error?.message || error) }] }
64
+ }
65
+ const dryRun = settings.retentionDryRun !== false
66
+ let bindings = []
67
+ try { bindings = reliableBindings() } catch (error) {
68
+ errors.push({ step: 'bindings-read', error: String(error?.message || error) })
69
+ }
70
+ const result = { dryRun, errors }
71
+
72
+ result.boundTurnLogs = settings.retentionBoundTurnLogsEnabled === true
73
+ ? runStep('bound-turn-logs', () => gcTurnLogs(bindings, {
74
+ now: nowMs, olderThanDays: settings.retentionBoundTurnLogDays, dryRun,
75
+ }), errors, log)
76
+ : { ...disabled(), dryRun }
77
+
78
+ result.orphanTurnLogs = settings.retentionOrphanTurnLogsEnabled === true
79
+ ? runStep('orphan-turn-logs', () => {
80
+ const days = settings.retentionOrphanTurnLogDays
81
+ const plan = listOrphanTurnLogs(reliableBindings(), { now: nowMs, olderThanDays: days })
82
+ const removed = []
83
+ const kept = [...plan.kept]
84
+ if (!dryRun) {
85
+ for (const candidate of plan.candidates) {
86
+ // Refresh the binding snapshot immediately before each unlink. The log module
87
+ // also checks the exact file identity, age, and regular-file status again.
88
+ let currentBindings
89
+ try { currentBindings = reliableBindings() } catch (error) {
90
+ const message = String(error?.message || error)
91
+ kept.push({ name: candidate.name, reason: `bindings-unreadable:${message}` })
92
+ errors.push({ step: 'orphan-turn-logs', error: message })
93
+ notify(log, `retention orphan-turn-logs failed: ${message}`)
94
+ continue
95
+ }
96
+ const outcome = deleteOrphanTurnLog(candidate, currentBindings, { now: nowMs, olderThanDays: days })
97
+ if (outcome.ok) removed.push(candidate.name)
98
+ else kept.push({ name: candidate.name, reason: outcome.reason })
99
+ }
100
+ }
101
+ return { dryRun, olderThanDays: plan.olderThanDays, candidates: plan.candidates, removed, kept }
102
+ }, errors, log)
103
+ : { ...disabled('explicit-opt-in-required'), dryRun }
104
+
105
+ result.maintenanceLedger = settings.retentionMaintenanceLedgerEnabled === true
106
+ ? runStep('maintenance-ledger', () => pruneSettledMaintenanceItems({
107
+ now: nowMs, olderThanDays: settings.retentionMaintenanceLedgerDays, dryRun,
108
+ }), errors, log)
109
+ : { ...disabled(), dryRun }
110
+
111
+ result.sessionBindings = settings.retentionSessionBindingsEnabled === true
112
+ ? runStep('session-bindings', () => {
113
+ const isBusy = sessionId => busySession(ctx, sessionId, nowMs)
114
+ const plan = pruneSessionBindings({
115
+ now: nowMs, olderThanDays: settings.retentionSessionBindingDays, dryRun: true, isBusy,
116
+ })
117
+ if (dryRun) return plan
118
+ const applied = pruneSessionBindings({
119
+ now: nowMs, olderThanDays: settings.retentionSessionBindingDays, dryRun: false, isBusy,
120
+ })
121
+ for (const sessionId of applied.removed || []) {
122
+ try { clearSessionState(sessionId) } catch (error) {
123
+ notify(log, `retention session state cleanup failed for ${sessionId}: ${error?.message || error}`)
124
+ }
125
+ }
126
+ return { ...applied, planned: plan.candidates }
127
+ }, errors, log)
128
+ : { ...disabled(), dryRun }
129
+
130
+ result.vectors = settings.retentionVectorPruneEnabled === true
131
+ ? runStep('vectors', () => pruneVectorArtifacts({
132
+ now: nowMs,
133
+ keepGenerations: settings.retentionVectorKeepGenerations,
134
+ olderThanDays: settings.retentionVectorDays,
135
+ apply: !dryRun,
136
+ }), errors, log)
137
+ : { ...disabled(), dryRun }
138
+
139
+ result.rtIndex = settings.retentionVectorPruneEnabled === true
140
+ ? runStep('rt-index', () => pruneRtArtifacts({ now: nowMs,
141
+ olderThanDays: settings.retentionVectorDays, dryRun,
142
+ }), errors, log)
143
+ : { ...disabled(), dryRun }
144
+
145
+ const totalCandidates = [
146
+ result.boundTurnLogs?.deleted?.length || 0,
147
+ result.orphanTurnLogs?.candidates?.length || 0,
148
+ result.maintenanceLedger?.candidates?.length || 0,
149
+ result.sessionBindings?.candidates?.length || 0,
150
+ result.vectors?.candidates?.length || 0,
151
+ result.rtIndex?.candidates?.length || 0,
152
+ ].reduce((sum, count) => sum + count, 0)
153
+ result.candidateCount = totalCandidates
154
+ if (totalCandidates > 0) notify(log, `retention pass ${dryRun ? 'dry-run' : 'apply'}: ${totalCandidates} candidate(s)`)
155
+ return result
156
+ }
157
+
158
+ export const RETENTION_DEFAULTS = Object.freeze({
159
+ dryRun: true,
160
+ boundTurnLogsEnabled: true,
161
+ boundTurnLogDays: 30,
162
+ orphanTurnLogsEnabled: false,
163
+ orphanTurnLogDays: 90,
164
+ maintenanceLedgerEnabled: true,
165
+ maintenanceLedgerDays: 180,
166
+ sessionBindingsEnabled: false,
167
+ sessionBindingDays: 180,
168
+ vectorPruneEnabled: true,
169
+ vectorKeepGenerations: 2,
170
+ vectorDays: 7,
171
+ })
172
+
173
+ export { DAY as RETENTION_DAY_MS }