dsh-context-compression-improved 0.5.6 → 0.5.8

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 (183) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +323 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +163 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.d.ts +59 -0
  34. package/packages/selector/lib/client.js +1738 -10
  35. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  36. package/packages/selector/lib/index.d.ts +13 -1
  37. package/packages/selector/lib/index.js +295 -3
  38. package/packages/selector/lib/pruner.d.ts +65 -0
  39. package/packages/selector/lib/pruner.js +497 -262
  40. package/packages/selector/lib/style.css +88 -46
  41. package/packages/selector/package.json +114 -114
  42. package/packages/selector/screenshots.json +3 -3
  43. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  44. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  45. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  46. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  47. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  48. package/packages/selector/src/client/decode.ts +57 -49
  49. package/packages/selector/src/client/index.ts +240 -149
  50. package/packages/selector/src/client/locales/de.ts +141 -0
  51. package/packages/selector/src/client/locales/es.ts +141 -0
  52. package/packages/selector/src/client/locales/fr.ts +141 -0
  53. package/packages/selector/src/client/locales/it.ts +141 -0
  54. package/packages/selector/src/client/locales/ja.ts +141 -0
  55. package/packages/selector/src/client/locales/ko.ts +141 -0
  56. package/packages/selector/src/client/locales/ru.ts +141 -0
  57. package/packages/selector/src/client/locales.ts +282 -196
  58. package/packages/selector/src/client/monitor-fab.ts +336 -0
  59. package/packages/selector/src/client/preset-options.ts +88 -88
  60. package/packages/selector/src/client/savings-card.tsx +150 -0
  61. package/packages/selector/src/client/settings-section.tsx +140 -124
  62. package/packages/selector/src/css-modules.d.ts +6 -6
  63. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  64. package/packages/selector/src/estimator-catalog.ts +104 -104
  65. package/packages/selector/src/index.ts +673 -463
  66. package/packages/selector/src/invariant.ts +113 -113
  67. package/packages/selector/src/preset-overlay.ts +626 -626
  68. package/packages/selector/src/profiles.ts +431 -394
  69. package/packages/selector/src/pruner/content.ts +201 -201
  70. package/packages/selector/src/pruner/session.ts +94 -94
  71. package/packages/selector/src/pruner/state.ts +57 -50
  72. package/packages/selector/src/pruner/tuning.ts +23 -23
  73. package/packages/selector/src/pruner/types.ts +78 -78
  74. package/packages/selector/src/pruner.ts +2736 -2402
  75. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  76. package/packages/selector/src/runtime/audit.ts +303 -286
  77. package/packages/selector/src/runtime/config.ts +756 -706
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +436 -436
  82. package/packages/selector/src/runtime/monitor.ts +235 -0
  83. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  84. package/packages/selector/src/runtime/retrieve.ts +479 -457
  85. package/packages/selector/src/runtime/savings.ts +337 -0
  86. package/packages/selector/src/runtime/session-events.ts +30 -30
  87. package/packages/selector/src/runtime/summary-command.ts +127 -0
  88. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  89. package/packages/selector/src/runtime/token-count.ts +72 -72
  90. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  91. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  92. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  93. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  94. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  95. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  96. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  97. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  98. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  99. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  100. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  101. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  102. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  103. package/packages/selector/src/runtime/toolclass.ts +103 -103
  104. package/packages/selector/src/runtime/types.ts +365 -346
  105. package/packages/selector/src/runtime/value.ts +48 -48
  106. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  107. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  108. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  109. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  110. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -90
  111. package/packages/selector/tests/custom-contract.client.spec.ts +205 -204
  112. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  113. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  114. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  115. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  116. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  117. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -206
  118. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  119. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  120. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  121. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  122. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  123. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  124. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  125. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  126. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  127. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  128. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  129. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  130. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  131. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  132. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  133. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  134. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  135. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  136. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  137. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  138. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  139. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  140. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  141. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  142. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  143. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  144. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  145. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  146. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  147. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  148. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  149. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  150. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  151. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  152. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  153. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  154. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  155. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  156. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  157. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  158. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  159. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  160. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  161. package/packages/selector/tests/settings-seat.client.spec.ts +130 -118
  162. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  163. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  164. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  165. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  166. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  167. package/packages/selector/tsconfig.json +11 -11
  168. package/packages/selector/tsdown.client.config.ts +102 -102
  169. package/packages/selector/tsdown.config.ts +20 -20
  170. package/pnpm-workspace.yaml +66 -66
  171. package/scripts/capture-profile-baseline.mjs +42 -42
  172. package/scripts/generate-tokenizer-fixtures.py +81 -81
  173. package/scripts/generate-vision-fixtures.py +208 -208
  174. package/scripts/packed-components-smoke.mjs +732 -732
  175. package/scripts/packed-install-e2e.mjs +1273 -1273
  176. package/scripts/toolclass-corpus-replay.mjs +281 -281
  177. package/scripts/verify-release.mjs +318 -317
  178. package/tests/TEST_INVENTORY.md +41 -41
  179. package/tsconfig.base.json +18 -18
  180. package/tsconfig.json +7 -7
  181. package/tsconfig.tests.json +15 -15
  182. package/vitest.built.config.ts +9 -9
  183. package/vitest.config.ts +43 -43
@@ -1,1273 +1,1273 @@
1
- import { createHash } from 'node:crypto'
2
- import { spawn } from 'node:child_process'
3
- import { createReadStream } from 'node:fs'
4
- import { copyFile, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises'
5
- import { existsSync, readFileSync, readdirSync } from 'node:fs'
6
- import { createServer } from 'node:http'
7
- import { createRequire } from 'node:module'
8
- import { tmpdir } from 'node:os'
9
- import { basename, dirname, join } from 'node:path'
10
- import { Readable } from 'node:stream'
11
- import { fileURLToPath, pathToFileURL } from 'node:url'
12
-
13
- const root = fileURLToPath(new URL('..', import.meta.url))
14
- // Release mode (default) is fail-closed: the upgrade leg and the official
15
- // clean-harness lifecycle must both run to green or the gate exits non-zero.
16
- // Set DSH_E2E_MODE=dev for an offline smoke with explicit skip markers.
17
- const e2eMode = process.env.DSH_E2E_MODE === 'dev' ? 'dev' : 'release'
18
- const packages = [
19
- { directory: join(root, 'packages/selector') },
20
- ]
21
- // The full @deepseek-ai/* host closure (pinned in the workspace root manifest,
22
- // currently 0.1.5-rc.2): auto-installed peers must all resolve from the mock
23
- // registry, so the list must cover every peer the packed plugins and the
24
- // official packages declare.
25
- const rootManifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
26
- const officialHostPackages = Object.entries(rootManifest.devDependencies)
27
- .filter(([name]) => name.startsWith('@deepseek-ai/'))
28
- .map(([name, version]) => `${name}@${version}`)
29
-
30
- // Only the package-manager shims need a shell on Windows; every real executable
31
- // must be spawned directly, because cmd.exe re-parses arguments: `^` is its
32
- // escape character, so `HEAD^{tree}` reached git as `HEAD{tree}`, and a
33
- // multi-line `node -e` settings script was cut at its first newline into
34
- // `[eval]:1 const` / `SyntaxError: Unexpected end of input`. Both killed the
35
- // official-clone leg for reasons unrelated to what it asserts.
36
- const SHELL_COMMANDS = new Set(['npm', 'npm.cmd', 'pnpm', 'pnpm.cmd'])
37
- const usesShell = (command) => process.platform === 'win32' && SHELL_COMMANDS.has(command)
38
-
39
- const run = (command, args, options = {}) => new Promise((resolve, reject) => {
40
- const child = spawn(command, args, { stdio: 'inherit', shell: usesShell(command), ...options })
41
- child.once('error', reject)
42
- child.once('exit', (code, signal) => {
43
- if (code === 0) resolve()
44
- else reject(new Error(`${command} exited ${code ?? `from signal ${signal}`}`))
45
- })
46
- })
47
-
48
- const capture = (command, args, options = {}) => new Promise((resolve, reject) => {
49
- const child = spawn(command, args, { shell: usesShell(command), ...options, stdio: ['ignore', 'pipe', 'pipe'] })
50
- let stdout = ''
51
- let stderr = ''
52
- child.stdout.setEncoding('utf8')
53
- child.stderr.setEncoding('utf8')
54
- child.stdout.on('data', chunk => { stdout += chunk })
55
- child.stderr.on('data', chunk => { stderr += chunk })
56
- child.once('error', reject)
57
- child.once('exit', (code, signal) => {
58
- if (code === 0) resolve({ stdout, stderr })
59
- else reject(new Error([
60
- `${command} exited ${code ?? `from signal ${signal}`}`,
61
- stdout.trim(),
62
- stderr.trim(),
63
- ].filter(Boolean).join('\n')))
64
- })
65
- })
66
-
67
- const captureOutcome = (command, args, options = {}) => new Promise((resolve, reject) => {
68
- const child = spawn(command, args, { shell: usesShell(command), ...options, stdio: ['ignore', 'pipe', 'pipe'] })
69
- let stdout = ''
70
- let stderr = ''
71
- child.stdout.setEncoding('utf8')
72
- child.stderr.setEncoding('utf8')
73
- child.stdout.on('data', chunk => { stdout += chunk })
74
- child.stderr.on('data', chunk => { stderr += chunk })
75
- child.once('error', reject)
76
- child.once('exit', (code, signal) => resolve({ code, signal, stdout, stderr }))
77
- })
78
-
79
- const allocateLoopbackPort = () => new Promise((resolve, reject) => {
80
- const server = createServer()
81
- server.once('error', reject)
82
- server.listen(0, '127.0.0.1', () => {
83
- const address = server.address()
84
- if (address === null || typeof address === 'string') {
85
- server.close(() => reject(new Error('could not allocate a loopback port for the official profile probe')))
86
- return
87
- }
88
- server.close(error => error === undefined ? resolve(address.port) : reject(error))
89
- })
90
- })
91
-
92
- const assert = (condition, message) => {
93
- if (!condition) throw new Error(`packed Host smoke: ${message}`)
94
- }
95
-
96
- async function scanPublishedTree(packageRoot) {
97
- const pending = [packageRoot]
98
- const violations = []
99
- const forbidden = [
100
- { label: 'developer absolute path', pattern: /(?:\/home\/|[A-Za-z]:\\Users\\)/u },
101
- { label: 'OpenAI-style secret', pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/u },
102
- { label: 'NPM token', pattern: /\bnpm_[A-Za-z0-9]{20,}\b/u },
103
- { label: 'GitHub token', pattern: /\b(?:ghp_|github_pat_)[A-Za-z0-9_]{20,}\b/u },
104
- { label: 'assigned DeepSeek API key', pattern: /DEEPSEEK_API_KEY\s*=\s*[^\s"']+/u },
105
- ]
106
- while (pending.length > 0) {
107
- const directory = pending.pop()
108
- for (const entry of await readdir(directory, { withFileTypes: true })) {
109
- const path = join(directory, entry.name)
110
- if (entry.isDirectory()) {
111
- pending.push(path)
112
- continue
113
- }
114
- if (!/\.(?:js|d\.ts|json|md|ya?ml|txt)$/u.test(entry.name)
115
- || entry.name === 'tokenizer.json') continue
116
- const text = await readFile(path, 'utf8')
117
- for (const rule of forbidden) {
118
- if (rule.pattern.test(text)) violations.push(`${path}: ${rule.label}`)
119
- }
120
- }
121
- }
122
- if (violations.length > 0) throw new Error(`packed content scan failed:\n${violations.join('\n')}`)
123
- }
124
-
125
- async function runPackedHostSmoke(consumerRoot) {
126
- const consumerRequire = createRequire(join(consumerRoot, 'package.json'))
127
- const load = async specifier => import(pathToFileURL(consumerRequire.resolve(specifier)).href)
128
- const [
129
- cordis,
130
- groupModule,
131
- includeModule,
132
- loaderModule,
133
- agentModule,
134
- agentLoopModule,
135
- presetsModule,
136
- commandsModule,
137
- llmModule,
138
- sessionModule,
139
- scopeModule,
140
- settingsModule,
141
- systemPromptModule,
142
- sessionProjectionModule,
143
- tokenMeterModule,
144
- toolsModule,
145
- selectorModule,
146
- ] = await Promise.all([
147
- load('@deepseek-ai/cordis'),
148
- load('@deepseek-ai/cordis-plugin-group'),
149
- load('@deepseek-ai/cordis-plugin-include'),
150
- load('@deepseek-ai/cordis-plugin-loader'),
151
- load('@deepseek-ai/dsh-agent'),
152
- load('@deepseek-ai/dsh-agent-loop'),
153
- load('@deepseek-ai/dsh-agent-presets'),
154
- load('@deepseek-ai/dsh-commands'),
155
- load('@deepseek-ai/dsh-llm'),
156
- load('@deepseek-ai/dsh-session'),
157
- load('@deepseek-ai/dsh-scope'),
158
- load('@deepseek-ai/dsh-settings'),
159
- load('@deepseek-ai/dsh-system-prompt'),
160
- load('@deepseek-ai/dsh-session-projection'),
161
- load('@deepseek-ai/dsh-token-meter'),
162
- load('@deepseek-ai/dsh-tools'),
163
- load('dsh-context-compression-improved'),
164
- ])
165
-
166
- class MemorySettings extends settingsModule.SettingsProvider {
167
- writable = true
168
-
169
- load() {
170
- return Promise.resolve({})
171
- }
172
-
173
- persist() {
174
- return Promise.resolve()
175
- }
176
- }
177
-
178
- const presetRoot = join(consumerRoot, 'preset-fixtures')
179
- await mkdir(presetRoot)
180
- const marker = join(presetRoot, 'marker.mjs')
181
- await writeFile(marker, 'export function apply() {}\n')
182
- const source = `- id: source-marker\n name: ${JSON.stringify(marker)}\n`
183
- for (const id of ['standard', 'custom', 'minimal']) {
184
- const directory = join(presetRoot, id)
185
- await mkdir(directory)
186
- await writeFile(join(directory, presetsModule.COMPOSITION_FILE), source)
187
- }
188
-
189
- const runtime = new cordis.Context()
190
- try {
191
- runtime.baseUrl = `${pathToFileURL(presetRoot).href}/`
192
- await runtime.plugin(loaderModule.default).await()
193
- runtime.loader.builtins.include = includeModule.default
194
- runtime.loader.builtins.group = groupModule.default
195
- await runtime.plugin(llmModule.default).await()
196
- await runtime.plugin(sessionModule.default).await()
197
- await runtime.plugin(systemPromptModule.default, { personaPrefix: '' }).await()
198
- await runtime.plugin(toolsModule.default).await()
199
- await runtime.plugin(agentModule.default).await()
200
- await runtime.plugin(agentLoopModule.default, { agents: [] }).await()
201
- await runtime.plugin(commandsModule.default).await()
202
- await runtime.plugin(sessionProjectionModule.default).await()
203
- await runtime.plugin(tokenMeterModule.default).await()
204
- await runtime.plugin(MemorySettings).await()
205
- await runtime.plugin(presetsModule.default, {
206
- default: 'standard',
207
- roots: [{ path: presetRoot, trust: 'system' }],
208
- includeShippedRoot: false,
209
- includeUserRoot: false,
210
- }).await()
211
- await runtime.plugin({
212
- apply: selectorCtx => selectorModule.apply(selectorCtx, { presetOverlay: true }),
213
- }).await()
214
-
215
- const createAgent = async (sessionId, preset) => {
216
- const handle = await runtime.agents.create({
217
- sessionId: sessionModule.SessionId(sessionId),
218
- setup: async agentCtx => void await runtime.agentPresets.mount(agentCtx, preset),
219
- })
220
- return handle.agent
221
- }
222
- const hasRetrieve = agent => runtime.tools.get(
223
- 'context_compression_retrieve',
224
- scopeModule.scopeOf(agent.ctx),
225
- ) !== undefined
226
- const hasCompact = agent => runtime.commands.list(agent)
227
- .some(command => command.name === 'compact')
228
- const hasCompleteStack = agent =>
229
- runtime.agentPresets.serviceFor(agent, 'toolResultPruner') !== undefined
230
- && runtime.agentPresets.serviceFor(agent, 'compaction') !== undefined
231
- && hasRetrieve(agent)
232
- && hasCompact(agent)
233
- const hasNoStack = agent =>
234
- runtime.agentPresets.serviceFor(agent, 'toolResultPruner') === undefined
235
- && runtime.agentPresets.serviceFor(agent, 'compaction') === undefined
236
- && !hasRetrieve(agent)
237
- && !hasCompact(agent)
238
-
239
- const sourcePreset = await runtime.agentPresets.resolve('standard')
240
- const sourceText = await runtime.agentPresets.read('standard')
241
- const agent = await createAgent('packed-host-standard', 'standard')
242
- assert(hasCompleteStack(agent), 'standard preset did not mount the complete compression stack')
243
- assert((await runtime.agentPresets.resolve('standard')).path === sourcePreset.path,
244
- 'overlay changed the source preset path')
245
- assert(await runtime.agentPresets.read('standard') === sourceText,
246
- 'overlay changed the source preset contents')
247
- assert(!sourceText.includes('tool-result-pruner'), 'source preset was mutated')
248
-
249
- await runtime.agentPresets.recompose(agent.ctx, 'minimal')
250
- assert(hasNoStack(agent), 'exact Minimal preset retained compression')
251
- await runtime.agentPresets.recompose(agent.ctx, 'custom')
252
- assert(hasCompleteStack(agent), 'compression did not return after leaving Minimal')
253
-
254
- const parent = await createAgent('packed-host-parent', 'standard')
255
- const childHandle = await runtime.agents.create({
256
- sessionId: sessionModule.SessionId('packed-host-child'),
257
- setup: childCtx => void runtime.agentPresets.composeFrom(childCtx, parent.ctx),
258
- })
259
- const child = childHandle.agent
260
- const original = Symbol.for('cordis.original')
261
- const parentPruner = runtime.agentPresets.serviceFor(parent, 'toolResultPruner')
262
- const childPruner = runtime.agentPresets.serviceFor(child, 'toolResultPruner')
263
- const parentCompaction = runtime.agentPresets.serviceFor(parent, 'compaction')
264
- const childCompaction = runtime.agentPresets.serviceFor(child, 'compaction')
265
- assert(parentPruner !== undefined && childPruner !== undefined,
266
- 'parent or child pruner is missing')
267
- assert(parentCompaction !== undefined && childCompaction !== undefined,
268
- 'parent or child compaction engine is missing')
269
- assert(Object.is(childPruner[original], parentPruner[original]),
270
- 'child did not inherit the parent pruner instance')
271
- assert(Object.is(childCompaction[original], parentCompaction[original]),
272
- 'child did not inherit the parent compaction instance')
273
- assert(hasRetrieve(child) && hasCompact(child),
274
- 'child lacks the inherited retrieve tool or compact command')
275
-
276
- const namespace = 'context-compression'
277
- const settings = runtime.settings.get(namespace)
278
- assert(settings.custom.history.trigger === 500_000,
279
- 'packed Host did not expose the 500000 History default')
280
- assert(settings.custom.tailTrim.enabled === false && settings.custom.tailTrim.trigger === 700_000,
281
- 'packed Host did not expose disabled TailTrim at 700000')
282
-
283
- return {
284
- officialHostPackages: officialHostPackages.length,
285
- standardPreset: 'complete-stack',
286
- minimalPreset: 'no-stack',
287
- postMinimalPreset: 'complete-stack',
288
- childServices: 'same-parent-instances',
289
- sourcePreset: 'unchanged',
290
- defaults: { history: 500_000, tailTrim: { enabled: false, trigger: 700_000 } },
291
- }
292
- } finally {
293
- await runtime.fiber.dispose()
294
- }
295
- }
296
-
297
- async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, candidateVersion) {
298
- const clone = await realpath(referenceRoot)
299
- const git = async (...args) => (await capture('git', args, { cwd: clone })).stdout.trim()
300
- const before = {
301
- tag: await git('describe', '--tags', '--exact-match'),
302
- commit: await git('rev-parse', 'HEAD'),
303
- tree: await git('rev-parse', 'HEAD^{tree}'),
304
- status: await git('status', '--porcelain'),
305
- }
306
- assert(before.tag === 'dsh-v0.1.5-rc.2', `official clone tag is ${before.tag}`)
307
- assert(before.commit === 'fb2c4b9e698e30edb738bca4cf0618587db7d203',
308
- `official clone commit is ${before.commit}`)
309
- assert(before.tree === 'bd7dd6d90010a35d3d6ff9f12c1f6207d5b6fe38',
310
- `official clone tree is ${before.tree}`)
311
- assert(before.status === '', 'official clone is dirty before CLI smoke')
312
-
313
- const temporaryRoot = await mkdtemp(join(tmpdir(), 'dsh-selector-official-clone-'))
314
- const worktree = join(temporaryRoot, 'official')
315
- const dshHome = join(temporaryRoot, 'dsh-home')
316
- let added = false
317
- const environment = { ...process.env, DSH_HOME: dshHome }
318
- let lastLifecycle = { command: '(none)', code: 0, stdout: '', stderr: '' }
319
- // Positive controls for the CLI invocation path (issue #2). Declared at
320
- // function scope so the failure evidence can always report them, and assigned
321
- // once the clone checkout exists (spawn needs `cwd: worktree` to resolve).
322
- let scriptLayerControl = { code: null, stdout: '', stderr: '' }
323
- let directEntryControl = { code: null, stdout: '', stderr: '' }
324
- /** Path of the tiny runner that invokes the CLI's exported entry (see below). */
325
- let cliRunnerPath = null
326
- /**
327
- * Run the clone's CLI.
328
- *
329
- * Measured root cause of issue #2: the pinned clone's `apps/cli/src/bin.ts`
330
- * dispatches through `if (import.meta.main) { await runCli() }`, and under
331
- * tsx that flag evaluates falsy — so the module loads and does NOTHING. Both
332
- * `pnpm dsh …` (the clone's own `dsh` script) and a direct
333
- * `node --import tsx/esm apps/cli/src/bin.ts …` therefore exit 0 with empty
334
- * output, which is exactly what the two positive controls report. The leg
335
- * calls the CLI's EXPORTED entry instead, with argv shaped the way the entry
336
- * would see it, so the lifecycle exercises the CLI rather than the loader's
337
- * handling of a self-execution guard.
338
- */
339
- const dsh = async (...args) => {
340
- if (cliRunnerPath === null) throw new Error('e2e: the CLI runner probe was not prepared')
341
- const outcome = await captureOutcome(
342
- process.execPath,
343
- ['--import', 'tsx/esm', cliRunnerPath, ...args],
344
- { cwd: worktree, env: environment },
345
- )
346
- lastLifecycle = {
347
- command: `dsh ${args.join(' ')}`,
348
- code: outcome.code ?? -1,
349
- stdout: outcome.stdout,
350
- stderr: outcome.stderr,
351
- }
352
- if (outcome.code !== 0) {
353
- throw new Error([
354
- `${lastLifecycle.command} exited ${String(lastLifecycle.code)}`,
355
- outcome.stdout.trim(),
356
- outcome.stderr.trim(),
357
- ].filter(Boolean).join('\n'))
358
- }
359
- }
360
- const dumpConfig = () => capture(
361
- process.execPath,
362
- ['--import', 'tsx/esm', cliRunnerPath, '--profile', 'web', '--dump-config'],
363
- {
364
- cwd: worktree,
365
- env: environment,
366
- },
367
- ).then(captured => captured.stdout)
368
-
369
- /** Installed manifest of the profile-resolved plugin package. */
370
- const profilePackages = () => {
371
- const profileRoot = join(dshHome, 'profiles/web')
372
- const profileRequire = createRequire(join(profileRoot, 'package.json'))
373
- let selectorPath
374
- try {
375
- selectorPath = profileRequire.resolve('dsh-context-compression-improved/package.json')
376
- } catch (error) {
377
- // A silent no-op lifecycle command is the difference between "the package
378
- // manager refused" and "the CLI exited 0 without installing anything";
379
- // carry that evidence instead of a bare MODULE_NOT_FOUND.
380
- const declared = (() => {
381
- try {
382
- return JSON.stringify(JSON.parse(readFileSync(join(profileRoot, 'package.json'), 'utf8')).dependencies ?? {})
383
- } catch {
384
- return '(profile package.json unreadable)'
385
- }
386
- })()
387
- const installed = (() => {
388
- try {
389
- return JSON.stringify(readdirSync(join(profileRoot, 'node_modules')).slice(0, 40))
390
- } catch {
391
- return '(profiles/web/node_modules unreadable)'
392
- }
393
- })()
394
- throw new Error([
395
- `official profile ${profileRoot} does not resolve dsh-context-compression-improved`,
396
- `last lifecycle: ${lastLifecycle.command} (exit ${String(lastLifecycle.code)})`,
397
- `lifecycle stdout: ${lastLifecycle.stdout.trim()}`,
398
- `lifecycle stderr: ${lastLifecycle.stderr.trim()}`,
399
- // Positive controls: see the comment where they are captured (issue #2).
400
- `control script-layer (pnpm dsh --version): exit ${String(scriptLayerControl.code)} out=${scriptLayerControl.stdout.trim()} err=${scriptLayerControl.stderr.trim()}`,
401
- `control direct-entry (tsx bin.ts --version): exit ${String(directEntryControl.code)} out=${directEntryControl.stdout.trim()} err=${directEntryControl.stderr.trim()}`,
402
- `profile dependencies: ${declared}`,
403
- `profiles/web/node_modules: ${installed}`,
404
- ].join('\n'), { cause: error })
405
- }
406
- return {
407
- profileRoot,
408
- selectorPath,
409
- selector: JSON.parse(readFileSync(selectorPath, 'utf8')),
410
- }
411
- }
412
-
413
- /**
414
- * Host-plane runtime entries of the installed package. `client.js` is
415
- * excluded: it is a lazy-CJS web artifact whose requires (`react`, the
416
- * ui-slot packages) the web bundler supplies, and that stack is verified
417
- * from the built client libraries below.
418
- */
419
- const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'advisor-state.js', 'tail-trim.js', 'invariant.js']
420
-
421
- /**
422
- * Bare package names the installed package's host-plane runtime files import.
423
- *
424
- * The runtime directory is read off the INSTALLED manifest's own `main` rather
425
- * than assumed: the tarball this gate packs is `packages/selector` (`main`
426
- * `lib/index.js`), while the published root manifest points at
427
- * `packages/selector/lib/index.js`. Guessing either one read the wrong tree
428
- * and failed closed on an ENOENT that said nothing about the plugin.
429
- *
430
- * @param selectorDir - Installed directory of the plugin package.
431
- * @param selectorManifest - The installed manifest, for its `main` field.
432
- * @returns The package roots the host must be able to resolve.
433
- */
434
- const hostPlaneRuntimeImports = async (selectorDir, selectorManifest) => {
435
- const main = selectorManifest?.main
436
- if (typeof main !== 'string' || main.length === 0) {
437
- throw new Error(`installed package declares no main entry: ${JSON.stringify(selectorManifest?.main)}`)
438
- }
439
- const runtimeDir = dirname(join(selectorDir, main))
440
- if (!existsSync(runtimeDir)) {
441
- throw new Error(`installed package main ${main} points at a directory that is not in the tarball: ${runtimeDir}`)
442
- }
443
- const names = new Set()
444
- for (const entry of HOST_PLANE_ENTRIES) {
445
- const source = await readFile(join(runtimeDir, entry), 'utf8')
446
- for (const match of source.matchAll(/(?:^|[^.\w])(?:import|export)\s[^;]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])(?:import|require)\s*\(\s*['"]([^'"]+)['"]\s*\)/gmu)) {
447
- const specifier = match[1] ?? match[2]
448
- if (specifier.startsWith('.') || specifier.startsWith('node:')) continue
449
- names.add(specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/'))
450
- }
451
- }
452
- if (names.size === 0) throw new Error('installed package exposes no host-plane runtime import to verify')
453
- return names
454
- }
455
-
456
- /**
457
- * Verify every web/client peer exists as a BUILT artifact resolvable from
458
- * the packages that depend on it. Executable loading of the client stack
459
- * happens under the web bundler, not bare Node (the UI packages ship CSS
460
- * modules only a bundler can import): that load leg is the `build:web`
461
- * step of the worktree's `pnpm run build` above, which fails closed when
462
- * the client graph is broken.
463
- */
464
- const proveBuiltClientPeersLoad = async () => {
465
- const clientPeers = [
466
- '@deepseek-ai/dsh-client-locale',
467
- '@deepseek-ai/dsh-client-store',
468
- '@deepseek-ai/dsh-client-ui-primitives',
469
- '@deepseek-ai/dsh-client-ui-settings',
470
- '@deepseek-ai/dsh-client-ui-slots',
471
- '@deepseek-ai/dsh-client-ui-workspace',
472
- 'react',
473
- ]
474
- // pnpm's isolated layout keeps each package's dependents in ITS own
475
- // node_modules, so anchor resolution at the packages that actually
476
- // depend on the client stack: the web-app bundle (locale, store,
477
- // ui-settings, ui-workspace), the client-locale package (react,
478
- // ui-primitives, ui-slots), and the web app.
479
- const anchors = JSON.stringify([
480
- join(worktree, 'packages/bundle/web-app/package.json'),
481
- join(worktree, 'packages/client/locale/package.json'),
482
- join(worktree, 'apps/web/package.json'),
483
- ])
484
- const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', [
485
- "const { createRequire } = require('node:module')",
486
- `const anchors = ${anchors}.map(path => createRequire(path))`,
487
- `for (const peer of ${JSON.stringify(clientPeers)}) {`,
488
- ' const resolved = anchors.some(requireFrom => {',
489
- ' try { requireFrom.resolve(peer); return true } catch { return false }',
490
- ' })',
491
- " if (!resolved) throw new Error('built client peer resolved from no dependent package: ' + peer)",
492
- '}',
493
- "console.log('CLIENT_PEERS_OK')",
494
- ].join('\n')], { cwd: worktree, env: environment })
495
- if (outcome.code !== 0 || !outcome.stdout.includes('CLIENT_PEERS_OK')) {
496
- throw new Error(`built client peers failed to resolve in the official worktree:\n${outcome.stdout}\n${outcome.stderr}`)
497
- }
498
- return clientPeers.length
499
- }
500
-
501
- /**
502
- * Prove the plugin actually loads in the official profile: pnpm's peers check
503
- * cannot see the healed profiles/node_modules fallback by design, so the
504
- * release gate resolves and imports instead. Fail-closed parts:
505
- *
506
- * - every bare specifier the HOST-plane runtime files import must resolve from
507
- * the profile. That set is DERIVED from the installed artifact rather than
508
- * listed by hand: 0.5.3 imported `@deepseek-ai/schemastery` while declaring
509
- * it in no manifest a consumer reads, and a hand-maintained whitelist plus a
510
- * hand-maintained dependency list could not see it;
511
- * - every declared runtime dependency must resolve (the install surface);
512
- * - the node entry must import and export a callable `apply()`;
513
- * - a declared peer may stay unresolved only when no host-plane file imports
514
- * it — the web-host client packages are supplied by the web app, and their
515
- * built libraries are verified separately below.
516
- */
517
- const provePluginLoads = async () => {
518
- const { profileRoot, selectorPath, selector } = profilePackages()
519
- const selectorPeers = Object.keys(selector.peerDependencies ?? {})
520
- const selectorDependencies = Object.keys(selector.dependencies ?? {})
521
- const runtimeImports = [...await hostPlaneRuntimeImports(dirname(selectorPath), selector)].sort()
522
- const required = [...new Set([...runtimeImports, ...selectorDependencies])].sort()
523
- const script = [
524
- "const { createRequire } = require('node:module')",
525
- `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
526
- `for (const name of ${JSON.stringify(required)}) {`,
527
- ' requireFromProfile.resolve(name)',
528
- '}',
529
- "const selectorEntry = requireFromProfile.resolve('dsh-context-compression-improved')",
530
- 'const plugin = require(selectorEntry)',
531
- "if (typeof plugin.apply !== 'function') throw new Error('selector entry exports no apply()')",
532
- 'const unresolvedPeers = []',
533
- `for (const peer of ${JSON.stringify(selectorPeers)}) {`,
534
- ' try { requireFromProfile.resolve(peer) } catch { unresolvedPeers.push(peer) }',
535
- '}',
536
- "console.log('LOAD_OK ' + JSON.stringify(unresolvedPeers))",
537
- ].join('\n')
538
- const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
539
- cwd: worktree,
540
- env: environment,
541
- })
542
- const marker = outcome.stdout.split('\n').find(line => line.startsWith('LOAD_OK'))
543
- if (outcome.code !== 0 || marker === undefined) {
544
- throw new Error(`official profile failed to load the plugin, its host-plane imports and its engine peers:\n${outcome.stdout}\n${outcome.stderr}`)
545
- }
546
- const unresolvedPeers = JSON.parse(marker.slice('LOAD_OK '.length))
547
- const importedWithoutProvider = unresolvedPeers.filter(peer => runtimeImports.includes(peer))
548
- if (importedWithoutProvider.length > 0) {
549
- throw new Error(`selector peers the host-plane runtime imports did not resolve from the profile: ${importedWithoutProvider.join(', ')}`)
550
- }
551
- return {
552
- hostPlaneRuntimeImports: runtimeImports,
553
- installedRuntimeDependencies: selectorDependencies,
554
- unresolvedSelectorPeers: unresolvedPeers,
555
- builtClientPeersVerified: await proveBuiltClientPeersLoad(),
556
- }
557
- }
558
-
559
- /**
560
- * Boot the official profile FOR REAL through the CLI's own profile-boot
561
- * path — not --dump-config, which composes YAML without booting or
562
- * executing plugins. The probe mounts the full bundle tree (selector
563
- * included), then proves: the settings service resolves the registered
564
- * document (before the upgrade: the previous release's schema defaults;
565
- * after: the seeded savings/73 document parsed with the INSTALLED runtime),
566
- * the AgentPresets service composed the selector's standing overlay, and
567
- * the overlay's generated composition exists with the deterministic
568
- * identity filename. Any failure exits non-zero.
569
- */
570
- const runProfileBootProbe = async (phase, expectSeeded) => {
571
- const profilePort = await allocateLoopbackPort()
572
- const { profileRoot } = profilePackages()
573
- const settingsProof = expectSeeded
574
- ? [
575
- ' const requireFromProfile = createRequire(profileRoot)',
576
- " const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
577
- ' const plugin = requireFromProfile(pluginEntry)',
578
- ' const parsed = plugin.parseContextCompressionSettings(structuredClone(raw))',
579
- " if (parsed.profile !== 'savings' || parsed.autoCompact.thresholdPercent !== 73) {",
580
- " throw new Error('boot probe: booted settings did not expose the seeded document: ' + JSON.stringify(parsed))",
581
- ' }',
582
- ]
583
- : [
584
- // The previous release predates the autoCompact section and the
585
- // public parser; prove its OWN schema resolved the registered
586
- // namespace into a complete supported document instead.
587
- " if (raw?.profile !== 'balanced' || raw?.custom?.version !== 3) {",
588
- " throw new Error('boot probe: previous-release settings defaults did not resolve: ' + JSON.stringify(raw))",
589
- ' }',
590
- ]
591
- const probe = [
592
- "import { readdir } from 'node:fs/promises'",
593
- "import { tmpdir } from 'node:os'",
594
- "import { join } from 'node:path'",
595
- "import { createRequire } from 'node:module'",
596
- "import { pathToFileURL } from 'node:url'",
597
- `const worktree = String.raw\`${worktree}\``,
598
- `const profileRoot = String.raw\`${join(profileRoot, 'package.json')}\``,
599
- 'const bootModule = await import(pathToFileURL(join(worktree, \'apps/cli/src/profile-boot.ts\')).href)',
600
- // Import the workspace packages from their source trees (pinned, like
601
- // the profile-boot path above): the probe runs under tsx, and their
602
- // lib/ artifacts are only produced by the full release build, not the
603
- // library faces.
604
- "const appBoot = await import(pathToFileURL(join(worktree, 'packages/boot/app-boot/src/index.ts')).href)",
605
- "const settingsModule = await import(pathToFileURL(join(worktree, 'packages/settings/settings/src/index.ts')).href)",
606
- 'const preBootStores = new Set(await readdir(tmpdir()))',
607
- 'const { ctx } = await bootModule.runProfile({',
608
- " environment: appBoot.loadLayeredEnv('dsh'),",
609
- " profile: 'web',",
610
- ' patchFiles: [],',
611
- ` args: ['--host', '127.0.0.1', '--port', ${JSON.stringify(String(profilePort))}, '--no-open'],`,
612
- '})',
613
- 'try {',
614
- " const settings = ctx.get('settings')",
615
- " if (settings === undefined) throw new Error('boot probe: settings service missing')",
616
- " const raw = settings.get('context-compression')",
617
- ...settingsProof,
618
- " const presets = ctx.get('agentPresets')",
619
- " if (presets === undefined) throw new Error('boot probe: agentPresets service missing')",
620
- ' const key = await presets.standingKeyFor()',
621
- ' if (key?.agentPreset !== \'standard\') {',
622
- " throw new Error('boot probe: standing key did not compose the default preset: ' + JSON.stringify(key))",
623
- ' }',
624
- // Only stores CREATED BY THIS BOOT count: stale leftovers from earlier
625
- // runs or concurrent harnesses must never satisfy the overlay proof.
626
- ' const generated = []',
627
- " for (const entry of await readdir(tmpdir(), { withFileTypes: true })) {",
628
- ' if (!entry.isDirectory() || preBootStores.has(entry.name)) continue',
629
- " if (!entry.name.startsWith('dsh-context-compression-presets-')) continue",
630
- ' let children',
631
- ' try {',
632
- ' children = await readdir(join(tmpdir(), entry.name))',
633
- ' } catch {',
634
- ' continue // a concurrent process disposed its store mid-scan',
635
- ' }',
636
- " for (const child of children) {",
637
- " if (/^standard-[0-9a-f]{24}\\.agent\\.cordis\\.yml$/u.test(child)) generated.push(child)",
638
- ' }',
639
- ' }',
640
- ' if (generated.length === 0) {',
641
- " throw new Error('boot probe: the selector preset overlay generated no standing composition in this boot')",
642
- ' }',
643
- " console.log('BOOT_PROBE_OK ' + JSON.stringify({ phase: " + JSON.stringify(phase) + ", settings: " + JSON.stringify(expectSeeded ? 'seeded-savings-73' : 'previous-release-defaults') + ", generated: generated.length }))",
644
- '} finally {',
645
- ' await ctx.fiber.dispose()',
646
- '}',
647
- 'process.exit(0)',
648
- ].join('\n')
649
- const probePath = join(temporaryRoot, `boot-probe-${phase}.mjs`)
650
- await writeFile(probePath, probe, 'utf8')
651
- const outcome = await captureOutcome(process.execPath, ['--import', 'tsx/esm', probePath], {
652
- cwd: worktree,
653
- env: environment,
654
- })
655
- const marker = outcome.stdout.split('\n').find(line => line.startsWith('BOOT_PROBE_OK'))
656
- if (outcome.code !== 0 || marker === undefined) {
657
- throw new Error(`official profile boot probe (${phase}) failed:\n${outcome.stdout}\n${outcome.stderr}`)
658
- }
659
- return JSON.parse(marker.slice('BOOT_PROBE_OK '.length))
660
- }
661
-
662
- /** Seed real user settings through the plugin's own public surface. */
663
- const seedSettings = async () => {
664
- const { profileRoot } = profilePackages()
665
- const settingsPath = join(dshHome, 'settings.yaml')
666
- const script = [
667
- "const { writeFileSync, readFileSync, existsSync } = require('node:fs')",
668
- "const { createRequire } = require('node:module')",
669
- "const yaml = require('js-yaml')",
670
- `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
671
- "const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
672
- 'const plugin = require(pluginEntry)',
673
- "const document = {",
674
- " 'context-compression': {",
675
- " profile: 'savings',",
676
- ' custom: plugin.DEFAULT_CUSTOM_COMPRESSION_POLICY,',
677
- ' autoCompact: { thresholdPercent: 73 },',
678
- ' },',
679
- '}',
680
- `const path = String.raw\`${settingsPath}\``,
681
- 'const merged = existsSync(path) ? { ...yaml.load(readFileSync(path, \'utf8\')), ...document } : document',
682
- "writeFileSync(path, yaml.dump(merged), 'utf8')",
683
- "console.log('SEED_OK')",
684
- ].join('\n')
685
- const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
686
- cwd: worktree,
687
- env: environment,
688
- })
689
- if (outcome.code !== 0 || !outcome.stdout.includes('SEED_OK')) {
690
- throw new Error(`seeding official-profile settings failed:\n${outcome.stdout}\n${outcome.stderr}`)
691
- }
692
- return settingsPath
693
- }
694
-
695
- /** Read the seeded settings back through the upgraded plugin's parser. */
696
- const proveSettingsPreserved = async (settingsPath) => {
697
- const { profileRoot } = profilePackages()
698
- const script = [
699
- "const { readFileSync } = require('node:fs')",
700
- "const { createRequire } = require('node:module')",
701
- 'const yaml = require(\'js-yaml\')',
702
- `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
703
- "const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
704
- 'const plugin = require(pluginEntry)',
705
- `const document = yaml.load(readFileSync(String.raw\`${settingsPath}\`, 'utf8'))`,
706
- "const parsed = plugin.parseContextCompressionSettings(document['context-compression'])",
707
- "if (parsed.profile !== 'savings' || parsed.autoCompact.thresholdPercent !== 73) {",
708
- " throw new Error('upgraded profile lost the saved user settings: ' + JSON.stringify(parsed))",
709
- '}',
710
- "console.log('SETTINGS_OK')",
711
- ].join('\n')
712
- const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
713
- cwd: worktree,
714
- env: environment,
715
- })
716
- if (outcome.code !== 0 || !outcome.stdout.includes('SETTINGS_OK')) {
717
- throw new Error(`settings preservation proof failed:\n${outcome.stdout}\n${outcome.stderr}`)
718
- }
719
- }
720
-
721
- try {
722
- await run('git', ['worktree', 'add', '--detach', worktree, before.commit], { cwd: clone })
723
- added = true
724
- await run('pnpm', ['install', '--frozen-lockfile', '--ignore-scripts'], { cwd: worktree })
725
- // A source checkout ships no built artifacts (install above skips
726
- // prepare scripts). The boot probes run the REAL web profile —
727
- // dsh-base + dsh-web-app, the only bundle that mounts agent-presets and
728
- // therefore the selector's preset overlay — so build both library faces
729
- // AND the web frontend; the healed profiles/node_modules fallback also
730
- // symlinks the CLI's own workspace packages, which is why the checkout's
731
- // `vendor/schemastery/lib` has to exist too.
732
- await run('pnpm', ['run', 'build'], { cwd: worktree })
733
- // Fail closed on the artifacts every later probe needs. Measured on the Node
734
- // this workflow used to pin (24.0.0): `tsx` leaves `import.meta.main`
735
- // undefined there, the clone's guarded `scripts/build.ts` exited 0 in about
736
- // eight seconds having emitted nothing, and the boot probe then failed twice
737
- // over — `client bundles not found; run \`pnpm run build\` before launch`
738
- // from client composition, and `Cannot find module
739
- // .../profiles/node_modules/@deepseek-ai/schemastery/lib/index.mjs` from the
740
- // plugin, because the installation fallback resolves that name to the source
741
- // checkout's `vendor/schemastery`, whose `lib` only this build produces.
742
- for (const artifact of [
743
- 'packages/client/ui-settings/lib/client.js',
744
- 'vendor/schemastery/lib/index.mjs',
745
- ]) {
746
- if (!existsSync(join(worktree, artifact))) {
747
- throw new Error([
748
- `official clone build produced no ${artifact}`,
749
- 'the clone\'s build script is `tsx scripts/build.ts`, guarded by `if (import.meta.main)`;',
750
- 'tsx leaves that flag undefined on Node < 24.2, so the build exits 0 without building',
751
- ].join(' '))
752
- }
753
- }
754
-
755
- // Positive controls (recorded, never asserted), captured HERE because the
756
- // clone checkout must exist: `cwd: worktree` is what makes spawn work at
757
- // all. The clone's `dsh` script is `node --import tsx/esm
758
- // apps/cli/src/bin.ts`, and bin.ts' `plugin` mode ALWAYS calls runPlugin —
759
- // which either initializes the profile (printing `dsh: initialized profile
760
- // …`), forwards pnpm's inherited stdio, or reports a missing pnpm with exit
761
- // 127. It therefore cannot exit 0 with empty output, so a silent lifecycle
762
- // means the CLI never reached that mode. These two probes tell the two
763
- // candidate causes apart: the package manager's script layer swallowing the
764
- // invocation, versus the CLI entry itself. See issue #2.
765
- scriptLayerControl = await captureOutcome('pnpm', ['dsh', '--version'], { cwd: worktree, env: environment })
766
- directEntryControl = await captureOutcome(
767
- process.execPath,
768
- ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', '--version'],
769
- { cwd: worktree, env: environment },
770
- )
771
- // The runner the lifecycle uses. It imports the entry and calls the
772
- // exported `runCli()` after shaping argv exactly as the entry would see it
773
- // (`argv[1]` = the entry path), so every mode the entry supports — profile
774
- // boot, plugin forwarding, config dumps, help, version — behaves as it does
775
- // when the file really is the process entry point.
776
- cliRunnerPath = join(temporaryRoot, 'run-cli.mjs')
777
- await writeFile(cliRunnerPath, [
778
- "import { pathToFileURL } from 'node:url'",
779
- `const entry = ${JSON.stringify(join(worktree, 'apps/cli/src/bin.ts'))}`,
780
- 'process.argv = [process.argv[0], entry, ...process.argv.slice(2)]',
781
- 'const { runCli } = await import(pathToFileURL(entry).href)',
782
- 'await runCli()',
783
- ].join('\n'), 'utf8')
784
-
785
- // Real lifecycle: start on the published previous release.
786
- if (upgradeFrom === undefined) throw new Error('release gate requires the previous published release for the official lifecycle')
787
- await dsh('plugin', '--profile', 'web', 'add',
788
- `dsh-context-compression-improved@${upgradeFrom}`, '--registry', registry)
789
- const beforeUp = profilePackages()
790
- if (beforeUp.selector.version !== upgradeFrom) {
791
- throw new Error(`official lifecycle started on ${String(beforeUp.selector.version)}, expected ${upgradeFrom}`)
792
- }
793
-
794
- // Boot the profile once on the previous release. This asserts the added
795
- // bundle layer is live before any update and heals
796
- // $DSH_HOME/profiles/node_modules — the shared-module fallback the
797
- // plugin's harness peers resolve through in every later raw-node proof.
798
- const addedDump = await dumpConfig()
799
- assert(addedDump.includes('context-compression-improved-bundle'),
800
- 'official post-add dump lacks the context-compression Bundle layer')
801
-
802
- // Real profile start on the previous release, BEFORE seeding: the
803
- // previous-release schema predates the autoCompact section, so this probe
804
- // proves its own defaults resolve; the seeded document is asserted by the
805
- // post-up probe through the upgraded runtime.
806
- const postAddBoot = await runProfileBootProbe('post-add', false)
807
-
808
- const settingsPath = await seedSettings()
809
-
810
- // Standard update command moves the one install-facing package; assert the
811
- // version it lands before anything else runs.
812
- await dsh('plugin', '--profile', 'web', 'up',
813
- 'dsh-context-compression-improved@latest', '--registry', registry)
814
- const afterUp = profilePackages()
815
- if (afterUp.selector.version !== candidateVersion) {
816
- throw new Error(`official up landed ${String(afterUp.selector.version)}, expected ${String(candidateVersion)}`)
817
- }
818
- await proveSettingsPreserved(settingsPath)
819
- const loadProof = await provePluginLoads()
820
- const postUpBoot = await runProfileBootProbe('post-up', true)
821
- const upDump = await dumpConfig()
822
- for (const marker of ['context-compression-improved-bundle', 'presetOverlay: true']) {
823
- assert(upDump.includes(marker), `official post-up dump lacks ${marker}`)
824
- }
825
- assert(upDump.match(/context-compression-improved-bundle/gu)?.length === 1,
826
- 'official post-up dump contains more than one context-compression Bundle layer')
827
-
828
- // pnpm's peers check is informational: plugin peers resolve through the
829
- // healed profiles/node_modules fallback, which pnpm cannot see by design.
830
- const peers = await captureOutcome('pnpm', ['peers', 'check'], {
831
- cwd: join(dshHome, 'profiles/web'),
832
- env: environment,
833
- })
834
-
835
- await dsh('plugin', '--profile', 'web', 'remove', 'dsh-context-compression-improved')
836
- const removedDump = await dumpConfig()
837
- assert(!removedDump.includes('context-compression-improved-bundle'),
838
- 'official CLI remove left the context-compression Bundle layer active')
839
-
840
- await dsh('plugin', '--profile', 'web', 'add',
841
- 'dsh-context-compression-improved@latest', '--registry', registry)
842
- const secondDump = await dumpConfig()
843
- assert(secondDump.includes('context-compression-improved-bundle'),
844
- 'official CLI reinstall did not restore the context-compression Bundle layer')
845
-
846
- return {
847
- tag: before.tag,
848
- commit: before.commit,
849
- tree: before.tree,
850
- status: 'clean',
851
- install: 'entry-package-only',
852
- upgrade: {
853
- from: upgradeFrom,
854
- to: candidateVersion,
855
- selector: afterUp.selector.version,
856
- settingsPreserved: true,
857
- pluginAndEnginePeersLoad: loadProof,
858
- realProfileBoot: { postAdd: postAddBoot, postUp: postUpBoot },
859
- dump: 'single-bundle-layer',
860
- },
861
- remove: 'bundle-removed',
862
- reinstall: 'bundle-restored',
863
- peersCheck: {
864
- exitCode: peers.code,
865
- note: 'informational: plugin peers resolve via the healed profiles/node_modules fallback, proven by load',
866
- },
867
- }
868
- } finally {
869
- if (added) await run('git', ['worktree', 'remove', '--force', worktree], { cwd: clone })
870
- await rm(temporaryRoot, { recursive: true, force: true })
871
- }
872
- }
873
-
874
- const fixedArtifactRoot = process.env.DSH_SELECTOR_ARTIFACT_DIR
875
- const artifactRoot = fixedArtifactRoot === undefined
876
- ? await mkdtemp(join(tmpdir(), 'dsh-selector-pack-'))
877
- : await realpath(fixedArtifactRoot)
878
- const ownsArtifactRoot = fixedArtifactRoot === undefined
879
- const comparisonRoot = fixedArtifactRoot === undefined
880
- ? undefined
881
- : await mkdtemp(join(tmpdir(), 'dsh-selector-rebuild-'))
882
- const consumerRoot = await mkdtemp(join(tmpdir(), 'dsh-selector-consumer-'))
883
- let server
884
-
885
- try {
886
- const registryPackages = new Map()
887
- // Published previous-release metadata served alongside the packed candidate
888
- // so the upgrade leg can install the real shipped release first.
889
- const previousVersions = new Map()
890
- // The predecessor is whatever the registry actually offers. This used to be
891
- // the pinned literal '0.1.0-beta.2', which only ever existed under this
892
- // package's pre-rename name, so it could never resolve under the current one.
893
- let previousRelease = ''
894
- // True only once a real predecessor was found. Both release-mode gates below
895
- // key off it: the upgrade leg must run whenever users have something to
896
- // upgrade FROM, and must not block a package that has nothing to upgrade from.
897
- let predecessorFound = false
898
- let upgradeLeg = 'skipped-no-network'
899
- for (const name of ['dsh-context-compression-improved']) {
900
- try {
901
- const packumentResponse = await fetch(`https://registry.npmjs.org/${name}`)
902
- if (packumentResponse.status === 404) {
903
- upgradeLeg = 'skipped-package-not-published'
904
- previousVersions.clear()
905
- break
906
- }
907
- if (!packumentResponse.ok) throw new Error(`packument responded ${packumentResponse.status}`)
908
- const packument = await packumentResponse.json()
909
- const localVersion = JSON.parse(await readFile(join(packages[0].directory, 'package.json'), 'utf8')).version
910
- const times = packument.time ?? {}
911
- // Publication order, not semver order: the version a user would be
912
- // upgrading from is the most recently published one that is not the
913
- // candidate. Avoids a semver dependency and handles prereleases.
914
- const earlier = Object.keys(packument.versions ?? {})
915
- .filter((version) => version !== localVersion)
916
- .sort((a, b) => Date.parse(times[b] ?? '') - Date.parse(times[a] ?? ''))
917
- if (earlier.length === 0) {
918
- upgradeLeg = 'skipped-no-earlier-release'
919
- previousVersions.clear()
920
- break
921
- }
922
- previousRelease = earlier[0]
923
- const response = await fetch(`https://registry.npmjs.org/${name}/${previousRelease}`)
924
- if (!response.ok) throw new Error(`packument responded ${response.status}`)
925
- const manifest = await response.json()
926
- const tarballResponse = await fetch(manifest.dist.tarball)
927
- if (!tarballResponse.ok) throw new Error(`tarball responded ${tarballResponse.status}`)
928
- const bytes = Buffer.from(await tarballResponse.arrayBuffer())
929
- const filename = `${name}-${previousRelease}.tgz`
930
- const tarball = join(artifactRoot, `previous-${filename}`)
931
- await writeFile(tarball, bytes)
932
- previousVersions.set(name, {
933
- filename,
934
- manifest,
935
- tarball,
936
- sha1: createHash('sha1').update(bytes).digest('hex'),
937
- integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
938
- })
939
- } catch (error) {
940
- if (e2eMode === 'release') {
941
- throw new Error(`release gate requires the published previous release for the upgrade leg: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
942
- }
943
- upgradeLeg = `skipped-previous-release-unavailable:${error instanceof Error ? error.message : String(error)}`
944
- previousVersions.clear()
945
- break
946
- }
947
- }
948
- if (previousVersions.size === 1) {
949
- upgradeLeg = 'installed'
950
- predecessorFound = true
951
- }
952
- for (const descriptor of packages) {
953
- const manifest = JSON.parse(await readFile(join(descriptor.directory, 'package.json'), 'utf8'))
954
- if (fixedArtifactRoot === undefined) {
955
- await run('npm', ['pack', '--pack-destination', artifactRoot, descriptor.directory], { cwd: root })
956
- }
957
- const filename = `${manifest.name}-${manifest.version}.tgz`
958
- const tarball = join(artifactRoot, filename)
959
- await stat(tarball)
960
- const bytes = await readFile(tarball)
961
- if (comparisonRoot !== undefined) {
962
- await run('npm', ['pack', '--pack-destination', comparisonRoot, descriptor.directory], { cwd: root })
963
- const rebuilt = await readFile(join(comparisonRoot, filename))
964
- const reviewedHash = createHash('sha256').update(bytes).digest('hex')
965
- const rebuiltHash = createHash('sha256').update(rebuilt).digest('hex')
966
- if (reviewedHash !== rebuiltHash) {
967
- throw new Error(`${manifest.name} fixed tarball differs from the current workspace rebuild`)
968
- }
969
- }
970
- registryPackages.set(manifest.name, {
971
- filename,
972
- manifest,
973
- tarball,
974
- sha1: createHash('sha1').update(bytes).digest('hex'),
975
- sha256: createHash('sha256').update(bytes).digest('hex'),
976
- integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
977
- })
978
- }
979
-
980
- server = createServer(async (request, response) => {
981
- try {
982
- const requestUrl = new URL(request.url ?? '/', 'http://127.0.0.1')
983
- const decodedPath = decodeURIComponent(requestUrl.pathname)
984
- for (const [name, descriptor] of registryPackages) {
985
- if (decodedPath === `/${name}`) {
986
- const address = server.address()
987
- if (address === null || typeof address === 'string') throw new Error('registry has no TCP address')
988
- const tarballUrl = `http://127.0.0.1:${address.port}/${name}/-/${descriptor.filename}`
989
- const version = {
990
- ...descriptor.manifest,
991
- dist: {
992
- tarball: tarballUrl,
993
- shasum: descriptor.sha1,
994
- integrity: descriptor.integrity,
995
- },
996
- }
997
- const previous = previousVersions.get(name)
998
- const previousVersion = previous === undefined ? {} : {
999
- [previous.manifest.version]: {
1000
- ...previous.manifest,
1001
- dist: {
1002
- tarball: `http://127.0.0.1:${address.port}/${name}/-/${previous.filename}`,
1003
- shasum: previous.sha1,
1004
- integrity: previous.integrity,
1005
- },
1006
- },
1007
- }
1008
- const body = JSON.stringify({
1009
- name,
1010
- 'dist-tags': { latest: descriptor.manifest.version },
1011
- versions: { ...previousVersion, [descriptor.manifest.version]: version },
1012
- })
1013
- response.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) })
1014
- response.end(request.method === 'HEAD' ? undefined : body)
1015
- return
1016
- }
1017
- if (decodedPath === `/${name}/-/${descriptor.filename}`) {
1018
- const details = await stat(descriptor.tarball)
1019
- response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': details.size })
1020
- if (request.method === 'HEAD') response.end()
1021
- else createReadStream(descriptor.tarball).pipe(response)
1022
- return
1023
- }
1024
- }
1025
- for (const [name, previous] of previousVersions) {
1026
- if (decodedPath === `/${name}/-/${previous.filename}`) {
1027
- const details = await stat(previous.tarball)
1028
- response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': details.size })
1029
- if (request.method === 'HEAD') response.end()
1030
- else createReadStream(previous.tarball).pipe(response)
1031
- return
1032
- }
1033
- }
1034
-
1035
- if (request.method !== 'GET' && request.method !== 'HEAD') {
1036
- response.writeHead(404).end()
1037
- return
1038
- }
1039
- const upstream = await fetch(`https://registry.npmjs.org${requestUrl.pathname}${requestUrl.search}`, {
1040
- method: request.method,
1041
- headers: { accept: request.headers.accept ?? '*/*' },
1042
- })
1043
- const headers = {}
1044
- for (const name of ['content-type', 'content-length', 'cache-control', 'etag', 'last-modified']) {
1045
- const value = upstream.headers.get(name)
1046
- if (value !== null) headers[name] = value
1047
- }
1048
- response.writeHead(upstream.status, headers)
1049
- if (request.method === 'HEAD' || upstream.body === null) response.end()
1050
- else Readable.fromWeb(upstream.body).pipe(response)
1051
- } catch (error) {
1052
- response.writeHead(502, { 'content-type': 'text/plain' })
1053
- response.end(error instanceof Error ? error.message : String(error))
1054
- }
1055
- })
1056
- await new Promise((resolve, reject) => {
1057
- server.once('error', reject)
1058
- server.listen(0, '127.0.0.1', resolve)
1059
- })
1060
- const address = server.address()
1061
- if (address === null || typeof address === 'string') throw new Error('registry has no TCP address')
1062
- const registry = `http://127.0.0.1:${address.port}`
1063
-
1064
- await writeFile(join(consumerRoot, 'package.json'), JSON.stringify({
1065
- name: 'dsh-context-compression-improved-packed-e2e',
1066
- version: '0.0.0',
1067
- private: true,
1068
- }, null, 2))
1069
- // Stop pnpm's workspace walk-up: an ancestor with its own pnpm-workspace.yaml
1070
- // (e.g. a user home project) would otherwise absorb this consumer and land
1071
- // the install — and every resolution — outside the packed consumer.
1072
- await writeFile(join(consumerRoot, 'pnpm-workspace.yaml'), ['packages:', ' - .'].join(String.fromCharCode(10)))
1073
- if (upgradeLeg === 'installed') {
1074
- // Real upgrade path: install the published previous release, then move to
1075
- // the packed candidate through the standard update command.
1076
- await run('pnpm', [
1077
- 'add',
1078
- `dsh-context-compression-improved@${previousRelease}`,
1079
- ...officialHostPackages,
1080
- '--registry', registry,
1081
- ], { cwd: consumerRoot })
1082
- const previousSelectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1083
- const previousSelector = JSON.parse(await readFile(join(previousSelectorDir, 'package.json'), 'utf8'))
1084
- if (previousSelector.version !== previousRelease) {
1085
- throw new Error(`upgrade leg installed ${String(previousSelector.version)}, expected ${previousRelease}`)
1086
- }
1087
- await run('pnpm', [
1088
- 'up',
1089
- 'dsh-context-compression-improved@latest',
1090
- '--registry', registry,
1091
- ], { cwd: consumerRoot })
1092
- // The up command must land the packed candidate version.
1093
- const upgradedSelectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1094
- const upgradedSelector = JSON.parse(await readFile(join(upgradedSelectorDir, 'package.json'), 'utf8'))
1095
- const candidateVersion = registryPackages.get('dsh-context-compression-improved')?.manifest.version
1096
- if (candidateVersion === undefined) throw new Error('packed candidate version is unknown')
1097
- if (upgradedSelector.version !== candidateVersion) {
1098
- throw new Error(`upgrade leg landed ${String(upgradedSelector.version)}, expected ${String(candidateVersion)}`)
1099
- }
1100
- } else {
1101
- console.info(`UPGRADE_LEG_SKIPPED ${upgradeLeg}`)
1102
- await run('pnpm', [
1103
- 'add',
1104
- 'dsh-context-compression-improved@latest',
1105
- ...officialHostPackages,
1106
- '--registry', registry,
1107
- ], { cwd: consumerRoot })
1108
- }
1109
-
1110
- const selectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1111
- const selector = JSON.parse(await readFile(join(selectorDir, 'package.json'), 'utf8'))
1112
- if (selector.publishConfig?.tag !== 'latest') {
1113
- throw new Error('packed package is not guarded by publishConfig.tag=latest')
1114
- }
1115
- for (const peer of ['@deepseek-ai/dsh-command-compact', '@deepseek-ai/dsh-compaction-basic']) {
1116
- if (selector.peerDependencies?.[peer] !== '>=0.1.5-rc.2 <0.2.0-0') {
1117
- throw new Error(`packed selector has an invalid ${peer} peer range`)
1118
- }
1119
- }
1120
- for (const directory of [selectorDir]) {
1121
- const notice = await readFile(join(directory, 'THIRD_PARTY_NOTICES.md'), 'utf8')
1122
- if (!notice.includes('Copyright (c) 2026 DeepSeek')) {
1123
- throw new Error(`${basename(directory)} lacks the full DeepSeek Harness MIT notice`)
1124
- }
1125
- await scanPublishedTree(directory)
1126
- }
1127
-
1128
- const productionLicenses = Object.fromEntries(await Promise.all([
1129
- ['dsh-context-compression-improved', selectorDir, 'MIT'],
1130
- ['@huggingface/tokenizers', join(dirname(selectorDir), '@huggingface/tokenizers'), 'Apache-2.0'],
1131
- ['js-yaml', join(dirname(selectorDir), 'js-yaml'), 'MIT'],
1132
- ].map(async ([name, directory, expected]) => {
1133
- const resolved = await realpath(directory)
1134
- const manifest = JSON.parse(await readFile(join(resolved, 'package.json'), 'utf8'))
1135
- if (manifest.name !== name) throw new Error(`expected ${name}, found ${String(manifest.name)}`)
1136
- if (manifest.license !== expected) {
1137
- throw new Error(`${name} license is ${String(manifest.license)}, expected ${expected}`)
1138
- }
1139
- return [name, manifest.license]
1140
- })))
1141
- const yamlDir = await realpath(join(dirname(selectorDir), 'js-yaml'))
1142
- const argparseDir = await realpath(join(dirname(yamlDir), 'argparse'))
1143
- const argparse = JSON.parse(await readFile(join(argparseDir, 'package.json'), 'utf8'))
1144
- if (argparse.name !== 'argparse' || argparse.license !== 'Python-2.0') {
1145
- throw new Error(`argparse license is ${String(argparse.license)}, expected Python-2.0`)
1146
- }
1147
- productionLicenses.argparse = argparse.license
1148
-
1149
- const packedTokenizerArtifacts = {}
1150
- for (const artifactDir of ['deepseek-v4', 'deepseek-v4-vision-exp']) {
1151
- const manifest = JSON.parse(await readFile(join(selectorDir, 'assets', artifactDir, 'manifest.json'), 'utf8'))
1152
- const tokenizerBytes = await readFile(join(selectorDir, 'assets', artifactDir, 'tokenizer.json'))
1153
- const tokenizerHash = createHash('sha256').update(tokenizerBytes).digest('hex')
1154
- if (tokenizerBytes.length !== manifest.files['tokenizer.json'].bytes) throw new Error(`packed ${artifactDir} tokenizer size differs`)
1155
- if (tokenizerHash !== manifest.files['tokenizer.json'].sha256) throw new Error(`packed ${artifactDir} tokenizer hash differs`)
1156
- packedTokenizerArtifacts[artifactDir] = { bytes: tokenizerBytes.length, sha256: tokenizerHash }
1157
- }
1158
- const tokenizer = await readFile(join(selectorDir, 'assets/deepseek-v4/tokenizer.json'))
1159
- const tokenizerHash = packedTokenizerArtifacts['deepseek-v4'].sha256
1160
-
1161
- const client = await readFile(join(selectorDir, 'lib/client.js'), 'utf8')
1162
- if (!client.startsWith('window.__ModuleLoader__.load({')) throw new Error('packed client is not lazy-CJS')
1163
- if (/(?:\/home\/|[A-Za-z]:\\Users\\)/u.test(client)) throw new Error('packed client leaks a developer path')
1164
- const hostSmoke = await runPackedHostSmoke(consumerRoot)
1165
- const installedComponentsScript = join(consumerRoot, 'packed-components-smoke.mjs')
1166
- await copyFile(join(root, 'scripts/packed-components-smoke.mjs'), installedComponentsScript)
1167
- const installedComponentsOutput = await capture(process.execPath, [installedComponentsScript], {
1168
- cwd: consumerRoot,
1169
- })
1170
- const installedComponentsLine = installedComponentsOutput.stdout
1171
- .split(/\r?\n/u)
1172
- .find(line => line.startsWith('PACKED_COMPONENTS_E2E '))
1173
- if (installedComponentsLine === undefined) {
1174
- throw new Error(`installed component smoke lacks its result marker:\n${installedComponentsOutput.stdout}`)
1175
- }
1176
- const installedComponentsSmoke = JSON.parse(
1177
- installedComponentsLine.slice('PACKED_COMPONENTS_E2E '.length),
1178
- )
1179
- const visionLine = installedComponentsOutput.stdout
1180
- .split(/\r?\n/u)
1181
- .find(line => line.startsWith('PACKED_VISION_E2E '))
1182
- if (visionLine === undefined) {
1183
- throw new Error('installed component smoke lacks its vision-session result marker')
1184
- }
1185
- const packedVisionSmoke = JSON.parse(visionLine.slice('PACKED_VISION_E2E '.length))
1186
- assert(packedVisionSmoke.model === 'deepseek-v4-flash-vision-exp',
1187
- 'installed vision smoke reported the wrong model')
1188
- assert(packedVisionSmoke.imageSession?.measurement?.kind === 'tokenizer-estimate',
1189
- 'installed vision smoke did not prove a tokenizer-estimate image surface')
1190
- assert(packedVisionSmoke.imageSession.measurement.tokens === 340
1191
- && packedVisionSmoke.imageSession.measurement.upperBoundTokens === 384,
1192
- 'installed vision smoke reported the wrong 800x600 image estimate')
1193
- assert(packedVisionSmoke.imageSession.measurement.estimatorId
1194
- === 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp/image-token-estimate'
1195
- && packedVisionSmoke.imageSession.measurement.estimatorRevision
1196
- === '6821d6ad3681a4b137b066b76094fa82ebd0a380:v1',
1197
- 'installed vision smoke reported the wrong image estimator identity')
1198
- assert(packedVisionSmoke.imageSession.currentSurfaceKind === 'tokenizer-estimate'
1199
- && packedVisionSmoke.imageSession.exactRewriteIneligible === true
1200
- && packedVisionSmoke.imageSession.originalIntact === true,
1201
- 'installed vision smoke did not prove estimate propagation and exact-only safety')
1202
- let officialCloneSmoke = null
1203
- const candidateVersion = registryPackages.get('dsh-context-compression-improved')?.manifest.version
1204
- if (candidateVersion === undefined) throw new Error('packed candidate version is unknown')
1205
- const previousForLifecycle = predecessorFound ? previousRelease : undefined
1206
- if (!predecessorFound) {
1207
- // The official lifecycle installs the previous release and then upgrades to
1208
- // the candidate, so it has nothing to do without a predecessor. Record the
1209
- // same explicit marker the upgrade leg produced instead of failing the run.
1210
- officialCloneSmoke = upgradeLeg
1211
- } else if (process.env.DSH_OFFICIAL_CLONE !== undefined) {
1212
- officialCloneSmoke = await runOfficialCloneCliSmoke(
1213
- process.env.DSH_OFFICIAL_CLONE,
1214
- registry,
1215
- previousForLifecycle,
1216
- candidateVersion,
1217
- )
1218
- } else {
1219
- // Auto-provision a clean official checkout so the standard add → up →
1220
- // remove lifecycle runs without manual setup. Release mode fails closed;
1221
- // only dev mode may skip with an explicit marker.
1222
- const cloneRoot = join(artifactRoot, 'official-clone')
1223
- try {
1224
- await run('git', [
1225
- 'clone', '--depth', '1', '--branch', 'dsh-v0.1.5-rc.2',
1226
- 'https://github.com/deepseek-ai/deepseek-harness.git', cloneRoot,
1227
- ])
1228
- officialCloneSmoke = await runOfficialCloneCliSmoke(
1229
- cloneRoot,
1230
- registry,
1231
- previousForLifecycle,
1232
- candidateVersion,
1233
- )
1234
- } catch (error) {
1235
- if (e2eMode === 'release') throw error
1236
- console.info(`OFFICIAL_CLONE_SMOKE_SKIPPED ${error instanceof Error ? error.message : String(error)}`)
1237
- await rm(cloneRoot, { recursive: true, force: true })
1238
- }
1239
- }
1240
-
1241
- if (e2eMode === 'release' && predecessorFound && upgradeLeg !== 'installed') {
1242
- throw new Error(`release gate requires the upgrade leg to run; it reported: ${upgradeLeg}`)
1243
- }
1244
- if (e2eMode === 'release' && officialCloneSmoke === null) {
1245
- throw new Error('release gate requires the official clean-harness lifecycle to run')
1246
- }
1247
- console.info(JSON.stringify({
1248
- installCommand: 'pnpm add dsh-context-compression-improved@latest',
1249
- e2eMode,
1250
- upgradeLeg,
1251
- artifactSource: fixedArtifactRoot === undefined ? 'fresh-pack' : artifactRoot,
1252
- workspaceRebuildMatched: fixedArtifactRoot === undefined ? null : true,
1253
- selector: selector.version,
1254
- prunerEntry: 'dsh-context-compression-improved/pruner',
1255
- productionLicenses,
1256
- tokenizerArtifacts: packedTokenizerArtifacts,
1257
- tokenizerBytes: tokenizer.length,
1258
- tokenizerSha256: tokenizerHash,
1259
- hostSmoke,
1260
- installedComponentsSmoke,
1261
- packedVisionSmoke,
1262
- officialCloneSmoke,
1263
- tarballs: Object.fromEntries([...registryPackages].map(([name, value]) => [name, {
1264
- file: basename(value.tarball),
1265
- sha256: value.sha256,
1266
- }])),
1267
- }, null, 2))
1268
- } finally {
1269
- if (server !== undefined) await new Promise(resolve => server.close(resolve))
1270
- if (comparisonRoot !== undefined) await rm(comparisonRoot, { recursive: true, force: true })
1271
- if (ownsArtifactRoot) await rm(artifactRoot, { recursive: true, force: true })
1272
- await rm(consumerRoot, { recursive: true, force: true })
1273
- }
1
+ import { createHash } from 'node:crypto'
2
+ import { spawn } from 'node:child_process'
3
+ import { createReadStream } from 'node:fs'
4
+ import { copyFile, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises'
5
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
6
+ import { createServer } from 'node:http'
7
+ import { createRequire } from 'node:module'
8
+ import { tmpdir } from 'node:os'
9
+ import { basename, dirname, join } from 'node:path'
10
+ import { Readable } from 'node:stream'
11
+ import { fileURLToPath, pathToFileURL } from 'node:url'
12
+
13
+ const root = fileURLToPath(new URL('..', import.meta.url))
14
+ // Release mode (default) is fail-closed: the upgrade leg and the official
15
+ // clean-harness lifecycle must both run to green or the gate exits non-zero.
16
+ // Set DSH_E2E_MODE=dev for an offline smoke with explicit skip markers.
17
+ const e2eMode = process.env.DSH_E2E_MODE === 'dev' ? 'dev' : 'release'
18
+ const packages = [
19
+ { directory: join(root, 'packages/selector') },
20
+ ]
21
+ // The full @deepseek-ai/* host closure (pinned in the workspace root manifest,
22
+ // currently 0.1.5-rc.2): auto-installed peers must all resolve from the mock
23
+ // registry, so the list must cover every peer the packed plugins and the
24
+ // official packages declare.
25
+ const rootManifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
26
+ const officialHostPackages = Object.entries(rootManifest.devDependencies)
27
+ .filter(([name]) => name.startsWith('@deepseek-ai/'))
28
+ .map(([name, version]) => `${name}@${version}`)
29
+
30
+ // Only the package-manager shims need a shell on Windows; every real executable
31
+ // must be spawned directly, because cmd.exe re-parses arguments: `^` is its
32
+ // escape character, so `HEAD^{tree}` reached git as `HEAD{tree}`, and a
33
+ // multi-line `node -e` settings script was cut at its first newline into
34
+ // `[eval]:1 const` / `SyntaxError: Unexpected end of input`. Both killed the
35
+ // official-clone leg for reasons unrelated to what it asserts.
36
+ const SHELL_COMMANDS = new Set(['npm', 'npm.cmd', 'pnpm', 'pnpm.cmd'])
37
+ const usesShell = (command) => process.platform === 'win32' && SHELL_COMMANDS.has(command)
38
+
39
+ const run = (command, args, options = {}) => new Promise((resolve, reject) => {
40
+ const child = spawn(command, args, { stdio: 'inherit', shell: usesShell(command), ...options })
41
+ child.once('error', reject)
42
+ child.once('exit', (code, signal) => {
43
+ if (code === 0) resolve()
44
+ else reject(new Error(`${command} exited ${code ?? `from signal ${signal}`}`))
45
+ })
46
+ })
47
+
48
+ const capture = (command, args, options = {}) => new Promise((resolve, reject) => {
49
+ const child = spawn(command, args, { shell: usesShell(command), ...options, stdio: ['ignore', 'pipe', 'pipe'] })
50
+ let stdout = ''
51
+ let stderr = ''
52
+ child.stdout.setEncoding('utf8')
53
+ child.stderr.setEncoding('utf8')
54
+ child.stdout.on('data', chunk => { stdout += chunk })
55
+ child.stderr.on('data', chunk => { stderr += chunk })
56
+ child.once('error', reject)
57
+ child.once('exit', (code, signal) => {
58
+ if (code === 0) resolve({ stdout, stderr })
59
+ else reject(new Error([
60
+ `${command} exited ${code ?? `from signal ${signal}`}`,
61
+ stdout.trim(),
62
+ stderr.trim(),
63
+ ].filter(Boolean).join('\n')))
64
+ })
65
+ })
66
+
67
+ const captureOutcome = (command, args, options = {}) => new Promise((resolve, reject) => {
68
+ const child = spawn(command, args, { shell: usesShell(command), ...options, stdio: ['ignore', 'pipe', 'pipe'] })
69
+ let stdout = ''
70
+ let stderr = ''
71
+ child.stdout.setEncoding('utf8')
72
+ child.stderr.setEncoding('utf8')
73
+ child.stdout.on('data', chunk => { stdout += chunk })
74
+ child.stderr.on('data', chunk => { stderr += chunk })
75
+ child.once('error', reject)
76
+ child.once('exit', (code, signal) => resolve({ code, signal, stdout, stderr }))
77
+ })
78
+
79
+ const allocateLoopbackPort = () => new Promise((resolve, reject) => {
80
+ const server = createServer()
81
+ server.once('error', reject)
82
+ server.listen(0, '127.0.0.1', () => {
83
+ const address = server.address()
84
+ if (address === null || typeof address === 'string') {
85
+ server.close(() => reject(new Error('could not allocate a loopback port for the official profile probe')))
86
+ return
87
+ }
88
+ server.close(error => error === undefined ? resolve(address.port) : reject(error))
89
+ })
90
+ })
91
+
92
+ const assert = (condition, message) => {
93
+ if (!condition) throw new Error(`packed Host smoke: ${message}`)
94
+ }
95
+
96
+ async function scanPublishedTree(packageRoot) {
97
+ const pending = [packageRoot]
98
+ const violations = []
99
+ const forbidden = [
100
+ { label: 'developer absolute path', pattern: /(?:\/home\/|[A-Za-z]:\\Users\\)/u },
101
+ { label: 'OpenAI-style secret', pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/u },
102
+ { label: 'NPM token', pattern: /\bnpm_[A-Za-z0-9]{20,}\b/u },
103
+ { label: 'GitHub token', pattern: /\b(?:ghp_|github_pat_)[A-Za-z0-9_]{20,}\b/u },
104
+ { label: 'assigned DeepSeek API key', pattern: /DEEPSEEK_API_KEY\s*=\s*[^\s"']+/u },
105
+ ]
106
+ while (pending.length > 0) {
107
+ const directory = pending.pop()
108
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
109
+ const path = join(directory, entry.name)
110
+ if (entry.isDirectory()) {
111
+ pending.push(path)
112
+ continue
113
+ }
114
+ if (!/\.(?:js|d\.ts|json|md|ya?ml|txt)$/u.test(entry.name)
115
+ || entry.name === 'tokenizer.json') continue
116
+ const text = await readFile(path, 'utf8')
117
+ for (const rule of forbidden) {
118
+ if (rule.pattern.test(text)) violations.push(`${path}: ${rule.label}`)
119
+ }
120
+ }
121
+ }
122
+ if (violations.length > 0) throw new Error(`packed content scan failed:\n${violations.join('\n')}`)
123
+ }
124
+
125
+ async function runPackedHostSmoke(consumerRoot) {
126
+ const consumerRequire = createRequire(join(consumerRoot, 'package.json'))
127
+ const load = async specifier => import(pathToFileURL(consumerRequire.resolve(specifier)).href)
128
+ const [
129
+ cordis,
130
+ groupModule,
131
+ includeModule,
132
+ loaderModule,
133
+ agentModule,
134
+ agentLoopModule,
135
+ presetsModule,
136
+ commandsModule,
137
+ llmModule,
138
+ sessionModule,
139
+ scopeModule,
140
+ settingsModule,
141
+ systemPromptModule,
142
+ sessionProjectionModule,
143
+ tokenMeterModule,
144
+ toolsModule,
145
+ selectorModule,
146
+ ] = await Promise.all([
147
+ load('@deepseek-ai/cordis'),
148
+ load('@deepseek-ai/cordis-plugin-group'),
149
+ load('@deepseek-ai/cordis-plugin-include'),
150
+ load('@deepseek-ai/cordis-plugin-loader'),
151
+ load('@deepseek-ai/dsh-agent'),
152
+ load('@deepseek-ai/dsh-agent-loop'),
153
+ load('@deepseek-ai/dsh-agent-presets'),
154
+ load('@deepseek-ai/dsh-commands'),
155
+ load('@deepseek-ai/dsh-llm'),
156
+ load('@deepseek-ai/dsh-session'),
157
+ load('@deepseek-ai/dsh-scope'),
158
+ load('@deepseek-ai/dsh-settings'),
159
+ load('@deepseek-ai/dsh-system-prompt'),
160
+ load('@deepseek-ai/dsh-session-projection'),
161
+ load('@deepseek-ai/dsh-token-meter'),
162
+ load('@deepseek-ai/dsh-tools'),
163
+ load('dsh-context-compression-improved'),
164
+ ])
165
+
166
+ class MemorySettings extends settingsModule.SettingsProvider {
167
+ writable = true
168
+
169
+ load() {
170
+ return Promise.resolve({})
171
+ }
172
+
173
+ persist() {
174
+ return Promise.resolve()
175
+ }
176
+ }
177
+
178
+ const presetRoot = join(consumerRoot, 'preset-fixtures')
179
+ await mkdir(presetRoot)
180
+ const marker = join(presetRoot, 'marker.mjs')
181
+ await writeFile(marker, 'export function apply() {}\n')
182
+ const source = `- id: source-marker\n name: ${JSON.stringify(marker)}\n`
183
+ for (const id of ['standard', 'custom', 'minimal']) {
184
+ const directory = join(presetRoot, id)
185
+ await mkdir(directory)
186
+ await writeFile(join(directory, presetsModule.COMPOSITION_FILE), source)
187
+ }
188
+
189
+ const runtime = new cordis.Context()
190
+ try {
191
+ runtime.baseUrl = `${pathToFileURL(presetRoot).href}/`
192
+ await runtime.plugin(loaderModule.default).await()
193
+ runtime.loader.builtins.include = includeModule.default
194
+ runtime.loader.builtins.group = groupModule.default
195
+ await runtime.plugin(llmModule.default).await()
196
+ await runtime.plugin(sessionModule.default).await()
197
+ await runtime.plugin(systemPromptModule.default, { personaPrefix: '' }).await()
198
+ await runtime.plugin(toolsModule.default).await()
199
+ await runtime.plugin(agentModule.default).await()
200
+ await runtime.plugin(agentLoopModule.default, { agents: [] }).await()
201
+ await runtime.plugin(commandsModule.default).await()
202
+ await runtime.plugin(sessionProjectionModule.default).await()
203
+ await runtime.plugin(tokenMeterModule.default).await()
204
+ await runtime.plugin(MemorySettings).await()
205
+ await runtime.plugin(presetsModule.default, {
206
+ default: 'standard',
207
+ roots: [{ path: presetRoot, trust: 'system' }],
208
+ includeShippedRoot: false,
209
+ includeUserRoot: false,
210
+ }).await()
211
+ await runtime.plugin({
212
+ apply: selectorCtx => selectorModule.apply(selectorCtx, { presetOverlay: true }),
213
+ }).await()
214
+
215
+ const createAgent = async (sessionId, preset) => {
216
+ const handle = await runtime.agents.create({
217
+ sessionId: sessionModule.SessionId(sessionId),
218
+ setup: async agentCtx => void await runtime.agentPresets.mount(agentCtx, preset),
219
+ })
220
+ return handle.agent
221
+ }
222
+ const hasRetrieve = agent => runtime.tools.get(
223
+ 'context_compression_retrieve',
224
+ scopeModule.scopeOf(agent.ctx),
225
+ ) !== undefined
226
+ const hasCompact = agent => runtime.commands.list(agent)
227
+ .some(command => command.name === 'compact')
228
+ const hasCompleteStack = agent =>
229
+ runtime.agentPresets.serviceFor(agent, 'toolResultPruner') !== undefined
230
+ && runtime.agentPresets.serviceFor(agent, 'compaction') !== undefined
231
+ && hasRetrieve(agent)
232
+ && hasCompact(agent)
233
+ const hasNoStack = agent =>
234
+ runtime.agentPresets.serviceFor(agent, 'toolResultPruner') === undefined
235
+ && runtime.agentPresets.serviceFor(agent, 'compaction') === undefined
236
+ && !hasRetrieve(agent)
237
+ && !hasCompact(agent)
238
+
239
+ const sourcePreset = await runtime.agentPresets.resolve('standard')
240
+ const sourceText = await runtime.agentPresets.read('standard')
241
+ const agent = await createAgent('packed-host-standard', 'standard')
242
+ assert(hasCompleteStack(agent), 'standard preset did not mount the complete compression stack')
243
+ assert((await runtime.agentPresets.resolve('standard')).path === sourcePreset.path,
244
+ 'overlay changed the source preset path')
245
+ assert(await runtime.agentPresets.read('standard') === sourceText,
246
+ 'overlay changed the source preset contents')
247
+ assert(!sourceText.includes('tool-result-pruner'), 'source preset was mutated')
248
+
249
+ await runtime.agentPresets.recompose(agent.ctx, 'minimal')
250
+ assert(hasNoStack(agent), 'exact Minimal preset retained compression')
251
+ await runtime.agentPresets.recompose(agent.ctx, 'custom')
252
+ assert(hasCompleteStack(agent), 'compression did not return after leaving Minimal')
253
+
254
+ const parent = await createAgent('packed-host-parent', 'standard')
255
+ const childHandle = await runtime.agents.create({
256
+ sessionId: sessionModule.SessionId('packed-host-child'),
257
+ setup: childCtx => void runtime.agentPresets.composeFrom(childCtx, parent.ctx),
258
+ })
259
+ const child = childHandle.agent
260
+ const original = Symbol.for('cordis.original')
261
+ const parentPruner = runtime.agentPresets.serviceFor(parent, 'toolResultPruner')
262
+ const childPruner = runtime.agentPresets.serviceFor(child, 'toolResultPruner')
263
+ const parentCompaction = runtime.agentPresets.serviceFor(parent, 'compaction')
264
+ const childCompaction = runtime.agentPresets.serviceFor(child, 'compaction')
265
+ assert(parentPruner !== undefined && childPruner !== undefined,
266
+ 'parent or child pruner is missing')
267
+ assert(parentCompaction !== undefined && childCompaction !== undefined,
268
+ 'parent or child compaction engine is missing')
269
+ assert(Object.is(childPruner[original], parentPruner[original]),
270
+ 'child did not inherit the parent pruner instance')
271
+ assert(Object.is(childCompaction[original], parentCompaction[original]),
272
+ 'child did not inherit the parent compaction instance')
273
+ assert(hasRetrieve(child) && hasCompact(child),
274
+ 'child lacks the inherited retrieve tool or compact command')
275
+
276
+ const namespace = 'context-compression'
277
+ const settings = runtime.settings.get(namespace)
278
+ assert(settings.custom.history.trigger === 500_000,
279
+ 'packed Host did not expose the 500000 History default')
280
+ assert(settings.custom.tailTrim.enabled === false && settings.custom.tailTrim.trigger === 700_000,
281
+ 'packed Host did not expose disabled TailTrim at 700000')
282
+
283
+ return {
284
+ officialHostPackages: officialHostPackages.length,
285
+ standardPreset: 'complete-stack',
286
+ minimalPreset: 'no-stack',
287
+ postMinimalPreset: 'complete-stack',
288
+ childServices: 'same-parent-instances',
289
+ sourcePreset: 'unchanged',
290
+ defaults: { history: 500_000, tailTrim: { enabled: false, trigger: 700_000 } },
291
+ }
292
+ } finally {
293
+ await runtime.fiber.dispose()
294
+ }
295
+ }
296
+
297
+ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, candidateVersion) {
298
+ const clone = await realpath(referenceRoot)
299
+ const git = async (...args) => (await capture('git', args, { cwd: clone })).stdout.trim()
300
+ const before = {
301
+ tag: await git('describe', '--tags', '--exact-match'),
302
+ commit: await git('rev-parse', 'HEAD'),
303
+ tree: await git('rev-parse', 'HEAD^{tree}'),
304
+ status: await git('status', '--porcelain'),
305
+ }
306
+ assert(before.tag === 'dsh-v0.1.5-rc.2', `official clone tag is ${before.tag}`)
307
+ assert(before.commit === 'fb2c4b9e698e30edb738bca4cf0618587db7d203',
308
+ `official clone commit is ${before.commit}`)
309
+ assert(before.tree === 'bd7dd6d90010a35d3d6ff9f12c1f6207d5b6fe38',
310
+ `official clone tree is ${before.tree}`)
311
+ assert(before.status === '', 'official clone is dirty before CLI smoke')
312
+
313
+ const temporaryRoot = await mkdtemp(join(tmpdir(), 'dsh-selector-official-clone-'))
314
+ const worktree = join(temporaryRoot, 'official')
315
+ const dshHome = join(temporaryRoot, 'dsh-home')
316
+ let added = false
317
+ const environment = { ...process.env, DSH_HOME: dshHome }
318
+ let lastLifecycle = { command: '(none)', code: 0, stdout: '', stderr: '' }
319
+ // Positive controls for the CLI invocation path (issue #2). Declared at
320
+ // function scope so the failure evidence can always report them, and assigned
321
+ // once the clone checkout exists (spawn needs `cwd: worktree` to resolve).
322
+ let scriptLayerControl = { code: null, stdout: '', stderr: '' }
323
+ let directEntryControl = { code: null, stdout: '', stderr: '' }
324
+ /** Path of the tiny runner that invokes the CLI's exported entry (see below). */
325
+ let cliRunnerPath = null
326
+ /**
327
+ * Run the clone's CLI.
328
+ *
329
+ * Measured root cause of issue #2: the pinned clone's `apps/cli/src/bin.ts`
330
+ * dispatches through `if (import.meta.main) { await runCli() }`, and under
331
+ * tsx that flag evaluates falsy — so the module loads and does NOTHING. Both
332
+ * `pnpm dsh …` (the clone's own `dsh` script) and a direct
333
+ * `node --import tsx/esm apps/cli/src/bin.ts …` therefore exit 0 with empty
334
+ * output, which is exactly what the two positive controls report. The leg
335
+ * calls the CLI's EXPORTED entry instead, with argv shaped the way the entry
336
+ * would see it, so the lifecycle exercises the CLI rather than the loader's
337
+ * handling of a self-execution guard.
338
+ */
339
+ const dsh = async (...args) => {
340
+ if (cliRunnerPath === null) throw new Error('e2e: the CLI runner probe was not prepared')
341
+ const outcome = await captureOutcome(
342
+ process.execPath,
343
+ ['--import', 'tsx/esm', cliRunnerPath, ...args],
344
+ { cwd: worktree, env: environment },
345
+ )
346
+ lastLifecycle = {
347
+ command: `dsh ${args.join(' ')}`,
348
+ code: outcome.code ?? -1,
349
+ stdout: outcome.stdout,
350
+ stderr: outcome.stderr,
351
+ }
352
+ if (outcome.code !== 0) {
353
+ throw new Error([
354
+ `${lastLifecycle.command} exited ${String(lastLifecycle.code)}`,
355
+ outcome.stdout.trim(),
356
+ outcome.stderr.trim(),
357
+ ].filter(Boolean).join('\n'))
358
+ }
359
+ }
360
+ const dumpConfig = () => capture(
361
+ process.execPath,
362
+ ['--import', 'tsx/esm', cliRunnerPath, '--profile', 'web', '--dump-config'],
363
+ {
364
+ cwd: worktree,
365
+ env: environment,
366
+ },
367
+ ).then(captured => captured.stdout)
368
+
369
+ /** Installed manifest of the profile-resolved plugin package. */
370
+ const profilePackages = () => {
371
+ const profileRoot = join(dshHome, 'profiles/web')
372
+ const profileRequire = createRequire(join(profileRoot, 'package.json'))
373
+ let selectorPath
374
+ try {
375
+ selectorPath = profileRequire.resolve('dsh-context-compression-improved/package.json')
376
+ } catch (error) {
377
+ // A silent no-op lifecycle command is the difference between "the package
378
+ // manager refused" and "the CLI exited 0 without installing anything";
379
+ // carry that evidence instead of a bare MODULE_NOT_FOUND.
380
+ const declared = (() => {
381
+ try {
382
+ return JSON.stringify(JSON.parse(readFileSync(join(profileRoot, 'package.json'), 'utf8')).dependencies ?? {})
383
+ } catch {
384
+ return '(profile package.json unreadable)'
385
+ }
386
+ })()
387
+ const installed = (() => {
388
+ try {
389
+ return JSON.stringify(readdirSync(join(profileRoot, 'node_modules')).slice(0, 40))
390
+ } catch {
391
+ return '(profiles/web/node_modules unreadable)'
392
+ }
393
+ })()
394
+ throw new Error([
395
+ `official profile ${profileRoot} does not resolve dsh-context-compression-improved`,
396
+ `last lifecycle: ${lastLifecycle.command} (exit ${String(lastLifecycle.code)})`,
397
+ `lifecycle stdout: ${lastLifecycle.stdout.trim()}`,
398
+ `lifecycle stderr: ${lastLifecycle.stderr.trim()}`,
399
+ // Positive controls: see the comment where they are captured (issue #2).
400
+ `control script-layer (pnpm dsh --version): exit ${String(scriptLayerControl.code)} out=${scriptLayerControl.stdout.trim()} err=${scriptLayerControl.stderr.trim()}`,
401
+ `control direct-entry (tsx bin.ts --version): exit ${String(directEntryControl.code)} out=${directEntryControl.stdout.trim()} err=${directEntryControl.stderr.trim()}`,
402
+ `profile dependencies: ${declared}`,
403
+ `profiles/web/node_modules: ${installed}`,
404
+ ].join('\n'), { cause: error })
405
+ }
406
+ return {
407
+ profileRoot,
408
+ selectorPath,
409
+ selector: JSON.parse(readFileSync(selectorPath, 'utf8')),
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Host-plane runtime entries of the installed package. `client.js` is
415
+ * excluded: it is a lazy-CJS web artifact whose requires (`react`, the
416
+ * ui-slot packages) the web bundler supplies, and that stack is verified
417
+ * from the built client libraries below.
418
+ */
419
+ const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'config.js', 'tail-trim.js', 'invariant.js']
420
+
421
+ /**
422
+ * Bare package names the installed package's host-plane runtime files import.
423
+ *
424
+ * The runtime directory is read off the INSTALLED manifest's own `main` rather
425
+ * than assumed: the tarball this gate packs is `packages/selector` (`main`
426
+ * `lib/index.js`), while the published root manifest points at
427
+ * `packages/selector/lib/index.js`. Guessing either one read the wrong tree
428
+ * and failed closed on an ENOENT that said nothing about the plugin.
429
+ *
430
+ * @param selectorDir - Installed directory of the plugin package.
431
+ * @param selectorManifest - The installed manifest, for its `main` field.
432
+ * @returns The package roots the host must be able to resolve.
433
+ */
434
+ const hostPlaneRuntimeImports = async (selectorDir, selectorManifest) => {
435
+ const main = selectorManifest?.main
436
+ if (typeof main !== 'string' || main.length === 0) {
437
+ throw new Error(`installed package declares no main entry: ${JSON.stringify(selectorManifest?.main)}`)
438
+ }
439
+ const runtimeDir = dirname(join(selectorDir, main))
440
+ if (!existsSync(runtimeDir)) {
441
+ throw new Error(`installed package main ${main} points at a directory that is not in the tarball: ${runtimeDir}`)
442
+ }
443
+ const names = new Set()
444
+ for (const entry of HOST_PLANE_ENTRIES) {
445
+ const source = await readFile(join(runtimeDir, entry), 'utf8')
446
+ for (const match of source.matchAll(/(?:^|[^.\w])(?:import|export)\s[^;]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])(?:import|require)\s*\(\s*['"]([^'"]+)['"]\s*\)/gmu)) {
447
+ const specifier = match[1] ?? match[2]
448
+ if (specifier.startsWith('.') || specifier.startsWith('node:')) continue
449
+ names.add(specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/'))
450
+ }
451
+ }
452
+ if (names.size === 0) throw new Error('installed package exposes no host-plane runtime import to verify')
453
+ return names
454
+ }
455
+
456
+ /**
457
+ * Verify every web/client peer exists as a BUILT artifact resolvable from
458
+ * the packages that depend on it. Executable loading of the client stack
459
+ * happens under the web bundler, not bare Node (the UI packages ship CSS
460
+ * modules only a bundler can import): that load leg is the `build:web`
461
+ * step of the worktree's `pnpm run build` above, which fails closed when
462
+ * the client graph is broken.
463
+ */
464
+ const proveBuiltClientPeersLoad = async () => {
465
+ const clientPeers = [
466
+ '@deepseek-ai/dsh-client-locale',
467
+ '@deepseek-ai/dsh-client-store',
468
+ '@deepseek-ai/dsh-client-ui-primitives',
469
+ '@deepseek-ai/dsh-client-ui-settings',
470
+ '@deepseek-ai/dsh-client-ui-slots',
471
+ '@deepseek-ai/dsh-client-ui-workspace',
472
+ 'react',
473
+ ]
474
+ // pnpm's isolated layout keeps each package's dependents in ITS own
475
+ // node_modules, so anchor resolution at the packages that actually
476
+ // depend on the client stack: the web-app bundle (locale, store,
477
+ // ui-settings, ui-workspace), the client-locale package (react,
478
+ // ui-primitives, ui-slots), and the web app.
479
+ const anchors = JSON.stringify([
480
+ join(worktree, 'packages/bundle/web-app/package.json'),
481
+ join(worktree, 'packages/client/locale/package.json'),
482
+ join(worktree, 'apps/web/package.json'),
483
+ ])
484
+ const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', [
485
+ "const { createRequire } = require('node:module')",
486
+ `const anchors = ${anchors}.map(path => createRequire(path))`,
487
+ `for (const peer of ${JSON.stringify(clientPeers)}) {`,
488
+ ' const resolved = anchors.some(requireFrom => {',
489
+ ' try { requireFrom.resolve(peer); return true } catch { return false }',
490
+ ' })',
491
+ " if (!resolved) throw new Error('built client peer resolved from no dependent package: ' + peer)",
492
+ '}',
493
+ "console.log('CLIENT_PEERS_OK')",
494
+ ].join('\n')], { cwd: worktree, env: environment })
495
+ if (outcome.code !== 0 || !outcome.stdout.includes('CLIENT_PEERS_OK')) {
496
+ throw new Error(`built client peers failed to resolve in the official worktree:\n${outcome.stdout}\n${outcome.stderr}`)
497
+ }
498
+ return clientPeers.length
499
+ }
500
+
501
+ /**
502
+ * Prove the plugin actually loads in the official profile: pnpm's peers check
503
+ * cannot see the healed profiles/node_modules fallback by design, so the
504
+ * release gate resolves and imports instead. Fail-closed parts:
505
+ *
506
+ * - every bare specifier the HOST-plane runtime files import must resolve from
507
+ * the profile. That set is DERIVED from the installed artifact rather than
508
+ * listed by hand: 0.5.3 imported `@deepseek-ai/schemastery` while declaring
509
+ * it in no manifest a consumer reads, and a hand-maintained whitelist plus a
510
+ * hand-maintained dependency list could not see it;
511
+ * - every declared runtime dependency must resolve (the install surface);
512
+ * - the node entry must import and export a callable `apply()`;
513
+ * - a declared peer may stay unresolved only when no host-plane file imports
514
+ * it — the web-host client packages are supplied by the web app, and their
515
+ * built libraries are verified separately below.
516
+ */
517
+ const provePluginLoads = async () => {
518
+ const { profileRoot, selectorPath, selector } = profilePackages()
519
+ const selectorPeers = Object.keys(selector.peerDependencies ?? {})
520
+ const selectorDependencies = Object.keys(selector.dependencies ?? {})
521
+ const runtimeImports = [...await hostPlaneRuntimeImports(dirname(selectorPath), selector)].sort()
522
+ const required = [...new Set([...runtimeImports, ...selectorDependencies])].sort()
523
+ const script = [
524
+ "const { createRequire } = require('node:module')",
525
+ `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
526
+ `for (const name of ${JSON.stringify(required)}) {`,
527
+ ' requireFromProfile.resolve(name)',
528
+ '}',
529
+ "const selectorEntry = requireFromProfile.resolve('dsh-context-compression-improved')",
530
+ 'const plugin = require(selectorEntry)',
531
+ "if (typeof plugin.apply !== 'function') throw new Error('selector entry exports no apply()')",
532
+ 'const unresolvedPeers = []',
533
+ `for (const peer of ${JSON.stringify(selectorPeers)}) {`,
534
+ ' try { requireFromProfile.resolve(peer) } catch { unresolvedPeers.push(peer) }',
535
+ '}',
536
+ "console.log('LOAD_OK ' + JSON.stringify(unresolvedPeers))",
537
+ ].join('\n')
538
+ const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
539
+ cwd: worktree,
540
+ env: environment,
541
+ })
542
+ const marker = outcome.stdout.split('\n').find(line => line.startsWith('LOAD_OK'))
543
+ if (outcome.code !== 0 || marker === undefined) {
544
+ throw new Error(`official profile failed to load the plugin, its host-plane imports and its engine peers:\n${outcome.stdout}\n${outcome.stderr}`)
545
+ }
546
+ const unresolvedPeers = JSON.parse(marker.slice('LOAD_OK '.length))
547
+ const importedWithoutProvider = unresolvedPeers.filter(peer => runtimeImports.includes(peer))
548
+ if (importedWithoutProvider.length > 0) {
549
+ throw new Error(`selector peers the host-plane runtime imports did not resolve from the profile: ${importedWithoutProvider.join(', ')}`)
550
+ }
551
+ return {
552
+ hostPlaneRuntimeImports: runtimeImports,
553
+ installedRuntimeDependencies: selectorDependencies,
554
+ unresolvedSelectorPeers: unresolvedPeers,
555
+ builtClientPeersVerified: await proveBuiltClientPeersLoad(),
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Boot the official profile FOR REAL through the CLI's own profile-boot
561
+ * path — not --dump-config, which composes YAML without booting or
562
+ * executing plugins. The probe mounts the full bundle tree (selector
563
+ * included), then proves: the settings service resolves the registered
564
+ * document (before the upgrade: the previous release's schema defaults;
565
+ * after: the seeded savings/73 document parsed with the INSTALLED runtime),
566
+ * the AgentPresets service composed the selector's standing overlay, and
567
+ * the overlay's generated composition exists with the deterministic
568
+ * identity filename. Any failure exits non-zero.
569
+ */
570
+ const runProfileBootProbe = async (phase, expectSeeded) => {
571
+ const profilePort = await allocateLoopbackPort()
572
+ const { profileRoot } = profilePackages()
573
+ const settingsProof = expectSeeded
574
+ ? [
575
+ ' const requireFromProfile = createRequire(profileRoot)',
576
+ " const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
577
+ ' const plugin = requireFromProfile(pluginEntry)',
578
+ ' const parsed = plugin.parseContextCompressionSettings(structuredClone(raw))',
579
+ " if (parsed.profile !== 'savings' || parsed.autoCompact.thresholdPercent !== 73) {",
580
+ " throw new Error('boot probe: booted settings did not expose the seeded document: ' + JSON.stringify(parsed))",
581
+ ' }',
582
+ ]
583
+ : [
584
+ // The previous release predates the autoCompact section and the
585
+ // public parser; prove its OWN schema resolved the registered
586
+ // namespace into a complete supported document instead.
587
+ " if (raw?.profile !== 'balanced' || raw?.custom?.version !== 3) {",
588
+ " throw new Error('boot probe: previous-release settings defaults did not resolve: ' + JSON.stringify(raw))",
589
+ ' }',
590
+ ]
591
+ const probe = [
592
+ "import { readdir } from 'node:fs/promises'",
593
+ "import { tmpdir } from 'node:os'",
594
+ "import { join } from 'node:path'",
595
+ "import { createRequire } from 'node:module'",
596
+ "import { pathToFileURL } from 'node:url'",
597
+ `const worktree = String.raw\`${worktree}\``,
598
+ `const profileRoot = String.raw\`${join(profileRoot, 'package.json')}\``,
599
+ 'const bootModule = await import(pathToFileURL(join(worktree, \'apps/cli/src/profile-boot.ts\')).href)',
600
+ // Import the workspace packages from their source trees (pinned, like
601
+ // the profile-boot path above): the probe runs under tsx, and their
602
+ // lib/ artifacts are only produced by the full release build, not the
603
+ // library faces.
604
+ "const appBoot = await import(pathToFileURL(join(worktree, 'packages/boot/app-boot/src/index.ts')).href)",
605
+ "const settingsModule = await import(pathToFileURL(join(worktree, 'packages/settings/settings/src/index.ts')).href)",
606
+ 'const preBootStores = new Set(await readdir(tmpdir()))',
607
+ 'const { ctx } = await bootModule.runProfile({',
608
+ " environment: appBoot.loadLayeredEnv('dsh'),",
609
+ " profile: 'web',",
610
+ ' patchFiles: [],',
611
+ ` args: ['--host', '127.0.0.1', '--port', ${JSON.stringify(String(profilePort))}, '--no-open'],`,
612
+ '})',
613
+ 'try {',
614
+ " const settings = ctx.get('settings')",
615
+ " if (settings === undefined) throw new Error('boot probe: settings service missing')",
616
+ " const raw = settings.get('context-compression')",
617
+ ...settingsProof,
618
+ " const presets = ctx.get('agentPresets')",
619
+ " if (presets === undefined) throw new Error('boot probe: agentPresets service missing')",
620
+ ' const key = await presets.standingKeyFor()',
621
+ ' if (key?.agentPreset !== \'standard\') {',
622
+ " throw new Error('boot probe: standing key did not compose the default preset: ' + JSON.stringify(key))",
623
+ ' }',
624
+ // Only stores CREATED BY THIS BOOT count: stale leftovers from earlier
625
+ // runs or concurrent harnesses must never satisfy the overlay proof.
626
+ ' const generated = []',
627
+ " for (const entry of await readdir(tmpdir(), { withFileTypes: true })) {",
628
+ ' if (!entry.isDirectory() || preBootStores.has(entry.name)) continue',
629
+ " if (!entry.name.startsWith('dsh-context-compression-presets-')) continue",
630
+ ' let children',
631
+ ' try {',
632
+ ' children = await readdir(join(tmpdir(), entry.name))',
633
+ ' } catch {',
634
+ ' continue // a concurrent process disposed its store mid-scan',
635
+ ' }',
636
+ " for (const child of children) {",
637
+ " if (/^standard-[0-9a-f]{24}\\.agent\\.cordis\\.yml$/u.test(child)) generated.push(child)",
638
+ ' }',
639
+ ' }',
640
+ ' if (generated.length === 0) {',
641
+ " throw new Error('boot probe: the selector preset overlay generated no standing composition in this boot')",
642
+ ' }',
643
+ " console.log('BOOT_PROBE_OK ' + JSON.stringify({ phase: " + JSON.stringify(phase) + ", settings: " + JSON.stringify(expectSeeded ? 'seeded-savings-73' : 'previous-release-defaults') + ", generated: generated.length }))",
644
+ '} finally {',
645
+ ' await ctx.fiber.dispose()',
646
+ '}',
647
+ 'process.exit(0)',
648
+ ].join('\n')
649
+ const probePath = join(temporaryRoot, `boot-probe-${phase}.mjs`)
650
+ await writeFile(probePath, probe, 'utf8')
651
+ const outcome = await captureOutcome(process.execPath, ['--import', 'tsx/esm', probePath], {
652
+ cwd: worktree,
653
+ env: environment,
654
+ })
655
+ const marker = outcome.stdout.split('\n').find(line => line.startsWith('BOOT_PROBE_OK'))
656
+ if (outcome.code !== 0 || marker === undefined) {
657
+ throw new Error(`official profile boot probe (${phase}) failed:\n${outcome.stdout}\n${outcome.stderr}`)
658
+ }
659
+ return JSON.parse(marker.slice('BOOT_PROBE_OK '.length))
660
+ }
661
+
662
+ /** Seed real user settings through the plugin's own public surface. */
663
+ const seedSettings = async () => {
664
+ const { profileRoot } = profilePackages()
665
+ const settingsPath = join(dshHome, 'settings.yaml')
666
+ const script = [
667
+ "const { writeFileSync, readFileSync, existsSync } = require('node:fs')",
668
+ "const { createRequire } = require('node:module')",
669
+ "const yaml = require('js-yaml')",
670
+ `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
671
+ "const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
672
+ 'const plugin = require(pluginEntry)',
673
+ "const document = {",
674
+ " 'context-compression': {",
675
+ " profile: 'savings',",
676
+ ' custom: plugin.DEFAULT_CUSTOM_COMPRESSION_POLICY,',
677
+ ' autoCompact: { thresholdPercent: 73 },',
678
+ ' },',
679
+ '}',
680
+ `const path = String.raw\`${settingsPath}\``,
681
+ 'const merged = existsSync(path) ? { ...yaml.load(readFileSync(path, \'utf8\')), ...document } : document',
682
+ "writeFileSync(path, yaml.dump(merged), 'utf8')",
683
+ "console.log('SEED_OK')",
684
+ ].join('\n')
685
+ const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
686
+ cwd: worktree,
687
+ env: environment,
688
+ })
689
+ if (outcome.code !== 0 || !outcome.stdout.includes('SEED_OK')) {
690
+ throw new Error(`seeding official-profile settings failed:\n${outcome.stdout}\n${outcome.stderr}`)
691
+ }
692
+ return settingsPath
693
+ }
694
+
695
+ /** Read the seeded settings back through the upgraded plugin's parser. */
696
+ const proveSettingsPreserved = async (settingsPath) => {
697
+ const { profileRoot } = profilePackages()
698
+ const script = [
699
+ "const { readFileSync } = require('node:fs')",
700
+ "const { createRequire } = require('node:module')",
701
+ 'const yaml = require(\'js-yaml\')',
702
+ `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
703
+ "const pluginEntry = requireFromProfile.resolve('dsh-context-compression-improved/pruner')",
704
+ 'const plugin = require(pluginEntry)',
705
+ `const document = yaml.load(readFileSync(String.raw\`${settingsPath}\`, 'utf8'))`,
706
+ "const parsed = plugin.parseContextCompressionSettings(document['context-compression'])",
707
+ "if (parsed.profile !== 'savings' || parsed.autoCompact.thresholdPercent !== 73) {",
708
+ " throw new Error('upgraded profile lost the saved user settings: ' + JSON.stringify(parsed))",
709
+ '}',
710
+ "console.log('SETTINGS_OK')",
711
+ ].join('\n')
712
+ const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
713
+ cwd: worktree,
714
+ env: environment,
715
+ })
716
+ if (outcome.code !== 0 || !outcome.stdout.includes('SETTINGS_OK')) {
717
+ throw new Error(`settings preservation proof failed:\n${outcome.stdout}\n${outcome.stderr}`)
718
+ }
719
+ }
720
+
721
+ try {
722
+ await run('git', ['worktree', 'add', '--detach', worktree, before.commit], { cwd: clone })
723
+ added = true
724
+ await run('pnpm', ['install', '--frozen-lockfile', '--ignore-scripts'], { cwd: worktree })
725
+ // A source checkout ships no built artifacts (install above skips
726
+ // prepare scripts). The boot probes run the REAL web profile —
727
+ // dsh-base + dsh-web-app, the only bundle that mounts agent-presets and
728
+ // therefore the selector's preset overlay — so build both library faces
729
+ // AND the web frontend; the healed profiles/node_modules fallback also
730
+ // symlinks the CLI's own workspace packages, which is why the checkout's
731
+ // `vendor/schemastery/lib` has to exist too.
732
+ await run('pnpm', ['run', 'build'], { cwd: worktree })
733
+ // Fail closed on the artifacts every later probe needs. Measured on the Node
734
+ // this workflow used to pin (24.0.0): `tsx` leaves `import.meta.main`
735
+ // undefined there, the clone's guarded `scripts/build.ts` exited 0 in about
736
+ // eight seconds having emitted nothing, and the boot probe then failed twice
737
+ // over — `client bundles not found; run \`pnpm run build\` before launch`
738
+ // from client composition, and `Cannot find module
739
+ // .../profiles/node_modules/@deepseek-ai/schemastery/lib/index.mjs` from the
740
+ // plugin, because the installation fallback resolves that name to the source
741
+ // checkout's `vendor/schemastery`, whose `lib` only this build produces.
742
+ for (const artifact of [
743
+ 'packages/client/ui-settings/lib/client.js',
744
+ 'vendor/schemastery/lib/index.mjs',
745
+ ]) {
746
+ if (!existsSync(join(worktree, artifact))) {
747
+ throw new Error([
748
+ `official clone build produced no ${artifact}`,
749
+ 'the clone\'s build script is `tsx scripts/build.ts`, guarded by `if (import.meta.main)`;',
750
+ 'tsx leaves that flag undefined on Node < 24.2, so the build exits 0 without building',
751
+ ].join(' '))
752
+ }
753
+ }
754
+
755
+ // Positive controls (recorded, never asserted), captured HERE because the
756
+ // clone checkout must exist: `cwd: worktree` is what makes spawn work at
757
+ // all. The clone's `dsh` script is `node --import tsx/esm
758
+ // apps/cli/src/bin.ts`, and bin.ts' `plugin` mode ALWAYS calls runPlugin —
759
+ // which either initializes the profile (printing `dsh: initialized profile
760
+ // …`), forwards pnpm's inherited stdio, or reports a missing pnpm with exit
761
+ // 127. It therefore cannot exit 0 with empty output, so a silent lifecycle
762
+ // means the CLI never reached that mode. These two probes tell the two
763
+ // candidate causes apart: the package manager's script layer swallowing the
764
+ // invocation, versus the CLI entry itself. See issue #2.
765
+ scriptLayerControl = await captureOutcome('pnpm', ['dsh', '--version'], { cwd: worktree, env: environment })
766
+ directEntryControl = await captureOutcome(
767
+ process.execPath,
768
+ ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', '--version'],
769
+ { cwd: worktree, env: environment },
770
+ )
771
+ // The runner the lifecycle uses. It imports the entry and calls the
772
+ // exported `runCli()` after shaping argv exactly as the entry would see it
773
+ // (`argv[1]` = the entry path), so every mode the entry supports — profile
774
+ // boot, plugin forwarding, config dumps, help, version — behaves as it does
775
+ // when the file really is the process entry point.
776
+ cliRunnerPath = join(temporaryRoot, 'run-cli.mjs')
777
+ await writeFile(cliRunnerPath, [
778
+ "import { pathToFileURL } from 'node:url'",
779
+ `const entry = ${JSON.stringify(join(worktree, 'apps/cli/src/bin.ts'))}`,
780
+ 'process.argv = [process.argv[0], entry, ...process.argv.slice(2)]',
781
+ 'const { runCli } = await import(pathToFileURL(entry).href)',
782
+ 'await runCli()',
783
+ ].join('\n'), 'utf8')
784
+
785
+ // Real lifecycle: start on the published previous release.
786
+ if (upgradeFrom === undefined) throw new Error('release gate requires the previous published release for the official lifecycle')
787
+ await dsh('plugin', '--profile', 'web', 'add',
788
+ `dsh-context-compression-improved@${upgradeFrom}`, '--registry', registry)
789
+ const beforeUp = profilePackages()
790
+ if (beforeUp.selector.version !== upgradeFrom) {
791
+ throw new Error(`official lifecycle started on ${String(beforeUp.selector.version)}, expected ${upgradeFrom}`)
792
+ }
793
+
794
+ // Boot the profile once on the previous release. This asserts the added
795
+ // bundle layer is live before any update and heals
796
+ // $DSH_HOME/profiles/node_modules — the shared-module fallback the
797
+ // plugin's harness peers resolve through in every later raw-node proof.
798
+ const addedDump = await dumpConfig()
799
+ assert(addedDump.includes('context-compression-improved-bundle'),
800
+ 'official post-add dump lacks the context-compression Bundle layer')
801
+
802
+ // Real profile start on the previous release, BEFORE seeding: the
803
+ // previous-release schema predates the autoCompact section, so this probe
804
+ // proves its own defaults resolve; the seeded document is asserted by the
805
+ // post-up probe through the upgraded runtime.
806
+ const postAddBoot = await runProfileBootProbe('post-add', false)
807
+
808
+ const settingsPath = await seedSettings()
809
+
810
+ // Standard update command moves the one install-facing package; assert the
811
+ // version it lands before anything else runs.
812
+ await dsh('plugin', '--profile', 'web', 'up',
813
+ 'dsh-context-compression-improved@latest', '--registry', registry)
814
+ const afterUp = profilePackages()
815
+ if (afterUp.selector.version !== candidateVersion) {
816
+ throw new Error(`official up landed ${String(afterUp.selector.version)}, expected ${String(candidateVersion)}`)
817
+ }
818
+ await proveSettingsPreserved(settingsPath)
819
+ const loadProof = await provePluginLoads()
820
+ const postUpBoot = await runProfileBootProbe('post-up', true)
821
+ const upDump = await dumpConfig()
822
+ for (const marker of ['context-compression-improved-bundle', 'presetOverlay: true']) {
823
+ assert(upDump.includes(marker), `official post-up dump lacks ${marker}`)
824
+ }
825
+ assert(upDump.match(/context-compression-improved-bundle/gu)?.length === 1,
826
+ 'official post-up dump contains more than one context-compression Bundle layer')
827
+
828
+ // pnpm's peers check is informational: plugin peers resolve through the
829
+ // healed profiles/node_modules fallback, which pnpm cannot see by design.
830
+ const peers = await captureOutcome('pnpm', ['peers', 'check'], {
831
+ cwd: join(dshHome, 'profiles/web'),
832
+ env: environment,
833
+ })
834
+
835
+ await dsh('plugin', '--profile', 'web', 'remove', 'dsh-context-compression-improved')
836
+ const removedDump = await dumpConfig()
837
+ assert(!removedDump.includes('context-compression-improved-bundle'),
838
+ 'official CLI remove left the context-compression Bundle layer active')
839
+
840
+ await dsh('plugin', '--profile', 'web', 'add',
841
+ 'dsh-context-compression-improved@latest', '--registry', registry)
842
+ const secondDump = await dumpConfig()
843
+ assert(secondDump.includes('context-compression-improved-bundle'),
844
+ 'official CLI reinstall did not restore the context-compression Bundle layer')
845
+
846
+ return {
847
+ tag: before.tag,
848
+ commit: before.commit,
849
+ tree: before.tree,
850
+ status: 'clean',
851
+ install: 'entry-package-only',
852
+ upgrade: {
853
+ from: upgradeFrom,
854
+ to: candidateVersion,
855
+ selector: afterUp.selector.version,
856
+ settingsPreserved: true,
857
+ pluginAndEnginePeersLoad: loadProof,
858
+ realProfileBoot: { postAdd: postAddBoot, postUp: postUpBoot },
859
+ dump: 'single-bundle-layer',
860
+ },
861
+ remove: 'bundle-removed',
862
+ reinstall: 'bundle-restored',
863
+ peersCheck: {
864
+ exitCode: peers.code,
865
+ note: 'informational: plugin peers resolve via the healed profiles/node_modules fallback, proven by load',
866
+ },
867
+ }
868
+ } finally {
869
+ if (added) await run('git', ['worktree', 'remove', '--force', worktree], { cwd: clone })
870
+ await rm(temporaryRoot, { recursive: true, force: true })
871
+ }
872
+ }
873
+
874
+ const fixedArtifactRoot = process.env.DSH_SELECTOR_ARTIFACT_DIR
875
+ const artifactRoot = fixedArtifactRoot === undefined
876
+ ? await mkdtemp(join(tmpdir(), 'dsh-selector-pack-'))
877
+ : await realpath(fixedArtifactRoot)
878
+ const ownsArtifactRoot = fixedArtifactRoot === undefined
879
+ const comparisonRoot = fixedArtifactRoot === undefined
880
+ ? undefined
881
+ : await mkdtemp(join(tmpdir(), 'dsh-selector-rebuild-'))
882
+ const consumerRoot = await mkdtemp(join(tmpdir(), 'dsh-selector-consumer-'))
883
+ let server
884
+
885
+ try {
886
+ const registryPackages = new Map()
887
+ // Published previous-release metadata served alongside the packed candidate
888
+ // so the upgrade leg can install the real shipped release first.
889
+ const previousVersions = new Map()
890
+ // The predecessor is whatever the registry actually offers. This used to be
891
+ // the pinned literal '0.1.0-beta.2', which only ever existed under this
892
+ // package's pre-rename name, so it could never resolve under the current one.
893
+ let previousRelease = ''
894
+ // True only once a real predecessor was found. Both release-mode gates below
895
+ // key off it: the upgrade leg must run whenever users have something to
896
+ // upgrade FROM, and must not block a package that has nothing to upgrade from.
897
+ let predecessorFound = false
898
+ let upgradeLeg = 'skipped-no-network'
899
+ for (const name of ['dsh-context-compression-improved']) {
900
+ try {
901
+ const packumentResponse = await fetch(`https://registry.npmjs.org/${name}`)
902
+ if (packumentResponse.status === 404) {
903
+ upgradeLeg = 'skipped-package-not-published'
904
+ previousVersions.clear()
905
+ break
906
+ }
907
+ if (!packumentResponse.ok) throw new Error(`packument responded ${packumentResponse.status}`)
908
+ const packument = await packumentResponse.json()
909
+ const localVersion = JSON.parse(await readFile(join(packages[0].directory, 'package.json'), 'utf8')).version
910
+ const times = packument.time ?? {}
911
+ // Publication order, not semver order: the version a user would be
912
+ // upgrading from is the most recently published one that is not the
913
+ // candidate. Avoids a semver dependency and handles prereleases.
914
+ const earlier = Object.keys(packument.versions ?? {})
915
+ .filter((version) => version !== localVersion)
916
+ .sort((a, b) => Date.parse(times[b] ?? '') - Date.parse(times[a] ?? ''))
917
+ if (earlier.length === 0) {
918
+ upgradeLeg = 'skipped-no-earlier-release'
919
+ previousVersions.clear()
920
+ break
921
+ }
922
+ previousRelease = earlier[0]
923
+ const response = await fetch(`https://registry.npmjs.org/${name}/${previousRelease}`)
924
+ if (!response.ok) throw new Error(`packument responded ${response.status}`)
925
+ const manifest = await response.json()
926
+ const tarballResponse = await fetch(manifest.dist.tarball)
927
+ if (!tarballResponse.ok) throw new Error(`tarball responded ${tarballResponse.status}`)
928
+ const bytes = Buffer.from(await tarballResponse.arrayBuffer())
929
+ const filename = `${name}-${previousRelease}.tgz`
930
+ const tarball = join(artifactRoot, `previous-${filename}`)
931
+ await writeFile(tarball, bytes)
932
+ previousVersions.set(name, {
933
+ filename,
934
+ manifest,
935
+ tarball,
936
+ sha1: createHash('sha1').update(bytes).digest('hex'),
937
+ integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
938
+ })
939
+ } catch (error) {
940
+ if (e2eMode === 'release') {
941
+ throw new Error(`release gate requires the published previous release for the upgrade leg: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
942
+ }
943
+ upgradeLeg = `skipped-previous-release-unavailable:${error instanceof Error ? error.message : String(error)}`
944
+ previousVersions.clear()
945
+ break
946
+ }
947
+ }
948
+ if (previousVersions.size === 1) {
949
+ upgradeLeg = 'installed'
950
+ predecessorFound = true
951
+ }
952
+ for (const descriptor of packages) {
953
+ const manifest = JSON.parse(await readFile(join(descriptor.directory, 'package.json'), 'utf8'))
954
+ if (fixedArtifactRoot === undefined) {
955
+ await run('npm', ['pack', '--pack-destination', artifactRoot, descriptor.directory], { cwd: root })
956
+ }
957
+ const filename = `${manifest.name}-${manifest.version}.tgz`
958
+ const tarball = join(artifactRoot, filename)
959
+ await stat(tarball)
960
+ const bytes = await readFile(tarball)
961
+ if (comparisonRoot !== undefined) {
962
+ await run('npm', ['pack', '--pack-destination', comparisonRoot, descriptor.directory], { cwd: root })
963
+ const rebuilt = await readFile(join(comparisonRoot, filename))
964
+ const reviewedHash = createHash('sha256').update(bytes).digest('hex')
965
+ const rebuiltHash = createHash('sha256').update(rebuilt).digest('hex')
966
+ if (reviewedHash !== rebuiltHash) {
967
+ throw new Error(`${manifest.name} fixed tarball differs from the current workspace rebuild`)
968
+ }
969
+ }
970
+ registryPackages.set(manifest.name, {
971
+ filename,
972
+ manifest,
973
+ tarball,
974
+ sha1: createHash('sha1').update(bytes).digest('hex'),
975
+ sha256: createHash('sha256').update(bytes).digest('hex'),
976
+ integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
977
+ })
978
+ }
979
+
980
+ server = createServer(async (request, response) => {
981
+ try {
982
+ const requestUrl = new URL(request.url ?? '/', 'http://127.0.0.1')
983
+ const decodedPath = decodeURIComponent(requestUrl.pathname)
984
+ for (const [name, descriptor] of registryPackages) {
985
+ if (decodedPath === `/${name}`) {
986
+ const address = server.address()
987
+ if (address === null || typeof address === 'string') throw new Error('registry has no TCP address')
988
+ const tarballUrl = `http://127.0.0.1:${address.port}/${name}/-/${descriptor.filename}`
989
+ const version = {
990
+ ...descriptor.manifest,
991
+ dist: {
992
+ tarball: tarballUrl,
993
+ shasum: descriptor.sha1,
994
+ integrity: descriptor.integrity,
995
+ },
996
+ }
997
+ const previous = previousVersions.get(name)
998
+ const previousVersion = previous === undefined ? {} : {
999
+ [previous.manifest.version]: {
1000
+ ...previous.manifest,
1001
+ dist: {
1002
+ tarball: `http://127.0.0.1:${address.port}/${name}/-/${previous.filename}`,
1003
+ shasum: previous.sha1,
1004
+ integrity: previous.integrity,
1005
+ },
1006
+ },
1007
+ }
1008
+ const body = JSON.stringify({
1009
+ name,
1010
+ 'dist-tags': { latest: descriptor.manifest.version },
1011
+ versions: { ...previousVersion, [descriptor.manifest.version]: version },
1012
+ })
1013
+ response.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) })
1014
+ response.end(request.method === 'HEAD' ? undefined : body)
1015
+ return
1016
+ }
1017
+ if (decodedPath === `/${name}/-/${descriptor.filename}`) {
1018
+ const details = await stat(descriptor.tarball)
1019
+ response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': details.size })
1020
+ if (request.method === 'HEAD') response.end()
1021
+ else createReadStream(descriptor.tarball).pipe(response)
1022
+ return
1023
+ }
1024
+ }
1025
+ for (const [name, previous] of previousVersions) {
1026
+ if (decodedPath === `/${name}/-/${previous.filename}`) {
1027
+ const details = await stat(previous.tarball)
1028
+ response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': details.size })
1029
+ if (request.method === 'HEAD') response.end()
1030
+ else createReadStream(previous.tarball).pipe(response)
1031
+ return
1032
+ }
1033
+ }
1034
+
1035
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
1036
+ response.writeHead(404).end()
1037
+ return
1038
+ }
1039
+ const upstream = await fetch(`https://registry.npmjs.org${requestUrl.pathname}${requestUrl.search}`, {
1040
+ method: request.method,
1041
+ headers: { accept: request.headers.accept ?? '*/*' },
1042
+ })
1043
+ const headers = {}
1044
+ for (const name of ['content-type', 'content-length', 'cache-control', 'etag', 'last-modified']) {
1045
+ const value = upstream.headers.get(name)
1046
+ if (value !== null) headers[name] = value
1047
+ }
1048
+ response.writeHead(upstream.status, headers)
1049
+ if (request.method === 'HEAD' || upstream.body === null) response.end()
1050
+ else Readable.fromWeb(upstream.body).pipe(response)
1051
+ } catch (error) {
1052
+ response.writeHead(502, { 'content-type': 'text/plain' })
1053
+ response.end(error instanceof Error ? error.message : String(error))
1054
+ }
1055
+ })
1056
+ await new Promise((resolve, reject) => {
1057
+ server.once('error', reject)
1058
+ server.listen(0, '127.0.0.1', resolve)
1059
+ })
1060
+ const address = server.address()
1061
+ if (address === null || typeof address === 'string') throw new Error('registry has no TCP address')
1062
+ const registry = `http://127.0.0.1:${address.port}`
1063
+
1064
+ await writeFile(join(consumerRoot, 'package.json'), JSON.stringify({
1065
+ name: 'dsh-context-compression-improved-packed-e2e',
1066
+ version: '0.0.0',
1067
+ private: true,
1068
+ }, null, 2))
1069
+ // Stop pnpm's workspace walk-up: an ancestor with its own pnpm-workspace.yaml
1070
+ // (e.g. a user home project) would otherwise absorb this consumer and land
1071
+ // the install — and every resolution — outside the packed consumer.
1072
+ await writeFile(join(consumerRoot, 'pnpm-workspace.yaml'), ['packages:', ' - .'].join(String.fromCharCode(10)))
1073
+ if (upgradeLeg === 'installed') {
1074
+ // Real upgrade path: install the published previous release, then move to
1075
+ // the packed candidate through the standard update command.
1076
+ await run('pnpm', [
1077
+ 'add',
1078
+ `dsh-context-compression-improved@${previousRelease}`,
1079
+ ...officialHostPackages,
1080
+ '--registry', registry,
1081
+ ], { cwd: consumerRoot })
1082
+ const previousSelectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1083
+ const previousSelector = JSON.parse(await readFile(join(previousSelectorDir, 'package.json'), 'utf8'))
1084
+ if (previousSelector.version !== previousRelease) {
1085
+ throw new Error(`upgrade leg installed ${String(previousSelector.version)}, expected ${previousRelease}`)
1086
+ }
1087
+ await run('pnpm', [
1088
+ 'up',
1089
+ 'dsh-context-compression-improved@latest',
1090
+ '--registry', registry,
1091
+ ], { cwd: consumerRoot })
1092
+ // The up command must land the packed candidate version.
1093
+ const upgradedSelectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1094
+ const upgradedSelector = JSON.parse(await readFile(join(upgradedSelectorDir, 'package.json'), 'utf8'))
1095
+ const candidateVersion = registryPackages.get('dsh-context-compression-improved')?.manifest.version
1096
+ if (candidateVersion === undefined) throw new Error('packed candidate version is unknown')
1097
+ if (upgradedSelector.version !== candidateVersion) {
1098
+ throw new Error(`upgrade leg landed ${String(upgradedSelector.version)}, expected ${String(candidateVersion)}`)
1099
+ }
1100
+ } else {
1101
+ console.info(`UPGRADE_LEG_SKIPPED ${upgradeLeg}`)
1102
+ await run('pnpm', [
1103
+ 'add',
1104
+ 'dsh-context-compression-improved@latest',
1105
+ ...officialHostPackages,
1106
+ '--registry', registry,
1107
+ ], { cwd: consumerRoot })
1108
+ }
1109
+
1110
+ const selectorDir = await realpath(join(consumerRoot, 'node_modules/dsh-context-compression-improved'))
1111
+ const selector = JSON.parse(await readFile(join(selectorDir, 'package.json'), 'utf8'))
1112
+ if (selector.publishConfig?.tag !== 'latest') {
1113
+ throw new Error('packed package is not guarded by publishConfig.tag=latest')
1114
+ }
1115
+ for (const peer of ['@deepseek-ai/dsh-command-compact', '@deepseek-ai/dsh-compaction-basic']) {
1116
+ if (selector.peerDependencies?.[peer] !== '>=0.1.5-rc.2 <0.2.0-0') {
1117
+ throw new Error(`packed selector has an invalid ${peer} peer range`)
1118
+ }
1119
+ }
1120
+ for (const directory of [selectorDir]) {
1121
+ const notice = await readFile(join(directory, 'THIRD_PARTY_NOTICES.md'), 'utf8')
1122
+ if (!notice.includes('Copyright (c) 2026 DeepSeek')) {
1123
+ throw new Error(`${basename(directory)} lacks the full DeepSeek Harness MIT notice`)
1124
+ }
1125
+ await scanPublishedTree(directory)
1126
+ }
1127
+
1128
+ const productionLicenses = Object.fromEntries(await Promise.all([
1129
+ ['dsh-context-compression-improved', selectorDir, 'MIT'],
1130
+ ['@huggingface/tokenizers', join(dirname(selectorDir), '@huggingface/tokenizers'), 'Apache-2.0'],
1131
+ ['js-yaml', join(dirname(selectorDir), 'js-yaml'), 'MIT'],
1132
+ ].map(async ([name, directory, expected]) => {
1133
+ const resolved = await realpath(directory)
1134
+ const manifest = JSON.parse(await readFile(join(resolved, 'package.json'), 'utf8'))
1135
+ if (manifest.name !== name) throw new Error(`expected ${name}, found ${String(manifest.name)}`)
1136
+ if (manifest.license !== expected) {
1137
+ throw new Error(`${name} license is ${String(manifest.license)}, expected ${expected}`)
1138
+ }
1139
+ return [name, manifest.license]
1140
+ })))
1141
+ const yamlDir = await realpath(join(dirname(selectorDir), 'js-yaml'))
1142
+ const argparseDir = await realpath(join(dirname(yamlDir), 'argparse'))
1143
+ const argparse = JSON.parse(await readFile(join(argparseDir, 'package.json'), 'utf8'))
1144
+ if (argparse.name !== 'argparse' || argparse.license !== 'Python-2.0') {
1145
+ throw new Error(`argparse license is ${String(argparse.license)}, expected Python-2.0`)
1146
+ }
1147
+ productionLicenses.argparse = argparse.license
1148
+
1149
+ const packedTokenizerArtifacts = {}
1150
+ for (const artifactDir of ['deepseek-v4', 'deepseek-v4-vision-exp']) {
1151
+ const manifest = JSON.parse(await readFile(join(selectorDir, 'assets', artifactDir, 'manifest.json'), 'utf8'))
1152
+ const tokenizerBytes = await readFile(join(selectorDir, 'assets', artifactDir, 'tokenizer.json'))
1153
+ const tokenizerHash = createHash('sha256').update(tokenizerBytes).digest('hex')
1154
+ if (tokenizerBytes.length !== manifest.files['tokenizer.json'].bytes) throw new Error(`packed ${artifactDir} tokenizer size differs`)
1155
+ if (tokenizerHash !== manifest.files['tokenizer.json'].sha256) throw new Error(`packed ${artifactDir} tokenizer hash differs`)
1156
+ packedTokenizerArtifacts[artifactDir] = { bytes: tokenizerBytes.length, sha256: tokenizerHash }
1157
+ }
1158
+ const tokenizer = await readFile(join(selectorDir, 'assets/deepseek-v4/tokenizer.json'))
1159
+ const tokenizerHash = packedTokenizerArtifacts['deepseek-v4'].sha256
1160
+
1161
+ const client = await readFile(join(selectorDir, 'lib/client.js'), 'utf8')
1162
+ if (!client.startsWith('window.__ModuleLoader__.load({')) throw new Error('packed client is not lazy-CJS')
1163
+ if (/(?:\/home\/|[A-Za-z]:\\Users\\)/u.test(client)) throw new Error('packed client leaks a developer path')
1164
+ const hostSmoke = await runPackedHostSmoke(consumerRoot)
1165
+ const installedComponentsScript = join(consumerRoot, 'packed-components-smoke.mjs')
1166
+ await copyFile(join(root, 'scripts/packed-components-smoke.mjs'), installedComponentsScript)
1167
+ const installedComponentsOutput = await capture(process.execPath, [installedComponentsScript], {
1168
+ cwd: consumerRoot,
1169
+ })
1170
+ const installedComponentsLine = installedComponentsOutput.stdout
1171
+ .split(/\r?\n/u)
1172
+ .find(line => line.startsWith('PACKED_COMPONENTS_E2E '))
1173
+ if (installedComponentsLine === undefined) {
1174
+ throw new Error(`installed component smoke lacks its result marker:\n${installedComponentsOutput.stdout}`)
1175
+ }
1176
+ const installedComponentsSmoke = JSON.parse(
1177
+ installedComponentsLine.slice('PACKED_COMPONENTS_E2E '.length),
1178
+ )
1179
+ const visionLine = installedComponentsOutput.stdout
1180
+ .split(/\r?\n/u)
1181
+ .find(line => line.startsWith('PACKED_VISION_E2E '))
1182
+ if (visionLine === undefined) {
1183
+ throw new Error('installed component smoke lacks its vision-session result marker')
1184
+ }
1185
+ const packedVisionSmoke = JSON.parse(visionLine.slice('PACKED_VISION_E2E '.length))
1186
+ assert(packedVisionSmoke.model === 'deepseek-v4-flash-vision-exp',
1187
+ 'installed vision smoke reported the wrong model')
1188
+ assert(packedVisionSmoke.imageSession?.measurement?.kind === 'tokenizer-estimate',
1189
+ 'installed vision smoke did not prove a tokenizer-estimate image surface')
1190
+ assert(packedVisionSmoke.imageSession.measurement.tokens === 340
1191
+ && packedVisionSmoke.imageSession.measurement.upperBoundTokens === 384,
1192
+ 'installed vision smoke reported the wrong 800x600 image estimate')
1193
+ assert(packedVisionSmoke.imageSession.measurement.estimatorId
1194
+ === 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp/image-token-estimate'
1195
+ && packedVisionSmoke.imageSession.measurement.estimatorRevision
1196
+ === '6821d6ad3681a4b137b066b76094fa82ebd0a380:v1',
1197
+ 'installed vision smoke reported the wrong image estimator identity')
1198
+ assert(packedVisionSmoke.imageSession.currentSurfaceKind === 'tokenizer-estimate'
1199
+ && packedVisionSmoke.imageSession.exactRewriteIneligible === true
1200
+ && packedVisionSmoke.imageSession.originalIntact === true,
1201
+ 'installed vision smoke did not prove estimate propagation and exact-only safety')
1202
+ let officialCloneSmoke = null
1203
+ const candidateVersion = registryPackages.get('dsh-context-compression-improved')?.manifest.version
1204
+ if (candidateVersion === undefined) throw new Error('packed candidate version is unknown')
1205
+ const previousForLifecycle = predecessorFound ? previousRelease : undefined
1206
+ if (!predecessorFound) {
1207
+ // The official lifecycle installs the previous release and then upgrades to
1208
+ // the candidate, so it has nothing to do without a predecessor. Record the
1209
+ // same explicit marker the upgrade leg produced instead of failing the run.
1210
+ officialCloneSmoke = upgradeLeg
1211
+ } else if (process.env.DSH_OFFICIAL_CLONE !== undefined) {
1212
+ officialCloneSmoke = await runOfficialCloneCliSmoke(
1213
+ process.env.DSH_OFFICIAL_CLONE,
1214
+ registry,
1215
+ previousForLifecycle,
1216
+ candidateVersion,
1217
+ )
1218
+ } else {
1219
+ // Auto-provision a clean official checkout so the standard add → up →
1220
+ // remove lifecycle runs without manual setup. Release mode fails closed;
1221
+ // only dev mode may skip with an explicit marker.
1222
+ const cloneRoot = join(artifactRoot, 'official-clone')
1223
+ try {
1224
+ await run('git', [
1225
+ 'clone', '--depth', '1', '--branch', 'dsh-v0.1.5-rc.2',
1226
+ 'https://github.com/deepseek-ai/deepseek-harness.git', cloneRoot,
1227
+ ])
1228
+ officialCloneSmoke = await runOfficialCloneCliSmoke(
1229
+ cloneRoot,
1230
+ registry,
1231
+ previousForLifecycle,
1232
+ candidateVersion,
1233
+ )
1234
+ } catch (error) {
1235
+ if (e2eMode === 'release') throw error
1236
+ console.info(`OFFICIAL_CLONE_SMOKE_SKIPPED ${error instanceof Error ? error.message : String(error)}`)
1237
+ await rm(cloneRoot, { recursive: true, force: true })
1238
+ }
1239
+ }
1240
+
1241
+ if (e2eMode === 'release' && predecessorFound && upgradeLeg !== 'installed') {
1242
+ throw new Error(`release gate requires the upgrade leg to run; it reported: ${upgradeLeg}`)
1243
+ }
1244
+ if (e2eMode === 'release' && officialCloneSmoke === null) {
1245
+ throw new Error('release gate requires the official clean-harness lifecycle to run')
1246
+ }
1247
+ console.info(JSON.stringify({
1248
+ installCommand: 'pnpm add dsh-context-compression-improved@latest',
1249
+ e2eMode,
1250
+ upgradeLeg,
1251
+ artifactSource: fixedArtifactRoot === undefined ? 'fresh-pack' : artifactRoot,
1252
+ workspaceRebuildMatched: fixedArtifactRoot === undefined ? null : true,
1253
+ selector: selector.version,
1254
+ prunerEntry: 'dsh-context-compression-improved/pruner',
1255
+ productionLicenses,
1256
+ tokenizerArtifacts: packedTokenizerArtifacts,
1257
+ tokenizerBytes: tokenizer.length,
1258
+ tokenizerSha256: tokenizerHash,
1259
+ hostSmoke,
1260
+ installedComponentsSmoke,
1261
+ packedVisionSmoke,
1262
+ officialCloneSmoke,
1263
+ tarballs: Object.fromEntries([...registryPackages].map(([name, value]) => [name, {
1264
+ file: basename(value.tarball),
1265
+ sha256: value.sha256,
1266
+ }])),
1267
+ }, null, 2))
1268
+ } finally {
1269
+ if (server !== undefined) await new Promise(resolve => server.close(resolve))
1270
+ if (comparisonRoot !== undefined) await rm(comparisonRoot, { recursive: true, force: true })
1271
+ if (ownsArtifactRoot) await rm(artifactRoot, { recursive: true, force: true })
1272
+ await rm(consumerRoot, { recursive: true, force: true })
1273
+ }