dsh-context-kit 0.1.0 → 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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 LISHUANGXI1412
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LISHUANGXI1412
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,120 +1,149 @@
1
- # dsh-context-kit
2
-
3
- Save context tokens in DSH. One package, three parts:
4
-
5
- | part | what it does |
6
- | --- | --- |
7
- | **context index** (host) | Keeps a small, stable system-prompt section listing the *pointers* that compaction would otherwise erase: recent tool artifacts and touched paths. Summaries lose content, not locations. |
8
- | **preset tuner** (host) | Moves the automatic-compaction trigger earlier — and does it without freezing the agent preset, by regenerating the override from the preset that ships inside the app. |
9
- | **Settings panel** (web) | A Context page: drag the trigger point, apply, preview, remove. No YAML editing. |
10
-
11
- Why this combination: compaction is the lever that actually moves the bill. Compacting at 524K instead of
12
- 679K avoids re-sending the region above the trigger on every step; the index then makes sure the summary
13
- that replaces that region still tells the model where things are. The two are complementary — the index
14
- alone saves nothing on its own, and earlier compaction alone loses pointers.
15
-
16
- ## Install
17
-
18
- ```bash
19
- dsh plugin add dsh-context-kit
20
- ```
21
-
22
- Restart DSH. You get:
23
-
24
- - two host plugins (`context-kit-index`, `context-kit-tuner`),
25
- - a **Settings → Context** page,
26
- - a `preset_tuner` tool,
27
- - a `dsh-context-kit` CLI.
28
-
29
- ## Panel: Settings → Context
30
-
31
- - **Compact at** — the fraction of the context window that triggers compaction (default `0.5` → ~524K).
32
- - **Keep after compact** — how much survives compaction (default `0.16` → ~168K).
33
- - **Save** writes `settings.json`, **Apply to profile** regenerates the profile override, and the page
34
- tells you to restart. **Preview** shows the exact generated YAML before it is written.
35
- - **Remove override** deletes the managed block and falls back to upstream defaults.
36
-
37
- Saving is not the same as applying: the panel never touches YAML until you press Apply, and applying
38
- never happens silently.
39
-
40
- Where it stores things:
41
-
42
- ```
43
- <profile>/dsh-context-kit/settings.json # what the panel edits
44
- <profile>/cordis.patch.yml # managed block: generated, not hand-written
45
- <profile>/dsh-context-kit/backups/ # every overwrite keeps the previous file (last 10)
46
- ```
47
-
48
- Precedence: `settings.json` wins over the plugin's `config.presets` in the bundle/patch. In practice the
49
- plugin row can stay empty (`presets: {}`) and the panel is the single place where numbers live — the
50
- managed block in `cordis.patch.yml` always reflects what you last applied.
51
-
52
- ## Why the tuner exists (the freeze problem)
53
-
54
- The live `compaction-basic` instance lives **inside the agent preset**, in a group that is `isolate`d.
55
- A host-level plugin cannot reach that service, and a profile patch row `- id: compaction-basic` targets
56
- an inactive leftover row — it looks right and does nothing.
57
-
58
- Overriding a preset row replaces its `config` wholesale, so the only way in is to restate the whole
59
- preset. Hand-writing that copy freezes the preset: from then on you stop receiving upstream preset
60
- updates. The tuner instead reads the preset **out of the running app** (`resources/app.asar`) and
61
- regenerates the restatement:
62
-
63
- - upstream text is kept byte for byte,
64
- - your changes are inserted as extra lines only,
65
- - the result lives in a marked managed block,
66
- - after a DSH update the next startup (or `Apply`) regenerates it from the new upstream preset.
67
-
68
- Unit tests assert the insertion-only property against the real shipped presets, and a live check reads
69
- this machine's `app.asar` end to end.
70
-
71
- ## CLI
72
-
73
- ```bash
74
- dsh-context-kit status
75
- dsh-context-kit set --threshold 0.5 --retain 0.16 --preset cordis
76
- dsh-context-kit sync [--force --mode replace]
77
- dsh-context-kit preview
78
- dsh-context-kit clear
79
- ```
80
-
81
- `--resources "<DSH install>/resources"` when it cannot find the app by itself.
82
- `--force --mode replace` is required to take over a hand-written override; without it the tool refuses
83
- and points at the line numbers.
84
-
85
- ## Tool
86
-
87
- ```text
88
- preset_tuner(action="status" | "preview" | "sync" | "clear")
89
- ```
90
-
91
- `status` is read-only and reports upstream drift; `sync` writes and tells you to restart.
92
-
93
- ## Safety
94
-
95
- - **Fail closed.** If the upstream preset cannot be located, extracted, or modified safely (renamed
96
- plugin, changed layout, key already set upstream), nothing is written.
97
- - **Never edits upstream text**, only inserts.
98
- - **Never silently masks upstream values**: a configured key that upstream already sets aborts the sync.
99
- - **Refuses to eat hand-written overrides** unless explicitly forced.
100
- - **Backups + idempotence**: unchanged input writes nothing, so it never creates restart noise.
101
-
102
- ## What it does not do (yet)
103
-
104
- - It does not evict history itself. Batch eviction of old tool results is the next lever; the tuner
105
- already supports adding a plugin into a preset group, which is where such an evictor has to live to
106
- see the compaction service.
107
- - The trigger estimate assumes the documented window (`contextWindow` 1048576, `maxOutputTokens` 256000,
108
- `headroomTokens` 65536). Override them in the plugin config if your model differs.
109
-
110
- ## Rollback
111
-
112
- ```bash
113
- dsh-context-kit clear # then restart
114
- ```
115
-
116
- Backups remain in `<profile>/dsh-context-kit/backups/`.
117
-
118
- ## License
119
-
120
- MIT
1
+ # dsh-context-kit
2
+
3
+ Save context tokens in DSH. One package, three parts:
4
+
5
+ | part | what it does |
6
+ | --- | --- |
7
+ | **context index** (host) | Keeps a small, stable system-prompt section listing the *pointers* that compaction would otherwise erase: recent tool artifacts and touched paths. Summaries lose content, not locations. |
8
+ | **preset tuner** (host) | Moves the automatic-compaction trigger earlier — and does it without freezing the agent preset, by regenerating the override from the preset that ships inside the app. |
9
+ | **Settings panel** (web) | A Context page: drag the trigger point, apply, preview, remove. No YAML editing. |
10
+
11
+ Why this combination: compaction is the lever that actually moves the bill. Compacting at 524K instead of
12
+ 679K avoids re-sending the region above the trigger on every step; the index then makes sure the summary
13
+ that replaces that region still tells the model where things are. The two are complementary — the index
14
+ alone saves nothing on its own, and earlier compaction alone loses pointers.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ dsh plugin add dsh-context-kit
20
+ ```
21
+
22
+ Restart DSH. You get:
23
+
24
+ - two host plugins (`context-kit-index`, `context-kit-tuner`),
25
+ - a **Settings → Context** page,
26
+ - a `preset_tuner` tool,
27
+ - a `dsh-context-kit` CLI.
28
+
29
+ ## Panel: Settings → Context
30
+
31
+ - **Compact at** — the fraction of the context window that triggers compaction (default `0.5` → ~524K).
32
+ - **Keep after compact** — how much survives compaction (default `0.16` → ~168K).
33
+ - **Save** writes `settings.json`, **Apply to profile** regenerates the profile override, and the page
34
+ tells you to restart. **Preview** shows the exact generated YAML before it is written.
35
+ - **Remove override** deletes the managed block and falls back to upstream defaults.
36
+
37
+ Saving is not the same as applying: the panel never touches YAML until you press Apply, and applying
38
+ never happens silently.
39
+
40
+ Where it stores things:
41
+
42
+ ```
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
45
+ <profile>/cordis.patch.yml # managed block: generated, not hand-written
46
+ <profile>/dsh-context-kit/backups/ # every overwrite keeps the previous file (last 10)
47
+ ```
48
+
49
+ Precedence: `settings.json` wins over the plugin's `config.presets` in the bundle/patch. In practice the
50
+ plugin row can stay empty (`presets: {}`) and the panel is the single place where numbers live — the
51
+ managed block in `cordis.patch.yml` always reflects what you last applied.
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
+
79
+ ## Why the tuner exists (the freeze problem)
80
+
81
+ The live `compaction-basic` instance lives **inside the agent preset**, in a group that is `isolate`d.
82
+ A host-level plugin cannot reach that service, and a profile patch row `- id: compaction-basic` targets
83
+ an inactive leftover row — it looks right and does nothing.
84
+
85
+ Overriding a preset row replaces its `config` wholesale, so the only way in is to restate the whole
86
+ preset. Hand-writing that copy freezes the preset: from then on you stop receiving upstream preset
87
+ updates. The tuner instead reads the preset **out of the running app** (`resources/app.asar`) and
88
+ regenerates the restatement:
89
+
90
+ - upstream text is kept byte for byte,
91
+ - your changes are inserted as extra lines only,
92
+ - the result lives in a marked managed block,
93
+ - after a DSH update the next startup (or `Apply`) regenerates it from the new upstream preset.
94
+
95
+ Unit tests assert the insertion-only property against the real shipped presets, and a live check reads
96
+ this machine's `app.asar` end to end.
97
+
98
+ ## CLI
99
+
100
+ ```bash
101
+ dsh-context-kit status
102
+ dsh-context-kit set --threshold 0.5 --retain 0.16 --preset cordis
103
+ dsh-context-kit sync [--force --mode replace]
104
+ dsh-context-kit preview
105
+ dsh-context-kit clear
106
+ dsh-context-kit report [--days 7]
107
+ ```
108
+
109
+ `--resources "<DSH install>/resources"` when it cannot find the app by itself.
110
+ `--force --mode replace` is required to take over a hand-written override; without it the tool refuses
111
+ and points at the line numbers.
112
+
113
+ ## Tool
114
+
115
+ ```text
116
+ preset_tuner(action="status" | "preview" | "sync" | "clear" | "report", days?)
117
+ ```
118
+
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.
121
+
122
+ ## Safety
123
+
124
+ - **Fail closed.** If the upstream preset cannot be located, extracted, or modified safely (renamed
125
+ plugin, changed layout, key already set upstream), nothing is written.
126
+ - **Never edits upstream text**, only inserts.
127
+ - **Never silently masks upstream values**: a configured key that upstream already sets aborts the sync.
128
+ - **Refuses to eat hand-written overrides** unless explicitly forced.
129
+ - **Backups + idempotence**: unchanged input writes nothing, so it never creates restart noise.
130
+
131
+ ## What it does not do (yet)
132
+
133
+ - It does not evict history itself. Batch eviction of old tool results is the next lever; the tuner
134
+ already supports adding a plugin into a preset group, which is where such an evictor has to live to
135
+ see the compaction service.
136
+ - The trigger estimate assumes the documented window (`contextWindow` 1048576, `maxOutputTokens` 256000,
137
+ `headroomTokens` 65536). Override them in the plugin config if your model differs.
138
+
139
+ ## Rollback
140
+
141
+ ```bash
142
+ dsh-context-kit clear # then restart
143
+ ```
144
+
145
+ Backups remain in `<profile>/dsh-context-kit/backups/`.
146
+
147
+ ## License
148
+
149
+ MIT
@@ -1,138 +1,173 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dsh-context-kit CLI —— 在 app 之外跑 status / sync / clear / set。
4
- * 面板与 Host 工具走的是同一套逻辑(lib/kit-ops.mjs),这里只是命令行外壳。
5
- *
6
- * dsh-context-kit status
7
- * dsh-context-kit set --threshold 0.5 --retain 0.16 [--preset cordis]
8
- * dsh-context-kit sync [--force --mode replace]
9
- * dsh-context-kit preview
10
- * dsh-context-kit clear
11
- *
12
- * app 位置默认取 --resources / DSH_APP_RESOURCES;profile 默认按模块路径或 ~/.dsh 推断。
13
- */
14
- import { createKit, triggersFor } from '../lib/kit-ops.mjs'
15
-
16
- function parseArgs(argv) {
17
- const out = { _: [] }
18
- for (let i = 0; i < argv.length; i += 1) {
19
- const token = argv[i]
20
- if (!token.startsWith('--')) {
21
- out._.push(token)
22
- continue
23
- }
24
- const key = token.slice(2)
25
- const next = argv[i + 1]
26
- if (next === undefined || next.startsWith('--')) {
27
- out[key] = true
28
- continue
29
- }
30
- out[key] = next
31
- i += 1
32
- }
33
- return out
34
- }
35
-
36
- const fail = (message) => {
37
- console.error(`错误: ${message}`)
38
- process.exit(1)
39
- }
40
-
41
- const args = parseArgs(process.argv.slice(2))
42
- const command = args._[0] ?? 'status'
43
- const fmt = (tokens) => `${Math.round(tokens / 1024)}K`
44
-
45
- const config = {
46
- profileDir: typeof args['profile-dir'] === 'string' ? args['profile-dir'] : '',
47
- profile: typeof args.profile === 'string' ? args.profile : 'desktop',
48
- appRoot: typeof args['app-root'] === 'string' ? args['app-root'] : typeof args.resources === 'string' ? args.resources : '',
49
- autoSync: false,
50
- }
51
-
52
- let kit
53
- try {
54
- kit = createKit(config)
55
- } catch (error) {
56
- fail(error.message)
57
- }
58
-
59
- if (command === 'status') {
60
- const state = kit.describe()
61
- console.log(`profile : ${state.profileDir}(${state.profileVia})`)
62
- console.log(`补丁 : ${state.patchPath}`)
63
- console.log(`上游 : ${state.sources.join(' | ')}`)
64
- console.log(`预设 : ${state.upstreamPresets.join(', ')}`)
65
- console.log(`托管块 : ${state.managed.map((block) => `${block.presetId}@${block.sha}`).join(', ') || '<无>'}`)
66
- console.log(
67
- `阈值 : ${state.knobs.thresholdRatio}(${fmt(state.triggers.thresholdTokens)} 触发)` +
68
- ` / 保留 ${state.knobs.retainRatio}(${fmt(state.triggers.retainTokens)})`,
69
- )
70
- for (const entry of state.entries) {
71
- const where = !entry.previousSha ? '未生成' : entry.drifted ? `需重新 sync(${entry.previousSha}→${entry.upstreamSha})` : '已最新'
72
- console.log(` - ${entry.presetId}: ${where}`)
73
- }
74
- for (const item of state.foreign) console.log(` ! 手写覆盖: ${item.presetId} 第 ${item.line} 行`)
75
- for (const problem of state.problems) console.log(` ! ${problem}`)
76
- process.exit(0)
77
- }
78
-
79
- if (command === 'set') {
80
- const threshold = Number(args.threshold ?? 0.5)
81
- const retain = Number(args.retain ?? 0.16)
82
- try {
83
- const result = kit.saveCompaction({
84
- presetId: typeof args.preset === 'string' ? args.preset : undefined,
85
- thresholdRatio: threshold,
86
- retainRatio: retain,
87
- auto: args.auto !== 'false',
88
- })
89
- console.log(`已写入设置: ${result.presetId} threshold=${threshold} retain=${retain}`)
90
- console.log(`触发点约 ${fmt(result.triggers.thresholdTokens)},压缩后保留约 ${fmt(result.triggers.retainTokens)}`)
91
- console.log('接着运行 sync 把它写进 profile 补丁,然后重启 DSH。')
92
- } catch (error) {
93
- fail(error.message)
94
- }
95
- process.exit(0)
96
- }
97
-
98
- if (command === 'preview') {
99
- try {
100
- console.log(kit.preview())
101
- } catch (error) {
102
- fail(error.message)
103
- }
104
- process.exit(0)
105
- }
106
-
107
- if (command === 'sync') {
108
- try {
109
- const result = kit.sync({ force: Boolean(args.force), mode: args.mode === 'replace' ? 'replace' : 'append' })
110
- if (!result.changed) {
111
- console.log('已是最新,文件未改动。')
112
- process.exit(0)
113
- }
114
- console.log(`已写入 ${result.path}`)
115
- if (result.backup) console.log(`备份 ${result.backup}`)
116
- if (result.removedForeign) console.log(`接管 移除手写覆盖 ${result.removedForeign} 处`)
117
- for (const entry of result.entries) {
118
- console.log(` - ${entry.presetId}: sha ${entry.upstreamSha}${entry.drifted ? `(漂移 ${entry.previousSha}→${entry.upstreamSha})` : ''}`)
119
- }
120
- console.log('重启 DSH 后生效。')
121
- } catch (error) {
122
- fail(error.message)
123
- }
124
- process.exit(0)
125
- }
126
-
127
- if (command === 'clear') {
128
- const result = kit.clear()
129
- if (!result.changed) {
130
- console.log('没有托管块。')
131
- process.exit(0)
132
- }
133
- console.log(`已移除 ${result.removed} 个托管块${result.backup ? `,备份 ${result.backup}` : ''}。重启 DSH 后生效。`)
134
- process.exit(0)
135
- }
136
-
137
- fail(`未知命令: ${command}(可用: status | set | preview | sync | clear)`)
138
- export { triggersFor }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-context-kit CLI —— 在 app 之外跑 status / sync / clear / set。
4
+ * 面板与 Host 工具走的是同一套逻辑(lib/kit-ops.mjs),这里只是命令行外壳。
5
+ *
6
+ * dsh-context-kit status
7
+ * dsh-context-kit set --threshold 0.5 --retain 0.16 [--preset cordis]
8
+ * dsh-context-kit sync [--force --mode replace]
9
+ * dsh-context-kit preview
10
+ * dsh-context-kit clear
11
+ *
12
+ * app 位置默认取 --resources / DSH_APP_RESOURCES;profile 默认按模块路径或 ~/.dsh 推断。
13
+ */
14
+ import { createKit, triggersFor } from '../lib/kit-ops.mjs'
15
+
16
+ function parseArgs(argv) {
17
+ const out = { _: [] }
18
+ for (let i = 0; i < argv.length; i += 1) {
19
+ const token = argv[i]
20
+ if (!token.startsWith('--')) {
21
+ out._.push(token)
22
+ continue
23
+ }
24
+ const key = token.slice(2)
25
+ const next = argv[i + 1]
26
+ if (next === undefined || next.startsWith('--')) {
27
+ out[key] = true
28
+ continue
29
+ }
30
+ out[key] = next
31
+ i += 1
32
+ }
33
+ return out
34
+ }
35
+
36
+ const fail = (message) => {
37
+ console.error(`错误: ${message}`)
38
+ process.exit(1)
39
+ }
40
+
41
+ const args = parseArgs(process.argv.slice(2))
42
+ const command = args._[0] ?? 'status'
43
+ const fmt = (tokens) => `${Math.round(tokens / 1024)}K`
44
+
45
+ const config = {
46
+ profileDir: typeof args['profile-dir'] === 'string' ? args['profile-dir'] : '',
47
+ profile: typeof args.profile === 'string' ? args.profile : 'desktop',
48
+ appRoot: typeof args['app-root'] === 'string' ? args['app-root'] : typeof args.resources === 'string' ? args.resources : '',
49
+ autoSync: false,
50
+ }
51
+
52
+ let kit
53
+ try {
54
+ kit = createKit(config)
55
+ } catch (error) {
56
+ fail(error.message)
57
+ }
58
+
59
+ if (command === 'status') {
60
+ const state = kit.describe()
61
+ console.log(`profile : ${state.profileDir}(${state.profileVia})`)
62
+ console.log(`补丁 : ${state.patchPath}`)
63
+ console.log(`上游 : ${state.sources.join(' | ')}`)
64
+ console.log(`预设 : ${state.upstreamPresets.join(', ')}`)
65
+ console.log(`托管块 : ${state.managed.map((block) => `${block.presetId}@${block.sha}`).join(', ') || '<无>'}`)
66
+ console.log(
67
+ `阈值 : ${state.knobs.thresholdRatio}(${fmt(state.triggers.thresholdTokens)} 触发)` +
68
+ ` / 保留 ${state.knobs.retainRatio}(${fmt(state.triggers.retainTokens)})`,
69
+ )
70
+ for (const entry of state.entries) {
71
+ const where = !entry.previousSha ? '未生成' : entry.drifted ? `需重新 sync(${entry.previousSha}→${entry.upstreamSha})` : '已最新'
72
+ console.log(` - ${entry.presetId}: ${where}`)
73
+ }
74
+ for (const item of state.foreign) console.log(` ! 手写覆盖: ${item.presetId} 第 ${item.line} 行`)
75
+ for (const problem of state.problems) console.log(` ! ${problem}`)
76
+ process.exit(0)
77
+ }
78
+
79
+ if (command === 'set') {
80
+ const threshold = Number(args.threshold ?? 0.5)
81
+ const retain = Number(args.retain ?? 0.16)
82
+ try {
83
+ const result = kit.saveCompaction({
84
+ presetId: typeof args.preset === 'string' ? args.preset : undefined,
85
+ thresholdRatio: threshold,
86
+ retainRatio: retain,
87
+ auto: args.auto !== 'false',
88
+ })
89
+ console.log(`已写入设置: ${result.presetId} threshold=${threshold} retain=${retain}`)
90
+ console.log(`触发点约 ${fmt(result.triggers.thresholdTokens)},压缩后保留约 ${fmt(result.triggers.retainTokens)}`)
91
+ console.log('接着运行 sync 把它写进 profile 补丁,然后重启 DSH。')
92
+ } catch (error) {
93
+ fail(error.message)
94
+ }
95
+ process.exit(0)
96
+ }
97
+
98
+ if (command === 'preview') {
99
+ try {
100
+ console.log(kit.preview())
101
+ } catch (error) {
102
+ fail(error.message)
103
+ }
104
+ process.exit(0)
105
+ }
106
+
107
+ if (command === 'sync') {
108
+ try {
109
+ const result = kit.sync({ force: Boolean(args.force), mode: args.mode === 'replace' ? 'replace' : 'append' })
110
+ if (!result.changed) {
111
+ console.log('已是最新,文件未改动。')
112
+ process.exit(0)
113
+ }
114
+ console.log(`已写入 ${result.path}`)
115
+ if (result.backup) console.log(`备份 ${result.backup}`)
116
+ if (result.removedForeign) console.log(`接管 移除手写覆盖 ${result.removedForeign} 处`)
117
+ for (const entry of result.entries) {
118
+ console.log(` - ${entry.presetId}: sha ${entry.upstreamSha}${entry.drifted ? `(漂移 ${entry.previousSha}→${entry.upstreamSha})` : ''}`)
119
+ }
120
+ console.log('重启 DSH 后生效。')
121
+ } catch (error) {
122
+ fail(error.message)
123
+ }
124
+ process.exit(0)
125
+ }
126
+
127
+ if (command === 'clear') {
128
+ const result = kit.clear()
129
+ if (!result.changed) {
130
+ console.log('没有托管块。')
131
+ process.exit(0)
132
+ }
133
+ console.log(`已移除 ${result.removed} 个托管块${result.backup ? `,备份 ${result.backup}` : ''}。重启 DSH 后生效。`)
134
+ process.exit(0)
135
+ }
136
+
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)`)
173
+ export { triggersFor }