dsh-context-compression-improved 0.7.0-beta.1 → 0.8.0-beta.2

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 (93) hide show
  1. package/CHANGELOG.de.md +539 -0
  2. package/CHANGELOG.es.md +547 -0
  3. package/CHANGELOG.fr.md +534 -0
  4. package/CHANGELOG.it.md +536 -0
  5. package/CHANGELOG.ja.md +226 -220
  6. package/CHANGELOG.ko.md +220 -214
  7. package/CHANGELOG.md +372 -376
  8. package/CHANGELOG.ru.md +517 -0
  9. package/CHANGELOG.zh.md +204 -199
  10. package/README.de.md +98 -0
  11. package/README.es.md +98 -0
  12. package/README.fr.md +98 -0
  13. package/README.it.md +98 -0
  14. package/README.ja.md +85 -85
  15. package/README.ko.md +85 -85
  16. package/README.md +98 -97
  17. package/README.ru.md +98 -0
  18. package/README.zh.md +85 -86
  19. package/docs/installation.de.md +104 -0
  20. package/docs/installation.es.md +104 -0
  21. package/docs/installation.fr.md +104 -0
  22. package/docs/installation.it.md +104 -0
  23. package/docs/installation.ja.md +78 -78
  24. package/docs/installation.ko.md +78 -78
  25. package/docs/installation.md +103 -103
  26. package/docs/installation.ru.md +104 -0
  27. package/docs/installation.zh.md +100 -100
  28. package/eslint.config.js +30 -76
  29. package/package.json +69 -70
  30. package/packages/selector/dsh.plugin.json +2 -2
  31. package/packages/selector/lib/{intent-gate.js → advisor-state.js} +3 -91
  32. package/packages/selector/lib/client.js +736 -14
  33. package/packages/selector/lib/index.js +1 -92
  34. package/packages/selector/lib/profiles.d.ts +0 -9
  35. package/packages/selector/lib/pruner.d.ts +0 -59
  36. package/packages/selector/lib/pruner.js +7 -410
  37. package/packages/selector/lib/style.css +46 -46
  38. package/packages/selector/package.json +114 -114
  39. package/packages/selector/src/client/decode.ts +2 -6
  40. package/packages/selector/src/client/index.ts +244 -213
  41. package/packages/selector/src/client/locales/de.ts +98 -0
  42. package/packages/selector/src/client/locales/es.ts +98 -0
  43. package/packages/selector/src/client/locales/fr.ts +98 -0
  44. package/packages/selector/src/client/locales/it.ts +98 -0
  45. package/packages/selector/src/client/locales/ja.ts +98 -0
  46. package/packages/selector/src/client/locales/ko.ts +98 -0
  47. package/packages/selector/src/client/locales/ru.ts +98 -0
  48. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  49. package/packages/selector/src/index.ts +411 -418
  50. package/packages/selector/src/preset-overlay.ts +0 -3
  51. package/packages/selector/src/profiles.ts +10 -30
  52. package/packages/selector/src/pruner/content.ts +1 -1
  53. package/packages/selector/src/pruner/state.ts +0 -7
  54. package/packages/selector/src/pruner.ts +9 -253
  55. package/packages/selector/src/runtime/audit.ts +0 -17
  56. package/packages/selector/src/runtime/config.ts +11 -36
  57. package/packages/selector/src/runtime/reducers.ts +1 -1
  58. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +1 -46
  59. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -55
  60. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  61. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +1 -4
  62. package/packages/selector/src/runtime/types.ts +0 -12
  63. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -214
  64. package/packages/selector/tests/built/client-artifact.spec.ts +59 -61
  65. package/packages/selector/tests/code-skeleton.client.spec.ts +93 -94
  66. package/packages/selector/tests/custom-contract.client.spec.ts +222 -223
  67. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
  69. package/packages/selector/tests/preset-options-write.client.spec.ts +187 -188
  70. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
  71. package/packages/selector/tests/profiles.client.spec.tsx +434 -436
  72. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  73. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
  74. package/packages/selector/tests/runtime/audit.spec.ts +274 -275
  75. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  76. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  77. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2731 -2736
  78. package/packages/selector/tests/standing-generation.host.spec.ts +724 -704
  79. package/pnpm-workspace.yaml +66 -66
  80. package/scripts/packed-components-smoke.mjs +0 -2
  81. package/scripts/packed-install-e2e.mjs +5 -7
  82. package/scripts/verify-release.mjs +2 -3
  83. package/tests/TEST_INVENTORY.md +41 -41
  84. package/tsconfig.tests.json +1 -3
  85. package/vitest.config.ts +0 -14
  86. package/packages/selector/src/runtime/summary-command.ts +0 -133
  87. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  88. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  89. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  90. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  91. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  92. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  93. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
@@ -1,78 +1,78 @@
1
- import { existsSync, readFileSync } from 'node:fs'
2
- import { resolve } from 'node:path'
3
- import { describe, expect, it } from 'vitest'
4
-
5
- const root = resolve(import.meta.dirname, '../../..')
6
-
7
- describe('standalone package contract', () => {
8
- it('ships one install-facing package with no intra-repo dependency edge', () => {
9
- const selector = JSON.parse(readFileSync(resolve(root, 'selector/package.json'), 'utf8')) as {
10
- name: string
11
- version: string
12
- dependencies?: Record<string, string>
13
- peerDependencies?: Record<string, string>
14
- publishConfig?: { tag?: string }
15
- }
16
- expect(selector.name).toBe('dsh-context-compression-improved')
17
- expect(selector.dependencies?.['@huggingface/tokenizers']).toBe('0.1.3')
18
- expect(Object.keys(selector.dependencies ?? {})).not.toContain('dsh-context-compression-improved-runtime')
19
- expect(Object.keys(selector.peerDependencies ?? {})).not.toContain('dsh-context-compression-improved-runtime')
20
- expect(Object.keys(selector.peerDependencies ?? {})).not.toContain('@deepseek-ai/dsh-compaction-tool-result-pruner')
21
- expect(selector.peerDependencies?.['@deepseek-ai/dsh-compaction-basic'])
22
- .toBe('>=0.1.7-rc.1 <0.2.0-0')
23
- expect(selector.peerDependencies?.['@deepseek-ai/dsh-command-compact'])
24
- .toBe('>=0.1.7-rc.1 <0.2.0-0')
25
- expect(selector.publishConfig?.tag).toBe('latest')
26
- expect(existsSync(resolve(root, '../runtime/package.json'))).toBe(false)
27
- })
28
-
29
- it('makes the repository root the one git install surface', () => {
30
- const rootManifest = JSON.parse(readFileSync(resolve(root, '../package.json'), 'utf8')) as {
31
- name: string
32
- exports?: Record<string, unknown>
33
- dependencies?: Record<string, string>
34
- engines?: Record<string, string>
35
- dsh?: { bundle?: { patch?: string }, client?: { inject?: string[] } }
36
- }
37
- expect(rootManifest.name).toBe('dsh-context-compression-improved')
38
- for (const specifier of ['.', './invariant', './pruner', './client']) {
39
- expect(rootManifest.exports?.[specifier]).toBeDefined()
40
- }
41
- expect(rootManifest.dependencies?.['@huggingface/tokenizers']).toBe('0.1.3')
42
- expect(rootManifest.dependencies?.['js-yaml']).toBe('^4.3.2')
43
- expect(rootManifest.dsh?.bundle?.patch).toBe('./packages/selector/cordis.patch.yml')
44
- expect(rootManifest.dsh?.client?.inject).toEqual([
45
- '@deepseek-ai/dsh-client-locale',
46
- '@deepseek-ai/dsh-client-ui-primitives',
47
- '@deepseek-ai/dsh-client-ui-slots',
48
- '@deepseek-ai/dsh-client-ui-settings',
49
- ])
50
- expect(rootManifest.engines?.dsh).toBe('>=0.1.7-rc.1 <0.1.8-0')
51
- })
52
-
53
- it('uses the community package in the one Bundle patch', () => {
54
- const patch = readFileSync(resolve(root, 'selector/cordis.patch.yml'), 'utf8')
55
- expect(patch).toContain("name: 'dsh-context-compression-improved'")
56
- expect(patch).not.toContain('@deepseek-ai/dsh-client-ui-context-compression-selector')
57
- })
58
-
59
- it('never ships a retired plugin config key in the Bundle patch', () => {
60
- // Negative control: the patch is loaded by the host and validated against
61
- // the plugin's own Config schema, but nothing tied the two together — so
62
- // the retired review gate's `reviewQueueRoute` survived in this file after
63
- // the key was removed from the schema, advertising a route that can never
64
- // register. A retired key must fail here instead of shipping quietly.
65
- //
66
- // The pin is on KEY-SETTING lines, not on the whole document: the comments
67
- // above the rows deliberately name the retired key while explaining why it
68
- // is gone, and prose must not be mistaken for configuration.
69
- const patch = readFileSync(resolve(root, 'selector/cordis.patch.yml'), 'utf8')
70
- const lines = patch.split('\n')
71
- for (const retired of ['reviewQueueRoute', 'reviewMode', 'reviewTimeoutTurns', 'reviewHighImpactTokens']) {
72
- const setsRetired = lines.find(line => new RegExp(`^\\s*${retired}\\s*:`).test(line))
73
- expect(setsRetired, `${retired} is still set in the Bundle patch`).toBeUndefined()
74
- }
75
- // And the live flag the routes row exists for is still wired.
76
- expect(patch).toContain('estimatorCatalogRoute: true')
77
- })
78
- })
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ const root = resolve(import.meta.dirname, '../../..')
6
+
7
+ describe('standalone package contract', () => {
8
+ it('ships one install-facing package with no intra-repo dependency edge', () => {
9
+ const selector = JSON.parse(readFileSync(resolve(root, 'selector/package.json'), 'utf8')) as {
10
+ name: string
11
+ version: string
12
+ dependencies?: Record<string, string>
13
+ peerDependencies?: Record<string, string>
14
+ publishConfig?: { tag?: string }
15
+ }
16
+ expect(selector.name).toBe('dsh-context-compression-improved')
17
+ expect(selector.dependencies?.['@huggingface/tokenizers']).toBe('0.1.3')
18
+ expect(Object.keys(selector.dependencies ?? {})).not.toContain('dsh-context-compression-improved-runtime')
19
+ expect(Object.keys(selector.peerDependencies ?? {})).not.toContain('dsh-context-compression-improved-runtime')
20
+ expect(Object.keys(selector.peerDependencies ?? {})).not.toContain('@deepseek-ai/dsh-compaction-tool-result-pruner')
21
+ expect(selector.peerDependencies?.['@deepseek-ai/dsh-compaction-basic'])
22
+ .toBe('>=0.2.0-rc.1 <0.2.1-0')
23
+ expect(selector.peerDependencies?.['@deepseek-ai/dsh-command-compact'])
24
+ .toBe('>=0.2.0-rc.1 <0.2.1-0')
25
+ expect(selector.publishConfig?.tag).toBe('latest')
26
+ expect(existsSync(resolve(root, '../runtime/package.json'))).toBe(false)
27
+ })
28
+
29
+ it('makes the repository root the one git install surface', () => {
30
+ const rootManifest = JSON.parse(readFileSync(resolve(root, '../package.json'), 'utf8')) as {
31
+ name: string
32
+ exports?: Record<string, unknown>
33
+ dependencies?: Record<string, string>
34
+ engines?: Record<string, string>
35
+ dsh?: { bundle?: { patch?: string }, client?: { inject?: string[] } }
36
+ }
37
+ expect(rootManifest.name).toBe('dsh-context-compression-improved')
38
+ for (const specifier of ['.', './invariant', './pruner', './client']) {
39
+ expect(rootManifest.exports?.[specifier]).toBeDefined()
40
+ }
41
+ expect(rootManifest.dependencies?.['@huggingface/tokenizers']).toBe('0.1.3')
42
+ expect(rootManifest.dependencies?.['js-yaml']).toBe('^4.3.2')
43
+ expect(rootManifest.dsh?.bundle?.patch).toBe('./packages/selector/cordis.patch.yml')
44
+ expect(rootManifest.dsh?.client?.inject).toEqual([
45
+ '@deepseek-ai/dsh-client-locale',
46
+ '@deepseek-ai/dsh-client-ui-primitives',
47
+ '@deepseek-ai/dsh-client-ui-slots',
48
+ '@deepseek-ai/dsh-client-ui-settings',
49
+ ])
50
+ expect(rootManifest.engines?.dsh).toBe('>=0.2.0-rc.1 <0.2.1-0')
51
+ })
52
+
53
+ it('uses the community package in the one Bundle patch', () => {
54
+ const patch = readFileSync(resolve(root, 'selector/cordis.patch.yml'), 'utf8')
55
+ expect(patch).toContain("name: 'dsh-context-compression-improved'")
56
+ expect(patch).not.toContain('@deepseek-ai/dsh-client-ui-context-compression-selector')
57
+ })
58
+
59
+ it('never ships a retired plugin config key in the Bundle patch', () => {
60
+ // Negative control: the patch is loaded by the host and validated against
61
+ // the plugin's own Config schema, but nothing tied the two together — so
62
+ // the retired review gate's `reviewQueueRoute` survived in this file after
63
+ // the key was removed from the schema, advertising a route that can never
64
+ // register. A retired key must fail here instead of shipping quietly.
65
+ //
66
+ // The pin is on KEY-SETTING lines, not on the whole document: the comments
67
+ // above the rows deliberately name the retired key while explaining why it
68
+ // is gone, and prose must not be mistaken for configuration.
69
+ const patch = readFileSync(resolve(root, 'selector/cordis.patch.yml'), 'utf8')
70
+ const lines = patch.split('\n')
71
+ for (const retired of ['reviewQueueRoute', 'reviewMode', 'reviewTimeoutTurns', 'reviewHighImpactTokens']) {
72
+ const setsRetired = lines.find(line => new RegExp(`^\\s*${retired}\\s*:`).test(line))
73
+ expect(setsRetired, `${retired} is still set in the Bundle patch`).toBeUndefined()
74
+ }
75
+ // And the live flag the routes row exists for is still wired.
76
+ expect(patch).toContain('estimatorCatalogRoute: true')
77
+ })
78
+ })
@@ -1,230 +1,230 @@
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
+ /**
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
+ })