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,56 +1,79 @@
1
- /**
2
- * TokenPilot-inspired E1 unit coverage: pure estimator helpers. The channels
3
- * themselves are integration-level (host/direct transports) and are covered
4
- * by the fail-open contract — every malformed answer resolves to no verdicts.
5
- */
6
- import { describe, expect, it } from 'vitest'
7
- import {
8
- backoffCooldownMs,
9
- buildEstimatorUserPrompt,
10
- isCoolingDown,
11
- parseEstimatorAnswer,
12
- } from '../../../src/runtime/tokenpilot/estimator.ts'
13
-
14
- describe('tokenpilot estimator helpers', () => {
15
- it('parses well-formed verdict arrays, tolerating surrounding prose', () => {
16
- expect(parseEstimatorAnswer('[{"seq":12,"expired":true},{"seq":13,"expired":false}]')).toEqual([
17
- { seq: 12, expired: true },
18
- { seq: 13, expired: false },
19
- ])
20
- expect(parseEstimatorAnswer('Verdicts: [{"seq":7,"expired":true}] done')).toEqual([
21
- { seq: 7, expired: true },
22
- ])
23
- })
24
-
25
- it('yields no verdicts for malformed answers', () => {
26
- expect(parseEstimatorAnswer('')).toEqual([])
27
- expect(parseEstimatorAnswer('no json here')).toEqual([])
28
- expect(parseEstimatorAnswer('[{"seq":"12","expired":true}]')).toEqual([])
29
- expect(parseEstimatorAnswer('[{"seq":12}]')).toEqual([])
30
- expect(parseEstimatorAnswer('not json [')).toEqual([])
31
- })
32
-
33
- it('builds a path-only user prompt without file content', () => {
34
- const prompt = buildEstimatorUserPrompt([
35
- { seq: 4, path: 'src/a.ts', turn: 2 },
36
- { seq: 9, path: 'docs/b.md', turn: 3 },
37
- ])
38
- expect(prompt).toContain('"seq":4')
39
- expect(prompt).toContain('"path":"src/a.ts"')
40
- expect(prompt).not.toMatch(/content/i)
41
- })
42
-
43
- it('backs off exponentially with a five-minute cap', () => {
44
- expect(backoffCooldownMs(0)).toBe(1_000)
45
- expect(backoffCooldownMs(1)).toBe(1_000)
46
- expect(backoffCooldownMs(2)).toBe(2_000)
47
- expect(backoffCooldownMs(3)).toBe(4_000)
48
- expect(backoffCooldownMs(20)).toBe(300_000)
49
- })
50
-
51
- it('treats missing failure state as never cooling down', () => {
52
- expect(isCoolingDown(undefined, Date.now())).toBe(false)
53
- expect(isCoolingDown({ failures: 1, cooldownUntil: Date.now() - 1 }, Date.now())).toBe(false)
54
- expect(isCoolingDown({ failures: 1, cooldownUntil: Date.now() + 60_000 }, Date.now())).toBe(true)
55
- })
56
- })
1
+ /**
2
+ * TokenPilot-inspired E1 unit coverage: pure estimator helpers. The channels
3
+ * themselves are integration-level (host/direct transports) and are covered
4
+ * by the fail-open contract — every malformed answer resolves to no verdicts.
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import {
8
+ backoffCooldownMs,
9
+ buildEstimatorUserPrompt,
10
+ isCoolingDown,
11
+ parseEstimatorAnswer,
12
+ parseEstimatorAnswerDetailed,
13
+ } from '../../../src/runtime/tokenpilot/estimator.ts'
14
+
15
+ describe('tokenpilot estimator helpers', () => {
16
+ it('parses well-formed verdict arrays, tolerating surrounding prose', () => {
17
+ expect(parseEstimatorAnswer('[{"seq":12,"expired":true},{"seq":13,"expired":false}]')).toEqual([
18
+ { seq: 12, expired: true },
19
+ { seq: 13, expired: false },
20
+ ])
21
+ expect(parseEstimatorAnswer('Verdicts: [{"seq":7,"expired":true}] done')).toEqual([
22
+ { seq: 7, expired: true },
23
+ ])
24
+ })
25
+
26
+ it('yields no verdicts for malformed answers', () => {
27
+ expect(parseEstimatorAnswer('')).toEqual([])
28
+ expect(parseEstimatorAnswer('no json here')).toEqual([])
29
+ expect(parseEstimatorAnswer('[{"seq":"12","expired":true}]')).toEqual([])
30
+ expect(parseEstimatorAnswer('[{"seq":12}]')).toEqual([])
31
+ expect(parseEstimatorAnswer('not json [')).toEqual([])
32
+ })
33
+
34
+ it('reads the optional expectedRemainingTurns from the extended object form', () => {
35
+ const answer = parseEstimatorAnswerDetailed(
36
+ 'Result: {"expectedRemainingTurns":7.9,"items":[{"seq":3,"expired":false}]} end',
37
+ )
38
+ expect(answer.verdicts).toEqual([{ seq: 3, expired: false }])
39
+ // Fractional estimates floor to whole turns.
40
+ expect(answer.expectedRemainingTurns).toBe(7)
41
+ })
42
+
43
+ it('stays Ŝ-less for legacy arrays and malformed turn fields', () => {
44
+ const legacy = parseEstimatorAnswerDetailed('Verdicts: [{"seq":7,"expired":true}] done')
45
+ expect(legacy.verdicts).toEqual([{ seq: 7, expired: true }])
46
+ expect(legacy.expectedRemainingTurns).toBeUndefined()
47
+ const malformed = parseEstimatorAnswerDetailed('{"expectedRemainingTurns":"soon","items":[{"seq":1,"expired":true}]}')
48
+ expect(malformed.verdicts).toEqual([{ seq: 1, expired: true }])
49
+ expect(malformed.expectedRemainingTurns).toBeUndefined()
50
+ // Negative estimates are rejected like any other non-numeric field.
51
+ const negative = parseEstimatorAnswerDetailed('{"expectedRemainingTurns":-2,"items":[{"seq":1,"expired":true}]}')
52
+ expect(negative.expectedRemainingTurns).toBeUndefined()
53
+ expect(negative.verdicts).toEqual([{ seq: 1, expired: true }])
54
+ })
55
+
56
+ it('builds a path-only user prompt without file content', () => {
57
+ const prompt = buildEstimatorUserPrompt([
58
+ { seq: 4, path: 'src/a.ts', turn: 2 },
59
+ { seq: 9, path: 'docs/b.md', turn: 3 },
60
+ ])
61
+ expect(prompt).toContain('"seq":4')
62
+ expect(prompt).toContain('"path":"src/a.ts"')
63
+ expect(prompt).not.toMatch(/content/i)
64
+ })
65
+
66
+ it('backs off exponentially with a five-minute cap', () => {
67
+ expect(backoffCooldownMs(0)).toBe(1_000)
68
+ expect(backoffCooldownMs(1)).toBe(1_000)
69
+ expect(backoffCooldownMs(2)).toBe(2_000)
70
+ expect(backoffCooldownMs(3)).toBe(4_000)
71
+ expect(backoffCooldownMs(20)).toBe(300_000)
72
+ })
73
+
74
+ it('treats missing failure state as never cooling down', () => {
75
+ expect(isCoolingDown(undefined, Date.now())).toBe(false)
76
+ expect(isCoolingDown({ failures: 1, cooldownUntil: Date.now() - 1 }, Date.now())).toBe(false)
77
+ expect(isCoolingDown({ failures: 1, cooldownUntil: Date.now() + 60_000 }, Date.now())).toBe(true)
78
+ })
79
+ })
@@ -1,100 +1,116 @@
1
- /**
2
- * TokenPilot-inspired preset: policy derivation plus the backward-compat
3
- * golden. The fixture freezes the resolvePolicy output of every pre-existing
4
- * profile captured BEFORE this preset existed; any byte difference is a
5
- * compatibility regression, however intentional it feels.
6
- */
7
- import { readFileSync } from 'node:fs'
8
- import { join } from 'node:path'
9
- import { describe, expect, it } from 'vitest'
10
- import {
11
- parseContextCompressionSettings,
12
- resolveConfig,
13
- resolvePolicy,
14
- } from '../../../src/pruner.ts'
15
-
16
- const baseline = JSON.parse(readFileSync(
17
- join(import.meta.dirname, '..', 'fixtures', 'profile-baseline.json'),
18
- 'utf8',
19
- )) as {
20
- profiles: Record<string, Record<string, unknown>>
21
- }
22
-
23
- const OLD_PROFILES = ['off', 'native', 'balanced', 'cache-strict', 'savings', 'adaptive', 'custom'] as const
24
- const OPTION_CASES = [
25
- { label: 'defaults', options: {} },
26
- { label: 'linkage', options: { contextWindowTokens: 128_000, autoCompactThresholdPercent: 80 } },
27
- ] as const
28
-
29
- describe('tokenpilot-inspired preset', () => {
30
- it('keeps every pre-existing profile byte-identical to the pre-preset baseline', () => {
31
- const config = resolveConfig({})
32
- for (const profile of OLD_PROFILES) {
33
- for (const optionCase of OPTION_CASES) {
34
- const key = optionCase.label
35
- expect(
36
- resolvePolicy(config, profile, undefined, optionCase.options),
37
- `${profile}/${key}`,
38
- ).toStrictEqual(baseline.profiles[profile]?.[key])
39
- }
40
- }
41
- })
42
-
43
- it('derives from the balanced baseline and injects the capability matrix', () => {
44
- const config = resolveConfig({})
45
- const policy = resolvePolicy(config, 'tokenpilot-inspired')
46
- expect(policy.profile).toBe('tokenpilot-inspired')
47
- expect(policy.freshEnabled).toBe(true)
48
- expect(policy.aggregateEnabled).toBe(true)
49
- expect(policy.historyMode).toBe('routine')
50
- expect(policy.freshTriggerTokens).toBe(8_192)
51
- expect(policy.freshTargetTokens).toBe(3_072)
52
- expect(policy.aggregateTriggerTokens).toBe(32_768)
53
- expect(policy.aggregateTargetTokens).toBe(12_288)
54
- expect(policy.historyTriggerTokens).toBe(500_000)
55
- expect(policy.historyMinReclaimTokens).toBe(96_000)
56
- expect(policy.presetOptions).toStrictEqual({
57
- noNetSavingsGuard: true,
58
- skipReductionRecovery: true,
59
- dedupeToolResults: true,
60
- summaryLocator: true,
61
- prefixStabilizer: true,
62
- readState: true,
63
- estimator: { mode: '' },
64
- })
65
- // Other profiles never carry the capability matrix.
66
- expect(resolvePolicy(config, 'balanced').presetOptions).toBeUndefined()
67
- })
68
-
69
- it('links Auto Compact watermarks like balanced does', () => {
70
- const config = resolveConfig({})
71
- const policy = resolvePolicy(config, 'tokenpilot-inspired', undefined, {
72
- contextWindowTokens: 128_000,
73
- autoCompactThresholdPercent: 80,
74
- })
75
- expect(policy.autoCompactTokens).toBe(102_400)
76
- expect(policy.microDeadlineTokens).toBe(89_600)
77
- expect(policy.historyTriggerTokens).toBe(64_000)
78
- expect(policy.historyMinReclaimTokens).toBe(12_288)
79
- expect(policy.historyKeepRecentTokens).toBe(8_192)
80
- })
81
-
82
- it('accepts persisted presetOptions overrides and rejects unknown keys', () => {
83
- const base = {
84
- profile: 'balanced',
85
- custom: { version: 3, unit: 'tokens', fresh: { enabled: true, trigger: 2, target: 1 }, aggregate: { enabled: false, trigger: 2, target: 1 }, history: { enabled: false, trigger: 2, keepRecentToolCalls: 1, keepRecentTokens: 1, minReclaim: 1 }, prefixPolicy: 'preserve', tailTrim: { enabled: false, trigger: 2 } },
86
- }
87
- const doc = {
88
- ...base,
89
- presetOptions: { dedupeToolResults: false, estimatorMode: 'host' },
90
- }
91
- expect((parseContextCompressionSettings(structuredClone(doc)) as { presetOptions?: unknown }).presetOptions).toStrictEqual({
92
- dedupeToolResults: false,
93
- estimatorMode: 'host',
94
- })
95
- expect(() => parseContextCompressionSettings({
96
- ...base,
97
- presetOptions: { nope: true },
98
- })).toThrow()
99
- })
100
- })
1
+ /**
2
+ * TokenPilot-inspired preset: policy derivation plus the backward-compat
3
+ * golden. The fixture freezes the resolvePolicy output of every pre-existing
4
+ * profile captured BEFORE this preset existed; any byte difference is a
5
+ * compatibility regression, however intentional it feels.
6
+ */
7
+ import { readFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { describe, expect, it } from 'vitest'
10
+ import {
11
+ parseContextCompressionSettings,
12
+ resolveConfig,
13
+ resolvePolicy,
14
+ } from '../../../src/pruner.ts'
15
+
16
+ const baseline = JSON.parse(readFileSync(
17
+ join(import.meta.dirname, '..', 'fixtures', 'profile-baseline.json'),
18
+ 'utf8',
19
+ )) as {
20
+ profiles: Record<string, Record<string, unknown>>
21
+ }
22
+
23
+ const OLD_PROFILES = ['off', 'native', 'balanced', 'cache-strict', 'savings', 'adaptive', 'custom'] as const
24
+ const OPTION_CASES = [
25
+ { label: 'defaults', options: {} },
26
+ { label: 'linkage', options: { contextWindowTokens: 128_000, autoCompactThresholdPercent: 80 } },
27
+ ] as const
28
+
29
+ describe('tokenpilot-inspired preset', () => {
30
+ it('keeps every pre-existing profile byte-identical to the pre-preset baseline', () => {
31
+ const config = resolveConfig({})
32
+ for (const profile of OLD_PROFILES) {
33
+ for (const optionCase of OPTION_CASES) {
34
+ const key = optionCase.label
35
+ expect(
36
+ resolvePolicy(config, profile, undefined, optionCase.options),
37
+ `${profile}/${key}`,
38
+ ).toStrictEqual(baseline.profiles[profile]?.[key])
39
+ }
40
+ }
41
+ })
42
+
43
+ it('derives from the balanced baseline and injects the capability matrix', () => {
44
+ const config = resolveConfig({})
45
+ const policy = resolvePolicy(config, 'tokenpilot-inspired')
46
+ expect(policy.profile).toBe('tokenpilot-inspired')
47
+ expect(policy.freshEnabled).toBe(true)
48
+ expect(policy.aggregateEnabled).toBe(true)
49
+ expect(policy.historyMode).toBe('routine')
50
+ expect(policy.freshTriggerTokens).toBe(8_192)
51
+ expect(policy.freshTargetTokens).toBe(3_072)
52
+ expect(policy.aggregateTriggerTokens).toBe(32_768)
53
+ expect(policy.aggregateTargetTokens).toBe(12_288)
54
+ expect(policy.historyTriggerTokens).toBe(500_000)
55
+ expect(policy.historyMinReclaimTokens).toBe(96_000)
56
+ expect(policy.presetOptions).toStrictEqual({
57
+ noNetSavingsGuard: true,
58
+ skipReductionRecovery: true,
59
+ dedupeToolResults: true,
60
+ summaryLocator: true,
61
+ prefixStabilizer: true,
62
+ readState: true,
63
+ estimator: { mode: '' },
64
+ // Advisory advisor ships off with its documented defaults. The
65
+ // resolved matrix intentionally gains this group so it follows the
66
+ // estimator's resolved-consumption pattern; see
67
+ // .agents/plans/ctx-relevance-advisor/spec.md decision record.
68
+ //
69
+ // The retired review gate's four keys are intentionally absent here:
70
+ // they are still ACCEPTED by the parser for upgrade safety but never
71
+ // reach the resolved policy (a reduction must not be gated).
72
+ advisor: {
73
+ mode: '',
74
+ timeoutMs: 8000,
75
+ refreshTurns: 8,
76
+ scoreThreshold: 0.35,
77
+ sampleLimit: 16,
78
+ minTokens: 250,
79
+ },
80
+ })
81
+ // Other profiles never carry the capability matrix.
82
+ expect(resolvePolicy(config, 'balanced').presetOptions).toBeUndefined()
83
+ })
84
+
85
+ it('links Auto Compact watermarks like balanced does', () => {
86
+ const config = resolveConfig({})
87
+ const policy = resolvePolicy(config, 'tokenpilot-inspired', undefined, {
88
+ contextWindowTokens: 128_000,
89
+ autoCompactThresholdPercent: 80,
90
+ })
91
+ expect(policy.autoCompactTokens).toBe(102_400)
92
+ expect(policy.microDeadlineTokens).toBe(89_600)
93
+ expect(policy.historyTriggerTokens).toBe(64_000)
94
+ expect(policy.historyMinReclaimTokens).toBe(12_288)
95
+ expect(policy.historyKeepRecentTokens).toBe(8_192)
96
+ })
97
+
98
+ it('accepts persisted presetOptions overrides and rejects unknown keys', () => {
99
+ const base = {
100
+ profile: 'balanced',
101
+ custom: { version: 3, unit: 'tokens', fresh: { enabled: true, trigger: 2, target: 1 }, aggregate: { enabled: false, trigger: 2, target: 1 }, history: { enabled: false, trigger: 2, keepRecentToolCalls: 1, keepRecentTokens: 1, minReclaim: 1 }, prefixPolicy: 'preserve', tailTrim: { enabled: false, trigger: 2 } },
102
+ }
103
+ const doc = {
104
+ ...base,
105
+ presetOptions: { dedupeToolResults: false, estimatorMode: 'host' },
106
+ }
107
+ expect((parseContextCompressionSettings(structuredClone(doc)) as { presetOptions?: unknown }).presetOptions).toStrictEqual({
108
+ dedupeToolResults: false,
109
+ estimatorMode: 'host',
110
+ })
111
+ expect(() => parseContextCompressionSettings({
112
+ ...base,
113
+ presetOptions: { nope: true },
114
+ })).toThrow()
115
+ })
116
+ })
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Settings-seat contract pin for dsh-context-compression-improved's client.
3
+ *
4
+ * This spec locks WHERE the compression settings panel mounts: exactly ONE
5
+ * seat — the standalone `settings.section` entry (设置 → 上下文压缩) — and
6
+ * explicitly NOT the Plugins-section surfaces, and NOT a `shell.overlay` float
7
+ * (the retired review panel's seat was removed with the gate). History this
8
+ * pins against: the 0.1.5 line first lost every entry (a lazy `ctx.get` of
9
+ * locale/settingsScope raced the settings client and apply bailed), then showed
10
+ * the panel twice (item card + tab on top of the standalone section). Both were
11
+ * fixed by the declarative-inject + single-section shape below. When a future
12
+ * DSH line moves the seat again, migrate src/client/index.ts AND this file
13
+ * together.
14
+ */
15
+ import { describe, expect, it, vi } from 'vitest'
16
+ import type { Context as ClientContext } from '@deepseek-ai/cordis'
17
+ import { apply, inject } from '../src/client/index.ts'
18
+ import { ContextCompressionSettingsSection } from '../src/client/CompressionProfileSelector.tsx'
19
+
20
+ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({
21
+ IconChevronDownOutline14: () => null,
22
+ Menu: () => null,
23
+ }))
24
+
25
+ interface CapturedRegistration {
26
+ readonly slot: string
27
+ readonly options: Record<string, unknown>
28
+ readonly component: unknown
29
+ }
30
+
31
+ /**
32
+ * Drive apply against a stub host and capture every slot registration.
33
+ * @param options - `registerThrows` models an older host that does not declare
34
+ * the seat: the slot boundary rejects the registration, exactly the shape the
35
+ * 0.1.2-era hosts had.
36
+ */
37
+ function collectRegistrations(
38
+ options: { readonly registerThrows?: boolean } = {},
39
+ ): { declared: string[]; registrations: CapturedRegistration[] } {
40
+ const declared: string[] = []
41
+ const registrations: CapturedRegistration[] = []
42
+ const ctx = {
43
+ locale: { register: vi.fn(() => () => {}), bind: () => (key: string) => key },
44
+ settingsScope: { bind: vi.fn(() => ({}) as never) },
45
+ slots: {
46
+ inject: (slot: string, factory: () => (() => void) | Generator<() => void>) => {
47
+ declared.push(slot)
48
+ const result = factory()
49
+ const steps: Iterable<() => void> = typeof (result as { [Symbol.iterator]?: unknown })?.[Symbol.iterator] === 'function'
50
+ ? (result as Generator<() => void>)
51
+ : [result as () => void]
52
+ for (const step of steps) { void step }
53
+ return () => {}
54
+ },
55
+ register: (record: Record<string, unknown>, component: unknown) => {
56
+ if (options.registerThrows === true) throw new Error(`unknown slot ${String(record['name'])}`)
57
+ registrations.push({ slot: String(record['name']), options: record, component })
58
+ return () => {}
59
+ },
60
+ },
61
+ }
62
+ apply(ctx as unknown as ClientContext)
63
+ return { declared, registrations }
64
+ }
65
+
66
+ describe('settings-seat contract (standalone settings.section + input-bar session binder)', () => {
67
+ it('declares the services apply consumes (cordis waits; no lazy-get race)', () => {
68
+ expect(inject).toEqual(['slots', 'locale', 'settingsScope'])
69
+ })
70
+
71
+ it('injects exactly two seats: the settings.section panel + the input-bar session binder', () => {
72
+ const { declared, registrations } = collectRegistrations()
73
+ expect(declared).toEqual(['settings.section', 'conversation.input.left'])
74
+ expect(registrations).toHaveLength(2)
75
+ expect(registrations[0]!.slot).toBe('settings.section')
76
+ expect(registrations[1]!.slot).toBe('conversation.input.left')
77
+ })
78
+
79
+ it('no longer claims a shell.overlay float (the review panel it served is gone)', () => {
80
+ const { declared } = collectRegistrations()
81
+ expect(declared).not.toContain('shell.overlay')
82
+ })
83
+
84
+ it('pins the section identity (id/order/label/locale) and the panel component', () => {
85
+ const { registrations } = collectRegistrations()
86
+ const { options, component } = registrations[0]!
87
+ expect(options['id']).toBe('context-compression')
88
+ expect(options['order']).toBe(17)
89
+ expect(options['locale']).toBe('context-compression')
90
+ expect((options['label'] as () => string)()).toBe('nav')
91
+ expect(typeof options['inject']).toBe('function')
92
+ const face = (options['inject'] as () => Record<string, unknown>)()
93
+ expect(Object.keys(face).sort()).toEqual(['hooks', 'saveAutoCompact', 'saveCodeSkeleton', 'saveCustom', 'saveIntentSummary', 'saveMonitorPanel', 'savePresetOptions', 'select', 'resetCustom'].sort())
94
+ expect(component).toBe(ContextCompressionSettingsSection)
95
+ })
96
+
97
+ it('pins the input-bar binder: invisible component, inject captures the bare sessionId', () => {
98
+ const { registrations } = collectRegistrations()
99
+ const inputSeat = registrations[1]!
100
+ expect(inputSeat.options['id']).toBe('context-compression-session-bind')
101
+ expect(inputSeat.options['order']).toBe(170)
102
+ expect(typeof inputSeat.options['inject']).toBe('function')
103
+ const face = (inputSeat.options['inject'] as (sessionId: string) => Record<string, unknown>)('sess-42')
104
+ expect(face).toEqual({})
105
+ expect(inputSeat.component).toBeTypeOf('function')
106
+ })
107
+
108
+ it('never adds a Plugins-section card or tab alongside the standalone section', () => {
109
+ const { declared } = collectRegistrations()
110
+ expect(declared).not.toContain('settings.plugins.tab')
111
+ expect(declared).not.toContain('settings.plugin.item')
112
+ })
113
+
114
+ it('survives an older host that does not declare the seat, warning instead of crashing', () => {
115
+ // Cross-version tolerance: a host without this seat rejects the
116
+ // registration at the slot boundary. apply() must swallow that and warn —
117
+ // the historical failure mode was apply() bailing out, which silently took
118
+ // EVERY settings entry down with it.
119
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
120
+ try {
121
+ const { declared } = collectRegistrations({ registerThrows: true })
122
+ // It tried both seats (so the degradation is "loud", not a silent no-op)…
123
+ expect(declared).toEqual(['settings.section', 'conversation.input.left'])
124
+ // …and the rejection never escaped apply().
125
+ expect(warn).toHaveBeenCalled()
126
+ } finally {
127
+ warn.mockRestore()
128
+ }
129
+ })
130
+ })