fs.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /**
  2. * Behavioural check of this package's `node:fs` bridge over a real MemoryVfs:
  3. * encoding branches, Dirent, file descriptors, FileHandle append/replace semantics,
  4. * and Node's error codes.
  5. *
  6. * Migrated from apps/web-preview/scripts/checks/fs-check.ts.
  7. *
  8. * ONE module instance, and every import says so explicitly. The bridge reaches
  9. * the VFS through a module-level slot (`setActiveVfs`/`requireActiveVfs`), so the
  10. * harness that mounts the VFS and the bridge that reads it must be the same copy
  11. * of `src/storage/memory.ts`. Two copies mean the mount lands in one and the bridge reports
  12. * `no filesystem is mounted` from the other — the incident this check itself
  13. * caused once, when it imported the built `lib/` while the bridge resolved to
  14. * `src/`.
  15. *
  16. * Note the package-name subtlety that made that bug possible: the BARE specifier
  17. * `@deepseek-ai/dsh-experimental-webworker-runtime` resolves to built `lib/index.js`, while
  18. * `…/src/*` resolves to source. Under tsx those two happen to share a `vfs`
  19. * instance today, so a mixed-path version of this file passes — for now. Pinning
  20. * every import to `src/` removes the coincidence instead of depending on it.
  21. */
  22. import { expect, test } from 'vitest'
  23. import { MemoryVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/memory.ts'
  24. import { setActiveVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/active.ts'
  25. import * as fs from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/fs.ts'
  26. import * as fsp from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/fs/promises.ts'
  27. import type { VfsBigIntStats, VfsStats } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/types.ts'
  28. const vfs = new MemoryVfs()
  29. setActiveVfs(vfs)
  30. // Precondition, not a behaviour: prove the bridge reads the VFS this file mounted.
  31. // If these ever resolve to two module copies again, the write below would report
  32. // `no filesystem is mounted` — but a bridge that answered from some OTHER mounted
  33. // VFS would pass the whole suite while testing the wrong world, so the identity is
  34. // asserted rather than inferred from things working. The probe creates its own
  35. // directory: the suite's `/dsh` tree does not exist yet at this point.
  36. fs.mkdirSync('/dsh/.probe', { recursive: true })
  37. fs.writeFileSync('/dsh/.probe/instance', 'x')
  38. if (!vfs.existsSync('/dsh/.probe/instance')) {
  39. throw new Error('fs-check: the fs bridge is not reading the VFS this harness mounted '
  40. + '(two module instances — check that every import resolves through src/)')
  41. }
  42. vfs.rmSync('/dsh/.probe', { recursive: true })
  43. const check = (label: string, actual: unknown, expected: unknown): void => {
  44. const [seen, wanted] = [JSON.stringify(actual), JSON.stringify(expected)]
  45. test(label, () => { expect(seen).toBe(wanted) })
  46. }
  47. const throws = (label: string, run: () => unknown, code: string): void => {
  48. let outcome: string
  49. try {
  50. run()
  51. outcome = 'did not throw'
  52. } catch (error) {
  53. outcome = (error as { code?: string }).code ?? (error as Error).message
  54. }
  55. test(label, () => { expect(outcome).toContain(code) })
  56. }
  57. fs.mkdirSync('/dsh/config', { recursive: true })
  58. fs.writeFileSync('/dsh/config/cordis.yml', '- id: timer\n')
  59. check('readFileSync utf8', fs.readFileSync('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n')
  60. check('readFileSync options object', fs.readFileSync('/dsh/config/cordis.yml', { encoding: 'utf8' }), '- id: timer\n')
  61. check('readFileSync bytes length', (fs.readFileSync('/dsh/config/cordis.yml') as Uint8Array).byteLength, 12)
  62. check('readFileSync is Buffer', Buffer.isBuffer(fs.readFileSync('/dsh/config/cordis.yml')), true)
  63. check('existsSync true', fs.existsSync('/dsh/config/cordis.yml'), true)
  64. check('existsSync false', fs.existsSync('/dsh/nope'), false)
  65. check('statSync isFile', fs.statSync('/dsh/config/cordis.yml').isFile(), true)
  66. check('statSync size', fs.statSync('/dsh/config/cordis.yml').size, 12)
  67. check('statSync dir', fs.statSync('/dsh/config').isDirectory(), true)
  68. check('realpathSync', fs.realpathSync('/dsh/config/../config/cordis.yml'), '/dsh/config/cordis.yml')
  69. fs.appendFileSync('/dsh/config/cordis.yml', '- id: llm\n')
  70. check('appendFileSync', fs.readFileSync('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n- id: llm\n')
  71. fs.mkdirSync('/dsh/config/agent-presets/standard', { recursive: true })
  72. fs.writeFileSync('/dsh/config/agent-presets/standard/SKILL.md', '# skill\n')
  73. check('readdirSync names', fs.readdirSync('/dsh/config'), ['agent-presets', 'cordis.yml'])
  74. const entries = fs.readdirSync('/dsh/config', { withFileTypes: true }) as fs.Dirent[]
  75. check('readdirSync withFileTypes', entries.map(entry => [entry.name, entry.isFile(), entry.isDirectory()]), [
  76. ['agent-presets', false, true],
  77. ['cordis.yml', true, false],
  78. ])
  79. check('Dirent parentPath', entries[0]!.parentPath, '/dsh/config')
  80. const temporary = fs.mkdtempSync('/dsh/tmp/run-')
  81. check('mkdtempSync creates directory', fs.statSync(temporary).isDirectory(), true)
  82. check('mkdtempSync unique', fs.mkdtempSync('/dsh/tmp/run-') === temporary, false)
  83. throws('readFileSync missing', () => fs.readFileSync('/dsh/missing'), 'ENOENT')
  84. throws('statSync missing', () => fs.statSync('/dsh/missing'), 'ENOENT')
  85. throws('accessSync missing', () =>{ fs.accessSync('/dsh/missing') }, 'ENOENT')
  86. throws('readdirSync missing', () => fs.readdirSync('/dsh/missing'), 'ENOENT')
  87. throws('watchFile is loud', () => fs.watchFile('/dsh/config/cordis.yml'), 'not implemented')
  88. throws('createReadStream is loud', () => fs.createReadStream('/dsh/config/cordis.yml'), 'not implemented')
  89. const appendFd = fs.openSync('/dsh/log.jsonl', 'a')
  90. fs.writeSync(appendFd, '{"a":1}\n')
  91. fs.writeSync(appendFd, '{"a":2}\n')
  92. fs.closeSync(appendFd)
  93. check('append fd writes', fs.readFileSync('/dsh/log.jsonl', 'utf8'), '{"a":1}\n{"a":2}\n')
  94. const readFd = fs.openSync('/dsh/log.jsonl', 'r')
  95. const target = new Uint8Array(8)
  96. check('readSync count', fs.readSync(readFd, target, 0, 8), 8)
  97. check('readSync bytes', new TextDecoder().decode(target), '{"a":1}\n')
  98. check('readSync continues', fs.readSync(readFd, target, 0, 8), 8)
  99. check('readSync second line', new TextDecoder().decode(target), '{"a":2}\n')
  100. check('readSync at eof', fs.readSync(readFd, target, 0, 8), 0)
  101. fs.closeSync(readFd)
  102. throws('closed fd', () => fs.readSync(readFd, target, 0, 8), 'EBADF')
  103. const writeFd = fs.openSync('/dsh/truncated.txt', 'w')
  104. fs.writeSync(writeFd, 'abc')
  105. fs.closeSync(writeFd)
  106. check('write fd truncates', fs.readFileSync('/dsh/truncated.txt', 'utf8'), 'abc')
  107. fs.renameSync('/dsh/truncated.txt', '/dsh/renamed.txt')
  108. check('renameSync moves', [fs.existsSync('/dsh/truncated.txt'), fs.readFileSync('/dsh/renamed.txt', 'utf8')], [false, 'abc'])
  109. fs.rmSync('/dsh/renamed.txt')
  110. check('rmSync removes', fs.existsSync('/dsh/renamed.txt'), false)
  111. // A FileHandle opened for appending must append, not replace: the JSONL session
  112. // log writes its header frame first and every batch after it through this path.
  113. fs.writeFileSync('/dsh/log-handle.jsonl', 'header\n')
  114. const appendHandle = await fsp.open('/dsh/log-handle.jsonl', 'a')
  115. check('append handle sees the existing size', (await appendHandle.stat()).size, 7)
  116. await appendHandle.writeFile('batch-1\n')
  117. await appendHandle.sync()
  118. await appendHandle.close()
  119. const secondHandle = await fsp.open('/dsh/log-handle.jsonl', 'a')
  120. await secondHandle.writeFile('batch-2\n')
  121. await secondHandle.close()
  122. check('handle.writeFile appends in append mode', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'header\nbatch-1\nbatch-2\n')
  123. const replaceHandle = await fsp.open('/dsh/log-handle.jsonl', 'w')
  124. await replaceHandle.writeFile('replaced\n')
  125. await replaceHandle.close()
  126. check('handle.writeFile replaces without append mode', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'replaced\n')
  127. const truncHandle = await fsp.open('/dsh/log-handle.jsonl', 'r+')
  128. await truncHandle.truncate(4)
  129. await truncHandle.close()
  130. check('handle.truncate cuts the tail', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'repl')
  131. check('promises.readFile', await fsp.readFile('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n- id: llm\n')
  132. await fsp.writeFile('/dsh/promise.txt', 'p')
  133. check('promises.writeFile', fs.readFileSync('/dsh/promise.txt', 'utf8'), 'p')
  134. check('promises.stat', (await fsp.stat('/dsh/promise.txt')).isFile(), true)
  135. await fsp.cp('/dsh/config', '/dsh/config-copy')
  136. check('promises.cp tree', await fsp.readFile('/dsh/config-copy/agent-presets/standard/SKILL.md', 'utf8'), '# skill\n')
  137. await fsp.rm('/dsh/config-copy', { recursive: true })
  138. check('promises.rm recursive', fs.existsSync('/dsh/config-copy'), false)
  139. // ---------------------------------------------------------------------------
  140. // The `{ bigint: true }` stats the filesystem service reads.
  141. //
  142. // `dsh-fs-local` stats EVERY target this way before it lists or reads: it masks
  143. // `mode` with a BigInt literal and builds its version token from
  144. // `dev:ino:size:mtimeNs:ctimeNs`. A number-valued `mode` here made that mask
  145. // throw `Cannot mix BigInt and other types`, which the service reported as
  146. // FS_IO_ERROR and skill discovery swallowed as "empty directory" — the worker
  147. // booted with an empty skill catalog and no error anywhere.
  148. // ---------------------------------------------------------------------------
  149. const bigStats = (path: string): VfsBigIntStats => fs.statSync(path, { bigint: true }) as VfsBigIntStats
  150. fs.writeFileSync('/dsh/versioned.txt', 'one')
  151. {
  152. const stats = bigStats('/dsh/versioned.txt')
  153. check('bigint stat reports mode as a BigInt', typeof stats.mode, 'bigint')
  154. check('bigint mode masks to the creation-default file permission', Number(stats.mode & 0o777n), 0o644)
  155. check('bigint stat reports the identity fields the version token needs', [
  156. typeof stats.dev, typeof stats.ino, typeof stats.size, typeof stats.mtimeNs, typeof stats.ctimeNs,
  157. ], ['bigint', 'bigint', 'bigint', 'bigint', 'bigint'])
  158. check('bigint nanosecond time scales the millisecond time', stats.mtimeNs === stats.mtimeMs * 1_000_000n, true)
  159. check('bigint stat still answers the type predicates', [stats.isFile(), stats.isDirectory()], [true, false])
  160. check('plain stat keeps its number shape', typeof fs.statSync('/dsh/versioned.txt').mode, 'number')
  161. }
  162. {
  163. // Two writes inside one millisecond must not produce one version: the service's
  164. // stale-write guard compares these tokens.
  165. const token = (path: string): string => {
  166. const stats = bigStats(path)
  167. return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`
  168. }
  169. const before = token('/dsh/versioned.txt')
  170. fs.writeFileSync('/dsh/versioned.txt', 'two')
  171. check('a rewrite changes the version token', token('/dsh/versioned.txt') !== before, true)
  172. check('an unchanged file keeps its version token', token('/dsh/versioned.txt'), token('/dsh/versioned.txt'))
  173. }
  174. {
  175. const first = bigStats('/dsh/versioned.txt').ino
  176. fs.writeFileSync('/dsh/versioned.txt', 'three')
  177. check('identity survives a write to the same path', String(bigStats('/dsh/versioned.txt').ino), String(first))
  178. fs.rmSync('/dsh/versioned.txt')
  179. fs.writeFileSync('/dsh/versioned.txt', 'four')
  180. check('a removed and recreated path reports a new identity', bigStats('/dsh/versioned.txt').ino !== first, true)
  181. }
  182. check('a directory reports the creation-default mode in the bigint shape', Number(bigStats('/dsh/config').mode & 0o777n), 0o755)
  183. // ---------------------------------------------------------------------------
  184. // Permission bits round-trip: creation takes the caller's mode, chmod changes
  185. // it, stat reads back the stored value. dsh-credentials-local's owner-only
  186. // check reads exactly this (writeFileAtomic writes `wx` + mode 600, renames
  187. // into place, then the provider stats the result).
  188. // ---------------------------------------------------------------------------
  189. const plainMode = (path: string): number => (fs.statSync(path) as VfsStats).mode & 0o777
  190. fs.writeFileSync('/dsh/secrets.tmp', 'k: v\n', { mode: 0o600, flag: 'wx' })
  191. fs.renameSync('/dsh/secrets.tmp', '/dsh/secrets.yaml')
  192. check('a wx write with mode 600 stats as 600 after rename', plainMode('/dsh/secrets.yaml'), 0o600)
  193. fs.writeFileSync('/dsh/secrets.yaml', 'k: w\n')
  194. check('a rewrite keeps the creation bits', plainMode('/dsh/secrets.yaml'), 0o600)
  195. fs.chmodSync('/dsh/secrets.yaml', 0o640)
  196. check('chmod reads back exactly what was set', plainMode('/dsh/secrets.yaml'), 0o640)
  197. await fsp.chmod('/dsh/secrets.yaml', 0o600)
  198. check('promises.chmod reads back through the bigint shape', Number(bigStats('/dsh/secrets.yaml').mode & 0o777n), 0o600)
  199. fs.mkdirSync('/dsh/vault', { mode: 0o700 })
  200. check('mkdir honours its mode option', plainMode('/dsh/vault'), 0o700)
  201. check('promises.stat forwards the bigint option', typeof (await fsp.stat('/dsh/config', { bigint: true })).mode, 'bigint')