image-loadable.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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; the built lanes and every
  66. * preview build exercise this same path against real artifacts.
  67. */
  68. const subjectBuilt = existsSync(join(repoRoot, 'packages/util/timeout/lib/index.js'))
  69. let memo: ReturnType<typeof packVfsImage> | undefined
  70. const packed = (): ReturnType<typeof packVfsImage> => memo ??= packVfsImage({
  71. // The composition's own shape: one entry per plugin, `name:` on its own line.
  72. config: `- id: subject\n name: '${SUBJECT}'\n`,
  73. profile: 'image-loadable-check',
  74. workspaces,
  75. resolveFrom: repoRoot,
  76. // Synthetic composition: nothing boots the worker assembly, so its default
  77. // image entries must not be demanded of this one-package closure.
  78. entries: [],
  79. })
  80. let landlockMemo: ReturnType<typeof packVfsImage> | undefined
  81. const packedLandlock = (): ReturnType<typeof packVfsImage> => landlockMemo ??= packVfsImage({
  82. config: `- id: subject\n name: '${LANDLOCK}'\n`,
  83. profile: 'landlock-package-check',
  84. workspaces,
  85. resolveFrom: repoRoot,
  86. entries: [],
  87. })
  88. let pluginInventoryMemo: ReturnType<typeof packVfsImage> | undefined
  89. const packedPluginInventory = (): ReturnType<typeof packVfsImage> => pluginInventoryMemo ??= packVfsImage({
  90. config: `- id: subject\n name: '${PLUGIN_INVENTORY}'\n`,
  91. profile: 'plugin-inventory-check',
  92. workspaces,
  93. resolveFrom: repoRoot,
  94. entries: [],
  95. })
  96. let webServerMemo: ReturnType<typeof packVfsImage> | undefined
  97. const packedWebServer = (): ReturnType<typeof packVfsImage> => webServerMemo ??= packVfsImage({
  98. config: `- id: subject\n name: '${WEB_SERVER}'\n`,
  99. profile: 'webserver-dependency-check',
  100. workspaces,
  101. resolveFrom: repoRoot,
  102. entries: [],
  103. })
  104. /** The image's archive, inflated once: mounting reads the tar, not the gzip member. */
  105. let archiveMemo: Uint8Array | undefined
  106. const archive = async (): Promise<Uint8Array> =>
  107. archiveMemo ??= await inflateImage(packed().image, 'the image this spec packed')
  108. ;(subjectBuilt ? describe : describe.skip)('packed image', () => {
  109. it('materializes the roster with every dependency resolved', () => {
  110. const result = packed()
  111. expect(workspaces.has(SUBJECT)).toBe(true)
  112. expect(result.roster).toEqual([SUBJECT])
  113. expect(result.packages.has(SUBJECT)).toBe(true)
  114. expect(result.missing).toEqual([])
  115. })
  116. it('records the wrapper contract in the manifest and rewrote what it visited', () => {
  117. const result = packed()
  118. expect(Object.hasOwn(result.files, MANIFEST_PATH)).toBe(true)
  119. const manifest = JSON.parse(new TextDecoder().decode(result.files[MANIFEST_PATH])) as { lowered: string }
  120. expect(manifest.lowered).toBe(result.contract)
  121. expect(result.transform.rewritten).toBeGreaterThan(0)
  122. })
  123. it('names every JavaScript entry for the debugger, workspace files by repository path', () => {
  124. const result = packed()
  125. const decoder = new TextDecoder()
  126. const entries = Object.keys(result.files).filter(name => /\.[cm]?js$/.test(name))
  127. expect(entries.length).toBeGreaterThan(0)
  128. for (const name of entries) {
  129. const lines = decoder.decode(result.files[name]).split('\n')
  130. // V8 stacks and DevTools read the trailing comment, so worker
  131. // `new Function` bodies and page blobs alike show under a stable name
  132. // instead of as anonymous VM or blob entries.
  133. expect(lines.at(-1)).toMatch(/^\/\/# sourceURL=\S+$/)
  134. // A dangling map reference would make the debugger report one load
  135. // failure per named script; the packer ships no `.map` files.
  136. expect(lines.at(-2) ?? '').not.toContain('sourceMappingURL')
  137. }
  138. // A workspace entry is named by the path a reader navigates in this
  139. // repository, not by its image mount.
  140. const subject = decoder.decode(result.files[`node_modules/${SUBJECT}/lib/index.js`])
  141. expect(subject.endsWith('\n//# sourceURL=packages/util/timeout/lib/index.js')).toBe(true)
  142. })
  143. it('writes one gzip member whose header records no build facts', () => {
  144. const image = packed().image
  145. // RFC 1952 §2.3: magic, deflate, then the flag byte — no FNAME (0x08) or
  146. // FCOMMENT, a zero modification time, and "unknown" for the packing system.
  147. expect([...image.slice(0, 4)]).toEqual([0x1f, 0x8b, 0x08, 0x00])
  148. expect([...image.slice(4, 8)]).toEqual([0, 0, 0, 0])
  149. expect(image[9]).toBe(255)
  150. })
  151. it('packs the same tree to the same bytes', () => {
  152. // The preview build compares a freshly packed image against the shipped one,
  153. // so anything the compressor takes from its environment would read as a
  154. // changed tree.
  155. const again = packVfsImage({
  156. config: `- id: subject\n name: '${SUBJECT}'\n`,
  157. profile: 'image-loadable-check',
  158. workspaces,
  159. resolveFrom: repoRoot,
  160. entries: [],
  161. })
  162. expect(Buffer.from(again.image).equals(Buffer.from(packed().image))).toBe(true)
  163. })
  164. it('mounts and requires through the real loader, which carries no transform', async () => {
  165. const vfs = loadVfsImage(await archive(), DEFAULT_ROOT)
  166. expect(vfs.existsSync(`${DEFAULT_ROOT}/node_modules/${SUBJECT}/lib/index.js`)).toBe(true)
  167. const loader = new WorkerModuleLoader({
  168. vfs,
  169. root: DEFAULT_ROOT,
  170. staticModules: createNodeBuiltins(),
  171. staticModulePrefixes: REPLACED_PREFIXES,
  172. })
  173. // The loader this spec reads counters from must be the one that did the
  174. // requiring; a second instance would report an empty cache trivially.
  175. expect(loader.usage().modules).toBe(0)
  176. const required = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(SUBJECT) as Record<string, unknown>
  177. expect(typeof required.timeoutOf).toBe('function')
  178. expect(loader.usage().modules).toBeGreaterThan(0)
  179. })
  180. it('keeps third-party runtime JavaScript published under src', async () => {
  181. const result = packedWebServer()
  182. expect(result.missing).toEqual([])
  183. expect(Object.hasOwn(result.files, 'node_modules/debug/src/index.js')).toBe(true)
  184. expect(Object.hasOwn(result.files, 'node_modules/ms/index.js')).toBe(true)
  185. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed webserver'), DEFAULT_ROOT)
  186. const loader = new WorkerModuleLoader({
  187. vfs,
  188. root: DEFAULT_ROOT,
  189. staticModules: createNodeBuiltins(),
  190. staticModulePrefixes: REPLACED_PREFIXES,
  191. })
  192. setActiveVfs(vfs)
  193. setActiveModuleLoader(loader)
  194. const webserver = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(WEB_SERVER) as { WebServer?: unknown }
  195. expect(typeof webserver.WebServer).toBe('function')
  196. })
  197. it('runs the unchanged Landlock entry package over the Worker platform executable', async () => {
  198. const result = packedLandlock()
  199. expect(workspaces.has(LANDLOCK)).toBe(true)
  200. expect(result.packages.has(LANDLOCK)).toBe(true)
  201. expect(result.missing).toEqual([])
  202. expect(Object.hasOwn(result.files, `node_modules/${LANDLOCK}/lib/index.js`)).toBe(true)
  203. expect(createNodeBuiltins()[LANDLOCK]).toBeUndefined()
  204. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed Landlock package'), DEFAULT_ROOT)
  205. const loader = new WorkerModuleLoader({
  206. vfs,
  207. root: DEFAULT_ROOT,
  208. staticModules: createNodeBuiltins(),
  209. staticModulePrefixes: REPLACED_PREFIXES,
  210. })
  211. setActiveVfs(vfs)
  212. setActiveModuleLoader(loader)
  213. const landlock = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(LANDLOCK) as {
  214. LAUNCHER_BIN: string
  215. LAUNCHER_FAILURE_EXIT: number
  216. launcherPath(): string
  217. grantArgs(grants: { readOnly?: readonly string[]; readWrite?: readonly string[] }): string[]
  218. probe(): string
  219. }
  220. expect(landlock.LAUNCHER_BIN).toBe('landlock-run')
  221. expect(landlock.LAUNCHER_FAILURE_EXIT).toBe(125)
  222. expect(landlock.grantArgs({ readOnly: ['/'], readWrite: ['/tmp'] })).toEqual([
  223. '--ro', '/', '--rw', '/tmp',
  224. ])
  225. expect(landlock.launcherPath()).toBe(
  226. `${DEFAULT_ROOT}/node_modules/${LANDLOCK}/node_modules/${LANDLOCK}-${process.platform}-${process.arch}/bin/landlock-run`,
  227. )
  228. expect(landlock.probe()).toBe('full')
  229. })
  230. it('prepares the unchanged plugin-package inventory through Worker createRequire paths', async () => {
  231. const result = packedPluginInventory()
  232. expect(result.missing).toEqual([])
  233. const vfs = loadVfsImage(await inflateImage(result.image, 'the packed plugin inventory'), DEFAULT_ROOT)
  234. const loader = new WorkerModuleLoader({
  235. vfs,
  236. root: DEFAULT_ROOT,
  237. staticModules: createNodeBuiltins(),
  238. staticModulePrefixes: REPLACED_PREFIXES,
  239. })
  240. setActiveVfs(vfs)
  241. setActiveModuleLoader(loader)
  242. const inventory = loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(PLUGIN_INVENTORY) as {
  243. apply(ctx: unknown, config: unknown): void
  244. }
  245. type Prepared = { readonly value: { readonly version: number; readonly packages: readonly unknown[] } }
  246. type Prepare = (request: { readonly body: object; readonly signal: AbortSignal }) => Promise<Prepared>
  247. let prepare: Prepare | undefined
  248. const baseUrl = `file://${DEFAULT_ROOT}/config/cordis.yml`
  249. const tree: { readonly ctx: { readonly baseUrl: string }; entries(): readonly unknown[] } = {
  250. ctx: { baseUrl },
  251. entries: () => [entry],
  252. }
  253. const entry = {
  254. options: { name: PLUGIN_INVENTORY },
  255. disabled: false,
  256. fiber: { state: FiberState.ACTIVE },
  257. parent: { tree },
  258. }
  259. inventory.apply({
  260. baseUrl,
  261. loader: tree,
  262. deepseekLlmApiExtensions: {
  263. register: (field: string, contribution: { readonly prepare: Prepare }): void => {
  264. expect(field).toBe('dsh_plugin_packages')
  265. prepare = contribution.prepare
  266. },
  267. },
  268. }, {})
  269. if (prepare === undefined) throw new Error('packed plugin inventory did not register its request contribution')
  270. const prepared = await prepare({ body: {}, signal: new AbortController().signal })
  271. const manifest = JSON.parse(vfs.readFileSync(
  272. `${DEFAULT_ROOT}/node_modules/${PLUGIN_INVENTORY}/package.json`, 'utf8',
  273. ) as string) as { version: string }
  274. expect(prepared.value).toEqual({
  275. version: 1,
  276. packages: [{ name: PLUGIN_INVENTORY, version: manifest.version }],
  277. })
  278. })
  279. it('refuses a body the packer did not lower, naming the image', async () => {
  280. // The case above only proves the packed bytes are wrappable. This is the
  281. // other half: the loader has no transform to fall back on, so an entry the
  282. // collector missed must fail loud against the image rather than boot.
  283. const vfs = loadVfsImage(await archive(), DEFAULT_ROOT)
  284. vfs.seed(
  285. `${DEFAULT_ROOT}/node_modules/${SUBJECT}/lib/index.js`,
  286. new TextEncoder().encode('export const timeoutOf = () => 0\n'),
  287. )
  288. const loader = new WorkerModuleLoader({
  289. vfs,
  290. root: DEFAULT_ROOT,
  291. staticModules: createNodeBuiltins(),
  292. staticModulePrefixes: REPLACED_PREFIXES,
  293. })
  294. expect(() => loader.requireFrom(`${DEFAULT_ROOT}/workspace`)(SUBJECT))
  295. .toThrow(/still carries module syntax, so the image was not lowered by the packer/)
  296. })
  297. })