@magic6/dsh-compaction-policy-engine 0.5.15 → 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,50 @@ 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
+
7
51
  ## [0.5.15] - 2026-11-28
8
52
 
9
53
  ### Fixed — the policy now reaches the engine on the Windows desktop host
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,9 +189,14 @@ 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
 
194
202
  **Where those files are looked up**: the engine resolves the DSH home in the host's own
@@ -223,8 +231,9 @@ compaction fires.
223
231
 
224
232
  ## Configuration
225
233
 
226
- The policy can live in the mount row's `config:` or in `$DSH_HOME/settings.yaml` under the
227
- `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.
228
237
 
229
238
  ```yaml
230
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,16 @@ 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
+
189
197
  **这两个文件在哪**:引擎按宿主自己的顺序解析 DSH home —— 先取运行中宿主报告的
190
198
  `profileContext.home`(挂载任何插件行之前就已提供),再取非空的 `$DSH_HOME`(支持 `~`),
191
199
  最后是 `os.homedir()/.dsh`,与 `@deepseek-ai/dsh-home-paths` 同序;**不读 `HOME`**。
@@ -230,8 +238,8 @@ floor(min(W × threshold, W − O − headroomTokens))
230
238
 
231
239
  ## 配置
232
240
 
233
- 策略可以写在挂载行的 `config:`,也可以写在 `$DSH_HOME/settings.yaml` 的
234
- `compaction-control:` 段(面板编辑后者)。
241
+ 策略写在 `compaction-control-settings` 行的 `config:`(面板编辑的就是它);旧 profile 的
242
+ `$DSH_HOME/settings.yaml` `compaction-control:` 段仍会被读取,格式如下。
235
243
 
236
244
  ```yaml
237
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,24 +532,31 @@ 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
 
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;
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;
542
560
 
543
561
  // Read the same section straight from `settings.yaml` as well.
544
562
  //
@@ -574,7 +592,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
574
592
  // `patchFilePaths` for the measured failure).
575
593
  const runningProfile = profileContext?.name;
576
594
  this._patchFileWatcher = watchPatchFile({
577
- files: patchFilePaths(process.env, runningProfile, hostHome),
595
+ files: patchFilePaths(process.env, runningProfile, hostHome, patchPath),
578
596
  onConfig: (config) => {
579
597
  // `reloadPolicy` derives `source=` from which layers are present, so
580
598
  // this callback only records the value.
@@ -603,11 +621,38 @@ export class CompactionControlEngine extends BasicCompactionEngine {
603
621
  // from outside (the card renders either way, and a disabled or auto:false
604
622
  // engine prints no gate diagnostic at all). The fiber name says *which* mount
605
623
  // this is — a host-plane and a preset-realm engine print the same numbers.
606
- process.stderr.write(
624
+ const startup =
607
625
  `[compaction] engine up: fiber=${this.ctx.fiber?.name} ` +
608
- `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
626
+ `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
609
627
  `retain=${declaredText(this.controlConfig.default.retain, this.controlConfig.default.retainTokens)} auto=${controlConfig.auto} ` +
610
- `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
+ }),
611
656
  );
612
657
  }
613
658
 
@@ -630,6 +675,9 @@ export class CompactionControlEngine extends BasicCompactionEngine {
630
675
  // re-reads it is exactly how an edit went unnoticed until restart.
631
676
  let document = this.baseConfig;
632
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());
633
681
  // `_fileOrigin` says where `_fileSection` came from, and it is the only
634
682
  // honest answer: when `settings.yaml` is absent the watcher still reports
635
683
  // the composition as a fallback section, so testing `_fileSection` alone
@@ -639,11 +687,14 @@ export class CompactionControlEngine extends BasicCompactionEngine {
639
687
  if (this._fileSection !== undefined && this._fileOrigin === 'settings.yaml') {
640
688
  document = overlayDocument(document, this._fileSection);
641
689
  origin = 'settings.yaml';
642
- } else if (this.settingsState !== undefined) {
643
- const current = this.settingsState.current();
644
- if (current !== undefined) {
645
- document = current;
646
- 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';
647
698
  }
648
699
  }
649
700
  if (this._patchEntry !== undefined) {
@@ -668,6 +719,7 @@ export class CompactionControlEngine extends BasicCompactionEngine {
668
719
  `routes=${Object.keys(this.controlConfig.providers).join(',') || '-'} ` +
669
720
  `models=${this.controlConfig.models.length} source=${this._fileOrigin})`,
670
721
  );
722
+ this.publishRuntime();
671
723
  return true;
672
724
  }
673
725
 
@@ -679,6 +731,14 @@ export class CompactionControlEngine extends BasicCompactionEngine {
679
731
  * window was seen first.
680
732
  */
681
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
+ }
682
742
  const key = `${target.provider}\u0000${target.model}\u0000${contextWindow ?? ''}`;
683
743
  const cached = this.policyCache.get(key);
684
744
  if (cached !== undefined) return cached;
@@ -1457,10 +1517,13 @@ export class CompactionControlSettings {
1457
1517
  providers: z.dict(layer).volatile(),
1458
1518
  models: z.array(modelLayer).volatile(),
1459
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(),
1460
1523
  });
1461
1524
 
1462
- /** Live settings document, exposed for tests and diagnostics. */
1463
- settingsState;
1525
+ /** The row's own config, cells included: the live view every engine reads. */
1526
+ config;
1464
1527
 
1465
1528
  /**
1466
1529
  * @param ctx - context that may provide the `settings` service.
@@ -1469,8 +1532,15 @@ export class CompactionControlSettings {
1469
1532
  constructor(ctx, config = {}) {
1470
1533
  // Validated for the same reason the engine validates: a bad document
1471
1534
  // should fail where it was written, naming the field.
1472
- const base = resolveConfig(plainConfig(config));
1473
- 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
+ });
1474
1544
  // Publish the standing rule that compaction is automatic. This row is the
1475
1545
  // right owner because it is the only one mounted unconditionally on the host
1476
1546
  // plane — its scope is global, so no preset has to restate the rule — and
@@ -1491,7 +1561,7 @@ export class CompactionControlSettings {
1491
1561
  * @returns the merged document.
1492
1562
  */
1493
1563
  currentPolicy() {
1494
- return this.settingsState.current();
1564
+ return resolveConfig(policyDocumentOf(this.config));
1495
1565
  }
1496
1566
  }
1497
1567
 
@@ -88,8 +88,13 @@ export function settingsFilePath(home = resolveDshHome()) {
88
88
  * @param hostHome - the harness home reported by the running host, when known.
89
89
  * @returns absolute path candidates, most specific first.
90
90
  */
91
- export function patchFilePaths(env = process.env, profileName = undefined, hostHome = undefined) {
91
+ export function patchFilePaths(env = process.env, profileName = undefined, hostHome = undefined, patchPath = undefined) {
92
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)];
93
98
  const profiles = [];
94
99
  // `profileName` is the authoritative answer: the host exposes the *running*
95
100
  // profile as `ctx.profileContext.name`, and this plugin passes it in.
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.15",
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",