fs.spec.ts 11 KB

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