dsh-context-compression-improved 0.9.8 → 0.9.9-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +15 -98
  2. package/README.zh.md +14 -92
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +1 -1
  5. package/{packages/selector/lib → lib}/client.d.ts +16 -0
  6. package/{packages/selector/lib → lib}/client.js +393 -116
  7. package/{packages/selector/lib → lib}/index.js +829 -10
  8. package/{packages/selector/lib → lib}/invariant.js +2 -1
  9. package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
  10. package/{packages/selector/lib → lib}/pruner.js +77 -983
  11. package/lib/savings-integral.js +4515 -0
  12. package/{packages/selector/lib → lib}/tail-trim.js +2 -90
  13. package/lib/tool-result.js +150 -0
  14. package/package.json +125 -112
  15. package/screenshots.json +3 -6
  16. package/.gitattributes +0 -2
  17. package/.githooks/pre-push +0 -37
  18. package/.github/workflows/ci.yml +0 -39
  19. package/CHANGELOG.de.md +0 -580
  20. package/CHANGELOG.es.md +0 -588
  21. package/CHANGELOG.fr.md +0 -576
  22. package/CHANGELOG.it.md +0 -577
  23. package/CHANGELOG.ja.md +0 -261
  24. package/CHANGELOG.ko.md +0 -254
  25. package/CHANGELOG.md +0 -536
  26. package/CHANGELOG.ru.md +0 -554
  27. package/CHANGELOG.zh.md +0 -236
  28. package/CONTRIBUTING.md +0 -22
  29. package/README.de.md +0 -96
  30. package/README.es.md +0 -96
  31. package/README.fr.md +0 -96
  32. package/README.it.md +0 -96
  33. package/README.ja.md +0 -102
  34. package/README.ko.md +0 -102
  35. package/README.ru.md +0 -96
  36. package/SECURITY.md +0 -18
  37. package/assets/board.png +0 -0
  38. package/assets/context.png +0 -0
  39. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  40. package/docs/assets/context-compression-selector-settings.png +0 -0
  41. package/docs/compat-0.1.5-report.md +0 -77
  42. package/docs/installation.de.md +0 -104
  43. package/docs/installation.es.md +0 -104
  44. package/docs/installation.fr.md +0 -104
  45. package/docs/installation.it.md +0 -104
  46. package/docs/installation.ja.md +0 -78
  47. package/docs/installation.ko.md +0 -78
  48. package/docs/installation.md +0 -103
  49. package/docs/installation.ru.md +0 -104
  50. package/docs/installation.zh.md +0 -100
  51. package/docs/repair-log.md +0 -657
  52. package/eslint.config.js +0 -30
  53. package/packages/selector/LICENSE +0 -21
  54. package/packages/selector/README.md +0 -26
  55. package/packages/selector/README.zh.md +0 -24
  56. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  57. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  58. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  59. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  60. package/packages/selector/lib/config.js +0 -1777
  61. package/packages/selector/lib/host-generation.js +0 -62
  62. package/packages/selector/lib/style.css +0 -350
  63. package/packages/selector/package.json +0 -174
  64. package/packages/selector/screenshots.json +0 -3
  65. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  66. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  67. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  68. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  69. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  70. package/packages/selector/src/client/bridge-scope.ts +0 -125
  71. package/packages/selector/src/client/decode.ts +0 -57
  72. package/packages/selector/src/client/index.ts +0 -421
  73. package/packages/selector/src/client/locales/de.ts +0 -142
  74. package/packages/selector/src/client/locales/es.ts +0 -142
  75. package/packages/selector/src/client/locales/fr.ts +0 -142
  76. package/packages/selector/src/client/locales/it.ts +0 -142
  77. package/packages/selector/src/client/locales/ja.ts +0 -142
  78. package/packages/selector/src/client/locales/ko.ts +0 -142
  79. package/packages/selector/src/client/locales/ru.ts +0 -142
  80. package/packages/selector/src/client/locales.ts +0 -284
  81. package/packages/selector/src/client/monitor-fab.ts +0 -349
  82. package/packages/selector/src/client/preset-options.ts +0 -88
  83. package/packages/selector/src/client/savings-card.tsx +0 -150
  84. package/packages/selector/src/client/scope-face.ts +0 -24
  85. package/packages/selector/src/client/settings-section.tsx +0 -140
  86. package/packages/selector/src/compat/host-generation.ts +0 -96
  87. package/packages/selector/src/compat/llm-messages.ts +0 -50
  88. package/packages/selector/src/compat/settings-lease.ts +0 -108
  89. package/packages/selector/src/compat/tool-result.ts +0 -91
  90. package/packages/selector/src/css-modules.d.ts +0 -6
  91. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  92. package/packages/selector/src/estimator-catalog.ts +0 -104
  93. package/packages/selector/src/index.ts +0 -655
  94. package/packages/selector/src/invariant.ts +0 -113
  95. package/packages/selector/src/preset-overlay.ts +0 -749
  96. package/packages/selector/src/profiles.ts +0 -431
  97. package/packages/selector/src/pruner/content.ts +0 -198
  98. package/packages/selector/src/pruner/session.ts +0 -97
  99. package/packages/selector/src/pruner/state.ts +0 -61
  100. package/packages/selector/src/pruner/tuning.ts +0 -23
  101. package/packages/selector/src/pruner/types.ts +0 -78
  102. package/packages/selector/src/pruner.ts +0 -2868
  103. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  104. package/packages/selector/src/runtime/audit.ts +0 -303
  105. package/packages/selector/src/runtime/config.ts +0 -756
  106. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  107. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  108. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  109. package/packages/selector/src/runtime/measurement.ts +0 -444
  110. package/packages/selector/src/runtime/monitor.ts +0 -235
  111. package/packages/selector/src/runtime/reducers.ts +0 -1754
  112. package/packages/selector/src/runtime/retrieve.ts +0 -484
  113. package/packages/selector/src/runtime/savings-projection.ts +0 -226
  114. package/packages/selector/src/runtime/savings.ts +0 -417
  115. package/packages/selector/src/runtime/session-events.ts +0 -30
  116. package/packages/selector/src/runtime/summary-command.ts +0 -127
  117. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  118. package/packages/selector/src/runtime/token-count.ts +0 -72
  119. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  120. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  121. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  122. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  123. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  124. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  125. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  126. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  127. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  128. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  129. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  130. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  131. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  132. package/packages/selector/src/runtime/toolclass.ts +0 -103
  133. package/packages/selector/src/runtime/types.ts +0 -365
  134. package/packages/selector/src/runtime/value.ts +0 -48
  135. package/packages/selector/src/settings-bridge.ts +0 -175
  136. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  137. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  138. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  139. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  140. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  141. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  142. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  143. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  144. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  145. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
  146. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  147. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  148. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  149. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  150. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  152. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  153. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
  154. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  155. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  156. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  157. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  158. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  159. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  160. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  161. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  162. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  163. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  164. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  165. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  166. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  167. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  168. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  169. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  170. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  171. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  172. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  173. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  174. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  175. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  176. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  177. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  178. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  179. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  180. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  181. package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
  182. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  183. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
  184. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  185. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  186. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  187. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  188. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  189. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  190. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  191. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  192. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  193. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  194. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  195. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  196. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  197. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  198. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  199. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  200. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  201. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  202. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  203. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  204. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  205. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  206. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  207. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  208. package/packages/selector/tsconfig.json +0 -11
  209. package/packages/selector/tsdown.client.config.ts +0 -102
  210. package/packages/selector/tsdown.config.ts +0 -20
  211. package/pnpm-workspace.yaml +0 -72
  212. package/scripts/capture-profile-baseline.mjs +0 -42
  213. package/scripts/cell-browser-e2e.mjs +0 -354
  214. package/scripts/generate-tokenizer-fixtures.py +0 -81
  215. package/scripts/generate-vision-fixtures.py +0 -208
  216. package/scripts/hosts.mjs +0 -78
  217. package/scripts/packed-components-smoke.mjs +0 -763
  218. package/scripts/packed-install-e2e.mjs +0 -1346
  219. package/scripts/sync-hosts.mjs +0 -174
  220. package/scripts/toolclass-corpus-replay.mjs +0 -281
  221. package/scripts/verify-release.mjs +0 -335
  222. package/tests/TEST_INVENTORY.md +0 -41
  223. package/tsconfig.base.json +0 -18
  224. package/tsconfig.json +0 -7
  225. package/tsconfig.tests.json +0 -15
  226. package/vitest.built.config.ts +0 -9
  227. package/vitest.config.ts +0 -46
  228. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  229. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  230. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  231. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  232. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  233. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  234. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  235. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  236. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  237. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  238. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  239. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
@@ -1,167 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import {
3
- decideConservativeAdaptive,
4
- deriveAdaptiveTokenBounds,
5
- } from '../../src/runtime/adaptive-cost.ts'
6
- import type {
7
- ExactTokenizerTokenCount,
8
- TokenizerEstimateTokenCount,
9
- } from '../../src/runtime/token-count.ts'
10
-
11
- const exact = (
12
- tokens: number,
13
- tokenizerRevision = 'DeepSeek-V4-Pro-0813',
14
- ): ExactTokenizerTokenCount => ({
15
- kind: 'exact-tokenizer',
16
- tokens,
17
- tokenizerId: 'deepseek-v4-official',
18
- tokenizerRevision,
19
- })
20
-
21
- const estimate = (
22
- input: Omit<TokenizerEstimateTokenCount, 'kind'>,
23
- ): TokenizerEstimateTokenCount => ({ kind: 'tokenizer-estimate', ...input })
24
-
25
- describe('Conservative Adaptive interval', () => {
26
- it('subtracts removed tokens from the affected retained suffix instead of charging them twice', () => {
27
- expect(deriveAdaptiveTokenBounds({
28
- exactReclaimedTokens: 20_000,
29
- earliestChangedSeq: 2,
30
- previousPromptTokens: 30_500,
31
- expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
32
- previousRequestMeasurement: exact(30_500),
33
- measuredNodes: [
34
- { seq: 0, count: exact(10_000), characterPressure: 40_000 },
35
- { seq: 2, count: exact(20_000), characterPressure: 80_000 },
36
- { seq: 3, count: exact(500), characterPressure: 2_000 },
37
- ],
38
- })).toEqual({
39
- kind: 'available',
40
- measurementKind: 'exact-tokenizer',
41
- reclaimedLowerBoundTokens: 20_000,
42
- affectedRetainedSuffixUpperBoundTokens: 500,
43
- exactPrefixLowerBoundTokens: 10_000,
44
- })
45
- })
46
-
47
- it('subtracts the tokenizer-estimate conservative margin from reclaimed benefit', () => {
48
- expect(deriveAdaptiveTokenBounds({
49
- exactReclaimedTokens: 20_000,
50
- earliestChangedSeq: 2,
51
- previousPromptTokens: 30_500,
52
- expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
53
- previousRequestMeasurement: estimate({
54
- tokens: 30_300,
55
- upperBoundTokens: 30_500,
56
- estimatorId: 'deepseek-wire',
57
- estimatorRevision: 'r1',
58
- calibration: { sampleCount: 1, conservativeMarginTokens: 200 },
59
- }),
60
- measuredNodes: [{ seq: 0, count: exact(10_000), characterPressure: 40_000 }],
61
- })).toMatchObject({
62
- kind: 'available',
63
- measurementKind: 'tokenizer-estimate',
64
- reclaimedLowerBoundTokens: 19_800,
65
- affectedRetainedSuffixUpperBoundTokens: 700,
66
- })
67
- })
68
-
69
- it.each([
70
- [{ kind: 'unavailable', reason: 'no request tokenizer' } as const, 'request-measurement-unavailable'],
71
- [estimate({
72
- tokens: 10, upperBoundTokens: 20,
73
- estimatorId: 'e', estimatorRevision: 'r',
74
- }), 'estimate-calibration-unavailable'],
75
- ] as const)('fails closed when D/S cannot be bounded: %s', (measurement, reason) => {
76
- expect(deriveAdaptiveTokenBounds({
77
- exactReclaimedTokens: 100,
78
- earliestChangedSeq: 2,
79
- previousPromptTokens: 200,
80
- expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
81
- previousRequestMeasurement: measurement,
82
- measuredNodes: [{ seq: 0, count: exact(50), characterPressure: 200 }],
83
- })).toEqual({ kind: 'unknown', reason })
84
- })
85
-
86
- it('fails closed when the exact request count does not match the provider key tokenizer revision', () => {
87
- expect(deriveAdaptiveTokenBounds({
88
- exactReclaimedTokens: 100,
89
- earliestChangedSeq: 2,
90
- previousPromptTokens: 200,
91
- expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
92
- previousRequestMeasurement: exact(200, 'DeepSeek-V4-Flash-0731'),
93
- measuredNodes: [{ seq: 0, count: exact(50), characterPressure: 200 }],
94
- })).toEqual({ kind: 'unknown', reason: 'request-tokenizer-revision-mismatch' })
95
- })
96
-
97
- it('fails closed before subtracting an exact prefix from another tokenizer revision', () => {
98
- expect(deriveAdaptiveTokenBounds({
99
- exactReclaimedTokens: 100,
100
- earliestChangedSeq: 2,
101
- previousPromptTokens: 200,
102
- expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
103
- previousRequestMeasurement: exact(200),
104
- measuredNodes: [{ seq: 0, count: exact(50, 'DeepSeek-V4-Flash-0731'), characterPressure: 200 }],
105
- })).toEqual({ kind: 'unknown', reason: 'exact-prefix-tokenizer-revision-mismatch' })
106
- })
107
-
108
- it('allows routine History only when minimum removal value beats maximum cache-loss penalty', () => {
109
- expect(decideConservativeAdaptive({
110
- capacityPressure: false,
111
- bounds: {
112
- kind: 'available', measurementKind: 'exact-tokenizer',
113
- reclaimedLowerBoundTokens: 20_000,
114
- affectedRetainedSuffixUpperBoundTokens: 500,
115
- exactPrefixLowerBoundTokens: 10_000,
116
- },
117
- inputCacheHitRate: '0.014',
118
- inputCacheMissRate: '0.44',
119
- })).toMatchObject({
120
- allowHistory: true,
121
- reason: 'cost-interval-clearly-favourable',
122
- })
123
- })
124
-
125
- it.each([
126
- [19_000, 1_000, 'cache-risk-not-clearly-paid-back'],
127
- [20_000, 500, 'adaptive-unknown-price'],
128
- ] as const)('fails closed for overlap or unknown price', (reclaimed, suffix, expected) => {
129
- expect(decideConservativeAdaptive({
130
- capacityPressure: false,
131
- bounds: {
132
- kind: 'available', measurementKind: 'exact-tokenizer',
133
- reclaimedLowerBoundTokens: reclaimed,
134
- affectedRetainedSuffixUpperBoundTokens: suffix,
135
- exactPrefixLowerBoundTokens: 0,
136
- },
137
- ...(expected === 'adaptive-unknown-price'
138
- ? {}
139
- : { inputCacheHitRate: '0.014', inputCacheMissRate: '0.44' }),
140
- })).toMatchObject({ allowHistory: false, reason: expected })
141
- })
142
-
143
- it('lets capacity safety override missing price and telemetry', () => {
144
- expect(decideConservativeAdaptive({
145
- capacityPressure: true,
146
- bounds: { kind: 'unknown', reason: 'usage-unavailable' },
147
- })).toEqual({ allowHistory: true, reason: 'capacity-override' })
148
- })
149
-
150
- it('uses request-level cache hits only as a conservative exposure cap', () => {
151
- expect(decideConservativeAdaptive({
152
- capacityPressure: false,
153
- bounds: {
154
- kind: 'available', measurementKind: 'exact-tokenizer',
155
- reclaimedLowerBoundTokens: 20_000,
156
- affectedRetainedSuffixUpperBoundTokens: 10_000,
157
- exactPrefixLowerBoundTokens: 0,
158
- },
159
- observedCacheReadTokens: 100,
160
- inputCacheHitRate: '0.014',
161
- inputCacheMissRate: '0.44',
162
- })).toMatchObject({
163
- allowHistory: true,
164
- maximumCacheLossPenalty: '42600000000',
165
- })
166
- })
167
- })
@@ -1,230 +0,0 @@
1
- /**
2
- * The retired review gate's replacement, pinned at the host integration level.
3
- *
4
- * This spec exists to make the OLD failure impossible to reintroduce: with the
5
- * exact settings that used to divert 100% of a fresh batch into the human-gated
6
- * review queue (`reviewMode: true` + a `reviewHighImpactTokens` threshold far
7
- * below the batch), the batch must LAND, and the benefit model must publish its
8
- * opinion as a `reduction-advice` audit instead of withholding anything.
9
- *
10
- * "缩减不阻断自动处理": advice describes a landing, it never gates one.
11
- */
12
- import { describe, expect, it, vi } from 'vitest'
13
- import { Context } from '@deepseek-ai/cordis'
14
- import {
15
- ToolCallId as CallId,
16
- createMessage,
17
- createUserMessage,
18
- createToolResultMessage,
19
- } from '@deepseek-ai/dsh-llm'
20
- import SessionStore, {
21
- Session,
22
- SessionId,
23
- canonicalHeader,
24
- } from '@deepseek-ai/dsh-session'
25
- import { type SettingsNamespace } from '@deepseek-ai/dsh-settings'
26
- import { LegacySettingsProvider } from '../helpers/legacy-settings/index.ts'
27
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
28
- import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
29
- import TokenMeter from '@deepseek-ai/dsh-token-meter'
30
- import ToolRuntime from '@deepseek-ai/dsh-tools'
31
- import { LegacyNamespaceRegistrar } from '../helpers/legacy-namespace.ts'
32
- import ToolResultPruner, {
33
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
34
- } from '../../src/pruner.ts'
35
- import { measureForCompaction } from '../../src/runtime/measurement.ts'
36
- import {
37
- COMPRESSION_AUDIT_PREFIX,
38
- type CompressionAuditRecord,
39
- type CompressionRewriteAuditRecord,
40
- type ReductionAdviceAuditRecord,
41
- } from '../../src/runtime/audit.ts'
42
-
43
- const MODEL = 'deepseek-v4-flash'
44
-
45
- class TestSettings extends LegacySettingsProvider {
46
- readonly writable = true
47
- private readonly stored: Record<string, unknown> = {}
48
-
49
- protected override load(): Promise<Record<string, unknown>> {
50
- return Promise.resolve(structuredClone(this.stored))
51
- }
52
-
53
- protected override persist(namespace: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
54
- this.stored[namespace] = structuredClone(section)
55
- return Promise.resolve()
56
- }
57
- }
58
-
59
- async function runtimeContext(): Promise<Context> {
60
- const ctx = new Context()
61
- await ctx.plugin(SessionStore).await()
62
- await ctx.plugin(SystemPrompt).await()
63
- await ctx.plugin(ToolRuntime).await()
64
- await ctx.plugin(SessionProjectionRegistry).await()
65
- await ctx.plugin(TokenMeter).await()
66
- return ctx
67
- }
68
-
69
- function captureAudit(ctx: Context): { records(): CompressionAuditRecord[] } {
70
- const info = vi.spyOn(ctx.logger, 'info').mockImplementation(() => ctx.logger)
71
- return {
72
- records: () => info.mock.calls.flatMap((call) => {
73
- const line = String(call[0])
74
- return line.startsWith(COMPRESSION_AUDIT_PREFIX)
75
- ? [JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord]
76
- : []
77
- }),
78
- }
79
- }
80
-
81
- function rewrites(records: readonly CompressionAuditRecord[]): CompressionRewriteAuditRecord[] {
82
- return records.filter((record): record is CompressionRewriteAuditRecord => record.kind === 'rewrite')
83
- }
84
-
85
- function adviceOf(records: readonly CompressionAuditRecord[]): ReductionAdviceAuditRecord[] {
86
- return records.filter((record): record is ReductionAdviceAuditRecord => record.kind === 'reduction-advice')
87
- }
88
-
89
- const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
90
-
91
- function appendToolTurn(session: Session, turn: number, text: string): void {
92
- const callId = CallId(`call-${String(turn)}`)
93
- session.append('turn/start', { turn })
94
- if (session.requestHeader() === undefined) {
95
- session.append('request/header', {
96
- reason: 'initial',
97
- header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
98
- })
99
- }
100
- session.append('user/message', createUserMessage({
101
- content: [{ type: 'text', text: `user turn ${String(turn)}` }],
102
- source: { kind: 'user' },
103
- }), { surfaceOp: 'append' })
104
- session.append('step/start', { turn, step: 1 })
105
- session.append('assistant/message', {
106
- stream: [],
107
- turn,
108
- step: 1,
109
- message: createMessage({
110
- role: 'assistant',
111
- content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
112
- source: { kind: 'model', provider: 'deepseek', model: MODEL },
113
- }),
114
- }, { surfaceOp: 'append' })
115
- session.append('tool/call', { turn, step: 1, callId, name: 'bash', arguments: '{}' })
116
- session.append('tool/result', {
117
- turn,
118
- step: 1,
119
- message: createToolResultMessage({
120
- callId,
121
- content: [{ type: 'text', text }],
122
- isError: false,
123
- }),
124
- }, { surfaceOp: 'append' })
125
- session.append('step/end', { turn, step: 1 })
126
- }
127
-
128
- /**
129
- * The settings that used to withhold everything: review mode ON with a
130
- * high-impact threshold of 1 token. History pricing is kept production-like
131
- * (64,000 protected tail tokens) so the batch is only landable through the
132
- * fresh stage.
133
- */
134
- async function gatedSettings(ctx: Context): Promise<void> {
135
- await ctx.plugin(TestSettings).await()
136
- await ctx.plugin(LegacyNamespaceRegistrar).await()
137
- await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
138
- profile: 'tokenpilot-inspired',
139
- presetOptions: { reviewMode: true, reviewHighImpactTokens: 1 },
140
- })
141
- await ctx.plugin(ToolResultPruner, {
142
- profile: 'tokenpilot-inspired',
143
- freshTriggerTokens: 200,
144
- freshTargetTokens: 100,
145
- aggregateTriggerTokens: 1_000_000,
146
- aggregateTargetTokens: 900_000,
147
- historyTriggerTokens: 400,
148
- historyKeepRecentToolCalls: 0,
149
- historyKeepRecentTokens: 64_000,
150
- historyMinReclaimTokens: 1,
151
- }).await()
152
- }
153
-
154
- function freshSession(ctx: Context, id: string, text: string): Session {
155
- const session = Session.create(SessionId(id))
156
- appendToolTurn(session, 1, text)
157
- const total = measureForCompaction(ctx, session).totalTokens
158
- session.append('request/context', {
159
- provider: 'deepseek',
160
- model: MODEL,
161
- contextWindow: Math.floor(total / 0.6),
162
- })
163
- // Fresh landing publishes a surface replacement, which requires an open turn.
164
- session.append('turn/start', { turn: 2 })
165
- return session
166
- }
167
-
168
- /** ~36,400 characters. The shipped advice threshold is 4,000 tokens, and this
169
- * fixture is repetitive enough that the exact tokenizer packs it denser than
170
- * the conservative 4-chars-per-token estimate (an 18,200-character variant
171
- * measured under 4,000 tokens), so the volume is doubled to keep the
172
- * `high-impact` label deterministic. */
173
- const HIGH_IMPACT_TEXT = 'fresh reviewable evidence '.repeat(1_400)
174
-
175
- describe('advice never withholds (retired review gate)', () => {
176
- it('lands the fresh batch the gate used to divert, and advises instead', async () => {
177
- const ctx = await runtimeContext()
178
- await gatedSettings(ctx)
179
- const audit = captureAudit(ctx)
180
- const session = freshSession(ctx, 'advice-lands', HIGH_IMPACT_TEXT)
181
-
182
- const result = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
183
- const records = audit.records()
184
-
185
- // 1. The reduction LANDED. Under the retired gate this was the assertion
186
- // that failed: the batch was withheld pending human approval.
187
- expect(result.pruned).toHaveLength(1)
188
- expect(rewrites(records).some(entry => entry.component === 'fresh')).toBe(true)
189
-
190
- // 2. The benefit model still speaks — as advice about the landing.
191
- const advice = adviceOf(records)
192
- expect(advice).toHaveLength(1)
193
- expect(advice[0]!.stage).toBe('fresh')
194
- expect(advice[0]!.band).toBe('high-impact')
195
- expect(advice[0]!.maxTokensBefore).toBeGreaterThanOrEqual(4_000)
196
- expect(advice[0]!.recoveredTokens).toBeGreaterThan(0)
197
- // The batch it describes is exactly the batch that landed.
198
- const landedSeqs = rewrites(records).flatMap(entry => [...entry.sourceSeqs])
199
- expect(advice[0]!.itemSeqs.every(seq => landedSeqs.includes(seq))).toBe(true)
200
-
201
- // 3. Every advice record describes a landing, never a pending decision.
202
- expect(advice.length).toBeLessThanOrEqual(rewrites(records).length)
203
- })
204
-
205
- it('keeps the automatic path identical when no legacy gate key is present', async () => {
206
- const ctx = await runtimeContext()
207
- await ctx.plugin(TestSettings).await()
208
- await ctx.plugin(LegacyNamespaceRegistrar).await()
209
- await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
210
- profile: 'tokenpilot-inspired',
211
- })
212
- await ctx.plugin(ToolResultPruner, {
213
- profile: 'tokenpilot-inspired',
214
- freshTriggerTokens: 200,
215
- freshTargetTokens: 100,
216
- aggregateTriggerTokens: 1_000_000,
217
- aggregateTargetTokens: 900_000,
218
- historyTriggerTokens: 400,
219
- historyKeepRecentToolCalls: 0,
220
- historyKeepRecentTokens: 64_000,
221
- historyMinReclaimTokens: 1,
222
- }).await()
223
- const audit = captureAudit(ctx)
224
- const session = freshSession(ctx, 'advice-default', HIGH_IMPACT_TEXT)
225
-
226
- const result = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
227
- expect(result.pruned).toHaveLength(1)
228
- expect(adviceOf(audit.records())).toHaveLength(1)
229
- })
230
- })
@@ -1,272 +0,0 @@
1
- /**
2
- * Advisor integration and the advisory-only invariant.
3
- *
4
- * The invariant this spec exists to pin (K13): the advisor is statistics and
5
- * suggestions only. Whatever its channel returns — extreme scores, a hostile
6
- * summary, garbage, or nothing at all — `pruneSession` must land exactly the
7
- * same reductions it lands with the advisor off and the state empty.
8
- */
9
- import { describe, expect, it } from 'vitest'
10
- import { Context } from '@deepseek-ai/cordis'
11
- import {
12
- ToolCallId as CallId,
13
- createMessage,
14
- createUserMessage,
15
- createToolResultMessage,
16
- } from '@deepseek-ai/dsh-llm'
17
- import { canonicalHeader, Session, SessionId } from '@deepseek-ai/dsh-session'
18
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
19
- import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
20
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
21
- import TokenMeter from '@deepseek-ai/dsh-token-meter'
22
- import ToolRuntime from '@deepseek-ai/dsh-tools'
23
- import SessionStore from '@deepseek-ai/dsh-session'
24
- import ToolResultPruner from '../../src/pruner.ts'
25
- import {
26
- collectTaskSemantics,
27
- runSessionAdvisorPass,
28
- type AdvisorCandidate,
29
- } from '../../src/runtime/tokenpilot/advisor.ts'
30
- import { getAdvisorState, recordScore } from '../../src/runtime/tokenpilot/advisor-state.ts'
31
- import type { AdvisorOutcomeAuditRecord } from '../../src/runtime/audit.ts'
32
- import type { AdvisorChannel } from '../../src/runtime/tokenpilot/advisor.ts'
33
-
34
- // ── Orchestration against a scripted channel ───────────────────────────────
35
-
36
- const CANDIDATES: AdvisorCandidate[] = [
37
- { seq: 3, characterPressure: 4_000, preview: 'auth module login flow' },
38
- { seq: 5, characterPressure: 6_000, preview: 'database migration notes' },
39
- ]
40
-
41
- const TASK = {
42
- source: 'todos' as const,
43
- todoVersion: 'aaaa1111',
44
- taskText: 'migrate the auth module',
45
- }
46
-
47
- function advisorInput(turn: number, signal: AbortSignal): Parameters<typeof runSessionAdvisorPass>[3] {
48
- return {
49
- profile: 'tokenpilot-inspired',
50
- turn,
51
- candidates: CANDIDATES,
52
- task: TASK,
53
- advisor: { refreshTurns: 8, scoreThreshold: 0.35, sampleLimit: 16, minTokens: 250 },
54
- tailText: 'working on the migration',
55
- signal,
56
- }
57
- }
58
-
59
- function scriptedChannel(responses: (string | undefined)[]): { channel: AdvisorChannel, calls: { system: string, user: string }[] } {
60
- const calls: { system: string, user: string }[] = []
61
- return {
62
- calls,
63
- channel: {
64
- identity: () => 'host:mock/model',
65
- ask: async request => {
66
- calls.push({ system: request.system, user: request.user })
67
- return responses.shift()
68
- },
69
- },
70
- }
71
- }
72
-
73
- describe('runSessionAdvisorPass orchestration (K11)', () => {
74
- it('writes summary, scores, recertification marks, and emits three audits on success', async () => {
75
- const session = Session.create(SessionId('advisor-ok'))
76
- const { channel, calls } = scriptedChannel([
77
- '{"overallTask":"migrate the auth module","activeSubtasks":["port login flow"],"keywords":["auth","login"]}',
78
- '{"seq":3,"score":0.95,"reason":"current task"}\n{"seq":5,"score":0.10,"reason":"stale"}',
79
- ])
80
- const audits: AdvisorOutcomeAuditRecord[] = []
81
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(4, new AbortController().signal))
82
-
83
- expect(calls).toHaveLength(2)
84
- expect(outcome).toBeDefined()
85
- const state = getAdvisorState(session)
86
- expect(state.summary?.overallTask).toBe('migrate the auth module')
87
- expect(state.scores.get(3)?.score).toBe(0.95)
88
- expect(state.scores.get(5)?.score).toBe(0.10)
89
- // Below-threshold segment recertified as a suggestion only.
90
- expect(state.recertified.get(5)).toBe(4)
91
- expect(state.recertified.has(3)).toBe(false)
92
- expect(state.watermarkSeq).toBe(5)
93
- expect(audits.map(record => record.phase)).toEqual(['summary', 'scoring', 'decay'])
94
- expect(audits.every(record => record.ok)).toBe(true)
95
- expect(audits.find(record => record.phase === 'decay')?.decay).toBeDefined()
96
- })
97
-
98
- it('leaves state untouched and audits ok:false when the channel answers nothing', async () => {
99
- const session = Session.create(SessionId('advisor-fail'))
100
- const { channel, calls } = scriptedChannel([undefined, undefined])
101
- const audits: AdvisorOutcomeAuditRecord[] = []
102
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
103
-
104
- expect(outcome).toBeUndefined()
105
- expect(calls).toHaveLength(1) // summary failed; scoring never ran
106
- const state = getAdvisorState(session)
107
- expect(state.summary).toBeUndefined()
108
- expect(state.scores.size).toBe(0)
109
- expect(audits).toHaveLength(1)
110
- expect(audits[0]?.ok).toBe(false)
111
- expect(audits[0]?.reason).toBe('channel-empty')
112
- expect(state.inFlight).toBe(false)
113
- })
114
-
115
- it('skips entirely while a pass is in flight (re-entry guard)', async () => {
116
- const session = Session.create(SessionId('advisor-reentry'))
117
- const { channel, calls } = scriptedChannel([])
118
- const state = getAdvisorState(session)
119
- state.inFlight = true
120
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, advisorInput(1, new AbortController().signal))
121
- expect(outcome).toBeUndefined()
122
- expect(calls).toHaveLength(0)
123
- state.inFlight = false
124
- })
125
-
126
- it('does not advance the watermark on failure, so candidates rescore later', async () => {
127
- const session = Session.create(SessionId('advisor-watermark'))
128
- const failing = scriptedChannel([undefined])
129
- await runSessionAdvisorPass(session, failing.channel, () => undefined, advisorInput(1, new AbortController().signal))
130
- expect(getAdvisorState(session).watermarkSeq).toBe(0)
131
-
132
- const succeeding = scriptedChannel([
133
- '{"overallTask":"t","activeSubtasks":[],"keywords":["auth"]}',
134
- '{"seq":3,"score":0.9}',
135
- ])
136
- const audits: AdvisorOutcomeAuditRecord[] = []
137
- const outcome = await runSessionAdvisorPass(session, succeeding.channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
138
- expect(outcome).toBeDefined()
139
- expect(getAdvisorState(session).watermarkSeq).toBe(3)
140
- })
141
-
142
- it('returns undefined without any channel call when the session has no task semantics', async () => {
143
- const session = Session.create(SessionId('advisor-notask'))
144
- const { channel, calls } = scriptedChannel(['{"overallTask":"x","keywords":["k"]}'])
145
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, {
146
- ...advisorInput(1, new AbortController().signal),
147
- task: undefined,
148
- })
149
- expect(outcome).toBeUndefined()
150
- expect(calls).toHaveLength(0)
151
- })
152
- })
153
-
154
- describe('collectTaskSemantics over real event shapes', () => {
155
- it('reads a todo/write event appended alongside message events', () => {
156
- const events = [
157
- {
158
- type: 'user/message',
159
- seq: 1,
160
- time: 0,
161
- data: { content: [{ type: 'text', text: 'start the migration' }] },
162
- },
163
- {
164
- type: 'todo/write',
165
- seq: 2,
166
- time: 0,
167
- data: { todos: ['migrate the auth module', { content: 'write tests', status: 'pending' }] },
168
- },
169
- ] as unknown as readonly SessionEvent[]
170
- const task = collectTaskSemantics(events)
171
- expect(task?.source).toBe('todos')
172
- expect(task?.taskText).toContain('write tests')
173
- })
174
- })
175
-
176
- // ── K13: the advisory-only invariant, against the real pruner ──────────────
177
-
178
- describe('advisory-only invariant (K13): advisor outputs never change landings', () => {
179
- async function prunedResult(session: Session): Promise<unknown> {
180
- const ctx = new Context()
181
- try {
182
- await ctx.plugin(SessionStore).await()
183
- await ctx.plugin(SystemPrompt).await()
184
- await ctx.plugin(ToolRuntime).await()
185
- await ctx.plugin(SessionProjectionRegistry).await()
186
- await ctx.plugin(TokenMeter).await()
187
- await ctx.plugin(ToolResultPruner, {
188
- profile: 'native',
189
- nativeTriggerTokens: 100,
190
- nativeTargetTokens: 64,
191
- headChars: 8,
192
- tailChars: 8,
193
- }).await()
194
- return ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
195
- } finally {
196
- await ctx.fiber.dispose()
197
- }
198
- }
199
-
200
- function buildSession(id: string): Session {
201
- const session = Session.create(SessionId(id))
202
- const callId = CallId('call-1')
203
- session.append('turn/start', { turn: 1 })
204
- session.append('request/header', {
205
- reason: 'initial',
206
- header: canonicalHeader({ config: { provider: 'deepseek', model: 'deepseek-v4-flash' } }),
207
- })
208
- session.append('user/message', createUserMessage({
209
- content: [{ type: 'text', text: 'please inspect the failing module' }],
210
- source: { kind: 'user' },
211
- }), { surfaceOp: 'append' })
212
- session.append('step/start', { turn: 1, step: 1 })
213
- session.append('assistant/message', {
214
- stream: [],
215
- turn: 1,
216
- step: 1,
217
- message: createMessage({
218
- role: 'assistant',
219
- content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
220
- source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
221
- }),
222
- }, { surfaceOp: 'append' })
223
- session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
224
- session.append('tool/result', {
225
- turn: 1,
226
- step: 1,
227
- message: createToolResultMessage({
228
- callId,
229
- content: [{ type: 'text', text: 'gate evidence '.repeat(800) }],
230
- isError: false,
231
- }),
232
- }, { surfaceOp: 'append' })
233
- session.append('step/end', { turn: 1, step: 1 })
234
- // No turn/end: pruning lands its replacement inside the still-open turn.
235
- return session
236
- }
237
-
238
- it('lands identically with the advisor off, and with extreme scores or a failed pass', async () => {
239
- const scenarios: string[] = ['off', 'extreme-scores', 'failed-pass']
240
- const shapes: unknown[] = []
241
- for (const scenario of scenarios) {
242
- // One shared session id: replacement markers embed it, and the advisor
243
- // state is keyed by Session object identity, so this cannot cross-talk.
244
- const session = buildSession('advisor-invariant')
245
- if (scenario !== 'off') {
246
- const state = getAdvisorState(session)
247
- if (scenario === 'extreme-scores') {
248
- state.summary = {
249
- overallTask: 'ALL MUST BE KEPT',
250
- activeSubtasks: ['keep everything forever'],
251
- keywords: ['evidence'],
252
- todoVersion: 'deadbeef',
253
- turn: 1,
254
- }
255
- // Zero relevance everywhere: the most hostile score a channel could
256
- // return must still not delete, delay, or rewrite anything.
257
- recordScore(state, 2, { score: 0, turn: 1 })
258
- }
259
- if (scenario === 'failed-pass') {
260
- state.failures = { failures: 9, cooldownUntil: Date.now() + 600_000 }
261
- }
262
- }
263
- shapes.push(structuredClone(await prunedResult(session)))
264
- }
265
- for (const shape of shapes.slice(1)) {
266
- expect(shape).toEqual(shapes[0])
267
- }
268
- // And the baseline scenario actually reduced something (the test is real).
269
- const baseline = shapes[0] as { pruned: unknown[] }
270
- expect(baseline.pruned).toHaveLength(1)
271
- })
272
- })