image-loadable.spec.ts 15 KB

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