diff --git a/apps/vscode-e2e/src/suite/skills-diagnostics.test.ts b/apps/vscode-e2e/src/suite/skills-diagnostics.test.ts new file mode 100644 index 00000000000..71662e6cfed --- /dev/null +++ b/apps/vscode-e2e/src/suite/skills-diagnostics.test.ts @@ -0,0 +1,138 @@ +import * as assert from "assert" +import * as fs from "fs/promises" +import * as path from "path" + +import * as vscode from "vscode" + +import { setDefaultSuiteTimeout } from "./test-utils" +import { waitFor } from "./utils" + +const GOOD_SKILL = "e2e-skill-good" +const BAD_SKILL = "e2e-skill-bad" + +// Issue #859 reproduction content: the description is a double-quoted YAML +// scalar whose inner double quotes are left unescaped, which makes the +// frontmatter unparseable. +const MALFORMED_SKILL_MD = `--- +name: ${BAD_SKILL} +description: "Use when implementing features. Triggers on: "TDD", "test-driven development" +--- + +# E2E Skill Bad + +Instructions here. +` + +const FIXED_SKILL_MD = `--- +name: ${BAD_SKILL} +description: 'Use when implementing features. Triggers on: "TDD", "test-driven development"' +--- + +# E2E Skill Bad + +Instructions here. +` + +const GOOD_SKILL_MD = `--- +name: ${GOOD_SKILL} +description: A healthy skill used by the skill diagnostics e2e smoke test. +--- + +# E2E Skill Good + +Instructions here. +` + +// Write a skill file atomically (write to a sidecar, then rename over the +// target) so the extension host's file watcher only ever observes complete +// content. An in-place fs.writeFile is visible mid-write, the watcher can +// fire for that moment, and - because discovery scans are serialized - a +// mid-write event could be the last one, leaving a stale scan result. +const writeSkillFileAtomic = async (finalPath: string, content: string): Promise => { + const tmpPath = `${finalPath}.tmp` + await fs.writeFile(tmpPath, content, "utf8") + await fs.rename(tmpPath, finalPath) +} + +suite("Roo Code Skill Diagnostics", function () { + setDefaultSuiteTimeout(this) + + let skillsRoot: string + + setup(async function () { + const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath + assert.ok(workspaceRoot, "e2e workspace folder must be open") + skillsRoot = path.join(workspaceRoot, ".roo", "skills") + }) + + teardown(async function () { + // Remove only the skill directories this suite created so pre-existing + // or other suites' fixtures under .roo/skills are left intact. + await Promise.all( + [GOOD_SKILL, BAD_SKILL].map((name) => fs.rm(path.join(skillsRoot, name), { recursive: true, force: true })), + ) + }) + + test("should surface a malformed SKILL.md as a diagnostic without hiding healthy skills", async function () { + this.timeout(180_000) + + // Arrange: one healthy skill and one malformed skill on real disk in the + // workspace's .roo/skills directory, written atomically so the watcher + // only observes complete files. + await fs.mkdir(path.join(skillsRoot, GOOD_SKILL), { recursive: true }) + await writeSkillFileAtomic(path.join(skillsRoot, GOOD_SKILL, "SKILL.md"), GOOD_SKILL_MD) + await fs.mkdir(path.join(skillsRoot, BAD_SKILL), { recursive: true }) + const badSkillMd = path.join(skillsRoot, BAD_SKILL, "SKILL.md") + await writeSkillFileAtomic(badSkillMd, MALFORMED_SKILL_MD) + + // Act: the extension host's file watcher re-discovers skills; wait until + // the real SkillsManager reports the healthy skill and a diagnostic for + // the malformed one. + await waitFor( + async () => { + const state = globalThis.api.getSkillsState() + const goodVisible = state.skills.some((skill) => skill.name === GOOD_SKILL) + const badDiagnosed = state.skillDiagnostics.some((diagnostic) => diagnostic.path.includes(BAD_SKILL)) + return goodVisible && badDiagnosed + }, + { timeout: 60_000, interval: 500 }, + ) + + // Assert: the malformed skill is skipped with a diagnostic pointing at it, + // while the healthy skill is unaffected. + const state = globalThis.api.getSkillsState() + const diagnostic = state.skillDiagnostics.find((d) => d.path.includes(BAD_SKILL)) + assert.ok(diagnostic, "malformed SKILL.md should produce a diagnostic") + assert.strictEqual(diagnostic.source, "project") + assert.ok(diagnostic.message.length > 0, "diagnostic should carry the parse error message") + assert.ok( + state.skills.some((skill) => skill.name === GOOD_SKILL), + "healthy skill should still be discovered", + ) + assert.ok( + !state.skills.some((skill) => skill.name === BAD_SKILL), + "malformed skill should be omitted from skills", + ) + + // Act: repair the frontmatter in place (atomically); the watcher + // re-discovers and the diagnostic clears. + await writeSkillFileAtomic(badSkillMd, FIXED_SKILL_MD) + + await waitFor( + async () => { + const next = globalThis.api.getSkillsState() + const cleared = !next.skillDiagnostics.some((d) => d.path.includes(BAD_SKILL)) + const loaded = next.skills.some((skill) => skill.name === BAD_SKILL) + return cleared && loaded + }, + { timeout: 60_000, interval: 500 }, + ) + + const fixed = globalThis.api.getSkillsState() + assert.ok( + fixed.skills.some((skill) => skill.name === BAD_SKILL), + "fixed skill should load after repair", + ) + assert.ok(fixed.skills.find((skill) => skill.name === BAD_SKILL)?.description.includes("TDD") === true) + }) +}) diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index e64406fa9c6..5e200cdc125 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -6,6 +6,7 @@ import type { RooCodeSettings } from "./global-settings.js" import type { HistoryItem } from "./history.js" import type { ProviderSettingsEntry, ProviderSettings } from "./provider-settings.js" import type { IpcMessage, IpcServerEvents } from "./ipc.js" +import type { SkillDiagnostic, SkillMetadata } from "./skills.js" import type { WebviewThemeFixture } from "./vscode-extension-host.js" export type RooCodeAPIEvents = RooCodeEvents @@ -58,6 +59,15 @@ export interface RooCodeAPI extends EventEmitter { * @returns The number of persisted API conversation history entries, or 0 if unavailable. */ getTaskApiConversationHistoryLength(taskId: string): Promise + /** + * Returns the skill metadata and load diagnostics currently discovered by the + * extension host. Intended for use in tests only. + * @returns The discovered skills and any diagnostics for skills that failed to load. + */ + getSkillsState(): { + skills: SkillMetadata[] + skillDiagnostics: SkillDiagnostic[] + } /** * Checks for an ordered user turn and assistant tool call in persisted API history. * @param taskId The ID of the task. diff --git a/packages/types/src/skills.ts b/packages/types/src/skills.ts index 2f13b822ebb..65768f7f290 100644 --- a/packages/types/src/skills.ts +++ b/packages/types/src/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 +} + /** * Skill name validation constants per agentskills.io specification: * https://agentskills.io/specification diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 2e9ea7ccb84..b1bdb6095c9 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -18,7 +18,7 @@ import { OllamaModelsMessageType } from "./providers/ollama.js" import { OpenAiModelsMessageType } from "./providers/openai.js" import { VsCodeLmModelsMessageType } from "./providers/vscode-llm.js" import type { OpenAiCodexRateLimitInfo } from "./providers/openai-codex-rate-limits.js" -import type { SkillMetadata } from "./skills.js" +import type { SkillDiagnostic, SkillMetadata } from "./skills.js" import type { RuleMetadata } from "./rules.js" import type { TelemetrySetting } from "./telemetry.js" import type { WorktreeIncludeStatus } from "./worktree.js" @@ -235,6 +235,7 @@ export interface ExtensionMessage { list?: string[] // For dismissedUpsells tools?: SerializedCustomToolDefinition[] // For customToolsResult skills?: SkillMetadata[] // For skills response + skillDiagnostics?: SkillDiagnostic[] // For malformed skills omitted from the skills response rules?: RuleMetadata[] // For rules response modes?: { slug: string; name: string }[] // For modes response rooHistoryImportProgress?: { diff --git a/src/core/webview/__tests__/skillsMessageHandler.spec.ts b/src/core/webview/__tests__/skillsMessageHandler.spec.ts index 5d03b95a27a..f5fa7eec382 100644 --- a/src/core/webview/__tests__/skillsMessageHandler.spec.ts +++ b/src/core/webview/__tests__/skillsMessageHandler.spec.ts @@ -27,6 +27,7 @@ vi.mock("../../../i18n", () => ({ "skills:errors.manager_unavailable": "Skills manager not available", "skills:errors.missing_delete_fields": "Missing required fields: skillName or source", "skills:errors.missing_move_fields": "Missing required fields: skillName or source", + "skills:errors.missing_update_modes_fields": "Missing required fields: skillName or source", "skills:errors.skill_not_found": `Skill "${params?.name}" not found`, } return translations[key] || key @@ -41,15 +42,18 @@ import { handleDeleteSkill, handleMoveSkill, handleOpenSkillFile, + handleUpdateSkillModes, } from "../skillsMessageHandler" describe("skillsMessageHandler", () => { const mockLog = vi.fn() const mockPostMessageToWebview = vi.fn() const mockGetSkillsMetadata = vi.fn() + const mockGetSkillDiagnostics = vi.fn() const mockCreateSkill = vi.fn() const mockDeleteSkill = vi.fn() const mockMoveSkill = vi.fn() + const mockUpdateSkillModes = vi.fn() const mockGetSkill = vi.fn() const mockFindSkillByNameAndSource = vi.fn() @@ -57,9 +61,11 @@ describe("skillsMessageHandler", () => { const skillsManager = hasSkillsManager ? { getSkillsMetadata: mockGetSkillsMetadata, + getSkillDiagnostics: mockGetSkillDiagnostics, createSkill: mockCreateSkill, deleteSkill: mockDeleteSkill, moveSkill: mockMoveSkill, + updateSkillModes: mockUpdateSkillModes, getSkill: mockGetSkill, findSkillByNameAndSource: mockFindSkillByNameAndSource, } @@ -90,6 +96,7 @@ describe("skillsMessageHandler", () => { beforeEach(() => { vi.clearAllMocks() + mockGetSkillDiagnostics.mockReturnValue([]) }) describe("handleRequestSkills", () => { @@ -100,7 +107,34 @@ describe("skillsMessageHandler", () => { const result = await handleRequestSkills(provider) expect(result).toEqual(mockSkills) - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: mockSkills }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: mockSkills, + skillDiagnostics: [], + }) + }) + + it("sends structured malformed-skill diagnostics without hiding valid skills", async () => { + const provider = createMockProvider(true) + const diagnostics = [ + { + path: "/workspace/.roo/skills/broken/SKILL.md", + source: "project" as const, + message: "bad indentation of a mapping entry", + line: 3, + column: 20, + }, + ] + mockGetSkillsMetadata.mockReturnValue(mockSkills) + mockGetSkillDiagnostics.mockReturnValue(diagnostics) + + await handleRequestSkills(provider) + + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: mockSkills, + skillDiagnostics: diagnostics, + }) }) it("returns empty skills when skills manager is not available", async () => { @@ -109,7 +143,11 @@ describe("skillsMessageHandler", () => { const result = await handleRequestSkills(provider) expect(result).toEqual([]) - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: [] }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [], + skillDiagnostics: [], + }) }) it("handles errors and returns empty skills", async () => { @@ -122,7 +160,11 @@ describe("skillsMessageHandler", () => { expect(result).toEqual([]) expect(mockLog).toHaveBeenCalled() - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: [] }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [], + skillDiagnostics: [], + }) }) }) @@ -142,7 +184,11 @@ describe("skillsMessageHandler", () => { expect(result).toEqual(mockSkills) expect(mockCreateSkill).toHaveBeenCalledWith("new-skill", "global", "New skill description", undefined) expect(openFile).toHaveBeenCalledWith("/path/to/new-skill/SKILL.md") - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: mockSkills }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: mockSkills, + skillDiagnostics: [], + }) }) it("creates a skill with mode restriction", async () => { @@ -212,7 +258,11 @@ describe("skillsMessageHandler", () => { expect(result).toEqual([mockSkills[1]]) expect(mockDeleteSkill).toHaveBeenCalledWith("test-skill", "global", undefined) - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: [mockSkills[1]] }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [mockSkills[1]], + skillDiagnostics: [], + }) }) it("deletes a skill with mode restriction", async () => { @@ -280,7 +330,11 @@ describe("skillsMessageHandler", () => { expect(result).toEqual([mockSkills[0]]) expect(mockMoveSkill).toHaveBeenCalledWith("test-skill", "global", undefined, "code") - expect(mockPostMessageToWebview).toHaveBeenCalledWith({ type: "skills", skills: [mockSkills[0]] }) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [mockSkills[0]], + skillDiagnostics: [], + }) }) it("moves a skill from one mode to another", async () => { @@ -334,6 +388,132 @@ describe("skillsMessageHandler", () => { }) }) + describe("handleUpdateSkillModes", () => { + it("updates a skill's mode slugs successfully", async () => { + const provider = createMockProvider(true) + mockUpdateSkillModes.mockResolvedValue(undefined) + mockGetSkillsMetadata.mockReturnValue([mockSkills[0]]) + + const result = await handleUpdateSkillModes(provider, { + type: "updateSkillModes", + skillName: "test-skill", + source: "global", + newSkillModeSlugs: ["code"], + } as WebviewMessage) + + expect(result).toEqual([mockSkills[0]]) + expect(mockUpdateSkillModes).toHaveBeenCalledWith("test-skill", "global", ["code"]) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [mockSkills[0]], + skillDiagnostics: [], + }) + }) + + it("clears a skill's mode restriction with empty slugs", async () => { + const provider = createMockProvider(true) + mockUpdateSkillModes.mockResolvedValue(undefined) + mockGetSkillsMetadata.mockReturnValue([mockSkills[1]]) + + const result = await handleUpdateSkillModes(provider, { + type: "updateSkillModes", + skillName: "project-skill", + source: "project", + newSkillModeSlugs: [], + } as WebviewMessage) + + expect(result).toEqual([mockSkills[1]]) + expect(mockUpdateSkillModes).toHaveBeenCalledWith("project-skill", "project", []) + }) + + it("passes undefined mode slugs and refreshes state when newSkillModeSlugs is omitted", async () => { + const provider = createMockProvider(true) + mockUpdateSkillModes.mockResolvedValue(undefined) + mockGetSkillsMetadata.mockReturnValue([mockSkills[0]]) + // Forward a concrete (non-empty) diagnostic so the assertion proves the + // handler relays the diagnostics list rather than always posting [] + // (which would pass even if the field were dropped or hard-coded). + const diagnostics = [ + { + path: "/global/.roo/skills/broken/SKILL.md", + source: "global" as const, + message: "can not read a block mapping entry", + line: 3, + column: 10, + }, + ] + mockGetSkillDiagnostics.mockReturnValue(diagnostics) + + const message: WebviewMessage = { + type: "updateSkillModes", + skillName: "test-skill", + source: "global", + // newSkillModeSlugs omitted + } + const result = await handleUpdateSkillModes(provider, message) + + expect(result).toEqual([mockSkills[0]]) + expect(mockUpdateSkillModes).toHaveBeenCalledWith("test-skill", "global", undefined) + expect(mockPostMessageToWebview).toHaveBeenCalledWith({ + type: "skills", + skills: [mockSkills[0]], + skillDiagnostics: diagnostics, + }) + }) + + it("returns undefined when required fields are missing", async () => { + const provider = createMockProvider(true) + + const result = await handleUpdateSkillModes(provider, { + type: "updateSkillModes", + skillName: "test-skill", + // missing source + } as WebviewMessage) + + expect(result).toBeUndefined() + expect(mockUpdateSkillModes).not.toHaveBeenCalled() + expect(mockLog).toHaveBeenCalledWith( + "Error updating skill modes: Missing required fields: skillName or source", + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to update skill modes: Missing required fields: skillName or source", + ) + }) + + it("returns undefined when skills manager is not available", async () => { + const provider = createMockProvider(false) + + const result = await handleUpdateSkillModes(provider, { + type: "updateSkillModes", + skillName: "test-skill", + source: "global", + newSkillModeSlugs: ["code"], + } as WebviewMessage) + + expect(result).toBeUndefined() + expect(mockLog).toHaveBeenCalledWith("Error updating skill modes: Skills manager not available") + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to update skill modes: Skills manager not available", + ) + }) + + it("returns undefined and reports the error when updateSkillModes rejects", async () => { + const provider = createMockProvider(true) + mockUpdateSkillModes.mockRejectedValue(new Error("boom")) + + const result = await handleUpdateSkillModes(provider, { + type: "updateSkillModes", + skillName: "test-skill", + source: "global", + newSkillModeSlugs: ["code"], + } as WebviewMessage) + + expect(result).toBeUndefined() + expect(mockLog).toHaveBeenCalledWith("Error updating skill modes: boom") + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to update skill modes: boom") + }) + }) + describe("handleOpenSkillFile", () => { it("opens a skill file successfully", async () => { const provider = createMockProvider(true) diff --git a/src/core/webview/skillsMessageHandler.ts b/src/core/webview/skillsMessageHandler.ts index 2eab270734e..8687791c594 100644 --- a/src/core/webview/skillsMessageHandler.ts +++ b/src/core/webview/skillsMessageHandler.ts @@ -16,15 +16,16 @@ export async function handleRequestSkills(provider: ClineProvider): Promise { + let api: API + let mockOutputChannel: vscode.OutputChannel + let mockProvider: ClineProvider + let mockGetSkillsManager: ReturnType + + beforeEach(() => { + // mockOutputChannel and mockProvider are intentionally partial + // doubles: they implement only the members API touches (appendLine; + // context, getSkillsManager, on). The as-unknown-as casts are the + // last resort because the partial shapes are not subtypes of the full + // vscode.OutputChannel / ClineProvider types. + mockOutputChannel = { + appendLine: vi.fn(), + } as unknown as vscode.OutputChannel + + mockGetSkillsManager = vi.fn() + + mockProvider = { + context: {} as vscode.ExtensionContext, + getSkillsManager: mockGetSkillsManager, + on: vi.fn(), + } as unknown as ClineProvider + + api = new API(mockOutputChannel, mockProvider, makeClineProviderFactory(), undefined, true) + }) + + it("returns the skills and diagnostics from the skills manager", () => { + const skills = [ + { + name: "good-skill", + description: "A healthy skill.", + path: "/skills/good-skill/SKILL.md", + source: "project" as const, + }, + ] + const skillDiagnostics = [ + { path: "/skills/bad-skill/SKILL.md", source: "project" as const, message: "YAML syntax error", line: 3 }, + ] + mockGetSkillsManager.mockReturnValue({ + getSkillsMetadata: vi.fn().mockReturnValue(skills), + getSkillDiagnostics: vi.fn().mockReturnValue(skillDiagnostics), + }) + + expect(api.getSkillsState()).toEqual({ skills, skillDiagnostics }) + }) + + it("returns empty arrays when the skills manager is unavailable", () => { + mockGetSkillsManager.mockReturnValue(undefined) + + expect(api.getSkillsState()).toEqual({ skills: [], skillDiagnostics: [] }) + }) +}) diff --git a/src/extension/api.ts b/src/extension/api.ts index ccb9dce199a..467bdb935fe 100644 --- a/src/extension/api.ts +++ b/src/extension/api.ts @@ -307,6 +307,17 @@ export class API extends EventEmitter implements RooCodeAPI { } } + public getSkillsState() { + const skillsManager = this.sidebarProvider.getSkillsManager() + if (!skillsManager) { + return { skills: [], skillDiagnostics: [] } + } + return { + skills: skillsManager.getSkillsMetadata(), + skillDiagnostics: skillsManager.getSkillDiagnostics(), + } + } + /** Checks persisted turn ordering without exposing conversation contents to tests. */ public async hasTaskApiConversationHistorySequence( taskId: string, diff --git a/src/services/skills/SkillsManager.ts b/src/services/skills/SkillsManager.ts index 09809a9bccf..245b07aa2f7 100644 --- a/src/services/skills/SkillsManager.ts +++ b/src/services/skills/SkillsManager.ts @@ -7,7 +7,7 @@ import { parseFrontmatter } from "../../utils/safeFrontmatter" 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, @@ -17,11 +17,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. */ @@ -36,6 +70,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 { @@ -60,6 +96,7 @@ function isHiddenEntry(name: string): boolean { 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 @@ -109,6 +146,7 @@ export class SkillsManager { containerSkillPaths: new Set(), containers: new Map(), failedPaths: [], + diagnostics: [], } const skillsDirs = await this.getSkillsDirectories() @@ -148,6 +186,20 @@ export class SkillsManager { this.skills = pass.skills this.containerSkillPaths = pass.containerSkillPaths + for (const diagnostic of this.diagnostics) { + // A root this pass could not read may still hold the SKILL.md whose parse failure + // produced this diagnostic, exactly like the skills and containers kept above. A + // fresh diagnostic for the same path cannot exist here: loadSkillMetadata + // records the failure and returns without recording one. The next pass that + // reads the path clears it (see row 4774950127). A skill inside a symlinked + // container is the same case one level down: its parse failure is recorded under + // the container's target path, and that path sits under no failed path when only + // the skills root was unreadable, so the check has to consult kept containers + // exactly as the skill check above does (see row 4776975282). + if (!isUnderAny(diagnostic.path, pass.failedPaths) && !isUnderAny(diagnostic.path, keptContainers)) continue + pass.diagnostics.push(diagnostic) + } + this.diagnostics = pass.diagnostics this.containers = pass.containers } @@ -316,8 +368,45 @@ export class SkillsManager { } try { - // Use gray-matter to parse frontmatter - const { data: frontmatter } = parseFrontmatter(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 parse goes through parseFrontmatter, the helper main added with the + // frontmatter security fix: it pins the yaml engine, rejects a document- + // selected executable engine, and passes options, which bypasses gray-matter's + // shared, input-only parse cache. That last part is what keeps this call + // deterministic: a frontmatter that throws on first parse is not cached with + // an empty data object, so every later parse of the same content re-throws + // instead of silently returning that empty object. + let parsed: ReturnType + try { + parsed = parseFrontmatter(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") { @@ -392,6 +481,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. @@ -499,6 +611,13 @@ export class SkillsManager { } } + /** + * Get the SKILL.md load problems found by the last discovery pass (see issue #859). + */ + getSkillDiagnostics(): SkillDiagnostic[] { + return [...this.diagnostics] + } + /** * Get all skills metadata (for UI display) * Returns skills from all sources without content @@ -611,25 +730,25 @@ 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. ` + const skillContent = matter.stringify(body, frontmatter, SKILL_YAML_DUMP_OPTIONS) // Write the SKILL.md file await fs.writeFile(skillMdPath, skillContent, "utf-8") @@ -959,8 +1078,10 @@ Add your skill instructions here. delete frontmatter.mode } - // Serialize back to SKILL.md format - const newContent = matter.stringify({ content: body }, frontmatter) + // 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). + const newContent = matter.stringify({ content: body }, frontmatter, SKILL_YAML_DUMP_OPTIONS) await fs.writeFile(skill.path, newContent, "utf-8") // Refresh skills list diff --git a/src/services/skills/__tests__/SkillsManager.spec.ts b/src/services/skills/__tests__/SkillsManager.spec.ts index ba0fed4f46c..93fbb8cff64 100644 --- a/src/services/skills/__tests__/SkillsManager.spec.ts +++ b/src/services/skills/__tests__/SkillsManager.spec.ts @@ -1,4 +1,5 @@ import * as path from "path" +import matter from "gray-matter" // Use vi.hoisted to ensure mocks are available during hoisting const { @@ -83,6 +84,20 @@ vi.mock("os", () => ({ homedir: mockHomedir, })) +// Keep the real gray-matter parser by default, but let individual tests script +// the failure shape (e.g. a non-Error throw) to exercise recordDiagnostic's +// defensive fallbacks (see issue #859). vi.importActual resolves the CJS module +// to a namespace that exposes the parser as `default`, which the module's +// declared `export =` type does not carry, so the namespace is bridged through +// `unknown` once; the double assertion then bridges the mock back to the +// module's declared type. +vi.mock("gray-matter", async () => { + const actual = await vi.importActual("gray-matter") + const realParse = (actual as { default: typeof matter }).default + const parse = Object.assign(vi.fn(realParse), actual) as unknown as typeof matter + return { default: parse } +}) + // Mock vscode vi.mock("vscode", () => ({ workspace: { @@ -228,6 +243,71 @@ describe("SkillsManager", () => { }, ) + it("should rewrite modeSlugs via gray-matter serialization without reflowing the description", async () => { + const skillDir = p(globalSkillsDir, "modes-skill") + const skillMd = p(skillDir, "SKILL.md") + const description = 'Use when implementing features. Triggers on: "TDD", "test-driven development"' + const originalContent = `--- +name: modes-skill +description: '${description}' +--- + +# Modes Skill + +## Instructions + +Body here.` + + // Initial discovery so the skill is registered. + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (value: string) => value) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["modes-skill"] : [])) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === skillDir) { + return { isDirectory: () => true } + } + throw new Error("Not found") + }) + mockFileExists.mockImplementation(async (file: string) => file === skillMd) + mockReadFile.mockResolvedValue(originalContent) + mockWriteFile.mockResolvedValue(undefined) + + await skillsManager.discoverSkills() + expect(skillsManager.getAllSkills()).toHaveLength(1) + + // Apply a mode restriction; the file is rewritten with the new slugs. + await skillsManager.updateSkillModes("modes-skill", "global", ["code"]) + + expect(mockWriteFile).toHaveBeenCalledTimes(1) + const rewritten = String(mockWriteFile.mock.calls[0][1]) + const parsed = matter(rewritten) + // The description survives the round-trip exactly and stays quoted. + expect(parsed.data.description).toBe(description) + expect(rewritten).toContain(`description: '${description}'`) + // The new modeSlugs were written and the body is preserved. + expect(parsed.data.modeSlugs).toEqual(["code"]) + expect(rewritten).toContain("Body here.") + // lineWidth: -1 keeps the value on a single line: without it js-yaml folds + // a description this long across several lines, so pin the exact line and + // the absence of any continuation. + const descriptionLine = rewritten.split("\n").find((line) => line.startsWith("description:")) + expect(descriptionLine).toBe(`description: '${description}'`) + expect(rewritten).not.toContain("> ") + + // Clearing the restriction removes modeSlugs from the frontmatter. + // The rewrite re-reads the file, so the read mock has to serve what the previous + // rewrite actually staged; while it still returned the pre-edit content the + // assertion below passed even if production stopped deleting the key. + mockReadFile.mockResolvedValue(rewritten) + + await skillsManager.updateSkillModes("modes-skill", "global", []) + + const rewritten2 = String(mockWriteFile.mock.calls[1][1]) + const parsed2 = matter(rewritten2) + expect(parsed2.data.modeSlugs).toBeUndefined() + expect(parsed2.data.description).toBe(description) + }) + describe("discoverSkills", () => { it("should discover skills from global directory", async () => { const pdfSkillDir = p(globalSkillsDir, "pdf-processing") @@ -511,6 +591,161 @@ description: Invalid name format expect(skills).toHaveLength(0) }) + it("should skip skills with invalid YAML frontmatter and log the real cause (issue #859)", async () => { + const badSkillDir = p(globalSkillsDir, "test-skill") + const badSkillMd = p(badSkillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir + }) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir ? ["test-skill"] : [] + }) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === badSkillDir) { + return { isDirectory: () => true } + } + throw new Error("Not found") + }) + mockFileExists.mockImplementation(async (file: string) => file === badSkillMd) + mockReadFile.mockImplementation(async (file: string) => { + if (file === badSkillMd) { + return `--- +name: test-skill +description: Use when implementing features. Triggers on: "TDD", "test-driven development" +--- + +# Test Skill + +Instructions here.` + } + throw new Error("File not found") + }) + + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + try { + await skillsManager.discoverSkills() + + // The skill is skipped... + expect(skillsManager.getAllSkills()).toHaveLength(0) + + // ...and the real cause (a YAML syntax error) is reported instead + // of the misleading "missing required 'name' field" message. + const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" ")) + expect(logged.some((line) => line.includes("YAMLException"))).toBe(true) + expect(logged.some((line) => line.includes("missing required 'name' field"))).toBe(false) + // The unescaped-double-quotes hint points at the exact problem. + expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(true) + + // The structured diagnostic captures the parse failure location. + const diagnostics = skillsManager.getSkillDiagnostics() + expect(diagnostics).toHaveLength(1) + expect(diagnostics[0].path).toBe(badSkillMd) + expect(diagnostics[0].source).toBe("global") + expect(typeof diagnostics[0].message).toBe("string") + expect(diagnostics[0].line).toBe(3) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("should log a distinct YAML error for other malformed frontmatter (no quote hint)", async () => { + const badSkillDir = p(globalSkillsDir, "broken-skill") + const badSkillMd = p(badSkillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir + }) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir ? ["broken-skill"] : [] + }) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === badSkillDir) { + return { isDirectory: () => true } + } + throw new Error("Not found") + }) + mockFileExists.mockImplementation(async (file: string) => file === badSkillMd) + mockReadFile.mockImplementation(async (file: string) => { + if (file === badSkillMd) { + return `--- +name broken-skill +description: Missing colon makes this invalid YAML +--- + +# Broken skill` + } + throw new Error("File not found") + }) + + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + try { + await skillsManager.discoverSkills() + + expect(skillsManager.getAllSkills()).toHaveLength(0) + + const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" ")) + expect(logged.some((line) => line.includes("YAMLException"))).toBe(true) + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + // The unescaped-quotes hint only applies when the description line + // actually contains double quotes. + expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(false) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("should skip skills with unterminated frontmatter and a dangling quote (no line hint)", async () => { + const badSkillDir = p(globalSkillsDir, "unclosed-skill") + const badSkillMd = p(badSkillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir + }) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => { + return dir === globalSkillsDir ? ["unclosed-skill"] : [] + }) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === badSkillDir) { + return { isDirectory: () => true } + } + throw new Error("Not found") + }) + mockFileExists.mockImplementation(async (file: string) => file === badSkillMd) + mockReadFile.mockImplementation(async (file: string) => { + if (file === badSkillMd) { + // Unterminated frontmatter: the opening --- is never closed, and the + // dangling double quote makes gray-matter throw. The raw-line lookup + // cannot find a closing delimiter, so no quote hint is possible. + return `--- +name: unclosed-skill +description: "unclosed quote +rest of the file` + } + throw new Error("File not found") + }) + + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + try { + await skillsManager.discoverSkills() + + expect(skillsManager.getAllSkills()).toHaveLength(0) + + const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" ")) + expect(logged.some((line) => line.includes("YAMLException"))).toBe(true) + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + // Without a closing frontmatter delimiter there is no line to hint at. + expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(false) + } finally { + consoleErrorSpy.mockRestore() + } + }) it("should skip skills with name longer than 64 characters (spec compliance)", async () => { const longName = "a".repeat(65) const longDir = p(globalSkillsDir, longName) @@ -2148,6 +2383,108 @@ Instructions`) expect(writeCall[1]).toContain("- code") }) + it("round-trips the issue description and mode slugs through YAML frontmatter", async () => { + mockDirectoryExists.mockResolvedValue(false) + mockRealpath.mockImplementation(async (p: string) => p) + mockReaddir.mockResolvedValue([]) + mockFileExists.mockResolvedValue(false) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + const description = 'Triggers on: "TDD", "test-driven development"' + + await skillsManager.createSkill("tdd-skill", "global", description, ["code", "debug"]) + + const generatedContent = mockWriteFile.mock.calls[0][1] as string + const parsed = matter(generatedContent) + expect(parsed.data).toEqual({ + name: "tdd-skill", + description, + modeSlugs: ["code", "debug"], + }) + expect(parsed.content).toBe("\n# Tdd Skill\n\n## Instructions\n\nAdd your skill instructions here.\n") + }) + + it.each([ + ["colon-space", "Use when: tests fail"], + ["quotes", "Use \"red-green-refactor\" and 'small steps'"], + ["hash", "Use tests # not comments"], + ["leading punctuation", "- Start from a failing test"], + ["multiline", "First line\nSecond line: with # and quotes"], + ])("preserves YAML-sensitive %s descriptions", async (_caseName, description) => { + mockDirectoryExists.mockResolvedValue(false) + mockRealpath.mockImplementation(async (p: string) => p) + mockReaddir.mockResolvedValue([]) + mockFileExists.mockResolvedValue(false) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + await skillsManager.createSkill("yaml-sensitive", "global", description) + + const generatedContent = mockWriteFile.mock.calls[0][1] as string + expect(matter(generatedContent).data.description).toBe(description) + }) + + it("should escape double quotes in the description so the created skill loads (issue #859)", async () => { + mockDirectoryExists.mockResolvedValue(false) + mockRealpath.mockImplementation(async (p: string) => p) + mockReaddir.mockResolvedValue([]) + mockFileExists.mockResolvedValue(false) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + // Deliberately longer than js-yaml's default 80-column fold width: without + // lineWidth: -1 the serializer wraps this into a rolled scalar. + const description = + 'Use when implementing features. Triggers on: "TDD", "test-driven development", "red-green-refactor" and "refactoring" workflows' + const createdPath = await skillsManager.createSkill("test-skill", "global", description) + + // The written frontmatter must be valid YAML that round-trips the + // description, with the raw value quoted instead of unescaped. + const writtenContent = String(mockWriteFile.mock.calls[0][1]) + const parsed = matter(writtenContent) + expect(parsed.data.name).toBe("test-skill") + expect(parsed.data.description).toBe(description) + expect(writtenContent).toContain(`description: '${description}'`) + + // Re-discovery loads the created skill instead of silently skipping it. + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["test-skill"] : [])) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === p(globalSkillsDir, "test-skill")) { + return { isDirectory: () => true } + } + throw new Error("Not found") + }) + mockFileExists.mockImplementation(async (file: string) => file === createdPath) + mockReadFile.mockImplementation(async (file: string) => + file === createdPath ? writtenContent : Promise.reject(new Error("File not found")), + ) + + await skillsManager.discoverSkills() + + const skills = skillsManager.getAllSkills() + expect(skills).toHaveLength(1) + expect(skills[0].name).toBe("test-skill") + expect(skills[0].description).toBe(description) + }) + + it("should quote descriptions that would otherwise parse as YAML non-strings", async () => { + mockDirectoryExists.mockResolvedValue(false) + mockRealpath.mockImplementation(async (p: string) => p) + mockReaddir.mockResolvedValue([]) + mockFileExists.mockResolvedValue(false) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + await skillsManager.createSkill("flag-skill", "global", "yes") + + const writtenContent = String(mockWriteFile.mock.calls[0][1]) + const parsed = matter(writtenContent) + // Without quoting, js-yaml resolves "yes" to a boolean and the skill + // is rejected with a misleading "missing required 'description' field". + expect(typeof parsed.data.description).toBe("string") + expect(parsed.data.description).toBe("yes") + }) it("should create a project skill", async () => { mockDirectoryExists.mockResolvedValue(false) mockRealpath.mockImplementation(async (p: string) => p) @@ -2244,6 +2581,471 @@ Instructions`) }) }) + describe("skill diagnostics", () => { + it("reports malformed YAML with location while retaining valid skills", async () => { + const validSkillDir = p(globalSkillsDir, "valid-skill") + const malformedSkillDir = p(globalSkillsDir, "malformed-skill") + const validSkillPath = p(validSkillDir, "SKILL.md") + const malformedSkillPath = p(malformedSkillDir, "SKILL.md") + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => + dir === globalSkillsDir ? ["valid-skill", "malformed-skill"] : [], + ) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => + [validSkillPath, malformedSkillPath].includes(file), + ) + mockReadFile.mockImplementation(async (file: string) => { + if (file === validSkillPath) { + return "---\nname: valid-skill\ndescription: Still visible\n---\nValid instructions" + } + return '---\nname: malformed-skill\ndescription: Triggers on: "TDD"\n---\nBroken instructions' + }) + + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([ + expect.objectContaining({ name: "valid-skill", description: "Still visible" }), + ]) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + expect.objectContaining({ + path: malformedSkillPath, + source: "global", + message: expect.any(String), + line: 3, + column: expect.any(Number), + }), + ]) + }) + + it("serializes overlapping scans so an older scan cannot append stale diagnostics", async () => { + const skillDir = p(globalSkillsDir, "flaky-skill") + const skillPath = p(skillDir, "SKILL.md") + const staleContent = `--- +name: flaky-skill +description: "Broken "quote" frontmatter +--- + +Body.` + const goodContent = `--- +name: flaky-skill +description: Healthy after repair +--- + +Body.` + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["flaky-skill"] : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + + // What this row proves is queue-ordered publication: passes run in the order they + // were requested, so a pass requested while an earlier pass is still reading runs + // after that pass published, and the later pass' result is the one that survives. + // The first read is parked to hold the earlier pass mid-request. Nothing about the + // later pass is observable before the earlier one publishes - discoverSkills queues + // a pass before it issues any filesystem call - so the queue at SkillsManager.ts:212 + // is what this row guards: removing it reddens the row, while running the two scans + // one after the other leaves it green. + let resolveFirstRead!: (content: string) => void + const firstRead = new Promise((resolve) => { + resolveFirstRead = resolve + }) + let reads = 0 + let publishedWhileQueued: ReturnType = [] + mockReadFile.mockImplementation(async () => { + reads += 1 + if (reads === 2) { + // The pass that queued behind the stale one sees whatever the stale pass + // already published; serialisation is what makes it the stale diagnostics. + publishedWhileQueued = skillsManager.getSkillDiagnostics() + } + return reads === 1 ? firstRead : goodContent + }) + + const first = skillsManager.discoverSkills() + const second = skillsManager.discoverSkills() + // Release the parked read only once it is observably in flight, so a pass really is + // queued behind it when it resolves; releasing it in the same tick as the two calls + // above leaves nothing queued and the ordering asserted below was never contested. + await vi.waitFor(() => expect(mockReadFile.mock.calls.length).toBe(1)) + resolveFirstRead(staleContent) + await Promise.all([first, second]) + + expect(publishedWhileQueued).toEqual([expect.objectContaining({ path: skillPath, source: "global" })]) + + expect(skillsManager.getSkillsMetadata()).toEqual([ + expect.objectContaining({ name: "flaky-skill", description: "Healthy after repair" }), + ]) + expect(skillsManager.getSkillDiagnostics()).toEqual([]) + }) + + it("does not expose a half-built snapshot to a reader while a scan is in progress", async () => { + const stablePath = p(globalSkillsDir, "stable-skill", "SKILL.md") + const slowPath = p(globalSkillsDir, "slow-skill", "SKILL.md") + const stableContent = `--- +name: stable-skill +description: Stable before the scan +--- + +Body.` + const slowContent = `--- +name: slow-skill +description: Loaded after the scan completes +--- + +Body.` + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + // The second scan sees an extra skill, and that skill's read is parked, so + // the reader runs while the scan is mid-flight. Committing incrementally + // would let the reader see the scan after the clear but before the slow + // skill was loaded. + let entries = ["stable-skill"] + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? entries : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === stablePath || file === slowPath) + let resolveSlowRead!: (content: string) => void + const slowRead = new Promise((resolve) => { + resolveSlowRead = resolve + }) + mockReadFile.mockImplementation(async (file: string) => (file === slowPath ? slowRead : stableContent)) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillsMetadata()).toHaveLength(1) + + // Slow skill first: the reader runs after the scan started but before any of + // its own skills were added, so an incremental commit would show an empty list. + entries = ["slow-skill", "stable-skill"] + const scan = skillsManager.discoverSkills() + await vi.waitFor(() => expect(mockReadFile.mock.calls.map((c) => c[0])).toContain(slowPath)) + expect(skillsManager.getSkillsMetadata()).toHaveLength(1) + expect(skillsManager.getSkillDiagnostics()).toEqual([]) + + resolveSlowRead(slowContent) + await scan + + expect(skillsManager.getSkillsMetadata()).toHaveLength(2) + }) + it("does not hint at unescaped quotes when the parse error is on another line", async () => { + const skillDir = p(globalSkillsDir, "hint-skill") + const skillPath = p(skillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["hint-skill"] : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + // The description is a valid single-quoted value that itself contains + // double quotes; the YAML error is on the unclosed name line instead, + // so the unescaped-quotes hint must not fire. + mockReadFile.mockResolvedValue(`--- +name: "unclosed +description: 'Triggers on "TDD" - valid quotes' +--- + +Body.`) + + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + try { + await skillsManager.discoverSkills() + + const logged = consoleErrorSpy.mock.calls.map((call) => call.join(" ")) + expect(logged.some((line) => line.includes("unescaped double quotes"))).toBe(false) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + expect.objectContaining({ path: skillPath, source: "global", line: 4 }), + ]) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("keeps reporting the same malformed skill on a re-scan (gray-matter cache must not swallow the error)", async () => { + const skillDir = p(globalSkillsDir, "cached-bad-skill") + const skillPath = p(skillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["cached-bad-skill"] : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + mockReadFile.mockResolvedValue(`--- +name: cached-bad-skill +description: "Broken "quote" description +--- + +Body.`) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillsMetadata()).toEqual([]) + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + + // A re-scan of the identical (unchanged) content must keep reporting the + // parse failure. gray-matter keeps a global content-keyed cache that it + // populates before parsing, so without bypassing it the first throw is + // cached with an empty data object and every later parse of the same + // content silently returns that object instead of re-throwing - which + // would resurface the misleading "missing required 'name' field" symptom + // from issue #859. + await skillsManager.discoverSkills() + expect(skillsManager.getSkillsMetadata()).toEqual([]) + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + expect(skillsManager.getSkillDiagnostics()[0]).toEqual( + expect.objectContaining({ path: skillPath, source: "global" }), + ) + }) + + it("records a diagnostic from a non-Error parse failure without location details", async () => { + const skillDir = p(globalSkillsDir, "raw-error-skill") + const skillPath = p(skillDir, "SKILL.md") + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (pathArg: string) => pathArg) + mockReaddir.mockImplementation(async (dir: string) => (dir === globalSkillsDir ? ["raw-error-skill"] : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + mockReadFile.mockResolvedValue(`--- +name: raw-error-skill +description: Healthy +--- + +Body.`) + // Script a parse failure that is a plain string (no YAML reason, no + // mark, not an Error) so every defensive fallback in recordDiagnostic + // is exercised. + vi.mocked(matter).mockImplementationOnce(() => { + throw "gray-matter exploded" + }) + + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([]) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + { + path: skillPath, + source: "global", + message: "gray-matter exploded", + line: undefined, + column: undefined, + }, + ]) + }) + + it("keeps a parse diagnostic when a later scan cannot read its skill's root", async () => { + const skillDir = p(globalSkillsDir, "hidden-after-outage") + const skillPath = p(skillDir, "SKILL.md") + const malformed = `--- +name: hidden-after-outage +description: Triggers on: "TDD" +--- + +Body.` + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (value: string) => value) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + mockReaddir.mockImplementation(async (dir: string) => + dir === globalSkillsDir ? ["hidden-after-outage"] : [], + ) + mockReadFile.mockResolvedValue(malformed) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + + // The next pass cannot read the root at all. The skill was never published, + // so the parse diagnostic the earlier pass earned is the only thing the user + // still knows about that folder; clearing it loses the warning while the + // cause is still there (see row 4774087427). + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + } + return [] + }) + + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([]) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + expect.objectContaining({ path: skillPath, source: "global", line: 3 }), + ]) + }) + + it("keeps only the diagnostic under the root that failed to read", async () => { + const brokenDir = p(globalSkillsDir, "still-broken") + const brokenPath = p(brokenDir, "SKILL.md") + const repairedDir = p(globalAgentsSkillsDir, "repaired-skill") + const repairedPath = p(repairedDir, "SKILL.md") + const malformedFor = (name: string) => `--- +name: ${name} +description: Triggers on: "TDD" +--- + +Body.` + const repaired = `--- +name: repaired-skill +description: Healthy after repair +--- + +Body.` + + mockDirectoryExists.mockImplementation( + async (dir: string) => dir === globalSkillsDir || dir === globalAgentsSkillsDir, + ) + mockRealpath.mockImplementation(async (value: string) => value) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === brokenPath || file === repairedPath) + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) return ["still-broken"] + if (dir === globalAgentsSkillsDir) return ["repaired-skill"] + return [] + }) + mockReadFile.mockImplementation(async (file: string) => + file === repairedPath ? malformedFor("repaired-skill") : malformedFor("still-broken"), + ) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillDiagnostics()).toHaveLength(2) + + // The second pass reads the .agents root and finds its skill repaired, so that + // diagnostic has earned its release, while the .roo root cannot be read at all, + // so its diagnostic must survive. A blanket keep and a blanket clear both fail + // here, which is what makes this row the per-path half of the contract. + mockReadFile.mockImplementation(async (file: string) => + file === repairedPath ? repaired : malformedFor("still-broken"), + ) + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + } + if (dir === globalAgentsSkillsDir) return ["repaired-skill"] + return [] + }) + + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([ + expect.objectContaining({ name: "repaired-skill", description: "Healthy after repair" }), + ]) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + expect.objectContaining({ path: brokenPath, source: "global" }), + ]) + }) + + it("clears the retained diagnostic once a later scan reads the repaired skill", async () => { + const skillDir = p(globalSkillsDir, "repaired-after-outage") + const skillPath = p(skillDir, "SKILL.md") + const malformed = `--- +name: repaired-after-outage +description: Triggers on: "TDD" +--- + +Body.` + const repaired = `--- +name: repaired-after-outage +description: Healthy after repair +--- + +Body.` + + mockDirectoryExists.mockImplementation(async (dir: string) => dir === globalSkillsDir) + mockRealpath.mockImplementation(async (value: string) => value) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockImplementation(async (file: string) => file === skillPath) + mockReaddir.mockImplementation(async (dir: string) => + dir === globalSkillsDir ? ["repaired-after-outage"] : [], + ) + mockReadFile.mockResolvedValue(malformed) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + + // An unreadable root keeps the diagnostic (the row above proves which roots + // qualify); this is the other half: the retention is not permanent. + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + } + return [] + }) + await skillsManager.discoverSkills() + + mockReaddir.mockImplementation(async (dir: string) => + dir === globalSkillsDir ? ["repaired-after-outage"] : [], + ) + mockReadFile.mockResolvedValue(repaired) + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([ + expect.objectContaining({ name: "repaired-after-outage", description: "Healthy after repair" }), + ]) + expect(skillsManager.getSkillDiagnostics()).toEqual([]) + }) + it("keeps a parse diagnostic whose container target lies outside the failed root", async () => { + // .roo/skills/shared -> /repo/skills, with one malformed SKILL.md inside. The + // diagnostic is recorded under the target path, not under the skills root. + const containerDir = p(globalSkillsDir, "shared") + const repoSkillsDir = p("/repo", "skills") + const skillDir = p(repoSkillsDir, "broken-in-container") + const skillMd = p(skillDir, "SKILL.md") + const malformed = `--- +name: broken-in-container +description: Triggers on: "TDD" +--- + +Body.` + + mockDirectoryExists.mockImplementation( + async (dir: string) => dir === globalSkillsDir || dir === containerDir, + ) + mockRealpath.mockImplementation(async (pathArg: string) => { + if (pathArg === globalSkillsDir) return globalSkillsDir + if (pathArg === containerDir) return repoSkillsDir + return pathArg + }) + mockStat.mockImplementation(async (pathArg: string) => { + if (pathArg === containerDir) return { isDirectory: () => true } + if (pathArg === skillDir) return { isDirectory: () => true } + throw enoent() + }) + mockSymlinks(containerDir) + mockFileExists.mockImplementation(async (file: string) => file === skillMd) + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) return ["shared"] + if (dir === repoSkillsDir) return ["broken-in-container"] + return [] + }) + mockReadFile.mockResolvedValue(malformed) + + await skillsManager.discoverSkills() + expect(skillsManager.getSkillDiagnostics()).toHaveLength(1) + + // The next pass cannot read the skills root. The container is still kept, because + // its link path sits under the failed root, so its target path becomes a kept + // container. The diagnostic lives under that target, which sits under no failed + // path, so retention must consult kept containers too, as the skill-retention + // check right above already does (see row 4776975282). + mockReaddir.mockImplementation(async (dir: string) => { + if (dir === globalSkillsDir) { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + } + return [] + }) + + await skillsManager.discoverSkills() + + expect(skillsManager.getSkillsMetadata()).toEqual([]) + expect(skillsManager.getSkillDiagnostics()).toEqual([ + expect.objectContaining({ path: skillMd, source: "global", line: 3 }), + ]) + }) + }) + describe("deleteSkill", () => { it("should delete an existing skill", async () => { const testSkillDir = p(globalSkillsDir, "test-skill") diff --git a/src/shared/skills.ts b/src/shared/skills.ts index f5151181f6d..6dc2cbf8ada 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) */ diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index 818e69d1992..828eb1c3711 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -517,4 +517,81 @@ export const stories: Record = { ) }, + + "skills-settings-diagnostics": async () => { + const [{ AppProviders }, { SkillsSettings }] = await Promise.all([ + import("../AppProviders"), + import("@/components/settings/SkillsSettings"), + ]) + // Deterministic diagnostics: one project skill with a YAML location, one global + // skill without position data, so the alert's path/location/message rendering is + // fully covered by the screenshot. + const skills = [ + { + name: "diagnostics-demo", + description: "Demo skill that loads successfully next to the broken ones", + path: "/workspace/.roo/skills/diagnostics-demo/SKILL.md", + source: "project" as const, + }, + ] + const skillDiagnostics = [ + { + path: "/workspace/.roo/skills/broken-skill/SKILL.md", + source: "project" as const, + message: "Invalid YAML frontmatter: unexpected end of the stream", + line: 3, + column: 12, + }, + { + path: "/home/user/.roo/skills/legacy-mode/SKILL.md", + source: "global" as const, + message: "Missing required 'description' field", + }, + ] + return ( + +
+ +
+
+ ) + }, + "skills-settings-many-diagnostics": async () => { + const [{ AppProviders }, { SkillsSettings }] = await Promise.all([ + import("../AppProviders"), + import("@/components/settings/SkillsSettings"), + ]) + // Fourteen diagnostics so the alert list is taller than the bounded height the + // header gives it. Every third one carries position data and the rest do not, so + // both row shapes are laid out while the header competes with the skills list for + // the height of the pane. + const skills = [ + { + name: "healthy-skill", + description: "Skill that loads successfully next to the broken ones", + path: "/workspace/.roo/skills/healthy-skill/SKILL.md", + source: "project" as const, + }, + ] + const skillDiagnostics = Array.from({ length: 14 }, (_, index) => ({ + path: `/workspace/.roo/skills/skill-${index + 1}/SKILL.md`, + source: index % 2 === 0 ? ("project" as const) : ("global" as const), + message: + index % 3 === 0 + ? `Invalid YAML frontmatter: unexpected end of the stream at line ${index + 1}` + : "Missing required 'description' field", + ...(index % 3 === 0 ? { line: index + 1, column: 12 } : {}), + })) + return ( + +
+ +
+
+ ) + }, } diff --git a/webview-ui/src/components/settings/SkillsSettings.tsx b/webview-ui/src/components/settings/SkillsSettings.tsx index b6de39df5ce..7140cb9925c 100644 --- a/webview-ui/src/components/settings/SkillsSettings.tsx +++ b/webview-ui/src/components/settings/SkillsSettings.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useMemo, useCallback } from "react" -import { Plus, Globe, Folder, Edit, Trash2, Settings } from "lucide-react" +import { Plus, Globe, Folder, Edit, Trash2, Settings, TriangleAlert } from "lucide-react" import { Trans } from "react-i18next" import { useAppTranslation } from "@/i18n/TranslationContext" @@ -35,8 +35,9 @@ import { CreateSkillDialog } from "./CreateSkillDialog" export const SkillsSettings: React.FC = () => { const { t } = useAppTranslation() - const { cwd, skills: rawSkills, customModes } = useExtensionState() + const { cwd, skills: rawSkills, skillDiagnostics: rawSkillDiagnostics, customModes } = useExtensionState() const skills = useMemo(() => rawSkills ?? [], [rawSkills]) + const skillDiagnostics = useMemo(() => rawSkillDiagnostics ?? [], [rawSkillDiagnostics]) const [deleteDialogOpen, setDeleteDialogOpen] = useState(false) const [skillToDelete, setSkillToDelete] = useState(null) @@ -233,6 +234,34 @@ export const SkillsSettings: React.FC = () => { }} />

+ {skillDiagnostics.length > 0 && ( +
+ +
+
{t("settings:skills.diagnostics.title")}
+
+ {t("settings:skills.diagnostics.description")} +
+
    + {skillDiagnostics.map((diagnostic) => { + const location = diagnostic.line + ? `:${diagnostic.line}${diagnostic.column ? `:${diagnostic.column}` : ""}` + : "" + return ( +
  • + + {diagnostic.path + location} + + : {diagnostic.message} +
  • + ) + })} +
+
+
+ )} {/* Add Skill button */}