@magic6/dsh-compaction-policy-engine 0.5.11 → 0.5.13

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.
@@ -0,0 +1,103 @@
1
+ # 分批压缩(plan)
2
+
3
+ > 目标:**单次请求装不下的历史,也能压掉。**
4
+
5
+ ## 0. 问题
6
+
7
+ 压缩是所有其它失败的恢复手段,但它自己有一条死路:
8
+
9
+ ```
10
+ 会话 surface > 模型窗口
11
+ → 触发压缩
12
+ → 摘要请求要发整段被压缩内容(如 204 万 token)
13
+ → 上游 400 context_length_exceeded
14
+ → 压缩失败 → 会话永久不可恢复
15
+ ```
16
+
17
+ 实测(2026-11-26 Win11):surface 2,100,381 tokens / 窗口 1,000,000,32 次压缩全失败,
18
+ 最终只能靠 `dsh-session-rescue` 在 DSH 之外改文件救回来。
19
+
20
+ **根因唯一**:摘要请求一次要把整段被压缩内容发出去,而这段内容可能比窗口还大。
21
+
22
+ ## 1. 契约
23
+
24
+ 父类 `summarizeCompaction` 的调用与约束:
25
+
26
+ ```js
27
+ summaryResult = await dependencies.summarize(prepared.input, agent, signal);
28
+ // summaryResult.summary 必须是 TextBlock[],父类会 frameSummary() 包成 checkpoint
29
+ // 约束:framedSummaryTokenCount < prepared.shadowedRouteTokenCount(摘要必须比被压缩内容小)
30
+ ```
31
+
32
+ `prepared.input` = `{ messages, tools? }`,其中 messages 是 surface 上被 shadow 的那一段。
33
+
34
+ **接入点**:`summarize()` 内部。它可以在返回前调用任意多次 LLM。
35
+
36
+ ## 2. 设计
37
+
38
+ ```
39
+ summarize(input, agent, signal)
40
+ │
41
+ ├─ 1. 量一下 input.messages 有多大
42
+ │
43
+ ├─ 装得下 → 走原路径(不变)
44
+ │
45
+ └─ 装不下 → 分批:
46
+ batch 1: [最早的 messages ...装满 budget] → S1(文本)
47
+ batch 2: ["前情提要:S1"] + [后续 ...装满 budget] → S2
48
+ batch 3: ["前情提要:S2"] + [后续 ...] → S3
49
+ ...
50
+ 最后:把 Sn 作为 summary 返回
51
+ ```
52
+
53
+ **关键点**:每批都把上一批的摘要作为"前情提要"带进去,所以信息不丢、且每批请求都装得下。
54
+
55
+ ### 预算
56
+
57
+ ```
58
+ budget = contextWindow × 0.8
59
+ ```
60
+
61
+ 留 20% 给输出与指令。800k 窗口 → 每批最多 640k token 输入。
62
+
63
+ ### 保护
64
+
65
+ | 保护 | 值 | 理由 |
66
+ |:--|:--|:--|
67
+ | 批次数上限 | 12 | 每批一次完整 LLM 调用,无上限会烧钱 |
68
+ | 每批前检查 `signal.aborted` | — | 用户取消要立刻停 |
69
+ | 单条消息本身超 budget | 离线裁剪该条 | 否则那批永远发不出去 |
70
+ | 摘要本身超 `shadowedRouteTokenCount` | 截断 | 否则父类直接拒绝 |
71
+
72
+ ## 3. 降级链
73
+
74
+ ```
75
+ ① 一次发完(默认,Mac 现行路径)
76
+ ② 分批(本方案)
77
+ ③ 离线裁剪后再试 ② ← 仅当单条消息就超 budget
78
+ ```
79
+
80
+ ③ 只在极端情况用:把超大的 tool 输出替换成头尾摘录。
81
+
82
+ ## 4. 改动
83
+
84
+ | 文件 | 改动 |
85
+ |:--|:--|
86
+ | `lib/summarize-budget.js` | 从 `src/` 移入(预算、切分、裁剪,纯函数,19 测试已绿) |
87
+ | `lib/index.js` | `summarize()` 加分批分支;新增 stage 诊断 |
88
+ | `test/summarize-chunked.test.js` | 分批的接续逻辑、预算、上限、取消 |
89
+ | `e2e/run.sh` | 场景 `oversize`:假 provider 8k 窗口 + 30k 历史,断言压缩成功 |
90
+
91
+ ## 5. 验收
92
+
93
+ - [ ] 装得下时行为**完全不变**(现有 222 测试全绿)
94
+ - [ ] 装不下时分批完成,且摘要覆盖全段(不是只留尾巴)
95
+ - [ ] 批次数超限时报错明确
96
+ - [ ] 每批都打诊断,能看出走了几批、每批多大
97
+ - [ ] e2e `oversize` 在旧版本红、新版本绿
98
+
99
+ ## 6. 不做
100
+
101
+ - 不改父类事务语义
102
+ - 不引入新依赖
103
+ - 不碰 `dsh-session-rescue`(那是 DSH 之外的抢修,与本方案正交)
package/lib/index.js CHANGED
@@ -218,6 +218,14 @@ const layerFields = {
218
218
  maxTokens: z.number().step(1).min(1).description('cap on the generated summary length'),
219
219
  compactionRetries: z.number().step(1).min(0).description('retries when a summarization attempt fails'),
220
220
  maxOverflowRetries: z.number().step(1).min(0).description('retries when the request itself overflowed the context window'),
221
+ replayFullConversation: z
222
+ .boolean()
223
+ .description(
224
+ 'send the whole surfaced conversation to the summarizer instead of only the shadowed region; ' +
225
+ 'needed only when the summarization route is a local inference engine whose prefix cache ' +
226
+ 'resumes from an exact token-prefix (see fullConversationMessages). Off by default: a ' +
227
+ 'conversation large enough to need compaction is one whose full replay may not fit the window.',
228
+ ),
221
229
  };
222
230
 
223
231
  /** The global default layer. */
@@ -230,6 +238,70 @@ const modelLayer = z.object({
230
238
  ...layerFields,
231
239
  });
232
240
 
241
+ /**
242
+ * The message list the last routed request actually sent: the system head plus
243
+ * every surface node's projected message, in surface order.
244
+ *
245
+ * Why a summary call may need all of it rather than only the shadowed region
246
+ * (measured against a local inference engine): that engine resumes only from a
247
+ * stored state that is an exact token-prefix of the new prompt, and it keeps at
248
+ * most `--prompt-cache` (6) checkpoints, taken at assistant-turn boundaries and
249
+ * every `--prompt-cache-every` (16384) fresh tokens. Those six slots hold the
250
+ * *recent* turn boundaries, so the shadowed region's own checkpoints are long
251
+ * evicted: a region-only replay matches nothing but the pinned system-prompt
252
+ * root and re-reads the whole region. Measured: a 403,413-token prompt read over
253
+ * 311 s, then killed by provider-d's 300 s idle watchdog, because a prefill
254
+ * emits no tokens and a slow engine therefore looks idle. Appending the
255
+ * instruction after the FULL conversation instead makes the call an exact
256
+ * extension of the live state, so the engine resumes at the live end and
257
+ * prefills only the instruction.
258
+ *
259
+ * The trade-off is deliberate: the summary then condenses the whole
260
+ * conversation, so the checkpoint and the verbatim-retained tail overlap. That
261
+ * costs the tail's tokens once per compaction, against re-reading the entire
262
+ * context on every one.
263
+ *
264
+ * ⚠️ Off by default, and it must stay that way. This is the opposite trade in
265
+ * the opposite direction: a conversation large enough to need compaction is one
266
+ * whose full replay may no longer fit the model window, and then the request
267
+ * that was supposed to rescue the session cannot be sent at all. That is exactly
268
+ * what happened on 2026-11-26 — 2,100,381 tokens of surface against a 1,000,000
269
+ * window, every compaction rejected before it left the host. Enable this only
270
+ * when the summarization route is a local engine that needs the prefix.
271
+ *
272
+ * @param session - the session whose surface to project.
273
+ * @returns the projected messages, or `undefined` when the surface is unreadable.
274
+ */
275
+ function fullConversationMessages(session) {
276
+ const nodes = session?.surface?.nodes;
277
+ if (!Array.isArray(nodes) || nodes.length === 0) return undefined;
278
+ const messages = [];
279
+ for (const seq of nodes) {
280
+ const event = session.eventAt?.(seq);
281
+ if (event === undefined || event === null) continue;
282
+ const message = session.deriveEventMessage?.(event);
283
+ if (message === null || message === undefined) continue;
284
+ messages.push(message);
285
+ }
286
+ return messages.length === 0 ? undefined : messages;
287
+ }
288
+
289
+ /**
290
+ * The summary request's message list: the full conversation when the operator
291
+ * opted in and the session can project it, otherwise the caller's own
292
+ * region-only input unchanged.
293
+ *
294
+ * @param input - the parent's region-only summarization input.
295
+ * @param agent - the agent whose session to project.
296
+ * @param replayFullConversation - the resolved policy flag.
297
+ * @returns the message list to send.
298
+ */
299
+ function summarizationInput(input, agent, replayFullConversation) {
300
+ if (replayFullConversation !== true) return input;
301
+ const messages = fullConversationMessages(agent?.session);
302
+ return messages === undefined ? input : { ...input, messages };
303
+ }
304
+
233
305
  /**
234
306
  * The routed (provider, model) of a conversation: the latest durable request
235
307
  * wins (that is what is actually in use), falling back to the agent's options.
@@ -768,9 +840,27 @@ export class CompactionControlEngine extends BasicCompactionEngine {
768
840
  `[compaction] FAILED fiber=${this.ctx.fiber?.name} trigger=${trigger} target=${target === undefined ? 'UNDEFINED' : `${target.provider}/${target.model}`} error=${String(error?.message ?? error)}\n`,
769
841
  );
770
842
  }
843
+ // The de-duplication above keeps the wording readable; this keeps the
844
+ // *persistence* visible. Silence was the actual defect on 2026-11-26.
845
+ this._consecutiveFailures += 1;
846
+ if (this._consecutiveFailures >= this.constructor.CONSECUTIVE_FAILURE_WARN_AT && !this._streakEscalated) {
847
+ this._streakEscalated = true;
848
+ process.stderr.write(
849
+ `[compaction] ⚠️ ${this._consecutiveFailures} CONSECUTIVE FAILURES fiber=${this.ctx.fiber?.name} ` +
850
+ `trigger=${trigger} target=${target === undefined ? 'UNDEFINED' : `${target.provider}/${target.model}`} ` +
851
+ `this.session=${agent?.session?.id ?? 'unknown'} error=${String(error?.message ?? error)} ` +
852
+ `— compaction is the recovery path for every other failure, so this session is no longer self-healing. ` +
853
+ `Check the summarization route and its declared context window; if the surface has outgrown the window, ` +
854
+ `a rescue outside DSH may be required (tools/dsh-session-rescue.mjs).\n`,
855
+ );
856
+ }
771
857
  throw error;
772
858
  }
773
859
  if (result !== null) {
860
+ // A success resets the streak: only *consecutive* failures say the route
861
+ // is broken, and an intermittent one must not accumulate into a warning.
862
+ this._consecutiveFailures = 0;
863
+ this._streakEscalated = false;
774
864
  process.stderr.write(
775
865
  `[compaction] FIRED fiber=${this.ctx.fiber?.name} trigger=${trigger} source=${this._fileOrigin} thresholdRatio=${this.config.thresholdRatio} thresholdTokens=${thresholdTokens ?? 'unknown'} shadowed=${result.shadowedSeqs.length} seqs=${result.shadowedRange.start}-${result.shadowedRange.end} tokens=~${result.shadowedTokenCount}\n`,
776
866
  );
@@ -985,6 +1075,30 @@ export class CompactionControlEngine extends BasicCompactionEngine {
985
1075
  /** Last failure reported per trigger, so a repeating failure is stated once. */
986
1076
  _reportedFailures = new Map();
987
1077
 
1078
+ /**
1079
+ * Consecutive compaction failures, and whether the current streak has already
1080
+ * been escalated.
1081
+ *
1082
+ * Why this exists: a repeating failure is de-duplicated above so the log stays
1083
+ * readable, but that same de-duplication is what let a Win11 session fail
1084
+ * **32 compactions in a row** without anyone noticing — every step logged
1085
+ * nothing new, and the conversation simply grew until it could never be
1086
+ * compacted again. De-duplicating the wording must not suppress the fact that
1087
+ * the failure is *persistent*.
1088
+ *
1089
+ * The escalation threshold is deliberately small: compaction is the recovery
1090
+ * path for every other failure, so three in a row means the session is no
1091
+ * longer self-healing and the operator has to hear it while a fix is still
1092
+ * cheap.
1093
+ */
1094
+ _consecutiveFailures = 0;
1095
+
1096
+ /** Whether the current failure streak has been escalated to a warning. */
1097
+ _streakEscalated = false;
1098
+
1099
+ /** Escalate once the streak reaches this many consecutive failures. */
1100
+ static CONSECUTIVE_FAILURE_WARN_AT = 3;
1101
+
988
1102
  /** Targets already warned about gating on the engine baseline. */
989
1103
  _reportedUnstatedThreshold = new Set();
990
1104
 
@@ -1014,13 +1128,16 @@ export class CompactionControlEngine extends BasicCompactionEngine {
1014
1128
  // the one payload that must stay bounded — a conversation large enough to
1015
1129
  // need compaction is one whose replay no longer fits, so the request that
1016
1130
  // was supposed to rescue the session could not be sent at all.
1017
- const effective = input;
1131
+ //
1132
+ // It is now opt-in (`replayFullConversation`), resolved below against the
1133
+ // same policy layer every other knob comes from.
1018
1134
  const target = conversationTarget(agent);
1019
1135
  // The window goes with the policy for the same reason it does in the gate:
1020
1136
  // an absolute retention has to be converted before the parent can compare
1021
1137
  // it, and a document stated in tokens must not resolve two different ways
1022
1138
  // on the two paths that apply it.
1023
1139
  const policy = target === undefined ? undefined : this.applyPolicy(target, await this.contextWindowOf(target, signal));
1140
+ const effective = summarizationInput(input, agent, policy?.replayFullConversation);
1024
1141
  const effort = await this.resolveEffort(target, signal);
1025
1142
  // The diagnostic, not the decision: `effort` below is exactly what it was
1026
1143
  // before this line existed, and the seam is still installed on the same
package/lib/policy.js CHANGED
@@ -123,6 +123,7 @@ const LAYER_KEYS = new Set([
123
123
  'maxTokens',
124
124
  'compactionRetries',
125
125
  'maxOverflowRetries',
126
+ 'replayFullConversation',
126
127
  ]);
127
128
 
128
129
  /** The only keys the document root may carry. */
@@ -281,6 +282,9 @@ function validateLayer(layer, path) {
281
282
  if (layer.maxTokens !== undefined) assertPositiveInt(`${path}.maxTokens`, layer.maxTokens);
282
283
  if (layer.headroomTokens !== undefined) assertNonNegativeInt(`${path}.headroomTokens`, layer.headroomTokens);
283
284
  if (layer.compactionRetries !== undefined) assertNonNegativeInt(`${path}.compactionRetries`, layer.compactionRetries);
285
+ if (layer.replayFullConversation !== undefined && typeof layer.replayFullConversation !== 'boolean') {
286
+ throw new CompactionConfigError(`${path}.replayFullConversation must be a boolean`);
287
+ }
284
288
  if (layer.maxOverflowRetries !== undefined) assertNonNegativeInt(`${path}.maxOverflowRetries`, layer.maxOverflowRetries);
285
289
  if (layer.summarizationModel !== undefined) assertModelRef(`${path}.summarizationModel`, layer.summarizationModel);
286
290
  if (layer.summarizationFallback !== undefined) assertFallbackChain(`${path}.summarizationFallback`, layer.summarizationFallback);
@@ -560,6 +564,12 @@ export function resolvePolicy(config, target, contextWindow) {
560
564
  headroomTokens: pick(layers, 'headroomTokens'),
561
565
  compactionRetries: pick(layers, 'compactionRetries') ?? 1,
562
566
  maxOverflowRetries: pick(layers, 'maxOverflowRetries') ?? 1,
567
+ /**
568
+ * Off unless a layer opts in. See `fullConversationMessages` for why the
569
+ * default must stay region-only: a session large enough to need compaction
570
+ * may not fit its own replay in the window.
571
+ */
572
+ replayFullConversation: pick(layers, 'replayFullConversation') ?? false,
563
573
  summarizationTarget,
564
574
  summarizationModel,
565
575
  /** Ordered fallback routes, already checked against `summarizationTarget`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magic6/dsh-compaction-policy-engine",
3
- "version": "0.5.11",
3
+ "version": "0.5.13",
4
4
  "description": "Layered, live-reloading context compaction policy for DeepSeek Harness: provider-level rules, field-by-field inheritance, ratio/token units and a settings panel on top of the official engine.",
5
5
  "type": "module",
6
6
  "main": "lib/companion.js",