- The universal skill platform for AI coding agents. Auto-generate instructions
- with Primer, persist learnings with Memory, distribute across Mesh networks.
- One CLI for Claude, Cursor, Windsurf, Copilot, and 28 more.
+ The package manager for AI agent skills. Install from 15,000+ skills,
+ auto-translate between formats, persist learnings with Memory.
+ Works with Claude, Cursor, Windsurf, Copilot, and 28 more.
diff --git a/package.json b/package.json
index d73652dc..e019e7ac 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "skillkit-monorepo",
"version": "1.10.0",
"private": true,
- "description": "Universal skills loader for AI coding agents - Monorepo",
+ "description": "The package manager for AI agent skills — install, translate, share across 32 coding agents",
"type": "module",
"scripts": {
"build": "turbo run build",
@@ -31,7 +31,13 @@
"coding-assistant",
"skill-loader",
"cli",
- "monorepo"
+ "monorepo",
+ "skill-md",
+ "package-manager",
+ "plugin",
+ "workflow",
+ "automation",
+ "SKILL.md"
],
"author": "Rohit Ghumare",
"license": "Apache-2.0",
diff --git a/packages/cli/src/__tests__/quick-security.test.ts b/packages/cli/src/__tests__/quick-security.test.ts
new file mode 100644
index 00000000..b03016e6
--- /dev/null
+++ b/packages/cli/src/__tests__/quick-security.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+import { join, normalize, resolve, sep } from 'node:path';
+
+function isPathInside(child: string, parent: string): boolean {
+ const resolved = resolve(child);
+ const resolvedParent = resolve(parent);
+ return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep);
+}
+
+function sanitizeName(name: string): string {
+ return name.split(/[/\\]/).pop() || name;
+}
+
+describe('Quick Command Security', () => {
+ describe('path traversal protection', () => {
+ const installDir = '/home/user/.claude/skills';
+
+ it('should block skill names that escape the install directory', () => {
+ const maliciousNames = ['../evil', '../../etc/passwd', '../../../tmp/bad', '..\\evil'];
+
+ for (const name of maliciousNames) {
+ const sanitized = sanitizeName(name);
+ const targetPath = normalize(join(installDir, sanitized));
+ expect(isPathInside(targetPath, installDir)).toBe(true);
+ expect(sanitized).not.toContain('..');
+ expect(sanitized).not.toContain('/');
+ expect(sanitized).not.toContain('\\');
+ }
+ });
+
+ it('should sanitize "../evil" to "evil"', () => {
+ expect(sanitizeName('../evil')).toBe('evil');
+ });
+
+ it('should sanitize "../../etc/passwd" to "passwd"', () => {
+ expect(sanitizeName('../../etc/passwd')).toBe('passwd');
+ });
+
+ it('should sanitize "..\\evil" to "evil"', () => {
+ expect(sanitizeName('..\\evil')).toBe('evil');
+ });
+
+ it('should keep valid skill names unchanged', () => {
+ expect(sanitizeName('my-skill')).toBe('my-skill');
+ expect(sanitizeName('react-best-practices')).toBe('react-best-practices');
+ });
+
+ it('should produce a path inside installDir after sanitization', () => {
+ const evilName = '../evil';
+ const sanitized = sanitizeName(evilName);
+ const targetPath = normalize(join(installDir, sanitized));
+ expect(isPathInside(targetPath, installDir)).toBe(true);
+ expect(targetPath).toBe(join(installDir, 'evil'));
+ });
+
+ it('should detect unsanitized traversal names before normalization', () => {
+ const rawPath = `${installDir}/../evil`;
+ expect(isPathInside(rawPath, installDir)).toBe(false);
+ });
+
+ it('should ensure sanitization prevents the traversal entirely', () => {
+ const evilName = '../evil';
+ const sanitized = sanitizeName(evilName);
+ const targetPath = normalize(join(installDir, sanitized));
+ expect(targetPath).toBe(join(installDir, 'evil'));
+ expect(targetPath.startsWith(installDir)).toBe(true);
+ });
+ });
+});
diff --git a/packages/cli/src/badge.ts b/packages/cli/src/badge.ts
new file mode 100644
index 00000000..18b47021
--- /dev/null
+++ b/packages/cli/src/badge.ts
@@ -0,0 +1,39 @@
+const SKILLKIT_LOGO_SVG_BASE64 =
+ 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0id2hpdGUiPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjEiIHk9IjEiLz48cmVjdCB3aWR0aD0iNiIgaGVpZ2h0PSI2IiB4PSI5IiB5PSIxIi8+PHJlY3Qgd2lkdGg9IjYiIGhlaWdodD0iNiIgeD0iMSIgeT0iOSIvPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjkiIHk9IjkiLz48L3N2Zz4=';
+
+function encodeBadgeSegment(text: string): string {
+ return encodeURIComponent(text).replace(/-/g, '--');
+}
+
+export function generateBadge(skills: string[]): {
+ url: string;
+ markdown: string;
+ html: string;
+} {
+ const count = skills.length;
+
+ if (count === 0) {
+ const url = `https://img.shields.io/badge/SkillKit-No%20Skills-555555?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
+ return {
+ url,
+ markdown: `[](https://agenstskills.com)`,
+ html: `

`,
+ };
+ }
+
+ const maxDisplay = 5;
+ const displayNames = skills.slice(0, maxDisplay);
+ const suffix = count > maxDisplay ? ` +${count - maxDisplay} more` : '';
+ const label = `SkillKit ${count} skills`;
+ const message = displayNames.join(' | ') + suffix;
+ const encodedLabel = encodeBadgeSegment(label);
+ const encodedMessage = encodeBadgeSegment(message);
+
+ const url = `https://img.shields.io/badge/${encodedLabel}-${encodedMessage}-black?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
+
+ return {
+ url,
+ markdown: `[](https://agenstskills.com)`,
+ html: `

`,
+ };
+}
diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.ts
index 6b143092..cb043113 100644
--- a/packages/cli/src/commands/find.ts
+++ b/packages/cli/src/commands/find.ts
@@ -8,6 +8,7 @@ import {
select,
header,
} from '../onboarding/index.js';
+import { FederatedSearch, GitHubSkillRegistry, RateLimitError } from '@skillkit/core';
interface SkillResult {
name: string;
@@ -54,6 +55,10 @@ export class FindCommand extends Command {
description: 'Minimal output (just list skills)',
});
+ federated = Option.Boolean('--federated,-f', false, {
+ description: 'Search external registries (GitHub SKILL.md files)',
+ });
+
async execute(): Promise
{
const s = spinner();
const limit = parseInt(this.limit, 10) || 10;
@@ -128,12 +133,46 @@ export class FindCommand extends Command {
}
}
+ if (this.federated && this.query) {
+ s.start('Searching external registries...');
+ const fedSearch = new FederatedSearch();
+ fedSearch.addRegistry(new GitHubSkillRegistry());
+ try {
+ const fedResult = await fedSearch.search(this.query, { limit: parseInt(this.limit, 10) || 10 });
+ s.stop(`Found ${fedResult.total} external skill(s) from ${fedResult.registries.join(', ') || 'none'}`);
+
+ if (fedResult.skills.length > 0) {
+ console.log('');
+ console.log(colors.bold('External Skills (SKILL.md):'));
+ for (const skill of fedResult.skills) {
+ const stars = typeof skill.stars === 'number' ? colors.muted(` ★${skill.stars}`) : '';
+ const desc = skill.description
+ ? colors.muted(` - ${skill.description.slice(0, 50)}${skill.description.length > 50 ? '...' : ''}`)
+ : '';
+ console.log(` ${colors.cyan(symbols.bullet)} ${colors.primary(skill.name)}${stars}${desc}`);
+ if (!this.quiet) {
+ console.log(` ${colors.muted(skill.source)}`);
+ }
+ }
+ console.log('');
+ }
+ } catch (err) {
+ if (err instanceof RateLimitError) {
+ s.stop(colors.warning('Rate limited by GitHub API'));
+ console.log(colors.muted('Set GITHUB_TOKEN env var or wait before retrying.'));
+ } else {
+ s.stop(colors.warning('Federated search failed'));
+ }
+ }
+ }
+
if (results.length === 0) {
console.log(colors.muted('No skills found matching your search'));
console.log('');
console.log(colors.muted('Try:'));
- console.log(colors.muted(' skillkit find --top # Show featured skills'));
- console.log(colors.muted(' skillkit ui # Browse in TUI'));
+ console.log(colors.muted(' skillkit find --top # Show featured skills'));
+ console.log(colors.muted(' skillkit find -f # Search external registries'));
+ console.log(colors.muted(' skillkit ui # Browse in TUI'));
return 0;
}
diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts
index 295ee6b0..68799556 100644
--- a/packages/cli/src/commands/index.ts
+++ b/packages/cli/src/commands/index.ts
@@ -108,3 +108,9 @@ export {
// Tree command for hierarchical skill browsing (Phase 21)
export { TreeCommand } from './tree.js';
+
+// Quick setup (zero-friction entry)
+export { QuickCommand } from './quick.js';
+
+// SKILL.md ecosystem
+export { SkillMdValidateCommand, SkillMdInitCommand, SkillMdCheckCommand } from './skillmd.js';
diff --git a/packages/cli/src/commands/quick.ts b/packages/cli/src/commands/quick.ts
new file mode 100644
index 00000000..9e69f05e
--- /dev/null
+++ b/packages/cli/src/commands/quick.ts
@@ -0,0 +1,375 @@
+import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
+import { join, resolve, normalize } from 'node:path';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+import { Command } from 'clipanion';
+import {
+ type ProjectProfile,
+ type SkillMetadata,
+ type AgentType,
+ ContextManager,
+ RecommendationEngine,
+ loadIndex as loadIndexFromCache,
+ isIndexStale,
+ buildSkillIndex,
+ saveIndex,
+ KNOWN_SKILL_REPOS,
+ isPathInside,
+ isLocalPath,
+ detectProvider,
+} from '@skillkit/core';
+import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
+import { getInstallDir, saveSkillMetadata } from '../helpers.js';
+import {
+ welcome,
+ spinner,
+ step,
+ success,
+ error,
+ warn,
+ colors,
+ symbols,
+ confirm,
+ select,
+ outro,
+ formatAgent,
+ getAgentIcon,
+ isCancel,
+ cancel,
+ showProjectSummary,
+ progressBar,
+ formatQualityBadge,
+ saveLastAgents,
+} from '../onboarding/index.js';
+
+function truncate(str: string, maxLen: number): string {
+ if (str.length <= maxLen) return str;
+ return str.slice(0, maxLen - 3) + '...';
+}
+
+export class QuickCommand extends Command {
+ static override paths = [['quick']];
+
+ static override usage = Command.Usage({
+ description: 'Zero-friction skill setup: detect agents, analyze project, recommend and install',
+ examples: [
+ ['Quick setup', '$0 quick'],
+ ],
+ });
+
+ async execute(): Promise {
+ const s = spinner();
+
+ try {
+ welcome();
+
+ step(`${colors.bold('Quick Setup')} - zero-friction skill installation`);
+ console.log('');
+
+ s.start('Detecting installed AI agents...');
+ const allAdapters = getAllAdapters();
+ const detectedAgents: AgentType[] = [];
+
+ for (const adapter of allAdapters) {
+ try {
+ const installDir = getInstallDir(false, adapter.type);
+ const globalDir = getInstallDir(true, adapter.type);
+ if (existsSync(installDir) || existsSync(globalDir) || existsSync(adapter.configFile)) {
+ detectedAgents.push(adapter.type);
+ }
+ } catch {
+ // skip
+ }
+ }
+
+ if (detectedAgents.length === 0) {
+ const fallback = await detectAgent();
+ detectedAgents.push(fallback);
+ }
+
+ s.stop(`Detected ${detectedAgents.length} agent${detectedAgents.length !== 1 ? 's' : ''}: ${detectedAgents.map(formatAgent).join(', ')}`);
+
+ s.start('Analyzing project...');
+ const targetPath = resolve(process.cwd());
+ const manager = new ContextManager(targetPath);
+ let context = manager.get();
+ if (!context) {
+ context = manager.init();
+ }
+ s.stop('Project analyzed');
+
+ if (!context) {
+ error('Failed to analyze project');
+ return 1;
+ }
+
+ const profile: ProjectProfile = {
+ name: context.project.name,
+ type: context.project.type,
+ stack: context.stack,
+ patterns: context.patterns,
+ installedSkills: context.skills?.installed || [],
+ excludedSkills: context.skills?.excluded || [],
+ };
+
+ const languages = profile.stack.languages.map((l: { name: string; version?: string }) => `${l.name}${l.version ? ` ${l.version}` : ''}`);
+ const frameworks = profile.stack.frameworks.map((f: { name: string; version?: string }) => `${f.name}${f.version ? ` ${f.version}` : ''}`);
+
+ showProjectSummary({
+ name: profile.name,
+ type: profile.type,
+ languages,
+ frameworks,
+ });
+
+ let index = loadIndexFromCache();
+
+ if (!index || index.skills.length === 0) {
+ s.start('Building skill index from known sources...');
+ try {
+ const result = await buildSkillIndex(KNOWN_SKILL_REPOS, (message: string) => {
+ s.message(message);
+ });
+ index = result.index;
+ saveIndex(index);
+ s.stop(`Indexed ${index.skills.length} skills`);
+ } catch {
+ s.stop(colors.error('Failed to build index'));
+ warn('Could not fetch skill index. Try running: skillkit recommend --update');
+ return 1;
+ }
+ } else if (isIndexStale(index)) {
+ step(colors.muted('Skill index is stale. Run "skillkit recommend --update" to refresh.'));
+ }
+
+ const engine = new RecommendationEngine();
+ engine.loadIndex(index);
+
+ const result = engine.recommend(profile, {
+ limit: 5,
+ minScore: 20,
+ excludeInstalled: true,
+ includeReasons: true,
+ });
+
+ const recommendations = result.recommendations;
+
+ if (recommendations.length === 0) {
+ warn('No matching skills found for your project.');
+ console.log(colors.muted('Try running: skillkit recommend --update'));
+ return 0;
+ }
+
+ console.log('');
+ console.log(colors.bold(`Top ${recommendations.length} Recommended Skills:`));
+ console.log('');
+
+ const options: Array<{ value: string; label: string; hint?: string }> = [];
+
+ for (let i = 0; i < recommendations.length; i++) {
+ const rec = recommendations[i];
+ let scoreColor: (text: string) => string;
+ if (rec.score >= 70) {
+ scoreColor = colors.success;
+ } else if (rec.score >= 50) {
+ scoreColor = colors.warning;
+ } else {
+ scoreColor = colors.muted;
+ }
+ const scoreBar = progressBar(rec.score, 100, 10);
+ const qualityScore = rec.skill.quality ?? null;
+ const qualityDisplay = typeof qualityScore === 'number' && Number.isFinite(qualityScore)
+ ? ` ${formatQualityBadge(qualityScore)}`
+ : '';
+
+ console.log(` ${colors.bold(`${i + 1}.`)} ${scoreColor(`${rec.score}%`)} ${colors.dim(scoreBar)} ${colors.bold(rec.skill.name)}${qualityDisplay}`);
+
+ if (rec.skill.description) {
+ console.log(` ${colors.muted(truncate(rec.skill.description, 70))}`);
+ }
+
+ options.push({
+ value: `${i}`,
+ label: `${rec.skill.name} (${rec.score}% match)`,
+ hint: rec.skill.source || undefined,
+ });
+ }
+
+ console.log('');
+
+ const skipOption = { value: 'skip', label: 'Skip installation' };
+ const selectResult = await select({
+ message: 'Select a skill to install',
+ options: [...options, skipOption],
+ });
+
+ if (isCancel(selectResult) || selectResult === 'skip') {
+ cancel('Quick setup complete (no installation)');
+ return 0;
+ }
+
+ const selectedIndex = parseInt(selectResult as string, 10);
+ const selectedSkill = recommendations[selectedIndex];
+
+ if (!selectedSkill || !selectedSkill.skill.source) {
+ error('Selected skill has no installable source');
+ return 1;
+ }
+
+ const agentDisplay = detectedAgents.length <= 3
+ ? detectedAgents.map(formatAgent).join(', ')
+ : `${detectedAgents.slice(0, 2).map(formatAgent).join(', ')} +${detectedAgents.length - 2} more`;
+
+ const confirmResult = await confirm({
+ message: `Install ${colors.bold(selectedSkill.skill.name)} to ${agentDisplay}?`,
+ initialValue: true,
+ });
+
+ if (isCancel(confirmResult) || !confirmResult) {
+ cancel('Installation cancelled');
+ return 0;
+ }
+
+ saveLastAgents(detectedAgents);
+
+ const providerAdapter = detectProvider(selectedSkill.skill.source);
+
+ if (!providerAdapter) {
+ error(`Could not detect provider for: ${selectedSkill.skill.source}`);
+ return 1;
+ }
+
+ s.start(`Fetching ${selectedSkill.skill.name}...`);
+
+ const cloneResult = await providerAdapter.clone(selectedSkill.skill.source, '', { depth: 1 });
+
+ if (!cloneResult.success || !cloneResult.path) {
+ s.stop(colors.error(cloneResult.error || 'Failed to fetch source'));
+ return 1;
+ }
+
+ const discoveredSkills = cloneResult.discoveredSkills || [];
+ const matchedSkill = discoveredSkills.find(ds => ds.name === selectedSkill.skill.name) || discoveredSkills[0];
+
+ if (!matchedSkill) {
+ s.stop(colors.error('Skill not found in repository'));
+ return 1;
+ }
+
+ s.stop(`Found ${selectedSkill.skill.name}`);
+
+ let primaryPath: string | null = null;
+ const installedAgents: string[] = [];
+
+ for (const agentType of detectedAgents) {
+ const adapter = getAdapter(agentType);
+ const installDir = getInstallDir(false, agentType);
+
+ if (!existsSync(installDir)) {
+ mkdirSync(installDir, { recursive: true });
+ }
+
+ const sanitizedName = matchedSkill.name.split(/[/\\]/).pop() || matchedSkill.name;
+ const targetInstallPath = normalize(join(installDir, sanitizedName));
+
+ if (!isPathInside(targetInstallPath, installDir)) {
+ error(`Skipping ${matchedSkill.name} for ${adapter.name} (install path escapes target directory)`);
+ continue;
+ }
+
+ const securityRoot = cloneResult.tempRoot || cloneResult.path;
+ if (!isPathInside(matchedSkill.path, securityRoot)) {
+ error(`Skipping ${matchedSkill.name} for ${adapter.name} (path traversal detected)`);
+ continue;
+ }
+
+ const useSymlink = detectedAgents.length > 1 && primaryPath !== null;
+
+ s.start(`Installing to ${adapter.name}${useSymlink ? ' (symlink)' : ''}...`);
+
+ try {
+ if (existsSync(targetInstallPath)) {
+ rmSync(targetInstallPath, { recursive: true, force: true });
+ }
+
+ if (useSymlink && primaryPath) {
+ symlinkSync(primaryPath, targetInstallPath, 'dir');
+ } else {
+ cpSync(matchedSkill.path, targetInstallPath, { recursive: true, dereference: true });
+ if (detectedAgents.length > 1 && primaryPath === null) {
+ primaryPath = targetInstallPath;
+ }
+
+ const packageJsonPath = join(targetInstallPath, 'package.json');
+ if (existsSync(packageJsonPath)) {
+ s.stop(`Installed to ${adapter.name}`);
+ s.start('Installing npm dependencies...');
+ try {
+ await execFileAsync('npm', ['install', '--production'], { cwd: targetInstallPath });
+ s.stop('Dependencies installed');
+ } catch {
+ s.stop(colors.warning('Dependencies failed'));
+ console.log(colors.muted('Run manually: npm install in ' + targetInstallPath));
+ }
+ s.start('Finishing installation...');
+ }
+ }
+
+ const metadata: SkillMetadata = {
+ name: matchedSkill.name,
+ description: selectedSkill.skill.description || '',
+ source: selectedSkill.skill.source,
+ sourceType: providerAdapter.type,
+ subpath: matchedSkill.name,
+ installedAt: new Date().toISOString(),
+ enabled: true,
+ };
+ saveSkillMetadata(targetInstallPath, metadata);
+
+ installedAgents.push(agentType);
+ s.stop(`Installed to ${adapter.name}${useSymlink ? ' (symlink)' : ''}`);
+ } catch (err) {
+ s.stop(colors.error(`Failed to install to ${adapter.name}`));
+ console.log(colors.muted(err instanceof Error ? err.message : String(err)));
+ }
+ }
+
+ const cleanupPath = cloneResult.tempRoot || cloneResult.path;
+ if (!isLocalPath(selectedSkill.skill.source) && cleanupPath && existsSync(cleanupPath)) {
+ rmSync(cleanupPath, { recursive: true, force: true });
+ }
+
+ if (installedAgents.length > 0) {
+ console.log('');
+ success(`Installed ${colors.bold(matchedSkill.name)} to ${installedAgents.length} agent${installedAgents.length !== 1 ? 's' : ''}`);
+ for (const a of installedAgents) {
+ console.log(colors.muted(` ${symbols.success} ${getAgentIcon(a)} ${formatAgent(a)}`));
+ }
+
+ console.log('');
+ const badgeUrl = `https://img.shields.io/badge/SkillKit-${encodeURIComponent(matchedSkill.name)}-black?style=flat-square`;
+ console.log(colors.dim('Add to your README:'));
+ console.log(colors.muted(` [](https://agenstskills.com)`));
+
+ outro('Quick setup complete!');
+
+ console.log('');
+ console.log(colors.muted('Next steps:'));
+ console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit sync')} to update agent configs`));
+ console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit recommend')} for more suggestions`));
+ console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit list')} to see installed skills`));
+ console.log('');
+ } else {
+ warn('No agents were installed');
+ }
+
+ return 0;
+ } catch (err) {
+ s.stop(colors.error('Quick setup failed'));
+ console.log(colors.muted(err instanceof Error ? err.message : String(err)));
+ return 1;
+ }
+ }
+}
diff --git a/packages/cli/src/commands/skillmd.ts b/packages/cli/src/commands/skillmd.ts
new file mode 100644
index 00000000..5c5cef53
--- /dev/null
+++ b/packages/cli/src/commands/skillmd.ts
@@ -0,0 +1,440 @@
+import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs';
+import { join, resolve, basename, relative } from 'node:path';
+import { Command, Option } from 'clipanion';
+import {
+ colors,
+ symbols,
+ spinner,
+ step,
+ success,
+ error,
+ warn,
+ header,
+} from '../onboarding/index.js';
+
+interface SkillMdValidation {
+ path: string;
+ exists: boolean;
+ hasName: boolean;
+ hasDescription: boolean;
+ hasTriggers: boolean;
+ hasCapabilities: boolean;
+ triggerCount: number;
+ capabilityCount: number;
+ score: number;
+ issues: string[];
+}
+
+function validateSkillMd(filePath: string): SkillMdValidation {
+ const result: SkillMdValidation = {
+ path: filePath,
+ exists: false,
+ hasName: false,
+ hasDescription: false,
+ hasTriggers: false,
+ hasCapabilities: false,
+ triggerCount: 0,
+ capabilityCount: 0,
+ score: 0,
+ issues: [],
+ };
+
+ if (!existsSync(filePath)) {
+ result.issues.push('File does not exist');
+ return result;
+ }
+
+ result.exists = true;
+ const content = readFileSync(filePath, 'utf-8');
+
+ if (!content.trim()) {
+ result.issues.push('File is empty');
+ return result;
+ }
+
+ const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
+ const bodyContent = frontmatterMatch
+ ? content.slice(frontmatterMatch[0].length)
+ : content;
+
+ if (frontmatterMatch) {
+ const frontmatter = frontmatterMatch[1];
+ if (/^name:\s*.+$/m.test(frontmatter)) result.hasName = true;
+ if (/^description:\s*.+$/m.test(frontmatter)) result.hasDescription = true;
+ }
+
+ if (!result.hasName) {
+ if (/^#\s+.+$/m.test(bodyContent)) result.hasName = true;
+ }
+
+ if (!result.hasDescription) {
+ if (/^##?\s*(description|about|overview)\b/im.test(bodyContent)) {
+ result.hasDescription = true;
+ } else {
+ const lines = bodyContent.split(/\r?\n/).filter(l => l.trim());
+ const nonHeaderLines = lines.filter(l => !l.startsWith('#'));
+ if (nonHeaderLines.length >= 2) result.hasDescription = true;
+ }
+ }
+
+ const triggerPatterns = [
+ /triggers?\s*when/i,
+ /when\s*to\s*use/i,
+ /use\s*this\s*when/i,
+ /\*\*triggers?\b/i,
+ /^[-*]\s+.+(when|if|pattern|trigger)/im,
+ /glob:/i,
+ ];
+
+ for (const pattern of triggerPatterns) {
+ if (pattern.test(content)) {
+ result.hasTriggers = true;
+ break;
+ }
+ }
+
+ if (result.hasTriggers) {
+ const triggerSection = content.match(/triggers?\s*when[:\s]*\n((?:[-*]\s+.+\n?)+)/i);
+ result.triggerCount = triggerSection
+ ? (triggerSection[1].match(/^[-*]\s+/gm) || []).length
+ : 1;
+ }
+
+ const capabilityPatterns = [
+ /capabilities?[:\s]/i,
+ /features?[:\s]/i,
+ /what\s*(it|this)\s*(does|can)/i,
+ /^##?\s*capabilities/im,
+ /^##?\s*features/im,
+ ];
+
+ for (const pattern of capabilityPatterns) {
+ if (pattern.test(content)) {
+ result.hasCapabilities = true;
+ break;
+ }
+ }
+
+ if (result.hasCapabilities) {
+ const capSection = content.match(/(?:capabilities?|features?)[:\s]*\n((?:[-*]\s+.+\n?)+)/i);
+ result.capabilityCount = capSection
+ ? (capSection[1].match(/^[-*]\s+/gm) || []).length
+ : 1;
+ }
+
+ if (!result.hasName) result.issues.push('Missing name field');
+ if (!result.hasDescription) result.issues.push('Missing description section');
+ if (!result.hasTriggers) result.issues.push('No trigger patterns found');
+ if (!result.hasCapabilities) result.issues.push('No capabilities list found');
+
+ let score = 0;
+ if (result.exists) score += 10;
+ if (result.hasName) score += 20;
+ if (result.hasDescription) score += 25;
+ if (result.hasTriggers) score += 20;
+ if (result.hasCapabilities) score += 15;
+ if (result.triggerCount >= 3) score += 5;
+ if (result.capabilityCount >= 3) score += 5;
+
+ if (frontmatterMatch) {
+ const fm = frontmatterMatch[1];
+ if (/^version:/m.test(fm)) score += 3;
+ if (/^license:/m.test(fm)) score += 2;
+ if (/^tags:/m.test(fm)) score += 3;
+ if (/^metadata:/m.test(fm)) score += 2;
+ }
+
+ result.score = Math.min(100, score);
+ return result;
+}
+
+function printValidation(validation: SkillMdValidation, verbose = false): void {
+ const scoreColor = validation.score >= 80
+ ? colors.success
+ : validation.score >= 60
+ ? colors.warning
+ : colors.error;
+
+ console.log(` ${colors.muted('Score:')} ${scoreColor(`${validation.score}`)}/100`);
+ console.log(` ${validation.hasName ? colors.success(symbols.success) : colors.error(symbols.error)} Name field`);
+ console.log(` ${validation.hasDescription ? colors.success(symbols.success) : colors.error(symbols.error)} Description section`);
+ console.log(` ${validation.hasTriggers ? colors.success(symbols.success) : colors.error(symbols.error)} Trigger patterns${validation.triggerCount > 0 ? ` (${validation.triggerCount})` : ''}`);
+ console.log(` ${validation.hasCapabilities ? colors.success(symbols.success) : colors.error(symbols.error)} Capabilities list${validation.capabilityCount > 0 ? ` (${validation.capabilityCount})` : ''}`);
+
+ if (verbose && validation.issues.length > 0) {
+ console.log('');
+ console.log(` ${colors.warning('Issues:')}`);
+ for (const issue of validation.issues) {
+ console.log(` ${colors.warning(symbols.warning)} ${issue}`);
+ }
+ }
+}
+
+export class SkillMdValidateCommand extends Command {
+ static override paths = [['skillmd', 'validate'], ['skill-md', 'validate']];
+
+ static override usage = Command.Usage({
+ description: 'Validate a SKILL.md file against the standard',
+ examples: [
+ ['Validate SKILL.md in current directory', '$0 skillmd validate'],
+ ['Validate specific file', '$0 skillmd validate ./path/to/SKILL.md'],
+ ],
+ });
+
+ targetPath = Option.String({ required: false, name: 'path' });
+
+ verbose = Option.Boolean('--verbose,-v', false, {
+ description: 'Show detailed validation results',
+ });
+
+ json = Option.Boolean('--json', false, {
+ description: 'Output as JSON',
+ });
+
+ async execute(): Promise {
+ const targetPath = this.targetPath || join(process.cwd(), 'SKILL.md');
+ const resolvedPath = resolve(targetPath);
+ const filePath = resolvedPath.endsWith('SKILL.md') ? resolvedPath : join(resolvedPath, 'SKILL.md');
+
+ if (!this.json) {
+ header('SKILL.md Validation');
+ step(`Validating: ${colors.cyan(filePath)}`);
+ console.log('');
+ }
+
+ const validation = validateSkillMd(filePath);
+
+ if (this.json) {
+ console.log(JSON.stringify(validation, null, 2));
+ return validation.score >= 60 ? 0 : 1;
+ }
+
+ console.log(colors.primary(basename(filePath)));
+ printValidation(validation, this.verbose);
+ console.log('');
+
+ if (validation.score >= 80) {
+ success(`SKILL.md is compliant (score: ${validation.score}/100)`);
+ } else if (validation.score >= 60) {
+ warn(`SKILL.md needs improvement (score: ${validation.score}/100)`);
+ } else {
+ error(`SKILL.md does not meet minimum standard (score: ${validation.score}/100)`);
+ }
+
+ return validation.score >= 60 ? 0 : 1;
+ }
+}
+
+export class SkillMdInitCommand extends Command {
+ static override paths = [['skillmd', 'init'], ['skill-md', 'init']];
+
+ static override usage = Command.Usage({
+ description: 'Create a template SKILL.md in the current directory',
+ examples: [
+ ['Create SKILL.md template', '$0 skillmd init'],
+ ['Create with custom name', '$0 skillmd init --name my-skill'],
+ ],
+ });
+
+ name = Option.String('--name,-n', {
+ description: 'Skill name',
+ });
+
+ force = Option.Boolean('--force,-f', false, {
+ description: 'Overwrite existing SKILL.md',
+ });
+
+ async execute(): Promise {
+ const outputPath = join(process.cwd(), 'SKILL.md');
+
+ if (existsSync(outputPath) && !this.force) {
+ warn('SKILL.md already exists');
+ console.log(colors.muted('Use --force to overwrite'));
+ return 1;
+ }
+
+ const skillName = this.name || basename(process.cwd());
+ const formattedName = skillName
+ .split('-')
+ .map((w: string) => w.charAt(0).toUpperCase() + w.slice(1))
+ .join(' ');
+
+ const template = [
+ '---',
+ `name: ${skillName}`,
+ 'description: What this skill does and when to use it',
+ 'version: "1.0"',
+ 'license: MIT',
+ 'tags: [general]',
+ 'metadata:',
+ ' author: your-name',
+ '---',
+ '',
+ `# ${formattedName}`,
+ '',
+ 'Brief description of what this skill provides to AI coding agents.',
+ '',
+ '## Triggers when:',
+ `- User asks about ${skillName} related tasks`,
+ `- Project contains ${skillName} configuration files`,
+ `- Code changes involve ${skillName} patterns`,
+ '',
+ '## Capabilities:',
+ `- Provides best practices for ${skillName}`,
+ '- Generates boilerplate code and configurations',
+ '- Validates existing implementations',
+ '- Suggests improvements and optimizations',
+ '',
+ '## Steps',
+ '1. First step the AI agent should take',
+ '2. Second step with specific instructions',
+ '3. Third step with expected outcome',
+ '',
+ '## Examples',
+ '',
+ '```',
+ 'Example code or configuration here',
+ '```',
+ '',
+ ].join('\n');
+
+ writeFileSync(outputPath, template);
+ success(`Created SKILL.md for "${skillName}"`);
+ console.log('');
+ console.log(colors.muted('Next steps:'));
+ console.log(` ${colors.cyan('1.')} Edit SKILL.md with your skill instructions`);
+ console.log(` ${colors.cyan('2.')} Run ${colors.cyan('skillkit skillmd validate')} to check compliance`);
+ console.log(` ${colors.cyan('3.')} Run ${colors.cyan('skillkit publish submit')} to share with the marketplace`);
+
+ return 0;
+ }
+}
+
+export class SkillMdCheckCommand extends Command {
+ static override paths = [['skillmd', 'check'], ['skill-md', 'check']];
+
+ static override usage = Command.Usage({
+ description: 'Check all SKILL.md files in the project for compliance',
+ examples: [
+ ['Check current directory', '$0 skillmd check'],
+ ['Check specific directory', '$0 skillmd check ./skills'],
+ ],
+ });
+
+ targetPath = Option.String({ required: false, name: 'path' });
+
+ verbose = Option.Boolean('--verbose,-v', false, {
+ description: 'Show detailed validation results',
+ });
+
+ async execute(): Promise {
+ const targetPath = resolve(this.targetPath || process.cwd());
+
+ header('SKILL.md Compliance Check');
+
+ const s = spinner();
+ s.start('Scanning for SKILL.md files...');
+ const skillMdFiles = this.findSkillMdFiles(targetPath);
+ s.stop(`Found ${skillMdFiles.length} SKILL.md file(s)`);
+
+ if (skillMdFiles.length === 0) {
+ warn('No SKILL.md files found');
+ console.log(colors.muted(`Searched: ${targetPath}`));
+ console.log('');
+ console.log(colors.muted('Create one with:'));
+ console.log(` ${colors.cyan('skillkit skillmd init')}`);
+ return 0;
+ }
+
+ const validations: SkillMdValidation[] = skillMdFiles.map(f => validateSkillMd(f));
+ validations.sort((a, b) => b.score - a.score);
+
+ console.log('');
+
+ for (const validation of validations) {
+ const relativePath = relative(targetPath, validation.path);
+ const scoreColor = validation.score >= 80 ? colors.success : validation.score >= 60 ? colors.warning : colors.error;
+ console.log(`${scoreColor(symbols.bullet)} ${colors.primary(relativePath)} ${colors.muted(`(${validation.score}/100)`)}`);
+ if (this.verbose) {
+ printValidation(validation, true);
+ console.log('');
+ }
+ }
+
+ console.log('');
+
+ const passing = validations.filter(v => v.score >= 60).length;
+ const failing = validations.filter(v => v.score < 60).length;
+ const avgScore = Math.round(validations.reduce((sum, v) => sum + v.score, 0) / validations.length);
+
+ console.log(colors.muted('Summary:'));
+ console.log(` ${colors.muted('Total:')} ${validations.length}`);
+ console.log(` ${colors.success(symbols.success)} Passing (60+): ${passing}`);
+ if (failing > 0) {
+ console.log(` ${colors.error(symbols.error)} Failing: ${failing}`);
+ }
+ console.log(` ${colors.muted('Average score:')} ${avgScore}/100`);
+ console.log('');
+
+ if (failing > 0) {
+ error(`${failing} SKILL.md file(s) below minimum standard`);
+ return 1;
+ }
+
+ success('All SKILL.md files are compliant');
+ return 0;
+ }
+
+ private findSkillMdFiles(dir: string): string[] {
+ const results: string[] = [];
+ const directFile = join(dir, 'SKILL.md');
+ if (existsSync(directFile)) results.push(directFile);
+
+ const searchDirs = [
+ join(dir, 'skills'),
+ join(dir, '.claude', 'skills'),
+ join(dir, '.cursor', 'skills'),
+ join(dir, '.codex', 'skills'),
+ join(dir, '.github', 'skills'),
+ ];
+
+ for (const searchDir of searchDirs) {
+ if (!existsSync(searchDir)) continue;
+ this.scanDir(searchDir, results, 0);
+ }
+
+ try {
+ const entries = readdirSync(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const entrySkillMd = join(dir, entry.name, 'SKILL.md');
+ if (existsSync(entrySkillMd) && !results.includes(entrySkillMd)) {
+ results.push(entrySkillMd);
+ }
+ }
+ } catch {
+ // ignore read errors
+ }
+
+ return results;
+ }
+
+ private scanDir(dir: string, results: string[], depth: number): void {
+ if (depth > 3) return;
+ try {
+ const entries = readdirSync(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ const entryPath = join(dir, entry.name);
+ if (entry.isFile() && entry.name === 'SKILL.md') {
+ if (!results.includes(entryPath)) results.push(entryPath);
+ }
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
+ this.scanDir(entryPath, results, depth + 1);
+ }
+ }
+ } catch {
+ // ignore read errors
+ }
+ }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b63034ea..4b826049 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -104,3 +104,6 @@ export * from './execution/index.js';
// Hybrid Search (QMD-Inspired Vector + Keyword Search)
export * from './search/index.js';
+
+// Federated Registry (External Skill Sources)
+export * from './registry/index.js';
diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts
new file mode 100644
index 00000000..e3fc26d7
--- /dev/null
+++ b/packages/core/src/registry/index.ts
@@ -0,0 +1,163 @@
+export interface ExternalSkill {
+ name: string;
+ description: string;
+ source: string;
+ registry: string;
+ path?: string;
+ stars?: number;
+ updatedAt?: string;
+}
+
+export interface ExternalRegistry {
+ name: string;
+ search(query: string, options?: { limit?: number; timeoutMs?: number }): Promise;
+}
+
+export interface FederatedResult {
+ skills: ExternalSkill[];
+ registries: string[];
+ total: number;
+ query: string;
+}
+
+export class RateLimitError extends Error {
+ constructor(registry: string) {
+ super(`Rate limited by ${registry} API. Authenticate with a token or wait before retrying.`);
+ this.name = 'RateLimitError';
+ }
+}
+
+export class GitHubSkillRegistry implements ExternalRegistry {
+ name = 'github';
+ private baseUrl = 'https://api.github.com';
+
+ async search(query: string, options?: { limit?: number; timeoutMs?: number }): Promise {
+ const limit = options?.limit ?? 20;
+ const timeoutMs = options?.timeoutMs ?? 10_000;
+ const searchQuery = `SKILL.md ${query} in:path,file`;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+
+ try {
+ const headers: Record = {
+ Accept: 'application/vnd.github.v3+json',
+ 'User-Agent': 'skillkit-cli',
+ };
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
+ if (token) {
+ headers.Authorization = `Bearer ${token}`;
+ }
+
+ const response = await fetch(
+ `${this.baseUrl}/search/code?q=${encodeURIComponent(searchQuery)}&per_page=${limit}`,
+ {
+ headers,
+ signal: controller.signal,
+ },
+ );
+ clearTimeout(timer);
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new RateLimitError(this.name);
+ }
+ return [];
+ }
+
+ const data = (await response.json()) as {
+ items?: Array<{
+ repository: {
+ full_name: string;
+ description?: string;
+ html_url: string;
+ stargazers_count?: number;
+ updated_at?: string;
+ };
+ path: string;
+ name: string;
+ }>;
+ };
+
+ if (!data.items) return [];
+
+ const seen = new Set();
+ const skills: ExternalSkill[] = [];
+
+ for (const item of data.items) {
+ const repo = item.repository.full_name;
+ if (seen.has(repo)) continue;
+ seen.add(repo);
+
+ const pathParts = item.path.split('/');
+ const skillName =
+ pathParts.length > 1
+ ? pathParts[pathParts.length - 2]
+ : repo.split('/').pop() || repo;
+
+ skills.push({
+ name: skillName,
+ description: item.repository.description || '',
+ source: item.repository.html_url,
+ registry: this.name,
+ path: item.path,
+ stars: item.repository.stargazers_count,
+ updatedAt: item.repository.updated_at,
+ });
+ }
+
+ return skills;
+ } catch (err) {
+ clearTimeout(timer);
+ if (err instanceof RateLimitError) throw err;
+ return [];
+ }
+ }
+}
+
+export class FederatedSearch {
+ private registries: ExternalRegistry[] = [];
+
+ addRegistry(registry: ExternalRegistry): void {
+ this.registries.push(registry);
+ }
+
+ async search(query: string, options?: { limit?: number }): Promise {
+ const limit = options?.limit ?? 20;
+ const results = await Promise.allSettled(
+ this.registries.map((r) => r.search(query, { limit })),
+ );
+
+ const allSkills: ExternalSkill[] = [];
+ const activeRegistries: string[] = [];
+
+ for (let i = 0; i < results.length; i++) {
+ const result = results[i];
+ if (result.status === 'fulfilled' && result.value.length > 0) {
+ allSkills.push(...result.value);
+ activeRegistries.push(this.registries[i].name);
+ } else if (result.status === 'rejected' && result.reason instanceof RateLimitError) {
+ throw result.reason;
+ }
+ }
+
+ const seen = new Set();
+ const deduplicated: ExternalSkill[] = [];
+ for (const skill of allSkills) {
+ const key = `${skill.source}:${skill.name}`;
+ if (!seen.has(key)) {
+ seen.add(key);
+ deduplicated.push(skill);
+ }
+ }
+
+ deduplicated.sort((a, b) => (b.stars ?? 0) - (a.stars ?? 0));
+
+ return {
+ skills: deduplicated.slice(0, limit),
+ registries: activeRegistries,
+ total: deduplicated.length,
+ query,
+ };
+ }
+}
diff --git a/packages/core/src/skills.ts b/packages/core/src/skills.ts
index 31d9aaf1..dfd919df 100644
--- a/packages/core/src/skills.ts
+++ b/packages/core/src/skills.ts
@@ -1,5 +1,5 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
-import { join, basename } from 'node:path';
+import { join, basename, resolve, sep } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js';
@@ -391,6 +391,7 @@ export function validateSkill(skillPath: string): { valid: boolean; errors: stri
}
export function isPathInside(child: string, parent: string): boolean {
- const relative = child.replace(parent, '');
- return !relative.startsWith('..') && !relative.includes('/..');
+ const resolved = resolve(child);
+ const resolvedParent = resolve(parent);
+ return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep);
}
diff --git a/src/core/skills.ts b/src/core/skills.ts
index a3f556ea..9202cc3d 100644
--- a/src/core/skills.ts
+++ b/src/core/skills.ts
@@ -1,5 +1,5 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
-import { join, basename } from 'node:path';
+import { join, basename, resolve, sep } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js';
@@ -328,6 +328,7 @@ export function validateSkill(skillPath: string): { valid: boolean; errors: stri
}
export function isPathInside(child: string, parent: string): boolean {
- const relative = child.replace(parent, '');
- return !relative.startsWith('..') && !relative.includes('/..');
+ const resolved = resolve(child);
+ const resolvedParent = resolve(parent);
+ return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep);
}