dsh-memu-memory 1.3.2 → 1.3.4

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 (48) hide show
  1. package/AGENTS.md +11 -3
  2. package/CHANGELOG.md +57 -3
  3. package/README.md +6 -11
  4. package/README.zh.md +6 -11
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/mobile.jpg +0 -0
  7. package/assets/screenshots/relations.jpg +0 -0
  8. package/assets/screenshots/settings.jpg +0 -0
  9. package/assets/screenshots/stats.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 +21 -0
  13. package/docs/contributing.md +5 -2
  14. package/docs/memory-semantics.md +17 -0
  15. package/docs/troubleshooting.md +44 -0
  16. package/lib/binding-diagnostics.js +2 -2
  17. package/lib/client.js +125 -18
  18. package/lib/consolidation-snapshot.js +101 -5
  19. package/lib/consolidation-worker.js +1 -1
  20. package/lib/cycle.js +19 -1
  21. package/lib/index.js +83 -2
  22. package/lib/private.js +450 -165
  23. package/lib/rpc.js +14 -1
  24. package/lib/state.js +11 -1
  25. package/lib/turn-log.js +522 -0
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +53 -25
  28. package/lib/webui/standalone.css +4 -29
  29. package/lib/worker-pool.js +741 -0
  30. package/package.json +1 -1
  31. package/scripts/acceptance-local.mjs +6 -5
  32. package/scripts/build-graph.mjs +32 -4
  33. package/scripts/check-all.mjs +2 -0
  34. package/scripts/check-idle-compositing.mjs +61 -0
  35. package/scripts/make-readme-shots.mjs +59 -0
  36. package/scripts/prune-turnlogs.mjs +30 -0
  37. package/tests/browser.test.mjs +27 -0
  38. package/tests/client-render.test.mjs +171 -0
  39. package/tests/consolidation-snapshot.test.mjs +89 -1
  40. package/tests/graph-view.test.mjs +60 -3
  41. package/tests/loader.mjs +2 -0
  42. package/tests/salience-domain.test.mjs +139 -0
  43. package/tests/settings-coverage.test.mjs +97 -0
  44. package/tests/stubs/dsh-session-query.js +26 -0
  45. package/tests/turn-log.test.mjs +474 -0
  46. package/tests/webui.test.mjs +19 -0
  47. package/tests/worker-lifecycle.test.mjs +1046 -0
  48. package/docs/recall-benchmark.md +0 -238
package/lib/rpc.js CHANGED
@@ -1040,6 +1040,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1040
1040
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1041
1041
  // 自动关联:恢复默认 = 回到 suggest(只出候选、不写边)。
1042
1042
  'autoLinkMode', 'allowWorkerAssertion',
1043
+ // 增量回合日志(设计文档 §10.1):恢复默认 = on + 纯对话档。
1044
+ 'consolidationTurnLog', 'consolidationTurnLogTools',
1045
+ // 整理执行器(T1 §10.2):恢复默认 = 回到 'fork'(现状每窗新 fork)。
1046
+ 'consolidationRunner',
1043
1047
  ]) patch[key] = DEFAULT_SETTINGS[key]
1044
1048
  return redactConsolidationSettings(updateSettings(patch))
1045
1049
  }
@@ -1068,6 +1072,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1068
1072
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1069
1073
  // 自动关联的写入门控(DESIGN §6.4):suggest / deterministic / off。
1070
1074
  'autoLinkMode', 'allowWorkerAssertion',
1075
+ // 增量回合日志(设计文档 §10.1):on/off + 工具行三档(none/errors/summary)。
1076
+ 'consolidationTurnLog', 'consolidationTurnLogTools',
1077
+ // 整理执行器(T1 §10.2):'fork'(默认,现状)/ 'worker'(持久整理 worker)。
1078
+ 'consolidationRunner',
1071
1079
  ])
1072
1080
  const clean = {}
1073
1081
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
@@ -1221,7 +1229,12 @@ async function dispatch(ctx, endpoint, payload = {}) {
1221
1229
  return { ok: true, scopeMissing: libraryScopeMissing(result.library), archived: archivedLibraryView() }
1222
1230
  }
1223
1231
  case 'listSessions': {
1224
- return { sessions: await recentSessions(ctx, payload?.limit) }
1232
+ const sessions = await recentSessions(ctx, payload?.limit)
1233
+ // 手动整理按钮需要「这个库绑了哪些对话」。绑定表里本来就有 libraryId
1234
+ // (boundSessions 计数用的就是它),这里只补一个只读字段:不新增端点、
1235
+ // 不动鉴权,整理仍然走会话维度的 generatePrivate(与侧边栏同一通道)。
1236
+ const bindings = loadState().sessions || {}
1237
+ return { sessions: sessions.map(row => ({ ...row, libraryId: bindings[row.id]?.libraryId || null })) }
1225
1238
  }
1226
1239
  case 'listPrivate': {
1227
1240
  const sessionId = requireSessionId(payload)
package/lib/state.js CHANGED
@@ -153,6 +153,16 @@ export const DEFAULT_SETTINGS = {
153
153
  consolidationCustomApiKey: '',
154
154
  consolidationCustomModel: '',
155
155
  consolidationCustomApi: 'openai-completions',
156
+ // T0 构件 1(设计文档 §10.1):增量回合日志。'on'(默认)按回合实时落盘,是持久
157
+ // 整理 worker 的上下文载体(缓存,不是账本);'off' 时输入退回现场 condenseEvents。
158
+ consolidationTurnLog: 'on',
159
+ // T1 构件(设计文档 §10.2):整理执行器。'fork'(默认)= 现状每窗新 fork,行为零
160
+ // 变化;'worker' = 持久整理 worker(lib/worker-pool.js,epoch 制跨窗复用,三级试活,
161
+ // 五退役条件,§4)。回滚 = 切回 'fork',数据层无依赖(turn-log 是缓存,账本才算数)。
162
+ consolidationRunner: 'fork',
163
+ // 工具行三档(§3.1):'none' 纯对话(默认,实测每窗 ≈3.7k);'errors' 只留错误
164
+ // 结果行(≈357 字符/窗的廉价保险);'summary' 完整一行摘要(coding 域保真最高)。
165
+ consolidationTurnLogTools: 'none',
156
166
  // A positive age marks cleanup candidates; deletion always needs a user action.
157
167
  purgeArchivedAfterDays: 0,
158
168
  }
@@ -412,7 +422,7 @@ export function updateSettings(patch) {
412
422
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
413
423
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
414
424
  }
415
- const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
425
+ const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
416
426
  for (const [key, value] of Object.entries(patch || {})) {
417
427
  if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
418
428
  if (enums[key]) {
@@ -0,0 +1,522 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { dataDir, ensureDir, warn, redactSecrets, isSafeId, shortHash, stamp } from './paths.js'
5
+ import { getSettings, getSessionBinding } from './state.js'
6
+
7
+ // T0 构件 1(设计文档 §3):增量回合日志。
8
+ //
9
+ // 定位是纯旁路缓存,不是账本(§0 铁律 1):每行一个宿主 turn/end 的 seq 区间,
10
+ // 记录规则与 condenseEvents 同口径(§3.1,不发明新规则)。任何失败只 warn,
11
+ // 绝不影响主会话;正确性永远由宿主转录 + 缺口重建兜底(§3.3)。
12
+ //
13
+ // 三层 caps(§3.1):user/model 各 2000 字全保;工具行 160 字;整条记录 4000 字
14
+ // 总闸——超预算只砍 tools 行(按序装、砍尾并标注省略数),user/model 不动。
15
+
16
+ export const TURNLOG_USER_MODEL_CHARS = 2000
17
+ export const TURNLOG_TOOL_LINE_CHARS = 160
18
+ export const TURNLOG_RECORD_CHARS = 4000
19
+ export const TURNLOG_KEEP_CHARS = 200_000
20
+ export const TURNLOG_GC_DAYS = 30
21
+
22
+ const TURNLOG_SUFFIX = '.turnlog.jsonl'
23
+
24
+ function truncate(text, max) {
25
+ const s = String(text || '')
26
+ return s.length > max ? `${s.slice(0, max)}…` : s
27
+ }
28
+
29
+ function firstLine(text) {
30
+ const s = String(text || '').replace(/\r/g, '')
31
+ const nl = s.indexOf('\n')
32
+ return (nl >= 0 ? s.slice(0, nl) : s).trim()
33
+ }
34
+
35
+ function textOfBlocks(blocks) {
36
+ if (typeof blocks === 'string') return blocks.trim()
37
+ if (!Array.isArray(blocks)) return ''
38
+ return blocks
39
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
40
+ .map((b) => b.text)
41
+ .join('')
42
+ .trim()
43
+ }
44
+
45
+ function argsText(value) {
46
+ if (value == null) return ''
47
+ return typeof value === 'string' ? value : JSON.stringify(value)
48
+ }
49
+
50
+ /**
51
+ * 会话 id 直接拼进文件名。宿主 id 是安全字符集;防御性兜底把任何奇怪 id 哈希成
52
+ * 固定名(缓存可重建,哈希碰撞的最坏结果是两段日志混在一个文件里,可接受)。
53
+ */
54
+ function logFileName(sessionId) {
55
+ const raw = String(sessionId || '')
56
+ return (isSafeId(raw) ? raw : `sid-${shortHash(raw)}`) + TURNLOG_SUFFIX
57
+ }
58
+
59
+ export function turnLogPath(sessionId) {
60
+ return path.join(ensureDir(path.join(dataDir(), 'sessions')), logFileName(sessionId))
61
+ }
62
+
63
+ function safeSeqRange(record) {
64
+ const seq = record?.seq
65
+ if (!Array.isArray(seq) || seq.length !== 2) return null
66
+ const start = Number(seq[0])
67
+ const end = Number(seq[1])
68
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) return null
69
+ return [start, end]
70
+ }
71
+
72
+ // —— 记录规则(§3.1,与 condenseEvents 同口径) ————————————————
73
+
74
+ function toolCallIdOfResult(event) {
75
+ const message = event?.data?.message
76
+ return [message?.callId, message?.toolCallId, message?.source?.callId]
77
+ .find((value) => typeof value === 'string' && value) || null
78
+ }
79
+
80
+ function toolLine(name, args, status, errorText) {
81
+ const head = `${name || '?'}${args ? `(${truncate(args, 120)})` : ''}`
82
+ const tail = status === 'ok' ? ' → 成功'
83
+ : status === 'error' ? ` → 失败: ${firstLine(errorText)}`
84
+ : ' → 无结果'
85
+ // 工具行与对话文本同一待遇:先脱敏再截断(§3.1「记录时应用 redactSecrets」)。
86
+ return truncate(redactSecrets(head + tail), TURNLOG_TOOL_LINE_CHARS)
87
+ }
88
+
89
+ /**
90
+ * 'summary' 档工具行:调用 + 结果按 callId 配对。tool/call 事件是权威侧
91
+ * (assistant 消息里的 tool-call 块是同一次调用的双写,不单独成行——condenseEvents C2 同款)。
92
+ */
93
+ function summaryToolLines(events) {
94
+ const lines = []
95
+ const calls = new Map() // callId -> line entry
96
+ for (const event of events) {
97
+ if (event?.type !== 'tool/call') continue
98
+ const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
99
+ if (id && calls.has(id)) continue // 同一 callId 双写去重
100
+ const entry = { name: event?.data?.name || '?', args: argsText(event?.data?.arguments), status: 'pending', errorText: '' }
101
+ if (id) calls.set(id, entry)
102
+ lines.push(entry)
103
+ }
104
+ for (const event of events) {
105
+ if (event?.type !== 'tool/result') continue
106
+ const id = toolCallIdOfResult(event)
107
+ const entry = id ? calls.get(id) : null
108
+ const isError = event?.data?.message?.isError === true
109
+ const text = textOfBlocks(event?.data?.message?.content)
110
+ if (entry && !entry.done) {
111
+ entry.status = isError ? 'error' : 'ok'
112
+ entry.errorText = text
113
+ entry.done = true
114
+ } else if (!entry) {
115
+ // 结果先于调用可见(乱序/旧 fixture):结果行自己成行,错误结果在 errors 档也要可见。
116
+ lines.push({ name: '?', args: '', status: isError ? 'error' : 'ok', errorText: text, done: true })
117
+ }
118
+ }
119
+ return lines.map((entry) => toolLine(entry.name, entry.args, entry.status === 'pending' ? 'none' : entry.status, entry.errorText))
120
+ }
121
+
122
+ /** 'errors' 档:只收 isError 的工具结果行——失败尝试是漏网事实的最廉价来源(§3.1)。 */
123
+ function errorToolLines(events) {
124
+ const names = new Map()
125
+ for (const event of events) {
126
+ if (event?.type !== 'tool/call') continue
127
+ const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
128
+ if (id && !names.has(id)) names.set(id, event?.data?.name || '?')
129
+ }
130
+ const lines = []
131
+ for (const event of events) {
132
+ if (event?.type !== 'tool/result' || event?.data?.message?.isError !== true) continue
133
+ const id = toolCallIdOfResult(event)
134
+ const name = (id && names.get(id)) || '?'
135
+ lines.push(toolLine(name, '', 'error', textOfBlocks(event?.data?.message?.content)))
136
+ }
137
+ return lines
138
+ }
139
+
140
+ function joinParts(parts, max) {
141
+ return truncate(redactSecrets(parts.join('\n')), max)
142
+ }
143
+
144
+ /**
145
+ * 把一段宿主事件流转成回合记录数组(纯函数:同输入同输出)。
146
+ *
147
+ * 分组与 candidateSeedEvents 同款:turn/start 开组(或流中途无组时首个事件开组),
148
+ * turn/end 封组;尾部没有 turn/end 的半回合不产出记录(未结算)。
149
+ * options.tools 覆盖设置档(测试用),默认读 consolidationTurnLogTools。
150
+ */
151
+ export function buildTurnRecords(events, options = {}) {
152
+ let toolsMode = options.tools
153
+ if (toolsMode === undefined) {
154
+ try { toolsMode = getSettings().consolidationTurnLogTools } catch { toolsMode = undefined }
155
+ }
156
+ if (toolsMode !== 'errors' && toolsMode !== 'summary') toolsMode = 'none'
157
+
158
+ const groups = []
159
+ let current = null
160
+ for (const event of Array.isArray(events) ? events : []) {
161
+ if (!event || typeof event.type !== 'string') continue
162
+ if (event.type === 'turn/start' || current === null) {
163
+ current = []
164
+ groups.push(current)
165
+ }
166
+ current.push(event)
167
+ if (event.type === 'turn/end') current = null
168
+ }
169
+
170
+ const records = []
171
+ for (const group of groups) {
172
+ const end = group[group.length - 1]
173
+ if (end?.type !== 'turn/end') continue // 未闭合的半回合留给下一窗对账重建
174
+ const startSeq = Number(group[0]?.seq)
175
+ const endSeq = Number(end?.seq)
176
+ if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq) || startSeq < 0 || endSeq < startSeq) continue
177
+
178
+ const userParts = []
179
+ const modelParts = []
180
+ let scene = null
181
+ for (const event of group) {
182
+ if (event.type === 'user/message') {
183
+ // 只收真人消息:插件注入 / 调度 / 心跳一律不记(§3.1 过滤口径)。
184
+ if (event?.data?.source?.kind !== 'user') continue
185
+ const text = textOfBlocks(event?.data?.content)
186
+ if (text) userParts.push(text)
187
+ const sceneTime = event?.data?.sceneTime
188
+ if (typeof sceneTime === 'string' && sceneTime.trim()) scene = sceneTime
189
+ } else if (event.type === 'assistant/message') {
190
+ // assistant 只收 text 块:reasoning / tool-call 块不进对话记录。
191
+ const text = textOfBlocks(event?.data?.message?.content)
192
+ if (text) modelParts.push(text)
193
+ }
194
+ }
195
+
196
+ const record = {
197
+ seq: [startSeq, endSeq],
198
+ at: Number.isFinite(end?.time) ? new Date(end.time).toISOString() : null,
199
+ scene,
200
+ user: joinParts(userParts, TURNLOG_USER_MODEL_CHARS),
201
+ model: joinParts(modelParts, TURNLOG_USER_MODEL_CHARS),
202
+ }
203
+ const kind = end?.data?.reason?.kind
204
+ if (kind && kind !== 'completed') record.interrupted = true
205
+
206
+ let toolLines = []
207
+ if (toolsMode === 'summary') toolLines = summaryToolLines(group)
208
+ else if (toolsMode === 'errors') toolLines = errorToolLines(group)
209
+ if (toolLines.length > 0) record.tools = toolLines
210
+
211
+ // 空回合(纯注入/心跳/无对话无工具)不落行。
212
+ if (!record.user && !record.model && !(record.tools && record.tools.length > 0)) continue
213
+
214
+ applyRecordCap(record)
215
+ records.push(record)
216
+ }
217
+ return records
218
+ }
219
+
220
+ /** 4000 字总闸:超预算只砍 tools 尾部(user/model 在各自 2000 内全保)。 */
221
+ function applyRecordCap(record) {
222
+ const tools = record.tools
223
+ if (!Array.isArray(tools) || tools.length === 0) return
224
+ if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS) return
225
+ const marker = (n) => `…[另有 ${n} 条工具调用已省略]`
226
+ let kept = tools.length
227
+ while (kept >= 0) {
228
+ record.tools = tools.slice(0, kept)
229
+ if (kept < tools.length) record.tools.push(marker(tools.length - kept))
230
+ if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS || kept === 0) return
231
+ kept -= 1
232
+ }
233
+ }
234
+
235
+ // —— 落盘与读取 ————————————————————————————————————————————
236
+
237
+ function scanTurnLog(sessionId) {
238
+ const file = turnLogPath(sessionId)
239
+ let raw
240
+ try {
241
+ raw = fs.readFileSync(file, 'utf8')
242
+ } catch (error) {
243
+ // ENOENT = 空日志(正常);其他读失败当作不可读:绝不在没读到的地方重写。
244
+ if (error?.code !== 'ENOENT') warn(`turn-log read failed for ${logFileName(sessionId)}: ${error?.message || error}`)
245
+ return { file, entries: [], badLines: 0, unreadable: error?.code !== 'ENOENT' }
246
+ }
247
+ const entries = []
248
+ let badLines = 0
249
+ for (const line of raw.split('\n')) {
250
+ const trimmed = line.trim()
251
+ if (!trimmed) continue
252
+ let record = null
253
+ try { record = JSON.parse(trimmed) } catch { badLines += 1 }
254
+ entries.push({ raw: trimmed, record })
255
+ }
256
+ return { file, entries, badLines, unreadable: false }
257
+ }
258
+
259
+ /** 坏行原样保留地原子重写(Windows 上 rename 的 EPERM/EBUSY 重试用 paths.js 同款节奏)。 */
260
+ function rewriteTurnLog(file, lines) {
261
+ ensureDir(path.dirname(file))
262
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
263
+ try {
264
+ fs.writeFileSync(tmp, lines.length > 0 ? lines.join('\n') + '\n' : '', 'utf8')
265
+ for (let attempt = 0; ; attempt++) {
266
+ try { fs.renameSync(tmp, file); break } catch (error) {
267
+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
268
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
269
+ }
270
+ }
271
+ } catch (error) {
272
+ try { fs.rmSync(tmp, { force: true }) } catch {}
273
+ throw error
274
+ }
275
+ }
276
+
277
+ /**
278
+ * 重建补洞会把旧回合追加到文件尾部,打乱"文件序 = 时间序"的不变量(读取侧
279
+ * readIncrement/tailSlice/pruneHead 都按文件序工作)。这里把有效记录按 seq 排回
280
+ * 升序;坏行 seq 未知,原样保留在尾部。仅在确实乱序时重写,append-only 常态零开销。
281
+ */
282
+ function sortTurnLogBySeq(sessionId) {
283
+ const scan = scanTurnLog(sessionId)
284
+ if (scan.unreadable || scan.entries.length === 0) return
285
+ const valid = []
286
+ const bad = []
287
+ for (const entry of scan.entries) {
288
+ if (safeSeqRange(entry.record)) valid.push(entry)
289
+ else bad.push(entry)
290
+ }
291
+ let ordered = true
292
+ for (let i = 1; i < valid.length; i += 1) {
293
+ if (valid[i].record.seq[0] < valid[i - 1].record.seq[0]) { ordered = false; break }
294
+ }
295
+ if (ordered) return
296
+ valid.sort((a, b) => a.record.seq[0] - b.record.seq[0] || a.record.seq[1] - b.record.seq[1])
297
+ try {
298
+ rewriteTurnLog(scan.file, [...valid, ...bad].map((entry) => entry.raw))
299
+ } catch (error) {
300
+ warn(`turn-log sort failed for ${logFileName(sessionId)}: ${error?.message || error}`)
301
+ }
302
+ }
303
+
304
+ /**
305
+ * 追加一行回合记录。记录器是旁路:任何失败只 warn,绝不抛给主会话(§3.2)。
306
+ * 落盘后顺带做一次头部裁剪(§3.4:只裁已结算段)。
307
+ */
308
+ export function recordTurn(sessionId, record) {
309
+ try {
310
+ if (!safeSeqRange(record)) {
311
+ warn(`turn-log record rejected for ${logFileName(sessionId)}: missing a valid seq range`)
312
+ return null
313
+ }
314
+ const line = JSON.stringify({ ...record, at: record.at || stamp() })
315
+ fs.appendFileSync(turnLogPath(sessionId), line + '\n', 'utf8')
316
+ try {
317
+ let lastSleepSeq = null
318
+ try { lastSleepSeq = getSessionBinding(String(sessionId))?.lastSleepSeq ?? null } catch {}
319
+ pruneHead(String(sessionId), TURNLOG_KEEP_CHARS, lastSleepSeq)
320
+ } catch {}
321
+ return line
322
+ } catch (error) {
323
+ warn(`turn-log append failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
324
+ return null
325
+ }
326
+ }
327
+
328
+ /**
329
+ * 自 afterSeq 之后的增量回合。回合是不可分单位(§3.3):记录天然整回合,
330
+ * 所以按 seqStart > afterSeq 过滤即可,不存在半回合重复读。
331
+ * 注意:worker 增量入口 loadWorkerIncrement 用 readIncrement(-1) 读全量后自行按
332
+ * seqEnd > lastSleepSeq 过滤(跨骑回合整条收),本函数的 afterSeq 过滤只服务直接调用方。
333
+ */
334
+ export function readIncrement(sessionId, afterSeq) {
335
+ const scan = scanTurnLog(sessionId)
336
+ const after = Number(afterSeq)
337
+ const from = Number.isSafeInteger(after) ? after : -1
338
+ const records = scan.entries
339
+ .map((entry) => entry.record)
340
+ .filter((record) => {
341
+ const range = safeSeqRange(record)
342
+ return range && range[0] > from
343
+ })
344
+ return { records, badLines: scan.badLines }
345
+ }
346
+
347
+ /**
348
+ * 校验 [fromSeq, throughSeq] 的日志覆盖与连续性(§3.3)。
349
+ * missingRanges 是窗口内没有被任何记录盖住的 seq 子区间(含记录之间的空洞)。
350
+ */
351
+ export function verifyGap(sessionId, fromSeq, throughSeq) {
352
+ const scan = scanTurnLog(sessionId)
353
+ const from = Number(fromSeq)
354
+ const through = Number(throughSeq)
355
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
356
+ return { ok: true, missingRanges: [], badLines: scan.badLines }
357
+ }
358
+ const covered = scan.entries
359
+ .map((entry) => entry.record)
360
+ .map((record) => safeSeqRange(record))
361
+ .filter((range) => range && range[1] >= from && range[0] <= through)
362
+ .sort((a, b) => a[0] - b[0])
363
+ const missingRanges = []
364
+ let cursor = from
365
+ for (const [start, end] of covered) {
366
+ if (start > cursor) missingRanges.push([cursor, start - 1])
367
+ if (end + 1 > cursor) cursor = end + 1
368
+ }
369
+ if (cursor <= through) missingRanges.push([cursor, through])
370
+ return { ok: missingRanges.length === 0, missingRanges, badLines: scan.badLines }
371
+ }
372
+
373
+ /**
374
+ * 用宿主事件重建 [fromSeq, throughSeq] 的缺失回合(§3.3:绝不假设日志完整)。
375
+ * 只补洞:与现有记录重叠的区间跳过,重复调用幂等。
376
+ */
377
+ export function rebuildRange(sessionId, fromSeq, throughSeq, events) {
378
+ const from = Number(fromSeq)
379
+ const through = Number(throughSeq)
380
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
381
+ return { ok: false, rebuilt: 0, reason: 'invalid range' }
382
+ }
383
+ const slice = (Array.isArray(events) ? events : []).filter((event) => {
384
+ const seq = Number(event?.seq)
385
+ return Number.isSafeInteger(seq) && seq >= from && seq <= through
386
+ })
387
+ const candidates = buildTurnRecords(slice).filter((record) => {
388
+ const [start, end] = safeSeqRange(record) || [NaN, NaN]
389
+ return start >= from && end <= through
390
+ })
391
+ const scan = scanTurnLog(sessionId)
392
+ const existing = scan.entries.map((entry) => safeSeqRange(entry.record)).filter(Boolean)
393
+ let rebuilt = 0
394
+ for (const record of candidates) {
395
+ const [start, end] = record.seq
396
+ if (existing.some(([s, e]) => start <= e && end >= s)) continue
397
+ if (recordTurn(sessionId, record)) rebuilt += 1
398
+ }
399
+ // 补洞追加的旧回合可能落在文件尾部,排回时间序,保证增量/尾部/裁剪口径一致。
400
+ if (rebuilt > 0) sortTurnLogBySeq(sessionId)
401
+ return { ok: true, rebuilt, requested: [from, through], records: candidates }
402
+ }
403
+
404
+ /**
405
+ * 取尾部整回合,总量(序列化后)≤ maxChars。回合不可分:最新一回合即使超预算
406
+ * 也整条返回(截了就不是完整证据);再往前按预算装。
407
+ */
408
+ export function tailSlice(sessionId, maxChars) {
409
+ const scan = scanTurnLog(sessionId)
410
+ const budget = Math.max(0, Number(maxChars) || 0)
411
+ const records = []
412
+ let used = 0
413
+ for (let i = scan.entries.length - 1; i >= 0; i--) {
414
+ const record = scan.entries[i].record
415
+ const range = record ? safeSeqRange(record) : null
416
+ if (!range) continue
417
+ const len = JSON.stringify(record).length
418
+ if (records.length > 0 && used + len > budget) break
419
+ records.unshift(record)
420
+ used += len
421
+ }
422
+ return { records, text: records.map((record) => JSON.stringify(record)).join('\n'), chars: used, badLines: scan.badLines }
423
+ }
424
+
425
+ /**
426
+ * 头部裁剪(§3.4):只裁 seqEnd ≤ lastSleepSeq 的**已结算**记录。未结算段超上限
427
+ * 就让文件暂超——裁进未结算区间等于把缺口推进需要重建的地方,绝不这么干。
428
+ * 坏行 seq 未知、无法证明已结算,同样保留。
429
+ */
430
+ export function pruneHead(sessionId, keepChars = TURNLOG_KEEP_CHARS, lastSleepSeq = null) {
431
+ const scan = scanTurnLog(sessionId)
432
+ const charsOf = (entry) => entry.raw.length + 1
433
+ const total = scan.entries.reduce((sum, entry) => sum + charsOf(entry), 0)
434
+ const budget = Number(keepChars) > 0 ? Number(keepChars) : TURNLOG_KEEP_CHARS
435
+ const settledThrough = Number.isSafeInteger(Number(lastSleepSeq)) ? Number(lastSleepSeq) : null
436
+ if (scan.unreadable || total <= budget || settledThrough === null) {
437
+ // 读失败绝不重写;没超预算不用动;没有结算游标时整份日志都是未结算段,暂超就暂超。
438
+ return { pruned: 0, charsBefore: total, charsAfter: total, unreadable: scan.unreadable }
439
+ }
440
+ const keep = [...scan.entries]
441
+ let keptTotal = total
442
+ let pruned = 0
443
+ while (keep.length > 0 && keptTotal > budget) {
444
+ const range = keep[0].record ? safeSeqRange(keep[0].record) : null
445
+ if (!range || range[1] > settledThrough) break // 未结算/坏行:到此为止
446
+ keptTotal -= charsOf(keep[0])
447
+ keep.shift()
448
+ pruned += 1
449
+ }
450
+ if (pruned === 0) return { pruned: 0, charsBefore: total, charsAfter: total }
451
+ try {
452
+ rewriteTurnLog(scan.file, keep.map((entry) => entry.raw))
453
+ } catch (error) {
454
+ warn(`turn-log head prune failed for ${logFileName(sessionId)}: ${error?.message || error}`)
455
+ return { pruned: 0, charsBefore: total, charsAfter: total, error: String(error?.message || error) }
456
+ }
457
+ const charsAfter = keep.reduce((sum, entry) => sum + charsOf(entry), 0)
458
+ return { pruned, charsBefore: total, charsAfter }
459
+ }
460
+
461
+ /**
462
+ * 休眠 GC(§3.4):日志无未结算增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天
463
+ * 无活动 → 删文件。缓存级操作;复活后交接尾部/增量走重建路径自动补。
464
+ * 两个条件都满足才删:有未结算增量(整理没做完)的日志是增量来源,保留。
465
+ */
466
+ export function gcTurnLogs(bindings, { now = Date.now(), olderThanDays = TURNLOG_GC_DAYS, dryRun = false } = {}) {
467
+ const deleted = []
468
+ const kept = []
469
+ const days = Number(olderThanDays) > 0 ? Number(olderThanDays) : TURNLOG_GC_DAYS
470
+ for (const binding of Array.isArray(bindings) ? bindings : []) {
471
+ const sessionId = binding?.sessionId
472
+ if (!sessionId) continue
473
+ let stat = null
474
+ try { stat = fs.statSync(turnLogPath(sessionId)) } catch { continue } // 没有日志,无事可做
475
+ const lastTurnAt = Date.parse(binding.lastTurnAt || '') || 0
476
+ if (!(lastTurnAt > 0) || now - lastTurnAt < days * 86_400_000) {
477
+ kept.push({ sessionId, reason: 'recent-activity', lastTurnAt: binding.lastTurnAt || null })
478
+ continue
479
+ }
480
+ const lastSleepSeq = Number(binding.lastSleepSeq)
481
+ if (!Number.isSafeInteger(lastSleepSeq) || lastSleepSeq < 0) {
482
+ kept.push({ sessionId, reason: 'never-settled', size: stat.size })
483
+ continue
484
+ }
485
+ const scan = scanTurnLog(sessionId)
486
+ if (scan.unreadable) {
487
+ kept.push({ sessionId, reason: 'unreadable' })
488
+ continue
489
+ }
490
+ let maxSeqEnd = -1
491
+ for (const entry of scan.entries) {
492
+ const range = entry.record ? safeSeqRange(entry.record) : null
493
+ if (range && range[1] > maxSeqEnd) maxSeqEnd = range[1]
494
+ }
495
+ if (maxSeqEnd > lastSleepSeq) {
496
+ kept.push({ sessionId, reason: 'unsettled-increment', maxSeqEnd, lastSleepSeq })
497
+ continue
498
+ }
499
+ if (dryRun) {
500
+ deleted.push(sessionId)
501
+ continue
502
+ }
503
+ try {
504
+ fs.rmSync(scan.file, { force: true })
505
+ deleted.push(sessionId)
506
+ } catch (error) {
507
+ kept.push({ sessionId, reason: `delete-failed: ${error?.code || error}` })
508
+ }
509
+ }
510
+ return { deleted, kept }
511
+ }
512
+
513
+ export function deleteTurnLog(sessionId) {
514
+ try {
515
+ const file = turnLogPath(sessionId)
516
+ fs.rmSync(file, { force: true })
517
+ return { ok: true, file }
518
+ } catch (error) {
519
+ warn(`turn-log delete failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
520
+ return { ok: false, error: String(error?.message || error) }
521
+ }
522
+ }