Skip to content

Commit 202c1e3

Browse files
authored
fix: keep the skill tree when Windows denies the swap rename (#57)
1 parent 7ccb1b7 commit 202c1e3

4 files changed

Lines changed: 205 additions & 16 deletions

File tree

‎src/generator.ts‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
collectInstalledModulePackages,
88
copySkillTree,
99
createModuleDestination,
10+
createStagingPath,
1011
buildNuxtTemplateFiles,
1112
buildVueTemplateFiles,
1213
discoverPackageSkillsFromInstalledPackage,
@@ -44,7 +45,7 @@ import {
4445
createLocalSourceFingerprints,
4546
resolveManualContribution,
4647
} from './generation/sources'
47-
import { isGeneratedSkillFreshWithOptions, writeGenerationState } from './generation/state'
48+
import { isGeneratedSkillFreshWithOptions, readGenerationState, writeGenerationState } from './generation/state'
4849
import {
4950
normalizeRemoteOptions,
5051
type ModuleOptions,
@@ -206,6 +207,21 @@ async function collectInstalledPackages(nuxt: Nuxt) {
206207
}
207208
}
208209

210+
/**
211+
* True when `skillRoot` already holds this exact generation, so publishing can skip the folder
212+
* swap that Windows sometimes refuses while the repo's watchers hold a handle on the tree.
213+
*/
214+
async function isPublishedCopyCurrent(generatedSkillRoot: string, skillRoot: string): Promise<boolean> {
215+
const [generated, published, entryExists] = await Promise.all([
216+
readGenerationState(generatedSkillRoot),
217+
readGenerationState(skillRoot),
218+
pathExists(join(skillRoot, 'SKILL.md')),
219+
])
220+
return Boolean(generated && published && entryExists
221+
&& generated.fingerprint === published.fingerprint
222+
&& generated.generatedAt === published.generatedAt)
223+
}
224+
209225
/**
210226
* Puts the generated tree where each agent loads skills. Agents that load skill folders get the
211227
* whole tree, written once to `.agents/skills` for the agents that read it. Agents with a rules
@@ -242,7 +258,9 @@ export async function publishSkill(input: {
242258
}
243259

244260
if (loadsSkillFolders(target)) {
245-
await replaceSkillTree(generatedSkillRoot, skillRoot)
261+
if (!(await isPublishedCopyCurrent(generatedSkillRoot, skillRoot))) {
262+
await replaceSkillTree(generatedSkillRoot, skillRoot)
263+
}
246264
continue
247265
}
248266

@@ -296,12 +314,6 @@ export async function generateSkillTree(input: {
296314
// Older versions kept the tree in the build dir.
297315
await fsp.rm(join(nuxt.options.buildDir, 'skill-hub'), { recursive: true, force: true })
298316
}
299-
// Built here, then swapped in, so a failed run keeps the previous tree.
300-
const stagingRoot = `${generatedSkillRoot}.staging`
301-
const referencesRoot = join(stagingRoot, 'references')
302-
const nuxtRoot = join(referencesRoot, 'nuxt')
303-
const vueRoot = join(referencesRoot, 'vue')
304-
const modulesRoot = join(referencesRoot, 'modules')
305317
const monorepoScopePath = resolveMonorepoScopePath(nuxt.options.rootDir, exportRoot)
306318
const manualContributions: SkillHubContribution[] = []
307319
const remoteOptions = normalizeRemoteOptions(options.remote)
@@ -489,6 +501,12 @@ export async function generateSkillTree(input: {
489501
logger.warn(`[validation] ${issue.packageName}/${issue.skillName}: ${issue.reason}`)
490502
}
491503

504+
// Built here, then swapped in, so a failed run keeps the previous tree.
505+
const stagingRoot = await createStagingPath(generatedSkillRoot)
506+
const referencesRoot = join(stagingRoot, 'references')
507+
const nuxtRoot = join(referencesRoot, 'nuxt')
508+
const vueRoot = join(referencesRoot, 'vue')
509+
const modulesRoot = join(referencesRoot, 'modules')
492510
await emptyDir(stagingRoot)
493511
try {
494512
await ensureDir(nuxtRoot)

‎src/internal.ts‎

Lines changed: 73 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { existsSync, lstatSync, promises as fsp } from 'node:fs'
2+
import { randomBytes } from 'node:crypto'
23
import { homedir } from 'node:os'
34
import { basename, dirname, isAbsolute, join, relative, resolve } from 'pathe'
45
import matter from 'gray-matter'
@@ -625,23 +626,89 @@ export async function copySkillTree(sourceDir: string, destinationDir: string, i
625626
})
626627
}
627628

629+
const RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY'])
630+
const RENAME_RETRY_DELAYS_MS = [50, 100, 200, 400, 800]
631+
632+
/**
633+
* Windows denies a rename while another process (a watcher, indexer or virus scanner) holds a
634+
* handle in the tree, which clears within a few hundred milliseconds.
635+
*/
636+
async function renameWithRetry(from: string, to: string): Promise<void> {
637+
for (const delay of RENAME_RETRY_DELAYS_MS) {
638+
try {
639+
await fsp.rename(from, to)
640+
return
641+
}
642+
catch (error) {
643+
if (!RENAME_RETRY_CODES.has((error as NodeJS.ErrnoException).code ?? '')) {
644+
throw error
645+
}
646+
await new Promise(resolve => setTimeout(resolve, delay))
647+
}
648+
}
649+
await fsp.rename(from, to)
650+
}
651+
652+
function isProcessAlive(pid: number): boolean {
653+
try {
654+
process.kill(pid, 0)
655+
return true
656+
}
657+
catch (error) {
658+
return (error as NodeJS.ErrnoException).code === 'EPERM'
659+
}
660+
}
661+
628662
/**
629-
* Moves a finished `staging` tree to `target`. Readers see the old tree or the new one, never a
630-
* partial one, and a failure before this call leaves `target` untouched.
663+
* Returns a staging path next to `target` that no other process uses, so a dev server and
664+
* `nuxt prepare` can't wipe each other's tree. Removes staging trees left by runs that crashed.
665+
*/
666+
export async function createStagingPath(target: string): Promise<string> {
667+
const prefix = `${basename(target)}.staging`
668+
const parent = dirname(target)
669+
await ensureDir(parent)
670+
for (const name of await fsp.readdir(parent)) {
671+
if (!name.startsWith(prefix)) {
672+
continue
673+
}
674+
const pid = Number(name.slice(prefix.length + 1).split('-')[0])
675+
if (!pid || !isProcessAlive(pid)) {
676+
await fsp.rm(join(parent, name), { recursive: true, force: true })
677+
}
678+
}
679+
return join(parent, `${prefix}-${process.pid}-${randomBytes(4).toString('hex')}`)
680+
}
681+
682+
/**
683+
* Moves a finished `staging` tree to `target`. If the move fails, the old tree goes back to
684+
* `target`. If another process published `target` meanwhile, its tree wins.
631685
*/
632686
export async function swapDir(staging: string, target: string): Promise<void> {
633687
const previous = `${target}.previous`
634688
await fsp.rm(previous, { recursive: true, force: true })
635-
if (await pathExists(target)) {
636-
await fsp.rename(target, previous)
689+
const hadTarget = await pathExists(target)
690+
if (hadTarget) {
691+
await renameWithRetry(target, previous)
692+
}
693+
try {
694+
await renameWithRetry(staging, target)
695+
}
696+
catch (error) {
697+
if (await pathExists(target)) {
698+
await fsp.rm(previous, { recursive: true, force: true })
699+
return
700+
}
701+
if (hadTarget) {
702+
await renameWithRetry(previous, target)
703+
}
704+
throw error
637705
}
638-
await fsp.rename(staging, target)
639706
await fsp.rm(previous, { recursive: true, force: true })
640707
}
641708

642709
/** Like `copySkillTree`, but the destination switches over only once the copy is complete. */
643710
export async function replaceSkillTree(sourceDir: string, destinationDir: string): Promise<void> {
644-
const staging = `${destinationDir}.staging`
711+
const staging = await createStagingPath(destinationDir)
645712
try {
646713
await copySkillTree(sourceDir, staging, true)
647714
await swapDir(staging, destinationDir)

‎test/internal.test.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { promises as fsp } from 'node:fs'
22
import { tmpdir } from 'node:os'
33
import { join } from 'node:path'
4-
import { describe, expect, it, vi } from 'vitest'
4+
import { afterEach, describe, expect, it, vi } from 'vitest'
55
import {
6+
createStagingPath,
67
discoverInstalledPackageFromDirectory,
78
getTargetSkillRoot,
89
isValidSkillName,
@@ -297,6 +298,10 @@ describe('getTargetSkillRoot', () => {
297298
})
298299

299300
describe('swapDir and replaceSkillTree', () => {
301+
afterEach(() => {
302+
vi.restoreAllMocks()
303+
})
304+
300305
it('replaces a tree only once the new one is complete', async () => {
301306
const root = await fsp.mkdtemp(join(tmpdir(), 'skill-hub-swap-'))
302307
const target = join(root, 'skill')
@@ -305,7 +310,6 @@ describe('swapDir and replaceSkillTree', () => {
305310

306311
await expect(replaceSkillTree(join(root, 'missing'), target)).rejects.toThrow()
307312
await expect(fsp.readFile(join(target, 'SKILL.md'), 'utf8')).resolves.toBe('old')
308-
await expect(fsp.access(`${target}.staging`)).rejects.toBeDefined()
309313

310314
const staging = join(root, 'staging')
311315
await fsp.mkdir(staging)
@@ -316,4 +320,86 @@ describe('swapDir and replaceSkillTree', () => {
316320
expect((await fsp.readdir(root)).sort()).toEqual(['skill'])
317321
await fsp.rm(root, { recursive: true, force: true })
318322
})
323+
324+
async function createSwapFixture() {
325+
const root = await fsp.mkdtemp(join(tmpdir(), 'skill-hub-swap-'))
326+
const target = join(root, 'skill')
327+
const staging = join(root, 'staging')
328+
await fsp.mkdir(target)
329+
await fsp.writeFile(join(target, 'SKILL.md'), 'old')
330+
await fsp.mkdir(staging)
331+
await fsp.writeFile(join(staging, 'SKILL.md'), 'new')
332+
return { root, target, staging }
333+
}
334+
335+
/** Makes `fsp.rename` fail with EPERM, as Windows does, for the first `times` moves from `from`. */
336+
function denyRenames(from: string, times: number) {
337+
const rename = fsp.rename.bind(fsp)
338+
let denied = 0
339+
return vi.spyOn(fsp, 'rename').mockImplementation(async (source, destination) => {
340+
if (source === from && denied < times) {
341+
denied++
342+
throw Object.assign(new Error(`EPERM: operation not permitted, rename '${source}' -> '${destination}'`), { code: 'EPERM' })
343+
}
344+
return rename(source, destination)
345+
})
346+
}
347+
348+
it('retries a rename that Windows denies for a moment', async () => {
349+
const { root, target, staging } = await createSwapFixture()
350+
denyRenames(staging, 2)
351+
352+
await swapDir(staging, target)
353+
354+
await expect(fsp.readFile(join(target, 'SKILL.md'), 'utf8')).resolves.toBe('new')
355+
expect((await fsp.readdir(root)).sort()).toEqual(['skill'])
356+
await fsp.rm(root, { recursive: true, force: true })
357+
})
358+
359+
it('puts the old tree back when the new one cannot move in', async () => {
360+
const { root, target, staging } = await createSwapFixture()
361+
denyRenames(staging, Number.POSITIVE_INFINITY)
362+
363+
await expect(swapDir(staging, target)).rejects.toMatchObject({ code: 'EPERM' })
364+
365+
await expect(fsp.readFile(join(target, 'SKILL.md'), 'utf8')).resolves.toBe('old')
366+
expect((await fsp.readdir(root)).sort()).toEqual(['skill', 'staging'])
367+
await fsp.rm(root, { recursive: true, force: true })
368+
})
369+
370+
it('keeps the tree another process published while this one was swapping', async () => {
371+
const { root, target, staging } = await createSwapFixture()
372+
const rename = fsp.rename.bind(fsp)
373+
vi.spyOn(fsp, 'rename').mockImplementation(async (source, destination) => {
374+
if (source === staging) {
375+
await fsp.mkdir(target, { recursive: true })
376+
await fsp.writeFile(join(target, 'SKILL.md'), 'other')
377+
throw Object.assign(new Error('EPERM'), { code: 'EPERM' })
378+
}
379+
return rename(source, destination)
380+
})
381+
382+
await swapDir(staging, target)
383+
384+
await expect(fsp.readFile(join(target, 'SKILL.md'), 'utf8')).resolves.toBe('other')
385+
expect((await fsp.readdir(root)).sort()).toEqual(['skill', 'staging'])
386+
await fsp.rm(root, { recursive: true, force: true })
387+
})
388+
389+
it('gives each run its own staging path and removes ones left by dead runs', async () => {
390+
const root = await fsp.mkdtemp(join(tmpdir(), 'skill-hub-staging-'))
391+
const target = join(root, 'skill')
392+
const live = `${target}.staging-${process.pid}-live`
393+
await fsp.mkdir(live)
394+
await fsp.mkdir(`${target}.staging`)
395+
await fsp.mkdir(`${target}.staging-2147483646-dead`)
396+
397+
const first = await createStagingPath(target)
398+
const second = await createStagingPath(target)
399+
400+
expect(first).not.toBe(second)
401+
expect(first.startsWith(`${target}.staging-${process.pid}-`)).toBe(true)
402+
expect(await fsp.readdir(root)).toEqual([`skill.staging-${process.pid}-live`])
403+
await fsp.rm(root, { recursive: true, force: true })
404+
})
319405
})

‎test/publish-skill.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,24 @@ describe('publishSkill', () => {
3939
expect(execSync('git status --porcelain', { cwd: root, encoding: 'utf8' }).trim()).toBe('?? .gitignore')
4040
})
4141

42+
it('leaves an up-to-date copy in place and replaces it after a new generation', async () => {
43+
const writeState = (generatedAt: string) => fsp.writeFile(
44+
join(generatedSkillRoot, '.state.json'),
45+
JSON.stringify({ fingerprint: 'abc', generatedAt, packageVersion: '0.0.0' }),
46+
)
47+
const skillRoot = join(root, '.claude/skills/nuxt-app')
48+
await writeState('2026-01-01T00:00:00.000Z')
49+
await publish(['claude-code'])
50+
await fsp.writeFile(join(skillRoot, 'marker'), '')
51+
52+
await publish(['claude-code'])
53+
await expect(fsp.access(join(skillRoot, 'marker'))).resolves.toBeUndefined()
54+
55+
await writeState('2026-01-02T00:00:00.000Z')
56+
await publish(['claude-code'])
57+
await expect(fsp.access(join(skillRoot, 'marker'))).rejects.toBeDefined()
58+
})
59+
4260
it('writes one pointer file for agents that load a rules directory', async () => {
4361
await publish(['windsurf'])
4462

0 commit comments

Comments
 (0)