dsh-context-kit 0.1.1 → 0.2.0

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/README.md CHANGED
@@ -41,6 +41,7 @@ Where it stores things:
41
41
 
42
42
  ```
43
43
  <profile>/dsh-context-kit/settings.json # what the panel edits
44
+ <profile>/dsh-context-kit/usage-cache.json # parsed session stats, keyed by path+mtime+size
44
45
  <profile>/cordis.patch.yml # managed block: generated, not hand-written
45
46
  <profile>/dsh-context-kit/backups/ # every overwrite keeps the previous file (last 10)
46
47
  ```
@@ -49,6 +50,32 @@ Precedence: `settings.json` wins over the plugin's `config.presets` in the bundl
49
50
  plugin row can stay empty (`presets: {}`) and the panel is the single place where numbers live — the
50
51
  managed block in `cordis.patch.yml` always reflects what you last applied.
51
52
 
53
+ ## Effect measurement
54
+
55
+ The second card in the panel answers "did this actually save anything?" without pretending to know
56
+ more than it can.
57
+
58
+ **Measured** (read from `~/.dsh/sessions/**/session.v4.jsonl.zstd`): steps, cache-hit / cache-miss /
59
+ output tokens, compaction count, average and peak context, cost expressed in hit-equivalents
60
+ (`miss × 10`, `output × 15`, hit = 1), and a rework signal — repeated identical tool calls, which is
61
+ the first sign compaction went too deep.
62
+
63
+ **Attributed by policy.** A session that compacted at ~712K ran under a different threshold than one
64
+ that compacted at ~419K, so the ledger is split by the observed trigger height (bucketed to 8K;
65
+ sessions that never compacted are listed as unclassifiable). "Data under the current threshold" tells
66
+ you how much of the window was actually produced by the setting you are looking at — it is 0 right
67
+ after you change the knobs, and grows from there. Do not read a saving off a window whose current
68
+ policy has no data.
69
+
70
+ **Estimated** (labelled in the UI and in the CLI): the saving versus the shipped default
71
+ (`0.8 / 0.16`). It replays your real per-step growth under both policies. It is a model, not a bill:
72
+ it assumes the same work happens and the same price ratio, and it does not price lost detail. When
73
+ the current threshold has almost no measured steps the panel says so explicitly.
74
+
75
+ Privacy: local only. The plugin reads session logs, writes a cache next to `settings.json`, and never
76
+ sends anything anywhere. The first run decompresses recent sessions (a few seconds); later runs reuse
77
+ the cache. The host RPC yields between files so the UI stays responsive.
78
+
52
79
  ## Why the tuner exists (the freeze problem)
53
80
 
54
81
  The live `compaction-basic` instance lives **inside the agent preset**, in a group that is `isolate`d.
@@ -76,6 +103,7 @@ dsh-context-kit set --threshold 0.5 --retain 0.16 --preset cordis
76
103
  dsh-context-kit sync [--force --mode replace]
77
104
  dsh-context-kit preview
78
105
  dsh-context-kit clear
106
+ dsh-context-kit report [--days 7]
79
107
  ```
80
108
 
81
109
  `--resources "<DSH install>/resources"` when it cannot find the app by itself.
@@ -85,10 +113,11 @@ and points at the line numbers.
85
113
  ## Tool
86
114
 
87
115
  ```text
88
- preset_tuner(action="status" | "preview" | "sync" | "clear")
116
+ preset_tuner(action="status" | "preview" | "sync" | "clear" | "report", days?)
89
117
  ```
90
118
 
91
- `status` is read-only and reports upstream drift; `sync` writes and tells you to restart.
119
+ `status` is read-only and reports upstream drift; `sync` writes and tells you to restart;
120
+ `report` returns the same measured/estimated summary as the panel card.
92
121
 
93
122
  ## Safety
94
123
 
@@ -134,5 +134,40 @@ if (command === 'clear') {
134
134
  process.exit(0)
135
135
  }
136
136
 
137
- fail(`未知命令: ${command}(可用: status | set | preview | sync | clear)`)
137
+ if (command === 'report') {
138
+ const days = Number(args.days ?? 7)
139
+ const report = await kit.report({ days })
140
+ const t = report.totals
141
+ const big = (value) => (value >= 1e9 ? `${(value / 1e9).toFixed(2)}B` : value >= 1e6 ? `${(value / 1e6).toFixed(1)}M` : `${Math.round(value / 1e3)}K`)
142
+ console.log(`窗口 : 最近 ${report.window.days} 天(自 ${report.window.since.slice(0, 10)})`)
143
+ console.log(`规模 : ${t.sessions} 会话 / ${t.steps} 步 / ${t.compactions} 次压缩`)
144
+ for (const policy of report.policies || []) {
145
+ console.log(
146
+ ` 分期 : ${policy.triggerTokens === null ? '无压缩(无法判断)' : `触发点 ≈${fmt(policy.triggerTokens)}`}` +
147
+ ` → ${policy.totals.sessions} 会话 / ${policy.totals.steps} 步${policy.isCurrent ? '(当前阈值)' : ''}`,
148
+ )
149
+ }
150
+ if (report.coverage) {
151
+ console.log(` 覆盖 : 当前阈值实测 ${report.coverage.stepsUnderCurrent} 步(${report.coverage.sharePct.toFixed(1)}%)`)
152
+ }
153
+ console.log(`实测用量: 命中 ${big(t.hit)} · 未命中 ${big(t.miss)} · 输出 ${big(t.out)}`)
154
+ console.log(`上下文 : 平均 ${fmt(t.promptAvg)} · 峰值 ${fmt(t.promptMax)}`)
155
+ console.log(`成本 : ${big(t.cost.total)}(命中当量,未命中占 ${t.missSharePct.toFixed(1)}%)`)
156
+ if (report.savings) {
157
+ console.log(
158
+ `节省估算: ${report.savings.savedPct.toFixed(1)}%(基线 ${report.savings.baseThresholdRatio}/${report.savings.baseRetainRatio}` +
159
+ ` → 当前 ${report.savings.thresholdRatio}/${report.savings.retainRatio},压缩 ${report.savings.baseEvents}→${report.savings.currentEvents} 次)`,
160
+ )
161
+ console.log(' 这是估算,不是账单。')
162
+ if (report.coverage && report.coverage.isModelOnly) {
163
+ console.log(' ! 当前阈值下的实测样本太少,只能当方向。')
164
+ }
165
+ }
166
+ console.log(`返工 : 重复调用 ${t.duplicates} / 不同调用 ${t.distinctCalls}(${t.duplicatePct.toFixed(1)}%)`)
167
+ console.log(`解压 : 本次 ${(report.decompressedBytes / 1e6).toFixed(1)}MB,缓存 ${report.files.length} 个文件`)
168
+ console.log(report.privacy)
169
+ process.exit(0)
170
+ }
171
+
172
+ fail(`未知命令: ${command}(可用: status | set | preview | sync | clear | report)`)
138
173
  export { triggersFor }
package/client/panel.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // dsh-context-kit 的 Settings 面板(Web 客户端插件)。
2
- // 通过 ctx.connection.rpc 调宿主 contextKit 服务:status / save / sync / preview / clear。
2
+ // 通过 ctx.connection.rpc 调宿主 contextKit 服务:status / save / sync / preview / clear / report。
3
3
  window.__ModuleLoader__.load({
4
4
  id: 'dsh-context-kit',
5
5
  factory(require) {
@@ -12,7 +12,6 @@ window.__ModuleLoader__.load({
12
12
  subtitle: 'Save tokens by compacting earlier, without freezing the preset.',
13
13
  threshold: 'Compact at',
14
14
  retain: 'Keep after compact',
15
- auto: 'Automatic compaction',
16
15
  save: 'Save',
17
16
  sync: 'Apply to profile',
18
17
  preview: 'Preview',
@@ -35,6 +34,32 @@ window.__ModuleLoader__.load({
35
34
  upstream: 'Upstream',
36
35
  busy: 'Working…',
37
36
  error: 'Error',
37
+ effectTitle: 'Measured effect',
38
+ effectHint: "Reads this machine's session logs. Nothing leaves the device.",
39
+ effectRun: 'Measure last 7 days',
40
+ effectRunning: 'Reading session logs…',
41
+ effectEmpty: 'Measuring… the first run decompresses recent sessions and may take a few seconds. Less than 7 days of history is fine — the window is capped at 7 days, not required.',
42
+ effectSessions: 'sessions',
43
+ effectSteps: 'steps',
44
+ effectCompactions: 'compactions',
45
+ effectHit: 'cache hit',
46
+ effectMiss: 'cache miss',
47
+ effectOut: 'output',
48
+ effectMissShare: 'miss share of cost',
49
+ effectContext: 'context (avg / peak)',
50
+ effectCost: 'cost (hit-equivalents)',
51
+ effectSavings: 'Estimated saving',
52
+ effectSavingsNote: 'estimate: replays your real per-step growth against the shipped default; not a bill',
53
+ effectRework: 'Rework signal',
54
+ effectReworkNote: 'repeated identical calls — the first sign compaction went too deep',
55
+ effectSkipped: 'skipped files',
56
+ effectWindow: 'window',
57
+ effectFiles: 'session logs read',
58
+ effectAt: 'measured at',
59
+ effectPolicies: 'observed policies',
60
+ effectCurrent: 'current',
61
+ effectCoverage: 'data under the current threshold',
62
+ effectModelOnly: 'Too few steps ran under the current threshold — treat the estimate as a direction, not a result.',
38
63
  }
39
64
 
40
65
  const ZH = {
@@ -43,7 +68,6 @@ window.__ModuleLoader__.load({
43
68
  subtitle: '早点压缩来省 token,同时不冻结预设。',
44
69
  threshold: '压缩触发于',
45
70
  retain: '压缩后保留',
46
- auto: '启用自动压缩',
47
71
  save: '保存',
48
72
  sync: '写入 profile',
49
73
  preview: '预览',
@@ -66,27 +90,68 @@ window.__ModuleLoader__.load({
66
90
  upstream: '上游',
67
91
  busy: '处理中…',
68
92
  error: '出错',
93
+ effectTitle: '实测效果',
94
+ effectHint: '只读本机会话日志,数据不出设备。',
95
+ effectRun: '统计最近 7 天',
96
+ effectRunning: '正在读会话日志…',
97
+ effectEmpty: '正在统计… 第一次要解压最近的会话,可能需要几秒。用不满 7 天也能统计 —— 7 天是窗口上限,不是前提。',
98
+ effectSessions: '个会话',
99
+ effectSteps: '步',
100
+ effectCompactions: '次压缩',
101
+ effectHit: '缓存命中',
102
+ effectMiss: '未命中',
103
+ effectOut: '输出',
104
+ effectMissShare: '未命中占成本',
105
+ effectContext: '上下文(均值 / 峰值)',
106
+ effectCost: '成本(命中当量)',
107
+ effectSavings: '估算节省',
108
+ effectSavingsNote: '估算:用你的真实每步增量回放官方默认阈值,不等于账单',
109
+ effectRework: '返工信号',
110
+ effectReworkNote: '重复的相同调用 —— 压缩压过头的第一信号',
111
+ effectSkipped: '跳过文件',
112
+ effectWindow: '窗口',
113
+ effectFiles: '个会话日志',
114
+ effectAt: '统计时间',
115
+ effectPolicies: '观测到的策略',
116
+ effectCurrent: '当前',
117
+ effectCoverage: '当前阈值下的实测',
118
+ effectModelOnly: '当前阈值下实际跑过的步数还太少 —— 这个估算只能当方向,不能当结论。',
69
119
  }
70
120
 
71
- const CSS = `
72
- .ck_wrap { display: flex; flex-direction: column; gap: 14px; }
73
- .ck_head h2 { margin: 0 0 4px; font-size: 15px; }
74
- .ck_head p { margin: 0; opacity: .7; font-size: 12px; }
75
- .ck_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }
76
- .ck_row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
77
- .ck_row label { min-width: 110px; font-size: 12px; opacity: .8; }
78
- .ck_row input[type=range] { flex: 1 1 160px; }
79
- .ck_val { font-variant-numeric: tabular-nums; min-width: 72px; text-align: right; font-size: 12px; }
80
- .ck_btns { display: flex; gap: 8px; flex-wrap: wrap; }
81
- .ck_btn { border: 1px solid rgba(127,127,127,.35); background: transparent; border-radius: 8px; padding: 6px 12px; cursor: pointer; font-size: 12px; }
82
- .ck_btn.primary { background: #2563eb; border-color: #2563eb; color: #fff; }
83
- .ck_btn:disabled { opacity: .5; cursor: default; }
84
- .ck_meta { font-size: 11px; opacity: .65; word-break: break-all; }
85
- .ck_state { font-size: 12px; padding: 6px 8px; border-radius: 8px; background: rgba(127,127,127,.12); }
86
- .ck_warn { color: #d97706; }
87
- .ck_err { color: #dc2626; }
88
- .ck_pre { max-height: 220px; overflow: auto; font-size: 11px; background: rgba(127,127,127,.12); padding: 8px; border-radius: 8px; white-space: pre-wrap; }
89
- `
121
+ const CSS = [
122
+ '.ck_wrap { display: flex; flex-direction: column; gap: 14px; }',
123
+ '.ck_head h2 { margin: 0 0 4px; font-size: 15px; }',
124
+ '.ck_head p { margin: 0; opacity: .7; font-size: 12px; }',
125
+ '.ck_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }',
126
+ '.ck_row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }',
127
+ '.ck_row label { min-width: 110px; font-size: 12px; opacity: .8; }',
128
+ '.ck_row input[type=range] { flex: 1 1 160px; }',
129
+ '.ck_val { font-variant-numeric: tabular-nums; min-width: 72px; text-align: right; font-size: 12px; }',
130
+ '.ck_btns { display: flex; gap: 8px; flex-wrap: wrap; }',
131
+ '.ck_btn { border: 1px solid rgba(127,127,127,.35); background: transparent; border-radius: 8px; padding: 6px 12px; cursor: pointer; font-size: 12px; }',
132
+ '.ck_btn.primary { background: #2563eb; border-color: #2563eb; color: #fff; }',
133
+ '.ck_btn:disabled { opacity: .5; cursor: default; }',
134
+ '.ck_meta { font-size: 11px; opacity: .65; word-break: break-all; }',
135
+ '.ck_state { font-size: 12px; padding: 6px 8px; border-radius: 8px; background: rgba(127,127,127,.12); }',
136
+ '.ck_warn { color: #d97706; }',
137
+ '.ck_err { color: #dc2626; }',
138
+ '.ck_pre { max-height: 220px; overflow: auto; font-size: 11px; background: rgba(127,127,127,.12); padding: 8px; border-radius: 8px; white-space: pre-wrap; }',
139
+ ].join('\n')
140
+
141
+ const fmtK = (tokens) => {
142
+ if (!Number.isFinite(tokens)) return '—'
143
+ if (tokens >= 1024 * 1024) return (tokens / (1024 * 1024)).toFixed(1) + 'M'
144
+ return Math.round(tokens / 1024) + 'K'
145
+ }
146
+ const fmtBig = (value) => {
147
+ if (!Number.isFinite(value)) return '—'
148
+ if (value >= 1e9) return (value / 1e9).toFixed(2) + 'B'
149
+ if (value >= 1e6) return (value / 1e6).toFixed(1) + 'M'
150
+ if (value >= 1e3) return Math.round(value / 1e3) + 'K'
151
+ return String(Math.round(value))
152
+ }
153
+ const pct = (ratio) => Math.round(Number(ratio) * 1000) / 10 + '%'
154
+ const meta = (value) => h('div', { className: 'ck_meta' }, value)
90
155
 
91
156
  function makeT(ctx) {
92
157
  try {
@@ -106,7 +171,9 @@ window.__ModuleLoader__.load({
106
171
  }
107
172
  } catch {}
108
173
  let id = 'en'
109
- try { id = ctx.locale.getLocale().id } catch {}
174
+ try {
175
+ id = ctx.locale.getLocale().id
176
+ } catch {}
110
177
  const dict = id === 'zh' ? ZH : EN
111
178
  return dict[key] || fallback || key
112
179
  }
@@ -114,7 +181,7 @@ window.__ModuleLoader__.load({
114
181
 
115
182
  function makeApi(ctx) {
116
183
  function call(method, args) {
117
- return ctx.connection.rpc.call('/api', `contextKit/${method}`, { args: args || {} }, undefined).then(function (response) {
184
+ return ctx.connection.rpc.call('/api', 'contextKit/' + method, { args: args || {} }, undefined).then(function (response) {
118
185
  if (response && response.ok) return response.value
119
186
  const message = response && response.error ? response.error.message : 'context kit remote call failed'
120
187
  const error = new Error(message)
@@ -123,28 +190,91 @@ window.__ModuleLoader__.load({
123
190
  })
124
191
  }
125
192
  return {
126
- status: function () { return call('status', {}) },
127
- save: function (input) {
128
- return call('save', {
193
+ status: () => call('status', {}),
194
+ preview: () => call('preview', {}),
195
+ clear: () => call('clear', {}),
196
+ sync: () => call('sync', { force: false, mode: 'append' }),
197
+ report: (days) => call('report', { days: days }),
198
+ save: (input) =>
199
+ call('save', {
129
200
  presetId: input.presetId,
130
201
  thresholdRatio: input.thresholdRatio,
131
202
  retainRatio: input.retainRatio,
132
203
  auto: input.auto,
133
204
  group: input.group,
134
- })
135
- },
136
- sync: function () { return call('sync', { force: false, mode: 'append' }) },
137
- preview: function () { return call('preview', {}) },
138
- clear: function () { return call('clear', {}) },
205
+ }),
139
206
  }
140
207
  }
141
208
 
142
- const fmtK = function (tokens) {
143
- if (!Number.isFinite(tokens)) return '—'
144
- if (tokens >= 1024 * 1024) return (tokens / (1024 * 1024)).toFixed(1) + 'M'
145
- return Math.round(tokens / 1024) + 'K'
209
+ function EffectCard(props) {
210
+ const t = props.t
211
+ const report = props.report
212
+ const rows = []
213
+ if (report) {
214
+ const total = report.totals
215
+ rows.push(meta(total.sessions + ' ' + t('effectSessions') + ' · ' + total.steps + ' ' + t('effectSteps') + ' · ' + total.compactions + ' ' + t('effectCompactions')))
216
+ if (report.policies && report.policies.length) {
217
+ rows.push(meta(t('effectPolicies')))
218
+ for (const policy of report.policies) {
219
+ const label = policy.triggerTokens === null ? '—' : fmtK(policy.triggerTokens)
220
+ rows.push(meta(' ' + label + ': ' + policy.totals.sessions + ' ' + t('effectSessions') + ' / ' + policy.totals.steps + ' ' + t('effectSteps') + (policy.isCurrent ? ' ← ' + t('effectCurrent') : '')))
221
+ }
222
+ }
223
+ if (report.coverage) {
224
+ rows.push(meta(t('effectCoverage') + ': ' + report.coverage.stepsUnderCurrent + ' ' + t('effectSteps') + ' (' + pct(report.coverage.sharePct / 100) + ')'))
225
+ }
226
+ rows.push(
227
+ h('div', { className: 'ck_row' },
228
+ meta(t('effectHit') + ' ' + fmtBig(total.hit)),
229
+ meta(t('effectMiss') + ' ' + fmtBig(total.miss)),
230
+ meta(t('effectOut') + ' ' + fmtBig(total.out))),
231
+ )
232
+ rows.push(
233
+ h('div', { className: 'ck_row' },
234
+ meta(t('effectMissShare') + ' ' + pct(total.missSharePct / 100)),
235
+ meta(t('effectContext') + ' ' + fmtK(total.promptAvg) + ' / ' + fmtK(total.promptMax)),
236
+ meta(t('effectCost') + ' ' + fmtBig(total.cost.total))),
237
+ )
238
+ if (report.savings) {
239
+ rows.push(
240
+ h('div', { className: 'ck_row' },
241
+ h('span', { className: 'ck_val' }, '−' + report.savings.savedPct.toFixed(1) + '%'),
242
+ meta(t('effectSavings') + ' · ' + t('effectSavingsNote'))),
243
+ )
244
+ if (report.coverage && report.coverage.isModelOnly) {
245
+ rows.push(h('div', { className: 'ck_meta ck_warn' }, t('effectModelOnly')))
246
+ }
247
+ }
248
+ rows.push(meta(t('effectRework') + ' ' + total.duplicates + ' / ' + total.distinctCalls + ' (' + pct(total.duplicatePct / 100) + ') · ' + t('effectReworkNote')))
249
+ if (report.skipped && report.skipped.length) rows.push(h('div', { className: 'ck_meta ck_warn' }, t('effectSkipped') + ': ' + report.skipped.length))
250
+ rows.push(meta(report.privacy))
251
+ } else {
252
+ rows.push(meta(t('effectEmpty')))
253
+ }
254
+ return h('div', { className: 'ck_card' },
255
+ h('div', { className: 'ck_row' },
256
+ h('label', null, t('effectTitle')),
257
+ meta(t('effectHint')),
258
+ h('button', { className: 'ck_btn', type: 'button', disabled: props.busy, onClick: props.onRun },
259
+ props.busy ? t('effectRunning') : t('effectRun'))),
260
+ ...rows)
261
+ }
262
+
263
+ function SliderRow(props) {
264
+ return h('div', { className: 'ck_row' },
265
+ h('label', null, props.label),
266
+ h('input', {
267
+ type: 'range',
268
+ min: props.min,
269
+ max: props.max,
270
+ step: 0.01,
271
+ value: props.value,
272
+ disabled: props.disabled,
273
+ onChange: function (event) { props.onChange(Number(event.target.value)) },
274
+ }),
275
+ h('span', { className: 'ck_val' }, fmtK(props.tokens)),
276
+ h('span', { className: 'ck_meta' }, pct(props.value) + ' ' + props.ofWindow))
146
277
  }
147
- const pct = function (ratio) { return Math.round(Number(ratio) * 1000) / 10 + '%' }
148
278
 
149
279
  function Panel(props) {
150
280
  const t = props.t
@@ -156,6 +286,7 @@ window.__ModuleLoader__.load({
156
286
  const [message, setMessage] = React.useState('')
157
287
  const [error, setError] = React.useState('')
158
288
  const [pre, setPre] = React.useState('')
289
+ const [report, setReport] = React.useState(null)
159
290
 
160
291
  const load = React.useCallback(function () {
161
292
  return api.status().then(function (next) {
@@ -164,7 +295,9 @@ window.__ModuleLoader__.load({
164
295
  setThreshold(Number(next.knobs.thresholdRatio) || 0.5)
165
296
  setRetain(Number(next.knobs.retainRatio) || 0.16)
166
297
  }
167
- }).catch(function (cause) { setError(String(cause && cause.message ? cause.message : cause)) })
298
+ }).catch(function (cause) {
299
+ setError(String(cause && cause.message ? cause.message : cause))
300
+ })
168
301
  }, [api])
169
302
 
170
303
  React.useEffect(function () { load() }, [load])
@@ -182,10 +315,9 @@ window.__ModuleLoader__.load({
182
315
  }
183
316
 
184
317
  const presetId = state && state.presets && state.presets.length ? state.presets[0] : 'cordis'
185
- const window2 = state && state.triggers ? state.triggers.contextWindow : 1048576
186
- const triggerTokens = Math.floor(window2 * threshold)
187
- const retainTokens = Math.floor(window2 * retain)
188
-
318
+ const windowSize = state && state.triggers ? state.triggers.contextWindow : 1048576
319
+ const triggerTokens = Math.floor(windowSize * threshold)
320
+ const retainTokens = Math.floor(windowSize * retain)
189
321
  const entry = state && state.entries ? state.entries[0] : null
190
322
  const stateText = !entry
191
323
  ? t('missing')
@@ -195,83 +327,86 @@ window.__ModuleLoader__.load({
195
327
  ? t('upToDate') + ' · ' + entry.upstreamSha
196
328
  : t('missing')
197
329
 
330
+ const configCard = h('div', { className: 'ck_card' },
331
+ h(SliderRow, {
332
+ label: t('threshold'), min: 0.2, max: 0.85, value: threshold,
333
+ tokens: triggerTokens, ofWindow: t('ofWindow'), disabled: busy,
334
+ onChange: setThreshold,
335
+ }),
336
+ h(SliderRow, {
337
+ label: t('retain'), min: 0.04, max: Math.max(0.05, threshold - 0.02), value: retain,
338
+ tokens: retainTokens, ofWindow: t('ofWindow'), disabled: busy,
339
+ onChange: setRetain,
340
+ }),
341
+ meta(t('triggers') + ' ' + fmtK(triggerTokens) + ' · ' + t('keeps') + ' ' + fmtK(retainTokens)),
342
+ h('div', { className: 'ck_btns' },
343
+ h('button', {
344
+ className: 'ck_btn primary', type: 'button', disabled: busy,
345
+ onClick: function () {
346
+ return run(t('saved'), function () {
347
+ return api.save({ presetId: presetId, thresholdRatio: threshold, retainRatio: retain, auto: true, group: 'compaction' }).then(load)
348
+ })
349
+ },
350
+ }, t('save')),
351
+ h('button', {
352
+ className: 'ck_btn', type: 'button', disabled: busy,
353
+ onClick: function () {
354
+ return run('', function () {
355
+ return api.sync().then(function (result) {
356
+ setMessage(result && result.changed ? t('synced') : t('unchanged'))
357
+ return load()
358
+ })
359
+ })
360
+ },
361
+ }, t('sync')),
362
+ h('button', {
363
+ className: 'ck_btn', type: 'button', disabled: busy,
364
+ onClick: function () {
365
+ return run('', function () {
366
+ return api.preview().then(function (result) { setPre(result && result.text ? result.text : '') })
367
+ })
368
+ },
369
+ }, t('preview')),
370
+ h('button', {
371
+ className: 'ck_btn', type: 'button', disabled: busy,
372
+ onClick: function () {
373
+ return run(t('cleared'), function () { return api.clear().then(load) })
374
+ },
375
+ }, t('clear')),
376
+ h('button', {
377
+ className: 'ck_btn', type: 'button', disabled: busy,
378
+ onClick: function () { return load() },
379
+ }, t('refresh'))))
380
+
381
+ const infoRows = []
382
+ if (state) infoRows.push(h('div', { className: 'ck_state' }, stateText))
383
+ if (state && state.foreign && state.foreign.length) infoRows.push(h('div', { className: 'ck_state ck_warn' }, t('foreign')))
384
+ if (message) infoRows.push(meta(message))
385
+ if (error) infoRows.push(h('div', { className: 'ck_meta ck_err' }, t('error') + ': ' + error))
386
+ if (state) infoRows.push(meta(t('profile') + ': ' + state.profileDir + ' · ' + t('patch') + ': ' + state.patchPath))
387
+ if (state) infoRows.push(meta(t('upstream') + ': ' + (state.sources || []).join(' | ')))
388
+ if (state && state.managed && state.managed.length) {
389
+ infoRows.push(meta(state.managed.map(function (block) { return block.presetId + '@' + block.sha }).join(', ')))
390
+ }
391
+ infoRows.push(meta(t('restart')))
392
+ if (pre) infoRows.push(h('pre', { className: 'ck_pre' }, pre))
393
+
198
394
  return h('div', { className: 'ck_wrap' },
199
395
  h('div', { className: 'ck_head' },
200
396
  h('h2', null, t('title')),
201
397
  h('p', null, t('subtitle'))),
202
-
203
- h('div', { className: 'ck_card' },
204
- h('div', { className: 'ck_row' },
205
- h('label', null, t('threshold')),
206
- h('input', {
207
- type: 'range', min: 0.2, max: 0.85, step: 0.01, value: threshold,
208
- disabled: busy,
209
- onChange: function (event) { setThreshold(Number(event.target.value)) },
210
- }),
211
- h('span', { className: 'ck_val' }, fmtK(triggerTokens)),
212
- h('span', { className: 'ck_meta' }, pct(threshold) + ' ' + t('ofWindow'))),
213
- h('div', { className: 'ck_row' },
214
- h('label', null, t('retain')),
215
- h('input', {
216
- type: 'range', min: 0.04, max: Math.max(0.05, threshold - 0.02), step: 0.01, value: retain,
217
- disabled: busy,
218
- onChange: function (event) { setRetain(Number(event.target.value)) },
219
- }),
220
- h('span', { className: 'ck_val' }, fmtK(retainTokens)),
221
- h('span', { className: 'ck_meta' }, pct(retain) + ' ' + t('ofWindow'))),
222
- h('div', { className: 'ck_meta' },
223
- t('triggers') + ' ' + fmtK(triggerTokens) + ' · ' + t('keeps') + ' ' + fmtK(retainTokens)),
224
- h('div', { className: 'ck_btns' },
225
- h('button', {
226
- className: 'ck_btn primary', type: 'button', disabled: busy,
227
- onClick: function () {
228
- return run(t('saved'), function () {
229
- return api.save({ presetId: presetId, thresholdRatio: threshold, retainRatio: retain, auto: true, group: 'compaction' })
230
- .then(load)
231
- })
232
- },
233
- }, t('save')),
234
- h('button', {
235
- className: 'ck_btn', type: 'button', disabled: busy,
236
- onClick: function () {
237
- return run('', function () {
238
- return api.sync().then(function (result) {
239
- setMessage(result && result.changed ? t('synced') : t('unchanged'))
240
- return load()
241
- })
242
- })
243
- },
244
- }, t('sync')),
245
- h('button', {
246
- className: 'ck_btn', type: 'button', disabled: busy,
247
- onClick: function () {
248
- return run('', function () {
249
- return api.preview().then(function (result) { setPre(result && result.text ? result.text : '') })
250
- })
251
- },
252
- }, t('preview')),
253
- h('button', {
254
- className: 'ck_btn', type: 'button', disabled: busy,
255
- onClick: function () {
256
- return run(t('cleared'), function () { return api.clear().then(load) })
257
- },
258
- }, t('clear')),
259
- h('button', {
260
- className: 'ck_btn', type: 'button', disabled: busy,
261
- onClick: function () { return load() },
262
- }, t('refresh')))),
263
-
264
- state ? h('div', { className: 'ck_state' }, stateText) : null,
265
- state && state.foreign && state.foreign.length ? h('div', { className: 'ck_state ck_warn' }, t('foreign')) : null,
266
- message ? h('div', { className: 'ck_meta' }, message) : null,
267
- error ? h('div', { className: 'ck_meta ck_err' }, t('error') + ': ' + error) : null,
268
- state ? h('div', { className: 'ck_meta' }, t('profile') + ': ' + state.profileDir + ' · ' + t('patch') + ': ' + state.patchPath) : null,
269
- state ? h('div', { className: 'ck_meta' }, t('upstream') + ': ' + (state.sources || []).join(' | ')) : null,
270
- state && state.managed && state.managed.length
271
- ? h('div', { className: 'ck_meta' }, state.managed.map(function (block) { return block.presetId + '@' + block.sha }).join(', '))
272
- : null,
273
- h('div', { className: 'ck_meta' }, t('restart')),
274
- pre ? h('pre', { className: 'ck_pre' }, pre) : null)
398
+ configCard,
399
+ h(EffectCard, {
400
+ t: t,
401
+ report: report,
402
+ busy: busy,
403
+ onRun: function () {
404
+ return run('', function () {
405
+ return api.report(7).then(function (next) { setReport(next) })
406
+ })
407
+ },
408
+ }),
409
+ ...infoRows)
275
410
  }
276
411
 
277
412
  return {
package/lib/kit-ops.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import { existsSync, readFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
10
11
  import { join } from 'node:path'
11
12
 
12
13
  import { commitSync, planSync } from './tuner/sync.mjs'
@@ -20,6 +21,7 @@ import {
20
21
  PATCH_FILE,
21
22
  } from './tuner/tuner.mjs'
22
23
  import { readSettings, setCompaction, writeSettings } from './settings.mjs'
24
+ import { loadReportAsync } from './usage.mjs'
23
25
 
24
26
  const KNOB_DEFAULTS = { auto: true, thresholdRatio: 0.5, retainRatio: 0.16 }
25
27
  const CONTEXT_DEFAULTS = { contextWindow: 1048576, maxOutputTokens: 256000, headroomTokens: 65536 }
@@ -111,8 +113,9 @@ export function createKit(config = {}) {
111
113
 
112
114
  /** settings.json 优先于插件 config:面板保存后不必重启就能被工具/CLI 看到。 */
113
115
  const currentSettings = () => {
114
- const paths = pathsOf()
115
- const stored = readSettings(paths.profile.dir)
116
+ // 只读 settings.json,不解析 app.asar:CLI 的 report / set 在 app 之外也要能跑
117
+ const profile = profileOf()
118
+ const stored = readSettings(profile.dir)
116
119
  const merged = { ...settings, presetTweaks: { ...settings.presetTweaks } }
117
120
  for (const [presetId, value] of Object.entries(stored.presets ?? {})) {
118
121
  merged.presetTweaks[presetId] = {
@@ -196,6 +199,26 @@ export function createKit(config = {}) {
196
199
  return { ...result, removed: managed.length, restartRequired: result.changed }
197
200
  },
198
201
 
202
+ /**
203
+ * 效果台账:读本机会话日志统计真实用量,并回放“当前阈值 vs 默认阈值”的节省估算。
204
+ * 只读本地文件;缓存放在 profile 目录下,第二次调用不再重解压。
205
+ */
206
+ async report({ days = 7 } = {}) {
207
+ const profile = profileOf()
208
+ const active = currentSettings()
209
+ const focus = Object.keys(active.presetTweaks)[0] ?? 'cordis'
210
+ const knob = active.presetTweaks[focus]?.plugins?.['compaction-basic']?.config ?? {}
211
+ const home = text(process.env.DSH_HOME) || join(homedir(), '.dsh')
212
+ return loadReportAsync({
213
+ home,
214
+ cachePath: join(profile.dir, 'dsh-context-kit', 'usage-cache.json'),
215
+ days: Math.min(90, Math.max(1, Number(days) || 7)),
216
+ contextWindow: active.context.contextWindow,
217
+ thresholdRatio: finite(knob.thresholdRatio) ?? KNOB_DEFAULTS.thresholdRatio,
218
+ retainRatio: finite(knob.retainRatio) ?? KNOB_DEFAULTS.retainRatio,
219
+ })
220
+ },
221
+
199
222
  /** 面板/CLI 保存:只写 settings.json(不写 YAML),返回最新状态。 */
200
223
  saveCompaction(input = {}) {
201
224
  const profile = profileOf()
package/lib/remote.mjs CHANGED
@@ -48,8 +48,12 @@ export class ContextKitRemoteService extends TypertRemoteService {
48
48
  clear() {
49
49
  return this.kit.clear()
50
50
  }
51
+
52
+ async report(days) {
53
+ return this.kit.report({ days: Number(days) || 7 })
54
+ }
51
55
  }
52
56
 
53
- for (const method of ['status', 'preview', 'save', 'sync', 'clear']) {
57
+ for (const method of ['status', 'preview', 'save', 'sync', 'clear', 'report']) {
54
58
  markRemoteMethod(ContextKitRemoteService, method)
55
59
  }