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

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,85 @@ 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.16] - 2026-11-30
8
+
9
+ ### Fixed — the policy reaches the engine through the loader, not a file poll
10
+
11
+ The engine had three channels for the user's document, and on dsh 0.2.2 two of
12
+ them were dead: `installSection` — the `settings` service API the plugin called
13
+ since 0.5.0 — exists nowhere in that host, and `settings.yaml` is absent on
14
+ profiles that ship the importer. The one channel left was a one-second poll of
15
+ `cordis.patch.yml` whose path the plugin derived itself; 0.5.15 fixed the path,
16
+ but "the user's policy arrives" still hung on a file read. Measured on a Win11
17
+ desktop over 2026-11-24 → 11-30: every automatic compaction ran on the 0.8
18
+ baseline while the card read 42%.
19
+
20
+ The companion row (`compaction-control-settings`) now provides its own config as
21
+ a cordis service. The loader resolves that config into volatile cells and
22
+ updates them in place on every card save, so the engine's view of the document
23
+ is live: no file, no poll, no path. The engine overlays it on the composition
24
+ and re-reads it by value before each policy lookup, so a save applies to the
25
+ next compaction. The file readers stay as the fallback for a profile without
26
+ the companion row, and the engine now uses the exact `profileContext.patchPath`
27
+ the host reports instead of deriving one.
28
+
29
+ ### Added — the engine reports the policy it applies
30
+
31
+ The engine writes the policy it resolved (threshold, retain, `auto`, source,
32
+ mount) into a volatile `runtime` cell. The settings card and the session badge
33
+ read it and say so when it disagrees with the saved document or never arrives —
34
+ "saved but never delivered" used to look exactly like "in force". The card and
35
+ the badge popover gain an **Applied by the engine** line; the badge dot turns
36
+ amber on a mismatch.
37
+
38
+ ### Fixed — settings card and session badge (web)
39
+
40
+ - The badge popover was translucent (`--dsw-specific-menu` is a 64 %-alpha tint
41
+ with no backdrop filter, so the conversation showed through it) and its
42
+ two-column layout collapsed — `.ccbKey{flex:none}` let a long label squeeze the
43
+ value column to one character per line. It is now an opaque surface with a
44
+ grid layout; the panel is 320 px wide.
45
+ - The model-list notice rendered "Reading the model list…" for as long as the
46
+ card stayed open and never while loading: the condition was inverted. It now
47
+ shows while loading, names a failed read, and disappears once the list is in.
48
+ - Card controls had three different widths and a left edge that moved with the
49
+ presence of a Reset button; they are 220 px and right-aligned in every row.
50
+
51
+ ## [0.5.15] - 2026-11-28
52
+
53
+ ### Fixed — the policy now reaches the engine on the Windows desktop host
54
+
55
+ On Windows the desktop host starts dsh with neither `DSH_HOME` nor `HOME` set
56
+ (Windows has no `HOME`) and `cwd = <home>/profiles/desktop`. Both file readers
57
+ derived the harness home from `process.env.HOME`, which on that host is the
58
+ relative path `.dsh`: every patch candidate resolved to
59
+ `<home>/profiles/desktop/.dsh/profiles/desktop/cordis.patch.yml`, a file that
60
+ does not exist. A missing candidate is the normal case for every file but one,
61
+ so nothing was reported, and the engine ran on its built-in baseline —
62
+ `thresholdRatio 0.8`, `retainRatio 0.16`, `maxTokens 8192` — while the settings
63
+ card, fed by the loader, read the configured 42%.
64
+
65
+ Measured on a Win11 `desktop` profile: the only gate-triggered compaction fired
66
+ at 680,081 tokens (the 0.8 threshold with the request's 256k `maxTokens`
67
+ reserved: 678,464); once the request moved to 131k `maxTokens` the threshold
68
+ became 800,000 and the session grew to 745k (74%) without compacting. The
69
+ pressure gate measures provider-reported usage, so "42% in the card, compacts at
70
+ 80%" was the entire symptom.
71
+
72
+ The home is now resolved the way the host resolves it
73
+ (`@deepseek-ai/dsh-home-paths`): the home the running host reports
74
+ (`ctx.profileContext.home`, provided before any profile row mounts), then a
75
+ non-blank `DSH_HOME` (with `~` expansion), then `os.homedir()/.dsh` — never
76
+ `HOME`. The same order applies to `settings.yaml`.
77
+
78
+ ### Changed — a missing patch layer is said once
79
+
80
+ `watchPatchFile` gains `onMissing`, called once when no candidate file exists at
81
+ all; the engine prints `[compaction] WARNING … no profile patch layer found
82
+ (tried …)` naming the paths. A candidate that exists but carries no entry for
83
+ this plugin stays silent — that is a profile configured elsewhere, not a missing
84
+ layer.
85
+
7
86
  ## [0.5.10] - 2026-11-26
8
87
 
9
88
  ### Fixed — installing the plugin now actually takes over compaction
package/README.en.md CHANGED
@@ -55,9 +55,12 @@ 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 (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
58
+ - **Live reload (configuration, not code).** The engine reads the companion row's
59
+ (`compaction-control-settings`) live config: the host resolves that row's `config:` into
60
+ volatile cells, a panel save updates the cells in place, and a **policy edit** applies to
61
+ the next compaction without a restart — no file, no path to derive. Polling
62
+ `settings.yaml` and the patch file is only the fallback for a profile without the
63
+ companion row. This covers configuration only: **upgrading the plugin
61
64
  itself always requires a restart**, because loaded modules are never replaced
62
65
  (see [Live reload scope](#live-reload-scope)).
63
66
  The panel writes the same document. The engine mount row's own `config:` is read at load
@@ -186,11 +189,26 @@ Disable the old engine and enable the new one in the **same composition**, revie
186
189
 
187
190
  ### Live reload scope
188
191
 
189
- The settings panel writes `$DSH_HOME/settings.yaml`. The engine polls that file **and** the
190
- `compaction-control-settings` row every second, so panel edits and edits to that row apply to
191
- the next compaction without a restart. The **engine mount row** (`compaction-control`) is
192
+ The settings panel writes the `compaction-control-settings` row's `config:` (the profile's
193
+ `cordis.patch.yml`). The engine injects the `compactionControlPolicy` service the companion
194
+ row provides and reads the very config the host resolved (volatile cells, updated in place on
195
+ a panel save), so panel edits apply to the next compaction without a restart. Without the
196
+ companion row, the engine polls `settings.yaml` and the patch file every second as a
197
+ fallback. The settings card and the session badge both show the **policy the engine reports
198
+ applying** (value and source) and say so when it disagrees with the saved document or never
199
+ arrives. The **engine mount row** (`compaction-control`) is
192
200
  read at plugin load; editing its `config:` requires a restart.
193
201
 
202
+ **Where those files are looked up**: the engine resolves the DSH home in the host's own
203
+ order — the home the running host reports (`profileContext.home`, provided before any
204
+ profile row mounts), then a non-blank `$DSH_HOME` (`~` expanded), then `os.homedir()/.dsh`,
205
+ matching `@deepseek-ai/dsh-home-paths`; it never reads `HOME`. Before 0.5.15 the Windows
206
+ desktop host had neither variable set (Windows has no `HOME`, and the desktop app does not
207
+ export `DSH_HOME`), so the path collapsed to a relative `.dsh/…`, the policy file was never
208
+ read, and the engine silently ran on its built-in 0.8 baseline while the settings card —
209
+ fed by the loader — still showed 42%. When no candidate file exists at all, the engine now
210
+ prints one `[compaction] WARNING … no profile patch layer found (tried …)`.
211
+
194
212
  ### Threshold semantics
195
213
 
196
214
  The official engine's trigger is
@@ -213,8 +231,9 @@ compaction fires.
213
231
 
214
232
  ## Configuration
215
233
 
216
- The policy can live in the mount row's `config:` or in `$DSH_HOME/settings.yaml` under the
217
- `compaction-control:` section (the panel edits the latter).
234
+ The policy lives in the `compaction-control-settings` row's `config:` (what the panel
235
+ edits); an older profile's `$DSH_HOME/settings.yaml` `compaction-control:` section is still
236
+ read, in this format.
218
237
 
219
238
  ```yaml
220
239
  compaction-control:
package/README.md CHANGED
@@ -49,9 +49,11 @@ models[] → providers{} → default
49
49
  `thresholdTokens` / `retainTokens` 是绝对预算。换算写回父类时使用
50
50
  `(tokens + 0.5) / window`,保证精确回到声明的数;路由没有声明窗口时**拒绝猜**,
51
51
  在真正需要策略的那一步报错并点名路由。
52
- - **热加载(配置,不含代码)。** 引擎每秒轮询 `settings.yaml` 与 `compaction-control-settings`
53
- 行;**策略修改**在下一次压缩生效,不需要重启。但这只覆盖配置:**升级插件版本必须重启
54
- DSH**,已加载的模块不会被替换(见[热加载范围](#热加载范围))。
52
+ - **热加载(配置,不含代码)。** 引擎读的是 companion 行(`compaction-control-settings`)
53
+ 的活配置:宿主把该行的 `config:` 解析成 volatile 单元格,面板保存时单元格就地更新,
54
+ **策略修改**在下一次压缩生效,不需要重启、不经文件、不猜路径。`settings.yaml` 与 patch
55
+ 文件的轮询只在 companion 行缺席时兜底。但这只覆盖配置:**升级插件版本必须重启 DSH**,
56
+ 已加载的模块不会被替换(见[热加载范围](#热加载范围))。
55
57
  - **部分文档合并。** `settings.yaml` 的 `compaction-control:` 段与挂载行 `config:` **逐字段**
56
58
  合并(映射递归、数组整体替换),面板保存不会悄悄抹掉 profile 里的 `models[]` 层。
57
59
  - **设置面板。** 编辑全局层或某个供应商层,切换单位时不留下两个键,空隙过小时给出红字提示;
@@ -182,10 +184,24 @@ dsh plugin --profile web add "$PWD/examples/standard-with-policy"
182
184
 
183
185
  ### 热加载范围
184
186
 
185
- 设置面板写 `$DSH_HOME/settings.yaml`。引擎每秒轮询该文件**以及** `compaction-control-settings`
186
- 行,所以面板修改和这一行的修改会在下一次压缩生效,不需要重启。**引擎挂载行**
187
+ 设置面板写 `compaction-control-settings` 行的 `config:`(profile 的 `cordis.patch.yml`)。
188
+ 引擎注入 companion 行提供的 `compactionControlPolicy` 服务,读的就是宿主解析后的这份配置
189
+ (volatile 单元格,面板保存即就地更新),所以面板修改在下一次压缩生效,不需要重启。
190
+ companion 行缺席时,引擎每秒轮询 `settings.yaml` 与 patch 文件作为兜底。**引擎挂载行**
187
191
  (`compaction-control`)的 `config:` 在插件加载时读取,改它需要重启。
188
192
 
193
+ 设置页卡片与会话头徽标都显示**引擎实际上报的策略**(来源与数值);上报的数值与保存的
194
+ 文档不一致、或引擎没有上报时,两处都会明说——2026-11-30 之前,"保存了但没送达"在界面上
195
+ 和"已生效"长得一模一样。
196
+
197
+ **这两个文件在哪**:引擎按宿主自己的顺序解析 DSH home —— 先取运行中宿主报告的
198
+ `profileContext.home`(挂载任何插件行之前就已提供),再取非空的 `$DSH_HOME`(支持 `~`),
199
+ 最后是 `os.homedir()/.dsh`,与 `@deepseek-ai/dsh-home-paths` 同序;**不读 `HOME`**。
200
+ 0.5.15 之前,Windows 桌面版上这两个变量都没有(Windows 没有 `HOME`,桌面版也不导出
201
+ `DSH_HOME`),路径退化成相对的 `.dsh/…`,策略文件从未被读到,引擎静默跑在内置基线 0.8 上,
202
+ 而设置卡片走 loader、仍显示 42%。现在若所有候选文件都不存在,会打一行
203
+ `[compaction] WARNING … no profile patch layer found (tried …)`。
204
+
189
205
  > ⚠️ **升级插件本身必须重启 DSH。**
190
206
  >
191
207
  > 热加载只覆盖配置文档,**不覆盖代码**。DSH 的加载器把已安装的模块留在进程里:
@@ -222,8 +238,8 @@ floor(min(W × threshold, W − O − headroomTokens))
222
238
 
223
239
  ## 配置
224
240
 
225
- 策略可以写在挂载行的 `config:`,也可以写在 `$DSH_HOME/settings.yaml` 的
226
- `compaction-control:` 段(面板编辑后者)。
241
+ 策略写在 `compaction-control-settings` 行的 `config:`(面板编辑的就是它);旧 profile 的
242
+ `$DSH_HOME/settings.yaml` `compaction-control:` 段仍会被读取,格式如下。
227
243
 
228
244
  ```yaml
229
245
  compaction-control:
package/lib/client.js CHANGED
@@ -44,6 +44,12 @@ window.__ModuleLoader__.load({
44
44
  modelLoading: '正在读取模型列表…',
45
45
  modelEmpty: '当前没有可用的模型路由,只能选 auto。',
46
46
  modelFailed: '模型列表读取失败,只能选 auto。',
47
+ // ── 引擎实际生效的策略(设置页卡片 + 会话头部弹层)────────────
48
+ engineLabel: '引擎实际生效',
49
+ engineHint: '策略引擎当前采用的值;与上方设置不一致时,以引擎为准',
50
+ engineMismatch: '设置与引擎不一致:改动没有送达策略引擎(引擎未重载,或引擎未挂载)。',
51
+ engineMissing: '未收到策略引擎的状态:引擎未挂载,或配置没有送达。上方只是保存的文档,不保证在生效。',
52
+ engineUnknown: '—',
47
53
  // ── 摘要模型的回退链与安全余量 ────────────────────────────────
48
54
  headroom: '安全余量(token)',
49
55
  headroomHint: '留空沿用下层',
@@ -134,6 +140,11 @@ window.__ModuleLoader__.load({
134
140
  modelLoading: 'Reading the model list…',
135
141
  modelEmpty: 'No model route is currently available, so only auto can be chosen.',
136
142
  modelFailed: 'The model list could not be read, so only auto can be chosen.',
143
+ engineLabel: 'Applied by the engine',
144
+ engineHint: 'what the policy engine resolves right now; when it differs from the settings above, the engine wins',
145
+ engineMismatch: 'Settings and engine disagree: the change never reached the policy engine (not reloaded, or not mounted).',
146
+ 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
+ engineUnknown: '—',
137
148
  // ── Summarization fallback chain and reserve ──────────────────
138
149
  headroom: 'Reserve (tokens)',
139
150
  headroomHint: 'blank inherits the layer below',
@@ -270,13 +281,25 @@ window.__ModuleLoader__.load({
270
281
  // operator asks *after* a compaction, not the state they read every time
271
282
  // they look up — the policy headline beside it stays the primary face.
272
283
  '.ccbLast{color:var(--dsw-alias-label-tertiary);font-size:11px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
273
- '.ccbPanel{position:absolute;top:calc(100% + 8px);right:0;z-index:100;box-sizing:border-box;width:286px;background:var(--dsw-specific-menu);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);border:0;border-radius:12px;padding:12px;font-size:12px;line-height:18px;text-align:left}',
284
+ '.ccbPanel{position:absolute;top:calc(100% + 8px);right:0;z-index:100;box-sizing:border-box;width:320px;background:var(--dsw-alias-hovercard-bg);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);border:0;border-radius:12px;padding:12px;font-size:12px;line-height:18px;text-align:left}',
274
285
  '.ccbTitle{margin:0 0 2px;color:var(--dsw-alias-label-primary);font-size:12px;font-weight:500}',
275
286
  '.ccbTarget{margin:0 0 10px;color:var(--dsw-alias-label-tertiary);font-size:11px;word-break:break-all}',
276
287
  '.ccbRows{margin:0;display:flex;flex-direction:column;gap:6px}',
277
- '.ccbRow{display:flex;align-items:baseline;gap:8px}',
278
- '.ccbKey{color:var(--dsw-alias-label-secondary);flex:none;min-width:78px}',
279
- '.ccbVal{margin-left:auto;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;text-align:right}',
288
+ '.ccbRow{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(0,1fr);align-items:baseline;gap:2px 12px}',
289
+ '.ccbKey{color:var(--dsw-alias-label-secondary);min-width:0}',
290
+ '.ccbKey .ccbHint{display:block;margin-top:2px}',
291
+ '.ccbVal{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;text-align:right;min-width:0;overflow-wrap:anywhere}',
292
+ '.ccbDotBad{background:var(--dsw-alias-state-warn-primary)}',
293
+ // ── 模型设置页底部的策略卡片 ──────────────────────────────────
294
+ // 共享 kit 的 `.ccRow` 是 flex + 固定宽控件,控件左边缘随「重置」按钮有无而漂移;
295
+ // 这里改成「标签 + 按需追加列」的网格:列只在有子项时存在,控件统一宽度并右对齐,
296
+ // 有无「重置」按钮的行右边缘都对齐(固定三列会给空列留一个 gap,差 10px)。
297
+ '.cccCard{gap:10px}',
298
+ '.cccCard .ccRow{display:grid;grid-template-columns:minmax(0,1fr);grid-auto-flow:column;grid-auto-columns:max-content;align-items:center;gap:10px}',
299
+ '.cccCard .ccRow > .ccInput,.cccCard .ccRow > .ccInputWide,.cccCard .ccRow > .ccSelect{width:220px;max-width:220px;box-sizing:border-box;justify-self:end}',
300
+ '.cccCard .ccRow > .ccReset{justify-self:end;white-space:nowrap}',
301
+ '.cccEngine{display:flex;align-items:center;gap:8px;margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
302
+ '.cccEngineErr{color:var(--dsw-alias-label-error)}',
280
303
  '.ccbHint{color:var(--dsw-alias-label-tertiary);font-size:11px;margin:0}',
281
304
  '.ccbSrc{color:var(--dsw-alias-label-tertiary);font-size:11px}',
282
305
  '.ccbWarn{color:var(--dsw-alias-label-error);margin:8px 0 0;font-size:11px}',
@@ -701,11 +724,35 @@ window.__ModuleLoader__.load({
701
724
  const stagedChainValid =
702
725
  stagedChainEntry.length > 0 && stagedChainEntry !== primaryRoute && !chain.includes(stagedChainEntry);
703
726
 
727
+ // The engine's own report, so "saved" and "in force" are two different
728
+ // lines on screen. A document that never reached the engine used to look
729
+ // exactly like one that did.
730
+ const engineState = props.useEngineRuntime?.();
731
+ // The engine reports the global default layer it resolved; the card
732
+ // compares against that layer, whichever layer is being edited below.
733
+ const engine = engineReport(
734
+ engineState?.value,
735
+ { thresholdRatio: snapshot?.value?.default?.threshold, thresholdTokens: snapshot?.value?.default?.thresholdTokens },
736
+ t,
737
+ );
704
738
  return jsx.jsxs('div', {
705
- className: 'ccWrap',
739
+ className: 'ccWrap cccCard',
706
740
  children: [
707
741
  jsx.jsx('span', { className: 'ccTitle', children: t('title') }),
708
742
  jsx.jsx('p', { className: 'ccHint', children: t('hint') }),
743
+ jsx.jsxs('p', {
744
+ className: engine.level === 'missing' || engine.level === 'warn' ? 'cccEngine cccEngineErr' : 'cccEngine',
745
+ children: [
746
+ jsx.jsx('span', {
747
+ className: `ccbDot ccbDot${engine.level === 'ok' ? '' : 'Bad'}`,
748
+ }),
749
+ `${t('engineLabel')}: ${
750
+ engine.level === 'missing'
751
+ ? t('engineMissing')
752
+ : `${engine.text}${engine.mismatch ? ` — ${t('engineMismatch')}` : ''}`
753
+ }`,
754
+ ],
755
+ }),
709
756
  locked ? jsx.jsx('p', { className: 'ccError', children: t('memoryNote') }) : null,
710
757
  jsx.jsxs('div', {
711
758
  className: 'ccRow',
@@ -864,7 +911,14 @@ window.__ModuleLoader__.load({
864
911
  }),
865
912
  ],
866
913
  }),
867
- catalog === undefined ? null : jsx.jsx('p', { className: 'ccSubHint', children: t('modelLoading') }),
914
+ // `undefined` is still loading, `null` a failed read, an object the list.
915
+ // The condition used to be inverted: the loading line rendered once
916
+ // the catalog had resolved and never while it was pending (2026-11-30).
917
+ catalog === undefined
918
+ ? jsx.jsx('p', { className: 'ccSubHint', children: t('modelLoading') })
919
+ : catalog === null
920
+ ? jsx.jsx('p', { className: 'ccSubHint', children: t('modelFailed') })
921
+ : null,
868
922
  // ── 摘要模型的 fallback 链 ────────────────────────────────
869
923
  // 顺序即语义:从强到弱依次尝试,最强的免费大模型在前、收费的在后。
870
924
  // 单向不可逆,所以每一行都给出上移/下移,而不是只让用户删了重加。
@@ -1159,6 +1213,23 @@ window.__ModuleLoader__.load({
1159
1213
  * @param props - row content; `hint` renders under the label as the
1160
1214
  * explanation, `unit` as a muted suffix on the value.
1161
1215
  */
1216
+ /**
1217
+ * What the engine says it applies, next to what the document says.
1218
+ *
1219
+ * `runtime` is the engine's report from the companion's volatile cell.
1220
+ * `level` is `ok` when it matches the document, `warn` when it does not
1221
+ * (the Win11 state: card 42 %, engine 80 %), `missing` when no engine has
1222
+ * reported, and `none` while the report has not been read yet.
1223
+ */
1224
+ function engineReport(runtime, view, t) {
1225
+ 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;
1229
+ const mismatch = declared !== undefined && applied !== undefined && declared !== applied;
1230
+ return { level: mismatch ? 'warn' : 'ok', text, mismatch };
1231
+ }
1232
+
1162
1233
  function PolicyRow(props) {
1163
1234
  const { label, value, source, hint, unit, t } = props;
1164
1235
  return jsx.jsxs('div', {
@@ -1292,6 +1363,7 @@ window.__ModuleLoader__.load({
1292
1363
  const [open, setOpen] = react.useState(false);
1293
1364
  const rootRef = react.useRef(null);
1294
1365
  const policy = usePolicy((value) => value);
1366
+ const engineState = props.useEngineRuntime?.();
1295
1367
  /**
1296
1368
  * Whether this client can see the host's policy at all.
1297
1369
  *
@@ -1544,7 +1616,10 @@ window.__ModuleLoader__.load({
1544
1616
  title: aria,
1545
1617
  onClick: () => setOpen(!open),
1546
1618
  children: [
1547
- jsx.jsx('span', { className: autoOn ? 'ccbDot' : 'ccbDot ccbOff' }),
1619
+ jsx.jsx('span', {
1620
+ className:
1621
+ !autoOn ? 'ccbDot ccbOff' : engineReport(engineState?.value, view, t).level === 'ok' ? 'ccbDot' : 'ccbDot ccbDotBad',
1622
+ }),
1548
1623
  jsx.jsx('span', { children: headline }),
1549
1624
  lastSummaryText === undefined
1550
1625
  ? null
@@ -1592,8 +1667,23 @@ window.__ModuleLoader__.load({
1592
1667
  triggerRow === null ? null : jsx.jsx(PolicyRow, { ...triggerRow, t }),
1593
1668
  windowRow === null ? null : jsx.jsx(PolicyRow, { ...windowRow, t }),
1594
1669
  gapRow === null ? null : jsx.jsx(PolicyRow, { ...gapRow, t }),
1670
+ jsx.jsx(PolicyRow, {
1671
+ key: 'engine',
1672
+ label: t('engineLabel'),
1673
+ hint: t('engineHint'),
1674
+ value: engineReport(engineState?.value, view, t).text,
1675
+ t,
1676
+ }),
1595
1677
  ],
1596
1678
  }),
1679
+ (() => {
1680
+ const report = engineReport(engineState?.value, view, t);
1681
+ return report.level === 'warn'
1682
+ ? jsx.jsx('p', { className: 'ccbWarn', children: t('engineMismatch') })
1683
+ : report.level === 'missing' && engineState?.status === 'ready'
1684
+ ? jsx.jsx('p', { className: 'ccbWarn', children: t('engineMissing') })
1685
+ : null;
1686
+ })(),
1597
1687
  autoOn ? null : jsx.jsx('p', { className: 'ccbWarn', children: t('pOffHint') }),
1598
1688
  !policyKnown ? jsx.jsx('p', { className: 'ccbWarn', children: t('badgeUnknownHint') }) : null,
1599
1689
  autoOn && gapShort ? jsx.jsx('p', { className: 'ccbWarn', children: t('pGapWarn') }) : null,
@@ -1702,6 +1792,51 @@ window.__ModuleLoader__.load({
1702
1792
  return value;
1703
1793
  };
1704
1794
 
1795
+ /**
1796
+ * The engine's report of what it applies, read from the companion's
1797
+ * volatile `runtime` cell through `settings.describe`.
1798
+ *
1799
+ * The cell is written by the engine and emits no document event, so the
1800
+ * form snapshot never refreshes on its own; a slow poll is the same
1801
+ * trade the resilience card makes for its breaker state. It changes
1802
+ * only on a policy reload, so eight seconds is plenty.
1803
+ */
1804
+ let runtimeState = { status: 'idle', value: undefined };
1805
+ const runtimeListeners = new Set();
1806
+ const readRuntime = async () => {
1807
+ if (runtimeState.status === 'loading' || ctx.remote?.settings?.describe === undefined) return;
1808
+ runtimeState = { ...runtimeState, status: 'loading' };
1809
+ try {
1810
+ const response = await ctx.remote.settings.describe();
1811
+ if (!response.ok) throw new Error(`${response.error.code}: ${response.error.message}`);
1812
+ const namespaces = response.value?.namespaces ?? [];
1813
+ const row = SETTINGS_ENTRIES.map((id) => namespaces.find((entry) => entry.ns === id)).find(
1814
+ (entry) => entry !== undefined && entry.value?.runtime !== undefined,
1815
+ );
1816
+ runtimeState = { status: 'ready', value: row?.value?.runtime };
1817
+ } catch {
1818
+ runtimeState = { status: 'error', value: undefined };
1819
+ }
1820
+ for (const listener of runtimeListeners) listener();
1821
+ };
1822
+ const useEngineRuntime = () => {
1823
+ const [snapshot, setSnapshot] = react.useState(runtimeState);
1824
+ react.useEffect(() => {
1825
+ void readRuntime();
1826
+ const listener = () => setSnapshot(runtimeState);
1827
+ runtimeListeners.add(listener);
1828
+ const timer = setInterval(() => void readRuntime(), 8000);
1829
+ // Browsers return a number; Node (tests) a Timeout that would otherwise
1830
+ // keep the process alive after the last test.
1831
+ timer.unref?.();
1832
+ return () => {
1833
+ clearInterval(timer);
1834
+ runtimeListeners.delete(listener);
1835
+ };
1836
+ }, []);
1837
+ return snapshot;
1838
+ };
1839
+
1705
1840
  ctx.slots.inject('settings.models.footer', function* () {
1706
1841
  yield ctx.slots.register(
1707
1842
  {
@@ -1712,6 +1847,7 @@ window.__ModuleLoader__.load({
1712
1847
  t,
1713
1848
  scope,
1714
1849
  useCatalog,
1850
+ useEngineRuntime,
1715
1851
  useScope: (select) => {
1716
1852
  const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
1717
1853
  react.useEffect(() => scope.subscribe(() => setSnapshot(scope.getSnapshot())), []);
@@ -1756,6 +1892,7 @@ window.__ModuleLoader__.load({
1756
1892
  }
1757
1893
  return {
1758
1894
  useSession: () => binding.session,
1895
+ useEngineRuntime,
1759
1896
  usePolicy: (select) => {
1760
1897
  const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
1761
1898
  react.useEffect(() => scope.subscribe(() => setSnapshot(scope.getSnapshot())), []);
@@ -1777,6 +1914,10 @@ window.__ModuleLoader__.load({
1777
1914
  'locale',
1778
1915
  'remote',
1779
1916
  'remote.session',
1917
+ // The engine's report is read through `settings.describe` (the volatile
1918
+ // `runtime` cell emits no document event); a remote is reachable only
1919
+ // when its slice is injected — anything else throws at first use.
1920
+ 'remote.settings',
1780
1921
  'sessions',
1781
1922
  // 0.2.0:`settingsScope` 已不存在,settings 表单服务改名 `configForms`
1782
1923
  // (由 dsh-client-ui-settings 提供)。名字写错 = entry 永远 pending。
package/lib/index.js CHANGED
@@ -31,9 +31,13 @@ import {
31
31
  resolveSummarizationEffort,
32
32
  toBasicConfig,
33
33
  } from './policy.js';
34
- import { SETTINGS_NS, installSettings, plainConfig, settingsSchema } from './settings.js';
34
+ import { isVolatile } from '@deepseek-ai/cosmokit';
35
+ import { POLICY_SERVICE, policyDocumentOf, plainConfig, runtimeSchema } from './settings.js';
35
36
  import { patchFilePaths, settingsFilePath, watchPatchFile, watchSettingsFile } from './settings-file.js';
36
37
 
38
+ /** cosmokit 的共享 volatile 写协议;设置页 describe 读取的就是这个单元格。 */
39
+ const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write');
40
+
37
41
  export { CompactionConfigError } from './policy.js';
38
42
  export {
39
43
  AUTO,
@@ -47,7 +51,7 @@ export {
47
51
  resolveSummarizationEffort,
48
52
  toBasicConfig,
49
53
  } from './policy.js';
50
- export { SETTINGS_NS, plainConfig, settingsSchema } from './settings.js';
54
+ export { POLICY_SERVICE, SETTINGS_NS, plainConfig, policyDocumentOf, runtimeSchema } from './settings.js';
51
55
 
52
56
  // The two range re-pricing helpers are exported because the manual-retention
53
57
  // contract rests on them: a test can drive them directly and assert the shape of
@@ -499,8 +503,15 @@ export class CompactionControlEngine extends BasicCompactionEngine {
499
503
  /** Warning texts already printed, so an unworkable policy is stated once. */
500
504
  reportedWarnings = new Set();
501
505
 
502
- /** Live settings document, or undefined when no settings provider is mounted. */
503
- settingsState;
506
+ /**
507
+ * The companion row's live document, or undefined until that row mounts.
508
+ *
509
+ * @type {{ current: () => object | undefined, runtimeRef?: object } | undefined}
510
+ */
511
+ _livePolicy;
512
+
513
+ /** `JSON.stringify` of the live document last resolved, so a card save between two steps is noticed. */
514
+ _liveSignature;
504
515
 
505
516
  /**
506
517
  * @param ctx - context providing the LLM, token-meter, and session services.
@@ -521,15 +532,32 @@ export class CompactionControlEngine extends BasicCompactionEngine {
521
532
  this.controlConfig = controlConfig;
522
533
  this.baseConfig = controlConfig;
523
534
 
524
- // Publish the user-facing settings section, based on this plugin's own config,
525
- // so a profile ships a working policy the user tunes from the settings page.
526
- // With no settings provider the section is never published at all.
527
- this.settingsState = installSettings(ctx, SETTINGS_NS, settingsSchema, controlConfig, () => {
528
- // The document changed (possibly an external file edit): drop every cached
529
- // policy, or the cache would pin it for the life of the process.
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.
540
+ //
541
+ // The file readers below stay as the fallback for a profile that mounts no
542
+ // companion row, and for an edit made straight to the patch file.
543
+ ctx.inject([POLICY_SERVICE], (policyCtx) => {
544
+ this._livePolicy = policyCtx[POLICY_SERVICE];
530
545
  this.reloadPolicy();
531
546
  });
532
547
 
548
+ // The running host's own facts, provided before any profile row mounts
549
+ // (`boot()` runs `prepare(hostCtx)` — which provides `profileContext` —
550
+ // before `mountRootInclude`). `home` is the harness home the host actually
551
+ // resolved and `name` the running profile, so both file readers below work
552
+ // with no help from the environment at all. On Windows the desktop host
553
+ // passes neither `DSH_HOME` nor `HOME` (Windows has no `HOME`), which is how
554
+ // every candidate used to resolve to a path that does not exist (2026-11-28).
555
+ const profileContext = ctx.get?.('profileContext');
556
+ const hostHome = typeof profileContext?.home === 'string' ? profileContext.home : undefined;
557
+ // The exact patch file the launcher resolved — the same value the config
558
+ // editor reads — so no path is derived when the host has already answered.
559
+ const patchPath = typeof profileContext?.patchPath === 'string' ? profileContext.patchPath : undefined;
560
+
533
561
  // Read the same section straight from `settings.yaml` as well.
534
562
  //
535
563
  // The injected path above is canonical, but it does not reach a preset-plane
@@ -537,7 +565,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
537
565
  // the file said 0.2, with no change notification. This reader gives the engine
538
566
  // the one source both realms share and a person actually edits.
539
567
  this._settingsFileWatcher = watchSettingsFile({
540
- file: settingsFilePath(),
568
+ file: settingsFilePath(hostHome),
541
569
  fallbackSection: controlConfig,
542
570
  onSection: (section, origin) => {
543
571
  this._fileSection = section;
@@ -562,15 +590,26 @@ export class CompactionControlEngine extends BasicCompactionEngine {
562
590
  // *parent* process's profile when this dsh was launched from an agent's
563
591
  // shell tool. `profileContext` is the host's own answer (see
564
592
  // `patchFilePaths` for the measured failure).
565
- const runningProfile = ctx.get?.('profileContext')?.name;
593
+ const runningProfile = profileContext?.name;
566
594
  this._patchFileWatcher = watchPatchFile({
567
- files: patchFilePaths(process.env, runningProfile),
595
+ files: patchFilePaths(process.env, runningProfile, hostHome, patchPath),
568
596
  onConfig: (config) => {
569
597
  // `reloadPolicy` derives `source=` from which layers are present, so
570
598
  // this callback only records the value.
571
599
  this._patchEntry = config;
572
600
  this.reloadPolicy();
573
601
  },
602
+ // 2026-11-28, Win11 desktop: no candidate existed because the home was
603
+ // derived from `HOME`, which Windows does not set. Every gate then ran on
604
+ // the 0.8 baseline while the settings card read 42%, and nothing said so
605
+ // for days. Name the paths once so the next occurrence is one line.
606
+ onMissing: (files) => {
607
+ const message =
608
+ `compaction-control: no profile patch layer found (tried ${files.join(', ')}); ` +
609
+ 'the engine runs on the composition defaults until the layer appears — check DSH_HOME and the running profile';
610
+ this.ctx.logger?.warn?.(message);
611
+ process.stderr.write(`[compaction] WARNING fiber=${this.ctx.fiber?.name} ${message}\n`);
612
+ },
574
613
  onError: (error) => {
575
614
  this.ctx.logger?.warn?.(`compaction-control: profile patch unreadable (${error.message}); keeping the last good policy`);
576
615
  },
@@ -582,11 +621,38 @@ export class CompactionControlEngine extends BasicCompactionEngine {
582
621
  // from outside (the card renders either way, and a disabled or auto:false
583
622
  // engine prints no gate diagnostic at all). The fiber name says *which* mount
584
623
  // this is — a host-plane and a preset-realm engine print the same numbers.
585
- process.stderr.write(
624
+ const startup =
586
625
  `[compaction] engine up: fiber=${this.ctx.fiber?.name} ` +
587
- `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
626
+ `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
588
627
  `retain=${declaredText(this.controlConfig.default.retain, this.controlConfig.default.retainTokens)} auto=${controlConfig.auto} ` +
589
- `thinking=${THINKING_OFF} source=${this._fileOrigin}\n`,
628
+ `thinking=${THINKING_OFF} source=${this._fileOrigin}`;
629
+ process.stderr.write(`${startup}\n`);
630
+ // The Windows desktop host keeps no stderr; its own log plane is the logger.
631
+ this.ctx.logger?.info?.(startup);
632
+ }
633
+
634
+ /**
635
+ * Report the policy this engine applies into the companion's `runtime` cell.
636
+ *
637
+ * The settings card and the session badge read that cell, so "saved but never
638
+ * delivered" shows up as a mismatch on screen instead of as a session that
639
+ * quietly grows past the threshold the operator believes is in force.
640
+ */
641
+ publishRuntime() {
642
+ const ref = this._livePolicy?.runtimeRef;
643
+ if (ref === undefined || typeof ref[VOLATILE_WRITE] !== 'function') return;
644
+ const declared = this.controlConfig.default;
645
+ ref[VOLATILE_WRITE](
646
+ runtimeSchema({
647
+ threshold: declared.threshold,
648
+ thresholdTokens: declared.thresholdTokens,
649
+ retain: declared.retain,
650
+ retainTokens: declared.retainTokens,
651
+ auto: this.controlConfig.auto,
652
+ source: this._fileOrigin,
653
+ fiber: this.ctx.fiber?.name ?? '',
654
+ updatedAt: Date.now(),
655
+ }),
590
656
  );
591
657
  }
592
658
 
@@ -609,6 +675,9 @@ export class CompactionControlEngine extends BasicCompactionEngine {
609
675
  // re-reads it is exactly how an edit went unnoticed until restart.
610
676
  let document = this.baseConfig;
611
677
  let origin = 'composition';
678
+ // Recorded before validation: a live document that is refused must not be
679
+ // re-examined on every step until it changes again.
680
+ this._liveSignature = this._livePolicy === undefined ? undefined : JSON.stringify(this._livePolicy.current());
612
681
  // `_fileOrigin` says where `_fileSection` came from, and it is the only
613
682
  // honest answer: when `settings.yaml` is absent the watcher still reports
614
683
  // the composition as a fallback section, so testing `_fileSection` alone
@@ -618,11 +687,14 @@ export class CompactionControlEngine extends BasicCompactionEngine {
618
687
  if (this._fileSection !== undefined && this._fileOrigin === 'settings.yaml') {
619
688
  document = overlayDocument(document, this._fileSection);
620
689
  origin = 'settings.yaml';
621
- } else if (this.settingsState !== undefined) {
622
- const current = this.settingsState.current();
623
- if (current !== undefined) {
624
- document = current;
625
- origin = 'settings-service';
690
+ } else if (this._livePolicy !== undefined) {
691
+ // The companion row's own config, as the loader resolved it: the bundle's
692
+ // composition under the user's override. Overlaid for the same reason as
693
+ // the file layers — a partial save must not drop the rest.
694
+ const live = this._livePolicy.current();
695
+ if (live !== undefined) {
696
+ document = overlayDocument(document, live);
697
+ origin = 'companion';
626
698
  }
627
699
  }
628
700
  if (this._patchEntry !== undefined) {
@@ -647,6 +719,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
647
719
  `routes=${Object.keys(this.controlConfig.providers).join(',') || '-'} ` +
648
720
  `models=${this.controlConfig.models.length} source=${this._fileOrigin})`,
649
721
  );
722
+ this.publishRuntime();
650
723
  return true;
651
724
  }
652
725
 
@@ -658,6 +731,14 @@ export class CompactionControlEngine extends BasicCompactionEngine {
658
731
  * window was seen first.
659
732
  */
660
733
  policyFor(target, contextWindow) {
734
+ // The loader updates the companion's cells without an event this row can
735
+ // hear (`loader/volatile-update` is scoped to the companion's own fiber),
736
+ // so the live document is compared by value here — a few small objects per
737
+ // step — and any difference is resolved before the cache is consulted.
738
+ if (this._livePolicy !== undefined) {
739
+ const signature = JSON.stringify(this._livePolicy.current());
740
+ if (signature !== this._liveSignature) this.reloadPolicy();
741
+ }
661
742
  const key = `${target.provider}\u0000${target.model}\u0000${contextWindow ?? ''}`;
662
743
  const cached = this.policyCache.get(key);
663
744
  if (cached !== undefined) return cached;
@@ -1436,10 +1517,13 @@ export class CompactionControlSettings {
1436
1517
  providers: z.dict(layer).volatile(),
1437
1518
  models: z.array(modelLayer).volatile(),
1438
1519
  auto: z.boolean().volatile(),
1520
+ // The engine's report of what it applies; written only into the cell, never
1521
+ // into the patch file. Declared volatile so the loader hands out a live cell.
1522
+ runtime: runtimeSchema.volatile(),
1439
1523
  });
1440
1524
 
1441
- /** Live settings document, exposed for tests and diagnostics. */
1442
- settingsState;
1525
+ /** The row's own config, cells included: the live view every engine reads. */
1526
+ config;
1443
1527
 
1444
1528
  /**
1445
1529
  * @param ctx - context that may provide the `settings` service.
@@ -1448,8 +1532,15 @@ export class CompactionControlSettings {
1448
1532
  constructor(ctx, config = {}) {
1449
1533
  // Validated for the same reason the engine validates: a bad document
1450
1534
  // should fail where it was written, naming the field.
1451
- const base = resolveConfig(plainConfig(config));
1452
- this.settingsState = installSettings(ctx, SETTINGS_NS, settingsSchema, base, () => {});
1535
+ resolveConfig(policyDocumentOf(config));
1536
+ this.config = config;
1537
+ // One service per row, read by every engine that can see this context. The
1538
+ // loader keeps these very cell objects and updates them in place, so a
1539
+ // reader that calls `current()` after a card save sees the new document.
1540
+ ctx.provide(POLICY_SERVICE, {
1541
+ current: () => policyDocumentOf(this.config),
1542
+ runtimeRef: isVolatile(config?.runtime) ? config.runtime : undefined,
1543
+ });
1453
1544
  // Publish the standing rule that compaction is automatic. This row is the
1454
1545
  // right owner because it is the only one mounted unconditionally on the host
1455
1546
  // plane — its scope is global, so no preset has to restate the rule — and
@@ -1470,7 +1561,7 @@ export class CompactionControlSettings {
1470
1561
  * @returns the merged document.
1471
1562
  */
1472
1563
  currentPolicy() {
1473
- return this.settingsState.current();
1564
+ return resolveConfig(policyDocumentOf(this.config));
1474
1565
  }
1475
1566
  }
1476
1567
 
@@ -22,30 +22,79 @@
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, patchPath = undefined) {
92
+ const home = resolveDshHome(env, hostHome);
93
+ // The host reports the exact file it resolved (`ctx.profileContext.patchPath`),
94
+ // the same value the config editor reads. It needs no derivation, and once it
95
+ // is known nothing else is tried: a fallback to another profile's file would
96
+ // apply that profile's policy whenever this one carries no entry.
97
+ if (typeof patchPath === 'string' && patchPath !== '') return [resolve(patchPath)];
49
98
  const profiles = [];
50
99
  // `profileName` is the authoritative answer: the host exposes the *running*
51
100
  // profile as `ctx.profileContext.name`, and this plugin passes it in.
@@ -367,13 +416,23 @@ export function watchSettingsFile(options) {
367
416
  * The first candidate that yields a config wins, and the reported `origin`
368
417
  * names the file so a log line can tell the two sources apart.
369
418
  *
370
- * @param options - `files`, `entryId` (string or candidate ids), `onConfig`, `onError`, `intervalMs`.
419
+ * A candidate that does not exist is the normal case for every file but one,
420
+ * so it is skipped quietly — but when *no* candidate exists the engine is
421
+ * running on the composition defaults, which for this plugin means the built-in
422
+ * baseline rather than the operator's policy. That is reported once through
423
+ * `onMissing`, naming the paths that were tried: on 2026-11-28 the Windows
424
+ * desktop host resolved every candidate to a non-existent path and the only
425
+ * symptom was a session that compacted at 80% instead of 42%.
426
+ *
427
+ * @param options - `files`, `entryId` (string or candidate ids), `onConfig`, `onError`, `onMissing`, `intervalMs`.
371
428
  * @returns a disposer that stops watching.
372
429
  */
373
430
  export function watchPatchFile(options) {
374
- const { files, entryId = PATCH_ENTRY_IDS, onConfig, onError, intervalMs = 1000 } = options;
431
+ const { files, entryId = PATCH_ENTRY_IDS, onConfig, onError, onMissing, intervalMs = 1000 } = options;
375
432
  let last = null;
433
+ let missingReported = false;
376
434
  const read = () => {
435
+ let anyExists = false;
377
436
  for (const file of files) {
378
437
  let text;
379
438
  try {
@@ -383,6 +442,7 @@ export function watchPatchFile(options) {
383
442
  if (error?.code !== 'ENOENT') onError?.(error);
384
443
  continue;
385
444
  }
445
+ anyExists = true;
386
446
  let config;
387
447
  try {
388
448
  config = readPatchEntryConfig(text, entryId);
@@ -399,6 +459,12 @@ export function watchPatchFile(options) {
399
459
  }
400
460
  // No candidate carried the entry: leave the last good config in place
401
461
  // rather than reverting to the composition on a transient read failure.
462
+ // No candidate *exists* at all is different: nothing will ever arrive,
463
+ // and the operator has to hear which paths were tried.
464
+ if (!anyExists && !missingReported) {
465
+ missingReported = true;
466
+ onMissing?.(files);
467
+ }
402
468
  };
403
469
  read();
404
470
  const timer = setInterval(read, intervalMs);
package/lib/settings.js CHANGED
@@ -1,11 +1,24 @@
1
1
  /**
2
2
  * Settings wiring for dsh-compaction-policy-engine.
3
3
  *
4
- * `ctx.settings.installSection(ns, schema, entry, hooks)` publishes a namespaced
5
- * section of the user settings document and hands back a live getter; the
6
- * provider already merges "schema defaults, then the registrant's composition
7
- * base, then the user document", so this module must not merge anything itself.
8
- * Validation is split the same way as `policy.js`: shape here, meaning there.
4
+ * How the user's document reaches the engine (2026-11-30):
5
+ *
6
+ * settings card ──mutate──▶ loader entry `compaction-control-settings`
7
+ * │ volatile cells, updated in place
8
+ * ▼
9
+ * `compactionControlPolicy` service ──▶ engine (host plane
10
+ * or preset realm)
11
+ *
12
+ * The companion row's config is resolved by the loader into volatile cells, and
13
+ * a save from the card updates those cells in place (`_commitVolatile` in
14
+ * cordis-plugin-loader). A service that reads the cells is therefore a live view
15
+ * of what the user saved: no file, no poll, no path to derive.
16
+ *
17
+ * What this module must not do is call a `settings` service API: the
18
+ * `installSection` it used to call exists nowhere in dsh 0.2.2, so that channel
19
+ * never delivered a single value — the engine ran on its baseline while the card,
20
+ * fed by the loader, showed the saved numbers. Measured on a Win11 desktop over
21
+ * days (2026-11-24 → 11-30).
9
22
  *
10
23
  * @module dsh-compaction-policy-engine/settings
11
24
  */
@@ -16,6 +29,12 @@ import { isVolatile } from '@deepseek-ai/cosmokit';
16
29
  /** The settings namespace this plugin owns. Must be lowercase-hyphenated. */
17
30
  export const SETTINGS_NS = 'compaction-control';
18
31
 
32
+ /**
33
+ * The cordis service through which the companion row hands its live document to
34
+ * every engine that can see it (the host plane and each preset realm).
35
+ */
36
+ export const POLICY_SERVICE = 'compactionControlPolicy';
37
+
19
38
  /**
20
39
  * Fields shared by the global default and every override layer. The vocabulary
21
40
  * mirrors `policy.js` (`threshold`/`retain`), not the parent's
@@ -50,35 +69,25 @@ const modelLayer = z.object({
50
69
  });
51
70
 
52
71
  /**
53
- * Schema of the user's `compaction-control` section.
72
+ * What the engine reports back: the policy it actually applies, written into a
73
+ * volatile `runtime` cell the settings plane reads.
54
74
  *
55
- * Deliberately the same shape as the plugin's own `Config`, so the same
56
- * `resolveConfig` accepts either document.
75
+ * This is the answer to "did my change reach the session I am looking at".
76
+ * Without it the card can only echo the saved document, and a document that
77
+ * never arrived looks exactly like one that did. Flat and JSON-only: cosmokit
78
+ * freezes what a cell holds, and the value crosses the wire to the browser.
57
79
  */
58
- export const settingsSchema = z.object({
59
- default: z.object(layerFields).volatile(),
60
- providers: z.dict(z.object(layerFields)).volatile(),
61
- models: z.array(modelLayer).volatile(),
62
- auto: z.boolean().volatile(),
80
+ export const runtimeSchema = z.object({
81
+ threshold: z.number().description('the ratio the gate applies'),
82
+ thresholdTokens: z.number().step(1).min(1).description('the absolute budget the gate applies'),
83
+ retain: z.number().description('the tail ratio a compaction keeps'),
84
+ retainTokens: z.number().step(1).min(1).description('the absolute tail a compaction keeps'),
85
+ auto: z.boolean().description('whether the pressure gate is armed'),
86
+ source: z.string().description('which layer the engine resolved last'),
87
+ fiber: z.string().description('the mount that reported'),
88
+ updatedAt: z.number().description('Unix milliseconds of the report'),
63
89
  });
64
90
 
65
- /**
66
- * Publish this plugin's section and keep a live getter for the effective
67
- * document.
68
- *
69
- * `current()` delegates to the provider on every call, so an external edit is
70
- * visible without a restart; caching it would reintroduce exactly the staleness
71
- * this module exists to remove. With no settings provider (a bare profile, or a
72
- * unit test) the section is never published and the plugin runs on its Cordis
73
- * config alone — a deliberate degradation every existing deployment relies on.
74
- *
75
- * @param ctx - context that may provide the `settings` service.
76
- * @param ns - settings namespace to own.
77
- * @param schema - schema resolving the section.
78
- * @param base - the composition default, used until the user overrides it.
79
- * @param onChange - called when the effective document changes.
80
- * @returns an object exposing the live document and whether a provider took it.
81
- */
82
91
  /**
83
92
  * Unwrap the live cells a `.volatile()` field resolves to.
84
93
  *
@@ -95,44 +104,17 @@ export function plainConfig(value) {
95
104
  return value;
96
105
  }
97
106
 
98
- export function installSettings(ctx, ns, schema, base, onChange) {
99
- /**
100
- * Getter over the provider's resolved document.
101
- *
102
- * Starts by returning the composition base, so `current()` is meaningful
103
- * even before a provider responds — and stays meaningful when none exists.
104
- */
105
- let read = () => base;
106
-
107
- const state = {
108
- /** Whether a settings provider took the section. */
109
- installed: false,
110
- /**
111
- * The effective document: composition default overlaid by the user
112
- * section.
113
- *
114
- * Delegates to the provider's getter on every call rather than
115
- * snapshotting, which is what makes an external edit to `settings.yaml`
116
- * visible without a restart.
117
- */
118
- current: () => read(),
119
- };
120
-
121
- ctx.inject(['settings'], (settingsCtx) => {
122
- settingsCtx.settings.installSection(ctx, ns, schema, base, {
123
- // The provider calls this with a getter over its own resolved value,
124
- // so calling it here yields the merged document. It is a getter, not a
125
- // snapshot: re-reading inside `current()` is what makes a later write
126
- // visible without a restart.
127
- setSource: (providerRead) => {
128
- read = providerRead;
129
- },
130
- onChange: () => {
131
- state.installed = true;
132
- onChange();
133
- },
134
- });
135
- });
136
-
137
- return state;
138
- }
107
+ /**
108
+ * The policy document inside a companion config, with the engine's `runtime`
109
+ * report left out: it is not part of the document, and `resolveConfig` rejects
110
+ * unknown top-level fields — by design.
111
+ *
112
+ * @param config - the companion row's config, cells or plain.
113
+ * @returns the plain document, without `runtime`.
114
+ */
115
+ export function policyDocumentOf(config) {
116
+ const plain = plainConfig(config ?? {});
117
+ if (plain === null || typeof plain !== 'object' || Array.isArray(plain)) return plain;
118
+ const { runtime, ...document } = plain;
119
+ return document;
120
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magic6/dsh-compaction-policy-engine",
3
- "version": "0.5.14",
3
+ "version": "0.5.16",
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",