@magic6/dsh-compaction-policy-engine 0.5.16 → 0.5.18

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/CHANGELOG.md CHANGED
@@ -4,6 +4,75 @@ All notable changes to this project are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.5.18] - 2026-12-01
8
+
9
+ ### Added — every agent preset runs the policy engine, `/compact` included
10
+
11
+ dsh-web-app's presets (`cordis`, `minimal`, `ptc`, `standard`) each isolate
12
+ `ctx.compaction` around the stock `compaction-basic` and disable the host plane's
13
+ `command-compact` and `tool-result-pruner`. With the engine on the host plane, a
14
+ preset session got the policy for automatic compaction only; `/compact` ran the
15
+ stock engine at 0.16 / 65536 with no fallback chain, and pruning was skipped.
16
+ Installing the plugin and then picking the standard preset looked like the policy
17
+ did not apply.
18
+
19
+ The bundle now ships a `compaction-control-presets` row. At every start it finds
20
+ each preset's isolated compaction group and swaps the stock engine row for this
21
+ engine — in memory, through the loader's own entry update, so the preset
22
+ re-registers normally and nothing is persisted or snapshotted. A dsh upgrade that
23
+ changes a preset is picked up on the next start.
24
+
25
+ Measured on a real host: every settings save re-applies the composition and used
26
+ to hand the presets their stock options back (dismissing the welcome notice was
27
+ enough — the next `/compact` in a new standard session ran the stock engine,
28
+ 65536-token summary). The row re-makes its swap inside the loader's
29
+ `loader/patch-context` waterfall before a preset row restarts; if the host-plane
30
+ engine ever meets a preset realm on the stock engine it re-runs the takeover and
31
+ warns. In a standard-preset session after a re-sync: one gate diagnostic per
32
+ step, `FIRED` at the configured threshold, and `/compact` compacted through the
33
+ policy engine (8192-token summary).
34
+
35
+ The host-plane engine stands down for a realm that runs its own policy engine
36
+ (the preset's `agent/pre-step` still bubbles to it), so one engine acts per step
37
+ and the overflow retry budget is not doubled. Opt out with
38
+ `- id: compaction-control-presets / disabled: true`.
39
+
40
+ ### Changed — tests run against the libraries the host actually ships
41
+
42
+ The suite imported `@deepseek-ai/cordis` and `@deepseek-ai/dsh-compaction`
43
+ without declaring them; it worked only because npm hoists a peer's transitive
44
+ dependencies (under pnpm's isolated layout nine test files failed to import),
45
+ and npm resolved the prerelease peer range to `dsh-compaction-basic` 0.2.1-rc.5
46
+ while dsh 0.2.2-rc.5 ships 0.2.2-rc.5 — CI was testing against an older host
47
+ library than production runs. Both are now pinned devDependencies matching the
48
+ dsh 0.2.2-rc.5 install tree (cordis 4.1.0, schemastery 3.19.0, cosmokit 1.9.0).
49
+ Verified on macOS (node 26), Windows 11 with the desktop runtime (node 24,
50
+ pnpm) and in CI: 239/239, 0 skipped; headless e2e 2/2.
51
+
52
+ ### Added — the card and the badge say which presets were taken over
53
+
54
+ The engine's runtime report gains `presets` (and `preset`, for a realm mount);
55
+ the settings card and the badge popover show "Preset takeover: standard, minimal,
56
+ …" or "no agent presets". `/compact` logs `manual request … preset=<id>` naming
57
+ the engine that took it, and an engine logs `engine down` when its realm is
58
+ disposed — a session silently falling back to the stock engine used to leave no
59
+ trace.
60
+
61
+ ## [0.5.17] - 2026-11-30
62
+
63
+ ### Fixed — the engine is read the companion service with `ctx.get`, not `ctx.inject`
64
+
65
+ 0.5.16 fetched the companion's live policy with `ctx.inject([…])`. In cordis an
66
+ inject whose dependency never arrives leaves the fiber pending, and the host
67
+ then stops calling the engine at all — no gate check, no diagnostic. It only
68
+ shows on a profile whose companion row is absent (the bundle inserts one by
69
+ default), which is exactly what the e2e "unstated threshold" scenario strips
70
+ down, and that scenario went red in CI. The service is now read on demand with
71
+ `ctx.get`, so an engine without a companion row stays usable and keeps
72
+ reporting; the signature check in `policyFor` still picks the service up as
73
+ soon as the row mounts. The e2e scenario now asserts the engine states the
74
+ threshold and layer it applies.
75
+
7
76
  ## [0.5.16] - 2026-11-30
8
77
 
9
78
  ### Fixed — the policy reaches the engine through the loader, not a file poll
package/README.en.md CHANGED
@@ -78,7 +78,7 @@ A model can override `threshold` while still inheriting `retain`, `maxTokens`,
78
78
  "I think my context is nearly full" refusal loop observed in long sessions.
79
79
  - **Manual `/compact` is durable.** A client disconnect or reconnect does not kill a 20–40 s
80
80
  compaction transaction; the command reports the real reason when it cannot start.
81
- - **Tested.** 198 `node --test` cases across 13 files, including a real-bundle client
81
+ - **Tested.** 239 `node --test` cases across 15 files, including a real-bundle client
82
82
  evaluation, policy resolution, unit conversion, patch-file parsing and manual-compaction
83
83
  retention.
84
84
 
@@ -124,15 +124,18 @@ The package is a bundle. It mounts:
124
124
 
125
125
  ### Choose the realm first
126
126
 
127
- `ctx.compaction` is a **per-realm single-slot seam**. The engine must live in the same realm
128
- the agent resolves `ctx.compaction` from. Mounting it elsewhere creates a second engine; both
129
- subscribe to the bubbling `agent/pre-step`, and the lower threshold wins — the symptom is
130
- "compaction became unexpectedly early after installing the plugin".
127
+ `ctx.compaction` is a **per-realm single-slot seam**, and `/compact` (`command-compact`) resolves
128
+ it inside the agent's realm. dsh-web-app's four built-in presets (`cordis`, `minimal`, `ptc`,
129
+ `standard`) each run the stock `compaction-basic` inside an isolated `compaction` group and
130
+ disable the host plane's `command-compact` and `tool-result-pruner`. With the engine on the host
131
+ plane only, a preset session got the policy for *automatic* compaction (the `agent/pre-step`
132
+ event bubbles past the isolation) while `/compact` ran the stock engine at 0.16 / 65536 with no
133
+ fallback chain, and tool-result pruning was skipped.
131
134
 
132
135
  | profile | where the agent's engine lives | how to mount |
133
136
  |:--|:--|:--|
134
- | `headless` | the host plane (no agent preset) | the profile's `cordis.patch.yml`, overriding the bundle's engine row |
135
- | `web` | the **agent preset** (`dsh-web-app` disables the host-plane `compaction-basic`) | a preset declaration override; this repo ships an example bundle |
137
+ | `headless` | the host plane (no agent preset) | nothing; the bundle takes over |
138
+ | `web` / `desktop` | the **preset realm** | nothing; the bundle's `compaction-control-presets` row takes every preset over at each start (below) |
136
139
 
137
140
  #### Headless (host plane)
138
141
 
@@ -155,28 +158,38 @@ The bundle already inserts `compaction-control` (disabled). Override that row; d
155
158
  The loader key is **`disabled`**, not `disable`; the typo is silently dropped by the static
156
159
  config and looks like "I disabled it, but it is still enabled".
157
160
 
158
- #### Web (agent preset)
159
-
160
- DSH 0.2.2 presets are `@deepseek-ai/dsh-agent-preset` declarations carried by bundle
161
- patches. The legacy `$DSH_HOME/.agent-presets/<id>/agent.cordis.yml` directory is no longer
162
- read. The web agent realm isolates `ctx.compaction`, so a host-plane engine is not seen by
163
- the agent.
164
-
165
- This repo ships an example bundle that overrides the shipped `preset-standard` and replaces
166
- `compaction-basic` inside its `compaction` group with `compaction-control` (keeping
167
- `command-compact` and `tool-result-pruner`):
168
-
169
- ```bash
170
- dsh plugin --profile web add "$PWD"
171
- dsh plugin --profile web add "$PWD/examples/standard-with-policy"
172
- ```
173
-
174
- Restart the web app and open a new session. The example is a snapshot of the standard preset
175
- from DSH 0.2.2. If you have customized the standard preset, merge the `compaction` group into
176
- your own preset declaration instead of installing the example blindly (Creator mode can
177
- author that override). The file is
178
- [`examples/standard-with-policy/cordis.patch.yml`](examples/standard-with-policy/cordis.patch.yml);
179
- its header says the same.
161
+ #### Web / desktop (preset realm): taken over at start
162
+
163
+ The bundle's `compaction-control-presets` row (`lib/presets.js`) waits for the host tree to
164
+ settle, walks every `@deepseek-ai/dsh-agent-preset` row in the loader, finds the group with
165
+ `isolate.compaction: true`, and replaces the row named `@deepseek-ai/dsh-compaction-basic` with
166
+ `compaction-control` (this package's `./engine`, told its preset through `config.preset`). The
167
+ rewrite goes through the loader entry's own `update()`, so `AgentPreset` re-registers the
168
+ preset with a normal lifecycle and the registry, the mounted tree and the config editor agree
169
+ on one definition.
170
+
171
+ - **Nothing persisted, no snapshot.** Every start derives from the *installed* presets, so a dsh
172
+ upgrade that changes them is picked up next time. One log line per preset:
173
+ `presets: preset-standard taken-over (compaction-basic → compaction-control)`.
174
+ - **A composition re-sync cannot undo it.** Every settings save makes the include row re-apply
175
+ bundles + patch file, which used to hand every preset its stock options again (measured
176
+ 2026-12-01: dismissing the welcome notice put all four presets back on the stock engine, and
177
+ the next `/compact` in a new standard session ran it). The row hooks the loader's
178
+ `loader/patch-context` waterfall and re-makes the swap before the preset row restarts; if the
179
+ host-plane engine ever meets a preset realm on the stock engine anyway, it re-runs the
180
+ takeover and warns.
181
+ - **One engine acts per step.** The host-plane copy still hears the preset's `agent/pre-step`
182
+ (events bubble past isolation); it stands down when the agent's realm already runs a policy
183
+ engine, so nothing is measured twice and the overflow retry budget is not doubled.
184
+ - **Visible.** The settings card and the badge popover carry a "Preset takeover: standard,
185
+ minimal, …" line ("no agent presets" on headless), and every `/compact` logs
186
+ `manual request … preset=standard`, naming the engine that took it.
187
+ - **Opt out** with `- id: compaction-control-presets / disabled: true` in the profile patch.
188
+ - Your own presets are covered too, as long as their compaction group isolates `compaction`
189
+ and runs the stock engine; a `config` on the stock row is not carried over (the policy
190
+ document governs) and is named in the log. To take a preset over by hand, or with another
191
+ engine, override its declaration — [`examples/standard-with-policy`](examples/standard-with-policy/cordis.patch.yml)
192
+ shows that form; the takeover row skips a preset that already runs `compaction-control`.
180
193
 
181
194
  Two silent failure modes are easy to create:
182
195
 
@@ -356,7 +369,7 @@ the deployed policy.
356
369
  npm test
357
370
  ```
358
371
 
359
- 198 cases across 13 files, including:
372
+ 239 cases across 15 files, including:
360
373
 
361
374
  - `manual-compaction.test.js` — gate retry, UI signal abort, real failures, honest messages,
362
375
  and a contract assertion against the installed official package;
@@ -371,7 +384,16 @@ npm test
371
384
  `unstated-threshold.test.js` — summarizer fallback, patch entry shapes, settings merge,
372
385
  summary framing and the unstated-threshold warning;
373
386
  - `client-policy.test.js` / `client.test.js` — panel calculations, unit switching, provider
374
- layers, session badge, illegal value blocking, inline bundle consistency.
387
+ layers, session badge, illegal value blocking, inline bundle consistency, the engine
388
+ report line (tokens first when both units exist), the preset-takeover line;
389
+ - `presets.test.js` — the takeover as a pure transform (all four 0.2.2 preset shapes,
390
+ `!!js` nodes, already ours, non-isolated group, stock row with config), a fake loader
391
+ updated once and idempotently, a tree that never settles, the `loader/patch-context`
392
+ hook re-making the swap on re-sync, `reapply()`;
393
+ - `realm-deferral.test.js` — the host-plane engine standing down for a realm policy engine
394
+ (without measuring), not standing down for a stock engine / itself / no context, the
395
+ brand across module copies, runtime `preset`/`presets`, re-publish on the takeover
396
+ event, one `reapply` for a stock realm.
375
397
 
376
398
  ## Tested platforms
377
399
 
@@ -380,9 +402,9 @@ assumed:
380
402
 
381
403
  | Platform | Version | Result | How |
382
404
  |:--|:--|:--|:--|
383
- | macOS | 26.6.2 arm64 | ✅ 198/198 | full `npm test` on the machine |
384
- | Windows | 11 22631 x64 | ✅ 198/198 | full `npm test` on real hardware |
385
- | Linux | ubuntu-latest x64 | ✅ 198/198 | GitHub Actions (Node 20 / 22) |
405
+ | macOS | 26.12.1 arm64 | ✅ 239/239 | full `npm test` on the machine (2026-12-01, 0.5.18) |
406
+ | Windows | 11 22631 x64 | ✅ 239/239 | full run on real hardware, desktop runtime node 24.21 + pnpm (2026-12-01, 0.5.18) |
407
+ | Linux | ubuntu-latest x64 | ✅ 239/239 | GitHub Actions (Node 20 / 22, 0.5.18) |
386
408
 
387
409
  The Windows row was added on 2026-11-25, when CI ran `ubuntu-latest` only and most
388
410
  users were on Windows. The first real Windows run found two Windows-only failures (POSIX path assertions,
package/README.md CHANGED
@@ -64,7 +64,7 @@ models[] → providers{} → default
64
64
  用量,不得因为自认为「上下文快满了」而停止、缩短或移交工作。
65
65
  - **手动 `/compact` 是持久工作。** 客户端断线/重连不会杀死一次 20–40 秒的压缩事务;无法开始
66
66
  时如实报告原因,不把空锁说成「已有压缩在跑」。
67
- - **有测试。** 198 个 `node --test` 用例,分布在 13 个文件,覆盖真实 bundle 渲染、三层解析、
67
+ - **有测试。** 239 个 `node --test` 用例,分布在 15 个文件,覆盖真实 bundle 渲染、三层解析、
68
68
  单位换算、补丁文件解析和手动压缩保留量。
69
69
 
70
70
  ## 安装与挂载
@@ -127,15 +127,17 @@ super(ctx, "compaction") // 第二个 -> 'service "compaction" has been regist
127
127
 
128
128
  ### 先确定挂载平面
129
129
 
130
- `ctx.compaction` 是**按 realm 解析的单槽服务**。`isolate: compaction: true` 让每个 preset realm
131
- 各有一份,所以 preset 宿主里会同时存在「宿主平面一个 + preset 内一个」——两个 context,不冲突。
132
- 宿主平面的引擎服务 `headless` 与解析到宿主平面的 agent;想让策略进到某个 preset 内部,
133
- 替换它自己的 `compaction` 组(见下)。
130
+ `ctx.compaction` 是**按 realm 解析的单槽服务**。`isolate: compaction: true` 让每个预设 realm
131
+ 各有一份:预设会话里同时存在「宿主平面一个 + 预设内一个」,而 `/compact`(`command-compact`)
132
+ 只认 realm 里的那一个。dsh-web-app 的四个内置预设(cordis / minimal / ptc / standard)都在隔离的
133
+ compaction 组里放原版 `compaction-basic`,并把宿主平面的 `command-compact` 与
134
+ `tool-result-pruner` 停掉——所以只把引擎挂在宿主平面时,预设会话的**自动**压缩走策略
135
+ (`agent/pre-step` 冒泡),`/compact` 却走原版引擎(0.16 / 65536、无回退链),剪枝也被跳过。
134
136
 
135
137
  | profile | agent 的压缩引擎属于谁 | 需要做什么 |
136
138
  |:--|:--|:--|
137
- | `headless` | 宿主平面(没有 preset) | 无。bundle 已接管 |
138
- | `web` / `desktop` | **agent preset**(宿主平面的 `compaction-basic` 由 `dsh-web-app` 停用) | 宿主平面已接管;要让 preset 内部也用策略,需覆盖 preset 声明 |
139
+ | `headless` | 宿主平面(没有预设) | 无。bundle 已接管 |
140
+ | `web` / `desktop` | **预设 realm** | 无。bundle 的 `compaction-control-presets` 行每次启动接管所有预设(见下) |
139
141
 
140
142
  #### headless(宿主平面)
141
143
 
@@ -153,25 +155,31 @@ super(ctx, "compaction") // 第二个 -> 'service "compaction" has been regist
153
155
  loader 认的键是 **`disabled`**,不是 `disable`;写错不会报错,会被静态配置静默丢掉
154
156
  (看起来停用了,其实还启用)。
155
157
 
156
- #### web(agent preset)
157
-
158
- DSH 0.2.2 的 preset 是 bundle patch 里的 `@deepseek-ai/dsh-agent-preset` 声明。旧目录
159
- `$DSH_HOME/.agent-presets/<id>/agent.cordis.yml` 已经不再被读取。web 的 agent realm 隔离了
160
- `ctx.compaction`,宿主平面的引擎它看不到。
161
-
162
- 本仓库带一个示例 bundle:覆盖 `preset-standard`,把 `compaction` 组里的 `compaction-basic`
163
- 换成 `compaction-control`,并保留 `command-compact` 与 `tool-result-pruner`:
164
-
165
- ```bash
166
- dsh plugin --profile web add "$PWD"
167
- dsh plugin --profile web add "$PWD/examples/standard-with-policy"
168
- ```
169
-
170
- 重启 web app,新开会话验证。示例是 DSH 0.2.2 标准 preset 的快照;如果你改过标准 preset,请把
171
- `compaction` 组的手动合并进你自己的 preset 声明,而不是盲目安装示例(Creator 模式可以代写
172
- 这个覆盖)。文件在
173
- [`examples/standard-with-policy/cordis.patch.yml`](examples/standard-with-policy/cordis.patch.yml),
174
- 头部也写了同样的提醒。
158
+ #### web / desktop(预设 realm):启动时接管
159
+
160
+ bundle 里的 `compaction-control-presets` 行(`lib/presets.js`)等宿主树稳定后,遍历 loader 里所有
161
+ `@deepseek-ai/dsh-agent-preset` 行,找到 `isolate.compaction: true` 的组,把其中
162
+ `name: '@deepseek-ai/dsh-compaction-basic'` 的那一行换成 `compaction-control`(本包的 `./engine`,
163
+ `config.preset` 记下所属预设),再经 loader 自己的 `entry.update()` 走 `AgentPreset` 的正常
164
+ 重注册——注册表、挂载树、配置编辑器看到的是同一份定义。
165
+
166
+ - **不落盘、不快照。** 每次启动都按**已安装**的预设重新推导;dsh 升级改了预设,下一次启动自动
167
+ 跟上。日志一行一个预设:`presets: preset-standard taken-over (compaction-basic → compaction-control)`。
168
+ - **重新同步冲不掉。** 任何设置保存都会让 include 行重新应用整份组合(bundle + patch 文件),
169
+ 内存里的改动本来会被原版声明覆盖(2026-12-01 实测:点掉"预览版说明"就把四个预设全部打回
170
+ 原版,之后新建的标准会话 `/compact` 走了原版引擎)。接管行挂在 loader 的
171
+ `loader/patch-context` waterfall 上,在预设行重启前把替换重做一遍;宿主平面引擎若仍遇到跑
172
+ 原版的预设 realm,会再触发一次接管并告警。
173
+ - **同一步只有一个引擎行动。** 预设 realm 里有了自己的策略引擎后,宿主平面那份仍听得见
174
+ `agent/pre-step`(事件冒泡不受隔离影响);它检测到 agent 的 realm 已是策略引擎就让路——不
175
+ 重复测量,不把溢出重试次数翻倍。
176
+ - **看得见。** 设置卡片与徽标弹层多一行"预设接管:standard, minimal, …"(headless 显示"无
177
+ 预设");每次 `/compact` 在日志里有一行 `manual request … preset=standard`,说明是哪个引擎接的。
178
+ - **退出。** profile patch 里写 `- id: compaction-control-presets / disabled: true`。
179
+ - 自己声明的预设同样适用,只要它的 compaction 组隔离了 `compaction` 并跑原版引擎;组里原版行
180
+ 带的 `config` 不会搬到策略引擎(策略文档为准),日志会点名。想手工接管或换别的引擎,仍可
181
+ 覆盖预设声明,[`examples/standard-with-policy`](examples/standard-with-policy/cordis.patch.yml)
182
+ 是这种写法的样例——接管行遇到已换成 `compaction-control` 的预设会跳过。
175
183
 
176
184
  两种静默坏组合:
177
185
 
@@ -342,7 +350,7 @@ Models 页脚 → **Compaction policy** 卡片:
342
350
  npm test
343
351
  ```
344
352
 
345
- 198 个用例,分布在 13 个文件,包括:
353
+ 239 个用例,分布在 15 个文件,包括:
346
354
 
347
355
  - `manual-compaction.test.js` — 闸门重试、UI 信号中断、真实失败、诚实消息,以及对已安装官方包
348
356
  的契约断言;
@@ -355,7 +363,13 @@ npm test
355
363
  `unstated-threshold.test.js` — 摘要回退、补丁 entry 形状、settings 合并、摘要框架与
356
364
  未声明阈值告警;
357
365
  - `client-policy.test.js` / `client.test.js` — 面板计算、单位切换、供应商层、会话徽标、
358
- 非法值拦截、内联 bundle 一致性。
366
+ 非法值拦截、内联 bundle 一致性、引擎上报行(双单位 token 优先)、预设接管行;
367
+ - `presets.test.js` — 预设接管的纯变换(rc.5 四种形状、`!!js` 节点、已接管、非隔离组、
368
+ 原版带 config)、假 loader 只更新一次且幂等、树不稳定超时仍接管、`loader/patch-context`
369
+ 钩子在重新同步时重做替换、`reapply()`;
370
+ - `realm-deferral.test.js` — 宿主平面引擎对 realm 内策略引擎让路(且不测量)、原版/自身/
371
+ 无 ctx 不让路、品牌跨模块副本、runtime 的 `preset`/`presets`、接管事件触发重发布、
372
+ 原版 realm 触发一次 reapply。
359
373
 
360
374
  ## 支持的平台
361
375
 
@@ -363,9 +377,9 @@ npm test
363
377
 
364
378
  | 平台 | 版本 | 结果 | 验证方式 |
365
379
  |:--|:--|:--|:--|
366
- | macOS | 26.6.2 arm64 | ✅ 198/198 | 本机全量 `npm test` |
367
- | Windows | 11 22631 x64 | ✅ 198/198 | 真机全量 `npm test` |
368
- | Linux | ubuntu-latest x64 | ✅ 198/198 | GitHub Actions(Node 20 / 22) |
380
+ | macOS | 26.12.1 arm64 | ✅ 239/239 | 本机全量 `npm test`(2026-12-01,0.5.18) |
381
+ | Windows | 11 22631 x64 | ✅ 239/239 | 真机全量,桌面版运行时 node 24.21 + pnpm(2026-12-01,0.5.18) |
382
+ | Linux | ubuntu-latest x64 | ✅ 239/239 | GitHub Actions(Node 20 / 22,0.5.18) |
369
383
 
370
384
  Windows 一行是 2026-11-25 才加上的:在那之前 CI 只跑 `ubuntu-latest`,
371
385
  而用户主要在 Windows 上用。第一次在真机跑就抓出两个 Windows 独有的测试
package/cordis.patch.yml CHANGED
@@ -66,6 +66,15 @@
66
66
  - id: compaction-control
67
67
  name: '@magic6/dsh-compaction-policy-engine/engine'
68
68
 
69
+ # Preset takeover: dsh-web-app's presets each run the stock engine inside an
70
+ # isolated `compaction` group, so `/compact` there ignored the policy (and the
71
+ # host plane has no pruner). This row swaps that one line in every declared
72
+ # preset, in memory, at every start — see lib/presets.js. Opt out with
73
+ # `- id: compaction-control-presets / disabled: true`.
74
+ - insert:
75
+ - id: compaction-control-presets
76
+ name: '@magic6/dsh-compaction-policy-engine/presets'
77
+
69
78
  - insert:
70
79
  - id: compaction-control-settings
71
80
  name: '@magic6/dsh-compaction-policy-engine'
package/lib/client.js CHANGED
@@ -50,6 +50,9 @@ window.__ModuleLoader__.load({
50
50
  engineMismatch: '设置与引擎不一致:改动没有送达策略引擎(引擎未重载,或引擎未挂载)。',
51
51
  engineMissing: '未收到策略引擎的状态:引擎未挂载,或配置没有送达。上方只是保存的文档,不保证在生效。',
52
52
  engineUnknown: '—',
53
+ presetsLabel: '预设接管',
54
+ presetsHint: '这些预设的压缩组已换成策略引擎,其中的 /compact 也走策略',
55
+ presetsNone: '无预设(headless 组合)',
53
56
  // ── 摘要模型的回退链与安全余量 ────────────────────────────────
54
57
  headroom: '安全余量(token)',
55
58
  headroomHint: '留空沿用下层',
@@ -145,6 +148,9 @@ window.__ModuleLoader__.load({
145
148
  engineMismatch: 'Settings and engine disagree: the change never reached the policy engine (not reloaded, or not mounted).',
146
149
  engineMissing: 'No report from the policy engine: it is not mounted, or the settings never reached it. The numbers above are only the saved document.',
147
150
  engineUnknown: '—',
151
+ presetsLabel: 'Preset takeover',
152
+ presetsHint: "these presets' compaction groups run the policy engine, so /compact follows the policy there too",
153
+ presetsNone: 'No agent presets in this composition',
148
154
  // ── Summarization fallback chain and reserve ──────────────────
149
155
  headroom: 'Reserve (tokens)',
150
156
  headroomHint: 'blank inherits the layer below',
@@ -735,11 +741,16 @@ window.__ModuleLoader__.load({
735
741
  { thresholdRatio: snapshot?.value?.default?.threshold, thresholdTokens: snapshot?.value?.default?.thresholdTokens },
736
742
  t,
737
743
  );
744
+ const presets = presetsText(engineState?.value, t);
738
745
  return jsx.jsxs('div', {
739
746
  className: 'ccWrap cccCard',
740
747
  children: [
741
748
  jsx.jsx('span', { className: 'ccTitle', children: t('title') }),
742
749
  jsx.jsx('p', { className: 'ccHint', children: t('hint') }),
750
+ presets === null ? null : jsx.jsx('p', {
751
+ className: 'cccEngine',
752
+ children: `${t('presetsLabel')}: ${presets} — ${t('presetsHint')}`,
753
+ }),
743
754
  jsx.jsxs('p', {
744
755
  className: engine.level === 'missing' || engine.level === 'warn' ? 'cccEngine cccEngineErr' : 'cccEngine',
745
756
  children: [
@@ -1223,13 +1234,31 @@ window.__ModuleLoader__.load({
1223
1234
  */
1224
1235
  function engineReport(runtime, view, t) {
1225
1236
  if (runtime === undefined) return { level: 'missing', text: t('engineUnknown') };
1226
- const text = [ratioText(runtime.threshold), ratioText(runtime.retain), runtime.source].filter(Boolean).join(' · ');
1227
- const declared = view.thresholdRatio ?? view.thresholdTokens ?? undefined;
1228
- const applied = runtime.threshold ?? runtime.thresholdTokens ?? undefined;
1237
+ // Either unit, tokens first — the resolver's own precedence. A document can
1238
+ // carry both (a ratio from the composition base under a token override
1239
+ // the card saved); showing the ratio would name the number the engine
1240
+ // is *not* applying. And a token-only policy must not degrade to a bare
1241
+ // source name.
1242
+ const budget = (ratio, tokens) => (tokens !== undefined ? tokenText(tokens) : ratio !== undefined ? ratioText(ratio) : null);
1243
+ const text = [budget(runtime.threshold, runtime.thresholdTokens), budget(runtime.retain, runtime.retainTokens), runtime.source].filter(Boolean).join(' · ');
1244
+ const declared = view.thresholdTokens ?? view.thresholdRatio ?? undefined;
1245
+ const applied = runtime.thresholdTokens ?? runtime.threshold ?? undefined;
1229
1246
  const mismatch = declared !== undefined && applied !== undefined && declared !== applied;
1230
1247
  return { level: mismatch ? 'warn' : 'ok', text, mismatch };
1231
1248
  }
1232
1249
 
1250
+ /**
1251
+ * Which agent presets had their stock engine swapped for this one.
1252
+ *
1253
+ * `runtime.presets` is written by the preset-takeover row through the
1254
+ * engine's report; `undefined` means that row is not mounted, and the
1255
+ * line is omitted rather than shown empty.
1256
+ */
1257
+ function presetsText(runtime, t) {
1258
+ if (!Array.isArray(runtime?.presets)) return null;
1259
+ return runtime.presets.length === 0 ? t('presetsNone') : runtime.presets.join(', ');
1260
+ }
1261
+
1233
1262
  function PolicyRow(props) {
1234
1263
  const { label, value, source, hint, unit, t } = props;
1235
1264
  return jsx.jsxs('div', {
@@ -1674,6 +1703,13 @@ window.__ModuleLoader__.load({
1674
1703
  value: engineReport(engineState?.value, view, t).text,
1675
1704
  t,
1676
1705
  }),
1706
+ presetsText(engineState?.value, t) === null ? null : jsx.jsx(PolicyRow, {
1707
+ key: 'presets',
1708
+ label: t('presetsLabel'),
1709
+ hint: t('presetsHint'),
1710
+ value: presetsText(engineState?.value, t),
1711
+ t,
1712
+ }),
1677
1713
  ],
1678
1714
  }),
1679
1715
  (() => {
package/lib/index.js CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  toBasicConfig,
33
33
  } from './policy.js';
34
34
  import { isVolatile } from '@deepseek-ai/cosmokit';
35
- import { POLICY_SERVICE, policyDocumentOf, plainConfig, runtimeSchema } from './settings.js';
35
+ import { POLICY_SERVICE, PRESETS_SERVICE, policyDocumentOf, plainConfig, runtimeSchema } from './settings.js';
36
36
  import { patchFilePaths, settingsFilePath, watchPatchFile, watchSettingsFile } from './settings-file.js';
37
37
 
38
38
  /** cosmokit 的共享 volatile 写协议;设置页 describe 读取的就是这个单元格。 */
@@ -445,13 +445,28 @@ const CONTEXT_POLICY_ORDER = 100;
445
445
  * one session can change models mid-conversation and each model may carry its
446
446
  * own threshold and summarization route.
447
447
  */
448
+ /** Brand for "this realm's `compaction` is a policy engine", safe across module copies. */
449
+ const POLICY_ENGINE = Symbol.for('compactionControl.policyEngine');
450
+
448
451
  export class CompactionControlEngine extends BasicCompactionEngine {
452
+ /** See {@link POLICY_ENGINE}; read off a constructor, so a second copy of this package still matches. */
453
+ static [POLICY_ENGINE] = true;
454
+ /**
455
+ * Identity through cordis's traceable proxy: `ctx.get('compaction')` hands out
456
+ * a proxy around the service, never the instance itself, so `===` would tell
457
+ * an engine that it is a stranger to its own realm. A token read off the
458
+ * object reaches the target and does not.
459
+ */
460
+ instanceToken = Symbol('CompactionControlEngine');
461
+
449
462
  /**
450
463
  * This plugin's config schema. Must be declared explicitly: statics are
451
464
  * inherited, so omitting it would make the loader validate this plugin's
452
465
  * document against the *parent's* schema (see the schema's own comment).
453
466
  */
454
467
  static Config = z.object({
468
+ /** The agent preset whose realm this engine serves; written by the takeover row. */
469
+ preset: z.string(),
455
470
  // 根字段判活(`.volatile()`):dsh-settings 只把带 volatile 字段的 entry
456
471
  // 供到设置平面(volatileForm),而 schemastery 不允许"字典里再嵌 volatile
457
472
  // 字段"($.providers.*.threshold ... without an enclosing volatile field),
@@ -504,11 +519,19 @@ export class CompactionControlEngine extends BasicCompactionEngine {
504
519
  reportedWarnings = new Set();
505
520
 
506
521
  /**
507
- * The companion row's live document, or undefined until that row mounts.
522
+ * The companion row's live document, or undefined until that row is active.
508
523
  *
509
- * @type {{ current: () => object | undefined, runtimeRef?: object } | undefined}
524
+ * Read with `ctx.get` on demand rather than `ctx.inject`: an inject whose
525
+ * dependency never arrives (a profile without the companion row) keeps this
526
+ * fiber pending, and the host then never calls the engine at all — measured
527
+ * 2026-11-30 on the e2e "unstated threshold" scenario. `get` costs nothing
528
+ * and answers as soon as the row is up.
529
+ *
530
+ * @returns {{ current: () => object | undefined, runtimeRef?: object } | undefined}
510
531
  */
511
- _livePolicy;
532
+ livePolicy() {
533
+ return this.ctx.get?.(POLICY_SERVICE);
534
+ }
512
535
 
513
536
  /** `JSON.stringify` of the live document last resolved, so a card save between two steps is noticed. */
514
537
  _liveSignature;
@@ -520,11 +543,17 @@ export class CompactionControlEngine extends BasicCompactionEngine {
520
543
  constructor(ctx, config = {}) {
521
544
  // Resolve first: a malformed policy must fail here, with this plugin's own
522
545
  // diagnostics, rather than at the first compaction.
523
- const controlConfig = resolveConfig(plainConfig(config));
546
+ // `preset` names the agent preset whose realm this engine serves; the
547
+ // takeover row writes it. It is not a policy field, so it leaves the
548
+ // document before `resolveConfig` (which rejects unknown roots) sees it.
549
+ const { preset, ...document } = plainConfig(config) ?? {};
550
+ const presetId = typeof preset === 'string' && preset !== '' ? preset : undefined;
551
+ const controlConfig = resolveConfig(document);
524
552
  // Seed the parent with the global default layer, so inherited code paths that
525
553
  // read `this.config` without a routed request already see the right numbers.
526
554
  const baseline = resolvePolicy(controlConfig, { provider: '', model: '' });
527
555
  super(ctx, { ...toBasicConfig(baseline), auto: controlConfig.auto });
556
+ this.preset = presetId;
528
557
  // Keep the parent's *own* resolved shape (`headroomTokens` above all, which it
529
558
  // defaults to 65536): every later `applyPolicy` rebuild starts from it, because
530
559
  // `toBasicConfig` names only the fields this plugin owns.
@@ -532,18 +561,15 @@ export class CompactionControlEngine extends BasicCompactionEngine {
532
561
  this.controlConfig = controlConfig;
533
562
  this.baseConfig = controlConfig;
534
563
 
535
- // The companion row (`compaction-control-settings`) owns the user's document
536
- // and this row mounts first, so its service is injected rather than read: the
537
- // callback runs as soon as that row is up, and again if it ever remounts. Its
538
- // cells are updated in place by the loader on every card save, so this one
539
- // hand-off is a live view — no file, no poll, no path to derive.
564
+ // The companion row (`compaction-control-settings`) owns the user's document.
565
+ // Its cells are updated in place by the loader on every card save, so reading
566
+ // the service (`livePolicy()`) is a live view — no file, no poll, no path to
567
+ // derive. It is picked up on the next policy lookup, and again if the row
568
+ // remounts; see `livePolicy()` for why this is not an `inject`.
540
569
  //
541
570
  // The file readers below stay as the fallback for a profile that mounts no
542
571
  // companion row, and for an edit made straight to the patch file.
543
- ctx.inject([POLICY_SERVICE], (policyCtx) => {
544
- this._livePolicy = policyCtx[POLICY_SERVICE];
545
- this.reloadPolicy();
546
- });
572
+ if (this.livePolicy() !== undefined) this.reloadPolicy();
547
573
 
548
574
  // The running host's own facts, provided before any profile row mounts
549
575
  // (`boot()` runs `prepare(hostCtx)` — which provides `profileContext` —
@@ -621,14 +647,30 @@ export class CompactionControlEngine extends BasicCompactionEngine {
621
647
  // from outside (the card renders either way, and a disabled or auto:false
622
648
  // engine prints no gate diagnostic at all). The fiber name says *which* mount
623
649
  // this is — a host-plane and a preset-realm engine print the same numbers.
650
+ // A realm mount (a preset's compaction group) says so: the host-plane engine
651
+ // and a preset one print the same numbers, and only this tells them apart.
624
652
  const startup =
625
- `[compaction] engine up: fiber=${this.ctx.fiber?.name} ` +
653
+ `[compaction] engine up: fiber=${this.ctx.fiber?.name}${preset === undefined ? '' : ` preset=${preset}`} ` +
626
654
  `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
627
655
  `retain=${declaredText(this.controlConfig.default.retain, this.controlConfig.default.retainTokens)} auto=${controlConfig.auto} ` +
628
656
  `thinking=${THINKING_OFF} source=${this._fileOrigin}`;
629
657
  process.stderr.write(`${startup}\n`);
630
658
  // The Windows desktop host keeps no stderr; its own log plane is the logger.
631
659
  this.ctx.logger?.info?.(startup);
660
+ // And one line on the way out. An engine that is disposed while sessions
661
+ // still route to its realm leaves them on whatever the realm resolves
662
+ // next — usually the stock engine — and nothing else says so.
663
+ // The preset-takeover row finishes after this engine is up; its report names
664
+ // the presets in `runtime.presets`, so the engines re-publish when it does.
665
+ ctx.effect(() => ctx.root.on('compaction-control/presets', () => this.publishRuntime()), 'compaction-control: presets report');
666
+ ctx.effect(
667
+ () => () => {
668
+ const shutdown = `[compaction] engine down: fiber=${this.ctx.fiber?.name}${preset === undefined ? '' : ` preset=${preset}`}`;
669
+ process.stderr.write(`${shutdown}\n`);
670
+ this.ctx.logger?.info?.(shutdown);
671
+ },
672
+ 'compaction-control: engine down',
673
+ );
632
674
  }
633
675
 
634
676
  /**
@@ -639,7 +681,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
639
681
  * quietly grows past the threshold the operator believes is in force.
640
682
  */
641
683
  publishRuntime() {
642
- const ref = this._livePolicy?.runtimeRef;
684
+ const ref = this.livePolicy()?.runtimeRef;
643
685
  if (ref === undefined || typeof ref[VOLATILE_WRITE] !== 'function') return;
644
686
  const declared = this.controlConfig.default;
645
687
  ref[VOLATILE_WRITE](
@@ -651,11 +693,70 @@ export class CompactionControlEngine extends BasicCompactionEngine {
651
693
  auto: this.controlConfig.auto,
652
694
  source: this._fileOrigin,
653
695
  fiber: this.ctx.fiber?.name ?? '',
696
+ preset: this.preset,
697
+ presets: this.ctx.get?.(PRESETS_SERVICE)?.takenOver,
654
698
  updatedAt: Date.now(),
655
699
  }),
656
700
  );
657
701
  }
658
702
 
703
+ /**
704
+ * Heal a preset realm that is back on the stock engine.
705
+ *
706
+ * The takeover row re-applies its swap inside the loader's own re-sync
707
+ * hook, so this should never fire; if the loader's internals ever change
708
+ * under it, a preset session would silently run `/compact` on the stock
709
+ * engine again — the exact state this package exists to end. The host-plane
710
+ * engine is the one place that can notice (it hears every preset's
711
+ * pre-step), so it re-runs the takeover and says so, once per realm.
712
+ */
713
+ healStockRealm(agent) {
714
+ const engine = agent?.ctx?.get?.('compaction');
715
+ if (engine === undefined || engine?.constructor?.[POLICY_ENGINE] === true) return;
716
+ const takeover = this.ctx.get?.(PRESETS_SERVICE);
717
+ if (takeover?.reapply === undefined || takeover.healed?.has?.(agent.ctx)) return;
718
+ (takeover.healed ??= new Set()).add(agent.ctx);
719
+ const preset = this.ctx.get?.('agentPresets')?.generationFor?.(agent.ctx)?.mount?.presetId;
720
+ const line = `presets: ${preset ?? 'a preset'} realm runs the stock engine; re-applying the takeover`;
721
+ process.stderr.write(`[compaction] ${line}\n`);
722
+ this.ctx.logger?.warn?.(line);
723
+ Promise.resolve(takeover.reapply()).catch((error) => {
724
+ this.ctx.logger?.warn?.(`presets: re-apply failed: ${error instanceof Error ? error.message : String(error)}`);
725
+ });
726
+ }
727
+
728
+ /**
729
+ * Whether another policy engine owns compaction for this agent's realm.
730
+ *
731
+ * A preset realm runs its own copy of this engine once the takeover row has
732
+ * replaced its stock engine, and this host-plane copy still hears the realm's
733
+ * `agent/pre-step` (events bubble past service isolation). Both would act:
734
+ * the second measurement is wasted and the overflow retry budget doubles.
735
+ * The realm's engine wins; this one stands down for that agent.
736
+ *
737
+ * @param agent - The session's agent.
738
+ * @returns True when a *different* policy engine is the agent's `compaction`.
739
+ */
740
+ deferredToRealm(agent) {
741
+ let engine;
742
+ try {
743
+ engine = agent?.ctx?.get?.('compaction');
744
+ } catch {
745
+ return false;
746
+ }
747
+ if (engine?.constructor?.[POLICY_ENGINE] !== true) return false;
748
+ return engine.instanceToken !== this.instanceToken;
749
+ }
750
+
751
+ /**
752
+ * Price a proposed request header (model switch). Stand down for a realm that
753
+ * runs its own policy engine, exactly like the pressure gate.
754
+ */
755
+ async compactPressure(agent, header, signal, requireBelowThreshold) {
756
+ if (this.deferredToRealm(agent)) return null;
757
+ return super.compactPressure(agent, header, signal, requireBelowThreshold);
758
+ }
759
+
659
760
  /**
660
761
  * Re-resolve the operator's document and drop cached policies.
661
762
  *
@@ -677,7 +778,8 @@ export class CompactionControlEngine extends BasicCompactionEngine {
677
778
  let origin = 'composition';
678
779
  // Recorded before validation: a live document that is refused must not be
679
780
  // re-examined on every step until it changes again.
680
- this._liveSignature = this._livePolicy === undefined ? undefined : JSON.stringify(this._livePolicy.current());
781
+ const livePolicy = this.livePolicy();
782
+ this._liveSignature = livePolicy === undefined ? undefined : JSON.stringify(livePolicy.current());
681
783
  // `_fileOrigin` says where `_fileSection` came from, and it is the only
682
784
  // honest answer: when `settings.yaml` is absent the watcher still reports
683
785
  // the composition as a fallback section, so testing `_fileSection` alone
@@ -687,11 +789,11 @@ export class CompactionControlEngine extends BasicCompactionEngine {
687
789
  if (this._fileSection !== undefined && this._fileOrigin === 'settings.yaml') {
688
790
  document = overlayDocument(document, this._fileSection);
689
791
  origin = 'settings.yaml';
690
- } else if (this._livePolicy !== undefined) {
792
+ } else if (livePolicy !== undefined) {
691
793
  // The companion row's own config, as the loader resolved it: the bundle's
692
794
  // composition under the user's override. Overlaid for the same reason as
693
795
  // the file layers — a partial save must not drop the rest.
694
- const live = this._livePolicy.current();
796
+ const live = livePolicy.current();
695
797
  if (live !== undefined) {
696
798
  document = overlayDocument(document, live);
697
799
  origin = 'companion';
@@ -735,8 +837,9 @@ export class CompactionControlEngine extends BasicCompactionEngine {
735
837
  // hear (`loader/volatile-update` is scoped to the companion's own fiber),
736
838
  // so the live document is compared by value here — a few small objects per
737
839
  // step — and any difference is resolved before the cache is consulted.
738
- if (this._livePolicy !== undefined) {
739
- const signature = JSON.stringify(this._livePolicy.current());
840
+ const livePolicy = this.livePolicy();
841
+ if (livePolicy !== undefined) {
842
+ const signature = JSON.stringify(livePolicy.current());
740
843
  if (signature !== this._liveSignature) this.reloadPolicy();
741
844
  }
742
845
  const key = `${target.provider}\u0000${target.model}\u0000${contextWindow ?? ''}`;
@@ -855,6 +958,8 @@ export class CompactionControlEngine extends BasicCompactionEngine {
855
958
  * remain the parent's.
856
959
  */
857
960
  async compactIfNeeded(agent, trigger, signal) {
961
+ if (this.deferredToRealm(agent)) return null;
962
+ this.healStockRealm(agent);
858
963
  const target = conversationTarget(agent);
859
964
  let thresholdTokens;
860
965
  let result;
@@ -982,6 +1087,13 @@ export class CompactionControlEngine extends BasicCompactionEngine {
982
1087
  // The request signal governs only the decision to *start*: a caller that
983
1088
  // already gave up must not open a transaction nobody is waiting for.
984
1089
  signal?.throwIfAborted?.();
1090
+ // One line per `/compact`, before any refusal: which engine the realm's
1091
+ // command reached is otherwise invisible — a preset still on the stock
1092
+ // engine and one already taken over look identical from the chat.
1093
+ const request =
1094
+ `[compaction] manual request: fiber=${this.ctx.fiber?.name}${this.preset === undefined ? '' : ` preset=${this.preset}`} agent=${agent?.id ?? '?'}`;
1095
+ process.stderr.write(`${request}\n`);
1096
+ this.ctx.logger?.info?.(request);
985
1097
  // A running turn is not a closing gate; waiting for it would stall the
986
1098
  // command for the length of the turn and then still refuse. Say so at once.
987
1099
  if (agent?.status === 'running') {
package/lib/presets.js ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Take over the compaction group of every declared agent preset.
3
+ *
4
+ * `ctx.compaction` resolves per realm. dsh-web-app's four presets (`cordis`,
5
+ * `minimal`, `ptc`, `standard`) each declare a `compaction` group with
6
+ * `isolate: { compaction: true }` around the stock
7
+ * `@deepseek-ai/dsh-compaction-basic`, and the web-app patch disables the host
8
+ * plane's `command-compact` and `tool-result-pruner`. With the policy engine on
9
+ * the host plane, a preset session therefore got the policy for *automatic*
10
+ * compaction only (the `agent/pre-step` event bubbles past the isolation),
11
+ * while `/compact` ran the stock engine at 0.16 / 65536 with no fallback chain,
12
+ * and tool-result pruning was skipped because the host plane has no pruner.
13
+ *
14
+ * The registry rejects duplicate ids, keeps definitions immutable and offers no
15
+ * "edit" API, so the only declarative route is an id-targeted override of the
16
+ * whole `preset-*` row — a snapshot that drifts the moment the installed
17
+ * preset changes. This row instead rewrites, in memory and at every start, the
18
+ * one line that matters: inside each preset's compaction group the stock engine
19
+ * row becomes this package's engine row. The rewrite goes through the loader
20
+ * entry's own update path, so the preset is re-registered as a new revision
21
+ * with a normal lifecycle, and the registry, the mounted tree and the config
22
+ * editor all agree on what is mounted. Nothing is persisted: the next start
23
+ * derives again from whatever the installed dsh ships.
24
+ *
25
+ * Opt out with `- id: compaction-control-presets / disabled: true` in the
26
+ * profile patch.
27
+ *
28
+ * @module dsh-compaction-policy-engine/presets
29
+ */
30
+
31
+ /** The row plugin that declares a preset; its `config.plugins` is the realm. */
32
+ export const PRESET_PLUGIN = '@deepseek-ai/dsh-agent-preset';
33
+ /** The stock engine row every built-in preset places inside its compaction group. */
34
+ export const STOCK_ENGINE = '@deepseek-ai/dsh-compaction-basic';
35
+ /** This package's engine export — the row `name` the loader mounts. */
36
+ export const POLICY_ENGINE = '@magic6/dsh-compaction-policy-engine/engine';
37
+ export const PRESETS_SERVICE = 'compactionControlPresets';
38
+
39
+ const GROUP_NAMES = new Set(['cordis:group', '@deepseek-ai/cordis-plugin-group']);
40
+ const DEFAULT_ENGINE_ROW = Object.freeze({ id: 'compaction-control', name: POLICY_ENGINE });
41
+ /** How long to wait for the host tree to settle before acting anyway. */
42
+ const SETTLE_MS = 15_000;
43
+
44
+ function isRecord(value) {
45
+ if (!value || typeof value !== 'object' || '__jsExpr' in value) return false;
46
+ const prototype = Object.getPrototypeOf(value);
47
+ return prototype === Object.prototype || prototype === null;
48
+ }
49
+
50
+ function isGroup(row) {
51
+ return row.group === true || GROUP_NAMES.has(row.name);
52
+ }
53
+
54
+ /**
55
+ * Rewrite the stock compaction engine inside every isolated compaction group.
56
+ *
57
+ * Pure: returns a new list only when something changed. Rows outside a
58
+ * `isolate.compaction` group are passed through untouched, including `!!js`
59
+ * expression nodes (`{ __jsExpr }`), which stay plain objects.
60
+ *
61
+ * @param plugins - A preset's declared `config.plugins`.
62
+ * @param engineRow - The row that replaces the stock engine.
63
+ * @returns The rewritten list plus what happened: `replaced` (stock row ids),
64
+ * `ours` (rows already running this engine) and `stockConfig` (stock rows
65
+ * that carried a config, which is not carried over — the policy document
66
+ * governs).
67
+ */
68
+ export function takeOverPlugins(plugins, engineRow = DEFAULT_ENGINE_ROW) {
69
+ const report = { plugins, replaced: [], ours: [], stockConfig: [], untouched: true };
70
+ if (!Array.isArray(plugins)) return report;
71
+ const walk = (rows) => {
72
+ let changed = false;
73
+ const next = rows.map((row) => {
74
+ if (!isRecord(row) || !Array.isArray(row.config)) return row;
75
+ const children = isGroup(row) ? walk(row.config) : row.config;
76
+ if (!isGroup(row)) return row;
77
+ if (row.isolate?.compaction !== true) {
78
+ if (children === row.config) return row;
79
+ changed = true;
80
+ return { ...row, config: children };
81
+ }
82
+ let groupChanged = children !== row.config;
83
+ const nextChildren = children.map((child) => {
84
+ if (!isRecord(child)) return child;
85
+ if (child.name === STOCK_ENGINE) {
86
+ if (child.config !== undefined && Object.keys(child.config).length > 0) {
87
+ report.stockConfig.push({ group: row.id, id: child.id, keys: Object.keys(child.config) });
88
+ }
89
+ report.replaced.push(child.id ?? STOCK_ENGINE);
90
+ groupChanged = true;
91
+ return { ...engineRow };
92
+ }
93
+ if (child.name === engineRow.name) report.ours.push(child.id ?? engineRow.name);
94
+ return child;
95
+ });
96
+ if (!groupChanged) return row;
97
+ changed = true;
98
+ return { ...row, config: nextChildren };
99
+ });
100
+ return changed ? next : rows;
101
+ };
102
+ report.plugins = walk(plugins);
103
+ report.untouched = report.plugins === plugins;
104
+ return report;
105
+ }
106
+
107
+ /**
108
+ * The engine row a preset realm gets: this package's engine, told which preset
109
+ * it serves so that `engine up` and the runtime report can say so.
110
+ */
111
+ function engineRowFor(options) {
112
+ const config = options.config;
113
+ return { ...DEFAULT_ENGINE_ROW, config: { preset: config?.id ?? options.id.replace(/^preset-/, '') } };
114
+ }
115
+
116
+ /**
117
+ * Rewrite one loader entry's config in place, before the loader applies it.
118
+ *
119
+ * @returns True when the entry was a preset that still ran the stock engine.
120
+ */
121
+ function swapInPlace(entry) {
122
+ const options = entry?.options;
123
+ if (options?.name !== PRESET_PLUGIN) return false;
124
+ const result = takeOverPlugins(options.config?.plugins, engineRowFor(options));
125
+ if (result.untouched) return false;
126
+ options.config = { ...options.config, plugins: result.plugins };
127
+ return true;
128
+ }
129
+
130
+ /**
131
+ * Apply the takeover to every preset row in a loader tree.
132
+ *
133
+ * @param loader - The host `loader` service (`ctx.get('loader')`).
134
+ * @param options - `log` receives one line per outcome; `settleMs` bounds the
135
+ * wait for the host tree (a row waiting forever for a service must not keep
136
+ * the presets on the stock engine as well).
137
+ * @returns Which presets were taken over, already ran this engine, or have no
138
+ * isolated compaction group.
139
+ */
140
+ export async function takeOverPresets(loader, { log = () => {}, settleMs = SETTLE_MS } = {}) {
141
+ const report = { status: 'done', presets: [], takenOver: [] };
142
+ // The profile composition is loaded through a `cordis:include` row, so the
143
+ // preset rows live in that row's subtree, not in the loader's top-level store
144
+ // (measured 2026-12-01: the top level holds exactly one entry). `entries()`
145
+ // walks every nested subtree.
146
+ const entries = [...(loader?.entries?.() ?? Object.values(loader?.store ?? {}))].filter(
147
+ (entry) => entry.options?.name === PRESET_PLUGIN,
148
+ );
149
+ if (entries.length === 0) {
150
+ report.status = 'no-presets';
151
+ log('presets: no agent presets in this composition (headless?); nothing to take over');
152
+ return report;
153
+ }
154
+ // Never inside this row's own activation: the settle would wait on it (the
155
+ // caller defers with a timer). A tree that never settles must not block the
156
+ // takeover either — the preset rows have long since activated by then.
157
+ let settled = true;
158
+ let timer;
159
+ const timeout = new Promise((resolve) => {
160
+ timer = setTimeout(() => {
161
+ settled = false;
162
+ resolve();
163
+ }, settleMs);
164
+ });
165
+ await Promise.race([Promise.resolve(loader.await?.()), timeout]);
166
+ clearTimeout(timer);
167
+ if (!settled) log('presets: host tree did not settle in time; taking over the presets that are declared');
168
+ for (const entry of entries) {
169
+ const options = entry.options;
170
+ const config = options.config;
171
+ const result = takeOverPlugins(config?.plugins, engineRowFor(options));
172
+ let status;
173
+ if (result.untouched) {
174
+ status = result.ours.length > 0 ? 'already-ours' : 'no-compaction-group';
175
+ } else {
176
+ await entry.update({ config: { ...config, plugins: result.plugins } });
177
+ status = 'taken-over';
178
+ // The preset id the registry and the session header use, not the loader row id.
179
+ report.takenOver.push(config?.id ?? options.id.replace(/^preset-/, ''));
180
+ }
181
+ for (const notice of result.stockConfig) {
182
+ log(`presets: ${options.id} configured its stock engine (${notice.id}: ${notice.keys.join(', ')}); those keys are not carried over — the policy document governs`);
183
+ }
184
+ report.presets.push({ id: options.id, status });
185
+ log(`presets: ${options.id} ${status}${status === 'taken-over' ? ` (${result.replaced.join(', ')} → ${DEFAULT_ENGINE_ROW.id})` : ''}`);
186
+ }
187
+ return report;
188
+ }
189
+
190
+ export const name = 'compaction-control-presets';
191
+
192
+ /**
193
+ * Mount: publish the outcome where the engine's runtime report can read it,
194
+ * then run once the host tree has settled.
195
+ *
196
+ * @param ctx - The host-plane context of this row.
197
+ */
198
+ export function apply(ctx) {
199
+ const state = { status: 'pending', presets: [], takenOver: [], reapplied: 0 };
200
+ ctx.provide(PRESETS_SERVICE, state);
201
+ const log = (line) => {
202
+ process.stderr.write(`[compaction] ${line}\n`);
203
+ ctx.logger?.info?.(line);
204
+ };
205
+ const run = (loader) =>
206
+ takeOverPresets(loader, { log })
207
+ .then((report) => {
208
+ state.status = report.status;
209
+ state.presets = report.presets;
210
+ state.takenOver = report.takenOver;
211
+ // Every engine (host plane and each taken-over realm) reads the
212
+ // outcome through its runtime report; tell them it changed.
213
+ ctx.root.emit('compaction-control/presets', report);
214
+ return report;
215
+ })
216
+ .catch((error) => {
217
+ // Loud: a preset left on the stock engine is exactly the state this
218
+ // row exists to end, and it looks identical from the card.
219
+ state.status = 'failed';
220
+ const message = `presets: takeover failed: ${error instanceof Error ? error.message : String(error)}`;
221
+ process.stderr.write(`[compaction] ${message}\n`);
222
+ ctx.logger?.warn?.(message);
223
+ return undefined;
224
+ });
225
+ const loaderOf = () => ctx.get('loader');
226
+ const timer = setTimeout(() => {
227
+ const loader = loaderOf();
228
+ if (loader === undefined) {
229
+ state.status = 'no-loader';
230
+ log('presets: no loader service in this composition; nothing to take over');
231
+ return;
232
+ }
233
+ run(loader);
234
+ }, 0);
235
+ timer.unref?.();
236
+ ctx.effect(() => () => clearTimeout(timer), 'presets-takeover');
237
+
238
+ // A composition re-sync (every settings save re-applies bundles + patch file
239
+ // through the include row) hands every preset entry its *stock* options again.
240
+ // The loader runs this waterfall right before it restarts a row on new
241
+ // config, so the swap is made there: the preset never re-registers on the
242
+ // stock engine, and nothing needs to be persisted. Measured 2026-12-01:
243
+ // without it, dismissing the welcome notice reverted all four presets and
244
+ // the next `/compact` in a new standard session ran the stock engine.
245
+ //
246
+ // The loader emits on its own context, which is not a descendant of this
247
+ // row's, so the listener lives on the root and is tied to this fiber.
248
+ ctx.effect(() => {
249
+ const dispose = ctx.root.on('loader/patch-context', (entry, next) => {
250
+ if (swapInPlace(entry)) {
251
+ state.reapplied += 1;
252
+ log(`presets: ${entry.options.id} re-applied after a composition re-sync`);
253
+ ctx.root.emit('compaction-control/presets', state);
254
+ }
255
+ return next();
256
+ });
257
+ return dispose;
258
+ }, 'presets-takeover: re-sync hook');
259
+
260
+ /** Re-run the takeover now (idempotent); the host engine calls it if it meets a preset realm on the stock engine. */
261
+ state.reapply = () => {
262
+ const loader = loaderOf();
263
+ if (loader === undefined) return Promise.resolve(undefined);
264
+ return run(loader);
265
+ };
266
+ }
package/lib/settings.js CHANGED
@@ -34,6 +34,8 @@ export const SETTINGS_NS = 'compaction-control';
34
34
  * every engine that can see it (the host plane and each preset realm).
35
35
  */
36
36
  export const POLICY_SERVICE = 'compactionControlPolicy';
37
+ /** Host service the preset-takeover row publishes its outcome under. */
38
+ export const PRESETS_SERVICE = 'compactionControlPresets';
37
39
 
38
40
  /**
39
41
  * Fields shared by the global default and every override layer. The vocabulary
@@ -85,6 +87,8 @@ export const runtimeSchema = z.object({
85
87
  auto: z.boolean().description('whether the pressure gate is armed'),
86
88
  source: z.string().description('which layer the engine resolved last'),
87
89
  fiber: z.string().description('the mount that reported'),
90
+ preset: z.string().description('the agent preset whose realm the reporting engine serves'),
91
+ presets: z.array(z.string()).description('agent presets whose compaction group now runs this engine'),
88
92
  updatedAt: z.number().description('Unix milliseconds of the report'),
89
93
  });
90
94
 
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@magic6/dsh-compaction-policy-engine",
3
- "version": "0.5.16",
3
+ "version": "0.5.18",
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",
7
7
  "exports": {
8
8
  ".": "./lib/companion.js",
9
9
  "./engine": "./lib/engine.js",
10
+ "./presets": "./lib/presets.js",
10
11
  "./policy": "./lib/policy.js",
11
12
  "./client-policy": "./lib/client-policy.js",
12
13
  "./client": "./lib/client.js"
@@ -26,31 +27,22 @@
26
27
  "test:e2e": "e2e/run.sh",
27
28
  "prepublishOnly": "npm test"
28
29
  },
29
- "keywords": [
30
- "dsh",
31
- "dsh-plugin",
32
- "deepseek-harness",
33
- "cordis",
34
- "compaction",
35
- "context-management",
36
- "threshold",
37
- "summarization"
38
- ],
39
- "license": "MIT",
40
- "author": "T-splines",
41
- "repository": {
42
- "type": "git",
43
- "url": "git+https://github.com/T-splines/dsh-compaction-policy-engine.git"
44
- },
45
- "homepage": "https://github.com/T-splines/dsh-compaction-policy-engine#readme",
46
- "bugs": {
47
- "url": "https://github.com/T-splines/dsh-compaction-policy-engine/issues"
48
- },
49
30
  "peerDependencies": {
50
31
  "@deepseek-ai/dsh-compaction-basic": ">=0.2.1-0 <0.3.0-0",
51
32
  "@deepseek-ai/schemastery": "^3.18.2",
52
33
  "@deepseek-ai/cosmokit": "^1.8.3"
53
34
  },
35
+ "devDependencies": {
36
+ "@deepseek-ai/cordis": "4.1.0",
37
+ "@deepseek-ai/cosmokit": "1.9.0",
38
+ "@deepseek-ai/dsh-compaction": "0.2.2-rc.5",
39
+ "@deepseek-ai/dsh-compaction-basic": "0.2.2-rc.5",
40
+ "@deepseek-ai/schemastery": "3.19.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=20.0.0",
44
+ "dsh": ">=0.2.1-0 <0.3.0-0"
45
+ },
54
46
  "dsh": {
55
47
  "manifestVersion": 1,
56
48
  "bundle": {
@@ -66,8 +58,24 @@
66
58
  ]
67
59
  }
68
60
  },
69
- "engines": {
70
- "node": ">=20.0.0",
71
- "dsh": ">=0.2.1-0 <0.3.0-0"
72
- }
61
+ "keywords": [
62
+ "dsh",
63
+ "dsh-plugin",
64
+ "deepseek-harness",
65
+ "cordis",
66
+ "compaction",
67
+ "context-management",
68
+ "threshold",
69
+ "summarization"
70
+ ],
71
+ "license": "MIT",
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/T-splines/dsh-compaction-policy-engine.git"
75
+ },
76
+ "homepage": "https://github.com/T-splines/dsh-compaction-policy-engine#readme",
77
+ "bugs": {
78
+ "url": "https://github.com/T-splines/dsh-compaction-policy-engine/issues"
79
+ },
80
+ "author": "T-splines"
73
81
  }