dsh-context-compression-improved 0.2.3 → 0.2.5

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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -0,0 +1,153 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ normalizeTerminalLines,
4
+ normalizeTerminalText,
5
+ } from '../../src/runtime/reducers.ts'
6
+
7
+ /** R9a drift harness: `retrieve` reads the ORIGINAL event, so every line
8
+ * number a reducer prints must point back into the original event, not into
9
+ * the normalized text. The assertions below pin EXACT original line numbers —
10
+ * removing the mapping (or off-by-oneing it) fails these cases, which is the
11
+ * reverse-proof the R9a acceptance asks for. */
12
+
13
+ describe('normalizeTerminalLines', () => {
14
+ it('keeps folded lines 1:1 with the original event through ANSI + \\r redraw + adjacent dups', () => {
15
+ // Original event, 1-based:
16
+ // 1 staging files... (ANSI-decorated)
17
+ // 2 progress 10%
18
+ // 3 progress 10% (adjacent dup)
19
+ // 4 progress 10% (adjacent dup)
20
+ // 5 Downloaded 100% (\r redraw of one physical line)
21
+ // 6 done (ANSI-decorated)
22
+ const original = [
23
+ '\u001B[32mstaging files...\u001B[0m',
24
+ 'progress 10%',
25
+ 'progress 10%',
26
+ 'progress 10%',
27
+ 'Downloaded 50%\rDownloaded 100%',
28
+ '\u001B[1mdone\u001B[0m',
29
+ ].join('\n')
30
+
31
+ const { folded, text } = normalizeTerminalLines(original)
32
+
33
+ expect(folded).toEqual([
34
+ { text: 'staging files...', content: 'staging files...', originalLine: 1 },
35
+ { text: 'progress 10%', content: 'progress 10%', originalLine: 2 },
36
+ {
37
+ text: '[previous line repeated 2 more times]',
38
+ content: '[previous line repeated 2 more times]',
39
+ originalLine: 3,
40
+ originalLineEnd: 4,
41
+ },
42
+ { text: 'Downloaded 100%', content: 'Downloaded 100%', originalLine: 5 },
43
+ { text: 'done', content: 'done', originalLine: 6 },
44
+ ])
45
+ // The folded text is byte-identical with the string API.
46
+ expect(text).toBe(normalizeTerminalText(original))
47
+ expect(text).toBe([
48
+ 'staging files...',
49
+ 'progress 10%',
50
+ '[previous line repeated 2 more times]',
51
+ 'Downloaded 100%',
52
+ 'done',
53
+ ].join('\n'))
54
+ })
55
+
56
+ it('maps every kept line back to the same original line through ANSI stripping alone', () => {
57
+ const original = ['\u001B[1malpha\u001B[0m', 'beta', '\u001B[31mgamma\u001B[0m'].join('\n')
58
+ const { folded } = normalizeTerminalLines(original)
59
+ expect(folded.map(line => [line.text, line.originalLine])).toEqual([
60
+ ['alpha', 1],
61
+ ['beta', 2],
62
+ ['gamma', 3],
63
+ ])
64
+ })
65
+
66
+ it('never changes the line count before folding (logical 1:1 original)', () => {
67
+ // \r redraws and ANSI escapes consume no newlines, so even a line that
68
+ // redraws many times stays one logical line. A trailing newline keeps its
69
+ // empty logical line (byte-compatibility with the string API).
70
+ const original = 'a\rb\rc\rd\nx\n\u001B[2Ky\n'
71
+ const { folded } = normalizeTerminalLines(original)
72
+ expect(folded.map(line => line.text)).toEqual(['d', 'x', 'y', ''])
73
+ expect(folded.map(line => line.originalLine)).toEqual([1, 2, 3, 4])
74
+ })
75
+
76
+ it('pins the repeat-marker range to the occurrences it replaces', () => {
77
+ const original = ['head', 'same', 'same', 'same', 'same', 'tail'].join('\n')
78
+ const { folded } = normalizeTerminalLines(original)
79
+ expect(folded).toEqual([
80
+ { text: 'head', content: 'head', originalLine: 1 },
81
+ { text: 'same', content: 'same', originalLine: 2 },
82
+ {
83
+ text: '[previous line repeated 3 more times]',
84
+ content: '[previous line repeated 3 more times]',
85
+ originalLine: 3,
86
+ originalLineEnd: 5,
87
+ },
88
+ { text: 'tail', content: 'tail', originalLine: 6 },
89
+ ])
90
+ })
91
+
92
+ // GF-1 dual view (spec.md 「行号修复补丁 GF-1」): a block-detected read
93
+ // gutter is stripped on the CONTENT view only — the output view keeps the
94
+ // host's `N: ` prefixes byte-for-byte because they are the model's only
95
+ // inline locator into the original file, while form detection and the fold
96
+ // keys must not see them.
97
+ it('strips a detected read gutter on the content view and keeps it on the output view', () => {
98
+ const original = [
99
+ '1: export function alpha() {',
100
+ '2: return 1',
101
+ '3: }',
102
+ '4: ',
103
+ '5: export function beta() {',
104
+ '6: }',
105
+ ].join('\n')
106
+ const { folded, text, contentText } = normalizeTerminalLines(original)
107
+ // Output view: the gutter is preserved verbatim.
108
+ expect(text).toBe(original)
109
+ // Content view: the gutter is gone.
110
+ expect(contentText).toBe([
111
+ 'export function alpha() {',
112
+ ' return 1',
113
+ '}',
114
+ '',
115
+ 'export function beta() {',
116
+ '}',
117
+ ].join('\n'))
118
+ // Every folded line still maps 1:1 into the original event.
119
+ expect(folded.map(line => line.originalLine)).toEqual([1, 2, 3, 4, 5, 6])
120
+ expect(folded.map(line => line.content)).toEqual([
121
+ 'export function alpha() {',
122
+ ' return 1',
123
+ '}',
124
+ '',
125
+ 'export function beta() {',
126
+ '}',
127
+ ])
128
+ })
129
+
130
+ it('does not strip a stray time-of-day colon as a read gutter (block-level guard)', () => {
131
+ // Only 1 of 5 non-empty lines is gutter-shaped, and the "numbers" are not
132
+ // strictly increasing — the block guard must keep both views intact.
133
+ const original = ['meeting at 12:30 pm', 'standup at 9:15 am', 'retro at 4:45 pm', 'done'].join('\n')
134
+ const { text, contentText } = normalizeTerminalLines(original)
135
+ expect(text).toBe(original)
136
+ expect(contentText).toBe(original)
137
+ })
138
+ })
139
+
140
+ /** 口径对拍 (task_2.3): `splitLines` (reducers.ts) and `splitScannedLines`
141
+ * (retrieve.ts) must count lines identically — both split on '\n' and drop
142
+ * only the trailing empty element when the text ends with a newline. retrieve
143
+ * scans the raw event, reducers see normalized text; the R9a mapping above is
144
+ * what keeps the two line spaces reconcilable. The behavioral proof lives in
145
+ * the drift cases; this suite pins the reducer-side convention. */
146
+ describe('line-splitting conventions', () => {
147
+ it('reducer-side folded lines join back to the text splitLines would produce', () => {
148
+ const original = 'one\ntwo\nthree'
149
+ const { folded, text } = normalizeTerminalLines(original)
150
+ expect(text.split('\n')).toEqual(folded.map(line => line.text))
151
+ expect(folded).toHaveLength(3)
152
+ })
153
+ })
@@ -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,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
+ })