@magic6/dsh-compaction-policy-engine 0.0.0-stage → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,75 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.5.4] - 2026-11-16
8
+
9
+ ### Fixed
10
+
11
+ - Bundle entry, engine subpath, and client module identities now use the scoped
12
+ npm package name, so the installed package resolves at runtime.
13
+ - Example bundle: engine entry uses the scoped package name.
14
+
15
+ ## [0.5.3] - 2026-11-16
16
+
17
+ ### Changed
18
+
19
+ - npm package renamed to `@magic6/dsh-compaction-policy-engine`; npm requires a
20
+ scoped package for the first automated publish.
21
+ - README: update the npm installation command.
22
+
23
+ ## [0.5.2] - 2026-11-16
24
+
25
+ ### Added
26
+
27
+ - npm distribution: install with `dsh plugin --profile web add dsh-compaction-policy-engine`.
28
+
29
+ ### Changed
30
+
31
+ - README: document npm installation and use absolute links for the language switch.
32
+
33
+ ## [0.5.1] - 2026-11-16
34
+
35
+ ### Changed
36
+
37
+ - README: add a visible English / Simplified Chinese language switch.
38
+
39
+ ## [0.5.0] - 2026-11-16
40
+
41
+ First public release.
42
+
43
+ ### Added
44
+
45
+ - Three-layer compaction policy (`models[]` → `providers{}` → `default`) with per-field
46
+ resolution.
47
+ - Ratio and absolute-token budget forms with exact conversion back to the official engine;
48
+ explicit failure when a route declares no window.
49
+ - Live reload from `settings.yaml` and the `compaction-control-settings` row without
50
+ restarting DSH; the engine mount row's `config:` is read at load.
51
+ - Partial-document merge of the `compaction-control:` settings section with the mount
52
+ config; profile `models[]` layers survive panel saves.
53
+ - Per-provider and per-model summarization models, plus a summarization fallback chain.
54
+ - Settings panel for the global/provider layers, unit switching, compactable-space warning
55
+ and a session badge showing the current trigger point and the last summarizing route.
56
+ - `compaction:context-policy` prompt preventing self-diagnosed "context nearly full"
57
+ refusals.
58
+ - Durable manual `/compact` that is not killed by client disconnects, with honest busy
59
+ messages.
60
+ - 198 `node --test` cases plus a real start-up smoke script.
61
+
62
+ ### Changed
63
+
64
+ - Package and repository renamed from `dsh-compaction-control` to
65
+ `dsh-compaction-policy-engine`. Entry ids (`compaction-control`,
66
+ `compaction-control-settings`) and the `compaction-control:` settings namespace are
67
+ unchanged; update the `name:` fields in profiles/presets.
68
+ - README rewritten for the public release; added a Chinese README, design document, security
69
+ policy, contribution guide, CI, and an example preset bundle for the web profile.
70
+
71
+ ### Removed
72
+
73
+ - Internal probe tools and one-off probes are not part of the public release.
74
+
75
+ Earlier development history is not part of this repository.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 T-splines
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,354 @@
1
- # Temporary Holding Version
1
+ # dsh-compaction-policy-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** | [简体中文](https://github.com/T-splines/dsh-compaction-policy-engine/blob/main/README.zh-CN.md)
4
+
5
+ **Per-model context compaction policy for DeepSeek Harness — three-layer thresholds, live reload and summarization-model selection, on top of the official compaction engine.**
6
+
7
+ The official `@deepseek-ai/dsh-compaction-basic` already supports a threshold, a
8
+ summarization model, and exact per-`(provider, model)` overrides through `modelPolicies`.
9
+ This plugin subclasses that engine and adds the layer above it:
10
+
11
+ - **provider-level layers** — one rule for every model behind a provider, instead of
12
+ enumerating each model id;
13
+ - **field-by-field inheritance** — a model can override `threshold` while inheriting
14
+ `retain`, `maxTokens` and the summarizer from its provider or the global layer;
15
+ - **ratio or absolute-token units**, converted against the route's declared window;
16
+ - **live reload plus a settings panel and session badge**;
17
+ - **a summarization fallback chain** and a context-policy prompt.
18
+
19
+ Region selection, tool-pairing balance, summary framing and the durable compaction
20
+ transaction remain the official implementation. If you only need a few exact
21
+ `(provider, model)` overrides, the official `modelPolicies` already covers you; this plugin
22
+ is for layered policy across many routes.
23
+
24
+ - [Why this exists](#why-this-exists)
25
+ - [What makes it different](#what-makes-it-different)
26
+ - [Install and mount](#install-and-mount)
27
+ - [Configuration](#configuration)
28
+ - [How policy is resolved](#how-policy-is-resolved)
29
+ - [Settings panel](#settings-panel)
30
+ - [Behavior guarantees](#behavior-guarantees)
31
+ - [Tests](#tests)
32
+ - [Compatibility and migration](#compatibility-and-migration)
33
+
34
+ ## Why this exists
35
+
36
+ The official engine's `modelPolicies` are exact `(provider, model)` pairs. When one gateway
37
+ exposes many model ids, or when several routes share the same policy, enumerating every pair
38
+ is brittle: a newly added model silently falls back to the global threshold until someone
39
+ adds it. This plugin lets one provider-level row cover every model behind that provider, and
40
+ resolves `models[] → providers{} → default` field by field.
41
+
42
+ ```
43
+ models[] → providers{} → default
44
+ ```
45
+
46
+ A model can override `threshold` while still inheriting `retain`, `maxTokens`,
47
+ `headroomTokens` and the summarization route from the provider or global layer.
48
+
49
+ ## What makes it different
50
+
51
+ - **Three-layer policy, per-field.** `models[]` → `providers{}` → `default`. Changing one
52
+ field does not require copying the whole layer, and one provider row covers every model
53
+ behind that provider.
54
+ - **Ratio or absolute tokens.** `threshold` / `retain` are ratios of the route's declared
55
+ window; `thresholdTokens` / `retainTokens` are absolute budgets. The plugin converts
56
+ exactly back into the parent engine's ratio (`(tokens + 0.5) / window`) and **refuses to
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.
60
+ The panel writes the same document. The engine mount row's own `config:` is read at load
61
+ (see [Install and mount](#install-and-mount)).
62
+ - **Partial settings document.** The `compaction-control:` section in `settings.yaml` is
63
+ merged **per field** with the mount config (maps recurse, arrays replace wholesale), so a
64
+ panel save cannot silently erase a `models[]` layer written in the profile.
65
+ - **Settings panel.** Edit the global layer or a provider layer, switch units without
66
+ leaving both keys behind, see warnings for an un-compactable gap, and see the session
67
+ badge's current trigger point and the route that actually wrote the last summary.
68
+ - **Summarization fallback chain.** `summarizationFallback` lists routes to try when the
69
+ primary summarizer fails, so one broken summarizer route does not disable compaction.
70
+ - **Context-policy prompt.** The companion registers a prompt section telling the model that
71
+ context management is automatic and that it cannot measure its own usage — preventing the
72
+ "I think my context is nearly full" refusal loop observed in long sessions.
73
+ - **Manual `/compact` is durable.** A client disconnect or reconnect does not kill a 20–40 s
74
+ compaction transaction; the command reports the real reason when it cannot start.
75
+ - **Tested.** 198 `node --test` cases across 13 files, including a real-bundle client
76
+ evaluation, policy resolution, unit conversion, patch-file parsing and manual-compaction
77
+ retention.
78
+
79
+ ## Install and mount
80
+
81
+ Requirements: DSH `0.2.2-rc.x`, Node.js 20+.
82
+
83
+ ### From npm
84
+
85
+ ```bash
86
+ dsh plugin --profile web add @magic6/dsh-compaction-policy-engine
87
+ ```
88
+
89
+ The npm package includes `examples/standard-with-policy` for reference; the preset override
90
+ rules below still apply. The `$PWD` commands in the web section assume a source checkout.
91
+
92
+ ### From source
93
+
94
+ ```bash
95
+ git clone https://github.com/T-splines/dsh-compaction-policy-engine.git
96
+ cd dsh-compaction-policy-engine
97
+ dsh plugin --profile web add "$PWD"
98
+ ```
99
+
100
+ The package is a bundle. It mounts:
101
+
102
+ - an **engine row** (`compaction-control`), **disabled by default**, and
103
+ - an **always-enabled companion row** (`compaction-control-settings`) that serves the
104
+ settings card and the context-policy prompt. It deliberately does **not** claim
105
+ `ctx.compaction`.
106
+
107
+ ### Choose the realm first
108
+
109
+ `ctx.compaction` is a **per-realm single-slot seam**. The engine must live in the same realm
110
+ the agent resolves `ctx.compaction` from. Mounting it elsewhere creates a second engine; both
111
+ subscribe to the bubbling `agent/pre-step`, and the lower threshold wins — the symptom is
112
+ "compaction became unexpectedly early after installing the plugin".
113
+
114
+ | profile | where the agent's engine lives | how to mount |
115
+ |:--|:--|:--|
116
+ | `headless` | the host plane (no agent preset) | the profile's `cordis.patch.yml`, overriding the bundle's engine row |
117
+ | `web` | the **agent preset** (`dsh-web-app` disables the host-plane `compaction-basic`) | a preset declaration override; this repo ships an example bundle |
118
+
119
+ #### Headless (host plane)
120
+
121
+ The bundle already inserts `compaction-control` (disabled). Override that row; do **not**
122
+ `insert` a second one:
123
+
124
+ ```yaml
125
+ # $DSH_HOME/profiles/<profile>/cordis.patch.yml
126
+ - id: compaction-basic
127
+ disabled: true
128
+
129
+ - id: compaction-control
130
+ disabled: false
131
+ config:
132
+ default:
133
+ threshold: 0.8
134
+ retain: 0.16
135
+ ```
136
+
137
+ The loader key is **`disabled`**, not `disable`; the typo is silently dropped by the static
138
+ config and looks like "I disabled it, but it is still enabled".
139
+
140
+ #### Web (agent preset)
141
+
142
+ DSH 0.2.2 presets are `@deepseek-ai/dsh-agent-preset` declarations carried by bundle
143
+ patches. The legacy `$DSH_HOME/.agent-presets/<id>/agent.cordis.yml` directory is no longer
144
+ read. The web agent realm isolates `ctx.compaction`, so a host-plane engine is not seen by
145
+ the agent.
146
+
147
+ This repo ships an example bundle that overrides the shipped `preset-standard` and replaces
148
+ `compaction-basic` inside its `compaction` group with `compaction-control` (keeping
149
+ `command-compact` and `tool-result-pruner`):
150
+
151
+ ```bash
152
+ dsh plugin --profile web add "$PWD"
153
+ dsh plugin --profile web add "$PWD/examples/standard-with-policy"
154
+ ```
155
+
156
+ Restart the web app and open a new session. The example is a snapshot of the standard preset
157
+ from DSH 0.2.2. If you have customized the standard preset, merge the `compaction` group into
158
+ your own preset declaration instead of installing the example blindly (Creator mode can
159
+ author that override). The file is
160
+ [`examples/standard-with-policy/cordis.patch.yml`](examples/standard-with-policy/cordis.patch.yml);
161
+ its header says the same.
162
+
163
+ Two silent failure modes are easy to create:
164
+
165
+ - engine on the host plane **and** the stock `compaction-basic` still enabled in the preset
166
+ → two engines, lower threshold wins;
167
+ - stock engine disabled **without** mounting a replacement → the seam is unclaimed and the
168
+ session silently stops compacting until the provider rejects it.
169
+
170
+ Disable the old engine and enable the new one in the **same composition**, reviewed together.
171
+
172
+ ### Live reload scope
173
+
174
+ The settings panel writes `$DSH_HOME/settings.yaml`. The engine polls that file **and** the
175
+ `compaction-control-settings` row every second, so panel edits and edits to that row apply to
176
+ the next compaction without a restart. The **engine mount row** (`compaction-control`) is
177
+ read at plugin load; editing its `config:` requires a restart.
178
+
179
+ ### Threshold semantics
180
+
181
+ The official engine's trigger is
182
+
183
+ ```
184
+ floor(min(W × threshold, W − O − headroomTokens))
185
+ ```
186
+
187
+ where `W` is the route's declared window, `O` the output reservation, and `headroomTokens`
188
+ defaults to 65,536. `measured` **includes the fixed system prompt and tool catalogue**. On a
189
+ deployment with a large tool set, a threshold of 0.5 can mean "compact after roughly 23K
190
+ tokens of conversation", not "compact when the conversation is half full".
191
+
192
+ The plugin's `threshold` / `retain` map to the official `thresholdRatio` / `retainRatio`;
193
+ `headroomTokens` and `maxTokens` are per-layer fields. The default is 0.8, the official
194
+ engine's default, so the plugin never triggers earlier than the stock engine unless a
195
+ headroom cap does. The session badge shows `window × threshold` as a quick preview; because
196
+ `W − O − headroomTokens` can be lower, treat that number as an **upper bound** on when
197
+ compaction fires.
198
+
199
+ ## Configuration
200
+
201
+ The policy can live in the mount row's `config:` or in `$DSH_HOME/settings.yaml` under the
202
+ `compaction-control:` section (the panel edits the latter).
203
+
204
+ ```yaml
205
+ compaction-control:
206
+ # global layer
207
+ default:
208
+ threshold: 0.8 # compact at this fraction of the window
209
+ retain: 0.16 # keep this tail fraction; must be < threshold
210
+ summarizationModel: auto # auto = the session's current route, or "provider/model"
211
+ summarizationFallback: [] # ordered "provider/model" routes to try after the primary
212
+ headroomTokens: 65536 # keep this much free below the threshold
213
+ maxTokens: 8192 # summary length cap
214
+ compactionRetries: 1
215
+ maxOverflowRetries: 1
216
+
217
+ # per-provider override (provider names come from the llm config)
218
+ providers:
219
+ some-provider:
220
+ threshold: 0.5
221
+
222
+ # exact (provider, model) override; highest priority
223
+ models:
224
+ - provider: local
225
+ model: model-262k
226
+ threshold: 0.9
227
+
228
+ # false = disable automatic compaction (manual /compact still works)
229
+ auto: true
230
+ ```
231
+
232
+ ### Two units per budget field
233
+
234
+ Each budget field has a ratio form and an absolute-token form. Use **one form per layer**:
235
+
236
+ | ratio (of the window) | absolute tokens | meaning |
237
+ |:--|:--|:--|
238
+ | `threshold` | `thresholdTokens` | compact when reached |
239
+ | `retain` | `retainTokens` | keep this much recent content |
240
+
241
+ If both forms appear in the same layer, the token form wins and a `[compaction] WARNING`
242
+ names the shadowed key. The whole section is not rejected, because the panel naturally
243
+ stores a token value next to a ratio baseline and silently ignoring it would be worse.
244
+
245
+ ### Other policy fields
246
+
247
+ Every field below is valid in `default`, a `providers{}` layer, or a `models[]` layer:
248
+
249
+ | field | default | meaning |
250
+ |:--|:--|:--|
251
+ | `summarizationModel` | `auto` | `auto` reuses the session's routed model; or an explicit `provider/model` |
252
+ | `summarizationFallback` | `[]` | ordered `provider/model` routes tried when the primary summarizer fails |
253
+ | `headroomTokens` | `65536` (official default) | tokens kept free below the threshold so the summary has room to be smaller |
254
+ | `maxTokens` | official default | cap on the generated summary length |
255
+ | `compactionRetries` | `1` | extra summarization attempts when pressure remains |
256
+ | `maxOverflowRetries` | `1` | retries after a confirmed context-window overflow; `0` disables recovery |
257
+
258
+ `auto` is a root-level switch, not a layer field: `false` disables automatic compaction while
259
+ manual `/compact` still works.
260
+
261
+ **The gap must be large enough.** The summary is a structured summary with a practical lower
262
+ bound (about 3.2K tokens). When `threshold − retain < 8192`, the summary cannot be smaller
263
+ than the content it replaces and the parent engine rejects it. The panel shows this as
264
+ "compactable space" with a warning; small windows may make a small gap unavoidable, so it is
265
+ a warning, not a load failure.
266
+
267
+ ## How policy is resolved
268
+
269
+ - `models[]` → `providers{}` → `default`, **per field**, resolved by
270
+ `(provider, model, window)` and cached. A session that switches models picks up the new
271
+ policy on the next threshold check.
272
+ - The engine reads the route **at the time of the check**, not at session start.
273
+ - A route that declares no context window cannot honor an absolute token budget: the field
274
+ is deferred and the error names the route when the policy is actually needed.
275
+ - Configuration errors (out-of-range ratio, `retain >= threshold`, unknown field, duplicate
276
+ `models[]` target, malformed `summarizationModel`) fail at plugin load with a message
277
+ pointing at the field.
278
+
279
+ ## Settings panel
280
+
281
+ Models page footer → **Compaction policy** card:
282
+
283
+ - choose the layer: global default or a provider route;
284
+ - edit each budget field; the number's shape is the unit (`0.2` ratio, `200000` tokens);
285
+ mixed/invalid values are marked and saving is disabled;
286
+ - switch units without leaving both keys in the document (the replaced key is `unset` in the
287
+ same operation);
288
+ - add/remove a provider override; removal unsets every field in the user layer, including
289
+ fields the card does not render;
290
+ - the session header badge shows the current trigger point (`ratio · tokens`), the layer
291
+ that supplied it (`models[]` / `providers{}` / `default` / engine default), the estimated
292
+ compactable space, and the route that wrote the last summary.
293
+
294
+ `models[]` remains hand-edited in `settings.yaml`: the settings writer treats arrays as
295
+ whole-value replacements, so a list editor would rewrite the whole table on every keystroke.
296
+ The badge still reports when a session hit a `models[]` entry.
297
+
298
+ Non-loopback browsers get DSH's memory-state view (`status: 'unavailable'`,
299
+ `writable: false`); the card says so instead of rendering plugin defaults as if they were
300
+ the deployed policy.
301
+
302
+ ## Behavior guarantees
303
+
304
+ - **Configuration errors fail at startup, not at the first compaction.** The exception is a
305
+ policy that needs the route's window; that fails at the step that actually needs it and
306
+ names the route.
307
+ - **`retain >= threshold` after an override is an error**, not a silent shrink of `retain`.
308
+ - **No semantic hijack.** Region selection, tool pairing and the durable transaction are
309
+ untouched from the official engine.
310
+ - **Manual compaction is persistent work.** `/compact` is not cancelled by a client
311
+ disconnect; only the agent's own maintenance signal can cancel it. Stop still works.
312
+ - **Failures are not misreported.** A busy gate is retried once with a bounded wait; if it
313
+ never releases, the message says the previous activity is still finishing, rather than
314
+ claiming a lock is held.
315
+ - **Context policy.** The companion says: context management is automatic; you cannot
316
+ measure your own usage; never stop or shorten work because you believe context is nearly
317
+ full. The rule is registered only when the profile has a `systemPrompt` service.
318
+
319
+ ## Tests
320
+
321
+ ```bash
322
+ npm test
323
+ ```
324
+
325
+ 198 cases across 13 files, including:
326
+
327
+ - `manual-compaction.test.js` — gate retry, UI signal abort, real failures, honest messages,
328
+ and a contract assertion against the installed official package;
329
+ - `context-policy.test.js` — prompt registration and absence without a `systemPrompt` service;
330
+ - `policy.test.js` — three-layer resolution, per-field merge, both units, conversion,
331
+ warnings, overlay document rules;
332
+ - `engine.test.js` — seam registration, `inject` inheritance, `Config` ownership, per-target
333
+ switching, window conversion, no-window refusal, profile `models[]` surviving a
334
+ `settings.yaml` section;
335
+ - `settings-file.test.js` — patch/settings parsing and immediate edits;
336
+ - `fallback.test.js`, `patch-file.test.js`, `settings.test.js`, `summary-prefix.test.js`,
337
+ `unstated-threshold.test.js` — summarizer fallback, patch entry shapes, settings merge,
338
+ summary framing and the unstated-threshold warning;
339
+ - `client-policy.test.js` / `client.test.js` — panel calculations, unit switching, provider
340
+ layers, session badge, illegal value blocking, inline bundle consistency.
341
+
342
+ ## Compatibility and migration
343
+
344
+ - DSH `0.2.2-rc.x` (`engines.dsh`: `>=0.2.2-0 <0.3.0-0`), Node.js 20+.
345
+ - **Renamed from `dsh-compaction-control` in 0.5.0.** Entry ids are unchanged:
346
+ `compaction-control` (engine), `compaction-control-settings` (companion), and the
347
+ `compaction-control:` settings namespace. Update the `name:` fields in your profile/preset
348
+ to `@magic6/dsh-compaction-policy-engine` (and `.../engine` for the engine row).
349
+ - The engine is still a subclass of the official `BasicCompactionEngine`; no `node_modules`
350
+ patch is required.
351
+
352
+ ## License
353
+
354
+ MIT. See [LICENSE](LICENSE).