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