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 0000000000..71662e6cfe --- /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 e64406fa9c..5e200cdc12 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 2f13b822eb..65768f7f29 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 3e23a7934c..abe2b19f9d 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" @@ -233,6 +233,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 5d03b95a27..f5fa7eec38 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 2eab270734..8687791c59 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 15be22d774..d7ca3aa93b 100644 --- a/src/extension/api.ts +++ b/src/extension/api.ts @@ -303,6 +303,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/i18n/__tests__/skills-error-locales.spec.ts b/src/i18n/__tests__/skills-error-locales.spec.ts new file mode 100644 index 0000000000..9a09c91de5 --- /dev/null +++ b/src/i18n/__tests__/skills-error-locales.spec.ts @@ -0,0 +1,33 @@ +import fs from "fs" +import path from "path" + +const localesDir = path.join(__dirname, "..", "locales") + +const languages = fs + .readdirSync(localesDir, { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory() && !dirent.name.startsWith(".")) + .map((dirent) => dirent.name) + +function loadSkillErrors(language: string): Record { + return JSON.parse(fs.readFileSync(path.join(localesDir, language, "skills.json"), "utf8")).errors +} + +describe("skills:errors.outside_skills_root locales", () => { + it("covers every shipped locale", () => { + expect(languages.length).toBeGreaterThan(0) + for (const language of languages) { + expect( + loadSkillErrors(language).outside_skills_root, + `outside_skills_root missing in ${language}`, + ).toBeTruthy() + } + }) + + it("keeps the source and path placeholders in every locale", () => { + for (const language of languages) { + const message = loadSkillErrors(language).outside_skills_root + expect(message, `{{source}} placeholder missing in ${language}`).toContain("{{source}}") + expect(message, `{{path}} placeholder missing in ${language}`).toContain("{{path}}") + } + }) +}) diff --git a/src/i18n/locales/ca/skills.json b/src/i18n/locales/ca/skills.json index 69f87c690c..7053710f59 100644 --- a/src/i18n/locales/ca/skills.json +++ b/src/i18n/locales/ca/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "No s'ha trobat l'habilitat \"{{name}}\"", "container_skill_read_only": "L'habilitat \"{{name}}\" prové d'una carpeta d'habilitats enllaçada simbòlicament ({{path}}) i no es pot moure ni eliminar aquí. Canvia-la a la seva carpeta d'origen.", "symlink_escapes_skill": "No es pot moure l'habilitat: l'enllaç simbòlic {{link}} apunta fora de la carpeta de l'habilitat i es trencaria a la nova ubicació.", - "move_restore_failed": "No s'ha pogut moure l'skill ({{error}}) i la carpeta original no s'ha pogut restaurar a {{path}}. El teu skill està a salvo a {{backupPath}}; torna'l a moure manualment." + "move_restore_failed": "No s'ha pogut moure l'skill ({{error}}) i la carpeta original no s'ha pogut restaurar a {{path}}. El teu skill està a salvo a {{backupPath}}; torna'l a moure manualment.", + "outside_skills_root": "No es pot actualitzar SKILL.md fora dels directoris d'habilitats {{source}}: {{path}}" } } diff --git a/src/i18n/locales/de/skills.json b/src/i18n/locales/de/skills.json index 1093bcc1f0..9ce73e11cf 100644 --- a/src/i18n/locales/de/skills.json +++ b/src/i18n/locales/de/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Skill \"{{name}}\" nicht gefunden", "container_skill_read_only": "Skill \"{{name}}\" stammt aus einem per Symlink eingebundenen Skills-Ordner ({{path}}) und kann hier nicht verschoben oder gelöscht werden. Ändere ihn in seinem Quellordner.", "symlink_escapes_skill": "Skill kann nicht verschoben werden: Der Symlink {{link}} zeigt aus dem Skill-Ordner heraus und würde am neuen Ort nicht mehr funktionieren.", - "move_restore_failed": "Das Verschieben des Skills ist fehlgeschlagen ({{error}}) und der ursprüngliche Ordner konnte nicht nach {{path}} wiederhergestellt werden. Dein Skill ist in {{backupPath}} sicher; verschiebe ihn manuell zurück." + "move_restore_failed": "Das Verschieben des Skills ist fehlgeschlagen ({{error}}) und der ursprüngliche Ordner konnte nicht nach {{path}} wiederhergestellt werden. Dein Skill ist in {{backupPath}} sicher; verschiebe ihn manuell zurück.", + "outside_skills_root": "SKILL.md kann nicht außerhalb der {{source}}-Skill-Verzeichnisse aktualisiert werden: {{path}}" } } diff --git a/src/i18n/locales/en/skills.json b/src/i18n/locales/en/skills.json index 78c708e93e..ea1f96fa59 100644 --- a/src/i18n/locales/en/skills.json +++ b/src/i18n/locales/en/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Skill \"{{name}}\" not found", "container_skill_read_only": "Skill \"{{name}}\" comes from a symlinked skills folder ({{path}}) and can't be moved or deleted here. Change it in its source folder.", "symlink_escapes_skill": "Can't move the skill: the symlink {{link}} points outside the skill folder and would break at the new location.", - "move_restore_failed": "Moving the skill failed ({{error}}) and its original folder couldn't be restored to {{path}}. Your skill is safe in {{backupPath}}; move it back manually." + "move_restore_failed": "Moving the skill failed ({{error}}) and its original folder couldn't be restored to {{path}}. Your skill is safe in {{backupPath}}; move it back manually.", + "outside_skills_root": "Refusing to update SKILL.md outside the {{source}} skills directories: {{path}}" } } diff --git a/src/i18n/locales/es/skills.json b/src/i18n/locales/es/skills.json index cb8a821a00..7129854959 100644 --- a/src/i18n/locales/es/skills.json +++ b/src/i18n/locales/es/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "No se encontró la habilidad \"{{name}}\"", "container_skill_read_only": "La habilidad \"{{name}}\" proviene de una carpeta de habilidades enlazada simbólicamente ({{path}}) y no se puede mover ni eliminar aquí. Cámbiala en su carpeta de origen.", "symlink_escapes_skill": "No se puede mover la habilidad: el enlace simbólico {{link}} apunta fuera de la carpeta de la habilidad y se rompería en la nueva ubicación.", - "move_restore_failed": "No se pudo mover el skill ({{error}}) y su carpeta original no se pudo restaurar en {{path}}. Tu skill está a salvo en {{backupPath}}; muévelo de vuelta manualmente." + "move_restore_failed": "No se pudo mover el skill ({{error}}) y su carpeta original no se pudo restaurar en {{path}}. Tu skill está a salvo en {{backupPath}}; muévelo de vuelta manualmente.", + "outside_skills_root": "No se puede actualizar SKILL.md fuera de los directorios de habilidades {{source}}: {{path}}" } } diff --git a/src/i18n/locales/fr/skills.json b/src/i18n/locales/fr/skills.json index a013c2b1e2..fb4b08d94a 100644 --- a/src/i18n/locales/fr/skills.json +++ b/src/i18n/locales/fr/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Compétence \"{{name}}\" introuvable", "container_skill_read_only": "La compétence \"{{name}}\" provient d'un dossier de compétences lié par un lien symbolique ({{path}}) et ne peut pas être déplacée ni supprimée ici. Modifie-la dans son dossier source.", "symlink_escapes_skill": "Impossible de déplacer la compétence : le lien symbolique {{link}} pointe hors du dossier de la compétence et serait cassé au nouvel emplacement.", - "move_restore_failed": "Le déplacement du skill a échoué ({{error}}) et son dossier d'origine n'a pas pu être restauré dans {{path}}. Ton skill est en sécurité dans {{backupPath}} ; remets-le en place manuellement." + "move_restore_failed": "Le déplacement du skill a échoué ({{error}}) et son dossier d'origine n'a pas pu être restauré dans {{path}}. Ton skill est en sécurité dans {{backupPath}} ; remets-le en place manuellement.", + "outside_skills_root": "Impossible de mettre à jour SKILL.md en dehors des dossiers de compétences {{source}} : {{path}}" } } diff --git a/src/i18n/locales/hi/skills.json b/src/i18n/locales/hi/skills.json index 66e06d81df..9cdc711929 100644 --- a/src/i18n/locales/hi/skills.json +++ b/src/i18n/locales/hi/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "स्किल \"{{name}}\" नहीं मिला", "container_skill_read_only": "स्किल \"{{name}}\" एक सिमलिंक किए गए स्किल फ़ोल्डर ({{path}}) से आता है और इसे यहाँ से न तो हटाया जा सकता है और न ही स्थानांतरित किया जा सकता है। इसे इसके मूल फ़ोल्डर में बदलें।", "symlink_escapes_skill": "स्किल स्थानांतरित नहीं किया जा सकता: सिमलिंक {{link}} स्किल फ़ोल्डर के बाहर इंगित करता है और नए स्थान पर टूट जाएगा।", - "move_restore_failed": "स्किल को मूव करना विफल रहा ({{error}}) और उसका मूल फ़ोल्डर {{path}} पर वापस नहीं लाया जा सका। तुम्हारी स्किल {{backupPath}} में सुरक्षित है; उसे मैन्युअल रूप से वापस ले जाओ।" + "move_restore_failed": "स्किल को मूव करना विफल रहा ({{error}}) और उसका मूल फ़ोल्डर {{path}} पर वापस नहीं लाया जा सका। तुम्हारी स्किल {{backupPath}} में सुरक्षित है; उसे मैन्युअल रूप से वापस ले जाओ।", + "outside_skills_root": "{{source}} स्किल निर्देशिकाओं के बाहर SKILL.md को अपडेट करने से मना किया गया: {{path}}" } } diff --git a/src/i18n/locales/id/skills.json b/src/i18n/locales/id/skills.json index a7616aed1d..aa179c32b1 100644 --- a/src/i18n/locales/id/skills.json +++ b/src/i18n/locales/id/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Skill \"{{name}}\" tidak ditemukan", "container_skill_read_only": "Skill \"{{name}}\" berasal dari folder skill yang di-symlink ({{path}}) dan tidak bisa dipindahkan atau dihapus di sini. Ubah di folder sumbernya.", "symlink_escapes_skill": "Tidak bisa memindahkan skill: symlink {{link}} mengarah ke luar folder skill dan akan rusak di lokasi baru.", - "move_restore_failed": "Gagal memindahkan skill ({{error}}) dan folder aslinya tidak dapat dipulihkan ke {{path}}. Skill kamu aman di {{backupPath}}; pindahkan kembali secara manual." + "move_restore_failed": "Gagal memindahkan skill ({{error}}) dan folder aslinya tidak dapat dipulihkan ke {{path}}. Skill kamu aman di {{backupPath}}; pindahkan kembali secara manual.", + "outside_skills_root": "Menolak memperbarui SKILL.md di luar direktori skill {{source}}: {{path}}" } } diff --git a/src/i18n/locales/it/skills.json b/src/i18n/locales/it/skills.json index e34c1055b5..8a69e28627 100644 --- a/src/i18n/locales/it/skills.json +++ b/src/i18n/locales/it/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Skill \"{{name}}\" non trovata", "container_skill_read_only": "La skill \"{{name}}\" proviene da una cartella di skill collegata tramite symlink ({{path}}) e non può essere spostata o eliminata qui. Modificala nella sua cartella di origine.", "symlink_escapes_skill": "Impossibile spostare la skill: il symlink {{link}} punta fuori dalla cartella della skill e non funzionerebbe nella nuova posizione.", - "move_restore_failed": "Lo spostamento della skill non è riuscito ({{error}}) e la cartella originale non è stata ripristinata in {{path}}. La tua skill è al sicuro in {{backupPath}}; spostala indietro manualmente." + "move_restore_failed": "Lo spostamento della skill non è riuscito ({{error}}) e la cartella originale non è stata ripristinata in {{path}}. La tua skill è al sicuro in {{backupPath}}; spostala indietro manualmente.", + "outside_skills_root": "Impossibile aggiornare SKILL.md al di fuori delle cartelle delle skill {{source}}: {{path}}" } } diff --git a/src/i18n/locales/ja/skills.json b/src/i18n/locales/ja/skills.json index c70cf80959..ab67fd5b1e 100644 --- a/src/i18n/locales/ja/skills.json +++ b/src/i18n/locales/ja/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "スキル「{{name}}」が見つかりません", "container_skill_read_only": "スキル「{{name}}」はシンボリックリンクされたスキルフォルダー({{path}})にあるため、ここでは移動も削除もできません。元のフォルダーで変更してください。", "symlink_escapes_skill": "スキルを移動できません:シンボリックリンク {{link}} がスキルフォルダーの外を指しているため、新しい場所では壊れてしまいます。", - "move_restore_failed": "スキルの移動に失敗し({{error}})、元のフォルダーを {{path}} に復元できませんでした。スキルは {{backupPath}} に安全に保存されています。手動で元に戻してください。" + "move_restore_failed": "スキルの移動に失敗し({{error}})、元のフォルダーを {{path}} に復元できませんでした。スキルは {{backupPath}} に安全に保存されています。手動で元に戻してください。", + "outside_skills_root": "{{source}} スキルディレクトリの外にある SKILL.md は更新できません:{{path}}" } } diff --git a/src/i18n/locales/ko/skills.json b/src/i18n/locales/ko/skills.json index ee78643b2b..bef5bdff56 100644 --- a/src/i18n/locales/ko/skills.json +++ b/src/i18n/locales/ko/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "스킬 \"{{name}}\"을(를) 찾을 수 없습니다", "container_skill_read_only": "스킬 \"{{name}}\"은(는) 심볼릭 링크된 스킬 폴더({{path}})에 있어 여기서 이동하거나 삭제할 수 없습니다. 원본 폴더에서 변경하세요.", "symlink_escapes_skill": "스킬을 이동할 수 없습니다: 심볼릭 링크 {{link}}이(가) 스킬 폴더 바깥을 가리키므로 새 위치에서 깨집니다.", - "move_restore_failed": "스킬 이동에 실패했고({{error}}) 원래 폴더를 {{path}}(으)로 복원하지 못했습니다. 스킬은 {{backupPath}}에 안전하게 있으니 직접 다시 옮겨 주세요." + "move_restore_failed": "스킬 이동에 실패했고({{error}}) 원래 폴더를 {{path}}(으)로 복원하지 못했습니다. 스킬은 {{backupPath}}에 안전하게 있으니 직접 다시 옮겨 주세요.", + "outside_skills_root": "{{source}} 스킬 디렉터리 밖의 SKILL.md는 업데이트할 수 없습니다: {{path}}" } } diff --git a/src/i18n/locales/nl/skills.json b/src/i18n/locales/nl/skills.json index 05a17f9768..6609ba44b8 100644 --- a/src/i18n/locales/nl/skills.json +++ b/src/i18n/locales/nl/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Vaardigheid \"{{name}}\" niet gevonden", "container_skill_read_only": "Vaardigheid \"{{name}}\" komt uit een via symlink gekoppelde vaardighedenmap ({{path}}) en kan hier niet worden verplaatst of verwijderd. Wijzig hem in de bronmap.", "symlink_escapes_skill": "Kan de vaardigheid niet verplaatsen: de symlink {{link}} wijst naar buiten de vaardighedenmap en zou op de nieuwe locatie niet meer werken.", - "move_restore_failed": "Het verplaatsen van de skill is mislukt ({{error}}) en de oorspronkelijke map kon niet worden hersteld naar {{path}}. Je skill staat veilig in {{backupPath}}; zet hem handmatig terug." + "move_restore_failed": "Het verplaatsen van de skill is mislukt ({{error}}) en de oorspronkelijke map kon niet worden hersteld naar {{path}}. Je skill staat veilig in {{backupPath}}; zet hem handmatig terug.", + "outside_skills_root": "Kan SKILL.md niet bijwerken buiten de {{source}}-vaardighedensmappen: {{path}}" } } diff --git a/src/i18n/locales/pl/skills.json b/src/i18n/locales/pl/skills.json index 0e583164b5..1c506e8671 100644 --- a/src/i18n/locales/pl/skills.json +++ b/src/i18n/locales/pl/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Nie znaleziono umiejętności \"{{name}}\"", "container_skill_read_only": "Umiejętność \"{{name}}\" pochodzi z folderu umiejętności podłączonego dowiązaniem symbolicznym ({{path}}) i nie można jej tutaj przenieść ani usunąć. Zmień ją w folderze źródłowym.", "symlink_escapes_skill": "Nie można przenieść umiejętności: dowiązanie symboliczne {{link}} wskazuje poza folder umiejętności i przestałoby działać w nowej lokalizacji.", - "move_restore_failed": "Przeniesienie skilla nie powiodło się ({{error}}), a oryginalnego folderu nie udało się przywrócić do {{path}}. Twój skill jest bezpieczny w {{backupPath}}; przenieś go z powrotem ręcznie." + "move_restore_failed": "Przeniesienie skilla nie powiodło się ({{error}}), a oryginalnego folderu nie udało się przywrócić do {{path}}. Twój skill jest bezpieczny w {{backupPath}}; przenieś go z powrotem ręcznie.", + "outside_skills_root": "Nie można zaktualizować SKILL.md poza katalogami umiejętności {{source}}: {{path}}" } } diff --git a/src/i18n/locales/pt-BR/skills.json b/src/i18n/locales/pt-BR/skills.json index 1a838e6bf3..a9d143b2c6 100644 --- a/src/i18n/locales/pt-BR/skills.json +++ b/src/i18n/locales/pt-BR/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Habilidade \"{{name}}\" não encontrada", "container_skill_read_only": "A habilidade \"{{name}}\" vem de uma pasta de habilidades vinculada por link simbólico ({{path}}) e não pode ser movida nem excluída aqui. Altere-a na pasta de origem.", "symlink_escapes_skill": "Não é possível mover a habilidade: o link simbólico {{link}} aponta para fora da pasta da habilidade e quebraria no novo local.", - "move_restore_failed": "Falha ao mover a skill ({{error}}) e a pasta original não pôde ser restaurada em {{path}}. Sua skill está segura em {{backupPath}}; mova-a de volta manualmente." + "move_restore_failed": "Falha ao mover a skill ({{error}}) e a pasta original não pôde ser restaurada em {{path}}. Sua skill está segura em {{backupPath}}; mova-a de volta manualmente.", + "outside_skills_root": "Não é possível atualizar o SKILL.md fora das pastas de habilidades {{source}}: {{path}}" } } diff --git a/src/i18n/locales/ru/skills.json b/src/i18n/locales/ru/skills.json index 18ceff9470..f4cdcead37 100644 --- a/src/i18n/locales/ru/skills.json +++ b/src/i18n/locales/ru/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Навык \"{{name}}\" не найден", "container_skill_read_only": "Навык \"{{name}}\" находится в папке навыков, подключённой через символическую ссылку ({{path}}), и его нельзя переместить или удалить здесь. Измени его в исходной папке.", "symlink_escapes_skill": "Не удалось переместить навык: символическая ссылка {{link}} указывает за пределы папки навыка и сломается в новом месте.", - "move_restore_failed": "Не удалось переместить навык ({{error}}), и исходную папку не получилось восстановить в {{path}}. Твой навык в безопасности в {{backupPath}}; верни его вручную." + "move_restore_failed": "Не удалось переместить навык ({{error}}), и исходную папку не получилось восстановить в {{path}}. Твой навык в безопасности в {{backupPath}}; верни его вручную.", + "outside_skills_root": "Нельзя обновить SKILL.md вне каталогов навыков {{source}}: {{path}}" } } diff --git a/src/i18n/locales/tr/skills.json b/src/i18n/locales/tr/skills.json index 0235bd8c19..6b5f4c1441 100644 --- a/src/i18n/locales/tr/skills.json +++ b/src/i18n/locales/tr/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "\"{{name}}\" becerisi bulunamadı", "container_skill_read_only": "\"{{name}}\" becerisi sembolik bağlantılı bir beceri klasöründen ({{path}}) geliyor ve burada taşınamaz veya silinemez. Kaynak klasöründe değiştir.", "symlink_escapes_skill": "Beceri taşınamıyor: {{link}} sembolik bağlantısı beceri klasörünün dışını gösteriyor ve yeni konumda bozulur.", - "move_restore_failed": "Skill taşınamadı ({{error}}) ve orijinal klasörü {{path}} konumuna geri yüklenemedi. Skill'in {{backupPath}} içinde güvende; onu elle geri taşı." + "move_restore_failed": "Skill taşınamadı ({{error}}) ve orijinal klasörü {{path}} konumuna geri yüklenemedi. Skill'in {{backupPath}} içinde güvende; onu elle geri taşı.", + "outside_skills_root": "{{source}} beceri klasörlerinin dışındaki SKILL.md güncellenemez: {{path}}" } } diff --git a/src/i18n/locales/vi/skills.json b/src/i18n/locales/vi/skills.json index 8c15253dbb..aaf358bcf3 100644 --- a/src/i18n/locales/vi/skills.json +++ b/src/i18n/locales/vi/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "Không tìm thấy kỹ năng \"{{name}}\"", "container_skill_read_only": "Kỹ năng \"{{name}}\" đến từ một thư mục kỹ năng được liên kết tượng trưng ({{path}}) nên không thể di chuyển hoặc xóa ở đây. Hãy thay đổi nó trong thư mục nguồn.", "symlink_escapes_skill": "Không thể di chuyển kỹ năng: liên kết tượng trưng {{link}} trỏ ra ngoài thư mục kỹ năng và sẽ bị hỏng ở vị trí mới.", - "move_restore_failed": "Không thể di chuyển skill ({{error}}) và không thể khôi phục thư mục gốc về {{path}}. Skill của bạn vẫn an toàn trong {{backupPath}}; hãy di chuyển lại thủ công." + "move_restore_failed": "Không thể di chuyển skill ({{error}}) và không thể khôi phục thư mục gốc về {{path}}. Skill của bạn vẫn an toàn trong {{backupPath}}; hãy di chuyển lại thủ công.", + "outside_skills_root": "Không thể cập nhật SKILL.md nằm ngoài các thư mục kỹ năng {{source}}: {{path}}" } } diff --git a/src/i18n/locales/zh-CN/skills.json b/src/i18n/locales/zh-CN/skills.json index 4ae1d9f960..c7a7954650 100644 --- a/src/i18n/locales/zh-CN/skills.json +++ b/src/i18n/locales/zh-CN/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "未找到技能 \"{{name}}\"", "container_skill_read_only": "技能 \"{{name}}\" 来自通过符号链接引入的技能文件夹({{path}}),无法在此移动或删除。请在其源文件夹中修改。", "symlink_escapes_skill": "无法移动技能:符号链接 {{link}} 指向技能文件夹之外,移动后会失效。", - "move_restore_failed": "移动技能失败({{error}}),且无法将原文件夹恢复到 {{path}}。你的技能安全保存在 {{backupPath}} 中,请手动将其移回。" + "move_restore_failed": "移动技能失败({{error}}),且无法将原文件夹恢复到 {{path}}。你的技能安全保存在 {{backupPath}} 中,请手动将其移回。", + "outside_skills_root": "无法更新位于 {{source}} 技能目录之外的 SKILL.md:{{path}}" } } diff --git a/src/i18n/locales/zh-TW/skills.json b/src/i18n/locales/zh-TW/skills.json index 9dd272f5a0..1c551df290 100644 --- a/src/i18n/locales/zh-TW/skills.json +++ b/src/i18n/locales/zh-TW/skills.json @@ -14,6 +14,7 @@ "skill_not_found": "找不到技能「{{name}}」", "container_skill_read_only": "技能「{{name}}」來自透過符號連結引入的技能資料夾({{path}}),無法在此移動或刪除。請在其來源資料夾中修改。", "symlink_escapes_skill": "無法移動技能:符號連結 {{link}} 指向技能資料夾之外,移動後會失效。", - "move_restore_failed": "移動技能失敗({{error}}),且無法將原資料夾還原到 {{path}}。你的技能安全保存在 {{backupPath}} 中,請手動將其移回。" + "move_restore_failed": "移動技能失敗({{error}}),且無法將原資料夾還原到 {{path}}。你的技能安全保存在 {{backupPath}} 中,請手動將其移回。", + "outside_skills_root": "無法更新位於 {{source}} 技能目錄之外的 SKILL.md:{{path}}" } } diff --git a/src/services/skills/SkillsManager.ts b/src/services/skills/SkillsManager.ts index 09809a9bcc..e0ba8c6922 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 { @@ -58,8 +94,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 @@ -74,14 +115,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(() => {}) + } + }) + } + } } /** @@ -109,6 +225,7 @@ export class SkillsManager { containerSkillPaths: new Set(), containers: new Map(), failedPaths: [], + diagnostics: [], } const skillsDirs = await this.getSkillsDirectories() @@ -149,6 +266,7 @@ export class SkillsManager { this.skills = pass.skills this.containerSkillPaths = pass.containerSkillPaths this.containers = pass.containers + this.diagnostics = pass.diagnostics } /** @@ -316,8 +434,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 +547,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. @@ -503,6 +681,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() } @@ -554,6 +736,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) @@ -602,8 +883,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 @@ -611,28 +893,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() @@ -922,6 +1214,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 @@ -944,24 +1256,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 } = parseFrontmatter(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 } = parseFrontmatter(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({ content: 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({ content: 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() @@ -1052,6 +1401,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 @@ -1091,6 +1441,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) @@ -1142,6 +1493,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()) @@ -1152,3 +1508,6 @@ Add your skill instructions here. this.rootRealPaths.clear() } } + + + diff --git a/src/services/skills/__tests__/SkillsManager.spec.ts b/src/services/skills/__tests__/SkillsManager.spec.ts index c5fad85a24..4f02752ec7 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 { @@ -19,6 +20,7 @@ const { mockLstat, mockSymlink, mockUnlink, + mockChmod, } = vi.hoisted(() => ({ mockReadlink: vi.fn(), mockCp: vi.fn(), @@ -37,6 +39,7 @@ const { mockRmdir: vi.fn(), mockSymlink: vi.fn(), mockUnlink: vi.fn(), + mockChmod: vi.fn(), })) // Platform-agnostic test paths @@ -72,6 +75,7 @@ vi.mock("fs/promises", () => ({ readlink: mockReadlink, symlink: mockSymlink, unlink: mockUnlink, + chmod: mockChmod, }, stat: mockStat, readFile: mockReadFile, @@ -87,6 +91,7 @@ vi.mock("fs/promises", () => ({ readlink: mockReadlink, symlink: mockSymlink, unlink: mockUnlink, + chmod: mockChmod, })) // Mock os module @@ -94,6 +99,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: { @@ -132,6 +151,7 @@ vi.mock("../../../i18n", () => ({ "skills:errors.already_exists": `Skill "${params?.name}" already exists at ${params?.path}`, "skills:errors.not_found": `Skill "${params?.name}" not found in ${params?.source}${params?.modeInfo}`, "skills:errors.move_restore_failed": `Moving the skill failed (${params?.error}) and its original folder couldn't be restored to ${params?.path}. Your skill is safe in ${params?.backupPath}; move it back manually.`, + "skills:errors.outside_skills_root": `Refusing to update SKILL.md outside the ${params?.source} skills directories: ${params?.path}`, } return translations[key] || key }, @@ -194,11 +214,16 @@ describe("SkillsManager", () => { vi.stubGlobal("frontmatterExecuted", executed) try { await skillsManager.updateSkillModes("example", "project", ["code"]) - expect(mockWriteFile).toHaveBeenCalledWith( - p(skillDir, "SKILL.md"), - expect.stringContaining(instructions), - "utf-8", - ) + // The publish is atomic: the payload is staged as .SKILL.md.