dsh-context-compression-improved 0.2.4 → 0.2.5

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