image-loadable.spec.ts 16 KB

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