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

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,41 @@ 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.15] - 2026-11-28
8
+
9
+ ### Fixed — the policy now reaches the engine on the Windows desktop host
10
+
11
+ On Windows the desktop host starts dsh with neither `DSH_HOME` nor `HOME` set
12
+ (Windows has no `HOME`) and `cwd = <home>/profiles/desktop`. Both file readers
13
+ derived the harness home from `process.env.HOME`, which on that host is the
14
+ relative path `.dsh`: every patch candidate resolved to
15
+ `<home>/profiles/desktop/.dsh/profiles/desktop/cordis.patch.yml`, a file that
16
+ does not exist. A missing candidate is the normal case for every file but one,
17
+ so nothing was reported, and the engine ran on its built-in baseline —
18
+ `thresholdRatio 0.8`, `retainRatio 0.16`, `maxTokens 8192` — while the settings
19
+ card, fed by the loader, read the configured 42%.
20
+
21
+ Measured on a Win11 `desktop` profile: the only gate-triggered compaction fired
22
+ at 680,081 tokens (the 0.8 threshold with the request's 256k `maxTokens`
23
+ reserved: 678,464); once the request moved to 131k `maxTokens` the threshold
24
+ became 800,000 and the session grew to 745k (74%) without compacting. The
25
+ pressure gate measures provider-reported usage, so "42% in the card, compacts at
26
+ 80%" was the entire symptom.
27
+
28
+ The home is now resolved the way the host resolves it
29
+ (`@deepseek-ai/dsh-home-paths`): the home the running host reports
30
+ (`ctx.profileContext.home`, provided before any profile row mounts), then a
31
+ non-blank `DSH_HOME` (with `~` expansion), then `os.homedir()/.dsh` — never
32
+ `HOME`. The same order applies to `settings.yaml`.
33
+
34
+ ### Changed — a missing patch layer is said once
35
+
36
+ `watchPatchFile` gains `onMissing`, called once when no candidate file exists at
37
+ all; the engine prints `[compaction] WARNING … no profile patch layer found
38
+ (tried …)` naming the paths. A candidate that exists but carries no entry for
39
+ this plugin stays silent — that is a profile configured elsewhere, not a missing
40
+ layer.
41
+
7
42
  ## [0.5.10] - 2026-11-26
8
43
 
9
44
  ### Fixed — installing the plugin now actually takes over compaction
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
 
@@ -176,6 +191,16 @@ The settings panel writes `$DSH_HOME/settings.yaml`. The engine polls that file
176
191
  the next compaction without a restart. The **engine mount row** (`compaction-control`) is
177
192
  read at plugin load; editing its `config:` requires a restart.
178
193
 
194
+ **Where those files are looked up**: the engine resolves the DSH home in the host's own
195
+ order — the home the running host reports (`profileContext.home`, provided before any
196
+ profile row mounts), then a non-blank `$DSH_HOME` (`~` expanded), then `os.homedir()/.dsh`,
197
+ matching `@deepseek-ai/dsh-home-paths`; it never reads `HOME`. Before 0.5.15 the Windows
198
+ desktop host had neither variable set (Windows has no `HOME`, and the desktop app does not
199
+ export `DSH_HOME`), so the path collapsed to a relative `.dsh/…`, the policy file was never
200
+ read, and the engine silently ran on its built-in 0.8 baseline while the settings card —
201
+ fed by the loader — still showed 42%. When no candidate file exists at all, the engine now
202
+ prints one `[compaction] WARNING … no profile patch layer found (tried …)`.
203
+
179
204
  ### Threshold semantics
180
205
 
181
206
  The official engine's trigger is
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,31 @@ dsh plugin --profile web add "$PWD/examples/standard-with-policy"
175
186
  行,所以面板修改和这一行的修改会在下一次压缩生效,不需要重启。**引擎挂载行**
176
187
  (`compaction-control`)的 `config:` 在插件加载时读取,改它需要重启。
177
188
 
189
+ **这两个文件在哪**:引擎按宿主自己的顺序解析 DSH home —— 先取运行中宿主报告的
190
+ `profileContext.home`(挂载任何插件行之前就已提供),再取非空的 `$DSH_HOME`(支持 `~`),
191
+ 最后是 `os.homedir()/.dsh`,与 `@deepseek-ai/dsh-home-paths` 同序;**不读 `HOME`**。
192
+ 0.5.15 之前,Windows 桌面版上这两个变量都没有(Windows 没有 `HOME`,桌面版也不导出
193
+ `DSH_HOME`),路径退化成相对的 `.dsh/…`,策略文件从未被读到,引擎静默跑在内置基线 0.8 上,
194
+ 而设置卡片走 loader、仍显示 42%。现在若所有候选文件都不存在,会打一行
195
+ `[compaction] WARNING … no profile patch layer found (tried …)`。
196
+
197
+ > ⚠️ **升级插件本身必须重启 DSH。**
198
+ >
199
+ > 热加载只覆盖配置文档,**不覆盖代码**。DSH 的加载器把已安装的模块留在进程里:
200
+ > `dsh-app-boot` 的 `refresh()` 原文是 *"Package contents and loaded modules are not
201
+ > reloaded."*,设置豁免的路径也写着 *"Existing plugin instances are not reloaded by
202
+ > this operation."*。所以 `dsh plugin add <包>@<新版本>` 之后:
203
+ >
204
+ > - 磁盘上的版本号已经是新的(设置页、`package.json` 都会显示新版本),
205
+ > - 但**正在运行的进程里仍是旧代码**,压缩走的是旧逻辑。
206
+ >
207
+ > 这种错配特别难看出来,因为版本号是对的。判断依据只能是行为:重启后看日志里有没有
208
+ > `[compact-debug]` 行(需要 `DSH_COMPACT_DEBUG=1`)与 `[compaction] FIRED`。
209
+ >
210
+ > 具体到本插件,`< 0.5.10` 的 bundle 带着 `disabled: true`,升级后不重启会**继续没有
211
+ > 压缩**,而且触发的仍是官方引擎的 80% 默认值——看起来像"新版本没生效",实际是旧代码
212
+ > 还在跑。
213
+
178
214
  ### 阈值语义
179
215
 
180
216
  官方引擎的触发点是
package/lib/index.js CHANGED
@@ -530,6 +530,16 @@ export class CompactionControlEngine extends BasicCompactionEngine {
530
530
  this.reloadPolicy();
531
531
  });
532
532
 
533
+ // The running host's own facts, provided before any profile row mounts
534
+ // (`boot()` runs `prepare(hostCtx)` — which provides `profileContext` —
535
+ // before `mountRootInclude`). `home` is the harness home the host actually
536
+ // resolved and `name` the running profile, so both file readers below work
537
+ // with no help from the environment at all. On Windows the desktop host
538
+ // passes neither `DSH_HOME` nor `HOME` (Windows has no `HOME`), which is how
539
+ // every candidate used to resolve to a path that does not exist (2026-11-28).
540
+ const profileContext = ctx.get?.('profileContext');
541
+ const hostHome = typeof profileContext?.home === 'string' ? profileContext.home : undefined;
542
+
533
543
  // Read the same section straight from `settings.yaml` as well.
534
544
  //
535
545
  // The injected path above is canonical, but it does not reach a preset-plane
@@ -537,7 +547,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
537
547
  // the file said 0.2, with no change notification. This reader gives the engine
538
548
  // the one source both realms share and a person actually edits.
539
549
  this._settingsFileWatcher = watchSettingsFile({
540
- file: settingsFilePath(),
550
+ file: settingsFilePath(hostHome),
541
551
  fallbackSection: controlConfig,
542
552
  onSection: (section, origin) => {
543
553
  this._fileSection = section;
@@ -562,15 +572,26 @@ export class CompactionControlEngine extends BasicCompactionEngine {
562
572
  // *parent* process's profile when this dsh was launched from an agent's
563
573
  // shell tool. `profileContext` is the host's own answer (see
564
574
  // `patchFilePaths` for the measured failure).
565
- const runningProfile = ctx.get?.('profileContext')?.name;
575
+ const runningProfile = profileContext?.name;
566
576
  this._patchFileWatcher = watchPatchFile({
567
- files: patchFilePaths(process.env, runningProfile),
577
+ files: patchFilePaths(process.env, runningProfile, hostHome),
568
578
  onConfig: (config) => {
569
579
  // `reloadPolicy` derives `source=` from which layers are present, so
570
580
  // this callback only records the value.
571
581
  this._patchEntry = config;
572
582
  this.reloadPolicy();
573
583
  },
584
+ // 2026-11-28, Win11 desktop: no candidate existed because the home was
585
+ // derived from `HOME`, which Windows does not set. Every gate then ran on
586
+ // the 0.8 baseline while the settings card read 42%, and nothing said so
587
+ // for days. Name the paths once so the next occurrence is one line.
588
+ onMissing: (files) => {
589
+ const message =
590
+ `compaction-control: no profile patch layer found (tried ${files.join(', ')}); ` +
591
+ 'the engine runs on the composition defaults until the layer appears — check DSH_HOME and the running profile';
592
+ this.ctx.logger?.warn?.(message);
593
+ process.stderr.write(`[compaction] WARNING fiber=${this.ctx.fiber?.name} ${message}\n`);
594
+ },
574
595
  onError: (error) => {
575
596
  this.ctx.logger?.warn?.(`compaction-control: profile patch unreadable (${error.message}); keeping the last good policy`);
576
597
  },
@@ -22,30 +22,74 @@
22
22
  */
23
23
 
24
24
  import { readFileSync } from 'node:fs';
25
- import { join } from 'node:path';
25
+ import { homedir } from 'node:os';
26
+ import { join, resolve } from 'node:path';
27
+
28
+ /**
29
+ * Resolve the DSH home the way the host does (`@deepseek-ai/dsh-home-paths`):
30
+ * the home the host reports, then a non-blank `DSH_HOME`, then `os.homedir()/.dsh`.
31
+ *
32
+ * Why not `HOME`: Windows has no `HOME` (it has `USERPROFILE`, which
33
+ * `os.homedir()` reads), and the desktop host starts dsh with neither variable
34
+ * set and `cwd = <home>/profiles/desktop`. `join(process.env.HOME ?? '', '.dsh')`
35
+ * therefore produced the *relative* path `.dsh` there, every candidate resolved
36
+ * to `<home>/profiles/desktop/.dsh/profiles/desktop/cordis.patch.yml`, and the
37
+ * patch layer that carried the operator's threshold was never read — the engine
38
+ * ran on its 0.8 baseline while the settings card read 42%. Measured 2026-11-28
39
+ * on a Win11 `desktop` profile; silent, because a missing candidate is the
40
+ * normal case for every file but one.
41
+ *
42
+ * `hostHome` is `ctx.profileContext.home`, which the host provides before any
43
+ * profile row mounts, so a `--dsh-home` the launcher was given without exporting
44
+ * it is still honoured. A blank value is not an answer (the core treats a blank
45
+ * `DSH_HOME` as unset, so that an empty override never resolves to the cwd).
46
+ *
47
+ * @param env - the environment to read.
48
+ * @param hostHome - the home reported by the running host, when known.
49
+ * @returns the absolute harness home.
50
+ */
51
+ export function resolveDshHome(env = process.env, hostHome = undefined) {
52
+ const chosen = nonBlank(hostHome) ?? nonBlank(env.DSH_HOME);
53
+ return resolve(chosen === undefined ? join(homedir(), '.dsh') : expandHome(chosen));
54
+ }
55
+
56
+ /** A string with non-whitespace content, else undefined. */
57
+ function nonBlank(value) {
58
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
59
+ }
60
+
61
+ /** Expand a leading `~` against `os.homedir()`, as the host's own resolver does. */
62
+ function expandHome(path) {
63
+ if (path === '~') return homedir();
64
+ if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2));
65
+ return path;
66
+ }
26
67
 
27
68
  /** The settings document this plugin's section lives in. */
28
- export function settingsFilePath(home = process.env.DSH_HOME ?? join(process.env.HOME ?? '', '.dsh')) {
69
+ export function settingsFilePath(home = resolveDshHome()) {
29
70
  return join(home, 'settings.yaml');
30
71
  }
31
72
 
32
73
  /**
33
74
  * The profile patch layer that carries this plugin's entry, if it is present.
34
75
  *
35
- * Every candidate is derived from `DSH_HOME` (or `HOME`), never hardcoded: a
36
- * test that redirects `DSH_HOME` to a temp directory must not have the real
37
- * profile's config read into it, and a hardcoded `/Users/...` path did exactly
38
- * that — it outranked the redirect and silently replaced every fixture.
76
+ * Every candidate is derived from the resolved harness home (see
77
+ * {@link resolveDshHome}), never hardcoded: a test that redirects `DSH_HOME` to
78
+ * a temp directory must not have the real profile's config read into it, and a
79
+ * hardcoded `/Users/...` path did exactly that — it outranked the redirect and
80
+ * silently replaced every fixture.
39
81
  *
40
82
  * `DSH_PROFILE` names the profile when dsh exports it; `web` is the profile
41
83
  * this deployment uses, and a wrong guess only costs one failed read per
42
84
  * second because a missing file means "no patch layer".
43
85
  *
44
86
  * @param env - the environment to read.
87
+ * @param profileName - the running profile, from `ctx.profileContext.name`.
88
+ * @param hostHome - the harness home reported by the running host, when known.
45
89
  * @returns absolute path candidates, most specific first.
46
90
  */
47
- export function patchFilePaths(env = process.env, profileName = undefined) {
48
- const home = env.DSH_HOME ?? join(env.HOME ?? '', '.dsh');
91
+ export function patchFilePaths(env = process.env, profileName = undefined, hostHome = undefined) {
92
+ const home = resolveDshHome(env, hostHome);
49
93
  const profiles = [];
50
94
  // `profileName` is the authoritative answer: the host exposes the *running*
51
95
  // profile as `ctx.profileContext.name`, and this plugin passes it in.
@@ -367,13 +411,23 @@ export function watchSettingsFile(options) {
367
411
  * The first candidate that yields a config wins, and the reported `origin`
368
412
  * names the file so a log line can tell the two sources apart.
369
413
  *
370
- * @param options - `files`, `entryId` (string or candidate ids), `onConfig`, `onError`, `intervalMs`.
414
+ * A candidate that does not exist is the normal case for every file but one,
415
+ * so it is skipped quietly — but when *no* candidate exists the engine is
416
+ * running on the composition defaults, which for this plugin means the built-in
417
+ * baseline rather than the operator's policy. That is reported once through
418
+ * `onMissing`, naming the paths that were tried: on 2026-11-28 the Windows
419
+ * desktop host resolved every candidate to a non-existent path and the only
420
+ * symptom was a session that compacted at 80% instead of 42%.
421
+ *
422
+ * @param options - `files`, `entryId` (string or candidate ids), `onConfig`, `onError`, `onMissing`, `intervalMs`.
371
423
  * @returns a disposer that stops watching.
372
424
  */
373
425
  export function watchPatchFile(options) {
374
- const { files, entryId = PATCH_ENTRY_IDS, onConfig, onError, intervalMs = 1000 } = options;
426
+ const { files, entryId = PATCH_ENTRY_IDS, onConfig, onError, onMissing, intervalMs = 1000 } = options;
375
427
  let last = null;
428
+ let missingReported = false;
376
429
  const read = () => {
430
+ let anyExists = false;
377
431
  for (const file of files) {
378
432
  let text;
379
433
  try {
@@ -383,6 +437,7 @@ export function watchPatchFile(options) {
383
437
  if (error?.code !== 'ENOENT') onError?.(error);
384
438
  continue;
385
439
  }
440
+ anyExists = true;
386
441
  let config;
387
442
  try {
388
443
  config = readPatchEntryConfig(text, entryId);
@@ -399,6 +454,12 @@ export function watchPatchFile(options) {
399
454
  }
400
455
  // No candidate carried the entry: leave the last good config in place
401
456
  // rather than reverting to the composition on a transient read failure.
457
+ // No candidate *exists* at all is different: nothing will ever arrive,
458
+ // and the operator has to hear which paths were tried.
459
+ if (!anyExists && !missingReported) {
460
+ missingReported = true;
461
+ onMissing?.(files);
462
+ }
402
463
  };
403
464
  read();
404
465
  const timer = setInterval(read, intervalMs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magic6/dsh-compaction-policy-engine",
3
- "version": "0.5.13",
3
+ "version": "0.5.15",
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",