1
0

built-bin.e2e.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { fileURLToPath, pathToFileURL } from 'node:url'
  5. import { execa } from 'execa'
  6. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  7. /** Published-entry acceptance for argument errors, profile lifecycle, and boot-free config dumps. */
  8. const repoRoot = fileURLToPath(new URL('../../../', import.meta.url))
  9. const dshBin = join(repoRoot, 'apps/cli/lib/bin.js')
  10. const invalidProvider = fileURLToPath(new URL('./fixtures/invalid-provider.cordis.yml', import.meta.url))
  11. async function runBuiltBin(
  12. args: readonly string[] = [],
  13. env: Record<string, string> = {},
  14. ): Promise<{ stdout: string; code: number; stderr: string }> {
  15. const result = await execa(process.execPath, [dshBin, ...args], {
  16. input: '',
  17. timeout: 25_000,
  18. killSignal: 'SIGKILL',
  19. reject: false,
  20. env,
  21. })
  22. if (result.timedOut) {
  23. throw new Error(`dsh built bin did not exit within 25s. stdout:\n${result.stdout}\nstderr:\n${result.stderr}`)
  24. }
  25. return { stdout: result.stdout, code: result.exitCode ?? -1, stderr: result.stderr }
  26. }
  27. async function waitForFile(file: string): Promise<void> {
  28. const deadline = Date.now() + 20_000
  29. while (!existsSync(file)) {
  30. if (Date.now() >= deadline) throw new Error(`dsh profile lifecycle marker did not appear: ${file}`)
  31. await new Promise(resolve => setTimeout(resolve, 20))
  32. }
  33. }
  34. interface ProfileLifecycleFixture {
  35. home: string
  36. ready: string
  37. settled: string
  38. disposed: string
  39. }
  40. /**
  41. * A minimal custom profile: one lifecycle-marker plugin bundle listed in
  42. * dsh.profile.bundles, no dsh-base — proving out-of-box composition machinery without
  43. * booting the entire product tree.
  44. */
  45. function createProfileLifecycleFixture(): ProfileLifecycleFixture {
  46. const home = mkdtempSync(join(tmpdir(), 'dsh-profile-lifecycle-'))
  47. const ready = join(home, 'ready')
  48. const settled = join(home, 'settled')
  49. const disposed = join(home, 'disposed')
  50. const bundleDir = join(home, 'lifecycle-bundle')
  51. mkdirSync(bundleDir, { recursive: true })
  52. writeFileSync(join(bundleDir, 'plugin.mjs'), [
  53. "import { writeFileSync } from 'node:fs'",
  54. "import { join } from 'node:path'",
  55. "export const name = 'profile-lifecycle-fixture'",
  56. 'export function apply(ctx, config = {}) {',
  57. ' let active = true',
  58. ' // Keep the event loop alive so process lifetime is signal-owned, like a real surface.',
  59. ' const heartbeat = setInterval(() => {}, 1000)',
  60. ' // Echo the mounted generation so the hot-reload e2e can assert both an',
  61. ' // applied override and its removal reverting to this bundle default.',
  62. " writeFileSync(join(process.env.DSH_HOME, 'config-echo'), String(config.generation ?? 'bundle-default'))",
  63. " writeFileSync(process.env.RAW_READY_FILE, 'ready')",
  64. ' void ctx.loader.await().then(() => {',
  65. " if (active) writeFileSync(process.env.RAW_SETTLED_FILE, 'settled')",
  66. ' })',
  67. ' ctx.effect(() => () => {',
  68. ' active = false',
  69. ' clearInterval(heartbeat)',
  70. " writeFileSync(process.env.RAW_DISPOSED_FILE, 'disposed')",
  71. ' })',
  72. '}',
  73. '',
  74. ].join('\n'))
  75. writeFileSync(join(bundleDir, 'cordis.patch.yml'), [
  76. '- insert:',
  77. ' - id: profile-lifecycle-fixture',
  78. ` name: ${pathToFileURL(join(bundleDir, 'plugin.mjs')).href}`,
  79. '',
  80. ].join('\n'))
  81. writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
  82. name: 'dsh-lifecycle-bundle',
  83. version: '0.0.0',
  84. type: 'module',
  85. dsh: { bundle: { patch: './cordis.patch.yml' } },
  86. }, undefined, 2))
  87. const profileDir = join(home, 'profiles', 'lifecycle')
  88. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  89. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  90. name: 'dsh-profile-lifecycle',
  91. private: true,
  92. dependencies: {},
  93. dsh: { profile: { bundles: ['dsh-lifecycle-bundle'] } },
  94. }, undefined, 2))
  95. // Hand-place the "installed" bundle where profile resolution finds it.
  96. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  97. const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle')
  98. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  99. try {
  100. rmSync(linkTarget, { recursive: true, force: true })
  101. } catch { /* fresh dir */ }
  102. // Copy-free: a package.json redirecting via a relative main is enough for require.resolve.
  103. mkdirSync(linkTarget, { recursive: true })
  104. for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) {
  105. writeFileSync(join(linkTarget, file), readFileSync(join(bundleDir, file)))
  106. }
  107. return { home, ready, settled, disposed }
  108. }
  109. function startProfileLifecycle(fixture: ProfileLifecycleFixture) {
  110. return execa(process.execPath, [dshBin, '--profile', 'lifecycle'], {
  111. cwd: fixture.home,
  112. input: '',
  113. reject: false,
  114. env: {
  115. DSH_HOME: fixture.home,
  116. RAW_READY_FILE: fixture.ready,
  117. RAW_SETTLED_FILE: fixture.settled,
  118. RAW_DISPOSED_FILE: fixture.disposed,
  119. },
  120. })
  121. }
  122. describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', () => {
  123. it('requires --profile and rejects removed commands', async () => {
  124. const bare = await runBuiltBin()
  125. expect(bare.code).toBe(1)
  126. expect(bare.stdout).toBe('')
  127. expect(bare.stderr).toContain('--profile <name> is required')
  128. const help = await runBuiltBin(['--help'])
  129. expect(help.code).toBe(0)
  130. expect(help.stdout).toContain('dsh --profile web')
  131. expect(help.stdout).toContain('dsh plugin --profile')
  132. expect(help.stdout).not.toMatch(/^\s+(?:tui|meta|upgrade)\b/mu)
  133. for (const removed of [['tui'], ['--config', 'x.yml'], ['-p', 'task']]) {
  134. const result = await runBuiltBin(removed)
  135. expect(result.code).toBe(1)
  136. }
  137. }, 30_000)
  138. it('fails loud on a nonexistent profile with the plugin-command hint', async () => {
  139. const home = mkdtempSync(join(tmpdir(), 'dsh-missing-profile-'))
  140. try {
  141. const result = await runBuiltBin(['--profile', 'nope'], { DSH_HOME: home })
  142. expect(result.code).toBe(1)
  143. expect(result.stderr).toContain('profile "nope" does not exist')
  144. expect(result.stderr).toContain('dsh plugin --profile nope add')
  145. } finally {
  146. rmSync(home, { recursive: true, force: true })
  147. }
  148. }, 30_000)
  149. it('reports a patch-overlay boot failure without hanging', async () => {
  150. // The HMR main watcher's initial scan once refreshed the include
  151. // mid-initial-apply, deadlocking the failing apply's rollback against the
  152. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  153. // ([Agent Note](../../../.agents/notes/implemented/bug-fix/2026-08-03-hmr-initial-scan-boot-deadlock.md)).
  154. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  155. try {
  156. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  157. DSH_HOME: home,
  158. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  159. DSH_TELEMETRY_DISABLED: '1',
  160. })
  161. expect(result.code).toBe(1)
  162. expect(result.stdout).toBe('')
  163. expect(result.stderr).toContain('llm-pi-ai')
  164. } finally {
  165. rmSync(home, { recursive: true, force: true })
  166. }
  167. }, 30_000)
  168. it('applies a custom profile bundle and disposes it on a startup-time signal', async () => {
  169. const fixture = createProfileLifecycleFixture()
  170. const child = startProfileLifecycle(fixture)
  171. try {
  172. await waitForFile(fixture.ready)
  173. child.kill('SIGTERM')
  174. const result = await child
  175. expect(result.exitCode).toBe(0)
  176. expect(result.signal).toBeUndefined()
  177. expect(existsSync(fixture.disposed)).toBe(true)
  178. } finally {
  179. child.kill('SIGKILL')
  180. rmSync(fixture.home, { recursive: true, force: true })
  181. }
  182. }, 30_000)
  183. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  184. const fixture = createProfileLifecycleFixture()
  185. const child = startProfileLifecycle(fixture)
  186. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  187. const configFile = join(fixture.home, 'config-echo')
  188. try {
  189. await waitForFile(fixture.settled)
  190. // The live profile layer: even without an hmr row in the composition,
  191. // the launcher mounts a config-only watcher, so an edited
  192. // cordis.patch.yml lands in the running tree (the reload disposes the
  193. // patched row's old fiber — observable as the disposed marker — and
  194. // mounts the new config, which echoes its generation and re-writes the
  195. // ready marker).
  196. rmSync(fixture.ready)
  197. writeFileSync(profilePatch, [
  198. '- id: profile-lifecycle-fixture',
  199. ' config:',
  200. ' generation: 2',
  201. '',
  202. ].join('\n'))
  203. await waitForFile(fixture.ready)
  204. expect(readFileSync(configFile, 'utf8')).toBe('2')
  205. // Removal reverts: the bundle's inserted row must return to its own
  206. // default config, not keep the removed override — the insert-aliasing
  207. // regression (a shared patch object mutated in place by a former
  208. // generation would make this impossible).
  209. rmSync(fixture.ready)
  210. writeFileSync(profilePatch, '[]\n')
  211. await waitForFile(fixture.ready)
  212. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  213. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  214. // and outranks the per-profile layer.
  215. rmSync(fixture.ready)
  216. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  217. '- id: profile-lifecycle-fixture',
  218. ' config:',
  219. ' generation: home',
  220. '',
  221. ].join('\n'))
  222. await waitForFile(fixture.ready)
  223. expect(readFileSync(configFile, 'utf8')).toBe('home')
  224. child.kill('SIGTERM')
  225. const result = await child
  226. expect(result.exitCode).toBe(0)
  227. expect(result.signal).toBeUndefined()
  228. expect(existsSync(fixture.disposed)).toBe(true)
  229. } finally {
  230. child.kill('SIGKILL')
  231. rmSync(fixture.home, { recursive: true, force: true })
  232. }
  233. }, 30_000)
  234. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  235. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  236. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  237. // would self-link the profile.
  238. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  239. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  240. try {
  241. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  242. name: 'anchored-bundle',
  243. version: '1.0.0',
  244. dsh: { bundle: { patch: './cordis.patch.yml' } },
  245. }))
  246. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  247. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  248. cwd: checkout,
  249. input: '',
  250. timeout: 60_000,
  251. killSignal: 'SIGKILL',
  252. reject: false,
  253. env: { DSH_HOME: home },
  254. })
  255. expect(result.exitCode).toBe(0)
  256. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  257. dependencies: Record<string, string>
  258. dsh: { profile: { bundles: string[] } }
  259. }
  260. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  261. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  262. } finally {
  263. rmSync(home, { recursive: true, force: true })
  264. rmSync(checkout, { recursive: true, force: true })
  265. }
  266. }, 90_000)
  267. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  268. // Reconcile runs against the INSTALLED state on every successful pnpm
  269. // run, so `update` (not only `add`) activates a package whose newer
  270. // version declares dsh.bundle. Simulated without a registry: hand-place
  271. // the installed package, flip its manifest, and run a benign pnpm verb.
  272. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  273. try {
  274. const profileDir = join(home, 'profiles', 'up')
  275. const installed = join(profileDir, 'node_modules', 'late-bundle')
  276. mkdirSync(installed, { recursive: true })
  277. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  278. name: 'dsh-profile-up',
  279. private: true,
  280. dependencies: { 'late-bundle': 'file:./late-bundle' },
  281. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  282. }))
  283. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  284. // v1: no dsh manifest — a plain dependency.
  285. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  286. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  287. expect(first.code).toBe(0)
  288. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  289. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  290. // v2: the installed package now declares dsh.bundle (an update landed).
  291. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  292. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  293. }))
  294. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  295. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  296. expect(second.code).toBe(0)
  297. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  298. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  299. } finally {
  300. rmSync(home, { recursive: true, force: true })
  301. }
  302. }, 30_000)
  303. describe('config dump', () => {
  304. let home: string
  305. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  306. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  307. it('prints the web profile bundle layers without a user layer', async () => {
  308. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  309. expect(code).toBe(0)
  310. expect(stderr).toBe('')
  311. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  312. expect(stdout).toContain('agents: []')
  313. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  314. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  315. }, 30_000)
  316. it('composes the profile user layer and a --patch overlay in order', async () => {
  317. // Auto-init the web profile first, then write its user layer.
  318. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  319. expect(init.code).toBe(0)
  320. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  321. writeFileSync(profilePatch, [
  322. '- id: agent-loop',
  323. ' config:',
  324. ' agents:',
  325. ' - id: personal',
  326. ' provider: personal-provider',
  327. ' model: personal-model',
  328. '- id: absent-row',
  329. ' config:',
  330. ' x: 1',
  331. '',
  332. ].join('\n'))
  333. const overlay = join(home, 'overlay.cordis.yml')
  334. writeFileSync(overlay, [
  335. '- id: agent-loop',
  336. ' config:',
  337. ' agents:',
  338. ' - id: configured',
  339. ' provider: configured-provider',
  340. ' model: configured-model',
  341. '',
  342. ].join('\n'))
  343. const { stdout, code, stderr } = await runBuiltBin(
  344. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  345. { DSH_HOME: home },
  346. )
  347. expect(code).toBe(0)
  348. expect(stdout).toContain('provider: configured-provider')
  349. expect(stdout).not.toContain('personal-provider')
  350. // Both layers patched the row; provenance lists them in application order.
  351. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  352. expect(stderr).toContain('patch: entry "absent-row" not found')
  353. }, 30_000)
  354. })
  355. })