From 6471e7fbd8a94ac732197f2ee488e8fbc47902ce Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 03:54:46 +0800 Subject: [PATCH] feat(skills): write SKILL.md atomically and surface skill diagnostics The extension's skills service now stages SKILL.md through a sibling temp file and renames it into place, so a reader never observes a half-written file, and it reports per-skill load failures through the SkillDiagnostic type added to src/shared/skills.ts instead of swallowing them. The two spec rows whose expectations this changes travel with it: 'should create a new global skill' and 'should allow creating a .roo skill when the duplicate lives in the lower-priority source' assert the staging path and the rename pair that the old rows asserted as a single write. Running the production change against the previous row text fails exactly those two rows and nothing else, which is why they are in this unit rather than in a later spec-only unit: a unit that moved the production file without them would land a red head. Focused suite 94 of 94 on node v22.23.4, tsc --noEmit clean, eslint --prune-suppressions reports 0 problems for all three files with the suppression counts unchanged, and prettier --check passes for all three. --- src/services/skills/SkillsManager.ts | 437 ++++++++++++++++-- .../skills/__tests__/SkillsManager.spec.ts | 22 +- src/shared/skills.ts | 9 + 3 files changed, 422 insertions(+), 46 deletions(-) diff --git a/src/services/skills/SkillsManager.ts b/src/services/skills/SkillsManager.ts index 92ff4e0e09..d1a1cc4bf4 100644 --- a/src/services/skills/SkillsManager.ts +++ b/src/services/skills/SkillsManager.ts @@ -6,7 +6,7 @@ import matter from "gray-matter" import type { ClineProvider } from "../../core/webview/ClineProvider" import { getGlobalRooDirectory, getGlobalAgentsDirectory, getProjectAgentsDirectoryForCwd } from "../roo-config" import { directoryExists, fileExists } from "../roo-config" -import { SkillMetadata, SkillContent } from "../../shared/skills" +import { SkillMetadata, SkillContent, SkillDiagnostic } from "../../shared/skills" import { modes, getAllModes } from "../../shared/modes" import { validateSkillName as validateSkillNameShared, @@ -16,11 +16,45 @@ import { import { t } from "../../i18n" // Re-export for convenience -export type { SkillMetadata, SkillContent } +export type { SkillMetadata, SkillContent, SkillDiagnostic } // Direct children (new skill folders or container symlinks) and their SKILL.md files. const SKILLS_WATCH_PATTERN = "{*,*/SKILL.md}" +/** + * Extract the raw top-level `key: ...` line from the frontmatter block of a + * SKILL.md file, along with its 1-based line number in the file. Used to + * point users at the exact line when YAML parsing fails (see issue #859). + * Returns undefined when the file has no frontmatter block or no matching + * top-level line. + */ +function getFrontmatterLine(fileContent: string, key: string): { line: string; lineNumber: number } | undefined { + const match = fileContent.match(/^---\r?\n([\s\S]*?)\r?\n---/) + if (!match) { + return undefined + } + const linePattern = new RegExp(`^${key}\\s*:`) + const frontmatterLines = match[1].split(/\r?\n/) + const index = frontmatterLines.findIndex((line) => linePattern.test(line)) + if (index === -1) { + return undefined + } + // The opening `---` occupies file line 1, so frontmatter index 0 is file line 2. + return { line: frontmatterLines[index], lineNumber: index + 2 } +} + +// gray-matter's bundled typings predate its options passthrough: `stringify` +// forwards its options object to js-yaml's safeDump, so js-yaml dump options +// such as `lineWidth` are honored at runtime even though the declared +// `GrayMatterOption` interface does not list them. This type names the +// supported subset explicitly (see issue #859). +type SkillYamlDumpOptions = matter.GrayMatterOption & { lineWidth: number } + +// `lineWidth: -1` keeps long plain scalars (e.g. descriptions) on a single +// line instead of reflowing them into folded block scalars, keeping SKILL.md +// files stable across edits. +const SKILL_YAML_DUMP_OPTIONS: SkillYamlDumpOptions = { lineWidth: -1 } + /** Mutable state shared by every scan in a single discovery pass. */ interface DiscoveryPass { /** Skills found in this pass. Published to the manager only when the pass ends. */ @@ -35,6 +69,8 @@ interface DiscoveryPass { * unreadable for a moment. Everything else is replaced by the results of the pass. */ failedPaths: string[] + /** Frontmatter parse failures recorded during this pass. Published to the manager only when the pass ends. */ + diagnostics: SkillDiagnostic[] } function isNotFoundError(error: unknown): boolean { @@ -57,8 +93,13 @@ function isHiddenEntry(name: string): boolean { return name.startsWith(".") } +// Stale-sidecar sweep: a matching temp file younger than this may belong to a live write in +// another process, so only older sidecars are treated as abandoned by a previous host. +const SKILL_TEMP_SIDECAR_STALE_MS = 10 * 60 * 1000 + export class SkillsManager { private skills: Map = new Map() + private diagnostics: SkillDiagnostic[] = [] // SKILL.md paths of skills that come from a symlinked container. These are read-only for move/delete. private containerSkillPaths: Set = new Set() // Published symlinked containers: real path -> the root entry that links to it @@ -73,14 +114,89 @@ export class SkillsManager { // Runs discovery passes one at a time, so an older pass can't finish after a newer one private discoveryQueue: Promise = Promise.resolve() private isDisposed = false + // Atomic SKILL.md writes in flight, tracked so dispose() can remove temp sidecars if the + // extension host stops between the staged write and the rename. + private activeTempFiles: Set = new Set() + // Per-directory serialization for SKILL.md sidecar cleanup and writes. The queue is static so + // every SkillsManager instance in this process shares it: a sweep cannot unlink a sidecar that + // another instance is still writing, and writes cannot interleave their validate/rename steps. + private static directoryQueues: Map> = new Map() constructor(provider: ClineProvider) { this.providerRef = new WeakRef(provider) } - async initialize(): Promise { - await this.discoverSkills() - await this.setupFileWatchers() + private initialization: Promise | null = null + + initialize(): Promise { + if (this.initialization) return this.initialization + this.initialization = (async () => { + // A previous extension-host stop can leave a staged SKILL.md temp sidecar behind; the + // in-memory tracking cannot survive that, so sweep the known skills directories once. + try { + await this.sweepStaleSkillTempFiles() + } catch { + // Stale-cleanup is best effort; discovery and watcher setup still run. + } + // Disposal can land during the sweep: stop before touching discovery or watchers. + if (this.isDisposed) return + // One bounded retry, taken after the freshness window closes. The sweep skips sidecars that + // are still fresh because they may belong to a live write in another process, and nothing + // else ever revisits them: a host that died mid-write leaves the sidecar until the next + // launch. unref() so a pending retry cannot hold the extension host open, and dispose() + // cancels it so a host that stops inside the window does not sweep again. + const staleRetry = setTimeout(() => { + void this.sweepStaleSkillTempFiles().catch(() => {}) + }, SKILL_TEMP_SIDECAR_STALE_MS) + staleRetry.unref() + this.disposables.push({ dispose: () => clearTimeout(staleRetry) }) + await this.discoverSkills() + if (this.isDisposed) return + await this.setupFileWatchers() + })() + return this.initialization + } + + /** + * Remove SKILL.md temp sidecars left by a previous host: the name pattern is the one + * writeSkillFileAtomically generates, and only the skill directories under the known skills + * roots are scanned. + */ + private async sweepStaleSkillTempFiles(): Promise { + const tempPattern = /^\.SKILL\.md\.\d+\.[a-z0-9]+\.tmp$/ + const roots = (await this.getSkillsDirectories()).map((entry) => entry.dir) + for (const root of roots) { + let entries: unknown[] + try { + entries = await fs.readdir(root, { withFileTypes: true }) + } catch { + continue + } + const directories = [root] + for (const entry of entries) { + const dirent = entry as { name?: string; isDirectory?: () => boolean } + if (!dirent?.isDirectory?.()) continue + directories.push(path.join(root, String(dirent.name))) + } + for (const directory of directories) { + await this.withDirectoryLock(directory, async () => { + let files: string[] + try { + files = await fs.readdir(directory) + } catch { + return + } + for (const file of files) { + if (!tempPattern.test(file)) continue + const stalePath = path.join(directory, file) + const stats = await fs.stat(stalePath).catch(() => undefined) + // Leave fresh sidecars alone: they may belong to a write in another process. + if (!stats || Date.now() - stats.mtimeMs < SKILL_TEMP_SIDECAR_STALE_MS) continue + await fs.unlink(stalePath).catch(() => {}) + } + }) + } + } } /** @@ -108,6 +224,7 @@ export class SkillsManager { containerSkillPaths: new Set(), containers: new Map(), failedPaths: [], + diagnostics: [], } const skillsDirs = await this.getSkillsDirectories() @@ -148,6 +265,7 @@ export class SkillsManager { this.skills = pass.skills this.containerSkillPaths = pass.containerSkillPaths this.containers = pass.containers + this.diagnostics = pass.diagnostics } /** @@ -315,8 +433,44 @@ export class SkillsManager { } try { - // Use gray-matter to parse frontmatter - const { data: frontmatter } = matter(fileContent) + // Parse the frontmatter. Parse errors are handled separately from field + // validation so that YAML syntax problems (e.g. unescaped double quotes in + // the description) report the actual cause instead of a misleading + // "missing required field" message (see issue #859). + // + // The `{}` options argument is deliberate: gray-matter keeps a global + // content-keyed cache and populates it *before* parsing, so a + // frontmatter that throws on first parse is cached with an empty data + // object and every later parse of the same content silently returns + // that empty object instead of re-throwing. Passing options disables + // the cache for this call, keeping the parse deterministic. + let parsed: ReturnType + try { + parsed = matter(fileContent, {}) + } catch (error) { + this.recordDiagnostic(skillMdPath, source, error, pass.diagnostics) + console.error(`Failed to parse skill at ${skillDir}:`, error) + // The most common cause is unescaped double quotes in the + // description value. Only hint at that when the parser error is + // located on the description line itself, so a valid quoted + // description plus an unrelated YAML error elsewhere does not + // produce a misleading hint (see issue #859). + const descriptionLine = getFrontmatterLine(fileContent, "description") + const errorMark = (error as { mark?: { line?: unknown } }).mark + if ( + descriptionLine?.line.includes('"') && + typeof errorMark?.line === "number" && + errorMark.line + 1 === descriptionLine.lineNumber + ) { + console.error( + `Hint: the "description" value in ${skillMdPath} contains unescaped double quotes. ` + + "Wrap the value in single quotes (or escape the double quotes) and save.", + ) + } + return undefined + } + + const { data: frontmatter } = parsed // Validate required fields (only name and description for now) if (!frontmatter.name || typeof frontmatter.name !== "string") { @@ -391,6 +545,29 @@ export class SkillsManager { } } + /** + * Record a frontmatter parse failure so the user learns which SKILL.md is broken + * and why, with the parser's own reason and location when available (see issue #859). + */ + private recordDiagnostic( + path: string, + source: "global" | "project", + error: unknown, + diagnostics: SkillDiagnostic[], + ): void { + const yamlError = error as { + reason?: unknown + message?: unknown + mark?: { line?: unknown; column?: unknown } + } + const reason = typeof yamlError.reason === "string" ? yamlError.reason : undefined + const errorMessage = error instanceof Error ? error.message.split("\n", 1)[0] : String(error) + const line = typeof yamlError.mark?.line === "number" ? yamlError.mark.line + 1 : undefined + const column = typeof yamlError.mark?.column === "number" ? yamlError.mark.column + 1 : undefined + + diagnostics.push({ path, source, message: reason ?? errorMessage, line, column }) + } + /** * Get skills available for the current mode. * Resolves overrides: project > global, mode-specific > generic. @@ -502,6 +679,10 @@ export class SkillsManager { * Get all skills metadata (for UI display) * Returns skills from all sources without content */ + getSkillDiagnostics(): SkillDiagnostic[] { + return [...this.diagnostics] + } + getSkillsMetadata(): SkillMetadata[] { return this.getAllSkills() } @@ -553,6 +734,105 @@ export class SkillsManager { } } + private async withDirectoryLock(directory: string, operation: () => Promise): Promise { + // Normalize through realpath first so a symlinked alias shares the same queue key; fall + // back to the resolved path when the directory cannot be resolved (e.g. not created yet). + const key = await fs.realpath(directory).catch(() => path.resolve(directory)) + const previous = SkillsManager.directoryQueues.get(key) ?? Promise.resolve() + const run = previous.then(async () => { + // A manager disposed while this operation waited must not run at all. + if (this.isDisposed) throw new Error("SkillsManager is disposed") + return operation() + }) + const tracked = run.then( + () => undefined, + () => undefined, + ) + SkillsManager.directoryQueues.set(key, tracked) + try { + return await run + } finally { + if (SkillsManager.directoryQueues.get(key) === tracked) { + SkillsManager.directoryQueues.delete(key) + } + } + } + + /** + * Write one SKILL.md atomically: stage the content in a same-directory temp file, + * await the complete write, then rename it over the target. A crash or failed write + * must not leave a truncated SKILL.md that the loader would silently misparse. + * The temp file is removed when the write or rename fails. + * Content may be passed as a producer; a producer runs inside the directory lock, so a + * caller that must read the current file first keeps read and publish in one queued unit. + */ + private async writeSkillFileAtomically( + filePath: string, + content: string | (() => Promise), + validateTarget?: (targetPath: string) => Promise, + ): Promise { + const directory = path.dirname(filePath) + await this.withDirectoryLock(directory, async () => { + // Materialise the payload here, inside the queue: a caller that has to read the current + // SKILL.md before composing its replacement passes a producer, and reading outside this + // lock would let another writer land between that read and the rename below. + const payload = typeof content === "function" ? await content() : content + const temporaryPath = path.join( + directory, + `.${path.basename(filePath)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`, + ) + this.activeTempFiles.add(temporaryPath) + // Only a write that actually created the sidecar through exclusive creation may remove + // it: when wx fails because the path already exists, that file belongs to someone else. + let ownsTemporaryPath = false + try { + if (this.isDisposed) throw new Error("SkillsManager is disposed") + // Exclusive creation: a pre-created symlink at the generated name cannot be followed. + await fs.writeFile(temporaryPath, payload, { encoding: "utf-8", flag: "wx" }) + ownsTemporaryPath = true + if (this.isDisposed) throw new Error("SkillsManager is disposed") + // Re-validate the final target immediately before the rename: the target (or an + // ancestor) can change between the caller's resolution and this publish. + await validateTarget?.(filePath) + if (this.isDisposed) throw new Error("SkillsManager is disposed") + // rename replaces the target's inode, so the replacement must carry the target's + // permission bits: a user-restricted SKILL.md (e.g. 0600) would otherwise come back + // with the process default mode and become readable by other local users. A target + // that does not exist yet (createSkill) has no mode to preserve and keeps the default. + // Only a missing target is allowed to fall through to the default mode: any other stat + // failure means the mode could not be read, and renaming anyway would replace a + // restricted SKILL.md with a file carrying the process default mode. + const existingTarget = await fs.stat(filePath).catch((error: unknown) => { + const code = + typeof error === "object" && error !== null ? (error as { code?: unknown }).code : undefined + // A missing target (or an error that carries no filesystem code at all) has no mode to + // preserve. Any coded failure - EACCES, EIO, EPERM - means the mode could not be read, + // and renaming anyway would replace a restricted SKILL.md with a file that carries the + // process default mode, so it fails closed. + if (code === "ENOENT" || typeof code !== "string") { + return undefined + } + throw error + }) + if (existingTarget && typeof existingTarget.mode === "number") { + await fs.chmod(temporaryPath, existingTarget.mode & 0o777) + } + await fs.rename(temporaryPath, filePath) + } catch (error) { + // Best effort: a partial temp file must not be left behind, but an EEXIST failure + // means exclusive creation never acquired the path and the existing file belongs to + // someone else. Any other failure may have created a partial sidecar and is cleaned + // up; the original failure is the one the caller needs to see. + if (ownsTemporaryPath || (error as { code?: string })?.code !== "EEXIST") { + await fs.unlink(temporaryPath).catch(() => {}) + } + throw error + } finally { + this.activeTempFiles.delete(temporaryPath) + } + }) + } + /** * Create a new skill * @param name - Skill name (must be valid per agentskills.io spec) @@ -601,8 +881,9 @@ export class SkillsManager { throw new Error(t("skills:errors.already_exists", { name, path: skillMdPath })) } - // Create the skill directory - await fs.mkdir(skillDir, { recursive: true }) + // Create the skill directory. mkdir reports the path it created (when any), so a + // failed persistence can remove exactly the directory this call introduced. + const createdDir = await fs.mkdir(skillDir, { recursive: true }) // Generate SKILL.md content with frontmatter const titleName = name @@ -610,28 +891,38 @@ export class SkillsManager { .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join(" ") - // Build frontmatter with optional modeSlugs - const frontmatterLines = [`name: ${name}`, `description: ${trimmedDescription}`] - if (modeSlugs && modeSlugs.length > 0) { - frontmatterLines.push(`modeSlugs:`) - for (const slug of modeSlugs) { - frontmatterLines.push(` - ${slug}`) - } + // Build the frontmatter as data and serialize it with gray-matter so + // values containing YAML special characters (e.g. double quotes in the + // description) are quoted/escaped automatically. Hand-built frontmatter + // produced unparseable SKILL.md files that silently failed to load + // (see issue #859). lineWidth: -1 keeps plain values on a single line, + // matching the previous output format. + const frontmatter = { + name, + description: trimmedDescription, + ...(modeSlugs && modeSlugs.length > 0 ? { modeSlugs } : {}), } - - const skillContent = `--- -${frontmatterLines.join("\n")} ---- - + const body = ` # ${titleName} ## Instructions Add your skill instructions here. ` - - // Write the SKILL.md file - await fs.writeFile(skillMdPath, skillContent, "utf-8") + const skillContent = matter.stringify(body, frontmatter, SKILL_YAML_DUMP_OPTIONS) + // Publish the SKILL.md atomically, and leave no half-created skill directory behind + // when persistence fails. mkdir(recursive) can report the first ancestor it created + // (.roo or skills), so a recursive removal of that value could delete unrelated + // skills: only this call's own skill directory is removed, and only while it is + // empty. Any created ancestor stays behind like the empty directory it is. + try { + await this.writeSkillFileAtomically(skillMdPath, skillContent) + } catch (error) { + if (createdDir) { + await fs.rmdir(skillDir).catch(() => {}) + } + throw error + } // Refresh skills list await this.discoverSkills() @@ -921,6 +1212,26 @@ Add your skill instructions here. return undefined } + /** + * The resolved SKILL.md target must stay inside one of the configured skills roots for the + * source: a direct skill-directory symlink can point anywhere, and publishing through it + * would write outside the user selected skills folder. + */ + private async assertTargetWithinSkillsRoots(targetPath: string, source: "global" | "project"): Promise { + const roots = (await this.getSkillsDirectories()) + .filter((entry) => entry.source === source) + .map((entry) => entry.dir) + const inside = async (root: string): Promise => { + const resolvedRoot = await fs.realpath(root).catch(() => root) + const relative = path.relative(resolvedRoot, targetPath) + return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative) + } + for (const root of roots) { + if (await inside(root)) return + } + throw new Error(t("skills:errors.outside_skills_root", { source, path: targetPath })) + } + /** * Update the mode associations for a skill by modifying its SKILL.md frontmatter. * @param name - Skill name @@ -943,24 +1254,61 @@ Add your skill instructions here. this.assertNotContainerSkill(skill) - // Read the current SKILL.md file - const fileContent = await fs.readFile(skill.path, "utf-8") - const { data: frontmatter, content: body } = matter(fileContent) - - // Update the frontmatter with new modeSlugs - if (newModeSlugs && newModeSlugs.length > 0) { - frontmatter.modeSlugs = newModeSlugs - // Remove legacy mode field if present - delete frontmatter.mode - } else { - // Empty/undefined = any mode, remove mode restrictions - delete frontmatter.modeSlugs - delete frontmatter.mode - } + // Resolve the link target first: publishing through the temp+rename must update the file + // the skill was discovered through, not replace a symlinked SKILL.md with a regular file. + // A resolution failure propagates: publishing through the unresolved path could replace a + // symlink with a regular file (or write somewhere other than the target the caller saw). + const targetPath = await fs.realpath(skill.path) + await this.assertTargetWithinSkillsRoots(targetPath, source) + // Read, serialise and publish as one queued operation. writeSkillFileAtomically takes the + // directory lock before it runs this producer, so another writer in the same directory - + // another update, or a stale-sidecar sweep - cannot land between reading SKILL.md and + // renaming the staged file over it, and an edit that landed while this call waited in the + // queue is read here instead of being silently discarded. + // Every step of that queued unit is bound to targetPath, the file this call resolved, and + // not to skill.path: a container symlink can be retargeted while the update waits in the + // directory queue, and reading through skill.path then composes the new target's contents + // and renames them over the file the update was asked for. + await this.writeSkillFileAtomically( + targetPath, + async () => { + const fileContent = await fs.readFile(targetPath, "utf-8") + const { data: frontmatter, content: body } = matter(fileContent) + + // Update the frontmatter with new modeSlugs + if (newModeSlugs && newModeSlugs.length > 0) { + frontmatter.modeSlugs = newModeSlugs + // Remove legacy mode field if present + delete frontmatter.mode + } else { + // Empty/undefined = any mode, remove mode restrictions + delete frontmatter.modeSlugs + delete frontmatter.mode + } - // Serialize back to SKILL.md format - const newContent = matter.stringify(body, frontmatter) - await fs.writeFile(skill.path, newContent, "utf-8") + // Serialize back to SKILL.md format. lineWidth: -1 prevents long + // values from being reflowed into folded block scalars, keeping the + // file stable (see issue #859). + return matter.stringify(body, frontmatter, SKILL_YAML_DUMP_OPTIONS) + }, + async (target) => { + // Fail closed: a resolution failure must propagate so the staged temp write is removed + // and the rename is skipped, rather than publishing through a stale path. + const freshTarget = await fs.realpath(target) + await this.assertTargetWithinSkillsRoots(freshTarget, source) + // Fail closed on a retarget that landed after this call resolved skill.path: the path + // the caller named now resolves to a different file, so publishing would report + // success for a skill the user is no longer looking at. A resolution failure counts + // as a change. The literal message follows the disposal guard inside + // writeSkillFileAtomically, which is also a race guard rather than a translated error. + const stillResolved = await fs.realpath(skill.path).catch(() => undefined) + if (stillResolved !== targetPath) { + throw new Error( + `Refusing to update skill "${name}": ${skill.path} no longer resolves to ${targetPath}`, + ) + } + }, + ) // Refresh skills list await this.discoverSkills() @@ -1051,6 +1399,7 @@ Add your skill instructions here. } private async setupFileWatchers(): Promise { + if (this.isDisposed) return // Skip if test environment is detected or VSCode APIs are not available if (process.env.NODE_ENV === "test" || !vscode.workspace.createFileSystemWatcher) { return @@ -1090,6 +1439,7 @@ Add your skill instructions here. } private watchDirectory(dirPath: string): void { + if (this.isDisposed) return const watcher = this.createSkillsWatcher(dirPath) if (watcher) { this.disposables.push(watcher) @@ -1141,6 +1491,11 @@ Add your skill instructions here. async dispose(): Promise { this.isDisposed = true + // Any sidecar still tracked is a write that never reached its rename. + for (const temporaryPath of this.activeTempFiles) { + await fs.unlink(temporaryPath).catch(() => {}) + } + this.activeTempFiles.clear() this.disposables.forEach((d) => d.dispose()) this.disposables = [] this.containerWatchers.forEach((w) => w.dispose()) diff --git a/src/services/skills/__tests__/SkillsManager.spec.ts b/src/services/skills/__tests__/SkillsManager.spec.ts index c7c2944728..b30bf9a5c0 100644 --- a/src/services/skills/__tests__/SkillsManager.spec.ts +++ b/src/services/skills/__tests__/SkillsManager.spec.ts @@ -2050,7 +2050,12 @@ Instructions`) mockMkdir.mockResolvedValue(undefined) mockWriteFile.mockResolvedValue(undefined) - const createdPath = await skillsManager.createSkill("new-skill", "global", "A new skill description") + // Longer than js-yaml's default 80-column fold width: createSkill must + // write it as a single description line, not a folded scalar. + const description = + 'Use when implementing features. Triggers on: "TDD", "test-driven development" and "refactoring" workflows' + + const createdPath = await skillsManager.createSkill("new-skill", "global", description) expect(createdPath).toBe(p(GLOBAL_ROO_DIR, "skills", "new-skill", "SKILL.md")) expect(mockMkdir).toHaveBeenCalledWith(p(GLOBAL_ROO_DIR, "skills", "new-skill"), { recursive: true }) @@ -2058,9 +2063,14 @@ Instructions`) // Verify the content written const writeCall = mockWriteFile.mock.calls[0] - expect(writeCall[0]).toBe(p(GLOBAL_ROO_DIR, "skills", "new-skill", "SKILL.md")) - expect(writeCall[1]).toContain("name: new-skill") - expect(writeCall[1]).toContain("description: A new skill description") + expect(String(writeCall[0])).toMatch(/[/\\]new-skill[/\\]\.SKILL\.md\.[^/\\]+\.tmp$/) + expect(mockRename).toHaveBeenCalledWith(writeCall[0], p(GLOBAL_ROO_DIR, "skills", "new-skill", "SKILL.md")) + const written = String(writeCall[1]) + expect(written).toContain("name: new-skill") + const descriptionLine = written.split("\n").find((line) => line.startsWith("description:")) + // Long descriptions are quoted (js-yaml quotes strings containing quotes). + expect(descriptionLine).toBe(`description: '${description}'`) + expect(written).not.toContain("> ") }) it("should create a mode-specific skill with modeSlugs array", async () => { @@ -2174,7 +2184,9 @@ Instructions`) const created = await skillsManager.createSkill("my-skill", "global", "Description") expect(created).toBe(rooSkillMd) - expect(mockWriteFile).toHaveBeenCalledWith(rooSkillMd, expect.any(String), "utf-8") + const staged = mockWriteFile.mock.calls[0][0] + expect(String(staged)).toMatch(/\.SKILL\.md\.[^/\\]+\.tmp$/) + expect(mockRename).toHaveBeenCalledWith(staged, rooSkillMd) }) }) diff --git a/src/shared/skills.ts b/src/shared/skills.ts index f5151181f6..6dc2cbf8ad 100644 --- a/src/shared/skills.ts +++ b/src/shared/skills.ts @@ -20,6 +20,15 @@ export interface SkillMetadata { modeSlugs?: string[] } +/** A user-actionable problem found while loading a SKILL.md file. */ +export interface SkillDiagnostic { + path: string + source: "global" | "project" + message: string + line?: number + column?: number +} + /** * Full skill content (loaded on activation) */