image-loadable.spec.ts 15 KB

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