skill-filesystem-watcher.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { EventEmitter } from 'node:events'
  2. import type { Stats } from 'node:fs'
  3. import { mkdir, realpath, rm, symlink, writeFile } from 'node:fs/promises'
  4. import { join } from 'node:path'
  5. import { tmpdir } from 'node:os'
  6. import { beforeEach, describe, expect, it, vi } from 'vitest'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import SkillRegistry from '@deepseek-ai/dsh-skill'
  9. interface FakeWatcherControl {
  10. emitter: EventEmitter
  11. closeCalls: number
  12. options: Record<string, unknown>
  13. path: string
  14. }
  15. interface FakeWatchFileControl {
  16. path: string
  17. listener(current: Stats, previous: Stats): void
  18. }
  19. interface FakeStatGate {
  20. started: PromiseWithResolvers<undefined>
  21. release: PromiseWithResolvers<undefined>
  22. }
  23. const watcherHarness = vi.hoisted(() => ({
  24. watchers: [] as FakeWatcherControl[],
  25. startupErrors: [] as Error[],
  26. closeErrors: 0,
  27. deferredReady: 0,
  28. watchFiles: [] as FakeWatchFileControl[],
  29. statGates: [] as FakeStatGate[],
  30. }))
  31. vi.mock('node:fs', async (importOriginal) => {
  32. const actual = await importOriginal<typeof import('node:fs')>()
  33. return {
  34. ...actual,
  35. watchFile(path: string, _options: unknown, listener: FakeWatchFileControl['listener']) {
  36. watcherHarness.watchFiles.push({ path, listener })
  37. },
  38. unwatchFile(path: string, listener: FakeWatchFileControl['listener']) {
  39. const index = watcherHarness.watchFiles.findIndex(control => control.path === path && control.listener === listener)
  40. if (index !== -1) watcherHarness.watchFiles.splice(index, 1)
  41. },
  42. }
  43. })
  44. vi.mock('node:fs/promises', async (importOriginal) => {
  45. const actual = await importOriginal<typeof import('node:fs/promises')>()
  46. return {
  47. ...actual,
  48. async stat(...args: Parameters<typeof actual.stat>) {
  49. const gate = watcherHarness.statGates.shift()
  50. if (gate !== undefined) {
  51. gate.started.resolve(undefined)
  52. await gate.release.promise
  53. }
  54. return await actual.stat(...args)
  55. },
  56. }
  57. })
  58. vi.mock('chokidar', () => ({
  59. default: {
  60. watch(path: unknown, options: Record<string, unknown>) {
  61. const emitter = new EventEmitter() as EventEmitter & { close(): Promise<void> }
  62. const control: FakeWatcherControl = { emitter, closeCalls: 0, options, path: String(path) }
  63. emitter.close = async () => {
  64. control.closeCalls += 1
  65. if (watcherHarness.closeErrors > 0) {
  66. watcherHarness.closeErrors -= 1
  67. throw new Error('close failed')
  68. }
  69. }
  70. watcherHarness.watchers.push(control)
  71. queueMicrotask(() => {
  72. if (watcherHarness.deferredReady > 0) {
  73. watcherHarness.deferredReady -= 1
  74. return
  75. }
  76. const error = watcherHarness.startupErrors.shift()
  77. if (error === undefined) emitter.emit('ready')
  78. else emitter.emit('error', error)
  79. })
  80. return emitter
  81. },
  82. },
  83. }))
  84. const SkillFileSystem = await import('../src/index.ts')
  85. async function tempDir(name: string): Promise<string> {
  86. return await import('node:fs/promises').then(fs => fs.mkdtemp(join(tmpdir(), `dsh-${name}-`)))
  87. }
  88. async function writeSkill(root: string, name: string): Promise<void> {
  89. const directory = join(root, name)
  90. await mkdir(directory, { recursive: true })
  91. await writeFile(join(directory, 'SKILL.md'), `---\nname: ${name}\ndescription: ${name}\n---\n\nBody.\n`)
  92. }
  93. async function settle(): Promise<void> {
  94. await new Promise(resolve => setTimeout(resolve, 0))
  95. }
  96. beforeEach(() => {
  97. watcherHarness.watchers.length = 0
  98. watcherHarness.startupErrors.length = 0
  99. watcherHarness.closeErrors = 0
  100. watcherHarness.deferredReady = 0
  101. watcherHarness.watchFiles.length = 0
  102. watcherHarness.statGates.length = 0
  103. })
  104. describe('skill-filesystem watcher failures', () => {
  105. it('canonicalizes an existing root before opening its native watcher', async () => {
  106. const target = await tempDir('skill-watch-canonical-target')
  107. const aliasParent = await tempDir('skill-watch-canonical-alias')
  108. const alias = join(aliasParent, 'alias')
  109. await symlink(target, alias, process.platform === 'win32' ? 'junction' : 'dir')
  110. const root = join(alias, '.dsh/skills')
  111. await writeSkill(root, 'canonical-skill')
  112. const ctx = new Context()
  113. await ctx.plugin(SkillRegistry)
  114. const fiber = await ctx.plugin(SkillFileSystem, {
  115. dshHome: join(alias, '.dsh'),
  116. agentsHome: join(alias, '.agents'),
  117. watch: true,
  118. })
  119. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['canonical-skill'])
  120. expect(watcherHarness.watchers[0]?.path).toBe(await realpath(root))
  121. expect(watcherHarness.watchers[0]?.options.persistent).toBe(true)
  122. await fiber.dispose()
  123. })
  124. it('preserves a symlink root when link following is disabled', async () => {
  125. const target = await tempDir('skill-watch-link-target')
  126. const aliasParent = await tempDir('skill-watch-link-alias')
  127. const alias = join(aliasParent, 'skills')
  128. await writeSkill(target, 'linked-skill')
  129. await symlink(target, alias, process.platform === 'win32' ? 'junction' : 'dir')
  130. const ctx = new Context()
  131. await ctx.plugin(SkillRegistry)
  132. const fiber = await ctx.plugin(SkillFileSystem, {
  133. includeDefaultRoots: false,
  134. customSkillDirs: [alias],
  135. watch: true,
  136. watchFollowSymlinks: false,
  137. })
  138. try {
  139. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['linked-skill'])
  140. expect(watcherHarness.watchers[0]?.path).toBe(alias)
  141. expect(watcherHarness.watchers[0]?.options.followSymlinks).toBe(false)
  142. } finally {
  143. await fiber.dispose()
  144. await rm(aliasParent, { recursive: true, force: true })
  145. await rm(target, { recursive: true, force: true })
  146. }
  147. })
  148. it('ignores missing-path probes until the observed path actually changes', async () => {
  149. const home = await tempDir('skill-watch-missing-stable')
  150. const ctx = new Context()
  151. await ctx.plugin(SkillRegistry)
  152. const fiber = await ctx.plugin(SkillFileSystem, {
  153. dshHome: join(home, '.dsh'),
  154. agentsHome: join(home, '.agents'),
  155. watch: true,
  156. watchPollIntervalMs: 10,
  157. })
  158. expect(await ctx.skills.snapshot()).toEqual({ skills: [], complete: true })
  159. expect(watcherHarness.watchFiles).toHaveLength(2)
  160. let invalidations = 0
  161. ctx.on('skills/change', () => { invalidations += 1 })
  162. for (const control of watcherHarness.watchFiles) {
  163. control.listener({} as Stats, {} as Stats)
  164. }
  165. await settle()
  166. expect(invalidations).toBe(0)
  167. expect(watcherHarness.watchFiles).toHaveLength(2)
  168. await fiber.dispose()
  169. })
  170. it('keeps skills loadable across persistent watcher startup failures without caching them', async () => {
  171. const home = await tempDir('skill-watch-start-error')
  172. const root = join(home, '.dsh/skills')
  173. await writeSkill(root, 'retry-skill')
  174. watcherHarness.startupErrors.push(
  175. new Error('watch failed once'),
  176. new Error('watch failed twice'),
  177. new Error('watch failed three times'),
  178. )
  179. watcherHarness.closeErrors = 1
  180. const ctx = new Context()
  181. await ctx.plugin(SkillRegistry)
  182. const fiber = await ctx.plugin(SkillFileSystem, {
  183. dshHome: join(home, '.dsh'),
  184. agentsHome: join(home, '.agents'),
  185. watch: true,
  186. watchUsePolling: true,
  187. watchFollowSymlinks: false,
  188. watchPollIntervalMs: 10,
  189. watchStabilityThresholdMs: 20,
  190. })
  191. expect(await ctx.skills.snapshot()).toMatchObject({
  192. skills: [{ name: 'retry-skill' }],
  193. complete: false,
  194. })
  195. expect((await ctx.skills.get('retry-skill'))?.content).toBe('Body.')
  196. expect(await ctx.skills.snapshot()).toMatchObject({
  197. skills: [{ name: 'retry-skill' }],
  198. complete: false,
  199. })
  200. expect(watcherHarness.watchers).toHaveLength(3)
  201. expect(watcherHarness.watchers[0]?.options).toMatchObject({
  202. atomic: true,
  203. depth: 1,
  204. followSymlinks: false,
  205. usePolling: true,
  206. interval: 10,
  207. awaitWriteFinish: {
  208. stabilityThreshold: 20,
  209. pollInterval: 10,
  210. },
  211. })
  212. await fiber.dispose()
  213. })
  214. it('filters events, coalesces invalidation, recovers runtime errors, and contains late callbacks', async () => {
  215. const home = await tempDir('skill-watch-runtime-error')
  216. const root = join(home, '.dsh/skills')
  217. await writeSkill(root, 'watched-skill')
  218. const ctx = new Context()
  219. await ctx.plugin(SkillRegistry)
  220. const fiber = await ctx.plugin(SkillFileSystem, {
  221. dshHome: join(home, '.dsh'),
  222. agentsHome: join(home, '.agents'),
  223. watch: true,
  224. watchPollIntervalMs: 10,
  225. watchStabilityThresholdMs: 20,
  226. })
  227. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['watched-skill'])
  228. let invalidations = 0
  229. ctx.on('skills/change', () => { invalidations += 1 })
  230. const first = watcherHarness.watchers[0]
  231. if (first === undefined) throw new Error('expected a root watcher')
  232. first.emitter.emit('change', join(first.path, 'notes.txt'))
  233. first.emitter.emit('change', join(home, 'outside.md'))
  234. first.emitter.emit('change', join(first.path, 'watched-skill/references.md'))
  235. first.emitter.emit('change', join(first.path, '.system/SKILL.md'))
  236. await settle()
  237. expect(invalidations).toBe(0)
  238. first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
  239. first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
  240. await settle()
  241. expect(invalidations).toBe(1)
  242. watcherHarness.closeErrors = 1
  243. watcherHarness.startupErrors.push(new Error('runtime rewatch failed'))
  244. first.emitter.emit('error', new Error('runtime watch failed'))
  245. await vi.waitFor(() => { expect(watcherHarness.watchers.length).toBeGreaterThanOrEqual(2) })
  246. expect(invalidations).toBeGreaterThanOrEqual(2)
  247. expect(await ctx.skills.snapshot()).toMatchObject({
  248. skills: [{ name: 'watched-skill' }],
  249. complete: true,
  250. })
  251. await fiber.dispose()
  252. first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
  253. first.emitter.emit('error', new Error('late error'))
  254. await settle()
  255. })
  256. it('replaces a retained watcher when its root emits unlinkDir', async () => {
  257. const home = await tempDir('skill-watch-root-unlink')
  258. const root = join(home, '.dsh/skills')
  259. await writeSkill(root, 'removed-skill')
  260. const ctx = new Context()
  261. await ctx.plugin(SkillRegistry)
  262. const fiber = await ctx.plugin(SkillFileSystem, {
  263. dshHome: join(home, '.dsh'),
  264. agentsHome: join(home, '.agents'),
  265. watch: true,
  266. watchPollIntervalMs: 10,
  267. watchStabilityThresholdMs: 20,
  268. })
  269. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['removed-skill'])
  270. const original = watcherHarness.watchers[0]
  271. if (original === undefined) throw new Error('expected a root watcher')
  272. await rm(root, { recursive: true })
  273. original.emitter.emit('unlinkDir', original.path)
  274. await vi.waitFor(() => { expect(original.closeCalls).toBeGreaterThan(0) })
  275. await vi.waitFor(() => {
  276. expect(watcherHarness.watchFiles.some(control => control.path === original.path)).toBe(true)
  277. })
  278. await fiber.dispose()
  279. })
  280. it('re-probes a retained root after child unlink and observes immediate recreation', async () => {
  281. const home = await tempDir('skill-watch-root-reprobe')
  282. const root = join(home, '.dsh/skills')
  283. await writeSkill(root, 'old-skill')
  284. const ctx = new Context()
  285. await ctx.plugin(SkillRegistry)
  286. const fiber = await ctx.plugin(SkillFileSystem, {
  287. dshHome: join(home, '.dsh'),
  288. agentsHome: join(home, '.agents'),
  289. watch: true,
  290. watchPollIntervalMs: 10,
  291. watchStabilityThresholdMs: 20,
  292. })
  293. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['old-skill'])
  294. const original = watcherHarness.watchers[0]
  295. if (original === undefined) throw new Error('expected a root watcher')
  296. await rm(root, { recursive: true })
  297. original.emitter.emit('unlink', join(original.path, 'old-skill/SKILL.md'))
  298. await settle()
  299. expect(await ctx.skills.snapshot()).toEqual({ skills: [], complete: true })
  300. const missingRoot = watcherHarness.watchFiles.find(control => control.path === original.path)
  301. expect(missingRoot).toBeDefined()
  302. await writeSkill(root, 'recreated-skill')
  303. missingRoot!.listener({} as Stats, {} as Stats)
  304. await vi.waitFor(() => { expect(watcherHarness.watchers).toHaveLength(2) })
  305. await settle()
  306. expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['recreated-skill'])
  307. await fiber.dispose()
  308. })
  309. it('settles an opening watcher when plugin disposal races its ready event', async () => {
  310. const home = await tempDir('skill-watch-opening-dispose')
  311. const root = join(home, '.dsh/skills')
  312. await writeSkill(root, 'racing-skill')
  313. watcherHarness.deferredReady = 1
  314. const ctx = new Context()
  315. await ctx.plugin(SkillRegistry)
  316. let provider!: InstanceType<typeof SkillFileSystem.FileSystemSkillProvider>
  317. const disposeProvider = ctx.skills.registerProvider((control) => {
  318. provider = new SkillFileSystem.FileSystemSkillProvider(ctx, control, {
  319. dshHome: join(home, '.dsh'),
  320. agentsHome: join(home, '.agents'),
  321. watch: true,
  322. watchPollIntervalMs: 10,
  323. watchStabilityThresholdMs: 20,
  324. })
  325. return provider
  326. })
  327. const discovery = provider.list({})
  328. await vi.waitFor(() => { expect(watcherHarness.watchers).toHaveLength(1) })
  329. const first = watcherHarness.watchers[0]
  330. if (first === undefined) throw new Error('expected an opening root watcher')
  331. const disposal = provider.dispose()
  332. await expect(discovery).rejects.toThrow('skill-filesystem watcher disposed')
  333. await disposal
  334. disposeProvider()
  335. await settle()
  336. expect(first.closeCalls).toBeGreaterThan(0)
  337. })
  338. it('closes an opening watcher when disposal wins the mode probe', async () => {
  339. const home = await tempDir('skill-watch-probe-dispose')
  340. const root = join(home, '.dsh/skills')
  341. await writeSkill(root, 'racing-skill')
  342. watcherHarness.deferredReady = 1
  343. const statGate: FakeStatGate = {
  344. started: Promise.withResolvers<undefined>(),
  345. release: Promise.withResolvers<undefined>(),
  346. }
  347. watcherHarness.statGates.push(statGate)
  348. const ctx = new Context()
  349. await ctx.plugin(SkillRegistry)
  350. let provider!: InstanceType<typeof SkillFileSystem.FileSystemSkillProvider>
  351. const disposeProvider = ctx.skills.registerProvider((control) => {
  352. provider = new SkillFileSystem.FileSystemSkillProvider(ctx, control, {
  353. dshHome: join(home, '.dsh'),
  354. agentsHome: join(home, '.agents'),
  355. watch: true,
  356. watchPollIntervalMs: 10,
  357. watchStabilityThresholdMs: 20,
  358. })
  359. return provider
  360. })
  361. const discovery = provider.list({})
  362. await statGate.started.promise
  363. const disposal = provider.dispose()
  364. statGate.release.resolve(undefined)
  365. await expect(discovery).rejects.toThrow('skill-filesystem watcher disposed')
  366. await disposal
  367. expect(watcherHarness.watchers).toHaveLength(1)
  368. expect(watcherHarness.watchers[0]?.closeCalls).toBeGreaterThan(0)
  369. disposeProvider()
  370. })
  371. it('contains an opening watcher rejection during provider teardown', async () => {
  372. const home = await tempDir('skill-watch-opening-reject')
  373. const root = join(home, '.dsh/skills')
  374. await writeSkill(root, 'rejected-skill')
  375. watcherHarness.deferredReady = 1
  376. const ctx = new Context()
  377. await ctx.plugin(SkillRegistry)
  378. let provider!: InstanceType<typeof SkillFileSystem.FileSystemSkillProvider>
  379. const disposeProvider = ctx.skills.registerProvider((control) => {
  380. provider = new SkillFileSystem.FileSystemSkillProvider(ctx, control, {
  381. dshHome: join(home, '.dsh'),
  382. agentsHome: join(home, '.agents'),
  383. watch: true,
  384. watchPollIntervalMs: 10,
  385. watchStabilityThresholdMs: 20,
  386. })
  387. return provider
  388. })
  389. const discovery = provider.list({})
  390. await vi.waitFor(() => { expect(watcherHarness.watchers).toHaveLength(1) })
  391. const first = watcherHarness.watchers[0]
  392. if (first === undefined) throw new Error('expected an opening root watcher')
  393. first.emitter.emit('error', new Error('opening failed during disposal'))
  394. const disposal = provider.dispose()
  395. await expect(discovery).rejects.toThrow('opening failed during disposal')
  396. await disposal
  397. disposeProvider()
  398. })
  399. })