Skip to content

Commit 2caa450

Browse files
committed
Implement symlinks for skills
1 parent 2baac5e commit 2caa450

2 files changed

Lines changed: 950 additions & 20 deletions

File tree

‎src/services/skills/SkillsManager.ts‎

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

21+
// Direct children (new skill folders or container symlinks) and their SKILL.md files.
22+
const SKILLS_WATCH_PATTERN = "{*,*/SKILL.md}"
23+
2124
export class SkillsManager {
2225
private skills: Map<string, SkillMetadata> = new Map()
2326
private providerRef: WeakRef<ClineProvider>
2427
private disposables: vscode.Disposable[] = []
28+
// Keyed by container real path. VS Code watchers don't follow symlinks.
29+
private containerWatchers: Map<string, vscode.Disposable> = new Map()
2530
private isDisposed = false
2631

2732
constructor(provider: ClineProvider) {
@@ -39,23 +44,38 @@ export class SkillsManager {
3944
* Also supports symlinks:
4045
* - .roo/skills can be a symlink to a directory containing skill subdirectories
4146
* - .roo/skills/[dirname] can be a symlink to a skill directory
47+
* - .roo/skills/[dirname] can be a symlink to a container of skill directories
4248
*/
4349
async discoverSkills(): Promise<void> {
4450
this.skills.clear()
51+
const containers = new Set<string>()
4552
const skillsDirs = await this.getSkillsDirectories()
4653

4754
for (const { dir, source, mode } of skillsDirs) {
48-
await this.scanSkillsDirectory(dir, source, mode)
55+
await this.scanSkillsDirectory(dir, source, mode, containers)
4956
}
57+
58+
this.syncContainerWatchers(containers)
5059
}
5160

5261
/**
5362
* Scan a skills directory for skill subdirectories.
54-
* Handles two symlink cases:
63+
* Handles symlink cases:
5564
* 1. The skills directory itself is a symlink (resolved by directoryExists using realpath)
5665
* 2. Individual skill subdirectories are symlinks
66+
* 3. Symlinked container of skills (e.g., .roo/skills/shared -> /repo/skills).
67+
* Only symlinks are treated as containers, and only one level deep.
68+
*
69+
* On name collisions the last loaded skill wins. Containers are loaded first
70+
* in reverse order, so direct skills win over container skills, and the
71+
* alphabetically first container wins over the others.
5772
*/
58-
private async scanSkillsDirectory(dirPath: string, source: "global" | "project", mode?: string): Promise<void> {
73+
private async scanSkillsDirectory(
74+
dirPath: string,
75+
source: "global" | "project",
76+
mode: string | undefined,
77+
containers: Set<string> = new Set<string>(),
78+
): Promise<void> {
5979
if (!(await directoryExists(dirPath))) {
6080
return
6181
}
@@ -64,8 +84,11 @@ export class SkillsManager {
6484
// Get the real path (resolves if dirPath is a symlink)
6585
const realDirPath = await fs.realpath(dirPath)
6686

67-
// Read directory entries
68-
const entries = await fs.readdir(realDirPath)
87+
// Sorted so collision handling doesn't depend on filesystem order
88+
const entries = [...(await fs.readdir(realDirPath))].sort()
89+
90+
const directSkills: string[] = []
91+
const containerPaths: string[] = []
6992

7093
for (const entryName of entries) {
7194
const entryPath = path.join(realDirPath, entryName)
@@ -74,14 +97,64 @@ export class SkillsManager {
7497
const stats = await fs.stat(entryPath).catch(() => null)
7598
if (!stats?.isDirectory()) continue
7699

77-
// Load skill metadata - the skill name comes from the entry name (symlink name if symlinked)
78-
await this.loadSkillMetadata(entryPath, source, mode, entryName)
100+
if (await fileExists(path.join(entryPath, "SKILL.md"))) {
101+
directSkills.push(entryName)
102+
} else if (await this.isSymlink(entryPath)) {
103+
containerPaths.push(entryPath)
104+
}
105+
}
106+
107+
for (const containerPath of containerPaths.reverse()) {
108+
await this.scanSkillContainer(containerPath, source, mode, containers)
109+
}
110+
111+
for (const entryName of directSkills) {
112+
// The skill name comes from the entry name (symlink name if symlinked)
113+
await this.loadSkillMetadata(path.join(realDirPath, entryName), source, mode, entryName)
79114
}
80115
} catch {
81116
// Directory doesn't exist or can't be read - this is fine
82117
}
83118
}
84119

120+
private async scanSkillContainer(
121+
containerPath: string,
122+
source: "global" | "project",
123+
mode: string | undefined,
124+
containers: Set<string>,
125+
): Promise<void> {
126+
try {
127+
const realContainerPath = await fs.realpath(containerPath)
128+
containers.add(realContainerPath)
129+
130+
const entries = [...(await fs.readdir(realContainerPath))].sort()
131+
for (const entryName of entries) {
132+
const entryPath = path.join(realContainerPath, entryName)
133+
134+
let isDirectory = false
135+
try {
136+
isDirectory = (await fs.stat(entryPath)).isDirectory()
137+
} catch (error) {
138+
console.error(`Failed to stat skill entry ${entryPath} in container ${containerPath}:`, error)
139+
}
140+
if (!isDirectory) continue
141+
142+
await this.loadSkillMetadata(entryPath, source, mode, entryName)
143+
}
144+
} catch (error) {
145+
console.error(`Failed to scan skills container ${containerPath}:`, error)
146+
}
147+
}
148+
149+
private async isSymlink(entryPath: string): Promise<boolean> {
150+
try {
151+
return (await fs.lstat(entryPath)).isSymbolicLink()
152+
} catch (error) {
153+
console.error(`Failed to check whether ${entryPath} is a symlink:`, error)
154+
return false
155+
}
156+
}
157+
85158
/**
86159
* Load skill metadata from a skill directory.
87160
* @param skillDir - The resolved path to the skill directory (target of symlink if symlinked)
@@ -484,10 +557,10 @@ Add your skill instructions here.
484557
baseDir = path.join(provider.cwd, ".roo")
485558
}
486559

487-
// Determine source and destination directories
488-
const sourceDirName = currentMode ? `skills-${currentMode}` : "skills"
560+
// Determine source and destination directories. The source comes from the
561+
// discovered path since skills from containers live outside skills/.
489562
const destDirName = newMode ? `skills-${newMode}` : "skills"
490-
const sourceDir = path.join(baseDir, sourceDirName, name)
563+
const sourceDir = path.dirname(skill.path)
491564
const destSkillsDir = path.join(baseDir, destDirName)
492565
const destDir = path.join(destSkillsDir, name)
493566
const destSkillMdPath = path.join(destDir, "SKILL.md")
@@ -500,15 +573,18 @@ Add your skill instructions here.
500573
// Ensure destination skills directory exists
501574
await fs.mkdir(destSkillsDir, { recursive: true })
502575

503-
// Move the skill directory
504-
await fs.rename(sourceDir, destDir)
576+
// Move the skill directory (falls back to copy+remove across filesystems)
577+
await this.moveDirectory(sourceDir, destDir)
505578

506-
// Clean up empty source skills directory
507-
const sourceSkillsDir = path.join(baseDir, sourceDirName)
579+
// Clean up empty source skills directory. Skip it if it's a symlink or the
580+
// skill came from a container, so we never leave dangling symlinks.
581+
const sourceRoot = path.join(baseDir, currentMode ? `skills-${currentMode}` : "skills")
508582
try {
509-
const entries = await fs.readdir(sourceSkillsDir)
510-
if (entries.length === 0) {
511-
await fs.rmdir(sourceSkillsDir)
583+
if (!(await this.isSymlink(sourceRoot)) && path.dirname(sourceDir) === (await fs.realpath(sourceRoot))) {
584+
const entries = await fs.readdir(sourceRoot)
585+
if (entries.length === 0) {
586+
await fs.rmdir(sourceRoot)
587+
}
512588
}
513589
} catch {
514590
// Ignore errors - directory might not exist or have permission issues
@@ -518,6 +594,84 @@ Add your skill instructions here.
518594
await this.discoverSkills()
519595
}
520596

597+
/**
598+
* Rename a directory, falling back to copy + delete across filesystems
599+
* (a container may be on another device).
600+
*
601+
* The fallback keeps the skill at exactly one discoverable location at every step:
602+
* 1. Copy the source into a hidden staging dir next to destDir (dest filesystem).
603+
* 2. Atomically rename the source aside to a hidden trash dir (source filesystem).
604+
* 3. Atomically promote staging to destDir. On failure, restore the source from trash.
605+
* 4. Best-effort delete of the trash dir. The move is already committed, so a
606+
* failure here is logged instead of thrown and never leaves a duplicate skill.
607+
*/
608+
private async moveDirectory(sourceDir: string, destDir: string): Promise<void> {
609+
try {
610+
await fs.rename(sourceDir, destDir)
611+
return
612+
} catch (error) {
613+
if ((error as NodeJS.ErrnoException)?.code !== "EXDEV") {
614+
throw error
615+
}
616+
}
617+
618+
const suffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
619+
const stagingDir = path.join(path.dirname(destDir), `.${path.basename(destDir)}.moving-${suffix}`)
620+
const trashDir = path.join(path.dirname(sourceDir), `.${path.basename(sourceDir)}.removing-${suffix}`)
621+
let sourceMovedAside = false
622+
623+
try {
624+
// verbatimSymlinks: otherwise relative links get rewritten to point into the deleted source
625+
await fs.cp(sourceDir, stagingDir, {
626+
recursive: true,
627+
errorOnExist: true,
628+
force: false,
629+
verbatimSymlinks: true,
630+
})
631+
632+
const destExists = await fs.lstat(destDir).then(
633+
() => true,
634+
(error: NodeJS.ErrnoException) => {
635+
if (error?.code === "ENOENT") {
636+
return false
637+
}
638+
throw error
639+
},
640+
)
641+
if (destExists) {
642+
throw Object.assign(new Error(`Destination already exists: ${destDir}`), { code: "EEXIST" })
643+
}
644+
645+
// Same parent directory, so this is atomic and cannot fail with EXDEV
646+
await fs.rename(sourceDir, trashDir)
647+
sourceMovedAside = true
648+
649+
await fs.rename(stagingDir, destDir)
650+
} catch (moveError) {
651+
if (sourceMovedAside) {
652+
try {
653+
await fs.rename(trashDir, sourceDir)
654+
} catch (restoreError) {
655+
// Keep the trash dir so the original content is never lost
656+
console.error(
657+
`Failed to restore skill directory ${sourceDir} from ${trashDir} after a failed move:`,
658+
restoreError,
659+
)
660+
}
661+
}
662+
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
663+
throw moveError
664+
}
665+
666+
// The move is committed and the source is no longer discoverable under its
667+
// original name, so leftover trash must not turn a successful move into an error.
668+
try {
669+
await fs.rm(trashDir, { recursive: true, force: true })
670+
} catch (cleanupError) {
671+
console.error(`Failed to remove moved skill's old directory ${trashDir}:`, cleanupError)
672+
}
673+
}
674+
521675
/**
522676
* Update the mode associations for a skill by modifying its SKILL.md frontmatter.
523677
* @param name - Skill name
@@ -685,11 +839,37 @@ Add your skill instructions here.
685839
}
686840

687841
private watchDirectory(dirPath: string): void {
842+
const watcher = this.createSkillsWatcher(dirPath)
843+
if (watcher) {
844+
this.disposables.push(watcher)
845+
}
846+
}
847+
848+
private syncContainerWatchers(containers: Set<string>): void {
849+
for (const [containerPath, watcher] of this.containerWatchers) {
850+
if (this.isDisposed || !containers.has(containerPath)) {
851+
watcher.dispose()
852+
this.containerWatchers.delete(containerPath)
853+
}
854+
}
855+
856+
if (this.isDisposed) return
857+
858+
for (const containerPath of containers) {
859+
if (this.containerWatchers.has(containerPath)) continue
860+
const watcher = this.createSkillsWatcher(containerPath)
861+
if (watcher) {
862+
this.containerWatchers.set(containerPath, watcher)
863+
}
864+
}
865+
}
866+
867+
private createSkillsWatcher(dirPath: string): vscode.Disposable | undefined {
688868
if (process.env.NODE_ENV === "test" || !vscode.workspace.createFileSystemWatcher) {
689-
return
869+
return undefined
690870
}
691871

692-
const pattern = new vscode.RelativePattern(dirPath, "**/SKILL.md")
872+
const pattern = new vscode.RelativePattern(dirPath, SKILLS_WATCH_PATTERN)
693873
const watcher = vscode.workspace.createFileSystemWatcher(pattern)
694874

695875
watcher.onDidChange(async (uri) => {
@@ -707,13 +887,15 @@ Add your skill instructions here.
707887
await this.discoverSkills()
708888
})
709889

710-
this.disposables.push(watcher)
890+
return watcher
711891
}
712892

713893
async dispose(): Promise<void> {
714894
this.isDisposed = true
715895
this.disposables.forEach((d) => d.dispose())
716896
this.disposables = []
897+
this.containerWatchers.forEach((w) => w.dispose())
898+
this.containerWatchers.clear()
717899
this.skills.clear()
718900
}
719901
}

0 commit comments

Comments
 (0)