Skip to content

Commit 17b2689

Browse files
fix(skills): bind a queued SKILL.md update to the target it resolved, and pin the sweep retry
The update path resolved skill.path once and then read through skill.path inside the directory queue, so a container symlink retargeted while an update waited composed the new target's contents and renamed them over the file the update was asked for. The queued producer now reads targetPath, and the pre-rename validation rejects the update when the path the caller named no longer resolves to it. Tests: pin the retarget window end to end, give the queued double-update test two distinguishable reads so a discarded read cannot pass, and add timer tests for the delayed stale-sidecar sweep and for disposal cancelling it.
1 parent 9714d1f commit 17b2689

2 files changed

Lines changed: 137 additions & 2 deletions

File tree

‎src/services/skills/SkillsManager.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1265,10 +1265,14 @@ Add your skill instructions here.
12651265
// another update, or a stale-sidecar sweep - cannot land between reading SKILL.md and
12661266
// renaming the staged file over it, and an edit that landed while this call waited in the
12671267
// queue is read here instead of being silently discarded.
1268+
// Every step of that queued unit is bound to targetPath, the file this call resolved, and
1269+
// not to skill.path: a container symlink can be retargeted while the update waits in the
1270+
// directory queue, and reading through skill.path then composes the new target's contents
1271+
// and renames them over the file the update was asked for.
12681272
await this.writeSkillFileAtomically(
12691273
targetPath,
12701274
async () => {
1271-
const fileContent = await fs.readFile(skill.path, "utf-8")
1275+
const fileContent = await fs.readFile(targetPath, "utf-8")
12721276
const { data: frontmatter, content: body } = matter(fileContent)
12731277

12741278
// Update the frontmatter with new modeSlugs
@@ -1292,6 +1296,17 @@ Add your skill instructions here.
12921296
// and the rename is skipped, rather than publishing through a stale path.
12931297
const freshTarget = await fs.realpath(target)
12941298
await this.assertTargetWithinSkillsRoots(freshTarget, source)
1299+
// Fail closed on a retarget that landed after this call resolved skill.path: the path
1300+
// the caller named now resolves to a different file, so publishing would report
1301+
// success for a skill the user is no longer looking at. A resolution failure counts
1302+
// as a change. The literal message follows the disposal guard inside
1303+
// writeSkillFileAtomically, which is also a race guard rather than a translated error.
1304+
const stillResolved = await fs.realpath(skill.path).catch(() => undefined)
1305+
if (stillResolved !== targetPath) {
1306+
throw new Error(
1307+
`Refusing to update skill "${name}": ${skill.path} no longer resolves to ${targetPath}`,
1308+
)
1309+
}
12951310
},
12961311
)
12971312

‎src/services/skills/__tests__/SkillsManager.spec.ts‎

Lines changed: 121 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2717,15 +2717,27 @@ Body.`
27172717
// Discovery is finished reading: from here every read of this SKILL.md belongs to an
27182718
// update, so the recorded order is the write path's own.
27192719
mockDirectoryExists.mockResolvedValue(false)
2720+
// What SKILL.md holds right now. A rename publishes what that update staged, so from the
2721+
// first rename on the file no longer holds the text the first update read. Returning one
2722+
// constant for both reads let a producer whose queued read was discarded look correct,
2723+
// because nothing distinguished the two reads.
2724+
let diskContent = skillContent
2725+
const editedContent =
2726+
"---\nname: queue-order\ndescription: A skill\nmodeSlugs:\n - code\n---\nInstructions edited after the first rename"
2727+
const stagedPayloads: string[] = []
27202728
mockReadFile.mockImplementation(async (file: string) => {
27212729
if (file === skillMd) {
27222730
events.push("read")
27232731
}
2724-
return skillContent
2732+
return diskContent
2733+
})
2734+
mockWriteFile.mockImplementation(async (_file: string, payload: string) => {
2735+
stagedPayloads.push(payload)
27252736
})
27262737
mockRename.mockImplementation(async (_from: string, to: string) => {
27272738
if (to === skillMd) {
27282739
events.push("rename")
2740+
diskContent = editedContent
27292741
}
27302742
})
27312743

@@ -2736,6 +2748,68 @@ Body.`
27362748
// Each update reads and publishes before the next update reads.
27372749
expect(events).toEqual(["read", "rename", "read", "rename"])
27382750
expect(mockRename).toHaveBeenCalledTimes(2)
2751+
expect(stagedPayloads.length).toBe(2)
2752+
// The second update's staged payload carries the body that follows the first rename: an
2753+
// update whose queued read was discarded would republish the body the first update read.
2754+
expect(stagedPayloads[0]).not.toContain("edited after the first rename")
2755+
expect(stagedPayloads[1]).toContain("edited after the first rename")
2756+
})
2757+
2758+
it("binds the queued read and the publish to the target resolved before the queue", async () => {
2759+
// The path discovery saw is a link whose resolution this update must keep. The retarget
2760+
// lands after this call resolved the link and while it waits in the directory queue,
2761+
// which is the window where reading through the link would compose the new target's
2762+
// contents and rename them over the file the update was asked for.
2763+
const skillDir = p(globalSkillsDir, "retargeted")
2764+
const linkMd = p(skillDir, "SKILL.md")
2765+
const originalTarget = p(globalSkillsDir, "shared-target", "SKILL.md")
2766+
const movedTarget = p(globalSkillsDir, "moved-target", "SKILL.md")
2767+
const originalContent =
2768+
"---\nname: retargeted\ndescription: A skill\n---\nInstructions on the file the update was asked for"
2769+
const movedContent =
2770+
"---\nname: retargeted\ndescription: A skill\n---\nInstructions on the file the link moved to"
2771+
let retargeted = false
2772+
mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir)
2773+
mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["retargeted"] : []))
2774+
mockStat.mockImplementation(async (pathArg: string) => {
2775+
if (pathArg === skillDir) {
2776+
return { isDirectory: () => true }
2777+
}
2778+
throw enoent()
2779+
})
2780+
mockFileExists.mockImplementation(async (file: string) => file === linkMd)
2781+
// Both targets stay inside the skills roots, so the publish-time containment check cannot
2782+
// be what rejects this update.
2783+
mockRealpath.mockImplementation(async (pathArg: string) => {
2784+
if (pathArg === linkMd) {
2785+
return retargeted ? movedTarget : originalTarget
2786+
}
2787+
return pathArg
2788+
})
2789+
mockReadFile.mockImplementation(async (file: string) => {
2790+
if (file === originalTarget) {
2791+
// The queued read is the moment the retarget becomes visible.
2792+
retargeted = true
2793+
return originalContent
2794+
}
2795+
return file === linkMd || file === movedTarget ? movedContent : originalContent
2796+
})
2797+
mockWriteFile.mockResolvedValue(undefined)
2798+
mockUnlink.mockResolvedValue(undefined)
2799+
mockRename.mockResolvedValue(undefined)
2800+
2801+
await skillsManager.discoverSkills()
2802+
2803+
await expect(skillsManager.updateSkillModes("retargeted", "global", ["code"])).rejects.toThrow(
2804+
"no longer resolves to",
2805+
)
2806+
// Discovery read through the link; every read that belongs to the update read the target.
2807+
expect(mockReadFile.mock.calls.filter((call: unknown[]) => call[0] === linkMd).length).toBe(1)
2808+
expect(mockReadFile.mock.calls.some((call: unknown[]) => call[0] === originalTarget)).toBe(true)
2809+
// The payload was composed from the original target, and nothing was renamed over it.
2810+
expect(String(mockWriteFile.mock.calls[0][1])).toContain("the file the update was asked for")
2811+
expect(mockRename).not.toHaveBeenCalled()
2812+
expect(mockUnlink).toHaveBeenCalledWith(String(mockWriteFile.mock.calls[0][0]))
27392813
})
27402814

27412815
it("fails closed when the pre-rename target resolution fails", async () => {
@@ -4256,6 +4330,52 @@ Instructions`)
42564330
expect(mockUnlink).not.toHaveBeenCalledWith(p(globalSkillsDir, freshName))
42574331
})
42584332

4333+
it("revisits fresh sidecars once the delayed sweep fires", async () => {
4334+
// The first sweep skips sidecars younger than the freshness window because they may belong to
4335+
// a live write in another process, and nothing else ever revisits them. The one delayed retry
4336+
// is what does, so both halves are pinned: no second sweep inside the window, one after it.
4337+
vi.useFakeTimers()
4338+
let sweeps = 0
4339+
const originalSweep = skillsManager["sweepStaleSkillTempFiles"]
4340+
skillsManager["sweepStaleSkillTempFiles"] = async () => {
4341+
sweeps += 1
4342+
}
4343+
try {
4344+
await skillsManager.initialize()
4345+
expect(sweeps).toBe(1)
4346+
// SKILL_TEMP_SIDECAR_STALE_MS is ten minutes and module-private, so the window is written
4347+
// here and the assertions below pin which side of it fires.
4348+
await vi.advanceTimersByTimeAsync(10 * 60 * 1000 - 1)
4349+
expect(sweeps).toBe(1)
4350+
await vi.advanceTimersByTimeAsync(1)
4351+
expect(sweeps).toBe(2)
4352+
} finally {
4353+
skillsManager["sweepStaleSkillTempFiles"] = originalSweep
4354+
vi.useRealTimers()
4355+
}
4356+
})
4357+
4358+
it("cancels the delayed sweep when disposal lands inside the window", async () => {
4359+
// A host that stops inside the freshness window must not sweep again after it: dispose()
4360+
// clears the retry timer, and without that clear the pending callback would run.
4361+
vi.useFakeTimers()
4362+
let sweeps = 0
4363+
const originalSweep = skillsManager["sweepStaleSkillTempFiles"]
4364+
skillsManager["sweepStaleSkillTempFiles"] = async () => {
4365+
sweeps += 1
4366+
}
4367+
try {
4368+
await skillsManager.initialize()
4369+
expect(sweeps).toBe(1)
4370+
await skillsManager.dispose()
4371+
await vi.advanceTimersByTimeAsync(10 * 60 * 1000 + 1)
4372+
expect(sweeps).toBe(1)
4373+
} finally {
4374+
skillsManager["sweepStaleSkillTempFiles"] = originalSweep
4375+
vi.useRealTimers()
4376+
}
4377+
})
4378+
42594379
it("shares one directory queue across symlink aliases", async () => {
42604380
const order: string[] = []
42614381
let releaseFirst!: () => void

0 commit comments

Comments
 (0)