dsh-context-compression-improved 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitattributes +2 -1
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +169 -39
- package/CHANGELOG.ko.md +167 -39
- package/CHANGELOG.md +333 -135
- package/CHANGELOG.zh.md +152 -39
- package/CONTRIBUTING.md +22 -22
- package/README.ja.md +85 -104
- package/README.ko.md +85 -103
- package/README.md +94 -112
- package/README.zh.md +85 -101
- package/THIRD_PARTY_NOTICES.md +14 -14
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.ja.md +78 -76
- package/docs/installation.ko.md +78 -76
- package/docs/installation.md +103 -76
- package/docs/installation.zh.md +100 -76
- package/docs/repair-log.md +657 -582
- package/eslint.config.js +30 -30
- package/package.json +163 -142
- package/packages/selector/README.md +26 -31
- package/packages/selector/README.zh.md +24 -31
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
- package/packages/selector/cordis.patch.yml +27 -19
- package/packages/selector/dsh.plugin.json +2 -2
- package/packages/selector/lib/client.d.ts +320 -228
- package/packages/selector/lib/client.js +3254 -1462
- package/packages/selector/lib/config.js +1713 -842
- package/packages/selector/lib/index.d.ts +46 -38
- package/packages/selector/lib/index.js +1099 -645
- package/packages/selector/lib/invariant.js +70 -70
- package/packages/selector/lib/pruner.d.ts +904 -684
- package/packages/selector/lib/pruner.js +5800 -3807
- package/packages/selector/lib/style.css +88 -46
- package/packages/selector/lib/tail-trim.js +145 -136
- package/packages/selector/package.json +18 -19
- package/packages/selector/screenshots.json +3 -6
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
- package/packages/selector/src/client/EstimatorControls.tsx +277 -281
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +249 -111
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -198
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/preset-options.ts +88 -70
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -126
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
- package/packages/selector/src/index.ts +671 -327
- package/packages/selector/src/invariant.ts +113 -113
- package/packages/selector/src/preset-overlay.ts +60 -1
- package/packages/selector/src/profiles.ts +431 -342
- package/packages/selector/src/pruner/content.ts +18 -5
- package/packages/selector/src/pruner/state.ts +57 -43
- package/packages/selector/src/pruner/types.ts +23 -5
- package/packages/selector/src/pruner.ts +2736 -2144
- package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
- package/packages/selector/src/runtime/audit.ts +303 -215
- package/packages/selector/src/runtime/config.ts +756 -613
- package/packages/selector/src/runtime/measurement.ts +436 -403
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/reducers.ts +1115 -97
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/session-events.ts +30 -17
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +166 -166
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +365 -309
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
- package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
- package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
- package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
- package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -129
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
- package/pnpm-workspace.yaml +66 -19
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -81
- package/scripts/generate-vision-fixtures.py +208 -208
- package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
- package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
- package/scripts/toolclass-corpus-replay.mjs +281 -0
- package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
- package/tests/TEST_INVENTORY.md +41 -42
- package/scripts/capture-profile-baseline.ts +0 -80
- package/tsconfig.scripts.json +0 -13
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
|
@@ -1,33 +1,78 @@
|
|
|
1
|
-
import { 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.
|
|
23
|
-
expect(selector.peerDependencies?.['@deepseek-ai/dsh-command-compact'])
|
|
24
|
-
.toBe('>=0.1.
|
|
25
|
-
expect(selector.publishConfig?.tag).toBe('latest')
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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.2-rc.1 <0.1.3-0')
|
|
23
|
+
expect(selector.peerDependencies?.['@deepseek-ai/dsh-command-compact'])
|
|
24
|
+
.toBe('>=0.1.2-rc.1 <0.1.3-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.2-rc.1 <0.1.3-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
|
+
})
|
|
@@ -31,9 +31,9 @@ describe('Conservative Adaptive interval', () => {
|
|
|
31
31
|
expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
|
|
32
32
|
previousRequestMeasurement: exact(30_500),
|
|
33
33
|
measuredNodes: [
|
|
34
|
-
{ seq: 0, count: exact(10_000) },
|
|
35
|
-
{ seq: 2, count: exact(20_000) },
|
|
36
|
-
{ seq: 3, count: exact(500) },
|
|
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
37
|
],
|
|
38
38
|
})).toEqual({
|
|
39
39
|
kind: 'available',
|
|
@@ -57,7 +57,7 @@ describe('Conservative Adaptive interval', () => {
|
|
|
57
57
|
estimatorRevision: 'r1',
|
|
58
58
|
calibration: { sampleCount: 1, conservativeMarginTokens: 200 },
|
|
59
59
|
}),
|
|
60
|
-
measuredNodes: [{ seq: 0, count: exact(10_000) }],
|
|
60
|
+
measuredNodes: [{ seq: 0, count: exact(10_000), characterPressure: 40_000 }],
|
|
61
61
|
})).toMatchObject({
|
|
62
62
|
kind: 'available',
|
|
63
63
|
measurementKind: 'tokenizer-estimate',
|
|
@@ -79,7 +79,7 @@ describe('Conservative Adaptive interval', () => {
|
|
|
79
79
|
previousPromptTokens: 200,
|
|
80
80
|
expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
|
|
81
81
|
previousRequestMeasurement: measurement,
|
|
82
|
-
measuredNodes: [{ seq: 0, count: exact(50) }],
|
|
82
|
+
measuredNodes: [{ seq: 0, count: exact(50), characterPressure: 200 }],
|
|
83
83
|
})).toEqual({ kind: 'unknown', reason })
|
|
84
84
|
})
|
|
85
85
|
|
|
@@ -90,7 +90,7 @@ describe('Conservative Adaptive interval', () => {
|
|
|
90
90
|
previousPromptTokens: 200,
|
|
91
91
|
expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
|
|
92
92
|
previousRequestMeasurement: exact(200, 'DeepSeek-V4-Flash-0731'),
|
|
93
|
-
measuredNodes: [{ seq: 0, count: exact(50) }],
|
|
93
|
+
measuredNodes: [{ seq: 0, count: exact(50), characterPressure: 200 }],
|
|
94
94
|
})).toEqual({ kind: 'unknown', reason: 'request-tokenizer-revision-mismatch' })
|
|
95
95
|
})
|
|
96
96
|
|
|
@@ -101,7 +101,7 @@ describe('Conservative Adaptive interval', () => {
|
|
|
101
101
|
previousPromptTokens: 200,
|
|
102
102
|
expectedTokenizerRevision: 'DeepSeek-V4-Pro-0813',
|
|
103
103
|
previousRequestMeasurement: exact(200),
|
|
104
|
-
measuredNodes: [{ seq: 0, count: exact(50, 'DeepSeek-V4-Flash-0731') }],
|
|
104
|
+
measuredNodes: [{ seq: 0, count: exact(50, 'DeepSeek-V4-Flash-0731'), characterPressure: 200 }],
|
|
105
105
|
})).toEqual({ kind: 'unknown', reason: 'exact-prefix-tokenizer-revision-mismatch' })
|
|
106
106
|
})
|
|
107
107
|
|
|
@@ -0,0 +1,232 @@
|
|
|
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 {
|
|
26
|
+
SettingsProvider,
|
|
27
|
+
type SettingsNamespace,
|
|
28
|
+
} from '@deepseek-ai/dsh-settings'
|
|
29
|
+
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
|
30
|
+
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
|
31
|
+
import TokenMeter from '@deepseek-ai/dsh-token-meter'
|
|
32
|
+
import ToolRuntime from '@deepseek-ai/dsh-tools'
|
|
33
|
+
import * as SelectorHost from '../../src/index.ts'
|
|
34
|
+
import ToolResultPruner, {
|
|
35
|
+
CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
|
|
36
|
+
} from '../../src/pruner.ts'
|
|
37
|
+
import { measureForCompaction } from '../../src/runtime/measurement.ts'
|
|
38
|
+
import {
|
|
39
|
+
COMPRESSION_AUDIT_PREFIX,
|
|
40
|
+
type CompressionAuditRecord,
|
|
41
|
+
type CompressionRewriteAuditRecord,
|
|
42
|
+
type ReductionAdviceAuditRecord,
|
|
43
|
+
} from '../../src/runtime/audit.ts'
|
|
44
|
+
|
|
45
|
+
const MODEL = 'deepseek-v4-flash'
|
|
46
|
+
|
|
47
|
+
class TestSettings extends SettingsProvider {
|
|
48
|
+
readonly writable = true
|
|
49
|
+
private readonly stored: Record<string, unknown> = {}
|
|
50
|
+
|
|
51
|
+
protected override load(): Promise<Record<string, unknown>> {
|
|
52
|
+
return Promise.resolve(structuredClone(this.stored))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
protected override persist(namespace: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
|
|
56
|
+
this.stored[namespace] = structuredClone(section)
|
|
57
|
+
return Promise.resolve()
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function runtimeContext(): Promise<Context> {
|
|
62
|
+
const ctx = new Context()
|
|
63
|
+
await ctx.plugin(SessionStore).await()
|
|
64
|
+
await ctx.plugin(SystemPrompt).await()
|
|
65
|
+
await ctx.plugin(ToolRuntime).await()
|
|
66
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
67
|
+
await ctx.plugin(TokenMeter).await()
|
|
68
|
+
return ctx
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function captureAudit(ctx: Context): { records(): CompressionAuditRecord[] } {
|
|
72
|
+
const info = vi.spyOn(ctx.logger, 'info').mockImplementation(() => ctx.logger)
|
|
73
|
+
return {
|
|
74
|
+
records: () => info.mock.calls.flatMap((call) => {
|
|
75
|
+
const line = String(call[0])
|
|
76
|
+
return line.startsWith(COMPRESSION_AUDIT_PREFIX)
|
|
77
|
+
? [JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord]
|
|
78
|
+
: []
|
|
79
|
+
}),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function rewrites(records: readonly CompressionAuditRecord[]): CompressionRewriteAuditRecord[] {
|
|
84
|
+
return records.filter((record): record is CompressionRewriteAuditRecord => record.kind === 'rewrite')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function adviceOf(records: readonly CompressionAuditRecord[]): ReductionAdviceAuditRecord[] {
|
|
88
|
+
return records.filter((record): record is ReductionAdviceAuditRecord => record.kind === 'reduction-advice')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
|
|
92
|
+
|
|
93
|
+
function appendToolTurn(session: Session, turn: number, text: string): void {
|
|
94
|
+
const callId = CallId(`call-${String(turn)}`)
|
|
95
|
+
session.append('turn/start', { turn })
|
|
96
|
+
if (session.requestHeader() === undefined) {
|
|
97
|
+
session.append('request/header', {
|
|
98
|
+
reason: 'initial',
|
|
99
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
session.append('user/message', createUserMessage({
|
|
103
|
+
content: [{ type: 'text', text: `user turn ${String(turn)}` }],
|
|
104
|
+
source: { kind: 'user' },
|
|
105
|
+
}), { surfaceOp: 'append' })
|
|
106
|
+
session.append('step/start', { turn, step: 1 })
|
|
107
|
+
session.append('assistant/message', {
|
|
108
|
+
stream: [],
|
|
109
|
+
turn,
|
|
110
|
+
step: 1,
|
|
111
|
+
message: createMessage({
|
|
112
|
+
role: 'assistant',
|
|
113
|
+
content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
|
|
114
|
+
source: { kind: 'model', provider: 'deepseek', model: MODEL },
|
|
115
|
+
}),
|
|
116
|
+
}, { surfaceOp: 'append' })
|
|
117
|
+
session.append('tool/call', { turn, step: 1, callId, name: 'bash', arguments: '{}' })
|
|
118
|
+
session.append('tool/result', {
|
|
119
|
+
turn,
|
|
120
|
+
step: 1,
|
|
121
|
+
message: createToolResultMessage({
|
|
122
|
+
callId,
|
|
123
|
+
content: [{ type: 'text', text }],
|
|
124
|
+
isError: false,
|
|
125
|
+
}),
|
|
126
|
+
}, { surfaceOp: 'append' })
|
|
127
|
+
session.append('step/end', { turn, step: 1 })
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The settings that used to withhold everything: review mode ON with a
|
|
132
|
+
* high-impact threshold of 1 token. History pricing is kept production-like
|
|
133
|
+
* (64,000 protected tail tokens) so the batch is only landable through the
|
|
134
|
+
* fresh stage.
|
|
135
|
+
*/
|
|
136
|
+
async function gatedSettings(ctx: Context): Promise<void> {
|
|
137
|
+
await ctx.plugin(TestSettings).await()
|
|
138
|
+
await ctx.plugin(SelectorHost).await()
|
|
139
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
140
|
+
profile: 'tokenpilot-inspired',
|
|
141
|
+
presetOptions: { reviewMode: true, reviewHighImpactTokens: 1 },
|
|
142
|
+
})
|
|
143
|
+
await ctx.plugin(ToolResultPruner, {
|
|
144
|
+
profile: 'tokenpilot-inspired',
|
|
145
|
+
freshTriggerTokens: 200,
|
|
146
|
+
freshTargetTokens: 100,
|
|
147
|
+
aggregateTriggerTokens: 1_000_000,
|
|
148
|
+
aggregateTargetTokens: 900_000,
|
|
149
|
+
historyTriggerTokens: 400,
|
|
150
|
+
historyKeepRecentToolCalls: 0,
|
|
151
|
+
historyKeepRecentTokens: 64_000,
|
|
152
|
+
historyMinReclaimTokens: 1,
|
|
153
|
+
}).await()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function freshSession(ctx: Context, id: string, text: string): Session {
|
|
157
|
+
const session = Session.create(SessionId(id))
|
|
158
|
+
appendToolTurn(session, 1, text)
|
|
159
|
+
const total = measureForCompaction(ctx, session).totalTokens
|
|
160
|
+
session.append('request/context', {
|
|
161
|
+
provider: 'deepseek',
|
|
162
|
+
model: MODEL,
|
|
163
|
+
contextWindow: Math.floor(total / 0.6),
|
|
164
|
+
})
|
|
165
|
+
// Fresh landing publishes a surface replacement, which requires an open turn.
|
|
166
|
+
session.append('turn/start', { turn: 2 })
|
|
167
|
+
return session
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** ~36,400 characters. The shipped advice threshold is 4,000 tokens, and this
|
|
171
|
+
* fixture is repetitive enough that the exact tokenizer packs it denser than
|
|
172
|
+
* the conservative 4-chars-per-token estimate (an 18,200-character variant
|
|
173
|
+
* measured under 4,000 tokens), so the volume is doubled to keep the
|
|
174
|
+
* `high-impact` label deterministic. */
|
|
175
|
+
const HIGH_IMPACT_TEXT = 'fresh reviewable evidence '.repeat(1_400)
|
|
176
|
+
|
|
177
|
+
describe('advice never withholds (retired review gate)', () => {
|
|
178
|
+
it('lands the fresh batch the gate used to divert, and advises instead', async () => {
|
|
179
|
+
const ctx = await runtimeContext()
|
|
180
|
+
await gatedSettings(ctx)
|
|
181
|
+
const audit = captureAudit(ctx)
|
|
182
|
+
const session = freshSession(ctx, 'advice-lands', HIGH_IMPACT_TEXT)
|
|
183
|
+
|
|
184
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
185
|
+
const records = audit.records()
|
|
186
|
+
|
|
187
|
+
// 1. The reduction LANDED. Under the retired gate this was the assertion
|
|
188
|
+
// that failed: the batch was withheld pending human approval.
|
|
189
|
+
expect(result.pruned).toHaveLength(1)
|
|
190
|
+
expect(rewrites(records).some(entry => entry.component === 'fresh')).toBe(true)
|
|
191
|
+
|
|
192
|
+
// 2. The benefit model still speaks — as advice about the landing.
|
|
193
|
+
const advice = adviceOf(records)
|
|
194
|
+
expect(advice).toHaveLength(1)
|
|
195
|
+
expect(advice[0]!.stage).toBe('fresh')
|
|
196
|
+
expect(advice[0]!.band).toBe('high-impact')
|
|
197
|
+
expect(advice[0]!.maxTokensBefore).toBeGreaterThanOrEqual(4_000)
|
|
198
|
+
expect(advice[0]!.recoveredTokens).toBeGreaterThan(0)
|
|
199
|
+
// The batch it describes is exactly the batch that landed.
|
|
200
|
+
const landedSeqs = rewrites(records).flatMap(entry => [...entry.sourceSeqs])
|
|
201
|
+
expect(advice[0]!.itemSeqs.every(seq => landedSeqs.includes(seq))).toBe(true)
|
|
202
|
+
|
|
203
|
+
// 3. Every advice record describes a landing, never a pending decision.
|
|
204
|
+
expect(advice.length).toBeLessThanOrEqual(rewrites(records).length)
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
it('keeps the automatic path identical when no legacy gate key is present', async () => {
|
|
208
|
+
const ctx = await runtimeContext()
|
|
209
|
+
await ctx.plugin(TestSettings).await()
|
|
210
|
+
await ctx.plugin(SelectorHost).await()
|
|
211
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
212
|
+
profile: 'tokenpilot-inspired',
|
|
213
|
+
})
|
|
214
|
+
await ctx.plugin(ToolResultPruner, {
|
|
215
|
+
profile: 'tokenpilot-inspired',
|
|
216
|
+
freshTriggerTokens: 200,
|
|
217
|
+
freshTargetTokens: 100,
|
|
218
|
+
aggregateTriggerTokens: 1_000_000,
|
|
219
|
+
aggregateTargetTokens: 900_000,
|
|
220
|
+
historyTriggerTokens: 400,
|
|
221
|
+
historyKeepRecentToolCalls: 0,
|
|
222
|
+
historyKeepRecentTokens: 64_000,
|
|
223
|
+
historyMinReclaimTokens: 1,
|
|
224
|
+
}).await()
|
|
225
|
+
const audit = captureAudit(ctx)
|
|
226
|
+
const session = freshSession(ctx, 'advice-default', HIGH_IMPACT_TEXT)
|
|
227
|
+
|
|
228
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
229
|
+
expect(result.pruned).toHaveLength(1)
|
|
230
|
+
expect(adviceOf(audit.records())).toHaveLength(1)
|
|
231
|
+
})
|
|
232
|
+
})
|
|
@@ -0,0 +1,272 @@
|
|
|
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
|
+
})
|