Skip to content

Commit d0bdecc

Browse files
committed
fix(skills): report YAML frontmatter parse errors and serialize SKILL.md safely
SKILL.md files whose description contains unescaped double quotes failed to parse silently: gray-matter's YAMLException was swallowed by the outer catch and users only saw a misleading "missing required 'name' field" log (issue #859). - Catch gray-matter parse errors separately in loadSkillMetadata and log the actual YAML syntax error, with a hint pointing at unescaped double quotes in the description line - Build createSkill frontmatter as data and serialize via matter.stringify so special characters (double quotes, YAML booleans such as "yes", etc.) are quoted automatically and created skills always load - Pass lineWidth: -1 to the dump options (with a typed alias for gray-matter's outdated options typings) to keep long plain scalars on one line and prevent updateSkillModes rewrites from reflowing values into folded block scalars - Add regression tests covering both the load path (invalid YAML is skipped with the real cause logged, no misleading field error) and the create path (quoted frontmatter round-trips and loads on re-discovery)
1 parent 871bb98 commit d0bdecc

2 files changed

Lines changed: 230 additions & 15 deletions

File tree

‎src/services/skills/SkillsManager.ts‎

Lines changed: 70 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,33 @@ import { t } from "../../i18n"
1818
// Re-export for convenience
1919
export type { SkillMetadata, SkillContent }
2020

21+
/**
22+
* Extract the raw top-level `key: ...` line from the frontmatter block of a
23+
* SKILL.md file. Used to point users at the exact line when YAML parsing
24+
* fails (see issue #859). Returns undefined when the file has no
25+
* frontmatter block or no matching top-level line.
26+
*/
27+
function getRawFrontmatterLine(fileContent: string, key: string): string | undefined {
28+
const match = fileContent.match(/^---\r?\n([\s\S]*?)\r?\n---/)
29+
if (!match) {
30+
return undefined
31+
}
32+
const linePattern = new RegExp(`^${key}\\s*:`)
33+
return match[1].split(/\r?\n/).find((line) => linePattern.test(line))
34+
}
35+
36+
// gray-matter's bundled typings predate its options passthrough: `stringify`
37+
// forwards its options object to js-yaml's safeDump, so js-yaml dump options
38+
// such as `lineWidth` are honored at runtime even though the declared
39+
// `GrayMatterOption` interface does not list them. This type names the
40+
// supported subset explicitly (see issue #859).
41+
type SkillYamlDumpOptions = matter.GrayMatterOption<string, SkillYamlDumpOptions> & { lineWidth: number }
42+
43+
// `lineWidth: -1` keeps long plain scalars (e.g. descriptions) on a single
44+
// line instead of reflowing them into folded block scalars, keeping SKILL.md
45+
// files stable across edits.
46+
const SKILL_YAML_DUMP_OPTIONS: SkillYamlDumpOptions = { lineWidth: -1 }
47+
2148
export class SkillsManager {
2249
private skills: Map<string, SkillMetadata> = new Map()
2350
private providerRef: WeakRef<ClineProvider>
@@ -101,8 +128,31 @@ export class SkillsManager {
101128
try {
102129
const fileContent = await fs.readFile(skillMdPath, "utf-8")
103130

104-
// Use gray-matter to parse frontmatter
105-
const { data: frontmatter, content: body } = matter(fileContent)
131+
// Use gray-matter to parse frontmatter. Parse errors are handled
132+
// separately from field validation so that YAML syntax problems
133+
// (e.g. unescaped double quotes in the description) report the
134+
// actual cause instead of a misleading "missing required field"
135+
// message (see issue #859).
136+
let frontmatter: Record<string, unknown>
137+
let body: string
138+
try {
139+
const parsed = matter(fileContent)
140+
frontmatter = parsed.data
141+
body = parsed.content
142+
} catch (parseError) {
143+
const parseMessage = parseError instanceof Error ? parseError.message : String(parseError)
144+
console.error(`Skill at ${skillDir} has invalid YAML frontmatter and was skipped: ${parseMessage}`)
145+
// The most common cause is unescaped double quotes in the
146+
// description value - point the user at the exact line.
147+
const descriptionLine = getRawFrontmatterLine(fileContent, "description")
148+
if (descriptionLine?.includes('"')) {
149+
console.error(
150+
`Hint: the "description" value in ${skillMdPath} contains unescaped double quotes. ` +
151+
"Wrap the value in single quotes (or escape the double quotes) and save.",
152+
)
153+
}
154+
return
155+
}
106156

107157
// Validate required fields (only name and description for now)
108158
if (!frontmatter.name || typeof frontmatter.name !== "string") {
@@ -394,26 +444,29 @@ export class SkillsManager {
394444
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
395445
.join(" ")
396446

397-
// Build frontmatter with optional modeSlugs
398-
const frontmatterLines = [`name: ${name}`, `description: ${trimmedDescription}`]
447+
// Build the frontmatter as data and serialize it with gray-matter so
448+
// values containing YAML special characters (e.g. double quotes in the
449+
// description) are quoted/escaped automatically. Hand-built frontmatter
450+
// produced unparseable SKILL.md files that then failed to load (see
451+
// issue #859). lineWidth: -1 keeps plain values on a single line, which
452+
// matches the previous output format.
453+
const frontmatterData: Record<string, unknown> = {
454+
name,
455+
description: trimmedDescription,
456+
}
399457
if (modeSlugs && modeSlugs.length > 0) {
400-
frontmatterLines.push(`modeSlugs:`)
401-
for (const slug of modeSlugs) {
402-
frontmatterLines.push(` - ${slug}`)
403-
}
458+
frontmatterData.modeSlugs = modeSlugs
404459
}
405460

406-
const skillContent = `---
407-
${frontmatterLines.join("\n")}
408-
---
409-
410-
# ${titleName}
461+
const skillBody = `# ${titleName}
411462
412463
## Instructions
413464
414465
Add your skill instructions here.
415466
`
416467

468+
const skillContent = matter.stringify(skillBody, frontmatterData, SKILL_YAML_DUMP_OPTIONS)
469+
417470
// Write the SKILL.md file
418471
await fs.writeFile(skillMdPath, skillContent, "utf-8")
419472

@@ -553,8 +606,10 @@ Add your skill instructions here.
553606
delete frontmatter.mode
554607
}
555608

556-
// Serialize back to SKILL.md format
557-
const newContent = matter.stringify(body, frontmatter)
609+
// Serialize back to SKILL.md format. lineWidth: -1 prevents long
610+
// values from being reflowed into folded block scalars, keeping the
611+
// file stable (see issue #859).
612+
const newContent = matter.stringify(body, frontmatter, SKILL_YAML_DUMP_OPTIONS)
558613
await fs.writeFile(skill.path, newContent, "utf-8")
559614

560615
// Refresh skills list

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

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ vi.mock("../../../i18n", () => ({
109109
},
110110
}))
111111

112+
import matter from "gray-matter"
113+
112114
import { SkillsManager } from "../SkillsManager"
113115
import { ClineProvider } from "../../../core/webview/ClineProvider"
114116

@@ -391,6 +393,105 @@ description: Name doesn't match directory
391393
expect(skills).toHaveLength(0)
392394
})
393395

396+
it("should skip skills with invalid YAML frontmatter and log the real cause (issue #859)", async () => {
397+
const badSkillDir = p(globalSkillsDir, "test-skill")
398+
const badSkillMd = p(badSkillDir, "SKILL.md")
399+
400+
mockDirectoryExists.mockImplementation(async (dir: string) => {
401+
return dir === globalSkillsDir
402+
})
403+
mockRealpath.mockImplementation(async (pathArg: string) => pathArg)
404+
mockReaddir.mockImplementation(async (dir: string) => {
405+
return dir === globalSkillsDir ? ["test-skill"] : []
406+
})
407+
mockStat.mockImplementation(async (pathArg: string) => {
408+
if (pathArg === badSkillDir) {
409+
return { isDirectory: () => true }
410+
}
411+
throw new Error("Not found")
412+
})
413+
mockFileExists.mockImplementation(async (file: string) => file === badSkillMd)
414+
mockReadFile.mockImplementation(async (file: string) => {
415+
if (file === badSkillMd) {
416+
return `---
417+
name: test-skill
418+
description: Use when implementing features. Triggers on: "TDD", "test-driven development"
419+
---
420+
421+
# Test Skill
422+
423+
Instructions here.`
424+
}
425+
throw new Error("File not found")
426+
})
427+
428+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
429+
430+
try {
431+
await skillsManager.discoverSkills()
432+
433+
// The skill is skipped...
434+
expect(skillsManager.getAllSkills()).toHaveLength(0)
435+
436+
// ...and the real cause (a YAML syntax error) is reported instead
437+
// of the misleading "missing required 'name' field" message.
438+
const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" "))
439+
expect(logged.some((line) => line.includes("invalid YAML frontmatter"))).toBe(true)
440+
expect(logged.some((line) => line.includes("missing required 'name' field"))).toBe(false)
441+
// The unescaped-double-quotes hint points at the exact problem.
442+
expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(true)
443+
} finally {
444+
consoleErrorSpy.mockRestore()
445+
}
446+
})
447+
448+
it("should log a distinct YAML error for other malformed frontmatter (no quote hint)", async () => {
449+
const badSkillDir = p(globalSkillsDir, "broken-skill")
450+
const badSkillMd = p(badSkillDir, "SKILL.md")
451+
452+
mockDirectoryExists.mockImplementation(async (dir: string) => {
453+
return dir === globalSkillsDir
454+
})
455+
mockRealpath.mockImplementation(async (pathArg: string) => pathArg)
456+
mockReaddir.mockImplementation(async (dir: string) => {
457+
return dir === globalSkillsDir ? ["broken-skill"] : []
458+
})
459+
mockStat.mockImplementation(async (pathArg: string) => {
460+
if (pathArg === badSkillDir) {
461+
return { isDirectory: () => true }
462+
}
463+
throw new Error("Not found")
464+
})
465+
mockFileExists.mockImplementation(async (file: string) => file === badSkillMd)
466+
mockReadFile.mockImplementation(async (file: string) => {
467+
if (file === badSkillMd) {
468+
return `---
469+
name broken-skill
470+
description: Missing colon makes this invalid YAML
471+
---
472+
473+
# Broken skill`
474+
}
475+
throw new Error("File not found")
476+
})
477+
478+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
479+
480+
try {
481+
await skillsManager.discoverSkills()
482+
483+
expect(skillsManager.getAllSkills()).toHaveLength(0)
484+
485+
const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" "))
486+
expect(logged.some((line) => line.includes("invalid YAML frontmatter"))).toBe(true)
487+
// The unescaped-quotes hint only applies when the description line
488+
// actually contains double quotes.
489+
expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(false)
490+
} finally {
491+
consoleErrorSpy.mockRestore()
492+
}
493+
})
494+
394495
it("should skip skills with invalid name formats (spec compliance)", async () => {
395496
const invalidNames = [
396497
"PDF-processing", // uppercase
@@ -1246,6 +1347,65 @@ Instructions`)
12461347
expect(createdPath).toBe(p(PROJECT_DIR, ".roo", "skills", "project-skill", "SKILL.md"))
12471348
})
12481349

1350+
it("should escape double quotes in the description so the created skill loads (issue #859)", async () => {
1351+
mockDirectoryExists.mockResolvedValue(false)
1352+
mockRealpath.mockImplementation(async (p: string) => p)
1353+
mockReaddir.mockResolvedValue([])
1354+
mockFileExists.mockResolvedValue(false)
1355+
mockMkdir.mockResolvedValue(undefined)
1356+
mockWriteFile.mockResolvedValue(undefined)
1357+
1358+
const description = 'Use when implementing features. Triggers on: "TDD", "test-driven development"'
1359+
const createdPath = await skillsManager.createSkill("test-skill", "global", description)
1360+
1361+
// The written frontmatter must be valid YAML that round-trips the
1362+
// description, with the raw value quoted instead of unescaped.
1363+
const writtenContent = String(mockWriteFile.mock.calls[0][1])
1364+
const parsed = matter(writtenContent)
1365+
expect(parsed.data.name).toBe("test-skill")
1366+
expect(parsed.data.description).toBe(description)
1367+
expect(writtenContent).toContain(`description: '${description}'`)
1368+
1369+
// Re-discovery loads the created skill instead of silently skipping it.
1370+
mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir)
1371+
mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["test-skill"] : []))
1372+
mockStat.mockImplementation(async (pathArg: string) => {
1373+
if (pathArg === p(globalSkillsDir, "test-skill")) {
1374+
return { isDirectory: () => true }
1375+
}
1376+
throw new Error("Not found")
1377+
})
1378+
mockFileExists.mockImplementation(async (file: string) => file === createdPath)
1379+
mockReadFile.mockImplementation(async (file: string) =>
1380+
file === createdPath ? writtenContent : Promise.reject(new Error("File not found")),
1381+
)
1382+
1383+
await skillsManager.discoverSkills()
1384+
1385+
const skills = skillsManager.getAllSkills()
1386+
expect(skills).toHaveLength(1)
1387+
expect(skills[0].name).toBe("test-skill")
1388+
expect(skills[0].description).toBe(description)
1389+
})
1390+
1391+
it("should quote descriptions that would otherwise parse as YAML non-strings", async () => {
1392+
mockDirectoryExists.mockResolvedValue(false)
1393+
mockRealpath.mockImplementation(async (p: string) => p)
1394+
mockReaddir.mockResolvedValue([])
1395+
mockFileExists.mockResolvedValue(false)
1396+
mockMkdir.mockResolvedValue(undefined)
1397+
mockWriteFile.mockResolvedValue(undefined)
1398+
1399+
await skillsManager.createSkill("flag-skill", "global", "yes")
1400+
1401+
const writtenContent = String(mockWriteFile.mock.calls[0][1])
1402+
const parsed = matter(writtenContent)
1403+
// Without quoting, js-yaml resolves "yes" to a boolean and the skill
1404+
// is rejected with a misleading "missing required 'description' field".
1405+
expect(typeof parsed.data.description).toBe("string")
1406+
expect(parsed.data.description).toBe("yes")
1407+
})
1408+
12491409
it("should throw error for invalid skill name", async () => {
12501410
await expect(skillsManager.createSkill("Invalid-Name", "global", "Description")).rejects.toThrow(
12511411
"Skill name must be lowercase letters/numbers/hyphens only",

0 commit comments

Comments
 (0)