image-loadable.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * End-to-end spec of the packer's actual product: an image this package builds must
  3. * mount in the runtime's VFS and be `require`-able by the runtime's module loader,
  4. * which holds no transform of its own.
  5. *
  6. * That last part is the point. "It boots" only proves nothing crashed; the loader
  7. * wraps module bodies exactly as the image holds them, so the pack-time pass is the
  8. * only thing that can make them wrappable. The refusal case is the positive
  9. * evidence: restore one un-lowered body and the same setup fails loud.
  10. *
  11. * A small synthetic composition rather than the real profile: packing the full
  12. * closure takes tens of seconds. The path under test — compose, materialize,
  13. * transform, tar, compress, inflate, mount, require — is the same one.
  14. *
  15. * ONE module instance: every runtime import here goes through `src/`, because the VFS
  16. * and the active loader are module-level slots. The "starts with nothing loaded"
  17. * case asserts the instance the spec holds is the one that did the work.
  18. */
  19. import { existsSync } from 'node:fs'
  20. import { join } from 'node:path'
  21. import { fileURLToPath } from 'node:url'
  22. import { describe, expect, it } from 'vitest'
  23. import { FiberState } from '@deepseek-ai/cordis'
  24. import { createNodeBuiltins, REPLACED_PREFIXES } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtins.ts'
  25. import {
  26. setActiveModuleLoader, WorkerModuleLoader,
  27. } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/module-system/module-loader.ts'
  28. import { inflateImage } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/image-gzip.ts'
  29. import { loadVfsImage } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/memory.ts'
  30. import { setActiveVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/active.ts'
  31. import { indexWorkspacePackages, previewFixtures } from '../src/repository.ts'
  32. import { DEFAULT_ROOT, MANIFEST_PATH, packVfsImage, packVfsOverlay } from '../src/pack.ts'
  33. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  34. /** A leaf workspace package: real build output, no dependencies to drag in. */
  35. const SUBJECT = '@deepseek-ai/dsh-timeout'
  36. const LANDLOCK = '@deepseek-ai/node-addon-landlock-run'
  37. const PLUGIN_INVENTORY = '@deepseek-ai/dsh-plugin-package-inventory-deepseek'
  38. const WEB_SERVER = '@deepseek-ai/dsh-host-webserver'
  39. const workspaces = indexWorkspacePackages(repoRoot)
  40. describe('preview example overlays', () => {
  41. it('packs source-looking paths and dot directories into a separate overlay', () => {
  42. const fixture = previewFixtures(repoRoot)[0]
  43. expect(fixture?.id).toBe('vfs-example')
  44. const result = packVfsOverlay(fixture?.trees ?? [])
  45. expect(new TextDecoder().decode(result.files['workspace/src/preview.ts']))
  46. .toContain("previewStatus = 'ready'")
  47. expect(new TextDecoder().decode(result.files['workspace/.agents/skills/preview-tour/SKILL.md']))
  48. .toContain('name: preview-tour')
  49. expect(Object.keys(result.files).filter(path => path.endsWith('/session.jsonl'))).toHaveLength(3)
  50. })
  51. it('fails loud when a declared seed tree is absent', () => {
  52. expect(() => packVfsOverlay([
  53. { mount: 'workspace', directory: join(repoRoot, 'missing-preview-seed') },
  54. ])).toThrow(/tree workspace is missing/)
  55. })
  56. it('refuses overlays that could replace runtime files', () => {
  57. const fixture = previewFixtures(repoRoot)[0]
  58. expect(() => packVfsOverlay([
  59. { mount: 'config', directory: fixture?.trees[0]?.directory ?? repoRoot },
  60. ])).toThrow(/must stay under home or workspace/)
  61. })
  62. })
  63. /**
  64. * The pack consumes built `lib/` output. An unbuilt checkout (the unit
  65. * coverage lane runs before any build) self-skips. Native Windows routes this
  66. * suite through its post-build uninstrumented gate, and preview builds exercise
  67. * the same path against complete real artifacts.
  68. */
  69. const subjectBuilt = existsSync(join(repoRoot, 'packages/util/timeout/lib/index.js'))
  70. let memo: ReturnType<typeof packVfsImage> | undefined
  71. const packed = (): ReturnType<typeof packVfsImage> => memo ??= packVfsImage({
  72. // The composition's own shape: one entry per plugin, `name:` on its own line.
  73. config: `- id: subject\n name: '${SUBJECT}'\n`,
  74. profile: 'image-loadable-check',
  75. workspaces,
  76. resolveFrom: repoRoot,
  77. // Synthetic composition: nothing boots the worker assembly, so its default
  78. // image entries must not be demanded of this one-package closure.
  79. entries: [],
  80. })
  81. let landlockMemo: ReturnType<typeof packVfsImage> | undefined
  82. const packedLandlock = (): ReturnType<typeof packVfsImage> => landlockMemo ??= packVfsImage({
  83. config: `- id: subject\n name: '${LANDLOCK}'\n`,
  84. profile: 'landlock-package-check',
  85. workspaces,
  86. resolveFrom: repoRoot,
  87. entries: [],
  88. })
  89. let pluginInventoryMemo: ReturnType<typeof packVfsImage> | undefined
  90. const packedPluginInventory = (): ReturnType<typeof packVfsImage> => pluginInventoryMemo ??= packVfsImage({
  91. config: `- id: subject\n name: '${PLUGIN_INVENTORY}'\n`,
  92. profile: 'plugin-inventory-check',
  93. workspaces,
  94. resolveFrom: repoRoot,
  95. entries: [],
  96. })
  97. let webServerMemo: ReturnType<typeof packVfsImage> | undefined
  98. const packedWebServer = (): ReturnType<typeof packVfsImage> => webServerMemo ??= packVfsImage({
  99. config: `- id: subject\n name: '${WEB_SERVER}'\n`,
  100. profile: 'webserver-dependency-check',
  101. workspaces,
  102. resolveFrom: repoRoot,
  103. entries: [],
  104. })
  105. /** The image's archive, inflated once: mounting reads the tar, not the gzip member. */
  106. let archiveMemo: Uint8Array | undefined
  107. const archive = async (): Promise<Uint8Array> =>
  108. archiveMemo ??= await inflateImage(packed().image, 'the image this spec packed')
  109. ;(subjectBuilt ? describe : describe.skip)('packed image', () => {
  110. it('materializes the roster with every dependency resolved', () => {
  111. const result = packed()
  112. expect(workspaces.has(SUBJECT)).toBe(true)
  113. expect(result.roster).toEqual([SUBJECT])
  114. expect(result.packages.has(SUBJECT)).toBe(true)
  115. expect(result.missing).toEqual([])
  116. })
  117. it('records the wrapper contract in the manifest and rewrote what it visited', () => {
  118. const result = packed()
  119. expect(Object.hasOwn(result.files, MANIFEST_PATH)).toBe(true)
  120. const manifest = JSON.parse(new TextDecoder().decode(result.files[MANIFEST_PATH])) as { lowered: string }
  121. expect(manifest.lowered).toBe(result.contract)
  122. expect(result.transform.rewritten).toBeGreaterThan(0)
  123. })
  124. it('names every JavaScript entry for the debugger, workspace files by repository path', () => {
  125. const result = packed()
  126. const decoder = new TextDecoder()
  127. const entries = Object.keys(result.files).filter(name => /\.[cm]?js$/.test(name))
  128. expect(entries.length).toBeGreaterThan(0)
  129. for (const name of entries) {
  130. const lines = decoder.decode(result.files[name]).split('\n')
  131. // V8 stacks and DevTools read the trailing comment, so worker
  132. // `new Function` bodies and page blobs alike show under a stable name
  133. // instead of as anonymous VM or blob entries.
  134. expect(lines.at(-1)).toMatch(/^\/\/# sourceURL=\S+$/)
  135. // A dangling map reference would make the debugger report one load
  136. // failure per named script; the packer ships no `.map` files.
  137. expect(lines.at(-2) ?? '').not.toContain('sourceMappingURL')
  138. }
  139. // A workspace entry is named by the path a reader navigates in this
  140. // repository, not by its image mount.
  141. const subject = decoder.decode(result.files[`node_modules/${SUBJECT}/lib/index.js`])
  142. expect(subject.endsWith('\n//# sourceURL=packages/util/timeout/lib/index.js')).toBe(true)
  143. })
  144. it('writes one gzip member whose header records no build facts', () => {
  145. const image = packed().image
  146. // RFC 1952 §2.3: magic, deflate, then the flag byte — no FNAME (0x08) or
  147. // FCOMMENT, a zero modification time, and "unknown" for the packing system.
  148. expect([...image.slice(0, 4)]).toEqual([0x1f, 0x8b, 0x08, 0x00])
  149. expect([...image.slice(4, 8)]).toEqual([0, 0, 0, 0])
  150. expect(image[9]).toBe(255)
  151. })
  152. it('packs the same tree to the same bytes', () => {
  153. // The preview build compares a freshly packed image against the shipped one,
  154. // so anything the compressor takes from its environment would read as a
  155. // changed tree.
  156. const again = packVfsImage({
  157. config: `- id: subject\n name: '${SUBJECT}'\n`,
  158. profile: 'image-loadable-check',
  159. workspaces,
  160. resolveFrom: repoRoot,
  161. entries: [],
  162. })
  163. expect(Buffer.from(again.image).equals(Buffer.from(packed().image))).toBe(true)
  164. })
  165. it('mounts and requires through the real loader, which carries no transform', async () => {
  166. const vfs = loadVfsImage(await archive(), DEFAULT_ROOT)
  167. expect(vfs.existsSync(`${DEFAULT_ROOT}/node_modules/${SUBJECT}/lib/index.js`)).toBe(true)
  168. const loader = new WorkerModuleLoader({
  169. vfs,
  170. root: DEFAULT_ROOT,
  171. staticModules: createNodeBuiltins(),
  172. staticModulePrefixes: REPLACED_PREFIXES,
  173. })
  174. // The loader this spec reads counters from must be the one that did the
  175. // requiring; a second instance would report an empty cache trivially.
  176. expect(loader.usage().modules).toBe(0)
  177. const required = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(SUBJECT) as Record<string, unknown>
  178. expect(typeof required.timeoutOf).toBe('function')
  179. expect(loader.usage().modules).toBeGreaterThan(0)
  180. })
  181. it('keeps third-party runtime JavaScript published under src', async () => {
  182. const result = packedWebServer()
  183. expect(result.missing).toEqual([])
  184. expect(Object.hasOwn(result.files, 'node_modules/debug/src/index.js')).toBe(true)
  185. expect(Object.hasOwn(result.files, 'node_modules/ms/index.js')).toBe(true)
  186. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed webserver'), DEFAULT_ROOT)
  187. const loader = new WorkerModuleLoader({
  188. vfs,
  189. root: DEFAULT_ROOT,
  190. staticModules: createNodeBuiltins(),
  191. staticModulePrefixes: REPLACED_PREFIXES,
  192. })
  193. setActiveVfs(vfs)
  194. setActiveModuleLoader(loader)
  195. const webserver = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(WEB_SERVER) as { WebServer?: unknown }
  196. expect(typeof webserver.WebServer).toBe('function')
  197. })
  198. it('runs the unchanged Landlock entry package over the Worker platform executable', async () => {
  199. const result = packedLandlock()
  200. expect(workspaces.has(LANDLOCK)).toBe(true)
  201. expect(result.packages.has(LANDLOCK)).toBe(true)
  202. expect(result.missing).toEqual([])
  203. expect(Object.hasOwn(result.files, `node_modules/${LANDLOCK}/lib/index.js`)).toBe(true)
  204. expect(createNodeBuiltins()[LANDLOCK]).toBeUndefined()
  205. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed Landlock package'), DEFAULT_ROOT)
  206. const loader = new WorkerModuleLoader({
  207. vfs,
  208. root: DEFAULT_ROOT,
  209. staticModules: createNodeBuiltins(),
  210. staticModulePrefixes: REPLACED_PREFIXES,
  211. })
  212. setActiveVfs(vfs)
  213. setActiveModuleLoader(loader)
  214. const landlock = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(LANDLOCK) as {
  215. LAUNCHER_BIN: string
  216. LAUNCHER_FAILURE_EXIT: number
  217. launcherPath(): string
  218. grantArgs(grants: { readOnly?: readonly string[]; readWrite?: readonly string[] }): string[]
  219. probe(): string
  220. }
  221. expect(landlock.LAUNCHER_BIN).toBe('landlock-run')
  222. expect(landlock.LAUNCHER_FAILURE_EXIT).toBe(125)
  223. expect(landlock.grantArgs({ readOnly: ['/'], readWrite: ['/tmp'] })).toEqual([
  224. '--ro', '/', '--rw', '/tmp',
  225. ])
  226. expect(landlock.launcherPath()).toBe(
  227. `${DEFAULT_ROOT}/node_modules/${LANDLOCK}/node_modules/${LANDLOCK}-${process.platform}-${process.arch}/bin/landlock-run`,
  228. )
  229. expect(landlock.probe()).toBe('full')
  230. })
  231. it('prepares the unchanged plugin-package inventory through Worker createRequire paths', async () => {
  232. const result = packedPluginInventory()
  233. expect(result.missing).toEqual([])
  234. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed plugin inventory'), DEFAULT_ROOT)
  235. const loader = new WorkerModuleLoader({
  236. vfs,
  237. root: DEFAULT_ROOT,
  238. staticModules: createNodeBuiltins(),
  239. staticModulePrefixes: REPLACED_PREFIXES,
  240. })
  241. setActiveVfs(vfs)
  242. setActiveModuleLoader(loader)
  243. const inventory = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(PLUGIN_INVENTORY) as {
  244. apply(ctx: unknown, config: unknown): void
  245. }
  246. type Prepared = { readonly value: { readonly version: number; readonly packages: readonly unknown[] } }
  247. type Prepare = (request: { readonly body: object; readonly signal: AbortSignal }) => Promise<Prepared>
  248. let prepare: Prepare | undefined
  249. const baseUrl = `file://${DEFAULT_ROOT}/config/cordis.yml`
  250. const tree: { readonly ctx: { readonly baseUrl: string }; entries(): readonly unknown[] } = {
  251. ctx: { baseUrl },
  252. entries: () => [entry],
  253. }
  254. const entry = {
  255. options: { name: PLUGIN_INVENTORY },
  256. disabled: false,
  257. fiber: { state: FiberState.ACTIVE },
  258. parent: { tree },
  259. }
  260. inventory.apply({
  261. baseUrl,
  262. loader: tree,
  263. deepseekLlmApiExtensions: {
  264. register: (field: string, contribution: { readonly prepare: Prepare }): void => {
  265. expect(field).toBe('dsh_plugin_packages')
  266. prepare = contribution.prepare
  267. },
  268. },
  269. }, {})
  270. if (prepare === undefined) throw new Error('packed plugin inventory did not register its request contribution')
  271. const prepared = await prepare({ body: {}, signal: new AbortController().signal })
  272. const manifest = JSON.parse(vfs.readFileSync(
  273. `${DEFAULT_ROOT}/node_modules/${PLUGIN_INVENTORY}/package.json`, 'utf8',
  274. ) as string) as { version: string }
  275. expect(prepared.value).toEqual({
  276. version: 1,
  277. packages: [{ name: PLUGIN_INVENTORY, version: manifest.version }],
  278. })
  279. })
  280. it('refuses a body the packer did not lower, naming the image', async () => {
  281. // The case above only proves the packed bytes are wrappable. This is the
  282. // other half: the loader has no transform to fall back on, so an entry the
  283. // collector missed must fail loud against the image rather than boot.
  284. const vfs = loadVfsImage(await archive(), DEFAULT_ROOT)
  285. vfs.seed(
  286. `${DEFAULT_ROOT}/node_modules/${SUBJECT}/lib/index.js`,
  287. new TextEncoder().encode('export const timeoutOf = () => 0\n'),
  288. )
  289. const loader = new WorkerModuleLoader({
  290. vfs,
  291. root: DEFAULT_ROOT,
  292. staticModules: createNodeBuiltins(),
  293. staticModulePrefixes: REPLACED_PREFIXES,
  294. })
  295. expect(() => loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(SUBJECT))
  296. .toThrow(/still carries module syntax, so the image was not lowered by the packer/)
  297. })
  298. })