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,204 +1,206 @@
1
- import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
- import { tmpdir } from 'node:os'
3
- import { dirname, join } from 'node:path'
4
- import { Context, Service } from '@deepseek-ai/cordis'
5
- import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
6
- import {
7
- SettingsProvider,
8
- settingsNamespace,
9
- type SettingsNamespace,
10
- } from '@deepseek-ai/dsh-settings'
11
- import { afterEach, describe, expect, it } from 'vitest'
12
- import { apply } from '../src/index.ts'
13
- import type { OverlayableAgentPresets } from '../src/preset-overlay.ts'
14
-
15
- let root: string | undefined
16
- let ctx: Context | undefined
17
-
18
- afterEach(async () => {
19
- await ctx?.fiber.dispose()
20
- ctx = undefined
21
- if (root !== undefined) await rm(root, { recursive: true, force: true })
22
- root = undefined
23
- })
24
-
25
- class MemorySettings extends SettingsProvider {
26
- readonly writable = true
27
- private readonly stored: Record<string, unknown> = {}
28
-
29
- protected load(): Promise<Record<string, unknown>> {
30
- return Promise.resolve(structuredClone(this.stored))
31
- }
32
-
33
- protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
34
- this.stored[ns] = structuredClone(section)
35
- return Promise.resolve()
36
- }
37
- }
38
-
39
- class FakeAgentPresets extends Service implements OverlayableAgentPresets {
40
- constructor(ctx: Context, readonly preset: AgentPreset) {
41
- super(ctx, 'agentPresets')
42
- }
43
-
44
- async resolve(): Promise<AgentPreset> {
45
- return this.preset
46
- }
47
-
48
- async mount(_agentCtx: unknown): Promise<AgentPreset> {
49
- return await this.resolve()
50
- }
51
-
52
- async recompose(_agentCtx: unknown, _id: string): Promise<AgentPreset> {
53
- return await this.resolve()
54
- }
55
-
56
- async standingKeyFor(): Promise<string> {
57
- return (await this.resolve()).path
58
- }
59
- }
60
-
61
- async function sourcePreset(): Promise<AgentPreset> {
62
- root = await mkdtemp(join(tmpdir(), 'dsh-selector-host-overlay-'))
63
- const path = join(root, 'standard', 'agent.cordis.yml')
64
- await mkdir(dirname(path), { recursive: true })
65
- await writeFile(path, "- id: persona\n name: '/opt/preset/persona.js'\n")
66
- return { id: 'standard', trust: 'system', path }
67
- }
68
-
69
- describe('context compression selector Host preset integration', () => {
70
- it('decorates native composition only for the lifetime of the selector fiber', async () => {
71
- const preset = await sourcePreset()
72
- ctx = new Context()
73
- await ctx.plugin(MemorySettings).await()
74
- await ctx.plugin(FakeAgentPresets, preset).await()
75
-
76
- const selector = ctx.plugin({ apply: (child) => {
77
- apply(child, { presetOverlay: true })
78
- } })
79
- await selector.await()
80
-
81
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
82
- const mounted = await service.mount({})
83
- expect(mounted.path).not.toBe(preset.path)
84
- expect(await readFile(mounted.path, 'utf8')).toContain('id: tool-result-pruner')
85
- expect((await service.resolve()).path).toBe(preset.path)
86
-
87
- await selector.dispose()
88
- expect((await service.mount({})).path).toBe(preset.path)
89
- })
90
-
91
- it('keeps settings and overlay alive across duplicate Host row disposal', async () => {
92
- const preset = await sourcePreset()
93
- ctx = new Context()
94
- await ctx.plugin(MemorySettings).await()
95
- await ctx.plugin(FakeAgentPresets, preset).await()
96
-
97
- const builtIn = ctx.plugin({ apply })
98
- await builtIn.await()
99
-
100
- const namespace = settingsNamespace('context-compression')
101
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
102
- expect((await service.mount({})).path).toBe(preset.path)
103
- expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
104
-
105
- await ctx.settings.update(namespace, { profile: 'cache-strict' })
106
- const selectedSettings = structuredClone(ctx.settings.get(namespace))
107
- expect(selectedSettings).toMatchObject({ profile: 'cache-strict' })
108
-
109
- const bundle = ctx.plugin({ apply: (child) => {
110
- apply(child, { presetOverlay: true })
111
- } })
112
- await bundle.await()
113
-
114
- const mounted = await service.mount({})
115
- expect(mounted.path).not.toBe(preset.path)
116
- expect((await service.recompose({}, 'standard')).path).toBe(mounted.path)
117
- expect(ctx.settings.get(namespace)).toEqual(selectedSettings)
118
- expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
119
-
120
- await builtIn.dispose()
121
- expect((await service.mount({})).path).toBe(mounted.path)
122
- expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
123
-
124
- await bundle.dispose()
125
- expect((await service.mount({})).path).toBe(preset.path)
126
- expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(0)
127
- })
128
-
129
- it('writes the saved Auto Compact threshold into the generated compaction-basic composition', async () => {
130
- const preset = await sourcePreset()
131
- ctx = new Context()
132
- await ctx.plugin(MemorySettings).await()
133
- await ctx.plugin(FakeAgentPresets, preset).await()
134
- // A settings-owning row must register the namespace before the update.
135
- await ctx.plugin({ apply }).await()
136
- const namespace = settingsNamespace('context-compression')
137
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
138
-
139
- const bundle = ctx.plugin({ apply: (child) => {
140
- apply(child, { presetOverlay: true })
141
- } })
142
- await bundle.await()
143
-
144
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
145
- const mounted = await service.mount({})
146
- const rendered = await readFile(mounted.path, 'utf8')
147
- expect(rendered).toContain('id: compaction-basic')
148
- expect(rendered).toContain('thresholdRatio: 0.73')
149
- // First-release retention stays pinned at 0.16 next to the threshold.
150
- expect(rendered).toContain('retainRatio: 0.16')
151
- // The SAME read feeds the runtime deployment config, so one generation
152
- // cannot split Auto Compact and micro compact across two thresholds.
153
- expect(rendered).toContain('id: tool-result-pruner')
154
- expect(rendered).toContain('autoCompactThresholdPercent: 73')
155
- await bundle.dispose()
156
- })
157
-
158
- it('defaults the generated threshold to 0.8 and keeps it absent from settings until saved', async () => {
159
- const preset = await sourcePreset()
160
- ctx = new Context()
161
- await ctx.plugin(MemorySettings).await()
162
- await ctx.plugin(FakeAgentPresets, preset).await()
163
-
164
- const bundle = ctx.plugin({ apply: (child) => {
165
- apply(child, { presetOverlay: true })
166
- } })
167
- await bundle.await()
168
-
169
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
170
- const rendered = await readFile((await service.mount({})).path, 'utf8')
171
- expect(rendered).toContain('thresholdRatio: 0.8')
172
- await bundle.dispose()
173
- })
174
-
175
- it('moves the standing composition generation when an equal-length threshold changes', async () => {
176
- const preset = await sourcePreset()
177
- ctx = new Context()
178
- await ctx.plugin(MemorySettings).await()
179
- await ctx.plugin(FakeAgentPresets, preset).await()
180
- // A settings-owning row must register the namespace before the update.
181
- await ctx.plugin({ apply }).await()
182
- const namespace = settingsNamespace('context-compression')
183
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
184
-
185
- const bundle = ctx.plugin({ apply: (child) => {
186
- apply(child, { presetOverlay: true })
187
- } })
188
- await bundle.await()
189
-
190
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
191
- const first = await service.mount({})
192
- expect(await readFile(first.path, 'utf8')).toContain('thresholdRatio: 0.7')
193
- expect(await service.standingKeyFor()).toBe(first.path)
194
-
195
- // Same character length, different content: the generated identity and
196
- // standing composition generation must both move to the new threshold.
197
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
198
- const second = await service.mount({})
199
- expect(second.path).not.toBe(first.path)
200
- expect(await readFile(second.path, 'utf8')).toContain('thresholdRatio: 0.8')
201
- expect(await service.standingKeyFor()).toBe(second.path)
202
- await bundle.dispose()
203
- })
204
- })
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { Context, Service } from '@deepseek-ai/cordis'
5
+ import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
6
+ import {
7
+ SettingsProvider,
8
+ type SettingsNamespace,
9
+ } from '@deepseek-ai/dsh-settings'
10
+ import { afterEach, describe, expect, it } from 'vitest'
11
+ import { apply } from '../src/index.ts'
12
+ import type { OverlayableAgentPresets } from '../src/preset-overlay.ts'
13
+
14
+ // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
15
+ const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
16
+
17
+ let root: string | undefined
18
+ let ctx: Context | undefined
19
+
20
+ afterEach(async () => {
21
+ await ctx?.fiber.dispose()
22
+ ctx = undefined
23
+ if (root !== undefined) await rm(root, { recursive: true, force: true })
24
+ root = undefined
25
+ })
26
+
27
+ class MemorySettings extends SettingsProvider {
28
+ readonly writable = true
29
+ private readonly stored: Record<string, unknown> = {}
30
+
31
+ protected load(): Promise<Record<string, unknown>> {
32
+ return Promise.resolve(structuredClone(this.stored))
33
+ }
34
+
35
+ protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
36
+ this.stored[ns] = structuredClone(section)
37
+ return Promise.resolve()
38
+ }
39
+ }
40
+
41
+ class FakeAgentPresets extends Service implements OverlayableAgentPresets {
42
+ constructor(ctx: Context, readonly preset: AgentPreset) {
43
+ super(ctx, 'agentPresets')
44
+ }
45
+
46
+ async resolve(): Promise<AgentPreset> {
47
+ return this.preset
48
+ }
49
+
50
+ async mount(_agentCtx: unknown): Promise<AgentPreset> {
51
+ return await this.resolve()
52
+ }
53
+
54
+ async recompose(_agentCtx: unknown, _id: string): Promise<AgentPreset> {
55
+ return await this.resolve()
56
+ }
57
+
58
+ async standingKeyFor(): Promise<string> {
59
+ return (await this.resolve()).path
60
+ }
61
+ }
62
+
63
+ async function sourcePreset(): Promise<AgentPreset> {
64
+ root = await mkdtemp(join(tmpdir(), 'dsh-selector-host-overlay-'))
65
+ const path = join(root, 'standard', 'agent.cordis.yml')
66
+ await mkdir(dirname(path), { recursive: true })
67
+ await writeFile(path, "- id: persona\n name: '/opt/preset/persona.js'\n")
68
+ return { id: 'standard', trust: 'system', path }
69
+ }
70
+
71
+ describe('context compression selector Host preset integration', () => {
72
+ it('decorates native composition only for the lifetime of the selector fiber', async () => {
73
+ const preset = await sourcePreset()
74
+ ctx = new Context()
75
+ await ctx.plugin(MemorySettings).await()
76
+ await ctx.plugin(FakeAgentPresets, preset).await()
77
+
78
+ const selector = ctx.plugin({ apply: (child) => {
79
+ apply(child, { presetOverlay: true })
80
+ } })
81
+ await selector.await()
82
+
83
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
84
+ const mounted = await service.mount({})
85
+ expect(mounted.path).not.toBe(preset.path)
86
+ expect(await readFile(mounted.path, 'utf8')).toContain('id: tool-result-pruner')
87
+ expect((await service.resolve()).path).toBe(preset.path)
88
+
89
+ await selector.dispose()
90
+ expect((await service.mount({})).path).toBe(preset.path)
91
+ })
92
+
93
+ it('keeps settings and overlay alive across duplicate Host row disposal', async () => {
94
+ const preset = await sourcePreset()
95
+ ctx = new Context()
96
+ await ctx.plugin(MemorySettings).await()
97
+ await ctx.plugin(FakeAgentPresets, preset).await()
98
+
99
+ const builtIn = ctx.plugin({ apply })
100
+ await builtIn.await()
101
+
102
+ const namespace = nsBrand('context-compression')
103
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
104
+ expect((await service.mount({})).path).toBe(preset.path)
105
+ expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
106
+
107
+ await ctx.settings.update(namespace, { profile: 'cache-strict' })
108
+ const selectedSettings = structuredClone(ctx.settings.get(namespace))
109
+ expect(selectedSettings).toMatchObject({ profile: 'cache-strict' })
110
+
111
+ const bundle = ctx.plugin({ apply: (child) => {
112
+ apply(child, { presetOverlay: true })
113
+ } })
114
+ await bundle.await()
115
+
116
+ const mounted = await service.mount({})
117
+ expect(mounted.path).not.toBe(preset.path)
118
+ expect((await service.recompose({}, 'standard')).path).toBe(mounted.path)
119
+ expect(ctx.settings.get(namespace)).toEqual(selectedSettings)
120
+ expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
121
+
122
+ await builtIn.dispose()
123
+ expect((await service.mount({})).path).toBe(mounted.path)
124
+ expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(1)
125
+
126
+ await bundle.dispose()
127
+ expect((await service.mount({})).path).toBe(preset.path)
128
+ expect(ctx.settings.describe().filter(row => row.ns === namespace)).toHaveLength(0)
129
+ })
130
+
131
+ it('writes the saved Auto Compact threshold into the generated compaction-basic composition', async () => {
132
+ const preset = await sourcePreset()
133
+ ctx = new Context()
134
+ await ctx.plugin(MemorySettings).await()
135
+ await ctx.plugin(FakeAgentPresets, preset).await()
136
+ // A settings-owning row must register the namespace before the update.
137
+ await ctx.plugin({ apply }).await()
138
+ const namespace = nsBrand('context-compression')
139
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
140
+
141
+ const bundle = ctx.plugin({ apply: (child) => {
142
+ apply(child, { presetOverlay: true })
143
+ } })
144
+ await bundle.await()
145
+
146
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
147
+ const mounted = await service.mount({})
148
+ const rendered = await readFile(mounted.path, 'utf8')
149
+ expect(rendered).toContain('id: compaction-basic')
150
+ expect(rendered).toContain('thresholdRatio: 0.73')
151
+ // First-release retention stays pinned at 0.16 next to the threshold.
152
+ expect(rendered).toContain('retainRatio: 0.16')
153
+ // The SAME read feeds the runtime deployment config, so one generation
154
+ // cannot split Auto Compact and micro compact across two thresholds.
155
+ expect(rendered).toContain('id: tool-result-pruner')
156
+ expect(rendered).toContain('autoCompactThresholdPercent: 73')
157
+ await bundle.dispose()
158
+ })
159
+
160
+ it('defaults the generated threshold to 0.8 and keeps it absent from settings until saved', async () => {
161
+ const preset = await sourcePreset()
162
+ ctx = new Context()
163
+ await ctx.plugin(MemorySettings).await()
164
+ await ctx.plugin(FakeAgentPresets, preset).await()
165
+
166
+ const bundle = ctx.plugin({ apply: (child) => {
167
+ apply(child, { presetOverlay: true })
168
+ } })
169
+ await bundle.await()
170
+
171
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
172
+ const rendered = await readFile((await service.mount({})).path, 'utf8')
173
+ expect(rendered).toContain('thresholdRatio: 0.8')
174
+ await bundle.dispose()
175
+ })
176
+
177
+ it('moves the standing composition generation when an equal-length threshold changes', async () => {
178
+ const preset = await sourcePreset()
179
+ ctx = new Context()
180
+ await ctx.plugin(MemorySettings).await()
181
+ await ctx.plugin(FakeAgentPresets, preset).await()
182
+ // A settings-owning row must register the namespace before the update.
183
+ await ctx.plugin({ apply }).await()
184
+ const namespace = nsBrand('context-compression')
185
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
186
+
187
+ const bundle = ctx.plugin({ apply: (child) => {
188
+ apply(child, { presetOverlay: true })
189
+ } })
190
+ await bundle.await()
191
+
192
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
193
+ const first = await service.mount({})
194
+ expect(await readFile(first.path, 'utf8')).toContain('thresholdRatio: 0.7')
195
+ expect(await service.standingKeyFor()).toBe(first.path)
196
+
197
+ // Same character length, different content: the generated identity and
198
+ // standing composition generation must both move to the new threshold.
199
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
200
+ const second = await service.mount({})
201
+ expect(second.path).not.toBe(first.path)
202
+ expect(await readFile(second.path, 'utf8')).toContain('thresholdRatio: 0.8')
203
+ expect(await service.standingKeyFor()).toBe(second.path)
204
+ await bundle.dispose()
205
+ })
206
+ })
@@ -0,0 +1,138 @@
1
+ /**
2
+ * 压缩监控浮动球(FAB)客户端单测——骨架来自 pm `d29bcb1^` 撤下的
3
+ * longtask-fab(计划 cci-monitor-fab task_3.1-3.4),数据层为注入依赖,
4
+ * 本文件自断言消费侧行为。真实时钟 + initialDelayMs=1,不用假时钟
5
+ * (jsdom × fake-timers 的 async advance 有已知坑)。
6
+ */
7
+ import { afterEach, describe, expect, it, vi } from 'vitest'
8
+ import { initMonitorFab, type MonitorFabDeps, type MonitorSnapshotPayload } from '../src/client/monitor-fab.ts'
9
+
10
+ const FAB_ID = 'dsh-cci-monitor-fab'
11
+
12
+ function snapshotPatch(patch: Partial<MonitorSnapshotPayload> = {}): MonitorSnapshotPayload {
13
+ return {
14
+ ok: true,
15
+ startedAt: new Date().toISOString(),
16
+ gross: { exact: 10_000, estimated: 0 },
17
+ offsets: { exact: 1_200, estimated: 0 },
18
+ net: { exact: 8_800, estimated: 0 },
19
+ usage: { requests: 5, cacheHitRate: 0.812 },
20
+ pricing: { currency: 'USD', actualCost: '0.12', estimatedSavedCost: '1.30' },
21
+ intent: { override: undefined, observedEnabled: false, gate: { floorFraction: 0.45, growthTokens: 50_000 }, lastFold: undefined },
22
+ recentOffsets: [{ component: 'fresh', tokens: 1_200 }],
23
+ sessionScope: null,
24
+ ...patch,
25
+ }
26
+ }
27
+
28
+ function makeDeps(patch: Partial<MonitorFabDeps> & { snapshots?: MonitorSnapshotPayload[] } = {}): MonitorFabDeps & {
29
+ snapshots: MonitorSnapshotPayload[]
30
+ overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
31
+ } {
32
+ const deps: MonitorFabDeps & {
33
+ snapshots: MonitorSnapshotPayload[]
34
+ overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
35
+ } = {
36
+ t: (key: string) => key,
37
+ sessionIdOf: () => undefined,
38
+ enabledOf: () => true,
39
+ fetchSnapshot: vi.fn(async () => deps.snapshots[deps.snapshots.length - 1]!),
40
+ applyOverride: vi.fn(async (_sessionId: string | undefined, action: 'on' | 'off' | 'clear') => {
41
+ deps.overrides.push({ sessionId: undefined, action })
42
+ }),
43
+ snapshots: [snapshotPatch()],
44
+ overrides: [],
45
+ initialDelayMs: 1,
46
+ }
47
+ return Object.assign(deps, patch)
48
+ }
49
+
50
+ /** 真实时钟下等条件成立(轮询 1ms 一轮,上限 500ms)。 */
51
+ async function waitFor(predicate: () => boolean): Promise<void> {
52
+ const deadline = Date.now() + 500
53
+ while (!predicate()) {
54
+ if (Date.now() > deadline) throw new Error('waitFor timeout')
55
+ await new Promise(resolve => setTimeout(resolve, 5))
56
+ }
57
+ }
58
+
59
+ afterEach(() => {
60
+ document.body.innerHTML = ''
61
+ localStorage.clear()
62
+ vi.restoreAllMocks()
63
+ })
64
+
65
+ describe('monitor fab (body-level overlay)', () => {
66
+ it('mounts idempotently — double init keeps a single FAB', () => {
67
+ const deps = makeDeps()
68
+ initMonitorFab(deps)
69
+ initMonitorFab(deps)
70
+ expect(document.querySelectorAll(`#${FAB_ID}`).length).toBe(1)
71
+ })
72
+
73
+ it('enabled gate hides the ball and suppresses polling', async () => {
74
+ const fetchSnapshot = vi.fn(async () => snapshotPatch())
75
+ initMonitorFab(makeDeps({ enabledOf: () => false, fetchSnapshot, initialDelayMs: 5 }))
76
+ const fab = document.getElementById(FAB_ID) as HTMLElement
77
+ await waitFor(() => fab.style.display === 'none')
78
+ expect(fetchSnapshot).not.toHaveBeenCalled()
79
+ })
80
+
81
+ it('enabled: ball visible, first tick renders the snapshot', async () => {
82
+ initMonitorFab(makeDeps())
83
+ const fab = document.getElementById(FAB_ID) as HTMLElement
84
+ await waitFor(() => fab.style.display === 'block')
85
+ const net = document.querySelector('[data-net]') as HTMLElement
86
+ expect(net.textContent).toBe('8,800')
87
+ expect(fab.classList.contains('lit')).toBe(false)
88
+ })
89
+
90
+ it('negative net lights the ball (负节省警示)', async () => {
91
+ initMonitorFab(makeDeps({ snapshots: [snapshotPatch({ net: { exact: -800, estimated: 0 } })] }))
92
+ await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
93
+ })
94
+
95
+ it('fetch failure flips the stale marker without throwing', async () => {
96
+ initMonitorFab(makeDeps({ fetchSnapshot: vi.fn(async () => { throw new Error('down') }) }))
97
+ await waitFor(() => document.querySelector('[data-stale]')?.classList.contains('show') === true)
98
+ })
99
+
100
+ it('override buttons drive applyOverride then refetch', async () => {
101
+ const deps = makeDeps()
102
+ initMonitorFab(deps)
103
+ await waitFor(() => (document.querySelector('[data-overoff]') as HTMLButtonElement)?.disabled === false)
104
+ ;(document.querySelector('[data-overoff]') as HTMLButtonElement).click()
105
+ await waitFor(() => deps.overrides.length === 1)
106
+ expect(deps.overrides).toEqual([{ sessionId: undefined, action: 'off' }])
107
+ await waitFor(() => (deps.fetchSnapshot as ReturnType<typeof vi.fn>).mock.calls.length >= 2)
108
+ })
109
+
110
+ it('灾难性遗忘区建议:点亮悬浮球并展示提示行', async () => {
111
+ const deps = makeDeps({
112
+ snapshots: [snapshotPatch({
113
+ net: { exact: 0, estimated: 0 },
114
+ context: { liveTokens: 90_000, contextWindow: 100_000, pct: 0.9 },
115
+ suggestion: { suggest: true, thresholdPct: 0.7, occupancyPct: 0.9 },
116
+ })],
117
+ })
118
+ initMonitorFab(deps)
119
+ await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
120
+ const hint = document.querySelector('[data-hint]') as HTMLElement
121
+ expect(hint.classList.contains('show')).toBe(true)
122
+ expect(hint.textContent).toBe('monitor.panel.suggest')
123
+ })
124
+
125
+ it('无建议时提示行隐藏', async () => {
126
+ initMonitorFab(makeDeps())
127
+ await waitFor(() => (document.querySelector('[data-net]') as HTMLElement).textContent !== '')
128
+ expect(document.querySelector('[data-hint]')?.classList.contains('show')).toBe(false)
129
+ })
130
+
131
+ it('position persists across drag-free re-init via localStorage', () => {
132
+ localStorage.setItem('dsh.cci.monitor.pos', JSON.stringify({ x: 40, y: 60 }))
133
+ initMonitorFab(makeDeps())
134
+ const fab = document.getElementById(FAB_ID) as HTMLElement
135
+ expect(fab.style.left).toBe('40px')
136
+ expect(fab.style.top).toBe('60px')
137
+ })
138
+ })