dsh-context-compression-improved 0.8.0 → 0.9.0

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