image-loadable.spec.ts 13 KB

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