dsh-context-compression-improved 0.5.7 → 0.5.8

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +16 -17
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +59 -0
  5. package/packages/selector/lib/client.js +1012 -17
  6. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +295 -3
  9. package/packages/selector/lib/pruner.d.ts +65 -0
  10. package/packages/selector/lib/pruner.js +497 -262
  11. package/packages/selector/lib/style.css +42 -0
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  15. package/packages/selector/src/client/decode.ts +10 -2
  16. package/packages/selector/src/client/index.ts +62 -0
  17. package/packages/selector/src/client/locales/de.ts +43 -0
  18. package/packages/selector/src/client/locales/es.ts +43 -0
  19. package/packages/selector/src/client/locales/fr.ts +43 -0
  20. package/packages/selector/src/client/locales/it.ts +43 -0
  21. package/packages/selector/src/client/locales/ja.ts +43 -0
  22. package/packages/selector/src/client/locales/ko.ts +43 -0
  23. package/packages/selector/src/client/locales/ru.ts +43 -0
  24. package/packages/selector/src/client/locales.ts +86 -0
  25. package/packages/selector/src/client/monitor-fab.ts +336 -0
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +18 -2
  28. package/packages/selector/src/index.ts +215 -5
  29. package/packages/selector/src/profiles.ts +37 -0
  30. package/packages/selector/src/pruner/state.ts +7 -0
  31. package/packages/selector/src/pruner.ts +337 -3
  32. package/packages/selector/src/runtime/audit.ts +17 -0
  33. package/packages/selector/src/runtime/config.ts +52 -2
  34. package/packages/selector/src/runtime/monitor.ts +235 -0
  35. package/packages/selector/src/runtime/retrieve.ts +24 -2
  36. package/packages/selector/src/runtime/savings.ts +337 -0
  37. package/packages/selector/src/runtime/summary-command.ts +127 -0
  38. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  39. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  43. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  44. package/packages/selector/src/runtime/types.ts +19 -0
  45. package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
  46. package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
  47. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  48. package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
  49. package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
  50. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  51. package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
  52. package/packages/selector/tests/profiles.client.spec.tsx +4 -2
  53. package/packages/selector/tests/runtime/audit.spec.ts +1 -0
  54. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  55. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  56. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  57. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  58. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  59. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  60. package/scripts/packed-install-e2e.mjs +1 -1
  61. package/scripts/verify-release.mjs +2 -1
@@ -0,0 +1,301 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest'
2
+ import { parseContextCompressionSettings, DEFAULT_CONTEXT_COMPRESSION_SETTINGS } from '../../src/runtime/config.ts'
3
+ import { SavingsLedger } from '../../src/runtime/savings.ts'
4
+ import {
5
+ applySessionOverride,
6
+ MONITOR_SUGGEST_PCT,
7
+ observeContextUsage,
8
+ buildMonitorSnapshot,
9
+ estimateSavingsPricing,
10
+ isSessionOverrideAction,
11
+ } from '../../src/runtime/monitor.ts'
12
+ import { getSummaryOverride } from '../../src/runtime/tokenpilot/advisor-state.ts'
13
+
14
+ /** 每用例独立 sessionId:advisor-state 的覆盖表是模块级,防用例间串扰。 */
15
+ let seq = 0
16
+ const uniqueSession = (): string => `monitor-spec-${++seq}`
17
+
18
+ afterEach(() => {
19
+ vi.restoreAllMocks()
20
+ })
21
+
22
+ describe('buildMonitorSnapshot', () => {
23
+ it('savings aggregate plus the intent control block, defaults lossless', () => {
24
+ const snap = buildMonitorSnapshot(undefined, new SavingsLedger())
25
+ expect(snap.gross.exact).toBe(0)
26
+ expect(snap.sessionScope).toBeNull()
27
+ expect(snap.intent.override).toBeUndefined()
28
+ expect(snap.intent.observedEnabled).toBeUndefined()
29
+ expect(snap.intent.gate).toEqual({ floorFraction: 0.45, growthTokens: 50_000 })
30
+ expect(snap.intent.lastFold).toBeUndefined()
31
+ })
32
+
33
+ it('session filter scopes the savings rows and the control block', () => {
34
+ const ledger = new SavingsLedger()
35
+ ledger.recordSaving({
36
+ sessionId: 's1',
37
+ component: 'fresh',
38
+ tokensBefore: 10_000,
39
+ tokensAfter: 2_000,
40
+ basis: 'exact-tokenizer',
41
+ sourceSeq: 1,
42
+ })
43
+ const scoped = buildMonitorSnapshot('s1', ledger)
44
+ expect(scoped.sessionScope).toBe('s1')
45
+ expect(scoped.gross.exact).toBe(8_000)
46
+ const other = buildMonitorSnapshot('s2', ledger)
47
+ expect(other.gross.exact).toBe(0)
48
+ })
49
+
50
+ it('reuses the ledger verbatim — no second accounting', () => {
51
+ const ledger = new SavingsLedger()
52
+ ledger.recordSaving({
53
+ sessionId: 's1',
54
+ component: 'fresh',
55
+ tokensBefore: 1_000,
56
+ tokensAfter: 100,
57
+ basis: 'exact-tokenizer',
58
+ sourceSeq: 2,
59
+ originalText: 'x\n'.repeat(400),
60
+ })
61
+ const monitor = buildMonitorSnapshot('s1', ledger)
62
+ expect(monitor).toMatchObject(ledger.snapshot('s1'))
63
+ })
64
+ })
65
+
66
+ describe('applySessionOverride (the /ctx-summary state machine)', () => {
67
+ it('pins on/off and echoes the post-action truth', () => {
68
+ const sessionId = uniqueSession()
69
+ expect(applySessionOverride(sessionId, 'on').override).toBe('on')
70
+ expect(getSummaryOverride(sessionId)).toBe('on')
71
+ expect(applySessionOverride(sessionId, 'off').override).toBe('off')
72
+ expect(getSummaryOverride(sessionId)).toBe('off')
73
+ })
74
+
75
+ it('clear returns the session to settings-driven', () => {
76
+ const sessionId = uniqueSession()
77
+ applySessionOverride(sessionId, 'off')
78
+ expect(applySessionOverride(sessionId, 'clear').override).toBeUndefined()
79
+ expect(getSummaryOverride(sessionId)).toBeUndefined()
80
+ })
81
+
82
+ it('isSessionOverrideAction narrows exactly the three actions', () => {
83
+ expect(isSessionOverrideAction('on')).toBe(true)
84
+ expect(isSessionOverrideAction('off')).toBe(true)
85
+ expect(isSessionOverrideAction('clear')).toBe(true)
86
+ expect(isSessionOverrideAction('status')).toBe(false)
87
+ expect(isSessionOverrideAction(42)).toBe(false)
88
+ })
89
+ })
90
+
91
+ describe('estimateSavingsPricing (moved from the entry — shared by savings and monitor routes)', () => {
92
+ const snapshot = {
93
+ startedAt: new Date().toISOString(),
94
+ net: { exact: 4_200, estimated: 0 },
95
+ usage: { requests: 3, inputTokens: 1_000, outputTokens: 500, cacheReadTokens: 200, cacheWriteTokens: 100 },
96
+ }
97
+
98
+ it('third-party routes fail closed to no pricing', () => {
99
+ const readService = (): unknown => ({ currentSelection: () => ({ provider: 'local-35b', model: 'Qwen3.6-35B-A3B' }) })
100
+ expect(estimateSavingsPricing(readService, snapshot)).toBeUndefined()
101
+ })
102
+
103
+ it('official routes carry actual cost and the labeled saved-cost estimate', () => {
104
+ const readService = (): unknown => ({ currentSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) })
105
+ const pricing = estimateSavingsPricing(readService, snapshot)
106
+ expect(pricing?.currency).toBe('USD')
107
+ expect(typeof pricing?.actualCost).toBe('string')
108
+ expect(typeof pricing?.estimatedSavedCost).toBe('string')
109
+ })
110
+
111
+ it('an empty ledger prices nothing', () => {
112
+ const readService = (): unknown => ({ currentSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) })
113
+ expect(estimateSavingsPricing(readService, {
114
+ startedAt: new Date().toISOString(),
115
+ net: { exact: 0, estimated: 0 },
116
+ usage: { requests: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
117
+ })).toBeUndefined()
118
+ })
119
+ })
120
+
121
+
122
+ import type { Context } from '@deepseek-ai/cordis'
123
+ import { registerMonitorRoute } from '../../src/index.ts'
124
+
125
+ /** Fake webServer: captures exact-path handlers; fake ctx wires direct arrival. */
126
+ function mountMonitorRoute(): { handler: (req: unknown, res: unknown) => void } {
127
+ let handler: (req: unknown, res: unknown) => void = () => {}
128
+ const webServer = { register: (def: { path: string, handler: typeof handler }) => { handler = def.handler; return () => undefined } }
129
+ const ctx = {
130
+ get: (name: string) => (name === 'webServer' ? webServer : undefined),
131
+ inject: (deps: string[], cb: (injected: Record<string, unknown>) => void) => cb({ webServer }),
132
+ effect: () => undefined,
133
+ } as unknown as Context
134
+ registerMonitorRoute(ctx)
135
+ return { handler }
136
+ }
137
+
138
+ interface CapturedResponse {
139
+ status: number
140
+ body: Record<string, unknown>
141
+ }
142
+
143
+ function fakeRes(): { res: unknown, captured: CapturedResponse } {
144
+ const captured = {} as CapturedResponse
145
+ const res = {
146
+ writeHead: (status: number) => { captured.status = status },
147
+ end: (body?: string) => { captured.body = JSON.parse(body ?? '{}') as Record<string, unknown> },
148
+ }
149
+ return { res, captured }
150
+ }
151
+
152
+ function fakeReq(url: string, method: string, body?: string): unknown {
153
+ return {
154
+ url,
155
+ method,
156
+ on: (event: string, cb: (chunk?: Buffer) => void) => {
157
+ if (event === 'data' && body !== undefined) cb(Buffer.from(body, 'utf8'))
158
+ if (event === 'end') cb()
159
+ },
160
+ }
161
+ }
162
+
163
+ describe('monitor route (GET snapshot / POST override)', () => {
164
+ const PATH = '/api/dsh-context-compression-improved/monitor'
165
+ const { handler } = mountMonitorRoute()
166
+
167
+ it('GET returns ok + savings + intent block scoped to the query session', () => {
168
+ const { res, captured } = fakeRes()
169
+ handler(fakeReq(`${PATH}?sessionId=route-s1`, 'GET'), res)
170
+ expect(captured.status).toBe(200)
171
+ expect(captured.body.ok).toBe(true)
172
+ expect(captured.body.sessionScope).toBe('route-s1')
173
+ expect((captured.body.intent as Record<string, unknown>).gate).toEqual({ floorFraction: 0.45, growthTokens: 50_000 })
174
+ })
175
+
176
+ it('POST drives the /ctx-summary override state machine', () => {
177
+ const sessionId = `route-${uniqueSession()}`
178
+ const { res, captured } = fakeRes()
179
+ handler(fakeReq(`${PATH}?sessionId=${sessionId}`, 'POST', '{"action":"off"}'), res)
180
+ expect(captured.status).toBe(200)
181
+ expect(captured.body).toEqual({ ok: true, override: 'off', sessionScope: sessionId })
182
+ expect(getSummaryOverride(sessionId)).toBe('off')
183
+ })
184
+
185
+ it('POST rejects an unknown action with 400 and touches no state', () => {
186
+ const sessionId = uniqueSession()
187
+ const { res, captured } = fakeRes()
188
+ handler(fakeReq(`${PATH}?sessionId=${sessionId}`, 'POST', '{"action":"boom"}'), res)
189
+ expect(captured.status).toBe(400)
190
+ expect(captured.body.ok).toBe(false)
191
+ expect(getSummaryOverride(sessionId)).toBeUndefined()
192
+ })
193
+
194
+ it('POST rejects a non-JSON body with 400', () => {
195
+ const { res, captured } = fakeRes()
196
+ handler(fakeReq(PATH, 'POST', 'not-json'), res)
197
+ expect(captured.status).toBe(400)
198
+ expect(captured.body.ok).toBe(false)
199
+ })
200
+ })
201
+
202
+ describe('monitorPanel settings parsing (schema surface, mirrors intentSummary cases)', () => {
203
+ const base = {
204
+ profile: 'balanced' as const,
205
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
206
+ }
207
+
208
+ it('defaults to hidden', () => {
209
+ expect(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.monitorPanel).toEqual({ enabled: false })
210
+ })
211
+
212
+ it('absent section inherits the default', () => {
213
+ const parsed = parseContextCompressionSettings({ ...base, autoCompact: { thresholdPercent: 80 } })
214
+ expect(parsed.monitorPanel).toEqual({ enabled: false })
215
+ })
216
+
217
+ it('accepts exactly { enabled: boolean }', () => {
218
+ const parsed = parseContextCompressionSettings({ ...base, monitorPanel: { enabled: true } })
219
+ expect(parsed.monitorPanel).toEqual({ enabled: true })
220
+ })
221
+
222
+ it('rejects extra keys (present-but-invalid is never silently defaulted)', () => {
223
+ expect(() => parseContextCompressionSettings({
224
+ ...base, monitorPanel: { enabled: true, position: 'left' },
225
+ })).toThrow(/expected exactly "enabled"/)
226
+ })
227
+
228
+ it('rejects non-boolean enabled', () => {
229
+ expect(() => parseContextCompressionSettings({
230
+ ...base, monitorPanel: { enabled: 'yes' },
231
+ })).toThrow(/monitorPanel\.enabled must be a boolean/)
232
+ })
233
+
234
+ it('rejects non-object section', () => {
235
+ expect(() => parseContextCompressionSettings({ ...base, monitorPanel: 'yes' }))
236
+ .toThrow(/monitorPanel must be a plain object/)
237
+ })
238
+ })
239
+
240
+ describe('context occupancy observation (task_6.2)', () => {
241
+ it('scoped snapshot carries the observed occupancy block', () => {
242
+ const sessionId = uniqueSession()
243
+ observeContextUsage(sessionId, 60_000, 128_000)
244
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
245
+ expect(snap.context).toEqual({ liveTokens: 60_000, contextWindow: 128_000, pct: 0.469, sessionId })
246
+ })
247
+
248
+ it('aggregate snapshot carries the most recently observed session', () => {
249
+ const a = uniqueSession()
250
+ const b = uniqueSession()
251
+ observeContextUsage(a, 10_000, 100_000)
252
+ observeContextUsage(b, 90_000, 100_000)
253
+ const snap = buildMonitorSnapshot(undefined, new SavingsLedger())
254
+ expect(snap.context?.sessionId).toBe(b)
255
+ expect(snap.context?.pct).toBe(0.9)
256
+ })
257
+
258
+ it('no observation yet — context block absent', () => {
259
+ const snap = buildMonitorSnapshot(uniqueSession(), new SavingsLedger())
260
+ expect(snap.context).toBeUndefined()
261
+ })
262
+
263
+ it('observation cap keeps the newest 64 sessions', () => {
264
+ for (let i = 0; i < 70; i++) observeContextUsage(`cap-${i}`, i, 1000)
265
+ const snap = buildMonitorSnapshot('cap-69', new SavingsLedger())
266
+ expect(snap.context?.sessionId).toBe('cap-69')
267
+ })
268
+
269
+ it('empty session id and non-finite tokens are ignored', () => {
270
+ observeContextUsage('', 5, 100)
271
+ observeContextUsage('fin-check', Number.NaN, 100)
272
+ expect(buildMonitorSnapshot('fin-check', new SavingsLedger()).context).toBeUndefined()
273
+ })
274
+ })
275
+
276
+ describe('catastrophic-forgetting suggestion (task: 建议压缩)', () => {
277
+ it('occupancy past the threshold suggests compression', () => {
278
+ const sessionId = uniqueSession()
279
+ observeContextUsage(sessionId, 90_000, 100_000)
280
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
281
+ expect(snap.suggestion?.suggest).toBe(true)
282
+ expect(snap.suggestion?.thresholdPct).toBe(MONITOR_SUGGEST_PCT)
283
+ expect(snap.suggestion?.occupancyPct).toBe(0.9)
284
+ })
285
+
286
+ it('below the threshold stays silent', () => {
287
+ const sessionId = uniqueSession()
288
+ observeContextUsage(sessionId, 50_000, 100_000)
289
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
290
+ expect(snap.suggestion?.suggest).toBe(false)
291
+ })
292
+
293
+ it('threshold sits below the host auto-compact default (提前一档人工干预窗口)', () => {
294
+ expect(MONITOR_SUGGEST_PCT).toBeLessThan(0.8)
295
+ })
296
+
297
+ it('unobserved sessions carry no suggestion block', () => {
298
+ expect(buildMonitorSnapshot(uniqueSession(), new SavingsLedger()).suggestion).toBeUndefined()
299
+ })
300
+ })
301
+
@@ -0,0 +1,120 @@
1
+ import { beforeEach, describe, expect, it } from 'vitest'
2
+ import { SavingsLedger, savingsHash } from '../../src/runtime/savings.ts'
3
+
4
+ /** 模拟 pruner land 的真实调用序列:先压缩,后全文重读。 */
5
+ describe('savings ledger(诚实口径)', () => {
6
+ let ledger: SavingsLedger
7
+ beforeEach(() => {
8
+ ledger = new SavingsLedger()
9
+ })
10
+
11
+ it('compression saving lands: gross = tokensBefore − tokensAfter, zero-negative ignored', () => {
12
+ ledger.recordSaving({
13
+ sessionId: 's1',
14
+ component: 'fresh',
15
+ tokensBefore: 10_000,
16
+ tokensAfter: 2_000,
17
+ basis: 'exact-tokenizer',
18
+ sourceSeq: 12,
19
+ originalText: 'const a = 1\n'.repeat(500),
20
+ })
21
+ const snap = ledger.snapshot('s1')
22
+ expect(snap.gross.exact).toBe(8_000)
23
+ expect(snap.net.exact).toBe(8_000)
24
+ // 无节省(没压掉任何东西)不入账
25
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 100, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 13 })
26
+ expect(ledger.snapshot('s1').gross.exact).toBe(8_000)
27
+ })
28
+
29
+ it('**先骨架后全文 = 负节省**:全文重读抵消原声称,净额可为负', () => {
30
+ const original = 'export function readFile() {\n // ...long body...\n}\n'.repeat(200)
31
+ ledger.recordSaving({
32
+ sessionId: 's1',
33
+ component: 'fresh',
34
+ tokensBefore: 5_000,
35
+ tokensAfter: 800,
36
+ basis: 'exact-tokenizer',
37
+ sourceSeq: 7,
38
+ originalText: original,
39
+ })
40
+ // 全文重读(同一原文 → 哈希配对):按全文计量记抵消
41
+ ledger.noteFullText({
42
+ sessionId: 's1',
43
+ seq: 40,
44
+ text: original,
45
+ measure: () => ({ tokens: 5_000, basis: 'exact-tokenizer' }),
46
+ })
47
+ const snap = ledger.snapshot('s1')
48
+ expect(snap.gross.exact).toBe(4_200)
49
+ expect(snap.offsets.exact).toBe(5_000)
50
+ expect(snap.net.exact).toBe(-800) // **负节省**
51
+ expect(snap.recentOffsets).toHaveLength(1)
52
+ expect(snap.recentOffsets[0]?.note).toContain('#7')
53
+ })
54
+
55
+ it('同一 (session, seq) 的全文只探测一次;抵消每个哈希只消费一次', () => {
56
+ const text = 'payload-body\n'.repeat(100)
57
+ ledger.recordSaving({ sessionId: 's1', component: 'history', tokensBefore: 900, tokensAfter: 100, basis: 'characters', sourceSeq: 3, originalText: text })
58
+ const measure = () => ({ tokens: 900, basis: 'characters' as const })
59
+ ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure })
60
+ ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure }) // 同 seq 重放:忽略
61
+ expect(ledger.snapshot('s1').offsets.estimated).toBe(900)
62
+ ledger.noteFullText({ sessionId: 's1', seq: 31, text: text + '\n', measure }) // 新 seq、同哈希:已消费,不再抵消
63
+ expect(ledger.snapshot('s1').offsets.estimated).toBe(900)
64
+ })
65
+
66
+ it('跨会话不串账;retrieve 抵消走估算口径分列', () => {
67
+ const text = 'data\n'.repeat(50)
68
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 1_000, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 1, originalText: text })
69
+ ledger.noteFullText({ sessionId: 's2', seq: 1, text, measure: () => ({ tokens: 1_000, basis: 'exact-tokenizer' }) })
70
+ expect(ledger.snapshot('s1').offsets.exact).toBe(0)
71
+ ledger.recordOffset({ sessionId: 's1', component: 'retrieve', tokens: 300, basis: 'characters' })
72
+ const snap = ledger.snapshot()
73
+ expect(snap.net.exact).toBe(900)
74
+ expect(snap.net.estimated).toBe(-300) // 口径分列:估算抵消不污染精确净额
75
+ expect(snap.sessions).toBe(1)
76
+ })
77
+
78
+ it('savingsHash 规整行尾与首尾空白:同文件两次读取的 innocuous 差异仍配对', () => {
79
+ expect(savingsHash('a\nb\r\nc')).toBe(savingsHash('a\nb\nc'))
80
+ expect(savingsHash(' a\nb ')).toBe(savingsHash('a\nb'))
81
+ expect(savingsHash('a')).not.toBe(savingsHash('b'))
82
+ })
83
+ })
84
+
85
+ describe('savings ledger(usage 聚合与分桶,monitor 口径)', () => {
86
+ let ledger: SavingsLedger
87
+ beforeEach(() => {
88
+ ledger = new SavingsLedger()
89
+ })
90
+
91
+ it('aggregates official usage per session and computes cache hit rate', () => {
92
+ ledger.recordUsage('s1', { inputTokens: 100, outputTokens: 500, cacheReadTokens: 9_000, cacheWriteTokens: 400 })
93
+ ledger.recordUsage('s1', { inputTokens: 200, outputTokens: 300, cacheReadTokens: 8_000, cacheWriteTokens: 500 })
94
+ const snap = ledger.snapshot('s1')
95
+ expect(snap.usage.requests).toBe(2)
96
+ expect(snap.usage.inputTokens).toBe(300)
97
+ expect(snap.usage.cacheReadTokens).toBe(17_000)
98
+ expect(snap.usage.cacheHitRate).toBeCloseTo(17_000 / 18_200, 3)
99
+ })
100
+
101
+ it('buckets sessions by net savings; per-session list only in global snapshot', () => {
102
+ ledger.recordUsage('s1', { inputTokens: 10, outputTokens: 1, cacheReadTokens: 90, cacheWriteTokens: 0 })
103
+ ledger.recordUsage('s2', { inputTokens: 10, outputTokens: 1, cacheReadTokens: 10, cacheWriteTokens: 0 })
104
+ ledger.recordSaving({ sessionId: 's2', component: 'fresh', tokensBefore: 500, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 1 })
105
+ const global = ledger.snapshot()
106
+ expect(global.perSession).toHaveLength(2)
107
+ expect(global.perSession[0]!.sessionId).toBe('s2')
108
+ expect(global.perSession[0]!.cacheHitRate).toBe(0.5)
109
+ const single = ledger.snapshot('s1')
110
+ expect(single.perSession).toHaveLength(0)
111
+ })
112
+
113
+ it('sessionSummaryLine renders one-line account for dispose log', () => {
114
+ ledger.recordUsage('s1', { inputTokens: 100, outputTokens: 10, cacheReadTokens: 900, cacheWriteTokens: 0 })
115
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 400, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 2 })
116
+ const line = ledger.sessionSummaryLine('s1')
117
+ expect(line).toContain('net=300(exact)/0(est)')
118
+ expect(line).toContain('cacheHit=90%')
119
+ })
120
+ })
@@ -0,0 +1,154 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ DEFAULT_CONTEXT_COMPRESSION_SETTINGS,
4
+ parseContextCompressionSettings,
5
+ } from '../../src/runtime/config.ts'
6
+ import {
7
+ getLastIntentFold,
8
+ getObservedIntentEnabled,
9
+ getSummaryOverride,
10
+ recordIntentFold,
11
+ setSummaryOverride,
12
+ observeIntentEnabled,
13
+ } from '../../src/runtime/tokenpilot/advisor-state.ts'
14
+ import {
15
+ parseSummaryCommandArgs,
16
+ registerSummaryCommand,
17
+ } from '../../src/runtime/summary-command.ts'
18
+
19
+ describe('intentSummary settings parsing', () => {
20
+ it('defaults to lossless off', () => {
21
+ expect(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.intentSummary).toEqual({ enabled: false })
22
+ })
23
+
24
+ it('absent section inherits the default', () => {
25
+ const parsed = parseContextCompressionSettings({
26
+ profile: 'balanced',
27
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
28
+ autoCompact: { thresholdPercent: 80 },
29
+ codeSkeleton: { enabled: false },
30
+ })
31
+ expect(parsed.intentSummary).toEqual({ enabled: false })
32
+ })
33
+
34
+ it('accepts exactly { enabled: boolean }', () => {
35
+ const parsed = parseContextCompressionSettings({
36
+ profile: 'balanced',
37
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
38
+ intentSummary: { enabled: true },
39
+ })
40
+ expect(parsed.intentSummary).toEqual({ enabled: true })
41
+ })
42
+
43
+ it('rejects extra keys (present-but-invalid is never silently defaulted)', () => {
44
+ expect(() => parseContextCompressionSettings({
45
+ profile: 'balanced',
46
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
47
+ intentSummary: { enabled: true, gate: 1 },
48
+ })).toThrow(/expected exactly "enabled"/)
49
+ })
50
+
51
+ it('rejects non-boolean enabled', () => {
52
+ expect(() => parseContextCompressionSettings({
53
+ profile: 'balanced',
54
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
55
+ intentSummary: { enabled: 'yes' },
56
+ })).toThrow(/intentSummary\.enabled must be a boolean/)
57
+ })
58
+
59
+ it('rejects non-object section', () => {
60
+ expect(() => parseContextCompressionSettings({
61
+ profile: 'balanced',
62
+ custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
63
+ intentSummary: true,
64
+ })).toThrow(/intentSummary must be a plain object/)
65
+ })
66
+ })
67
+
68
+ describe('session-scoped summary override state', () => {
69
+ it('round-trips and clears per session id, isolated across sessions', () => {
70
+ expect(getSummaryOverride('s1')).toBeUndefined()
71
+ setSummaryOverride('s1', 'off')
72
+ setSummaryOverride('s2', 'on')
73
+ expect(getSummaryOverride('s1')).toBe('off')
74
+ expect(getSummaryOverride('s2')).toBe('on')
75
+ setSummaryOverride('s1', undefined)
76
+ expect(getSummaryOverride('s1')).toBeUndefined()
77
+ expect(getSummaryOverride('s2')).toBe('on')
78
+ })
79
+
80
+ it('observed enabled flag round-trips independently', () => {
81
+ expect(getObservedIntentEnabled('sx')).toBeUndefined()
82
+ observeIntentEnabled('sx', true)
83
+ expect(getObservedIntentEnabled('sx')).toBe(true)
84
+ })
85
+
86
+ it('last fold record is newest-wins per session', () => {
87
+ expect(getLastIntentFold('sy')).toBeUndefined()
88
+ recordIntentFold('sy', { turn: 3, startSeq: 10, endSeq: 20, liveTokensBefore: 100_000, at: 1 })
89
+ recordIntentFold('sy', { turn: 5, startSeq: 30, endSeq: 40, liveTokensBefore: 150_000, at: 2 })
90
+ expect(getLastIntentFold('sy')).toMatchObject({ turn: 5, startSeq: 30 })
91
+ })
92
+ })
93
+
94
+ describe('/ctx-summary command surface', () => {
95
+ it('parses exactly off|on|status (case-insensitive, trimmed)', () => {
96
+ expect(parseSummaryCommandArgs(' off ')).toBe('off')
97
+ expect(parseSummaryCommandArgs('ON')).toBe('on')
98
+ expect(parseSummaryCommandArgs('Status')).toBe('status')
99
+ expect(parseSummaryCommandArgs('')).toBeUndefined()
100
+ expect(parseSummaryCommandArgs('now')).toBeUndefined()
101
+ expect(parseSummaryCommandArgs('off extra')).toBeUndefined()
102
+ })
103
+
104
+ it('handler sets and clears the override for the invocation session', async () => {
105
+ let registered: { name: string, handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: string, text: string }> } | undefined
106
+ const commands = { register: (definition: unknown): void => { registered = definition as typeof registered } }
107
+ const ctx = {
108
+ inject: (deps: readonly string[], callback: (injected: Record<string, unknown>) => void): void => {
109
+ if (deps.includes('commands')) callback({ commands })
110
+ },
111
+ }
112
+ registerSummaryCommand(ctx as never)
113
+ await vi.waitFor(() => expect(registered).toBeDefined())
114
+ expect(registered?.name).toBe('ctx-summary')
115
+
116
+ const agent = { session: { id: 'sess-1' } }
117
+ const off = await registered!.handler({ agent, rawInput: 'off' })
118
+ expect(off.kind).toBe('success')
119
+ expect(getSummaryOverride('sess-1')).toBe('off')
120
+
121
+ const on = await registered!.handler({ agent, rawInput: 'on' })
122
+ expect(on.kind).toBe('success')
123
+ expect(getSummaryOverride('sess-1')).toBe('on')
124
+
125
+ const bad = await registered!.handler({ agent, rawInput: 'wat' })
126
+ expect(bad.kind).toBe('error')
127
+ })
128
+
129
+ it('status reports override, gate and last fold', async () => {
130
+ let registered: { handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: string, text: string }> } | undefined
131
+ const commands = { register: (definition: unknown): void => { registered = definition as typeof registered } }
132
+ registerSummaryCommand({
133
+ inject: (_deps: readonly string[], callback: (injected: Record<string, unknown>) => void) => callback({ commands }),
134
+ } as never)
135
+ await vi.waitFor(() => expect(registered).toBeDefined())
136
+ recordIntentFold('sess-9', { turn: 7, startSeq: 5, endSeq: 9, liveTokensBefore: 120_000, at: 42 })
137
+ const out = await registered!.handler({ agent: { session: { id: 'sess-9' } }, rawInput: 'status' })
138
+ expect(out.kind).toBe('success')
139
+ expect(out.text).toContain('override: default')
140
+ expect(out.text).toContain('seq 5..9')
141
+ expect(out.text).toContain('45% of window')
142
+ })
143
+
144
+ it('stays quiet when the commands service never mounts', () => {
145
+ const ctx = {
146
+ inject: (deps: readonly string[], callback: (injected: Record<string, unknown>) => void) => {
147
+ // cordis semantics: the callback never runs when a dependency is absent.
148
+ void deps
149
+ void callback
150
+ },
151
+ }
152
+ expect(() => registerSummaryCommand(ctx as never)).not.toThrow()
153
+ })
154
+ })
@@ -63,16 +63,17 @@ function collectRegistrations(
63
63
  return { declared, registrations }
64
64
  }
65
65
 
66
- describe('settings-seat contract (standalone settings.section only)', () => {
66
+ describe('settings-seat contract (standalone settings.section + input-bar session binder)', () => {
67
67
  it('declares the services apply consumes (cordis waits; no lazy-get race)', () => {
68
68
  expect(inject).toEqual(['slots', 'locale', 'settingsScope'])
69
69
  })
70
70
 
71
- it('injects exactly the settings.section seat and nothing else', () => {
71
+ it('injects exactly two seats: the settings.section panel + the input-bar session binder', () => {
72
72
  const { declared, registrations } = collectRegistrations()
73
- expect(declared).toEqual(['settings.section'])
74
- expect(registrations).toHaveLength(1)
73
+ expect(declared).toEqual(['settings.section', 'conversation.input.left'])
74
+ expect(registrations).toHaveLength(2)
75
75
  expect(registrations[0]!.slot).toBe('settings.section')
76
+ expect(registrations[1]!.slot).toBe('conversation.input.left')
76
77
  })
77
78
 
78
79
  it('no longer claims a shell.overlay float (the review panel it served is gone)', () => {
@@ -89,10 +90,21 @@ describe('settings-seat contract (standalone settings.section only)', () => {
89
90
  expect((options['label'] as () => string)()).toBe('nav')
90
91
  expect(typeof options['inject']).toBe('function')
91
92
  const face = (options['inject'] as () => Record<string, unknown>)()
92
- expect(Object.keys(face).sort()).toEqual(['hooks', 'saveAutoCompact', 'saveCodeSkeleton', 'saveCustom', 'savePresetOptions', 'select', 'resetCustom'].sort())
93
+ expect(Object.keys(face).sort()).toEqual(['hooks', 'saveAutoCompact', 'saveCodeSkeleton', 'saveCustom', 'saveIntentSummary', 'saveMonitorPanel', 'savePresetOptions', 'select', 'resetCustom'].sort())
93
94
  expect(component).toBe(ContextCompressionSettingsSection)
94
95
  })
95
96
 
97
+ it('pins the input-bar binder: invisible component, inject captures the bare sessionId', () => {
98
+ const { registrations } = collectRegistrations()
99
+ const inputSeat = registrations[1]!
100
+ expect(inputSeat.options['id']).toBe('context-compression-session-bind')
101
+ expect(inputSeat.options['order']).toBe(170)
102
+ expect(typeof inputSeat.options['inject']).toBe('function')
103
+ const face = (inputSeat.options['inject'] as (sessionId: string) => Record<string, unknown>)('sess-42')
104
+ expect(face).toEqual({})
105
+ expect(inputSeat.component).toBeTypeOf('function')
106
+ })
107
+
96
108
  it('never adds a Plugins-section card or tab alongside the standalone section', () => {
97
109
  const { declared } = collectRegistrations()
98
110
  expect(declared).not.toContain('settings.plugins.tab')
@@ -107,8 +119,8 @@ describe('settings-seat contract (standalone settings.section only)', () => {
107
119
  const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
108
120
  try {
109
121
  const { declared } = collectRegistrations({ registerThrows: true })
110
- // It tried the seat (so the degradation is "loud", not a silent no-op)…
111
- expect(declared).toEqual(['settings.section'])
122
+ // It tried both seats (so the degradation is "loud", not a silent no-op)…
123
+ expect(declared).toEqual(['settings.section', 'conversation.input.left'])
112
124
  // …and the rejection never escaped apply().
113
125
  expect(warn).toHaveBeenCalled()
114
126
  } finally {
@@ -416,7 +416,7 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
416
416
  * ui-slot packages) the web bundler supplies, and that stack is verified
417
417
  * from the built client libraries below.
418
418
  */
419
- const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'advisor-state.js', 'tail-trim.js', 'invariant.js']
419
+ const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'config.js', 'tail-trim.js', 'invariant.js']
420
420
 
421
421
  /**
422
422
  * Bare package names the installed package's host-plane runtime files import.
@@ -39,6 +39,7 @@ if (rootPackage.dsh?.bundle?.patch !== './packages/selector/cordis.patch.yml') {
39
39
  const INSTALLATION_PROVIDED_RUNTIME = new Set([
40
40
  '@deepseek-ai/cordis',
41
41
  '@deepseek-ai/cordis-plugin-include',
42
+ '@deepseek-ai/dsh-commands',
42
43
  '@deepseek-ai/dsh-llm',
43
44
  '@deepseek-ai/dsh-session',
44
45
  '@deepseek-ai/dsh-settings',
@@ -48,7 +49,7 @@ const INSTALLATION_PROVIDED_RUNTIME = new Set([
48
49
  // stack (`react`, the ui-slot packages); its requires are reviewed from the
49
50
  // built artifact further down instead.
50
51
  const HOST_PLANE_ENTRIES = [
51
- 'lib/advisor-state.js',
52
+ 'lib/config.js',
52
53
  'lib/index.js',
53
54
  'lib/invariant.js',
54
55
  'lib/pruner.js',