dsh-context-compression-improved 0.2.4 → 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 (127) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +8 -8
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +212 -16
  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 +1 -19
  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 +75 -54
  22. package/packages/selector/README.md +7 -12
  23. package/packages/selector/README.zh.md +6 -13
  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 +16 -16
  27. package/packages/selector/lib/client.d.ts +97 -5
  28. package/packages/selector/lib/client.js +1884 -92
  29. package/packages/selector/lib/config.js +863 -6
  30. package/packages/selector/lib/index.d.ts +29 -21
  31. package/packages/selector/lib/index.js +424 -18
  32. package/packages/selector/lib/invariant.js +4 -4
  33. package/packages/selector/lib/pruner.d.ts +179 -4
  34. package/packages/selector/lib/pruner.js +1406 -371
  35. package/packages/selector/lib/style.css +42 -0
  36. package/packages/selector/lib/tail-trim.js +13 -4
  37. package/packages/selector/package.json +18 -27
  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 +200 -62
  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/profiles.ts +431 -342
  61. package/packages/selector/src/pruner/state.ts +57 -43
  62. package/packages/selector/src/pruner.ts +2736 -2154
  63. package/packages/selector/src/runtime/audit.ts +303 -231
  64. package/packages/selector/src/runtime/config.ts +756 -642
  65. package/packages/selector/src/runtime/measurement.ts +436 -432
  66. package/packages/selector/src/runtime/monitor.ts +235 -0
  67. package/packages/selector/src/runtime/retrieve.ts +479 -457
  68. package/packages/selector/src/runtime/savings.ts +337 -0
  69. package/packages/selector/src/runtime/session-events.ts +30 -17
  70. package/packages/selector/src/runtime/summary-command.ts +127 -0
  71. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  72. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  73. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  74. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  75. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  76. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  77. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  78. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  79. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  80. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  81. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
  82. package/packages/selector/src/runtime/types.ts +365 -325
  83. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  84. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  85. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  86. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  87. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  88. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  89. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  90. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  91. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  92. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  93. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  94. package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
  95. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  96. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  97. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  98. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  99. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  100. package/packages/selector/tests/runtime/audit.spec.ts +275 -172
  101. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  102. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  103. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  104. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  105. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
  106. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  107. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  108. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  109. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  110. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  111. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  112. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  113. package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
  114. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  115. package/pnpm-workspace.yaml +66 -19
  116. package/scripts/capture-profile-baseline.mjs +42 -0
  117. package/scripts/generate-tokenizer-fixtures.py +81 -81
  118. package/scripts/generate-vision-fixtures.py +208 -208
  119. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  120. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  121. package/scripts/toolclass-corpus-replay.mjs +281 -273
  122. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  123. package/tests/TEST_INVENTORY.md +41 -42
  124. package/scripts/capture-profile-baseline.ts +0 -80
  125. package/tsconfig.scripts.json +0 -13
  126. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  127. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,172 +1,275 @@
1
- import { describe, expect, it, vi } from 'vitest'
2
- import {
3
- COMPRESSION_AUDIT_PREFIX,
4
- emitCompressionAudit,
5
- formatCompressionAudit,
6
- } from '../../src/runtime/audit.ts'
7
- import type { CompressionAuditRecord, CompressionRewriteAuditRecord } from '../../src/runtime/audit.ts'
8
-
9
- const custom = {
10
- version: 3 as const,
11
- unit: 'tokens' as const,
12
- fresh: { enabled: true, trigger: 8_192, target: 3_072 },
13
- aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
14
- history: {
15
- enabled: true,
16
- trigger: 500_000,
17
- keepRecentToolCalls: 10,
18
- keepRecentTokens: 64_000,
19
- minReclaim: 96_000,
20
- },
21
- prefixPolicy: 'pressure-break' as const,
22
- tailTrim: { enabled: true, trigger: 700_000 },
23
- }
24
-
25
- describe('context-compression audit records', () => {
26
- it('formats one complete frozen-policy record without model-visible content', () => {
27
- const record: CompressionAuditRecord = {
28
- schemaVersion: 1,
29
- kind: 'policy-frozen',
30
- sessionId: 'audit-session',
31
- settingsSource: 'host-settings',
32
- settings: {
33
- profile: 'custom',
34
- custom,
35
- autoCompact: { thresholdPercent: 80 },
36
- codeSkeleton: { enabled: false },
37
- },
38
- deploymentConfig: {
39
- profile: 'balanced',
40
- headChars: 4_096,
41
- tailChars: 1_024,
42
- },
43
- }
44
-
45
- const line = formatCompressionAudit(record)
46
-
47
- expect(line).toBe(`${COMPRESSION_AUDIT_PREFIX}${JSON.stringify(record)}`)
48
- expect(JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length))).toEqual(record)
49
- expect(line).not.toContain('prompt')
50
- expect(line).not.toContain('toolArguments')
51
- expect(line).not.toContain('toolResult')
52
- expect(line).not.toContain('apiKey')
53
- })
54
-
55
- it('keeps component provenance and exact token arithmetic on rewrite records', () => {
56
- const record: CompressionAuditRecord = {
57
- schemaVersion: 1,
58
- kind: 'rewrite',
59
- sessionId: 'history-session',
60
- profile: 'cache-strict',
61
- component: 'history',
62
- stage: 'pressure',
63
- reducer: 'historical-tool-result-aging',
64
- historyMode: 'capacity-pressure',
65
- manifestEventType: 'compaction/prune',
66
- manifestSeq: 41,
67
- replacementSeq: 42,
68
- sourceSeqs: [12],
69
- tokensBefore: 600_100,
70
- tokensAfter: 100,
71
- tokensRemoved: 600_000,
72
- tokenizerId: 'mock-tokenizer',
73
- tokenizerRevision: 'r1',
74
- measurementBasis: 'exact-tokenizer',
75
- }
76
-
77
- const parsed = JSON.parse(
78
- formatCompressionAudit(record).slice(COMPRESSION_AUDIT_PREFIX.length),
79
- ) as CompressionAuditRecord
80
-
81
- expect(parsed).toEqual(record)
82
- expect(parsed.kind === 'rewrite' && parsed.tokensRemoved)
83
- .toBe(record.tokensBefore - record.tokensAfter)
84
- })
85
-
86
- // task_4c/G7: the elided-line count rides the rewrite audit record (optional,
87
- // JSON round-trip) so the compress→retrieve M/N ratio is computable from
88
- // session logs alone; records without reducer telemetry omit the field.
89
- it('round-trips elidedLines on rewrite records and omits it when absent', () => {
90
- const withTelemetry: CompressionAuditRecord = {
91
- schemaVersion: 1,
92
- kind: 'rewrite',
93
- sessionId: 'telemetry-session',
94
- profile: 'balanced',
95
- component: 'fresh',
96
- stage: 'fresh',
97
- reducer: 'hypa-code-skeleton',
98
- manifestEventType: 'compaction/prune',
99
- manifestSeq: 7,
100
- replacementSeq: 8,
101
- sourceSeqs: [6],
102
- tokensBefore: 20_000,
103
- tokensAfter: 3_000,
104
- tokensRemoved: 17_000,
105
- tokenizerId: 'mock-tokenizer',
106
- tokenizerRevision: 'r1',
107
- measurementBasis: 'exact-tokenizer',
108
- elidedLines: 412,
109
- }
110
- const parsed = JSON.parse(
111
- formatCompressionAudit(withTelemetry).slice(COMPRESSION_AUDIT_PREFIX.length),
112
- ) as CompressionRewriteAuditRecord
113
- expect(parsed.elidedLines).toBe(412)
114
-
115
- const { elidedLines: _omitted, ...placeholderRecord } = withTelemetry
116
- void _omitted
117
- const withoutTelemetry: CompressionAuditRecord = {
118
- ...placeholderRecord,
119
- reducer: 'error-evidence-placeholder',
120
- }
121
- expect('elidedLines' in withoutTelemetry).toBe(false)
122
- const parsedWithout = JSON.parse(
123
- formatCompressionAudit(withoutTelemetry).slice(COMPRESSION_AUDIT_PREFIX.length),
124
- ) as CompressionRewriteAuditRecord
125
- expect(parsedWithout.elidedLines).toBeUndefined()
126
- })
127
-
128
- it('publishes exactly one single-line info message', () => {
129
- const info = vi.fn()
130
- const record: CompressionAuditRecord = {
131
- schemaVersion: 1,
132
- kind: 'native-auto-compact',
133
- sessionId: 'native-session',
134
- manifestEventType: 'compaction/summary',
135
- manifestSeq: 9,
136
- reducer: 'llm-summary',
137
- provider: 'mock',
138
- model: 'mock',
139
- tokensBefore: 1_024,
140
- tokensAfter: null,
141
- }
142
-
143
- emitCompressionAudit({ info }, record)
144
-
145
- expect(info).toHaveBeenCalledOnce()
146
- expect(info).toHaveBeenCalledWith(formatCompressionAudit(record))
147
- expect(String(info.mock.calls[0]?.[0])).not.toContain('\n')
148
- })
149
-
150
- it('does not let logger failure roll back an already committed rewrite', () => {
151
- const record: CompressionAuditRecord = {
152
- schemaVersion: 1,
153
- kind: 'native-auto-compact',
154
- sessionId: 'native-session',
155
- manifestEventType: 'compaction/summary',
156
- manifestSeq: 9,
157
- reducer: 'llm-summary',
158
- provider: 'mock',
159
- model: 'mock',
160
- tokensBefore: 1_024,
161
- tokensAfter: null,
162
- }
163
-
164
- expect(() => {
165
- emitCompressionAudit({
166
- info: () => {
167
- throw new Error('logger unavailable')
168
- },
169
- }, record)
170
- }).not.toThrow()
171
- })
172
- })
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ COMPRESSION_AUDIT_PREFIX,
4
+ emitCompressionAudit,
5
+ formatCompressionAudit,
6
+ } from '../../src/runtime/audit.ts'
7
+ import type { CompressionAuditRecord, CompressionRewriteAuditRecord } from '../../src/runtime/audit.ts'
8
+
9
+ const custom = {
10
+ version: 3 as const,
11
+ unit: 'tokens' as const,
12
+ fresh: { enabled: true, trigger: 8_192, target: 3_072 },
13
+ aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
14
+ history: {
15
+ enabled: true,
16
+ trigger: 500_000,
17
+ keepRecentToolCalls: 10,
18
+ keepRecentTokens: 64_000,
19
+ minReclaim: 96_000,
20
+ },
21
+ prefixPolicy: 'pressure-break' as const,
22
+ tailTrim: { enabled: true, trigger: 700_000 },
23
+ }
24
+
25
+ describe('context-compression audit records', () => {
26
+ it('formats one complete frozen-policy record without model-visible content', () => {
27
+ const record: CompressionAuditRecord = {
28
+ schemaVersion: 1,
29
+ kind: 'policy-frozen',
30
+ sessionId: 'audit-session',
31
+ settingsSource: 'host-settings',
32
+ settings: {
33
+ profile: 'custom',
34
+ custom,
35
+ autoCompact: { thresholdPercent: 80 },
36
+ codeSkeleton: { enabled: false },
37
+ intentSummary: { enabled: false },
38
+ },
39
+ deploymentConfig: {
40
+ profile: 'balanced',
41
+ headChars: 4_096,
42
+ tailChars: 1_024,
43
+ },
44
+ }
45
+
46
+ const line = formatCompressionAudit(record)
47
+
48
+ expect(line).toBe(`${COMPRESSION_AUDIT_PREFIX}${JSON.stringify(record)}`)
49
+ expect(JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length))).toEqual(record)
50
+ expect(line).not.toContain('prompt')
51
+ expect(line).not.toContain('toolArguments')
52
+ expect(line).not.toContain('toolResult')
53
+ expect(line).not.toContain('apiKey')
54
+ })
55
+
56
+ it('keeps component provenance and exact token arithmetic on rewrite records', () => {
57
+ const record: CompressionAuditRecord = {
58
+ schemaVersion: 1,
59
+ kind: 'rewrite',
60
+ sessionId: 'history-session',
61
+ profile: 'cache-strict',
62
+ component: 'history',
63
+ stage: 'pressure',
64
+ reducer: 'historical-tool-result-aging',
65
+ historyMode: 'capacity-pressure',
66
+ manifestEventType: 'compaction/prune',
67
+ manifestSeq: 41,
68
+ replacementSeq: 42,
69
+ sourceSeqs: [12],
70
+ tokensBefore: 600_100,
71
+ tokensAfter: 100,
72
+ tokensRemoved: 600_000,
73
+ tokenizerId: 'mock-tokenizer',
74
+ tokenizerRevision: 'r1',
75
+ measurementBasis: 'exact-tokenizer',
76
+ }
77
+
78
+ const parsed = JSON.parse(
79
+ formatCompressionAudit(record).slice(COMPRESSION_AUDIT_PREFIX.length),
80
+ ) as CompressionAuditRecord
81
+
82
+ expect(parsed).toEqual(record)
83
+ expect(parsed.kind === 'rewrite' && parsed.tokensRemoved)
84
+ .toBe(record.tokensBefore - record.tokensAfter)
85
+ })
86
+
87
+ // task_4c/G7: the elided-line count rides the rewrite audit record (optional,
88
+ // JSON round-trip) so the compress→retrieve M/N ratio is computable from
89
+ // session logs alone; records without reducer telemetry omit the field.
90
+ it('round-trips elidedLines on rewrite records and omits it when absent', () => {
91
+ const withTelemetry: CompressionAuditRecord = {
92
+ schemaVersion: 1,
93
+ kind: 'rewrite',
94
+ sessionId: 'telemetry-session',
95
+ profile: 'balanced',
96
+ component: 'fresh',
97
+ stage: 'fresh',
98
+ reducer: 'hypa-code-skeleton',
99
+ manifestEventType: 'compaction/prune',
100
+ manifestSeq: 7,
101
+ replacementSeq: 8,
102
+ sourceSeqs: [6],
103
+ tokensBefore: 20_000,
104
+ tokensAfter: 3_000,
105
+ tokensRemoved: 17_000,
106
+ tokenizerId: 'mock-tokenizer',
107
+ tokenizerRevision: 'r1',
108
+ measurementBasis: 'exact-tokenizer',
109
+ elidedLines: 412,
110
+ }
111
+ const parsed = JSON.parse(
112
+ formatCompressionAudit(withTelemetry).slice(COMPRESSION_AUDIT_PREFIX.length),
113
+ ) as CompressionRewriteAuditRecord
114
+ expect(parsed.elidedLines).toBe(412)
115
+
116
+ const { elidedLines: _omitted, ...placeholderRecord } = withTelemetry
117
+ void _omitted
118
+ const withoutTelemetry: CompressionAuditRecord = {
119
+ ...placeholderRecord,
120
+ reducer: 'error-evidence-placeholder',
121
+ }
122
+ expect('elidedLines' in withoutTelemetry).toBe(false)
123
+ const parsedWithout = JSON.parse(
124
+ formatCompressionAudit(withoutTelemetry).slice(COMPRESSION_AUDIT_PREFIX.length),
125
+ ) as CompressionRewriteAuditRecord
126
+ expect(parsedWithout.elidedLines).toBeUndefined()
127
+ })
128
+
129
+ it('publishes exactly one single-line info message', () => {
130
+ const info = vi.fn()
131
+ const record: CompressionAuditRecord = {
132
+ schemaVersion: 1,
133
+ kind: 'native-auto-compact',
134
+ sessionId: 'native-session',
135
+ manifestEventType: 'compaction/summary',
136
+ manifestSeq: 9,
137
+ reducer: 'llm-summary',
138
+ provider: 'mock',
139
+ model: 'mock',
140
+ tokensBefore: 1_024,
141
+ tokensAfter: null,
142
+ }
143
+
144
+ emitCompressionAudit({ info }, record)
145
+
146
+ expect(info).toHaveBeenCalledOnce()
147
+ expect(info).toHaveBeenCalledWith(formatCompressionAudit(record))
148
+ expect(String(info.mock.calls[0]?.[0])).not.toContain('\n')
149
+ })
150
+
151
+ it('does not let logger failure roll back an already committed rewrite', () => {
152
+ const record: CompressionAuditRecord = {
153
+ schemaVersion: 1,
154
+ kind: 'native-auto-compact',
155
+ sessionId: 'native-session',
156
+ manifestEventType: 'compaction/summary',
157
+ manifestSeq: 9,
158
+ reducer: 'llm-summary',
159
+ provider: 'mock',
160
+ model: 'mock',
161
+ tokensBefore: 1_024,
162
+ tokensAfter: null,
163
+ }
164
+
165
+ expect(() => {
166
+ emitCompressionAudit({
167
+ info: () => {
168
+ throw new Error('logger unavailable')
169
+ },
170
+ }, record)
171
+ }).not.toThrow()
172
+ })
173
+
174
+ it('keeps reduction-advice records free of content, digests, and keys', () => {
175
+ const record: CompressionAuditRecord = {
176
+ schemaVersion: 1,
177
+ kind: 'reduction-advice',
178
+ sessionId: 'advice-session',
179
+ profile: 'tokenpilot-inspired',
180
+ band: 'high-impact',
181
+ stage: 'fresh',
182
+ itemSeqs: [7, 9],
183
+ pricedCandidates: 2,
184
+ maxTokensBefore: 9_200,
185
+ tokensBefore: 12_400,
186
+ tokensAfter: 3_100,
187
+ recoveredTokens: 9_300,
188
+ penaltyTokens: 0,
189
+ paybackTurns: 0,
190
+ turnIndex: 12,
191
+ }
192
+
193
+ const line = formatCompressionAudit(record)
194
+ const parsed = JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord
195
+ expect(parsed).toEqual(record)
196
+ // Only ids, enums, and numbers: no digests, no content fields.
197
+ expect(line).not.toContain('digest')
198
+ expect(line).not.toContain('"content"')
199
+ expect(line).not.toContain('"text"')
200
+ expect(line).not.toContain('apiKey')
201
+ })
202
+
203
+ it('describes an advised batch without any gate vocabulary', () => {
204
+ // The band can be the model's worst opinion — `not-worth-it` — and the
205
+ // record still only DESCRIBES a batch that landed: the retired review
206
+ // gate's decision vocabulary cannot be expressed any more.
207
+ const record: CompressionAuditRecord = {
208
+ schemaVersion: 1,
209
+ kind: 'reduction-advice',
210
+ sessionId: 'advice-session',
211
+ profile: 'tokenpilot-inspired',
212
+ band: 'not-worth-it',
213
+ stage: 'history',
214
+ itemSeqs: [3],
215
+ pricedCandidates: 1,
216
+ maxTokensBefore: 5_000,
217
+ tokensBefore: 5_000,
218
+ tokensAfter: 4_000,
219
+ recoveredTokens: 1_000,
220
+ penaltyTokens: 3_600,
221
+ paybackTurns: 36,
222
+ expectedSaving: 0,
223
+ }
224
+ const line = formatCompressionAudit(record)
225
+ const parsed = JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord
226
+ expect(parsed).toEqual(record)
227
+ for (const gone of ['proposalId', 'proposalKind', 'decision', 'receipt', '"event"', 'reasonCode']) {
228
+ expect(line).not.toContain(gone)
229
+ }
230
+ })
231
+
232
+ it('keeps advisor-outcome records free of prompts, keys, and content', () => {
233
+ const record: CompressionAuditRecord = {
234
+ schemaVersion: 1,
235
+ kind: 'advisor-outcome',
236
+ sessionId: 'advisor-session',
237
+ phase: 'decay',
238
+ ok: true,
239
+ sampledCount: 16,
240
+ decay: 0.42,
241
+ weightedChars: 57_688,
242
+ turnIndex: 12,
243
+ latencyMs: 0,
244
+ }
245
+
246
+ const line = formatCompressionAudit(record)
247
+ const parsed = JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord
248
+ expect(parsed).toEqual(record)
249
+ // Only enums and numbers: never the todo snapshot, assistant text, prompts, or keys.
250
+ expect(line).not.toContain('prompt')
251
+ expect(line).not.toContain('"content"')
252
+ expect(line).not.toContain('"text"')
253
+ expect(line).not.toContain('apiKey')
254
+ expect(line).not.toContain('todo')
255
+ })
256
+
257
+ it('carries failure reason codes and the LLM channel on advisor-outcome records', () => {
258
+ const record: CompressionAuditRecord = {
259
+ schemaVersion: 1,
260
+ kind: 'advisor-outcome',
261
+ sessionId: 'advisor-session',
262
+ phase: 'scoring',
263
+ channel: 'direct',
264
+ ok: false,
265
+ sampledCount: 0,
266
+ turnIndex: 3,
267
+ reason: 'no-direct-endpoint',
268
+ latencyMs: 4,
269
+ }
270
+ const parsed = JSON.parse(
271
+ formatCompressionAudit(record).slice(COMPRESSION_AUDIT_PREFIX.length),
272
+ ) as CompressionAuditRecord
273
+ expect(parsed).toEqual(record)
274
+ })
275
+ })
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Upgrade safety for the retired review gate's settings keys.
3
+ *
4
+ * The gate is gone, but its keys are PERSISTED: a live settings document still
5
+ * carries `reviewMode: false`, and both the runtime parser and the browser
6
+ * decoder reject unknown keys. Removing the keys from the accepted set would
7
+ * therefore make the plugin fail to load (runtime) or report the whole settings
8
+ * card as unreadable (client). This spec pins the accept-and-ignore contract in
9
+ * both directions, and pins that the keys never reach the resolved policy.
10
+ */
11
+ import { describe, expect, it } from 'vitest'
12
+ import {
13
+ parsePresetOptionsSettings,
14
+ resolveConfig,
15
+ resolvePolicy,
16
+ } from '../../src/runtime/config.ts'
17
+ import { decodePresetOptionsSettings } from '../../src/profiles.ts'
18
+
19
+ /** The exact legacy section a pre-0.5.2 install has on disk. */
20
+ const LEGACY_SECTION = {
21
+ estimatorMode: 'host',
22
+ estimatorProvider: 'local-35b',
23
+ estimatorModel: 'Qwen3.6-35B-A3B',
24
+ estimatorBaseUrl: 'http://192.168.100.242:8200/v1',
25
+ reviewMode: false,
26
+ }
27
+
28
+ describe('retired review-gate keys are accepted and ignored (runtime)', () => {
29
+ it('parses the legacy section without throwing and keeps the live keys', () => {
30
+ const parsed = parsePresetOptionsSettings(LEGACY_SECTION)
31
+ expect(parsed).toEqual({
32
+ estimatorMode: 'host',
33
+ estimatorProvider: 'local-35b',
34
+ estimatorModel: 'Qwen3.6-35B-A3B',
35
+ estimatorBaseUrl: 'http://192.168.100.242:8200/v1',
36
+ })
37
+ })
38
+
39
+ it('drops every retired key, even with values the old schema rejected', () => {
40
+ // The retired keys are not validated any more — a stale invalid value in an
41
+ // existing document must not be able to break the load.
42
+ const parsed = parsePresetOptionsSettings({
43
+ reviewMode: 'yes',
44
+ reviewTimeoutTurns: -1,
45
+ cacheHitDiscountAlpha: 'wide',
46
+ reviewHighImpactTokens: null,
47
+ })
48
+ expect(parsed).toEqual({})
49
+ })
50
+
51
+ it('still rejects a genuinely unknown key', () => {
52
+ expect(() => parsePresetOptionsSettings({ reviewModes: true })).toThrow(/unknown key/)
53
+ })
54
+
55
+ it('never lets a retired key reach the resolved policy matrix', () => {
56
+ // The section arrives as `unknown` from the settings document, so the cast
57
+ // mirrors the production path rather than widening the config surface.
58
+ const policy = resolvePolicy(
59
+ resolveConfig({
60
+ presetOptions: { reviewMode: true, reviewHighImpactTokens: 1 },
61
+ } as unknown as Parameters<typeof resolveConfig>[0]),
62
+ 'tokenpilot-inspired',
63
+ )
64
+ const matrix = policy.presetOptions
65
+ expect(matrix).toBeDefined()
66
+ for (const gone of ['reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens']) {
67
+ expect(Object.hasOwn(matrix as object, gone)).toBe(false)
68
+ }
69
+ // The surviving matrix is exactly the live capability set.
70
+ expect(Object.keys(matrix as object).sort()).toEqual([
71
+ 'advisor', 'dedupeToolResults', 'estimator', 'noNetSavingsGuard',
72
+ 'prefixStabilizer', 'readState', 'skipReductionRecovery', 'summaryLocator',
73
+ ])
74
+ })
75
+ })
76
+
77
+ describe('retired review-gate keys are accepted and ignored (client mirror)', () => {
78
+ it('decodes a legacy section instead of reporting the card unreadable', () => {
79
+ const decoded = decodePresetOptionsSettings(LEGACY_SECTION)
80
+ // `undefined` here would blank the settings card's presetOptions section.
81
+ expect(decoded).toEqual({
82
+ estimatorMode: 'host',
83
+ estimatorProvider: 'local-35b',
84
+ estimatorModel: 'Qwen3.6-35B-A3B',
85
+ estimatorBaseUrl: 'http://192.168.100.242:8200/v1',
86
+ })
87
+ })
88
+
89
+ it('tolerates legacy values the old decoder rejected', () => {
90
+ expect(decodePresetOptionsSettings({ reviewMode: 'yes', reviewHighImpactTokens: -5 })).toEqual({})
91
+ })
92
+
93
+ it('still refuses an unknown key', () => {
94
+ expect(decodePresetOptionsSettings({ reviewModes: true })).toBeUndefined()
95
+ })
96
+ })
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ INTENT_GATE_FLOOR_FRACTION,
4
+ INTENT_GATE_GROWTH_TOKENS,
5
+ evaluateIntentGate,
6
+ shouldRunIntentFold,
7
+ } from '../../src/runtime/tokenpilot/intent-gate.ts'
8
+
9
+ const BASE = {
10
+ enabled: true,
11
+ override: undefined,
12
+ liveTokens: 100_000,
13
+ contextWindow: 200_000,
14
+ baselineTokens: 0,
15
+ } as const
16
+
17
+ describe('intent growth gate', () => {
18
+ it('passes when every condition holds strictly', () => {
19
+ expect(shouldRunIntentFold({ ...BASE })).toBe(true)
20
+ })
21
+
22
+ it('is disabled when the frozen setting is off', () => {
23
+ const out = evaluateIntentGate({ ...BASE, enabled: false })
24
+ expect(out.decision).toBe(false)
25
+ expect(out.reason).toBe('disabled')
26
+ })
27
+
28
+ it('override off wins over everything, including a passing numeric profile', () => {
29
+ const out = evaluateIntentGate({ ...BASE, override: 'off' })
30
+ expect(out.decision).toBe(false)
31
+ expect(out.reason).toBe('override-off')
32
+ })
33
+
34
+ it('override on does NOT bypass the numeric gates', () => {
35
+ expect(shouldRunIntentFold({ ...BASE, override: 'on', liveTokens: 1_000 })).toBe(false)
36
+ })
37
+
38
+ it('unknown context window fails closed toward no-window', () => {
39
+ const out = evaluateIntentGate({ ...BASE, contextWindow: undefined })
40
+ expect(out.decision).toBe(false)
41
+ expect(out.reason).toBe('no-window')
42
+ })
43
+
44
+ it('floor boundary is exclusive: exactly at 45% does not trigger', () => {
45
+ const atFloor = BASE.contextWindow * INTENT_GATE_FLOOR_FRACTION
46
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: atFloor })).toBe(false)
47
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: atFloor + 1 })).toBe(true)
48
+ })
49
+
50
+ it('growth boundary is exclusive: exactly at the threshold does not trigger', () => {
51
+ const baseline = 90_000
52
+ const atGrowth = baseline + INTENT_GATE_GROWTH_TOKENS
53
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: atGrowth, baselineTokens: baseline })).toBe(false)
54
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: atGrowth + 1, baselineTokens: baseline })).toBe(true)
55
+ })
56
+
57
+ it('non-finite or negative counters fail closed', () => {
58
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: Number.NaN })).toBe(false)
59
+ expect(shouldRunIntentFold({ ...BASE, liveTokens: Number.POSITIVE_INFINITY })).toBe(false)
60
+ expect(shouldRunIntentFold({ ...BASE, baselineTokens: -1 })).toBe(false)
61
+ })
62
+ })