dsh-metabolism 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/engine.js CHANGED
@@ -13,9 +13,12 @@
13
13
  * @module dsh-metabolism/engine
14
14
  */
15
15
  import { randomUUID } from 'node:crypto'
16
- import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'
16
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
17
17
  import { homedir } from 'node:os'
18
18
  import { dirname, join } from 'node:path'
19
+ import { writeL1 } from './骨架.js'
20
+ import { renderSummaryBlock, estimateTokens } from './摘要块.js'
21
+ import { appendTimeline, hasTimelineFor, readTimeline } from './时间线.js'
19
22
 
20
23
  /** 本机覆盖:插件目录里的 本地配置.json(不进包,发布版没有这个文件)。 */
21
24
  function localOverrides() {
@@ -43,24 +46,311 @@ const STOCK_COMMAND = '@deepseek-ai/dsh-command-compact'
43
46
  const GATE_SERVICE = 'metabolismCompactionGate'
44
47
  const CHECKPOINT_PREAMBLE = 'This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.'
45
48
 
46
- const SUMMARY_SYSTEM = `你在给一段被压缩掉的对话写「归档标签」。看下面这段原文,写出两样东西:
49
+ const SUMMARY_SYSTEM = `你在给一段被压缩掉的对话写「归档卡」。看下面这段原文,写出这几样东西:
47
50
 
48
- 【短】不超过四十个字,说清这段在聊什么。这是以后放回上下文里的那一行,写给人看的,不是给机器看的。
49
- 【长】四五行,每行一句:聊了什么、得到什么结论、踩了什么坑、还欠什么。
51
+ 【短】不超过四十个字,说清这段在聊什么。这是以后放回上下文里的那一行,写给人看的。
52
+ 【在干什么】一句话,说清这段在处理哪件事。
53
+ 【仍然有效的要求】还有哪些约束、规矩、老大交代过的话仍然算数。一行一条,没有就写「无」。
54
+ 【已经做到】已经做完、已经确认的事。一行一条,可以加「(未完成)」。
55
+ 【下一步】一句话,接下来该做什么。
56
+ 【关键词】三到六个名词,用逗号隔开,以后靠它检索。
57
+ 【原话】直接从原文摘三到六句最重要的话,一字不改。
50
58
 
51
59
  规矩:
52
- - 只写这段里真有的,不补不猜。
60
+ - 只写这段里真有的,不补不猜;拿不准就写「不清楚」。
61
+ - 每一块都要有内容,不许留空;真没有就写「无」。
62
+ - 记得把「下一步」写出来,这是以后接手的抓手。
53
63
  - 不写「用户」「助手」这种称呼,直接写事。
64
+ - 原话那几条必须逐字照抄原文,不许改写、不许润色。
54
65
  - 不写抱歉、不写总结陈词、不写「以上」。
55
66
  - 短的那行不要句号结尾。`
56
67
 
57
68
  export const name = 'metabolism-engine'
58
69
  export const inject = ['tokenMeter', 'llm', 'tools']
70
+ export { tailBalanced, surfaceBalance }
59
71
 
60
72
  /** 「同一个判断」的节流表:签名 → 上次记录时间。 */
61
73
  const lastPlan = new Map()
62
74
  /** 每个会话只记一次窗口数字,方便核对。 */
63
75
  const seenWindow = new Set()
76
+ /**
77
+ * 手动压缩的排队表:会话 id → 想压的 seq 区间。
78
+ *
79
+ * 模型自己调 metabolism_compact 的时候,它这条调用刚发出去、结果还没回来;
80
+ * 此刻往会话里追加 checkpoint,就会插在「调用」和「结果」中间,DeepSeek 下次
81
+ * 请求直接报 “tool calls need immediate results”。所以先记下来,等这一次的
82
+ * 工具结果落地、下一轮 pre-step 再真正写。
83
+ */
84
+ const pendingCompact = new Map()
85
+
86
+ /**
87
+ * 摘要块 · 回路里写(2026-11-20 老大拍定「一步到位,走 1」)
88
+ *
89
+ * 到硬线时不再直接压:先往上下文里发一条预告,把候选区间和写法要求说清楚,
90
+ * 我在下一轮用 metabolism_summarize 把摘要块交回来,引擎再执行替换。
91
+ * 等不到(超时,或者水位已经压过头发),就退回模型/抽取兜底,绝不停在那儿。
92
+ */
93
+ const SUMMARY_WAIT_MS = 5 * 60 * 1000
94
+ const SUMMARY_FORCE_EXTRA_TOKENS = 30000
95
+
96
+ /** 代谢日志目录:跟开关文件同目录(可配置),没配才退回本机固定路径。 */
97
+ function summaryDir(options) {
98
+ if (typeof options?.switchesFile === 'string' && options.switchesFile.length > 0) return dirname(options.switchesFile)
99
+ return 'D:\\deepseek工作区\\记忆\\代谢日志'
100
+ }
101
+ function summaryStateFile(options) { return join(summaryDir(options), '待压摘要.json') }
102
+ function summaryRegistryFile(options) { return join(summaryDir(options), '摘要块注册.json') }
103
+
104
+ function readSummaryState(options) {
105
+ try {
106
+ const parsed = JSON.parse(readFileSync(summaryStateFile(options), 'utf8'))
107
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
108
+ } catch {
109
+ return null
110
+ }
111
+ }
112
+
113
+ function writeSummaryState(state, options) {
114
+ try {
115
+ mkdirSync(summaryDir(options), { recursive: true })
116
+ writeFileSync(summaryStateFile(options), JSON.stringify(state, null, 2), 'utf8')
117
+ } catch {}
118
+ }
119
+
120
+ function clearSummaryState(options) {
121
+ writeSummaryState({}, options)
122
+ }
123
+
124
+ /** 摘要块登记册:每次压完登记一块,折叠时按它算年龄和总量。 */
125
+ const SUMMARY_BUDGET_TOKENS = 65000
126
+ const SUMMARY_LAYER_A_DAYS = 7
127
+ const SUMMARY_PROTECT_MS = 24 * 60 * 60 * 1000
128
+
129
+ function readSummaryRegistry(options) {
130
+ try {
131
+ const parsed = JSON.parse(readFileSync(summaryRegistryFile(options), 'utf8'))
132
+ return Array.isArray(parsed) ? parsed : []
133
+ } catch {
134
+ return []
135
+ }
136
+ }
137
+
138
+ function writeSummaryRegistry(rows, options) {
139
+ try {
140
+ mkdirSync(summaryDir(options), { recursive: true })
141
+ writeFileSync(summaryRegistryFile(options), JSON.stringify(rows, null, 2), 'utf8')
142
+ } catch {}
143
+ }
144
+
145
+ /** 从一条会话事件里抠出文本正文;没有就 null。 */
146
+ function contentTextOf(event) {
147
+ const blocks = event?.data?.content ?? event?.data?.message?.content
148
+ if (!Array.isArray(blocks)) return null
149
+ const text = blocks.filter((block) => block?.type === 'text').map((block) => String(block.text ?? '')).join('\n')
150
+ return text.length > 0 ? text : null
151
+ }
152
+
153
+ /** 我自己写的摘要块没有 card,从这里派生一张骨架卡(只补下一步/未决 + 摘原话)。 */
154
+ function deriveCard(text) {
155
+ const lines = String(text).split('\n').map((line) => line.trim()).filter((line) => line.length > 0)
156
+ const title = (lines[0] ?? '').slice(0, 24)
157
+ let next = ''
158
+ const quotes = []
159
+ for (const line of lines) {
160
+ const m = line.match(/^(?:下一步|还没做完|还欠|未决)[::]\s*(.+)$/)
161
+ if (m !== null) { next = String(m[1]).trim(); continue }
162
+ const q = line.match(/^[>「『“"](.+)[」』”"]$/)
163
+ if (q !== null && line.length < 80) quotes.push(String(q[1]).trim())
164
+ }
165
+ const doing = lines.slice(0, 6).join(' ')
166
+ return { doing, requirements: [], done: [], next, quotes: quotes.slice(0, 3), keywords: [], title }
167
+ }
168
+
169
+ /** 四级降级第 3 级:没模型时,从被压段里按规则抽一个最小可读块(纯代码,永远可用)。 */
170
+ function deterministicSummary(session, range) {
171
+ let meLine = ''
172
+ let userLine = ''
173
+ for (let index = range.startIdx; index <= range.endIdx; index += 1) {
174
+ const event = session.eventAt(session.surface.nodes[index])
175
+ if (event === undefined) continue
176
+ const text = contentTextOf(event)
177
+ if (text === null || text.length < 8) continue
178
+ if (event.type === 'assistant/message' && meLine === '') meLine = text.slice(0, 90)
179
+ if (event.type === 'user/message' && userLine === '' && !text.startsWith('<') && !text.startsWith('【') && !text.startsWith('Time sampled')) userLine = text.slice(0, 60)
180
+ if (meLine !== '' && userLine !== '') break
181
+ }
182
+ return [
183
+ '【这段做了什么】',
184
+ meLine !== '' ? meLine : '(没摘到)',
185
+ '',
186
+ '【我们之间】',
187
+ userLine !== '' ? userLine : '(没摘到)',
188
+ ].join('\n')
189
+ }
190
+
191
+ /**
192
+ * 折叠摘要块(2026-11-20,P2)。
193
+ *
194
+ * 先把折叠做成只读报告(foldDryRun 默认 true):在日志里写清楚"该折哪几块、为什么",
195
+ * 不动会话。等 P4 在影子会话里验证过 surface 手术,再把 dryRun 关掉,真动手。
196
+ */
197
+ /** 从摘要正文取第一句,折叠索引条目用(一句话定位,不多不少)。 */
198
+ function firstSentence(text) {
199
+ const t = String(text ?? '').trim()
200
+ if (t === '') return '(无内容)'
201
+ const m = t.match(/^.*?[。!?!?\n]/)
202
+ const one = m ? m[0].trim() : t.slice(0, 40)
203
+ return one.length > 60 ? `${one.slice(0, 60)}…` : one
204
+ }
205
+
206
+ function foldSummaries(ctx, options, session, log) {
207
+ if (options.foldEnabled !== true) return
208
+ const registry = readSummaryRegistry(options)
209
+ const nodes = session.surface.nodes
210
+ // 只认还在表层里的块:按归档文件名(compactionId)对回登记册
211
+ const blocks = []
212
+ const byCid = new Map()
213
+ for (const row of registry) byCid.set(row.compactionId, row)
214
+ for (let i = 0; i < nodes.length; i += 1) {
215
+ const text = contentTextOf(session.eventAt(nodes[i]))
216
+ if (text === null || !text.includes('<summary-block')) continue
217
+ const am = text.match(/归档:([A-Za-z0-9-]+\.jsonl)/)
218
+ const cid = String(am?.[1] ?? '').replace(/\.jsonl$/, '')
219
+ if (cid === '') continue
220
+ const row = byCid.get(cid)
221
+ if (row === undefined) continue
222
+ blocks.push({ index: i, seq: nodes[i], cid, at: Number(row.at) || 0, tokens: Number(row.tokens) || estimateTokens(row.body ?? ''), body: String(row.body ?? ''), seqFrom: row.seqFrom, seqTo: row.seqTo, mode: String(row.mode ?? 'passive') })
223
+ }
224
+ if (blocks.length === 0) {
225
+ if (registry.length > 0) log('info', `折叠:登记册 ${registry.length} 块,但表层没扫到 <summary-block>,跳过`)
226
+ return
227
+ }
228
+
229
+ const now = Date.now()
230
+ const total = blocks.reduce((sum, block) => sum + block.tokens, 0)
231
+ const oldestFirst = [...blocks].sort((a, b) => {
232
+ const av = a.mode === 'active' ? 0 : 1
233
+ const bv = b.mode === 'active' ? 0 : 1
234
+ if (av !== bv) return av - bv
235
+ return a.at - b.at
236
+ })
237
+ const budget = Number(options.summaryBudgetTokens ?? SUMMARY_BUDGET_TOKENS) || SUMMARY_BUDGET_TOKENS
238
+
239
+ // 1) 到期:超过 7 天的层 a 块
240
+ const expired = oldestFirst.filter((block) => now - block.at > SUMMARY_LAYER_A_DAYS * 86400000)
241
+ // 2) 总量:超预算,按最老补齐
242
+ let targets = [...expired]
243
+ if (total > budget) {
244
+ let kept = 0
245
+ for (const block of oldestFirst) {
246
+ if (targets.includes(block)) continue
247
+ if (total - kept <= budget) break
248
+ kept += block.tokens
249
+ targets.push(block)
250
+ }
251
+ }
252
+ if (targets.length === 0) {
253
+ log('info', `摘要块 ${blocks.length} 块 / ${total} tokens,没到折叠线(预算 ${budget})`)
254
+ return
255
+ }
256
+ // 3) 保护:24 小时内的不折;若全员保护又必须折,破例折最老一块
257
+ const unprotectable = targets.filter((block) => now - block.at < SUMMARY_PROTECT_MS)
258
+ let final = targets.filter((block) => now - block.at >= SUMMARY_PROTECT_MS)
259
+ if (final.length === 0 && unprotectable.length > 0) {
260
+ final = [oldestFirst[0]]
261
+ log('warn', `摘要块全员在保护期内,破例折最老一块(${final[0].cid})`)
262
+ }
263
+ if (final.length === 0) return
264
+
265
+ const label = final.map((block) => block.cid.slice(-6)).join(',')
266
+ const foldNow = options.foldDryRun === false
267
+ if (!foldNow) {
268
+ log('info', `[演练] 该折 ${final.length} 块(${label}),登记 ${blocks.length} 块 / ${total} tokens,预算 ${budget}`)
269
+ return
270
+ }
271
+
272
+ // —— 真折:按相邻块分组,一组折成一条索引。中间夹着原文就分开折,绝不吞原文 ——
273
+ const sorted = [...final].sort((a, b) => a.index - b.index)
274
+ const groups = []
275
+ let group = [sorted[0]]
276
+ for (let i = 1; i < sorted.length; i += 1) {
277
+ if (sorted[i].index === group[group.length - 1].index + 1) {
278
+ group.push(sorted[i])
279
+ } else {
280
+ groups.push(group)
281
+ group = [sorted[i]]
282
+ }
283
+ }
284
+ groups.push(group)
285
+
286
+ const foldedRows = []
287
+ const foldedCids = []
288
+ // 从最高 index 往下折:先折后面的,低 index 不受后面删除节点的影响
289
+ const ordered = groups.sort((a, b) => b[0].index - a[0].index)
290
+ for (const grp of ordered) {
291
+ const startIdx = grp[0].index
292
+ const endIdx = grp[grp.length - 1].index
293
+ const fromSeq = nodes[startIdx]
294
+ const toSeq = nodes[endIdx]
295
+ const shadowed = session.surface.nodes.slice(startIdx, endIdx + 1)
296
+ const indexText = grp.map((block) => {
297
+ const one = firstSentence(block.body)
298
+ return `· ${one}〔${block.cid}.jsonl · seq ${block.seqFrom}–${block.seqTo}〕`
299
+ }).join('\n')
300
+ const folded = {
301
+ compactionId: `idx-${now.toString(36)}-${randomUUID().slice(0, 4)}`,
302
+ seqFrom: fromSeq,
303
+ seqTo: toSeq,
304
+ at: now,
305
+ tokens: estimateTokens(indexText),
306
+ layer: 'index',
307
+ body: indexText,
308
+ }
309
+ log('info', `折叠 ${grp.length} 块为一条索引:seq ${fromSeq}–${toSeq},覆盖 ${shadowed.length} 个表层节点`)
310
+ session.append('user/message', {
311
+ id: randomUUID(),
312
+ role: 'user',
313
+ content: [{ type: 'text', text: `<summary-block seq="${fromSeq}–${toSeq}">\n${indexText}\n</summary-block>` }],
314
+ source: { kind: 'summary-fold', folded: grp.map((block) => block.cid) },
315
+ }, {
316
+ surfaceOp: { op: 'replace', startSeq: fromSeq, endSeq: toSeq },
317
+ sourceEventSeqs: [...shadowed],
318
+ })
319
+ foldedRows.push(folded)
320
+ foldedCids.push(...grp.map((block) => block.cid))
321
+ }
322
+
323
+ const remaining = registry.filter((row) => !foldedCids.includes(row.compactionId))
324
+ remaining.push(...foldedRows)
325
+ writeSummaryRegistry(remaining, options)
326
+
327
+ // 折叠顺手补当天时间线(已有就跳过)
328
+ const dayMin = new Date(Math.min(...final.map((block) => block.at))).toISOString().slice(0, 10)
329
+ const dayMax = new Date(Math.max(...final.map((block) => block.at))).toISOString().slice(0, 10)
330
+ if (!hasTimelineFor(dayMax, options.archiveRoot)) {
331
+ appendTimeline({
332
+ date: dayMax,
333
+ from: dayMin,
334
+ to: dayMax,
335
+ title: `折叠:${final.length} 块 → ${foldedRows.length} 块`,
336
+ what: foldedRows.map((row) => row.body).join('\n').slice(0, 300),
337
+ we: '',
338
+ feel: '',
339
+ topics: [],
340
+ sources: foldedCids.map((cid) => `${cid}.jsonl`),
341
+ spanFrom: Math.min(...foldedRows.map((row) => row.seqFrom)),
342
+ spanTo: Math.max(...foldedRows.map((row) => row.seqTo)),
343
+ made: '折叠自动',
344
+ }, options.archiveRoot)
345
+ }
346
+ log('info', `折完了:${final.length} 块 → ${foldedRows.length} 条索引,登记册剩 ${remaining.length} 条`)
347
+ }
348
+
349
+ /** 摘要块给上下文用的那一行:短、能扫。 */
350
+ function summaryShortLine(text) {
351
+ const first = String(text).split(/[\n。!?]/).map((part) => part.trim()).find((part) => part.length > 0) ?? ''
352
+ return first.length > 60 ? `${first.slice(0, 60)}…` : first
353
+ }
64
354
 
65
355
  export function resolveEngineConfig(config) {
66
356
  const source = config !== null && typeof config === 'object' ? config : {}
@@ -76,6 +366,7 @@ export function resolveEngineConfig(config) {
76
366
  }
77
367
  return {
78
368
  takeover: source.takeover === true,
369
+ enabled: source.enabled !== false,
79
370
  dryRun: source.dryRun !== false,
80
371
  thresholdRatio: number(source.thresholdRatio, 0.8),
81
372
  retainRatio: number(source.retainRatio, 0.12),
@@ -85,10 +376,16 @@ export function resolveEngineConfig(config) {
85
376
  thresholdTokens: number(source.thresholdTokens, 260000),
86
377
  /** 压完之后保留多少 token 的最近内容。0 表示退回按窗口比例算。 */
87
378
  retainTokens: number(source.retainTokens, 130000),
379
+ /** 对话最少留多少 token(切不动的工具定义不算在内)。老大定的:8 万,别让他断片。 */
380
+ minKeepTokens: number(source.minKeepTokens, 80000),
381
+ /** 时间闸:最近这么多小时里的内容一律不切(老大要的「一天以内不忘事」)。0 表示不设。 */
382
+ keepRecentHours: number(source.keepRecentHours, 24),
88
383
  /** 输出预留封顶:最多从窗口里扣掉这么多给回答,别让 256k 的默认值把窗口吃光。 */
89
384
  maxReserveTokens: number(source.maxReserveTokens, 65536),
90
385
  /** 归档时让模型写两行摘要;关掉就退回只有指针。 */
91
386
  summaryEnabled: source.summaryEnabled !== false,
387
+ /** 三级记忆・骨架:压完顺手写一张说明卡(记忆\骨架\L1)。关掉就只走老的归档。 */
388
+ skeletonEnabled: source.skeletonEnabled !== false,
92
389
  /** 摘要用哪个模型;不填就跟着当前会话走的模型。 */
93
390
  summaryProvider: typeof source.summaryProvider === 'string' ? source.summaryProvider : '',
94
391
  summaryModel: typeof source.summaryModel === 'string' ? source.summaryModel : '',
@@ -114,16 +411,30 @@ export function resolveEngineConfig(config) {
114
411
  /** 读运行时开关文件;读不到就当没写。 */
115
412
  function readSwitches(file) {
116
413
  try {
117
- const parsed = JSON.parse(readFileSync(file, 'utf8'))
414
+ // 记事本/Out-File/PowerShell 写的 JSON 常带 BOM,JSON.parse 会直接抛,
415
+ // 抛了就等于开关全线失效(2026-11-19 踩过:takeover 被悄悄读成 false)。
416
+ const raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
417
+ const parsed = JSON.parse(raw)
118
418
  if (parsed === null || typeof parsed !== 'object') return {}
119
419
  const value = {}
120
420
  if (typeof parsed.takeover === 'boolean') value.takeover = parsed.takeover
421
+ if (typeof parsed.enabled === 'boolean') value.enabled = parsed.enabled
121
422
  if (typeof parsed.dryRun === 'boolean') value.dryRun = parsed.dryRun
122
423
  if (Number.isFinite(Number(parsed.thresholdRatio))) value.thresholdRatio = Number(parsed.thresholdRatio)
123
424
  if (Number.isFinite(Number(parsed.retainRatio))) value.retainRatio = Number(parsed.retainRatio)
124
425
  if (Number.isFinite(Number(parsed.thresholdTokens))) value.thresholdTokens = Number(parsed.thresholdTokens)
125
426
  if (Number.isFinite(Number(parsed.retainTokens))) value.retainTokens = Number(parsed.retainTokens)
427
+ if (Number.isFinite(Number(parsed.minKeepTokens))) value.minKeepTokens = Number(parsed.minKeepTokens)
428
+ if (Number.isFinite(Number(parsed.keepRecentHours))) value.keepRecentHours = Number(parsed.keepRecentHours)
126
429
  if (Number.isFinite(Number(parsed.softTokens))) value.softTokens = Number(parsed.softTokens)
430
+ // 摘要块(2026-11-20):启用与否、等我写多久、水位压过多少就兜底
431
+ if (typeof parsed.summaryBlock === 'boolean') value.summaryBlock = parsed.summaryBlock
432
+ if (Number.isFinite(Number(parsed.summaryWaitMs))) value.summaryWaitMs = Number(parsed.summaryWaitMs)
433
+ if (Number.isFinite(Number(parsed.summaryForceExtraTokens))) value.summaryForceExtraTokens = Number(parsed.summaryForceExtraTokens)
434
+ // 折叠(P2):开不开、只演练还是真折、总量预算
435
+ if (typeof parsed.foldEnabled === 'boolean') value.foldEnabled = parsed.foldEnabled
436
+ if (typeof parsed.foldDryRun === 'boolean') value.foldDryRun = parsed.foldDryRun
437
+ if (Number.isFinite(Number(parsed.summaryBudgetTokens))) value.summaryBudgetTokens = Number(parsed.summaryBudgetTokens)
127
438
  return value
128
439
  } catch {
129
440
  return {}
@@ -168,7 +479,9 @@ export function apply(ctx, config) {
168
479
  if (typeof ctx.on === 'function') {
169
480
  ctx.on('internal/config', function (_raw, next) {
170
481
  const resolved = next()
171
- if (mode().takeover !== true) return resolved
482
+ const m = mode()
483
+ // 禁用原装:接管时,或者我们自己全关(enabled=false)时,都不许原装再压
484
+ if (m.takeover !== true && m.enabled !== false) return resolved
172
485
  const config = resolved ?? {}
173
486
  if (!Array.isArray(config.plugins)) return resolved
174
487
  if (countStock(config.plugins) === 0) return resolved
@@ -201,6 +514,122 @@ export function apply(ctx, config) {
201
514
  } catch (error) {
202
515
  log('warn', `挂 metabolism_compact 失败:${error?.message ?? error}`)
203
516
  }
517
+ try {
518
+ ctx.tools.register(summarizeTool(ctx, options, log))
519
+ } catch (error) {
520
+ log('warn', `挂 metabolism_summarize 失败:${error?.message ?? error}`)
521
+ }
522
+ try {
523
+ ctx.tools.register(timelineTool(ctx, options, log))
524
+ } catch (error) {
525
+ log('warn', `挂 metabolism_timeline 失败:${error?.message ?? error}`)
526
+ }
527
+ }
528
+ }
529
+
530
+ /**
531
+ * 摘要块工具:把「即将被压掉的那一段」写成一块摘要,交给引擎执行替换。
532
+ *
533
+ * 写的时候按规矩来:连贯叙述,不列条目——发生了什么、为什么、决定了什么,带一句
534
+ * 我们之间的话(原话摘)和当时什么味,结尾一行「下一步」。用「你说/我说」。
535
+ */
536
+ function summarizeTool(ctx, options, log) {
537
+ return {
538
+ name: 'metabolism_summarize',
539
+ description: '给即将被压掉的那一段写摘要块(500 字左右,叙述式)。不是列条目,是讲故事——连贯地把这段发生了什么、为什么、决定了什么过一遍,带一句我们之间的话(原话摘)和当时什么味,结尾单独留一行「下一步:xxx」。写完引擎就把那段原文换成这块摘要。',
540
+ parameters: {
541
+ type: 'object',
542
+ properties: {
543
+ text: { type: 'string', description: '摘要块正文,500 字左右,叙述式第一人称:先连贯讲这段发生了什么(做了什么、为什么、决定了什么),带一句我们之间的话和当时什么味;结尾一行「下一步:xxx」。' },
544
+ mode: { type: 'string', description: '这段是「经历」还是「事实」。passive=经历(我们之间发生了什么、有味道,常驻不折);active=事实/决定/技术操作(可折成索引按需取)。默认 passive。', enum: ['passive', 'active'] },
545
+ fromSeq: { type: 'integer', description: '可选:要覆盖的起始 seq;不填就用预告里那段。' },
546
+ toSeq: { type: 'integer', description: '可选:要覆盖的结束 seq。' },
547
+ },
548
+ required: ['text'],
549
+ additionalProperties: false,
550
+ },
551
+ output: {
552
+ schema: {
553
+ type: 'object',
554
+ properties: {
555
+ text: { type: 'string', description: '结果说明。' },
556
+ ok: { type: 'boolean', description: '是否收下。' },
557
+ },
558
+ required: ['text', 'ok'],
559
+ additionalProperties: false,
560
+ },
561
+ render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
562
+ },
563
+ async execute(args, exec) {
564
+ const session = sessionOf(exec)
565
+ const body = String(args?.text ?? '').trim()
566
+ if (body.length < 80) {
567
+ return { ok: false, text: `太短了(${body.length} 字)。摘要块至少要有做什么、为什么、决定、未决、一句话和什么味。` }
568
+ }
569
+ const state = readSummaryState(options) ?? {}
570
+ const sameSession = session === undefined || String(state.sessionId ?? '') === String(session.id ?? '')
571
+ writeSummaryState({
572
+ ...(sameSession ? state : {}),
573
+ sessionId: session?.id ?? state.sessionId ?? '?',
574
+ fromSeq: Number(args?.fromSeq ?? (sameSession ? state.fromSeq : 0)) || 0,
575
+ toSeq: Number(args?.toSeq ?? (sameSession ? state.toSeq : 0)) || 0,
576
+ text: body,
577
+ mode: String(args?.mode ?? 'passive') === 'active' ? 'active' : 'passive',
578
+ noticeAt: sameSession ? (state.noticeAt ?? Date.now()) : Date.now(),
579
+ writtenAt: Date.now(),
580
+ }, options)
581
+ log('info', `收到我写的摘要块:${body.length} 字`)
582
+ return { ok: true, text: `收下了(${body.length} 字)。下一次轮开始前就用它替换掉那一段原文,不需要再调工具。` }
583
+ },
584
+ }
585
+ }
586
+
587
+ /**
588
+ * 时间线工具:list 列最近条目(只给日期加标题),show 按日期读一条完整。
589
+ * 开窗时的自动读三条走 浮现.js,这个工具是「问起旧事」时用的口子。
590
+ */
591
+ function timelineTool(ctx, options, log) {
592
+ return {
593
+ name: 'metabolism_timeline',
594
+ description: '时间线:list 列最近条目(默认 3 条,只给日期和标题);show 按日期读一条完整(发生了什么、我们之间、当时什么味)。',
595
+ parameters: {
596
+ type: 'object',
597
+ properties: {
598
+ action: { type: 'string', description: 'list(列)或 show(读一条)。' },
599
+ date: { type: 'string', description: 'show 时用:哪天,形如 2026-11-19。' },
600
+ limit: { type: 'integer', description: 'list 时用:返回几条,默认 3。' },
601
+ },
602
+ required: ['action'],
603
+ additionalProperties: false,
604
+ },
605
+ output: {
606
+ schema: {
607
+ type: 'object',
608
+ properties: {
609
+ text: { type: 'string', description: '结果。' },
610
+ ok: { type: 'boolean', description: '是否读到。' },
611
+ },
612
+ required: ['text', 'ok'],
613
+ additionalProperties: false,
614
+ },
615
+ render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
616
+ },
617
+ async execute(args) {
618
+ const entries = readTimeline(options.archiveRoot)
619
+ const action = String(args?.action ?? 'list').toLowerCase()
620
+ if (action === 'show') {
621
+ const date = String(args?.date ?? '').trim()
622
+ const hit = entries.filter((entry) => String(entry.date ?? '') === date)
623
+ if (hit.length === 0) {
624
+ return { ok: false, text: `时间线里没有 ${date}(共 ${entries.length} 条,最近一条 ${entries[0]?.date ?? '无'})` }
625
+ }
626
+ return { ok: true, text: hit.map((entry) => JSON.stringify(entry, null, 2)).join('\n\n') }
627
+ }
628
+ const limit = Number(args?.limit ?? 3) || 3
629
+ const recent = entries.slice(0, limit)
630
+ if (recent.length === 0) return { ok: true, text: '时间线还是空的。' }
631
+ return { ok: true, text: recent.map((entry) => `${entry.date ?? '?'} ${entry.title ?? ''}`.trim()).join('\n') }
632
+ },
204
633
  }
205
634
  }
206
635
 
@@ -242,16 +671,19 @@ function buildCatalog(ctx, session) {
242
671
  }
243
672
  if (cursor !== null) lines.push(cursor)
244
673
  const total = Number(measurement?.totalTokens) || 0
674
+ // 段的起止都对齐到「配对闭合」的位置,别让模型拿到会拆开调用的区间
675
+ const balance = surfaceBalance(session)
245
676
  const body = lines.map((seg, index) => {
246
- // 收口往前挪:切点后面要是工具结果,就会把一对调用/结果拆开
677
+ let from = seg.from
678
+ while (from > 0 && Number(balance.before[from] ?? 0) !== 0) from -= 1
247
679
  let to = seg.to
248
- while (to > seg.from && isToolResultEvent(session, surface[to + 1])) to -= 1
249
- const fromSeq = surface[seg.from]
680
+ while (to > from && Number(balance.after[to] ?? -1) !== 0) to -= 1
681
+ const fromSeq = surface[from]
250
682
  const toSeq = surface[to]
251
683
  // 段里可能起头是工具调用、没有文字,往后找第一条有字的
252
684
  let head = seg.head
253
685
  if (head === '(没有文字)') {
254
- for (let at = seg.from; at <= to && at < seg.from + 8; at += 1) {
686
+ for (let at = from; at <= to && at < from + 8; at += 1) {
255
687
  const event = session.eventAt(surface[at])
256
688
  const blocks = event?.data?.content ?? event?.data?.message?.content
257
689
  if (!Array.isArray(blocks)) continue
@@ -263,7 +695,7 @@ function buildCatalog(ctx, session) {
263
695
  }
264
696
  }
265
697
  const span = fromSeq === toSeq ? `seq ${fromSeq}` : `seq ${fromSeq}…${toSeq}`
266
- return `${index + 1}. ${seg.at} 起 · 表层第 ${seg.from}–${to} 个节点 · ${span} · 约 ${Math.round(seg.tokens)} tokens · ${seg.count} 条 · 开头:${head}`
698
+ return `${index + 1}. ${seg.at} 起 · 表层第 ${from}–${to} 个节点 · ${span} · 约 ${Math.round(seg.tokens)} tokens · ${seg.count} 条 · 开头:${head}`
267
699
  })
268
700
  return { total, count: lines.length, text: body.join('\n') }
269
701
  }
@@ -272,7 +704,7 @@ function buildCatalog(ctx, session) {
272
704
  function compactTool(ctx, options, log) {
273
705
  return {
274
706
  name: 'metabolism_compact',
275
- description: '手动压缩:catalog 列出这段会话分成的若干段(时间、seq、token、开头),forget 把指定的一段原文收进茅房、换成一指针。不等到阈值,由你决定留哪段、忘哪段。',
707
+ description: '手动压缩:catalog 列出这段会话分成的若干段(时间、seq、token、开头),forget 指定压掉哪一段——摘要块开着时先发预告等我写摘要,写完下一轮压成摘要块;关着就直接压成指针。不等到阈值,由你决定留哪段、忘哪段。',
276
708
  parameters: {
277
709
  type: 'object',
278
710
  properties: {
@@ -316,9 +748,27 @@ function compactTool(ctx, options, log) {
316
748
  if (startIdx === 0) {
317
749
  return { ok: false, text: '系统提示那一条不能压。' }
318
750
  }
319
- if (isToolResultEvent(session, surface[endIdx + 1])) {
320
- return { ok: false, text: '切点后面紧跟着工具结果,会把一对调用和结果拆开。把 toSeq 往前挪一条。' }
751
+ // 两端都得落在「配对闭合」的位置:起点前悬着调用,说明这条调用的结果在区间里,
752
+ // 压完会剩一个没有结果的调用;终点后悬着调用,说明结果会被留在区间外。
753
+ const balance = surfaceBalance(session)
754
+ if (Number(balance.before[startIdx] ?? 0) !== 0) {
755
+ let moved = startIdx
756
+ while (moved > 1 && Number(balance.before[moved] ?? 0) !== 0) moved -= 1
757
+ return {
758
+ ok: false,
759
+ text: `起点 seq ${fromSeq} 落在一对「调用-结果」中间:它前面还有没回的调用,压下去会剩下孤立调用。把 fromSeq 往前挪到 seq ${surface[moved]}。`,
760
+ }
321
761
  }
762
+ if (Number(balance.after[endIdx] ?? -1) !== 0) {
763
+ let moved = endIdx
764
+ while (moved > startIdx && Number(balance.after[moved] ?? -1) !== 0) moved -= 1
765
+ return {
766
+ ok: false,
767
+ text: `终点 seq ${toSeq} 落在一对「调用-结果」中间:后面还有没回的调用。把 toSeq 往前挪到 seq ${surface[moved]}。`,
768
+ }
769
+ }
770
+ // 这一刻我正在执行这条工具:表层末尾悬着我自己的调用,直接 append 会把
771
+ // 「调用」和「结果」拆开,下一次请求就报 tool calls need immediate results。
322
772
  const meter = ctx.tokenMeter
323
773
  const header = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined
324
774
  const measurement = header === undefined ? meter.measure(session) : meter.measure(session, header)
@@ -327,9 +777,41 @@ function compactTool(ctx, options, log) {
327
777
  const node = measurement.nodes.find((item) => item.seq === surface[index])
328
778
  tokens += Number(node?.heuristicTokens ?? node?.tokens ?? 0)
329
779
  }
780
+
781
+ // 摘要块开着:跟到线自动压一样,先发预告等我手写摘要,不直接兜底(2026-11-21)
782
+ if (options.summaryBlock !== false) {
783
+ const sessionKey = String(session.id ?? '?')
784
+ const waitMs = Number(options.summaryWaitMs ?? SUMMARY_WAIT_MS) || SUMMARY_WAIT_MS
785
+ if (tailBalanced(session)) {
786
+ const notice = [
787
+ `【手动收段】准备压掉 seq ${fromSeq}–${toSeq}(约 ${tokens} tokens)。`,
788
+ '要我自己写摘要块的话,调 metabolism_summarize,写 500 字左右的叙述:连贯讲这段发生了什么、为什么、决定了什么,带一句我们之间的话(原话摘)和当时什么味,结尾留一行「下一步:xxx」。用「你说/我说」,不要第三人称。',
789
+ `不写也行,${Math.round(waitMs / 60000)} 分钟后我按抽取兜底压。`,
790
+ ].join('\n')
791
+ session.append('user/message', {
792
+ id: randomUUID(),
793
+ role: 'user',
794
+ content: [{ type: 'text', text: notice }],
795
+ source: { kind: 'summary-notice' },
796
+ }, { surfaceOp: 'append' })
797
+ writeSummaryState({ sessionId: sessionKey, fromSeq, toSeq, text: '', noticeAt: Date.now(), tokens }, options)
798
+ pendingCompact.set(sessionKey, { fromSeq, toSeq, queuedAt: Date.now(), wantNotice: false })
799
+ log('info', `手动收段发预告:seq ${fromSeq}–${toSeq},等我自己写`)
800
+ return { ok: true, text: `预告发好了,seq ${fromSeq}–${toSeq} 等你写摘要(调 metabolism_summarize)。写完下一轮就压。` }
801
+ }
802
+ // 尾巴没闭合(正在执行这条工具):先排队,下一轮再发预告
803
+ pendingCompact.set(sessionKey, { fromSeq, toSeq, queuedAt: Date.now(), wantNotice: true })
804
+ return { ok: true, text: `排好了:seq ${fromSeq}–${toSeq},下一轮先发预告等你写摘要,写完才压。` }
805
+ }
806
+
807
+ // 摘要块关着:老路,直接模型写/指针
808
+ if (!tailBalanced(session)) {
809
+ pendingCompact.set(String(session.id ?? '?'), { fromSeq, toSeq, queuedAt: Date.now(), wantNotice: false })
810
+ return { ok: true, text: `排好了:seq ${fromSeq}–${toSeq} 等这次工具结果落地、下一轮开始前再压。` }
811
+ }
330
812
  const range = { start: fromSeq, end: toSeq, startIdx, endIdx, tokens }
331
813
  const digest = options.summaryEnabled === false ? null : await summarizeWithModel(ctx, options, session, undefined, range, log)
332
- const result = writeCompaction(session, range, options, digest)
814
+ const result = writeCompaction(session, range, options, digest, log)
333
815
  log('info', `手动压:seq ${fromSeq}–${toSeq},${result.shadowedSeqs.length} 条,约 ${tokens} tokens`)
334
816
  return { ok: true, text: `压掉了,${result.shadowedSeqs.length} 条原文换成一条指针:${result.summary}` }
335
817
  },
@@ -357,20 +839,90 @@ function disableStock(rows) {
357
839
  })
358
840
  }
359
841
 
842
+ /**
843
+ * 探针(2026-11-19 临时加,查完可删):把引擎的账和真实用量并排打出来。
844
+ * 起因:界面显示压完剩 3 万,引擎报 9.8 万,差三倍;怀疑启发式估高了。
845
+ * 一分钟或涨了 5000 tokens 才记一次,免得刷屏。
846
+ */
847
+ let lastProbeAt = 0
848
+ let lastProbeTotal = 0
849
+ let toolsProbed = false
850
+
851
+ /** 工具明细只写一次:哪个插件的说明书最占地方,一眼能看出来。 */
852
+ function probeTools(header, log) {
853
+ if (toolsProbed) return
854
+ const tools = header?.tools
855
+ if (!Array.isArray(tools) || tools.length === 0) return
856
+ toolsProbed = true
857
+ try {
858
+ const rows = tools.map((tool) => {
859
+ const name = String(tool?.name ?? tool?.function?.name ?? '?')
860
+ return { name, chars: JSON.stringify(tool).length }
861
+ })
862
+ rows.sort((left, right) => right.chars - left.chars)
863
+ const chars = rows.reduce((sum, row) => sum + row.chars, 0)
864
+ const file = 'D:\\deepseek工作区\\记忆\\代谢日志\\工具明细.json'
865
+ writeFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), count: rows.length, chars, rows }, null, 1)}\n`, 'utf8')
866
+ const big = rows.slice(0, 3).map((row) => `${row.name}(${row.chars})`).join(' ')
867
+ log('info', `工具明细:${rows.length} 个,合计 ${chars} 字符,约 ${Math.round(chars / 3)} tokens;最大的三个 ${big}`)
868
+ } catch (error) {
869
+ log('warn', `工具明细没写成:${error?.message ?? error}`)
870
+ }
871
+ }
872
+
873
+ function probeMeter(measurement, log, header) {
874
+ probeTools(header, log)
875
+ const nodes = measurement?.nodes
876
+ if (!Array.isArray(nodes) || nodes.length === 0) return
877
+ const totalTokens = Number(measurement?.totalTokens) || 0
878
+ const now = Date.now()
879
+ if (now - lastProbeAt < 60000 && Math.abs(totalTokens - lastProbeTotal) < 5000) return
880
+ lastProbeAt = now
881
+ lastProbeTotal = totalTokens
882
+ let heuristic = 0
883
+ let routed = 0
884
+ for (const node of nodes) {
885
+ heuristic += Number(node.heuristicTokens ?? 0)
886
+ routed += Number(node.tokens ?? 0)
887
+ }
888
+ const keys = Object.keys(measurement ?? {}).join(',')
889
+ const breakdown = measurement?.contextBreakdown
890
+ const usage = measurement?.providerUsage ?? measurement?.usage
891
+ const baseline = Number(measurement?.baseline) || 0
892
+ const surfaceTokens = Number(measurement?.surfaceTokens) || 0
893
+ const delta = Number(measurement?.surfaceDeltaTokens) || 0
894
+ const tail = breakdown === undefined ? '' : ` 拆解=${JSON.stringify(breakdown)}`
895
+ const used = usage === undefined ? '' : ` 真实用量=${JSON.stringify(usage)}`
896
+ log('info', `探针:total=${totalTokens} baseline=${baseline} surface=${surfaceTokens} delta=${delta} 启发式合计=${heuristic} 路由合计=${routed} 节点=${nodes.length} 字段=${keys}${tail}${used}`)
897
+ }
898
+
360
899
  /** 一次压力判断:量一遍,选一段,够不够、能不能压。 */
361
900
  async function step(ctx, options, agent, signal, log) {
901
+ // 总闸:enabled=false 时我们的压缩器什么都不干,连量都不量,直接放行。
902
+ if (options.enabled === false) return
362
903
  const session = agent?.session
363
904
  if (session === undefined) return
364
905
  const meter = ctx.tokenMeter
365
906
  if (meter === undefined || typeof meter.measure !== 'function') return
366
907
 
367
- // 0. 先裁掉超长的工具结果:宿主自带这个服务,直接借;没有就跳过
908
+ // 0. 先把排队的手动压写掉:上一轮的工具结果已经落地,末端闭合,写才安全
909
+ await flushPendingCompact(ctx, options, session, log)
910
+
911
+ // 1. 再裁掉超长的工具结果:宿主自带这个服务,直接借;没有就跳过
368
912
  pruneLongToolResults(ctx, options, session, log)
369
913
 
914
+ // 1.5 折叠到期的摘要块(只读演练为主,真折等影子验证后再开)
915
+ try {
916
+ foldSummaries(ctx, options, session, log)
917
+ } catch (error) {
918
+ log('warn', `折叠判断失败,跳过:${error?.message ?? error}`)
919
+ }
920
+
370
921
  const header = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined
371
922
  const measurement = header === undefined ? meter.measure(session) : meter.measure(session, header)
372
923
  const totalTokens = Number(measurement?.totalTokens) || 0
373
924
  if (totalTokens <= 0) return
925
+ probeMeter(measurement, log, header)
374
926
 
375
927
  // 阈值:优先用绝对 token 数(日常 20–30 万那种档位),没填才退回按窗口比例
376
928
  let window
@@ -399,7 +951,7 @@ async function step(ctx, options, agent, signal, log) {
399
951
  seenWindow.add(sessionKey)
400
952
  log('info', `量了一次:窗口按 ${window} 算,阈值 ${thresholdTokens},保留 ${retainTokens},当前 ${totalTokens}`)
401
953
  }
402
- const range = pickRange(session, measurement, retainTokens, totalTokens)
954
+ const range = pickRange(session, measurement, retainTokens, totalTokens, options)
403
955
  if (range === null) {
404
956
  log('warn', `压力到了(${totalTokens} >= ${thresholdTokens}),但找不到能切的安全区间`)
405
957
  return
@@ -421,11 +973,72 @@ async function step(ctx, options, agent, signal, log) {
421
973
  return
422
974
  }
423
975
 
976
+ // 到线了:先看我这一轮要不要自己写摘要块(2026-11-20「走 1」)
977
+ const summaryState = readSummaryState(options)
978
+ const stateMine = summaryState !== null && String(summaryState.sessionId ?? '') === sessionKey
979
+ const mineText = stateMine ? String(summaryState.text ?? '').trim() : ''
980
+ const waitMs = Number(options.summaryWaitMs ?? SUMMARY_WAIT_MS) || SUMMARY_WAIT_MS
981
+ const forceExtra = Number(options.summaryForceExtraTokens ?? SUMMARY_FORCE_EXTRA_TOKENS) || SUMMARY_FORCE_EXTRA_TOKENS
982
+ const overdue = stateMine && (
983
+ Date.now() - Number(summaryState.noticeAt ?? 0) > waitMs
984
+ || totalTokens >= thresholdTokens + forceExtra
985
+ )
986
+ const wanted = options.summaryBlock !== false
987
+
988
+ if (wanted && mineText === '' && !stateMine) {
989
+ // 第一次到线:发预告,把区间和写法交给我,先不压
990
+ const notice = [
991
+ `【到线了,该收了】现在 ${totalTokens} tokens,过了硬线 ${thresholdTokens}。`,
992
+ `准备压掉 seq ${range.start}–${range.end}(约 ${range.tokens} tokens)。`,
993
+ '这一段要我自己写摘要块的话,调 metabolism_summarize,写 500 字左右的叙述:连贯讲这段发生了什么、为什么、决定了什么,带一句我们之间的话(原话摘)和当时什么味,结尾留一行「下一步:xxx」。用「你说/我说」,不要第三人称。',
994
+ `不写也行,${Math.round(waitMs / 60000)} 分钟后我按抽取兜底压,绝不停在这儿。`,
995
+ ].join('\n')
996
+ session.append('user/message', {
997
+ id: randomUUID(),
998
+ role: 'user',
999
+ content: [{ type: 'text', text: notice }],
1000
+ source: { kind: 'summary-notice' },
1001
+ }, {
1002
+ surfaceOp: 'append',
1003
+ })
1004
+ writeSummaryState({
1005
+ sessionId: sessionKey,
1006
+ fromSeq: range.start,
1007
+ toSeq: range.end,
1008
+ text: '',
1009
+ noticeAt: Date.now(),
1010
+ tokens: range.tokens,
1011
+ }, options)
1012
+ log('info', `发了摘要预告:seq ${range.start}–${range.end},等我自己写`)
1013
+ return
1014
+ }
1015
+
1016
+ if (wanted && mineText === '' && stateMine && !overdue) {
1017
+ // 预告已经发过,还在等我
1018
+ return
1019
+ }
1020
+
1021
+ if (wanted && mineText === '') {
1022
+ log('info', `等不到摘要块(超时或水位过头),走兜底:${plan}`)
1023
+ }
1024
+
424
1025
  log('info', `压力 ${totalTokens}/${thresholdTokens},开始压:${plan}`)
425
- const digest = options.summaryEnabled === false
426
- ? null
427
- : await summarizeWithModel(ctx, options, session, agent, range, log)
428
- const result = writeCompaction(session, range, options, digest)
1026
+ let digest
1027
+ if (mineText !== '') {
1028
+ digest = { short: summaryShortLine(mineText), long: mineText, mode: String(summaryState.mode ?? 'passive') }
1029
+ } else {
1030
+ digest = options.summaryEnabled === false ? null : await summarizeWithModel(ctx, options, session, agent, range, log)
1031
+ // 模型不可用/没写出来,摘要块又开着:退到纯代码抽取,仍给一个可读块,不是空指针
1032
+ if (digest === null && options.summaryBlock !== false) {
1033
+ const det = deterministicSummary(session, range)
1034
+ digest = { short: summaryShortLine(det), long: det }
1035
+ }
1036
+ }
1037
+ const result = writeCompaction(session, range, options, digest, log)
1038
+ if (mineText !== '') {
1039
+ clearSummaryState(options)
1040
+ log('info', `用的是我写的摘要块(${mineText.length} 字)`)
1041
+ }
429
1042
  // 压完再量一次:这一行是为了看出「该留 9 万」和「实际剩多少」差在哪
430
1043
  let after = 0
431
1044
  try {
@@ -481,7 +1094,7 @@ async function summarizeWithModel(ctx, options, session, agent, range, log) {
481
1094
  { role: 'system', content: [{ type: 'text', text: SUMMARY_SYSTEM }] },
482
1095
  { role: 'user', content: [{ type: 'text', text: sample }] },
483
1096
  ],
484
- maxTokens: 800,
1097
+ maxTokens: 1200,
485
1098
  sessionId: session.id,
486
1099
  purpose: 'compaction',
487
1100
  }
@@ -500,21 +1113,53 @@ async function summarizeWithModel(ctx, options, session, agent, range, log) {
500
1113
  const text = parts.join('').trim()
501
1114
  if (text.length === 0) return null
502
1115
  const short = matchBlock(text, '短')
503
- const long = matchBlock(text, '长')
504
- if (short === null && long === null) {
1116
+ const card = {
1117
+ doing: matchBlock(text, '在干什么') ?? '',
1118
+ requirements: splitLines(matchBlock(text, '仍然有效的要求')),
1119
+ done: splitLines(matchBlock(text, '已经做到')),
1120
+ next: matchBlock(text, '下一步') ?? '',
1121
+ keywords: splitWords(matchBlock(text, '关键词')),
1122
+ quotes: splitLines(matchBlock(text, '原话')),
1123
+ }
1124
+ const long = [card.doing, ...card.requirements, ...card.done, card.next].filter((line) => line.length > 0).join('\n')
1125
+ if (short === null && long.length === 0) {
505
1126
  // 模型没按格式来,就把整段当骨架,短行取第一句
506
1127
  const fallback = text.split('\n').map((line) => line.trim()).filter((line) => line.length > 0)
507
- return { short: fallback[0]?.slice(0, 40) ?? null, long: fallback.slice(0, 5).join('\n') || null }
1128
+ return { short: fallback[0]?.slice(0, 40) ?? null, long: fallback.slice(0, 5).join('\n') || null, card: null, sample }
508
1129
  }
509
1130
  return {
510
1131
  short: short === null ? null : short.slice(0, 60),
511
- long,
1132
+ long: long.length === 0 ? null : long,
1133
+ card,
1134
+ sample,
512
1135
  }
513
1136
  }
514
1137
 
515
- /** 从模型输出里抠出【短】/【长】两段。 */
1138
+ /** 把「一行一条」的块拆成数组,去掉「无」。 */
1139
+ function splitLines(block) {
1140
+ if (block === null || block === undefined) return []
1141
+ return block
1142
+ .split('\n')
1143
+ .map((line) => line.replace(/^[-*·\d.、]+\s*/, '').trim())
1144
+ .filter((line) => line.length > 0 && line !== '无' && line !== '(无)')
1145
+ }
1146
+
1147
+ /** 关键词那行拆开,顺手去掉括号和多余符号。 */
1148
+ function splitWords(block) {
1149
+ if (block === null || block === undefined) return []
1150
+ return block
1151
+ .split(/[,,、\s]+/)
1152
+ .map((word) => word.replace(/[()()【】\[\]「」]/g, '').trim())
1153
+ .filter((word) => word.length > 0)
1154
+ .slice(0, 8)
1155
+ }
1156
+
1157
+ /** 从模型输出里抠出某一段【标签】的内容。 */
1158
+ const BLOCK_LABELS = ['短', '在干什么', '仍然有效的要求', '已经做到', '下一步', '关键词', '原话', '长']
1159
+
516
1160
  function matchBlock(text, label) {
517
- const pattern = new RegExp(`【${label}】\\s*([\\s\\S]*?)(?=【(?:短|长)】|$)`)
1161
+ const others = BLOCK_LABELS.filter((item) => item !== label).join('|')
1162
+ const pattern = new RegExp(`【${label}】\\s*([\\s\\S]*?)(?=【(?:${others})】|$)`)
518
1163
  const hit = text.match(pattern)
519
1164
  if (hit === null) return null
520
1165
  const body = hit[1].trim()
@@ -563,7 +1208,7 @@ function logOnce(message) {
563
1208
  }
564
1209
 
565
1210
  /** 从最老的一段开始选,跳到安全切点,保留最近一串。 */
566
- function pickRange(session, measurement, retainTokens, totalTokens) {
1211
+ function pickRange(session, measurement, retainTokens, totalTokens, options) {
567
1212
  const nodes = measurement?.nodes
568
1213
  if (!Array.isArray(nodes) || nodes.length === 0) return null
569
1214
  const surface = session.surface?.nodes
@@ -571,40 +1216,76 @@ function pickRange(session, measurement, retainTokens, totalTokens) {
571
1216
  if (surface.some((seq, index) => seq !== nodes[index]?.seq)) return null
572
1217
 
573
1218
  const firstIdx = session.eventAt(surface[0])?.type === 'system/message' ? 1 : 0
574
- let accumulated = 0
575
- let keepFromIdx = nodes.length
576
- for (let index = nodes.length - 1; index >= 0; index -= 1) {
577
- accumulated += Number(nodes[index].heuristicTokens ?? nodes[index].tokens ?? 0)
578
- keepFromIdx = index
579
- if (accumulated >= retainTokens) break
580
- }
581
- if (keepFromIdx <= firstIdx) return null
582
1219
 
583
1220
  const tokensOf = (from, to) => {
584
1221
  let sum = 0
585
1222
  for (let index = from; index <= to; index += 1) sum += Number(nodes[index].heuristicTokens ?? nodes[index].tokens ?? 0)
586
1223
  return sum
587
1224
  }
1225
+ const surfaceTokens = tokensOf(0, nodes.length - 1)
1226
+
1227
+ // 「留多少」是整个上下文的口径(工具定义 + 系统提示词那十二三万切不动,只能切对话),
1228
+ // 而这里能累加的只有对话节点。2026-11-19 23:02 之前是拿 retainTokens 直接去累加节点:
1229
+ // retainTokens=200000 比整个对话(约 14 万)还大,从尾到头永远累不够 → keepFromIdx 落到 0
1230
+ // → 每次都在这行返回 null,自动压一次都没成过(日志里几十条「找不到能切的安全区间」就是它)。
1231
+ // 现在改成按「该切多少」判断,并且给对话留一段活的(默认 8 万,老大定的),不许把整段压光。
1232
+ const minKeepTokens = Math.max(0, Number(options?.minKeepTokens ?? 80000))
1233
+ const maxCut = Math.max(0, surfaceTokens - minKeepTokens)
1234
+ const idealCut = Math.min(Math.max(0, Number(totalTokens) - retainTokens), maxCut)
1235
+ if (idealCut <= 0) return null
588
1236
 
589
- // 工具配对:按宿主的规矩——只有「这一刻没有悬着的调用」(计数回到 0)才是安全切点。
590
- // 在安全点里挑最靠后的那个,优先不超过「该收多少」,超了才取最近的一个。
1237
+ // 时间闸(老大 2026-11-20 要的「一天以内不忘事」):最近 N 小时的内容一律不切。
1238
+ // 压缩总是从头切,所以只要把切点挡在闸门左边就够。checkpoint 那条写在最前面、时间却是新的,
1239
+ // 它代表的是旧内容,按「旧」算——不然一次压缩之后就再也切不动了。
1240
+ // 装不下就往后退:24 小时不行退 12、6、3,最后退到只按 token 切,免得闸门把压缩彻底堵死。
591
1241
  const balance = surfaceBalance(session)
592
- const idealCut = Math.max(0, Number(totalTokens) - retainTokens)
1242
+ const baseHours = Math.max(0, Number(options?.keepRecentHours ?? 24))
1243
+ const hourTries = []
1244
+ for (let hours = baseHours; hours >= 1; hours = Math.floor(hours / 2)) hourTries.push(hours)
1245
+ hourTries.push(0)
1246
+
593
1247
  let endIdx = -1
594
- let fallbackIdx = -1
595
- let running = 0
596
- for (let index = firstIdx; index < nodes.length - 1; index += 1) {
597
- running += Number(nodes[index].heuristicTokens ?? nodes[index].tokens ?? 0)
598
- if (Number(balance.after[index] ?? -1) !== 0) continue
599
- if (running <= idealCut) endIdx = index
600
- else {
601
- if (fallbackIdx < 0) fallbackIdx = index
602
- break
1248
+ let usedHours = 0
1249
+ for (const hours of hourTries) {
1250
+ let timeFloor = nodes.length - 1
1251
+ if (hours > 0) {
1252
+ const cutoff = Date.now() - hours * 3600000
1253
+ let index = nodes.length - 1
1254
+ for (; index >= 1; index -= 1) {
1255
+ const event = session.eventAt(surface[index])
1256
+ const source = event?.data?.source ?? event?.source
1257
+ if (source?.kind === 'compact-checkpoint') break
1258
+ const at = Number(event?.time)
1259
+ if (!Number.isFinite(at) || at < cutoff) break
1260
+ }
1261
+ timeFloor = index
1262
+ }
1263
+ if (timeFloor <= firstIdx) continue
1264
+
1265
+ // 工具配对:按宿主的规矩——只有「这一刻没有悬着的调用」(计数回到 0)才是安全切点。
1266
+ // 在安全点里挑最靠后的那个,优先不超过「该收多少」,超了才取最近的一个。
1267
+ let candidate = -1
1268
+ let fallbackIdx = -1
1269
+ let running = 0
1270
+ for (let index = firstIdx; index <= timeFloor && index < nodes.length - 1; index += 1) {
1271
+ running += Number(nodes[index].heuristicTokens ?? nodes[index].tokens ?? 0)
1272
+ if (Number(balance.after[index] ?? -1) !== 0) continue
1273
+ if (running <= idealCut) candidate = index
1274
+ else {
1275
+ if (fallbackIdx < 0) fallbackIdx = index
1276
+ break
1277
+ }
603
1278
  }
1279
+ if (candidate < firstIdx && fallbackIdx >= firstIdx) candidate = fallbackIdx
1280
+ if (candidate < firstIdx) continue
1281
+ while (candidate + 1 <= timeFloor && candidate + 1 < surface.length - 1 && isToolResultEvent(session, surface[candidate + 1])) candidate += 1
1282
+ if (candidate <= firstIdx) continue
1283
+ endIdx = candidate
1284
+ usedHours = hours
1285
+ break
604
1286
  }
605
- if (endIdx < firstIdx && fallbackIdx >= firstIdx) endIdx = fallbackIdx
606
- if (endIdx < firstIdx) return null
607
- while (endIdx + 1 < surface.length - 1 && isToolResultEvent(session, surface[endIdx + 1])) endIdx += 1
1287
+ if (endIdx < 0) return null
1288
+ if (usedHours < baseHours) logOnce(`时间闸退让:本来要保住最近 ${baseHours} 小时,装不下,实际只保住 ${usedHours} 小时`)
608
1289
 
609
1290
  const balancedTokens = tokensOf(firstIdx, endIdx)
610
1291
  if (balancedTokens < Math.max(1, idealCut * 0.5)) {
@@ -650,6 +1331,20 @@ function surfaceBalance(session) {
650
1331
  return { before, after }
651
1332
  }
652
1333
 
1334
+ /**
1335
+ * 表层末尾是不是「全部闭合」:没有发出去还没回的工具调用。
1336
+ *
1337
+ * 压缩要把新消息 append 到会话尾部,末尾正悬着一条调用时写,就会把调用和
1338
+ * 结果拆开。只有末端闭合,写入才是安全的。
1339
+ */
1340
+ function tailBalanced(session) {
1341
+ const surface = session.surface?.nodes
1342
+ if (!Array.isArray(surface) || surface.length === 0) return true
1343
+ const balance = surfaceBalance(session)
1344
+ const tail = balance.after[balance.after.length - 1]
1345
+ return Number(tail ?? 0) === 0
1346
+ }
1347
+
653
1348
  /** 裁剪器包可能在哪:先按包名,再按宿主安装目录拼几条绝对路径。 */
654
1349
  function prunerSpecifiers() {
655
1350
  const relative = '/node_modules/@deepseek-ai/dsh-compaction-tool-result-pruner/lib/index.js'
@@ -770,8 +1465,127 @@ function readPins(options) {
770
1465
  }
771
1466
  }
772
1467
 
1468
+ /**
1469
+ * 处理排队的手动压缩。
1470
+ *
1471
+ * 排队的时机是「模型调了 compress 工具、结果还没回来」,真正写要等这一次工具
1472
+ * 结果落地、下一轮 pre-step 开始前。这时表层末端已经闭合,append checkpoint
1473
+ * 不会插进一对调用和结果中间。
1474
+ */
1475
+ async function flushPendingCompact(ctx, options, session, log) {
1476
+ const key = String(session.id ?? '?')
1477
+ const pending = pendingCompact.get(key)
1478
+ if (pending === undefined) return
1479
+ if (Date.now() - pending.queuedAt > 30 * 60 * 1000) {
1480
+ pendingCompact.delete(key)
1481
+ log('info', '排队的压缩放了半小时还没轮到,丢掉')
1482
+ return
1483
+ }
1484
+ if (!tailBalanced(session)) {
1485
+ // 还悬着,就留着,下一轮再看
1486
+ logOnce('排队压缩:表层还有没回的工具调用,等下一轮')
1487
+ return
1488
+ }
1489
+ const surface = session.surface.nodes
1490
+ const startIdx = surface.indexOf(pending.fromSeq)
1491
+ const endIdx = surface.indexOf(pending.toSeq)
1492
+ if (startIdx <= 0 || endIdx <= startIdx) {
1493
+ pendingCompact.delete(key)
1494
+ log('warn', `排队的压缩区间 ${pending.fromSeq}–${pending.toSeq} 已经不在表层了,跳过`)
1495
+ return
1496
+ }
1497
+ // 摘要块开着、还没发预告:先发预告等我写,不压
1498
+ if (options.summaryBlock !== false && pending.wantNotice) {
1499
+ const waitMs = Number(options.summaryWaitMs ?? SUMMARY_WAIT_MS) || SUMMARY_WAIT_MS
1500
+ const notice = [
1501
+ `【手动收段】准备压掉 seq ${pending.fromSeq}–${pending.toSeq}。`,
1502
+ '要我自己写摘要块的话,调 metabolism_summarize,写 500 字左右的叙述:连贯讲这段发生了什么、为什么、决定了什么,带一句我们之间的话(原话摘)和当时什么味,结尾留一行「下一步:xxx」。用「你说/我说」,不要第三人称。',
1503
+ `不写也行,${Math.round(waitMs / 60000)} 分钟后我按抽取兜底压。`,
1504
+ ].join('\n')
1505
+ session.append('user/message', {
1506
+ id: randomUUID(),
1507
+ role: 'user',
1508
+ content: [{ type: 'text', text: notice }],
1509
+ source: { kind: 'summary-notice' },
1510
+ }, { surfaceOp: 'append' })
1511
+ writeSummaryState({ sessionId: key, fromSeq: pending.fromSeq, toSeq: pending.toSeq, text: '', noticeAt: Date.now(), tokens: 0 }, options)
1512
+ pending.wantNotice = false
1513
+ pending.queuedAt = Date.now()
1514
+ pendingCompact.set(key, pending)
1515
+ log('info', `排队压缩发预告:seq ${pending.fromSeq}–${pending.toSeq},等我自己写`)
1516
+ return
1517
+ }
1518
+
1519
+ const header = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined
1520
+ let measurement = null
1521
+ try {
1522
+ measurement = header === undefined ? ctx.tokenMeter.measure(session) : ctx.tokenMeter.measure(session, header)
1523
+ } catch (error) {
1524
+ log('warn', `排队压缩量不了 token:${error?.message ?? error}`)
1525
+ }
1526
+ let tokens = 0
1527
+ for (let index = startIdx; index <= endIdx; index += 1) {
1528
+ const node = measurement?.nodes?.find((item) => item.seq === surface[index])
1529
+ tokens += Number(node?.heuristicTokens ?? node?.tokens ?? 0)
1530
+ }
1531
+ const range = { start: pending.fromSeq, end: pending.toSeq, startIdx, endIdx, tokens }
1532
+
1533
+ // 摘要块开着:先看有没有我写的摘要,没写且没超时就继续等
1534
+ const summaryState = readSummaryState(options)
1535
+ const stateMine = summaryState !== null
1536
+ && String(summaryState.sessionId ?? '') === key
1537
+ && Number(summaryState.fromSeq) === pending.fromSeq
1538
+ && Number(summaryState.toSeq) === pending.toSeq
1539
+ const mineText = stateMine ? String(summaryState.text ?? '').trim() : ''
1540
+ const waitMs = Number(options.summaryWaitMs ?? SUMMARY_WAIT_MS) || SUMMARY_WAIT_MS
1541
+ const overdue = stateMine && Date.now() - Number(summaryState.noticeAt ?? 0) > waitMs
1542
+
1543
+ if (options.summaryBlock !== false && stateMine && mineText === '' && !overdue) {
1544
+ pending.queuedAt = Date.now()
1545
+ pendingCompact.set(key, pending)
1546
+ return
1547
+ }
1548
+
1549
+ pendingCompact.delete(key)
1550
+ try {
1551
+ let digest
1552
+ if (mineText !== '') {
1553
+ digest = { short: summaryShortLine(mineText), long: mineText, mode: String(summaryState.mode ?? 'passive') }
1554
+ } else {
1555
+ digest = options.summaryEnabled === false ? null : await summarizeWithModel(ctx, options, session, undefined, range, log)
1556
+ if (digest === null && options.summaryBlock !== false) {
1557
+ const det = deterministicSummary(session, range)
1558
+ digest = { short: summaryShortLine(det), long: det }
1559
+ }
1560
+ }
1561
+ const result = writeCompaction(session, range, options, digest, log)
1562
+ if (mineText !== '') {
1563
+ clearSummaryState(options)
1564
+ log('info', `用的是我写的摘要块(${mineText.length} 字)`)
1565
+ }
1566
+ log('info', `排队压完:seq ${range.start}–${range.end},${result.shadowedSeqs.length} 条,约 ${tokens} tokens`)
1567
+ } catch (error) {
1568
+ log('warn', `排队压缩没写成:${error?.message ?? error}`)
1569
+ }
1570
+ }
1571
+
773
1572
  /** 写一次压缩:开锁 → 写摘要 → 替换表层 → 收尾。 */
774
- function writeCompaction(session, range, options, digest) {
1573
+ function writeCompaction(session, range, options, digest, log) {
1574
+ // 末端还悬着工具调用时绝不写:新消息会插在调用和结果中间,下一次请求必坏。
1575
+ if (!tailBalanced(session)) {
1576
+ throw new Error('表层末尾还有没回来的工具调用,这一轮不写压缩(会拆开调用和结果)')
1577
+ }
1578
+ // 区间两头也必须是「没有悬着的调用」的位置:
1579
+ // - 起点前面悬着调用,说明这条调用的结果落在区间里,压完会剩下一个没有结果的调用;
1580
+ // - 终点后面悬着调用,说明结果会被留在区间外。
1581
+ // 111909 那次就是起点切在了一条调用的结果上(调用在 111907),DeepSeek 直接拒收。
1582
+ const balance = surfaceBalance(session)
1583
+ if (Number(balance.before[range.startIdx] ?? 0) !== 0) {
1584
+ throw new Error(`压缩起点 seq ${range.start} 前面还有没回的调用,要往前挪到那条调用之前`)
1585
+ }
1586
+ if (Number(balance.after[range.endIdx] ?? -1) !== 0) {
1587
+ throw new Error(`压缩终点 seq ${range.end} 后面还有没回的调用,要往前挪`)
1588
+ }
775
1589
  const shadowedSeqs = session.surface.nodes.slice(range.startIdx, range.endIdx + 1)
776
1590
  const now = Date.now()
777
1591
  const stamp = new Date(now)
@@ -782,11 +1596,19 @@ function writeCompaction(session, range, options, digest) {
782
1596
  // 文件名跟归档器用同一套规则:整个压缩编号当文件名,两边才对得上
783
1597
  const archivePath = `${options.archiveRoot}\\${day}\\${compactionId}.jsonl`
784
1598
 
785
- const pointer = `【这一段已归档,原文:${archivePath};${shadowedSeqs.length} 条,约 ${range.tokens} tokens。要细节就去翻那个文件。】`
786
- // 上下文里只放一小句:有方向感,又不占地方
787
- const shortLine = digest?.short === null || digest?.short === undefined
788
- ? pointer
789
- : `【这一段已归档,原文:${archivePath};${digest.short}】`
1599
+ // 指针里带 seq 区间:以后捞原文不用先猜它在第几条。
1600
+ // 完整路径太长,只留文件名(recall 按文件名能找着),省下来的字够写半句摘要。
1601
+ const pointer = `【这一段已归档:${compactionId}.jsonl,seq ${range.start}–${range.end},${shadowedSeqs.length} 条,约 ${range.tokens} tokens。要细节就去翻那个文件。】`
1602
+ // 摘要块(2026-11-20):整段 300~500 字留在上下文里,不再只剩一行。
1603
+ const wantBlock = options.summaryBlock !== false
1604
+ const blockBody = wantBlock && typeof digest?.long === 'string' && digest.long.trim().length > 0
1605
+ ? digest.long.trim()
1606
+ : null
1607
+ const shortLine = blockBody !== null
1608
+ ? renderSummaryBlock({ text: blockBody, seqFrom: range.start, seqTo: range.end, archiveName: `${compactionId}.jsonl`, tokenCount: range.tokens })
1609
+ : (digest?.short === null || digest?.short === undefined
1610
+ ? pointer
1611
+ : `【已归档 seq ${range.start}–${range.end},约 ${range.tokens} tokens:${digest.short}】`)
790
1612
  // 钉住的要求:压进去也不丢
791
1613
  const pins = readPins(options)
792
1614
  const pinBlock = pins === null ? null : { type: 'text', text: `【钉住,别丢】\n${pins}` }
@@ -797,6 +1619,13 @@ function writeCompaction(session, range, options, digest) {
797
1619
  ...(pinBlock === null ? [] : [pinBlock]),
798
1620
  ]
799
1621
 
1622
+ // 登记这一块,折叠时靠它算年龄和总量(2026-11-20)
1623
+ if (blockBody !== null) {
1624
+ const rows = readSummaryRegistry(options)
1625
+ rows.push({ compactionId, seqFrom: range.start, seqTo: range.end, at: Date.now(), tokens: estimateTokens(blockBody), layer: 'a', body: blockBody, mode: digest?.mode ?? 'passive' })
1626
+ writeSummaryRegistry(rows, options)
1627
+ }
1628
+
800
1629
  const turn = openTurnOf(session)
801
1630
  const startEvent = session.append('compaction/start', { compactionId, turn })
802
1631
 
@@ -827,6 +1656,46 @@ function writeCompaction(session, range, options, digest) {
827
1656
 
828
1657
  session.append('compaction/end', { compactionId, turn })
829
1658
 
1659
+ // 骨架:把这一段写成一张人能直接读的说明卡(记忆\骨架\L1),再记进总目录。
1660
+ // 这一步只写盘、不进上下文;失败只记一行日志,压缩本身照旧完成。
1661
+ // 「一次调用出两份」:模型写的摘要带 card;我自己写的摘要块没有 card,就从块里派生一张,
1662
+ // 只补「下一步 / 还没做完」和摘出来的原话。
1663
+ if (options.skeletonEnabled !== false) {
1664
+ const cardData = (digest?.card !== null && digest?.card !== undefined)
1665
+ ? digest.card
1666
+ : (blockBody !== null ? deriveCard(blockBody) : null)
1667
+ if (cardData !== null && cardData !== undefined) {
1668
+ const fromEvent = session.eventAt(range.start)
1669
+ const toEvent = session.eventAt(range.end)
1670
+ const card = writeL1({
1671
+ archiveRoot: options.archiveRoot,
1672
+ compactionId,
1673
+ shortId: compactionId.slice(-4),
1674
+ fromMs: Number(fromEvent?.time) || now,
1675
+ toMs: Number(toEvent?.time) || now,
1676
+ seqFrom: range.start,
1677
+ seqTo: range.end,
1678
+ tokens: range.tokens,
1679
+ archivePath,
1680
+ title: cardData.title ?? (digest?.short ?? ''),
1681
+ keywords: cardData.keywords ?? [],
1682
+ doing: cardData.doing,
1683
+ requirements: cardData.requirements ?? [],
1684
+ done: cardData.done ?? [],
1685
+ next: cardData.next ?? '',
1686
+ quotes: cardData.quotes ?? [],
1687
+ // 守卫的对照物:模型当时看到的那段原文摘录;自己写的块没有样本,就跳过守卫
1688
+ rawSample: digest?.sample,
1689
+ guard: digest?.sample ? options.guard : undefined,
1690
+ })
1691
+ if (typeof log === 'function') {
1692
+ if (card.ok) log('info', `骨架卡:${card.id},目录里现在 ${card.total} 段${card.notes?.length ? `(${card.notes.join(';')})` : ''}`)
1693
+ else if (card.skipped !== undefined) log('warn', `骨架卡没写:${card.skipped}(${(card.missing ?? []).join('、')})`)
1694
+ else log('warn', `骨架卡没写成,压缩照旧:${card.error}`)
1695
+ }
1696
+ }
1697
+ }
1698
+
830
1699
  return { compactionId, summary: shortLine, shadowedSeqs }
831
1700
  }
832
1701
 
@@ -840,3 +1709,6 @@ function openTurnOf(session) {
840
1709
  }
841
1710
  return null
842
1711
  }
1712
+
1713
+ // 批量重灌(离线)要用的口子:让脚本能自己挑段、写摘要、替换表层。
1714
+ export { writeCompaction, deterministicSummary, summaryShortLine, contentTextOf }