Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(skills): discover one namespace level for local Skills

Zhang Yunjin77d7b4e3f696
diff --git a/apps/desktop/help-knowledge/skills.md b/apps/desktop/help-knowledge/skills.md
index 429e72aad1..ce5301f969 100644
--- a/apps/desktop/help-knowledge/skills.md
+++ b/apps/desktop/help-knowledge/skills.md
@@ -14,6 +14,7 @@ Skills are reusable agent capabilities you package as a folder and load into you
- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\Users\<you>\`.
- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.
- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.
+- Global and project discovery roots may also contain one namespace/container level (for example an author folder): Cindy checks each discovery root's direct children, then their direct children, and stops there. A folder with `SKILL.md` is a Skill; its child folders are skill resources, not separate Skills.
**Importing a local skill:**
@@ -44,6 +45,7 @@ Skills are reusable agent capabilities you package as a folder and load into you
- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.
- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.
+- For a Skill inside a namespace/container folder, renaming changes only the Skill's own folder name; the namespace stays the same.
- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.
- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.
- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared Skill links.
diff --git a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
index c3541786f9..fbfa2587d9 100644
--- a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
+++ b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
@@ -136,6 +136,75 @@ describe('shared Skill projection mutations', () => {
});
describe('prepareSharedGlobalSkillLinks', () => {
+ it('projects a nested namespace Skill into the Claude discovery root', async () => {
+ const root = await makeTmpDir();
+ const homeDir = path.join(root, 'home');
+ const paths = sharedGlobalSkillsPaths(homeDir);
+ const nested = path.join(paths.sharedSkillsDir, '@scope', 'nested');
+ await fs.mkdir(nested, { recursive: true });
+ await fs.writeFile(
+ path.join(nested, 'SKILL.md'),
+ '---\nname: nested\ndescription: Nested skill\n---\nBody\n',
+ 'utf8',
+ );
+
+ const result = await prepareSharedGlobalSkillLinks({ homeDir });
+
+ expect(result.changed).toBe(true);
+ expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'nested'), nested)).toBe(true);
+ });
+
+ it('resolves a project root for a nested project Skill path', () => {
+ const projectRoot = path.join(os.tmpdir(), 'cindy-nested-project-root', 'repo');
+ const skillPath = path.join(projectRoot, '.agents', 'skills', '@scope', 'nested');
+ expect(projectWorkingDirFromSkillPath(skillPath)).toBe(projectRoot);
+ });
+
+ it('does not walk generated dependency trees during projection', async () => {
+ const root = await makeTmpDir();
+ const homeDir = path.join(root, 'home');
+ const paths = sharedGlobalSkillsPaths(homeDir);
+ const direct = await writeSkill(paths.sharedSkillsDir, 'direct');
+ const generatedDirs = [
+ 'node_modules',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+ 'target',
+ '__macosx',
+ '__pycache__',
+ 'Node_Modules',
+ 'DIST',
+ ];
+ for (const generatedDir of generatedDirs) {
+ await writeSkill(paths.sharedSkillsDir, path.join(generatedDir, 'ignored'));
+ }
+
+ const result = await prepareSharedGlobalSkillLinks({ homeDir });
+
+ expect(result.changed).toBe(true);
+ expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'direct'), direct)).toBe(true);
+ for (const generatedDir of generatedDirs) {
+ await expect(fs.lstat(path.join(paths.claudeSkillsDir, generatedDir, 'ignored'))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ }
+ });
+
+ it('keeps a direct Skill whose folder name matches a pruned directory', async () => {
+ const root = await makeTmpDir();
+ const homeDir = path.join(root, 'home');
+ const paths = sharedGlobalSkillsPaths(homeDir);
+ const distSkill = await writeSkill(paths.sharedSkillsDir, 'dist');
+ await writeSkill(paths.sharedSkillsDir, path.join('node_modules', 'ignored'));
+
+ const result = await prepareSharedGlobalSkillLinks({ homeDir });
+
+ expect(result.changed).toBe(true);
+ expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'dist'), distSkill)).toBe(true);
+ });
+
it('does not pull other-agent skills into the shared index by default (opt-in gate, #2930)', async () => {
const root = await makeTmpDir();
const homeDir = path.join(root, 'home');
@@ -483,6 +552,28 @@ describe('prepareSharedProjectSkillLinks', () => {
expect(await sameRealPath(staleSharedLink, claudeSkill)).toBe(true);
});
+ it('repairs a broken absolute nested project link after the checkout moves', async () => {
+ const root = await makeTmpDir();
+ const oldWorkingDir = path.join(root, 'old-checkout');
+ const workingDir = path.join(root, 'moved-checkout');
+ const oldPaths = sharedProjectSkillsPaths(oldWorkingDir);
+ const paths = sharedProjectSkillsPaths(workingDir);
+ const claudeSkill = await writeSkill(paths.claudeSkillsDir, path.join('@scope', 'nested'));
+ const staleSharedLink = path.join(paths.sharedSkillsDir, 'nested');
+ await fs.mkdir(paths.sharedSkillsDir, { recursive: true });
+ await fs.symlink(
+ path.join(oldPaths.claudeSkillsDir, '@scope', 'nested'),
+ staleSharedLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+
+ const result = await prepareSharedProjectSkillLinks({ workingDir });
+
+ expect(result.changed).toBe(true);
+ expect(result.warnings).toEqual([]);
+ expect(await sameRealPath(staleSharedLink, claudeSkill)).toBe(true);
+ });
+
it('does not replace an unrelated broken project skill symlink', async () => {
const root = await makeTmpDir();
const workingDir = path.join(root, 'checkout');
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ba57201997..d4c5ccd333 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -265,6 +265,7 @@ import { RendererBootGuard } from './renderer-boot-guard';
import yaml from 'js-yaml';
import matter from 'gray-matter';
import type { Maker } from '@cindy/maker-core';
+import { shouldPruneSkillScanDirectory } from '@cindy/maker-core/skill-scan-limits';
import {
im,
feishuIm,
@@ -6654,7 +6655,8 @@ const registerIpcHandlers = () => {
// Scans `{workingDir}/.claude/commands/*.md` and `.claude/skills/*.md` for
// user-defined slash commands / skills (command-palette F1).
- // Returns [] if dirs don't exist. No recursion.
+ // Returns [] if dirs don't exist. Skills may have one namespace level;
+ // deeper directories are not scanned.
ipcMain.handle(
'workspace:scan-slash-commands',
async (
@@ -6732,17 +6734,32 @@ const registerIpcHandlers = () => {
dirPath: string,
): Array<{ name: string; description?: string; source: 'user' | 'skill' }> => {
if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory()) return [];
- const entries = fs.readdirSync(dirPath, { withFileTypes: true });
const results: Array<{ name: string; description?: string; source: 'user' | 'skill' }> =
[];
- for (const ent of entries) {
- if (!ent.isDirectory() || ent.name.startsWith('.')) continue;
- // Look for SKILL.md or skill.md inside the subdirectory
- const subDir = path.join(dirPath, ent.name);
- const skillFile = ['SKILL.md', 'skill.md'].find((f) =>
- fs.existsSync(path.join(subDir, f)),
- );
- if (!skillFile) continue;
+ const isSymlinkDirectory = (target: string): boolean => {
+ try {
+ return fs.lstatSync(target).isSymbolicLink();
+ } catch {
+ return false;
+ }
+ };
+ const readEntries = (dir: string): fs.Dirent[] => {
+ try {
+ return fs.readdirSync(dir, { withFileTypes: true })
+ .sort((a, b) => a.name.localeCompare(b.name));
+ } catch {
+ return [];
+ }
+ };
+ const findSkillFile = (dir: string): string | null =>
+ ['SKILL.md', 'skill.md'].find((f) => {
+ try {
+ return fs.statSync(path.join(dir, f)).isFile();
+ } catch {
+ return false;
+ }
+ }) ?? null;
+ const addSkill = (subDir: string, name: string, skillFile: string): void => {
let description: string | undefined;
try {
const raw = fs.readFileSync(path.join(subDir, skillFile), 'utf-8');
@@ -6750,7 +6767,44 @@ const registerIpcHandlers = () => {
} catch {
/* non-fatal */
}
- results.push({ name: ent.name, description, source: 'skill' });
+ results.push({ name, description, source: 'skill' });
+ };
+
+ const namespaces: Array<{ name: string; path: string }> = [];
+ for (const ent of readEntries(dirPath)) {
+ if (ent.name.startsWith('.') || /\.bak\.\d+$/.test(ent.name)) continue;
+ const subDir = path.join(dirPath, ent.name);
+ let stat: fs.Stats;
+ try {
+ stat = fs.statSync(subDir);
+ } catch {
+ continue;
+ }
+ if (!stat.isDirectory()) continue;
+ // Dirent can report a Windows junction as a directory; lstat keeps
+ // the no-recursive-symlink guarantee consistent across platforms.
+ const isSymlink = ent.isSymbolicLink() || isSymlinkDirectory(subDir);
+ const skillFile = findSkillFile(subDir);
+ if (skillFile) {
+ addSkill(subDir, ent.name, skillFile);
+ continue;
+ }
+ // Direct symlinked Skills are handled above; do not walk a symlinked namespace.
+ if (isSymlink || shouldPruneSkillScanDirectory(ent.name)) continue;
+ namespaces.push({ name: ent.name, path: subDir });
+ }
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ // Direct Skills win over a same-name nested Skill regardless of
+ // namespace ordering.
+ for (const namespace of namespaces) {
+ for (const nested of readEntries(namespace.path)) {
+ if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue;
+ if (results.some((result) => result.name === nested.name)) continue;
+ const nestedDir = path.join(namespace.path, nested.name);
+ const nestedSkillFile = findSkillFile(nestedDir);
+ if (nestedSkillFile) addSkill(nestedDir, nested.name, nestedSkillFile);
+ }
}
return results;
};
diff --git a/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts b/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
index d06371fad4..79919f63da 100644
--- a/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
@@ -100,6 +100,69 @@ describe('listInstalledSkills — symlink 跟随', () => {
}
});
+ it('includes one namespace level and stops at the third level', async () => {
+ const fs = await import('node:fs');
+ const path = await import('node:path');
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'learn-skills-idx-nested-'));
+ const root = path.join(tmpHome, '.agents', 'skills');
+ const nested = path.join(root, '@scope', 'nested');
+ const lower = path.join(root, '@scope', 'lower');
+ const tooDeep = path.join(root, '@scope', 'group', 'too-deep');
+ const backup = path.join(root, '@scope', 'backup.bak.1', 'ignored');
+ for (const skillDir of [nested, tooDeep, backup]) {
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ `---\nname: ${path.basename(skillDir)}\ndescription: nested\n---\nBody`,
+ 'utf8',
+ );
+ }
+ fs.mkdirSync(lower, { recursive: true });
+ fs.writeFileSync(
+ path.join(lower, 'skill.md'),
+ '---\nname: lower\ndescription: lower-case manifest\n---\nBody',
+ 'utf8',
+ );
+
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
+ try {
+ const { listInstalledSkills } = await import('../skillsIndex');
+ const { entries } = await listInstalledSkills();
+ expect(entries.map((entry) => entry.name).sort()).toEqual(['lower', 'nested']);
+ expect(entries.find((entry) => entry.name === 'nested')?.absolutePath).toBe(nested);
+ } finally {
+ homeSpy.mockRestore();
+ fs.rmSync(tmpHome, { recursive: true, force: true });
+ }
+ });
+
+ it('does not descend through a symlinked namespace', async () => {
+ const fs = await import('node:fs');
+ const path = await import('node:path');
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'learn-skills-idx-link-ns-'));
+ const root = path.join(tmpHome, '.agents', 'skills');
+ const externalNamespace = path.join(tmpHome, 'external-ns');
+ const nested = path.join(externalNamespace, 'nested');
+ fs.mkdirSync(nested, { recursive: true });
+ fs.writeFileSync(
+ path.join(nested, 'SKILL.md'),
+ '---\nname: linked-nested\ndescription: must not be listed\n---\nBody',
+ 'utf8',
+ );
+ fs.mkdirSync(root, { recursive: true });
+ fs.symlinkSync(externalNamespace, path.join(root, 'linked-ns'), 'junction');
+
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
+ try {
+ const { listInstalledSkills } = await import('../skillsIndex');
+ const { entries } = await listInstalledSkills();
+ expect(entries).toEqual([]);
+ } finally {
+ homeSpy.mockRestore();
+ fs.rmSync(tmpHome, { recursive: true, force: true });
+ }
+ });
+
it('redacts frontmatter metadata while scanning installed skills', async () => {
const fs = await import('node:fs');
const path = await import('node:path');
diff --git a/apps/desktop/src/main/learn-host/skillsIndex.ts b/apps/desktop/src/main/learn-host/skillsIndex.ts
index 7c2636fcdc..91c56c65e6 100644
--- a/apps/desktop/src/main/learn-host/skillsIndex.ts
+++ b/apps/desktop/src/main/learn-host/skillsIndex.ts
@@ -10,9 +10,11 @@
*/
import { promises as fs } from 'node:fs';
+import type { Dirent } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import matter from 'gray-matter';
+import { shouldPruneSkillScanDirectory } from '@cindy/maker-core/skill-scan-limits';
import { createLogger } from '../logger';
import { redactSensitive } from './redaction';
@@ -51,52 +53,97 @@ export function formatSkillsIndexBlock(entries: InstalledSkillEntry[], truncated
return `${lines.join('\n')}${tail}`;
}
+async function isDirectoryEntry(entry: Dirent, fullPath: string): Promise<boolean> {
+ if (entry.isDirectory()) return true;
+ if (!entry.isSymbolicLink()) return false;
+ try {
+ return (await fs.stat(fullPath)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+async function isSymlinkDirectory(target: string): Promise<boolean> {
+ try {
+ return (await fs.lstat(target)).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+async function findSkillMd(dir: string): Promise<string | null> {
+ for (const name of ['SKILL.md', 'skill.md']) {
+ try {
+ if ((await fs.stat(path.join(dir, name))).isFile()) return name;
+ } catch {
+ // Try the other spelling.
+ }
+ }
+ return null;
+}
+
/** 扫描全局 skill 根,读每个 SKILL.md 的 frontmatter name/description。 */
export async function listInstalledSkills(): Promise<{ entries: InstalledSkillEntry[]; truncatedCount: number }> {
const root = path.join(os.homedir(), '.agents', 'skills');
- let dirs: string[];
+ let skillTargets: Array<{ dir: string; skillFile: string }>;
try {
- const dirents = (await fs.readdir(root, { withFileTypes: true })).filter(
- (e) => !e.name.startsWith('.'),
- );
- const names: string[] = [];
- for (const e of dirents) {
- if (e.isDirectory()) {
- names.push(e.name);
+ const topLevel: Array<{ name: string; path: string; isSymlink: boolean }> = [];
+ for (const entry of await fs.readdir(root, { withFileTypes: true })) {
+ if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue;
+ const fullPath = path.join(root, entry.name);
+ if (!(await isDirectoryEntry(entry, fullPath))) continue;
+ const isSymlink = entry.isSymbolicLink()
+ || (entry.isDirectory() && await isSymlinkDirectory(fullPath));
+ topLevel.push({ name: entry.name, path: fullPath, isSymlink });
+ }
+ topLevel.sort((a, b) => a.name.localeCompare(b.name));
+
+ skillTargets = [];
+ for (const entry of topLevel) {
+ const skillFile = await findSkillMd(entry.path);
+ if (skillFile) {
+ skillTargets.push({ dir: entry.path, skillFile });
continue;
}
// 共享 skill 链接流程会把既有 Claude/Codex 全局 skill 以 symlink 形式挂进
- // 本根 —— 只认真实目录会漏掉它们,模型看不到已装清单就会蒸出近重复的新
- // skill 而不是改进原版(Codex review)。跟随链接,目标是目录即计入;
- // 后续 SKILL.md 读取本身走 follow 语义,坏链接在下方 catch 静默跳过。
- if (e.isSymbolicLink()) {
- try {
- if ((await fs.stat(path.join(root, e.name))).isDirectory()) names.push(e.name);
- } catch {
- // 悬空链接,跳过
- }
+ // 本根 —— 只认真实目录会漏掉它们。直接 symlink skill 已在上方计入;
+ // symlink namespace 不下钻,避免越界或循环。
+ if (entry.isSymlink || shouldPruneSkillScanDirectory(entry.name)) continue;
+
+ // 最多一层 namespace/author: <root>/<namespace>/<skill>。
+ let nestedEntries: Dirent[];
+ try {
+ nestedEntries = await fs.readdir(entry.path, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const nested of nestedEntries) {
+ if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue;
+ const nestedPath = path.join(entry.path, nested.name);
+ if (!(await isDirectoryEntry(nested, nestedPath))) continue;
+ const nestedSkillFile = await findSkillMd(nestedPath);
+ if (nestedSkillFile) skillTargets.push({ dir: nestedPath, skillFile: nestedSkillFile });
}
}
- dirs = names.sort();
} catch {
return { entries: [], truncatedCount: 0 };
}
const entries: InstalledSkillEntry[] = [];
let truncatedCount = 0;
- for (const dirName of dirs) {
+ for (const target of skillTargets) {
if (entries.length >= SKILLS_INDEX_MAX) {
- truncatedCount = dirs.length - SKILLS_INDEX_MAX;
+ truncatedCount = skillTargets.length - SKILLS_INDEX_MAX;
break;
}
- const skillDir = path.join(root, dirName);
+ const dirName = path.basename(target.dir);
try {
- const raw = await fs.readFile(path.join(skillDir, 'SKILL.md'), 'utf8');
+ const raw = await fs.readFile(path.join(target.dir, target.skillFile), 'utf8');
const parsed = matter(raw);
const data = parsed.data as Record<string, unknown>;
const name = redactPromptMetadata(String(data.name ?? dirName)) || dirName;
const description = redactPromptMetadata(String(data.description ?? '')).slice(0, DESC_CAP);
- entries.push({ name, description, absolutePath: skillDir });
+ entries.push({ name, description, absolutePath: target.dir });
} catch (err) {
// 无 SKILL.md / 解析失败的目录跳过(不是合法 skill)
log.debug?.('skip skill dir:', dirName, err);
diff --git a/apps/desktop/src/main/maker-host/shared-global-skills.ts b/apps/desktop/src/main/maker-host/shared-global-skills.ts
index 93caf01e62..3a7a4998b9 100644
--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts
+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts
@@ -1,6 +1,7 @@
import os from 'node:os';
import path from 'node:path';
import fs, { promises as fsp } from 'node:fs';
+import { shouldPruneSkillScanDirectory } from '@cindy/maker-core/skill-scan-limits';
type LinkStatus = 'linked' | 'kept' | 'conflict' | 'skipped' | 'error';
@@ -105,6 +106,14 @@ async function isDirectory(value: string): Promise<boolean> {
}
}
+function isSymlinkDirectory(target: string): boolean {
+ try {
+ return fs.lstatSync(target).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
async function hasSkillFile(dirPath: string): Promise<boolean> {
const candidates = ['SKILL.md', 'skill.md'];
for (const name of candidates) {
@@ -136,21 +145,13 @@ export function sharedProjectSkillsPaths(workingDir: string) {
};
}
-/** Returns the root only for a direct `<root>/.{agents,claude}/skills/<name>` child. */
+/** Returns the project root for a Skill below a `.agents`/`.claude` discovery root. */
export function projectWorkingDirFromSkillPath(skillPath: string): string | null {
- const resolved = path.resolve(skillPath);
- const skillsDir = path.dirname(resolved);
- const agentsDir = path.dirname(skillsDir);
- const equalsName = (actual: string, expected: string) =>
- process.platform === 'win32'
- ? actual.toLowerCase() === expected.toLowerCase()
- : actual === expected;
- if (!equalsName(path.basename(skillsDir), 'skills')) return null;
- const discoveryRoot = path.basename(agentsDir);
- if (!equalsName(discoveryRoot, '.agents') && !equalsName(discoveryRoot, '.claude')) {
- return null;
- }
- return path.dirname(agentsDir);
+ const normalized = path.resolve(skillPath).replace(/\\/g, '/');
+ const match = /(?:^|\/)\.(?:agents|claude)\/skills(?=\/|$)/i.exec(normalized);
+ if (!match) return null;
+ const skillsRoot = path.resolve(normalized.slice(0, (match.index ?? 0) + match[0].length));
+ return path.dirname(path.dirname(skillsRoot));
}
async function listSkillEntries(
@@ -158,38 +159,65 @@ async function listSkillEntries(
rootPath: string,
): Promise<SkillEntry[]> {
if (!(await isDirectory(rootPath))) return [];
-
- let entries;
- try {
- entries = await fsp.readdir(rootPath, { withFileTypes: true });
- } catch {
- return [];
- }
-
const skills: SkillEntry[] = [];
- for (const ent of entries.sort((a, b) => a.name.localeCompare(b.name))) {
- if (ent.name.startsWith('.')) continue;
- if (!ent.isDirectory() && !ent.isSymbolicLink()) continue;
-
- const skillPath = path.join(rootPath, ent.name);
- if (!(await hasSkillFile(skillPath))) continue;
+ const addSkill = async (skillPath: string, isSymlink: boolean): Promise<void> => {
let realPath: string;
let identity: string | null;
try {
realPath = normalizeForCompare(fs.realpathSync.native(skillPath));
identity = sourceIdentity(skillPath);
- } catch { continue; }
- if (!identity) continue;
-
+ } catch {
+ return;
+ }
+ if (!identity) return;
skills.push({
- name: ent.name,
+ name: path.basename(skillPath),
root,
path: skillPath,
realPath,
- isSymlink: ent.isSymbolicLink(),
+ isSymlink,
identity,
});
+ };
+
+ let entries;
+ try {
+ entries = await fsp.readdir(rootPath, { withFileTypes: true });
+ } catch {
+ return skills;
+ }
+
+ for (const ent of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (ent.name.startsWith('.')) continue;
+ if (/\.bak\.\d+$/.test(ent.name)) continue;
+ const skillPath = path.join(rootPath, ent.name);
+ // Dirent can report a Windows junction as a directory; lstat keeps the
+ // no-recursive-symlink guarantee consistent across platforms.
+ const isSymlink = ent.isSymbolicLink() || (ent.isDirectory() && isSymlinkDirectory(skillPath));
+ if (await hasSkillFile(skillPath)) {
+ await addSkill(skillPath, isSymlink);
+ continue;
+ }
+ // Direct symlinked Skills remain supported; a symlinked namespace is not walked.
+ if (isSymlink || !ent.isDirectory() || shouldPruneSkillScanDirectory(ent.name)) continue;
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ let namespaceEntries;
+ try {
+ namespaceEntries = await fsp.readdir(skillPath, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const nested of namespaceEntries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (nested.name.startsWith('.')) continue;
+ if (/\.bak\.\d+$/.test(nested.name)) continue;
+ const nestedPath = path.join(skillPath, nested.name);
+ if (!(await hasSkillFile(nestedPath))) continue;
+ const nestedIsSymlink = nested.isSymbolicLink()
+ || (nested.isDirectory() && isSymlinkDirectory(nestedPath));
+ await addSkill(nestedPath, nestedIsSymlink);
+ }
}
return skills;
}
@@ -207,11 +235,15 @@ function matchesManagedSkillTargetShape(
process.platform === 'win32'
? actual.toLowerCase() === expected.toLowerCase()
: actual === expected;
- const skillsDir = path.dirname(targetPath);
- const discoveryDir = path.dirname(skillsDir);
- return equalsName(path.basename(targetPath), skillName)
- && equalsName(path.basename(skillsDir), 'skills')
- && discoveryRoots.some((root) => equalsName(path.basename(discoveryDir), root));
+ const segments = path.resolve(targetPath).split(/[\\/]+/).filter(Boolean);
+ const leaf = segments[segments.length - 1];
+ if (!leaf || !equalsName(leaf, skillName)) return false;
+ for (let index = 0; index + 2 < segments.length; index += 1) {
+ const isDiscoveryRoot = discoveryRoots.some((root) => equalsName(segments[index], root));
+ // Flat and nested skills both live below `<discovery-root>/skills/<...>/<leaf>`.
+ if (isDiscoveryRoot && equalsName(segments[index + 1], 'skills')) return true;
+ }
+ return false;
}
async function cleanupBrokenManagedLinks(
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 40649b8048..e17f08e8d8 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -144,7 +144,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
id: "skills",
title: "Skills (reusable agent capabilities)",
summary: "Create, search, browse, install, disable, uninstall, publish, and update agent Skills; Skills appear as \"/\" slash commands and are shared across Claude Code, Codex, and Pi.",
- content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work across local agents:**\n\n- Skills are **engine-shared** — the same installed Skill is available to Claude Code, Codex, and Pi, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Creating or learning a Skill from the composer:**\n\n- Cindy includes `/cindy-skill-creator`. Invoke it with a description of the Skill you want, such as `/cindy-skill-creator Create a Skill that checks release notes`. Invoking it without a description asks what you want to create.\n- The current Agent creates or updates the Skill directly with its normal file tools. It does not use the `/learn` staging flow.\n- Ask for a Skill in the composer, for example “Find a release-notes Skill” or `/cindy-skill-creator Search our organization's code-review Skills`. The Agent can search SkillHub's public marketplace or your organization's catalog. Without a specified scope, organization identities search both; personal identities search the public marketplace. Results identify their source, including when two Skills share a name. Search alone does not install anything.\n- You can also ask `/cindy-skill-creator` to upload your own Skill to SkillHub or publish a new version directly in the conversation. Give the local Skill folder (or the Skill just created) and, for a first upload, who should be able to access it. Ordinary local creation/editing does not automatically publish it.\n- Uploads use Cindy's signed-in account, which determines ownership; choosing sharing targets does not change that ownership. The Agent can list your published Skills, upload the folder, and check scan/review status. Upload success does not mean public approval. Updating requires confirmed original authorship and management access, and preserves visibility and ownership; a missing authorship flag is not treated as permission. This works in a local desktop task, including when controlled from a phone; SSH files must first be made available on the Cindy host.\n- Each Agent upload or version update follows the task's permission mode: Ask requests approval for that publication, Auto reviews it against your request, and Full Access bypasses operation approval. A previous helper-tool approval does not authorize later publications. Search, listing, and status queries remain automatic.\n- Unless you request another location, new Skills go to `~/.agents/skills/<name>/`. Ask for a project-specific Skill to create it under `<working-dir>/.agents/skills/<name>/`.\n- Cindy also includes `/learn`. Bare `/learn` distills the current task; `/learn <description>` learns from a described workflow; `/learn hub:<scope>:<slug> [instructions]` learns from a SkillHub Skill. Cindy gathers evidence, runs the distillation in a separate task, and shows a diff for review before saving the proposed Skill.\n- The built-in `cindy-skill-creator` and `learn` entries appear in the local Skill list with an Official badge. You can disable or enable either entry there; because they ship with Cindy, they cannot be uninstalled. The setting applies to new or restarted Agent sessions. Disabling `learn` also disables the **Learn this skill** action in SkillHub after the local Skill list has refreshed.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared Skill links.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, choose visibility: personal identities support public or private; organization identities support public or organization sharing. Public publication is subject to review.\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",
+ content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work across local agents:**\n\n- Skills are **engine-shared** — the same installed Skill is available to Claude Code, Codex, and Pi, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n- Global and project discovery roots may also contain one namespace/container level (for example an author folder): Cindy checks each discovery root's direct children, then their direct children, and stops there. A folder with `SKILL.md` is a Skill; its child folders are skill resources, not separate Skills.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Creating or learning a Skill from the composer:**\n\n- Cindy includes `/cindy-skill-creator`. Invoke it with a description of the Skill you want, such as `/cindy-skill-creator Create a Skill that checks release notes`. Invoking it without a description asks what you want to create.\n- The current Agent creates or updates the Skill directly with its normal file tools. It does not use the `/learn` staging flow.\n- Ask for a Skill in the composer, for example “Find a release-notes Skill” or `/cindy-skill-creator Search our organization's code-review Skills`. The Agent can search SkillHub's public marketplace or your organization's catalog. Without a specified scope, organization identities search both; personal identities search the public marketplace. Results identify their source, including when two Skills share a name. Search alone does not install anything.\n- You can also ask `/cindy-skill-creator` to upload your own Skill to SkillHub or publish a new version directly in the conversation. Give the local Skill folder (or the Skill just created) and, for a first upload, who should be able to access it. Ordinary local creation/editing does not automatically publish it.\n- Uploads use Cindy's signed-in account, which determines ownership; choosing sharing targets does not change that ownership. The Agent can list your published Skills, upload the folder, and check scan/review status. Upload success does not mean public approval. Updating requires confirmed original authorship and management access, and preserves visibility and ownership; a missing authorship flag is not treated as permission. This works in a local desktop task, including when controlled from a phone; SSH files must first be made available on the Cindy host.\n- Each Agent upload or version update follows the task's permission mode: Ask requests approval for that publication, Auto reviews it against your request, and Full Access bypasses operation approval. A previous helper-tool approval does not authorize later publications. Search, listing, and status queries remain automatic.\n- Unless you request another location, new Skills go to `~/.agents/skills/<name>/`. Ask for a project-specific Skill to create it under `<working-dir>/.agents/skills/<name>/`.\n- Cindy also includes `/learn`. Bare `/learn` distills the current task; `/learn <description>` learns from a described workflow; `/learn hub:<scope>:<slug> [instructions]` learns from a SkillHub Skill. Cindy gathers evidence, runs the distillation in a separate task, and shows a diff for review before saving the proposed Skill.\n- The built-in `cindy-skill-creator` and `learn` entries appear in the local Skill list with an Official badge. You can disable or enable either entry there; because they ship with Cindy, they cannot be uninstalled. The setting applies to new or restarted Agent sessions. Disabling `learn` also disables the **Learn this skill** action in SkillHub after the local Skill list has refreshed.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- For a Skill inside a namespace/container folder, renaming changes only the Skill's own folder name; the namespace stays the same.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared Skill links.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, choose visibility: personal identities support public or private; organization identities support public or organization sharing. Public publication is subject to review.\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",
},
{
id: "updates-and-about",
diff --git a/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts b/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts
index bc10679bb8..3bcb665845 100644
--- a/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts
@@ -23,6 +23,16 @@ describe('local Skill removal targets', () => {
expect(inspectLocalSkillTarget(path.dirname(dir), [path.dirname(dir)])).toBeNull();
});
+ it('accepts a nested namespace Skill without treating the namespace as the entity', () => {
+ const skill = directory('.agents', 'skills', '@scope', 'nested');
+ const namespace = path.dirname(skill);
+ expect(inspectLocalSkillTarget(skill, [skill])).toMatchObject({
+ operationPath: fs.realpathSync.native(skill),
+ linkOnly: false,
+ });
+ expect(inspectLocalSkillTarget(namespace, [namespace])).toBeNull();
+ });
+
it.each([
['.Agents', 'Skills'], ['.Claude', 'Skills'], ['.Codex', 'Skills'],
['.Pi', 'Skills'], ['.Pi', 'Agent', 'Skills'], ['Codex-Home', 'Skills'], ['Pi-Agent-Home', 'Skills'],
diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
index c621090355..74a51a93a9 100644
--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
@@ -82,6 +82,194 @@ function createSymlinkedSkill() {
}
describe('scanAllSkills', () => {
+ it('keeps a nested namespace Skill in the local SkillHub projection', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-nested-skill-'));
+ tempRoots.push(root);
+ const skillDir = path.join(root, '.agents', 'skills', '@scope', 'nested');
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ '---\nname: nested\ndescription: >-\n Nested skill\n---\nBody\n',
+ 'utf-8',
+ );
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [{
+ engine: 'pi' as const,
+ kind: 'skill' as const,
+ scope: 'user' as const,
+ name: 'nested',
+ description: 'Nested skill',
+ absolutePath: skillDir,
+ mdPath: path.join(skillDir, 'SKILL.md'),
+ files: [],
+ }],
+ })),
+ } as unknown as Maker;
+
+ const result = await scanAllSkills({}, maker);
+
+ expect(result.skills).toHaveLength(1);
+ expect(result.skills[0]).toMatchObject({
+ name: 'nested',
+ description: 'Nested skill',
+ absolutePath: fs.realpathSync.native(skillDir),
+ mdPath: path.join(fs.realpathSync.native(skillDir), 'SKILL.md'),
+ });
+ });
+
+ it('uses the nested skill root when excluding package files', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-nested-exclusion-'));
+ tempRoots.push(root);
+ const skillDir = path.join(root, '.agents', 'skills', '@scope', 'nested');
+ const sensitiveFiles = [
+ path.join(skillDir, '.m2', 'settings.xml'),
+ path.join(skillDir, '.ssh', 'id_rsa'),
+ path.join(skillDir, '.config', 'gcloud', 'application_default_credentials.json'),
+ ];
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(path.join(skillDir, 'SKILL.md'), '# Nested\n', 'utf-8');
+ for (const filePath of sensitiveFiles) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, 'secret\n', 'utf-8');
+ }
+
+ const skillMd = path.join(skillDir, 'SKILL.md');
+ await expect(readSkillContent({ mdPath: skillMd })).resolves.toMatchObject({ success: true });
+ await expect(readSkillRawFile({ filePath: skillMd })).resolves.toMatchObject({ success: true });
+ for (const filePath of sensitiveFiles) {
+ await expect(readSkillSiblingFile({ filePath })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(readSkillRawFile({ filePath })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(writeSkillFile({ filePath, content: 'changed\n' })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ }
+
+ const listed = await listSkillFolderChildren({ dirPath: skillDir });
+ expect(listed).toMatchObject({ success: true });
+ expect(listed.entries?.map((entry) => entry.name)).not.toContain('.ssh');
+
+ // A deeper resource manifest must not raise the package root above the
+ // credential/config directories that contain it.
+ const deepManifestDirs = [
+ path.join(skillDir, '.config', 'gcloud', 'deep'),
+ path.join(skillDir, '.ssh', 'deep'),
+ ];
+ for (const dir of deepManifestDirs) {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), '# Deep resource\n', 'utf-8');
+ fs.writeFileSync(path.join(dir, 'payload.txt'), 'secret\n', 'utf-8');
+ }
+ for (const dir of deepManifestDirs) {
+ await expect(readSkillContent({ mdPath: path.join(dir, 'SKILL.md') })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(readSkillRawFile({ filePath: path.join(dir, 'payload.txt') })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(listSkillFolderChildren({ dirPath: dir })).resolves.toMatchObject({
+ success: true,
+ entries: [],
+ });
+ }
+
+ // The same must hold when the manifest sits directly in the excluded
+ // directory itself (`.m2` or `.config/gh`), not only deeper below it.
+ const exactContainerDirs = [
+ path.join(skillDir, '.m2'),
+ path.join(skillDir, '.config', 'gh'),
+ ];
+ for (const dir of exactContainerDirs) {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), '# Exact container\n', 'utf-8');
+ }
+ fs.writeFileSync(path.join(skillDir, '.config', 'gh', 'hosts.yml'), 'token: secret\n', 'utf-8');
+ for (const dir of exactContainerDirs) {
+ const listed = await listSkillFolderChildren({ dirPath: dir });
+ expect(listed).toMatchObject({ success: true });
+ const names = listed.entries?.map((entry) => entry.name) ?? [];
+ if (path.basename(dir) === '.m2') {
+ expect(names).not.toContain('settings.xml');
+ } else {
+ expect(names).toEqual([]);
+ }
+ }
+ await expect(readSkillRawFile({
+ filePath: path.join(skillDir, '.config', 'gh', 'hosts.yml'),
+ })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ });
+
+ it('excludes sensitive directories in the namespace position', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-sensitive-namespace-'));
+ tempRoots.push(root);
+ const skillsRoot = path.join(root, '.agents', 'skills');
+ const evilDirs = [
+ path.join(skillsRoot, '.ssh', 'evil'),
+ path.join(skillsRoot, '.m2', 'evil'),
+ path.join(skillsRoot, '.config', 'gh', 'evil'),
+ ];
+ for (const dir of evilDirs) {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), '# Evil\n', 'utf-8');
+ fs.writeFileSync(path.join(dir, 'payload.txt'), 'secret\n', 'utf-8');
+ }
+
+ for (const dir of evilDirs) {
+ await expect(readSkillRawFile({ filePath: path.join(dir, 'SKILL.md') })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(readSkillSiblingFile({ filePath: path.join(dir, 'payload.txt') })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(writeSkillFile({ filePath: path.join(dir, 'payload.txt'), content: 'x\n' })).resolves.toMatchObject({
+ success: false,
+ error: 'path is excluded from SkillHub packages',
+ });
+ await expect(listSkillFolderChildren({ dirPath: dir })).resolves.toMatchObject({
+ success: true,
+ entries: [],
+ });
+ }
+ });
+
+ it('keeps a nested Skill readable when its own leaf name is sensitive', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-sensitive-leaf-'));
+ tempRoots.push(root);
+ const skillDir = path.join(root, '.agents', 'skills', '@scope', 'credentials');
+ fs.mkdirSync(skillDir, { recursive: true });
+ const skillMd = path.join(skillDir, 'SKILL.md');
+ fs.writeFileSync(skillMd, '# Credentials helper\n', 'utf-8');
+ fs.writeFileSync(path.join(skillDir, 'notes.md'), 'notes\n', 'utf-8');
+
+ await expect(readSkillContent({ mdPath: skillMd })).resolves.toMatchObject({
+ success: true,
+ content: '# Credentials helper\n',
+ });
+ await expect(readSkillRawFile({ filePath: skillMd })).resolves.toMatchObject({ success: true });
+ await expect(writeSkillFile({ filePath: skillMd, content: '# Updated\n' })).resolves.toEqual({
+ success: true,
+ });
+ await expect(listSkillFolderChildren({ dirPath: skillDir })).resolves.toMatchObject({
+ success: true,
+ entries: expect.arrayContaining([{ name: 'SKILL.md', kind: 'file' }]),
+ });
+ });
+
it('always projects the bundled Skill as non-uninstallable and keeps a user same-name copy distinct', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-built-in-'));
tempRoots.push(root);
diff --git a/apps/desktop/src/main/skillhub/localSkillTarget.ts b/apps/desktop/src/main/skillhub/localSkillTarget.ts
index c0df2b48e7..cb6e65b183 100644
--- a/apps/desktop/src/main/skillhub/localSkillTarget.ts
+++ b/apps/desktop/src/main/skillhub/localSkillTarget.ts
@@ -10,20 +10,33 @@ export interface LocalSkillTarget {
aliases: string[];
}
-const standaloneSkillSuffix = /\/(?:\.(?:claude|agents|codex|pi)\/skills|\.pi\/agent\/skills|(?:codex-home|pi-agent-home)\/skills)\/[^/.][^/]*$/i;
+const skillDiscoveryRoot = /(?:^|\/)(?:\.(?:claude|agents|codex|pi)\/skills|\.pi\/agent\/skills|(?:codex-home|pi-agent-home)\/skills)(?=\/|$)/i;
-function isStandaloneSkillPath(value: string): boolean {
+function standalonePathParts(value: string): { root: string; relative: string[] } | null {
const normalized = path.resolve(value).replace(/\\/g, '/');
- return standaloneSkillSuffix.test(normalized);
+ const match = skillDiscoveryRoot.exec(normalized);
+ if (!match) return null;
+ const rootEnd = (match.index ?? 0) + match[0].length;
+ const relative = normalized.slice(rootEnd).split('/').filter(Boolean);
+ if (!relative.length || relative.some((segment) => segment.startsWith('.'))) return null;
+ return { root: normalized.slice(0, rootEnd), relative };
+}
+
+function isStandaloneSkillPath(value: string): boolean {
+ return standalonePathParts(value) !== null;
}
function isDirectSkillEntry(value: string): boolean {
+ const parts = standalonePathParts(value);
+ if (!parts) return false;
let current = path.resolve(value);
- const suffix = current.replace(/\\/g, '/').match(standaloneSkillSuffix)?.[0];
- if (!suffix) return false;
- // Check the entry, discovery root and engine config directories. The owner
- // prefix may itself be a tracked project alias or an OS path such as /var.
- for (const _segment of suffix.split('/').filter(Boolean)) {
+ const discoveryRoot = path.dirname(path.resolve(parts.root));
+ const ownerRoot = path.basename(discoveryRoot).toLowerCase() === 'agent'
+ ? path.dirname(path.dirname(discoveryRoot))
+ : path.dirname(discoveryRoot);
+ // Check the entry, namespace segments and every discovery-layout segment.
+ // The owner prefix may itself be a tracked project alias.
+ while (current !== ownerRoot) {
if (fs.lstatSync(current).isSymbolicLink()) return false;
current = path.dirname(current);
}
diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.ts
index 00e435b50d..64976787da 100644
--- a/apps/desktop/src/main/skillhub/scanner.ts
+++ b/apps/desktop/src/main/skillhub/scanner.ts
@@ -603,11 +603,12 @@ export async function listSkillFolderChildren(params: { dirPath: string; atteste
const skillRoot = attestedRoot
? fs.realpathSync.native(attestedRoot)
: findSkillRootForPath(dirPath);
+ const namespaceRoot = attestedRoot ? null : findNamespaceRootForPath(dirPath);
const entries: SkillFileEntry[] = fs
.readdirSync(resolvedDirPath, { withFileTypes: true })
.filter((s) => {
const childPath = path.join(listedDirPath, s.name);
- return !isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, childPath, s.name));
+ return !isIgnoredSkillPathWithRoots(childPath, skillRoot, namespaceRoot);
})
.map((s) => ({
name: s.name,
@@ -733,16 +734,76 @@ export function isExistingSkillPathGranted(
return false;
}
-function findSkillRootForPath(absolutePath: string): string | null {
- const norm = path.resolve(absolutePath).replace(/\\/g, '/');
- const markerMatch = /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/skills|codex-home\/skills)\//.exec(norm);
+function hasSkillManifest(skillDir: string): boolean {
+ return ['SKILL.md', 'skill.md'].some((name) => {
+ try {
+ return fs.statSync(path.join(skillDir, name)).isFile();
+ } catch {
+ return false;
+ }
+ });
+}
+
+interface SkillPathMarker {
+ markerRoot: string;
+ segments: string[];
+ flatKind: boolean;
+}
+
+function parseSkillPathMarker(absolutePath: string): SkillPathMarker | null {
+ const normalizedPath = path.resolve(absolutePath).replace(/\\/g, '/');
+ const markerMatch = /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/skills|codex-home\/skills)\//.exec(normalizedPath);
if (!markerMatch) return null;
- const afterMarker = norm.slice((markerMatch.index ?? 0) + markerMatch[0].length);
- const skillName = afterMarker.split('/').filter(Boolean)[0];
- if (!skillName) return null;
+ const segments = normalizedPath
+ .slice((markerMatch.index ?? 0) + markerMatch[0].length)
+ .split('/')
+ .filter(Boolean);
+ if (segments.length === 0) return null;
+
+ return {
+ markerRoot: path.normalize(
+ normalizedPath.slice(0, (markerMatch.index ?? 0) + markerMatch[0].length - 1),
+ ),
+ segments,
+ flatKind: markerMatch[0].includes('/commands/') || markerMatch[0].includes('/agents/'),
+ };
+}
+
+/** The namespace-level root used before nested Skill discovery existed. */
+function findNamespaceRootForPath(absolutePath: string): string | null {
+ const marker = parseSkillPathMarker(absolutePath);
+ return marker ? path.join(marker.markerRoot, marker.segments[0]) : null;
+}
+
+function findSkillRootForPath(absolutePath: string): string | null {
+ const marker = parseSkillPathMarker(absolutePath);
+ if (!marker) return null;
+ const { markerRoot, segments } = marker;
+ const firstSegment = segments[0];
+ const firstRoot = path.join(markerRoot, firstSegment);
+
+ // Commands and agents are flat `<name>.md` files.
+ if (marker.flatKind) return firstRoot;
+
+ // Hidden segments are never discovered by the scanner; never let a deeper
+ // manifest raise the read/write baseline into a hidden credential dir.
+ if (firstSegment.startsWith('.')) return markerRoot;
+
+ // Skills have at most one namespace/author level below the discovery root.
+ if (hasSkillManifest(firstRoot)) return firstRoot;
+ const secondSegment = segments[1];
+ if (secondSegment && !secondSegment.startsWith('.')) {
+ const secondRoot = path.join(firstRoot, secondSegment);
+ if (hasSkillManifest(secondRoot)) return secondRoot;
+ }
- return norm.slice(0, (markerMatch.index ?? 0) + markerMatch[0].length) + skillName;
+ // Keep the historical flat-layout fallback for incomplete paths. Hidden or
+ // excluded first segments use the marker root so the final relative path
+ // still contains that excluded segment.
+ return firstSegment.startsWith('.') || isIgnoredSkillPackagePath(firstSegment)
+ ? markerRoot
+ : firstRoot;
}
function skillPackageRelPath(rootDir: string | null, childPath: string, fallbackName: string): string {
@@ -751,12 +812,45 @@ function skillPackageRelPath(rootDir: string | null, childPath: string, fallback
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : fallbackName;
}
+function isIgnoredSkillPathWithRoots(
+ filePath: string,
+ skillRoot: string | null,
+ namespaceRoot: string | null,
+): boolean {
+ // Hidden discovery children are never scanned, so nothing below them is a
+ // package path. This also closes the namespace-position credential dirs.
+ if (namespaceRoot && path.basename(namespaceRoot).startsWith('.')) return true;
+ if (!skillRoot) {
+ return isIgnoredSkillPackagePath(
+ skillPackageRelPath(namespaceRoot, filePath, path.basename(filePath)),
+ );
+ }
+ if (isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, filePath, path.basename(filePath)))) {
+ return true;
+ }
+ // Only the namespace prefix above the Skill root is an extra exclusion
+ // surface; the Skill's own leaf name must not make its body unreadable.
+ if (namespaceRoot && skillRoot !== namespaceRoot) {
+ const namespacePrefix = skillPackageRelPath(namespaceRoot, path.dirname(skillRoot), '');
+ if (namespacePrefix && isIgnoredSkillPackagePath(namespacePrefix)) return true;
+ }
+ return false;
+}
+
function isIgnoredSkillFilePath(filePath: string, attestedRoot?: string): boolean {
- let skillRoot = attestedRoot ?? findSkillRootForPath(filePath);
if (attestedRoot) {
- try { skillRoot = fs.realpathSync.native(attestedRoot); } catch { return true; }
+ try {
+ const realRoot = fs.realpathSync.native(attestedRoot);
+ return isIgnoredSkillPackagePath(skillPackageRelPath(realRoot, filePath, path.basename(filePath)));
+ } catch {
+ return true;
+ }
}
- return isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, filePath, path.basename(filePath)));
+ return isIgnoredSkillPathWithRoots(
+ filePath,
+ findSkillRootForPath(filePath),
+ findNamespaceRootForPath(filePath),
+ );
}
export async function readSkillRawFile(params: { filePath: string; attestedRoot?: string }): Promise<{
diff --git a/packages/maker-core/package.json b/packages/maker-core/package.json
index c9fbfc4e5d..51797c6613 100644
--- a/packages/maker-core/package.json
+++ b/packages/maker-core/package.json
@@ -10,7 +10,8 @@
".": "./src/index.ts",
"./contacts-sync-worker": "./src/contacts/sync/worker-api.ts",
"./pi-extension-ui": "./src/agents/pi/extension-ui-capabilities.ts",
- "./pi-subagent-runs": "./src/agents/pi/pi-subagent-runs.ts"
+ "./pi-subagent-runs": "./src/agents/pi/pi-subagent-runs.ts",
+ "./skill-scan-limits": "./src/agents/shared/skill-scan-limits.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts
index 045fb400c1..f9b923049d 100644
--- a/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts
@@ -67,6 +67,26 @@ describe('collectPiProjectResourceCliPaths', () => {
expect(collectPiProjectResourceCliPaths(repo).skills).toEqual([realpathSync(skillDir)]);
});
+ it('collects nested namespace skills and prunes generated trees', () => {
+ const repo = makeRepo();
+ const piNested = path.join(repo, '.pi', 'skills', '@scope', 'pi-nested');
+ const agentsNested = path.join(repo, '.agents', 'skills', '@scope', 'agents-nested');
+ const tooDeep = path.join(repo, '.pi', 'skills', '@scope', 'group', 'too-deep');
+ const pruned = path.join(repo, '.pi', 'skills', 'dist', 'hidden');
+ for (const skillDir of [piNested, agentsNested, tooDeep, pruned]) {
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# nested\n');
+ }
+
+ const collected = collectPiProjectResourceCliPaths(repo);
+
+ expect(collected.skills).toEqual([
+ realpathSync(agentsNested),
+ realpathSync(piNested),
+ ].sort((a, b) => a.localeCompare(b)));
+ expect(collected.skills).not.toContain(realpathSync(tooDeep));
+ });
+
it('skips escaped symlinks and settings files', () => {
const repo = makeRepo();
const outside = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-cli-out-')));
@@ -87,6 +107,35 @@ describe('collectPiProjectResourceCliPaths', () => {
}
});
+ it('keeps a direct Skill whose folder name matches a pruned directory', () => {
+ const repo = makeRepo();
+ const directDist = path.join(repo, '.pi', 'skills', 'dist');
+ const nested = path.join(repo, '.pi', 'skills', 'node_modules', 'ignored');
+ for (const skillDir of [directDist, nested]) {
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# direct\n');
+ }
+
+ expect(collectPiProjectResourceCliPaths(repo).skills).toEqual([realpathSync(directDist)]);
+ });
+
+ it('does not walk a symlinked namespace inside the repo', () => {
+ const repo = makeRepo();
+ const externalNamespace = path.join(repo, 'external-ns');
+ const nestedSkill = path.join(externalNamespace, 'nested');
+ mkdirSync(nestedSkill, { recursive: true });
+ writeFileSync(path.join(nestedSkill, 'SKILL.md'), '# linked\n');
+ const link = path.join(repo, '.pi', 'skills', 'linked-ns');
+ mkdirSync(path.dirname(link), { recursive: true });
+ try {
+ symlinkSync(externalNamespace, link, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
+
+ expect(collectPiProjectResourceCliPaths(repo).skills).toEqual([]);
+ });
+
it('does not walk .agents/skills past the nearest git root', () => {
const repo = makeRepo();
const nested = path.join(repo, 'packages', 'app');
diff --git a/packages/maker-core/src/agents/pi/project-resource-cli.ts b/packages/maker-core/src/agents/pi/project-resource-cli.ts
index 240081814f..51e6232c98 100644
--- a/packages/maker-core/src/agents/pi/project-resource-cli.ts
+++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts
@@ -8,6 +8,7 @@
import fs from 'node:fs';
import path from 'node:path';
+import { shouldPruneSkillScanDirectory } from '../shared/skill-scan-limits.js';
export interface PiProjectResourceCliPaths {
readonly skills: readonly string[];
@@ -80,20 +81,54 @@ function listDir(dir: string): fs.Dirent[] {
}
}
+function isSymlinkDirectory(target: string): boolean {
+ try {
+ return fs.lstatSync(target).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+function hasSkillFile(dir: string): boolean {
+ return ['SKILL.md', 'skill.md'].some((name) => isFile(path.join(dir, name)));
+}
+
function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set<string>): void {
const resolvedDir = realpathOrNull(skillsDir);
if (!resolvedDir || !isDir(resolvedDir) || !isWithinRoot(repoRoot, resolvedDir)) return;
+
+ const addSkill = (realFolder: string): void => {
+ const skillMd = ['SKILL.md', 'skill.md']
+ .map((name) => path.join(realFolder, name))
+ .find(isFile);
+ const realMd = skillMd ? realpathOrNull(skillMd) : null;
+ if (realMd && isFile(realMd) && isWithinRoot(repoRoot, realMd)) bucket.add(realFolder);
+ };
+
for (const entry of listDir(resolvedDir)) {
- if (entry.name.startsWith('.')) continue;
- const realFolder = realpathOrNull(path.join(resolvedDir, entry.name));
+ if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue;
+ const candidatePath = path.join(resolvedDir, entry.name);
+ const realFolder = realpathOrNull(candidatePath);
if (!realFolder || !isDir(realFolder) || !isWithinRoot(repoRoot, realFolder)) continue;
- const upper = path.join(realFolder, 'SKILL.md');
- const lower = path.join(realFolder, 'skill.md');
- const skillMd = isFile(upper) ? upper : isFile(lower) ? lower : null;
- if (!skillMd) continue;
- const realMd = realpathOrNull(skillMd);
- if (!realMd || !isFile(realMd) || !isWithinRoot(repoRoot, realMd)) continue;
- bucket.add(realFolder);
+ if (hasSkillFile(realFolder)) {
+ addSkill(realFolder);
+ continue;
+ }
+ // Direct symlinked Skills remain supported above; a symlinked namespace
+ // could escape the repo or cycle and is intentionally not walked.
+ // lstat must see the unresolved path: a Windows junction may be reported
+ // as a directory by readdir and by the resolved realpath.
+ const isSymlink = entry.isSymbolicLink()
+ || (entry.isDirectory() && isSymlinkDirectory(candidatePath));
+ if (isSymlink || shouldPruneSkillScanDirectory(entry.name)) continue;
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ for (const nested of listDir(realFolder)) {
+ if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue;
+ const nestedFolder = realpathOrNull(path.join(realFolder, nested.name));
+ if (!nestedFolder || !isDir(nestedFolder) || !isWithinRoot(repoRoot, nestedFolder)) continue;
+ if (hasSkillFile(nestedFolder)) addSkill(nestedFolder);
+ }
}
}
diff --git a/packages/maker-core/src/agents/shared/customization-scanner.test.ts b/packages/maker-core/src/agents/shared/customization-scanner.test.ts
new file mode 100644
index 0000000000..38e0b4b103
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/customization-scanner.test.ts
@@ -0,0 +1,156 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { scanCustomizationSources, type SourceDef } from './customization-scanner.js';
+
+const roots: string[] = [];
+
+function tempRoot(): string {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-customization-scanner-'));
+ roots.push(root);
+ return root;
+}
+
+function writeSkill(sourceDir: string, relativeDir: string, name: string): string {
+ const skillDir = path.join(sourceDir, relativeDir);
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: >-\n ${name} description\n---\n`,
+ 'utf8',
+ );
+ return skillDir;
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('scanCustomizationSources', () => {
+ it('discovers direct Skills and one namespace level without recursing further', () => {
+ const root = tempRoot();
+ const sourceDir = path.join(root, 'skills');
+ const direct = writeSkill(sourceDir, 'direct', 'direct');
+ const nested = writeSkill(sourceDir, path.join('@scope', 'nested'), 'nested');
+ const deeper = writeSkill(sourceDir, path.join('@scope', 'group', 'deeper'), 'deeper');
+ const resourceDir = path.join(direct, 'references', 'looks-like-skill');
+ fs.mkdirSync(resourceDir, { recursive: true });
+ fs.writeFileSync(path.join(resourceDir, 'SKILL.md'), '---\nname: resource\n---\n');
+
+ const source: SourceDef = {
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'user',
+ dir: sourceDir,
+ };
+ const result = scanCustomizationSources([source]);
+
+ expect(result.errors).toEqual([]);
+ expect(result.items).toHaveLength(2);
+ expect(result.items.map((item) => item.name).sort()).toEqual(['direct', 'nested']);
+ expect(result.items.map((item) => item.absolutePath).sort()).toEqual([direct, nested].sort());
+ expect(result.items.map((item) => item.absolutePath)).not.toContain(deeper);
+ expect(result.items.every((item) => item.description)).toBe(true);
+ });
+
+ it('prunes generated dependency trees while still accepting direct Skills', () => {
+ const root = tempRoot();
+ const sourceDir = path.join(root, 'skills');
+ const direct = writeSkill(sourceDir, 'direct', 'direct');
+ const generatedDirs = [
+ 'node_modules',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+ 'target',
+ '__macosx',
+ '__pycache__',
+ 'Node_Modules',
+ 'DIST',
+ ];
+ for (const generatedDir of generatedDirs) {
+ writeSkill(sourceDir, path.join(generatedDir, 'ignored'), `${generatedDir}-ignored`);
+ }
+
+ const result = scanCustomizationSources([{
+ engine: 'codex',
+ kind: 'skill',
+ scope: 'user',
+ dir: sourceDir,
+ }]);
+
+ expect(result.errors).toEqual([]);
+ expect(result.items.map((item) => item.absolutePath)).toEqual([direct]);
+ });
+
+ it('keeps a direct Skill whose folder name matches a pruned directory', () => {
+ const root = tempRoot();
+ const sourceDir = path.join(root, 'skills');
+ const directDist = writeSkill(sourceDir, 'dist', 'dist-skill');
+ writeSkill(sourceDir, path.join('node_modules', 'ignored'), 'ignored');
+
+ const result = scanCustomizationSources([{
+ engine: 'codex',
+ kind: 'skill',
+ scope: 'user',
+ dir: sourceDir,
+ }]);
+
+ expect(result.errors).toEqual([]);
+ expect(result.items.map((item) => item.absolutePath)).toEqual([directDist]);
+ });
+
+ it('keeps a direct symlinked Skill discoverable without walking symlinked namespaces', (ctx) => {
+ const root = tempRoot();
+ const sourceDir = path.join(root, 'skills');
+ const directTarget = writeSkill(path.join(root, 'external'), 'linked', 'linked');
+ fs.mkdirSync(sourceDir, { recursive: true });
+ const link = path.join(sourceDir, 'linked');
+ try {
+ fs.symlinkSync(directTarget, link, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ ctx.skip();
+ return;
+ }
+
+ const result = scanCustomizationSources([{
+ engine: 'codex',
+ kind: 'skill',
+ scope: 'user',
+ dir: sourceDir,
+ }]);
+
+ expect(result.errors).toEqual([]);
+ expect(result.items.map((item) => item.absolutePath)).toEqual([link]);
+ });
+
+ it('does not descend through a symlinked namespace container', (ctx) => {
+ const root = tempRoot();
+ const sourceDir = path.join(root, 'skills');
+ const externalScope = path.join(root, 'external', '@scope');
+ const linkedSkill = writeSkill(path.join(root, 'external'), path.join('@scope', 'linked'), 'linked');
+ fs.mkdirSync(sourceDir, { recursive: true });
+ const direct = writeSkill(sourceDir, 'direct', 'direct');
+ const namespaceLink = path.join(sourceDir, '@scope');
+ try {
+ fs.symlinkSync(externalScope, namespaceLink, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ ctx.skip();
+ return;
+ }
+
+ const result = scanCustomizationSources([{
+ engine: 'codex',
+ kind: 'skill',
+ scope: 'user',
+ dir: sourceDir,
+ }]);
+
+ expect(result.errors).toEqual([]);
+ expect(result.items.map((item) => item.absolutePath)).toEqual([direct]);
+ expect(result.items.map((item) => item.absolutePath)).not.toContain(linkedSkill);
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/customization-scanner.ts b/packages/maker-core/src/agents/shared/customization-scanner.ts
index 5f584f8f4b..6b01e4f57d 100644
--- a/packages/maker-core/src/agents/shared/customization-scanner.ts
+++ b/packages/maker-core/src/agents/shared/customization-scanner.ts
@@ -14,6 +14,7 @@ import type {
AgentCustomizationFile,
ListCustomizationsResult,
} from '../../types/customizations.js';
+import { shouldPruneSkillScanDirectory } from './skill-scan-limits.js';
export interface SourceDef {
engine: 'claude-code' | 'codex' | 'pi';
@@ -49,10 +50,6 @@ export function parseFrontmatter(raw: string): {
}
}
-function direntIsDirectoryOrSymlink(dirent: fs.Dirent): boolean {
- return dirent.isDirectory() || dirent.isSymbolicLink();
-}
-
function readChildKind(parent: string, dirent: fs.Dirent): AgentCustomizationFile['kind'] {
if (dirent.isDirectory()) return 'dir';
if (!dirent.isSymbolicLink()) return 'file';
@@ -155,6 +152,83 @@ function realPathInside(parentRealPath: string, candidate: string): boolean {
}
}
+function isSymlinkDirectory(target: string): boolean {
+ try {
+ return fs.lstatSync(target).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+function findSkillMd(folder: string): string | null {
+ for (const name of ['SKILL.md', 'skill.md']) {
+ const candidate = path.join(folder, name);
+ try {
+ if (fs.statSync(candidate).isFile()) return candidate;
+ } catch {
+ // A missing or inaccessible candidate is not a skill folder.
+ }
+ }
+ return null;
+}
+
+function scanSkillFolders(
+ source: SourceDef,
+ containmentRoot: string | null,
+ items: AgentCustomization[],
+ errors: Array<{ path?: string; message: string }>,
+): void {
+ const pushSkill = (folder: string, mdPath: string): void => {
+ if (
+ containmentRoot &&
+ (!realPathInside(containmentRoot, folder) || !realPathInside(containmentRoot, mdPath))
+ ) {
+ return;
+ }
+ items.push(readFolderSkill(source, folder, mdPath));
+ };
+
+ const readDir = (dir: string): fs.Dirent[] | null => {
+ try {
+ return fs.readdirSync(dir, { withFileTypes: true });
+ } catch (err) {
+ errors.push({ path: dir, message: err instanceof Error ? err.message : String(err) });
+ return null;
+ }
+ };
+
+ const topLevelEntries = readDir(source.dir);
+ if (!topLevelEntries) return;
+ topLevelEntries.sort((a, b) => a.name.localeCompare(b.name));
+
+ for (const ent of topLevelEntries) {
+ if (ent.name.startsWith('.') || /\.bak\.\d+$/.test(ent.name)) continue;
+ const folder = path.join(source.dir, ent.name);
+ const mdPath = findSkillMd(folder);
+ if (mdPath) {
+ pushSkill(folder, mdPath);
+ // A skill's child directories are resources, not discoverable skills.
+ continue;
+ }
+
+ // Dirent can report a Windows junction as a directory; lstat keeps the
+ // no-recursive-symlink guarantee consistent across platforms.
+ const isSymlink = ent.isSymbolicLink() || (ent.isDirectory() && isSymlinkDirectory(folder));
+ if (isSymlink || !ent.isDirectory() || shouldPruneSkillScanDirectory(ent.name)) continue;
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ const namespaceEntries = readDir(folder);
+ if (!namespaceEntries) continue;
+ namespaceEntries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const nested of namespaceEntries) {
+ if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue;
+ const nestedFolder = path.join(folder, nested.name);
+ const nestedMd = findSkillMd(nestedFolder);
+ if (nestedMd) pushSkill(nestedFolder, nestedMd);
+ }
+ }
+}
+
function scanOneSource(source: SourceDef): {
items: AgentCustomization[];
errors: Array<{ path?: string; message: string }>;
@@ -174,38 +248,19 @@ function scanOneSource(source: SourceDef): {
if (!realPathInside(containmentRoot, source.dir)) return { items: [], errors };
}
- const entries = fs.readdirSync(source.dir, { withFileTypes: true });
const items: AgentCustomization[] = [];
+ if (source.kind === 'skill') {
+ scanSkillFolders(source, containmentRoot, items, errors);
+ return { items, errors };
+ }
+ const entries = fs.readdirSync(source.dir, { withFileTypes: true });
for (const ent of entries) {
if (ent.name.startsWith('.')) continue;
if (/\.bak\.\d+$/.test(ent.name)) continue;
-
- if (source.kind === 'skill') {
- if (!direntIsDirectoryOrSymlink(ent)) continue;
- const folder = path.join(source.dir, ent.name);
- const mdPath = path.join(folder, 'SKILL.md');
- let actualMd = mdPath;
- if (!fs.existsSync(actualMd) || !fs.statSync(actualMd).isFile()) {
- const lower = path.join(folder, 'skill.md');
- if (fs.existsSync(lower) && fs.statSync(lower).isFile()) {
- actualMd = lower;
- } else {
- continue;
- }
- }
- if (
- containmentRoot &&
- (!realPathInside(containmentRoot, folder) || !realPathInside(containmentRoot, actualMd))
- ) {
- continue;
- }
- items.push(readFolderSkill(source, folder, actualMd));
- } else {
- if (!ent.isFile()) continue;
- if (!ent.name.toLowerCase().endsWith('.md')) continue;
- items.push(readFileCustomization(source, path.join(source.dir, ent.name)));
- }
+ if (!ent.isFile()) continue;
+ if (!ent.name.toLowerCase().endsWith('.md')) continue;
+ items.push(readFileCustomization(source, path.join(source.dir, ent.name)));
}
return { items, errors };
diff --git a/packages/maker-core/src/agents/shared/palette-scanner.test.ts b/packages/maker-core/src/agents/shared/palette-scanner.test.ts
index e937f9c4eb..4928769a36 100644
--- a/packages/maker-core/src/agents/shared/palette-scanner.test.ts
+++ b/packages/maker-core/src/agents/shared/palette-scanner.test.ts
@@ -69,6 +69,35 @@ describe('scanClaudeSlashCommands', () => {
}
});
+ it('discovers one namespace level and stops at the third level', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'xdt-palette-nested-'));
+ const home = path.join(root, 'home');
+ const skillsDir = path.join(home, '.claude', 'skills');
+ const nested = path.join(skillsDir, '@scope', 'nested');
+ const tooDeep = path.join(skillsDir, '@scope', 'group', 'too-deep');
+
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('USERPROFILE', home);
+ try {
+ for (const skillDir of [nested, tooDeep]) {
+ await mkdir(skillDir, { recursive: true });
+ await writeFile(
+ path.join(skillDir, 'SKILL.md'),
+ `---\ndescription: ${path.basename(skillDir)}\n---\nbody\n`,
+ 'utf8',
+ );
+ }
+
+ const commands = await scanClaudeSlashCommands();
+
+ expect(commands.map((command) => command.name)).toContain('nested');
+ expect(commands.map((command) => command.name)).not.toContain('too-deep');
+ } finally {
+ vi.unstubAllEnvs();
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
it('includes skill directories that are symlinked into the global Claude skills root', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'xdt-palette-'));
const home = path.join(root, 'home');
diff --git a/packages/maker-core/src/agents/shared/palette-scanner.ts b/packages/maker-core/src/agents/shared/palette-scanner.ts
index abe5ec8540..9d36d791df 100644
--- a/packages/maker-core/src/agents/shared/palette-scanner.ts
+++ b/packages/maker-core/src/agents/shared/palette-scanner.ts
@@ -7,6 +7,7 @@ import type {
AtResourceItem,
ScanAtResourcesResult,
} from '../../types/palette.js';
+import { shouldPruneSkillScanDirectory } from './skill-scan-limits.js';
const MAX_SCAN_ITEMS = 2_000;
const IGNORE_DIRS = new Set([
@@ -271,34 +272,72 @@ async function scanClaudeCommandFiles(
return results;
}
+async function isSymlinkDirectory(target: string): Promise<boolean> {
+ try {
+ return (await fs.lstat(target)).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+async function findSkillFile(dir: string): Promise<string | null> {
+ for (const name of ['SKILL.md', 'skill.md']) {
+ if (await fs.stat(path.join(dir, name)).then((stat) => stat.isFile()).catch(() => false)) {
+ return name;
+ }
+ }
+ return null;
+}
+
async function scanClaudeSkillDirs(
dirPath: string,
scope: 'global' | 'project',
): Promise<AgentSlashCommand[]> {
if (!(await isDirectory(dirPath))) return [];
const results: AgentSlashCommand[] = [];
- const entries = (await fs.readdir(dirPath, { withFileTypes: true }))
- .filter((ent) => (ent.isDirectory() || ent.isSymbolicLink()) && !ent.name.startsWith('.'))
- .sort((a, b) => a.name.localeCompare(b.name));
-
- for (const ent of entries) {
- const subDir = path.join(dirPath, ent.name);
- const skillFile = (await Promise.all(
- ['SKILL.md', 'skill.md'].map(async (name) => ({
- name,
- exists: await fs.stat(path.join(subDir, name)).then((stat) => stat.isFile()).catch(() => false),
- })),
- )).find((entry) => entry.exists)?.name;
- if (!skillFile) continue;
-
+ const addSkill = async (subDir: string, name: string, skillFile: string): Promise<void> => {
const skillPath = path.join(subDir, skillFile);
results.push({
- name: ent.name,
+ name,
description: await readMarkdownDescription(skillPath),
source: 'skill',
path: skillPath,
scope,
});
+ };
+ const entries = (await fs.readdir(dirPath, { withFileTypes: true }))
+ .filter((ent) => (ent.isDirectory() || ent.isSymbolicLink())
+ && !ent.name.startsWith('.')
+ && !/\.bak\.\d+$/.test(ent.name))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ for (const ent of entries) {
+ const subDir = path.join(dirPath, ent.name);
+ const skillFile = await findSkillFile(subDir);
+ if (skillFile) {
+ await addSkill(subDir, ent.name, skillFile);
+ continue;
+ }
+ // Direct symlinked Skills remain supported; a symlinked namespace is not walked.
+ const isSymlink = ent.isSymbolicLink() || (ent.isDirectory() && await isSymlinkDirectory(subDir));
+ if (isSymlink || shouldPruneSkillScanDirectory(ent.name)) continue;
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ let nestedEntries;
+ try {
+ nestedEntries = await fs.readdir(subDir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const nested of nestedEntries
+ .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink())
+ && !entry.name.startsWith('.')
+ && !/\.bak\.\d+$/.test(entry.name))
+ .sort((a, b) => a.name.localeCompare(b.name))) {
+ const nestedDir = path.join(subDir, nested.name);
+ const nestedFile = await findSkillFile(nestedDir);
+ if (nestedFile) await addSkill(nestedDir, nested.name, nestedFile);
+ }
}
return results;
}
diff --git a/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts b/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
index f5a3bccbde..3ea1024f64 100644
--- a/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
+++ b/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
@@ -54,6 +54,20 @@ describe('remote Skill scanners', () => {
]);
});
+ it('discovers one namespace level and stops before the third level', async () => {
+ const fileOps = fakeRemoteFiles({
+ '$HOME/.agents/skills/@scope/nested/SKILL.md': '---\ndescription: Nested\n---',
+ '$HOME/.agents/skills/@scope/group/too-deep/SKILL.md': '---\ndescription: Too deep\n---',
+ '$HOME/.claude/skills/@scope/claude-nested/SKILL.md': '---\ndescription: Claude nested\n---',
+ });
+
+ const pi = await scanRemotePiSkills({ fileOps });
+ expect(pi.skills.map((skill) => skill.name)).toEqual(['nested']);
+
+ const claude = await scanRemoteClaudeSkills({ fileOps });
+ expect(claude.skills.map((skill) => skill.name)).toEqual(['claude-nested']);
+ });
+
it('discovers Pi global, project, and ancestor Skills only through the Git boundary', async () => {
const fileOps = fakeRemoteFiles({
'$HOME/.agents/skills/global/SKILL.md': '---\ndescription: Global\n---',
diff --git a/packages/maker-core/src/agents/shared/remote-skill-scanner.ts b/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
index d091476832..9483bee7b9 100644
--- a/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
+++ b/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
@@ -2,6 +2,7 @@ import path from 'node:path';
import type { RemoteAgentFileOps } from '../base-agent.js';
import type { AgentSkillCommand, ListAgentSkillsResult } from '../../types/palette.js';
+import { shouldPruneSkillScanDirectory } from './skill-scan-limits.js';
const SKILL_READ_LIMIT = 1_048_576;
@@ -70,12 +71,11 @@ async function scanSkillDirectories(input: {
runtimeCommandPrefix?: string;
}): Promise<AgentSkillCommand[]> {
const names = (await input.fileOps.listDir(input.root))
- .filter((name) => name && !name.startsWith('.') && !name.includes('/'))
+ .filter((name) => name && !name.startsWith('.') && !name.includes('/')
+ && !/\.bak\.\d+$/.test(name))
.sort((a, b) => a.localeCompare(b));
const found: AgentSkillCommand[] = [];
- for (const name of names) {
- const skillFile = await existingSkillFile(input.fileOps, path.posix.join(input.root, name));
- if (!skillFile) continue;
+ const addSkill = async (name: string, skillFile: string): Promise<void> => {
found.push({
kind: 'agent-skill',
name,
@@ -88,6 +88,29 @@ async function scanSkillDirectories(input: {
? { runtimeCommandName: `${input.runtimeCommandPrefix}${name}` }
: {}),
});
+ };
+
+ for (const name of names) {
+ const skillDir = path.posix.join(input.root, name);
+ const skillFile = await existingSkillFile(input.fileOps, skillDir);
+ if (skillFile) {
+ await addSkill(name, skillFile);
+ continue;
+ }
+ if (shouldPruneSkillScanDirectory(name)) continue;
+
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ const nestedNames = (await input.fileOps.listDir(skillDir))
+ .filter((nested) => nested && !nested.startsWith('.') && !nested.includes('/')
+ && !/\.bak\.\d+$/.test(nested))
+ .sort((a, b) => a.localeCompare(b));
+ for (const nestedName of nestedNames) {
+ const nestedFile = await existingSkillFile(
+ input.fileOps,
+ path.posix.join(skillDir, nestedName),
+ );
+ if (nestedFile) await addSkill(nestedName, nestedFile);
+ }
}
return found;
}
diff --git a/packages/maker-core/src/agents/shared/skill-scan-limits.ts b/packages/maker-core/src/agents/shared/skill-scan-limits.ts
new file mode 100644
index 0000000000..c528ec46c7
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/skill-scan-limits.ts
@@ -0,0 +1,27 @@
+/**
+ * Shared Skill namespace pruning policy.
+ *
+ * Skill discovery roots have a two-level structure at most:
+ * <discovery-root>/<namespace-or-author>/<skill>/
+ * A direct child can also be a Skill itself. Never recurse deeper.
+ *
+ * Keep this module dependency-free so lightweight Desktop projection code can
+ * import it without pulling the maker core graph.
+ */
+
+/** Common generated/dependency trees are not Skill namespaces. */
+export const SKILL_SCAN_PRUNED_DIRS: ReadonlySet<string> = new Set([
+ 'node_modules',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+ 'target',
+ '__macosx',
+ '__pycache__',
+]);
+
+/** Case-insensitive prune check so `DIST` / `Node_Modules` behave like their lowercase forms. */
+export function shouldPruneSkillScanDirectory(name: string): boolean {
+ return SKILL_SCAN_PRUNED_DIRS.has(name.toLowerCase());
+}