@magic6/dsh-compaction-policy-engine 0.5.12 → 0.5.14

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/README.en.md CHANGED
@@ -55,8 +55,11 @@ A model can override `threshold` while still inheriting `retain`, `maxTokens`,
55
55
  window; `thresholdTokens` / `retainTokens` are absolute budgets. The plugin converts
56
56
  exactly back into the parent engine's ratio (`(tokens + 0.5) / window`) and **refuses to
57
57
  guess** when a route declares no window, naming the route in the error.
58
- - **Live reload.** The engine polls `settings.yaml` and the `compaction-control-settings`
59
- row every second; a policy edit applies to the next compaction without restarting DSH.
58
+ - **Live reload (configuration, not code).** The engine polls `settings.yaml` and the
59
+ `compaction-control-settings` row every second; a **policy edit** applies to the next
60
+ compaction without restarting DSH. This covers configuration only: **upgrading the plugin
61
+ itself always requires a restart**, because loaded modules are never replaced
62
+ (see [Live reload scope](#live-reload-scope)).
60
63
  The panel writes the same document. The engine mount row's own `config:` is read at load
61
64
  (see [Install and mount](#install-and-mount)).
62
65
  - **Partial settings document.** The `compaction-control:` section in `settings.yaml` is
@@ -86,6 +89,18 @@ Requirements: DSH `0.2.1-rc.x` / `0.2.2-rc.x`, Node.js 20+.
86
89
  dsh plugin --profile web add @magic6/dsh-compaction-policy-engine
87
90
  ```
88
91
 
92
+ > ⚠️ **Restart DSH after installing or upgrading.**
93
+ >
94
+ > `dsh plugin add` only writes the package to disk; a running process does not reload modules
95
+ > (`dsh-app-boot`: *"Package contents and loaded modules are not reloaded."*). Until you
96
+ > restart, the settings panel already reports the new version while the old code is still
97
+ > executing — **the version string does not prove the plugin is live**. Upgrading from
98
+ > `< 0.5.10` is the worst case: that bundle shipped its engine `disabled: true`, so without a
99
+ > restart there is no compaction at all and the trigger stays at the official 80% default.
100
+ >
101
+ > Verify after restarting: with `DSH_COMPACT_DEBUG=1` the log should show `[compact-debug]`
102
+ > lines, and a successful compaction logs `[compaction] FIRED`.
103
+
89
104
  The npm package includes `examples/standard-with-policy` for reference; the preset override
90
105
  rules below still apply. The `$PWD` commands in the web section assume a source checkout.
91
106
 
package/README.md CHANGED
@@ -49,9 +49,9 @@ models[] → providers{} → default
49
49
  `thresholdTokens` / `retainTokens` 是绝对预算。换算写回父类时使用
50
50
  `(tokens + 0.5) / window`,保证精确回到声明的数;路由没有声明窗口时**拒绝猜**,
51
51
  在真正需要策略的那一步报错并点名路由。
52
- - **热加载。** 引擎每秒轮询 `settings.yaml` 与 `compaction-control-settings` 行;策略修改在
53
- 下一次压缩生效,不需要重启。面板写的是同一份文档。引擎挂载行自己的 `config:` 在加载时读取
54
- (见[安装与挂载](#安装与挂载))。
52
+ - **热加载(配置,不含代码)。** 引擎每秒轮询 `settings.yaml` 与 `compaction-control-settings`
53
+ 行;**策略修改**在下一次压缩生效,不需要重启。但这只覆盖配置:**升级插件版本必须重启
54
+ DSH**,已加载的模块不会被替换(见[热加载范围](#热加载范围))。
55
55
  - **部分文档合并。** `settings.yaml` 的 `compaction-control:` 段与挂载行 `config:` **逐字段**
56
56
  合并(映射递归、数组整体替换),面板保存不会悄悄抹掉 profile 里的 `models[]` 层。
57
57
  - **设置面板。** 编辑全局层或某个供应商层,切换单位时不留下两个键,空隙过小时给出红字提示;
@@ -75,6 +75,17 @@ models[] → providers{} → default
75
75
  dsh plugin --profile web add @magic6/dsh-compaction-policy-engine
76
76
  ```
77
77
 
78
+ > ⚠️ **装完 / 升级完,必须重启 DSH 才会生效。**
79
+ >
80
+ > `dsh plugin add` 只把包写到磁盘;正在运行的进程不会重新加载模块
81
+ > (`dsh-app-boot`:*"Package contents and loaded modules are not reloaded."*)。
82
+ > 重启之前,设置页显示的版本号已经是新的,但跑的仍是旧代码——**版本号不能用来判断是否生效**。
83
+ > 从 `< 0.5.10` 升级尤其明显:旧 bundle 的引擎是 `disabled: true`,不重启就等于没有压缩,
84
+ > 触发点还停在官方默认的 80%。
85
+ >
86
+ > 重启后确认:`DSH_COMPACT_DEBUG=1` 下日志里应出现 `[compact-debug]` 行,压缩成功时出现
87
+ > `[compaction] FIRED`。
88
+
78
89
  npm 包里包含 `examples/standard-with-policy` 供参考;下面的 preset 覆盖规则仍然适用。
79
90
  web 小节里的 `$PWD` 命令假设使用源码检出。
80
91
 
@@ -175,6 +186,23 @@ dsh plugin --profile web add "$PWD/examples/standard-with-policy"
175
186
  行,所以面板修改和这一行的修改会在下一次压缩生效,不需要重启。**引擎挂载行**
176
187
  (`compaction-control`)的 `config:` 在插件加载时读取,改它需要重启。
177
188
 
189
+ > ⚠️ **升级插件本身必须重启 DSH。**
190
+ >
191
+ > 热加载只覆盖配置文档,**不覆盖代码**。DSH 的加载器把已安装的模块留在进程里:
192
+ > `dsh-app-boot` 的 `refresh()` 原文是 *"Package contents and loaded modules are not
193
+ > reloaded."*,设置豁免的路径也写着 *"Existing plugin instances are not reloaded by
194
+ > this operation."*。所以 `dsh plugin add <包>@<新版本>` 之后:
195
+ >
196
+ > - 磁盘上的版本号已经是新的(设置页、`package.json` 都会显示新版本),
197
+ > - 但**正在运行的进程里仍是旧代码**,压缩走的是旧逻辑。
198
+ >
199
+ > 这种错配特别难看出来,因为版本号是对的。判断依据只能是行为:重启后看日志里有没有
200
+ > `[compact-debug]` 行(需要 `DSH_COMPACT_DEBUG=1`)与 `[compaction] FIRED`。
201
+ >
202
+ > 具体到本插件,`< 0.5.10` 的 bundle 带着 `disabled: true`,升级后不重启会**继续没有
203
+ > 压缩**,而且触发的仍是官方引擎的 80% 默认值——看起来像"新版本没生效",实际是旧代码
204
+ > 还在跑。
205
+
178
206
  ### 阈值语义
179
207
 
180
208
  官方引擎的触发点是
@@ -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.12",
3
+ "version": "0.5.14",
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",