dsh-context-compression-improved 0.5.6 → 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 (183) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +323 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +163 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.d.ts +59 -0
  34. package/packages/selector/lib/client.js +1738 -10
  35. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  36. package/packages/selector/lib/index.d.ts +13 -1
  37. package/packages/selector/lib/index.js +295 -3
  38. package/packages/selector/lib/pruner.d.ts +65 -0
  39. package/packages/selector/lib/pruner.js +497 -262
  40. package/packages/selector/lib/style.css +88 -46
  41. package/packages/selector/package.json +114 -114
  42. package/packages/selector/screenshots.json +3 -3
  43. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  44. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  45. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  46. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  47. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  48. package/packages/selector/src/client/decode.ts +57 -49
  49. package/packages/selector/src/client/index.ts +240 -149
  50. package/packages/selector/src/client/locales/de.ts +141 -0
  51. package/packages/selector/src/client/locales/es.ts +141 -0
  52. package/packages/selector/src/client/locales/fr.ts +141 -0
  53. package/packages/selector/src/client/locales/it.ts +141 -0
  54. package/packages/selector/src/client/locales/ja.ts +141 -0
  55. package/packages/selector/src/client/locales/ko.ts +141 -0
  56. package/packages/selector/src/client/locales/ru.ts +141 -0
  57. package/packages/selector/src/client/locales.ts +282 -196
  58. package/packages/selector/src/client/monitor-fab.ts +336 -0
  59. package/packages/selector/src/client/preset-options.ts +88 -88
  60. package/packages/selector/src/client/savings-card.tsx +150 -0
  61. package/packages/selector/src/client/settings-section.tsx +140 -124
  62. package/packages/selector/src/css-modules.d.ts +6 -6
  63. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  64. package/packages/selector/src/estimator-catalog.ts +104 -104
  65. package/packages/selector/src/index.ts +673 -463
  66. package/packages/selector/src/invariant.ts +113 -113
  67. package/packages/selector/src/preset-overlay.ts +626 -626
  68. package/packages/selector/src/profiles.ts +431 -394
  69. package/packages/selector/src/pruner/content.ts +201 -201
  70. package/packages/selector/src/pruner/session.ts +94 -94
  71. package/packages/selector/src/pruner/state.ts +57 -50
  72. package/packages/selector/src/pruner/tuning.ts +23 -23
  73. package/packages/selector/src/pruner/types.ts +78 -78
  74. package/packages/selector/src/pruner.ts +2736 -2402
  75. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  76. package/packages/selector/src/runtime/audit.ts +303 -286
  77. package/packages/selector/src/runtime/config.ts +756 -706
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +436 -436
  82. package/packages/selector/src/runtime/monitor.ts +235 -0
  83. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  84. package/packages/selector/src/runtime/retrieve.ts +479 -457
  85. package/packages/selector/src/runtime/savings.ts +337 -0
  86. package/packages/selector/src/runtime/session-events.ts +30 -30
  87. package/packages/selector/src/runtime/summary-command.ts +127 -0
  88. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  89. package/packages/selector/src/runtime/token-count.ts +72 -72
  90. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  91. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  92. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  93. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  94. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  95. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  96. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  97. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  98. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  99. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  100. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  101. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  102. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  103. package/packages/selector/src/runtime/toolclass.ts +103 -103
  104. package/packages/selector/src/runtime/types.ts +365 -346
  105. package/packages/selector/src/runtime/value.ts +48 -48
  106. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  107. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  108. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  109. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  110. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -90
  111. package/packages/selector/tests/custom-contract.client.spec.ts +205 -204
  112. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  113. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  114. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  115. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  116. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  117. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -206
  118. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  119. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  120. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  121. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  122. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  123. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  124. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  125. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  126. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  127. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  128. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  129. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  130. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  131. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  132. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  133. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  134. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  135. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  136. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  137. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  138. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  139. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  140. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  141. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  142. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  143. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  144. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  145. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  146. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  147. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  148. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  149. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  150. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  151. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  152. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  153. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  154. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  155. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  156. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  157. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  158. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  159. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  160. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  161. package/packages/selector/tests/settings-seat.client.spec.ts +130 -118
  162. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  163. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  164. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  165. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  166. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  167. package/packages/selector/tsconfig.json +11 -11
  168. package/packages/selector/tsdown.client.config.ts +102 -102
  169. package/packages/selector/tsdown.config.ts +20 -20
  170. package/pnpm-workspace.yaml +66 -66
  171. package/scripts/capture-profile-baseline.mjs +42 -42
  172. package/scripts/generate-tokenizer-fixtures.py +81 -81
  173. package/scripts/generate-vision-fixtures.py +208 -208
  174. package/scripts/packed-components-smoke.mjs +732 -732
  175. package/scripts/packed-install-e2e.mjs +1273 -1273
  176. package/scripts/toolclass-corpus-replay.mjs +281 -281
  177. package/scripts/verify-release.mjs +318 -317
  178. package/tests/TEST_INVENTORY.md +41 -41
  179. package/tsconfig.base.json +18 -18
  180. package/tsconfig.json +7 -7
  181. package/tsconfig.tests.json +15 -15
  182. package/vitest.built.config.ts +9 -9
  183. package/vitest.config.ts +43 -43
@@ -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
+
@@ -1,133 +1,133 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { codePointLength } from '../../src/runtime/config.ts'
3
- import { reduceFreshToolResult, type ReducerInput } from '../../src/runtime/reducers.ts'
4
-
5
- function input(overrides: Partial<ReducerInput> = {}): ReducerInput {
6
- return {
7
- toolName: 'mcp_remote_fetch',
8
- argumentsText: '{}',
9
- text: '',
10
- budgetChars: 4_000,
11
- sourceRef: 'session://s/event/1',
12
- isError: false,
13
- ...overrides,
14
- }
15
- }
16
-
17
- function markdownDoc(sections: number): string {
18
- const parts: string[] = ['# User Guide', 'Intro paragraph with orientation prose.']
19
- for (let index = 1; index <= sections; index++) {
20
- parts.push(`## Section ${String(index)}: Installation`)
21
- for (let line = 0; line < 12; line++) {
22
- parts.push(`Section ${String(index)} line ${String(line)} with ordinary documentation prose content.`)
23
- }
24
- }
25
- return parts.join('\n')
26
- }
27
-
28
- describe('document skeleton (R8)', () => {
29
- it('keeps every H1-H3 heading and at least one sentence per section', () => {
30
- const output = reduceFreshToolResult(input({ text: markdownDoc(8) }))
31
- expect(output).not.toBeNull()
32
- expect(output!.reducer).toBe('doc-skeleton')
33
- for (let index = 1; index <= 8; index++) {
34
- expect(output!.text).toContain(`## Section ${String(index)}: Installation`)
35
- // 每节 ≥1 句:the section's first line survives.
36
- expect(output!.text).toContain(`Section ${String(index)} line 0`)
37
- }
38
- expect(output!.text).toContain('# User Guide')
39
- })
40
-
41
- it('keeps the first two rows of every table block', () => {
42
- const doc = [
43
- '# Report',
44
- 'Intro.',
45
- '## Usage',
46
- 'Usage intro.',
47
- '## Tables',
48
- 'Tables intro.',
49
- ...Array.from({ length: 30 }, (_, i) => `Intro filler sentence ${String(i)} to make the section elidable.`),
50
- '| Name | Quota |',
51
- '| --- | --- |',
52
- '| Free | 5k |',
53
- '| Pro | 50k |',
54
- ...Array.from({ length: 30 }, (_, i) => `Closing filler sentence ${String(i)} to make the section elidable.`),
55
- 'Trailing prose line.',
56
- ].join('\n')
57
- const output = reduceFreshToolResult(input({ text: doc, toolName: 'mcp_fetch' }))
58
- expect(output!.reducer).toBe('doc-skeleton')
59
- expect(output!.text).toContain('| Name | Quota |')
60
- expect(output!.text).toContain('| --- | --- |')
61
- })
62
-
63
- it('cites original-event line ranges in elision markers (R9 spec)', () => {
64
- const output = reduceFreshToolResult(input({ text: markdownDoc(6) }))
65
- expect(output).not.toBeNull()
66
- // Every elision marker carries an original line range and a line count.
67
- const markers = output!.text.match(/\[\.\.\. lines \d+-\d+ elided \(\d+ lines\)[^\]]*\]/g) ?? []
68
- expect(markers.length).toBeGreaterThan(0)
69
- for (const marker of markers) {
70
- const [, start, end, count] = /\[\.\.\. lines (\d+)-(\d+) elided \((\d+) lines\)/.exec(marker) ?? []
71
- expect(Number(end) - Number(start) + 1).toBe(Number(count))
72
- }
73
- })
74
-
75
- it('misjudgment guard: logs and build output are not documents', () => {
76
- // Realistic build/log output carries no Markdown heading lines at all —
77
- // timestamps, INFO frames, and stack locations never match `^#\\s`.
78
- const log = [
79
- 'INFO 2026-01-01 starting build',
80
- 'WARN 2026-01-01 deprecated flag --legacy',
81
- 'INFO compiling modules',
82
- 'ERROR TS2345: cannot find name elsewhere',
83
- ...Array.from({ length: 40 }, (_, i) => `at /pkg/src/module${String(i)}.ts:12:5`),
84
- ].join('\n')
85
- const output = reduceFreshToolResult(input({ text: log, toolName: 'bash', argumentsText: '{"command":"pnpm build"}' }))
86
- expect(output?.reducer).not.toBe('doc-skeleton')
87
- })
88
- })
89
-
90
- describe('prose head+tail keep (R8b)', () => {
91
- const prose = [
92
- ...Array.from({ length: 60 }, (_, i) => `Early paragraph ${String(i)} with orientation prose for the reader.`),
93
- ...Array.from({ length: 60 }, (_, i) => `Middle paragraph ${String(i)} carries ordinary filler content.`),
94
- ...Array.from({ length: 60 }, (_, i) => `Final paragraph ${String(i)} holds the decisive conclusion about quotas.`),
95
- ].join('\n')
96
-
97
- it('keeps head AND tail non-empty with an elision marker in between', () => {
98
- const output = reduceFreshToolResult(input({ text: prose }))
99
- expect(output).not.toBeNull()
100
- expect(output!.reducer).toBe('prose-keep')
101
- const lines = output!.text.split('\n')
102
- expect(lines[0]).toContain('Early paragraph 0')
103
- expect(lines.at(-1)).toContain('Final paragraph 59')
104
- expect(output!.text).toMatch(/\[\.\.\. lines \d+-\d+ elided \(\d+ lines\)/)
105
- // The tail keeps conclusions the old head-only reducer dropped.
106
- expect(output!.text).toContain('decisive conclusion')
107
- })
108
-
109
- it('counter-proof: head-only retention provably loses the tail keyword', () => {
110
- // The old landing spots for prose were head-only (pi-head) or a salience
111
- // pass whose middle list is empty for prose. A head-only slice of B chars
112
- // can never contain a keyword that starts after char B: the prose is
113
- // ~11k chars and the decisive sentence sits in the last third, so any
114
- // head-only output within a 4k budget drops it by construction.
115
- const keywordIndex = prose.indexOf('decisive conclusion')
116
- expect(codePointLength(prose)).toBeGreaterThan(2 * 4_000)
117
- expect(keywordIndex).toBeGreaterThan(4_000)
118
- // The R8b output keeps it anyway (also asserted above).
119
- })
120
-
121
- it('misjudgment guard: source code still stays off the prose path', () => {
122
- const code = [
123
- 'import { createHash } from \'node:crypto\'',
124
- '',
125
- ...Array.from({ length: 40 }, (_, i) => `export function handler${String(i)}(input: string): string {`),
126
- ...Array.from({ length: 40 }, (_, i) => ` return hash(input, ${String(i)})`),
127
- '}',
128
- ].join('\n')
129
- const output = reduceFreshToolResult(input({ text: code }))
130
- expect(output?.reducer).not.toBe('prose-keep')
131
- expect(output?.reducer).not.toBe('doc-skeleton')
132
- })
133
- })
1
+ import { describe, expect, it } from 'vitest'
2
+ import { codePointLength } from '../../src/runtime/config.ts'
3
+ import { reduceFreshToolResult, type ReducerInput } from '../../src/runtime/reducers.ts'
4
+
5
+ function input(overrides: Partial<ReducerInput> = {}): ReducerInput {
6
+ return {
7
+ toolName: 'mcp_remote_fetch',
8
+ argumentsText: '{}',
9
+ text: '',
10
+ budgetChars: 4_000,
11
+ sourceRef: 'session://s/event/1',
12
+ isError: false,
13
+ ...overrides,
14
+ }
15
+ }
16
+
17
+ function markdownDoc(sections: number): string {
18
+ const parts: string[] = ['# User Guide', 'Intro paragraph with orientation prose.']
19
+ for (let index = 1; index <= sections; index++) {
20
+ parts.push(`## Section ${String(index)}: Installation`)
21
+ for (let line = 0; line < 12; line++) {
22
+ parts.push(`Section ${String(index)} line ${String(line)} with ordinary documentation prose content.`)
23
+ }
24
+ }
25
+ return parts.join('\n')
26
+ }
27
+
28
+ describe('document skeleton (R8)', () => {
29
+ it('keeps every H1-H3 heading and at least one sentence per section', () => {
30
+ const output = reduceFreshToolResult(input({ text: markdownDoc(8) }))
31
+ expect(output).not.toBeNull()
32
+ expect(output!.reducer).toBe('doc-skeleton')
33
+ for (let index = 1; index <= 8; index++) {
34
+ expect(output!.text).toContain(`## Section ${String(index)}: Installation`)
35
+ // 每节 ≥1 句:the section's first line survives.
36
+ expect(output!.text).toContain(`Section ${String(index)} line 0`)
37
+ }
38
+ expect(output!.text).toContain('# User Guide')
39
+ })
40
+
41
+ it('keeps the first two rows of every table block', () => {
42
+ const doc = [
43
+ '# Report',
44
+ 'Intro.',
45
+ '## Usage',
46
+ 'Usage intro.',
47
+ '## Tables',
48
+ 'Tables intro.',
49
+ ...Array.from({ length: 30 }, (_, i) => `Intro filler sentence ${String(i)} to make the section elidable.`),
50
+ '| Name | Quota |',
51
+ '| --- | --- |',
52
+ '| Free | 5k |',
53
+ '| Pro | 50k |',
54
+ ...Array.from({ length: 30 }, (_, i) => `Closing filler sentence ${String(i)} to make the section elidable.`),
55
+ 'Trailing prose line.',
56
+ ].join('\n')
57
+ const output = reduceFreshToolResult(input({ text: doc, toolName: 'mcp_fetch' }))
58
+ expect(output!.reducer).toBe('doc-skeleton')
59
+ expect(output!.text).toContain('| Name | Quota |')
60
+ expect(output!.text).toContain('| --- | --- |')
61
+ })
62
+
63
+ it('cites original-event line ranges in elision markers (R9 spec)', () => {
64
+ const output = reduceFreshToolResult(input({ text: markdownDoc(6) }))
65
+ expect(output).not.toBeNull()
66
+ // Every elision marker carries an original line range and a line count.
67
+ const markers = output!.text.match(/\[\.\.\. lines \d+-\d+ elided \(\d+ lines\)[^\]]*\]/g) ?? []
68
+ expect(markers.length).toBeGreaterThan(0)
69
+ for (const marker of markers) {
70
+ const [, start, end, count] = /\[\.\.\. lines (\d+)-(\d+) elided \((\d+) lines\)/.exec(marker) ?? []
71
+ expect(Number(end) - Number(start) + 1).toBe(Number(count))
72
+ }
73
+ })
74
+
75
+ it('misjudgment guard: logs and build output are not documents', () => {
76
+ // Realistic build/log output carries no Markdown heading lines at all —
77
+ // timestamps, INFO frames, and stack locations never match `^#\\s`.
78
+ const log = [
79
+ 'INFO 2026-01-01 starting build',
80
+ 'WARN 2026-01-01 deprecated flag --legacy',
81
+ 'INFO compiling modules',
82
+ 'ERROR TS2345: cannot find name elsewhere',
83
+ ...Array.from({ length: 40 }, (_, i) => `at /pkg/src/module${String(i)}.ts:12:5`),
84
+ ].join('\n')
85
+ const output = reduceFreshToolResult(input({ text: log, toolName: 'bash', argumentsText: '{"command":"pnpm build"}' }))
86
+ expect(output?.reducer).not.toBe('doc-skeleton')
87
+ })
88
+ })
89
+
90
+ describe('prose head+tail keep (R8b)', () => {
91
+ const prose = [
92
+ ...Array.from({ length: 60 }, (_, i) => `Early paragraph ${String(i)} with orientation prose for the reader.`),
93
+ ...Array.from({ length: 60 }, (_, i) => `Middle paragraph ${String(i)} carries ordinary filler content.`),
94
+ ...Array.from({ length: 60 }, (_, i) => `Final paragraph ${String(i)} holds the decisive conclusion about quotas.`),
95
+ ].join('\n')
96
+
97
+ it('keeps head AND tail non-empty with an elision marker in between', () => {
98
+ const output = reduceFreshToolResult(input({ text: prose }))
99
+ expect(output).not.toBeNull()
100
+ expect(output!.reducer).toBe('prose-keep')
101
+ const lines = output!.text.split('\n')
102
+ expect(lines[0]).toContain('Early paragraph 0')
103
+ expect(lines.at(-1)).toContain('Final paragraph 59')
104
+ expect(output!.text).toMatch(/\[\.\.\. lines \d+-\d+ elided \(\d+ lines\)/)
105
+ // The tail keeps conclusions the old head-only reducer dropped.
106
+ expect(output!.text).toContain('decisive conclusion')
107
+ })
108
+
109
+ it('counter-proof: head-only retention provably loses the tail keyword', () => {
110
+ // The old landing spots for prose were head-only (pi-head) or a salience
111
+ // pass whose middle list is empty for prose. A head-only slice of B chars
112
+ // can never contain a keyword that starts after char B: the prose is
113
+ // ~11k chars and the decisive sentence sits in the last third, so any
114
+ // head-only output within a 4k budget drops it by construction.
115
+ const keywordIndex = prose.indexOf('decisive conclusion')
116
+ expect(codePointLength(prose)).toBeGreaterThan(2 * 4_000)
117
+ expect(keywordIndex).toBeGreaterThan(4_000)
118
+ // The R8b output keeps it anyway (also asserted above).
119
+ })
120
+
121
+ it('misjudgment guard: source code still stays off the prose path', () => {
122
+ const code = [
123
+ 'import { createHash } from \'node:crypto\'',
124
+ '',
125
+ ...Array.from({ length: 40 }, (_, i) => `export function handler${String(i)}(input: string): string {`),
126
+ ...Array.from({ length: 40 }, (_, i) => ` return hash(input, ${String(i)})`),
127
+ '}',
128
+ ].join('\n')
129
+ const output = reduceFreshToolResult(input({ text: code }))
130
+ expect(output?.reducer).not.toBe('prose-keep')
131
+ expect(output?.reducer).not.toBe('doc-skeleton')
132
+ })
133
+ })