agent-skills-standard 1.8.2 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/dist/index.js +35 -16
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -63,10 +63,10 @@ Every skill delivered by this CLI is audited for its footprint in the AI's conte
|
|
|
63
63
|
|
|
64
64
|
| Metric | Savings (vs. Heavy Prompt) | Avg. Footprint | Quality |
|
|
65
65
|
| ------------------ | -------------------------: | -------------- | ------- |
|
|
66
|
-
| **Global Average** | **
|
|
66
|
+
| **Global Average** | **88% Savings** | ~457 tokens | 8.9/10 |
|
|
67
67
|
|
|
68
68
|
> [!IMPORTANT]
|
|
69
|
-
> **Context is Currency**: By reducing instruction overhead by **
|
|
69
|
+
> **Context is Currency**: By reducing instruction overhead by **88%**, you free up your AI's memory and budget for complex logic and large codebases.
|
|
70
70
|
|
|
71
71
|
- **🛡️ Multi-Agent Support**: Out-of-the-box mapping for Cursor, Claude Dev, GitHub Copilot, and more.
|
|
72
72
|
- **📦 Modular Registry**: Don't load everything. Only enable the skills your project actually uses.
|
|
@@ -78,13 +78,13 @@ Every skill delivered by this CLI is audited for its footprint in the AI's conte
|
|
|
78
78
|
|
|
79
79
|
---
|
|
80
80
|
|
|
81
|
-
|
|
81
|
+
### 📜 Benchmark History
|
|
82
82
|
|
|
83
|
-
| Version | Date
|
|
84
|
-
|
|
|
85
|
-
| v1.
|
|
86
|
-
| v1.
|
|
87
|
-
| v1.
|
|
83
|
+
| Version | Date | Skills | Avg Tokens | Savings (%) | Report |
|
|
84
|
+
| ------- | ---------- | ------ | ---------- | ----------- | -------------------------------------- |
|
|
85
|
+
| v1.9.1 | 2026-03-05 | 228 | 457 | 88% | [Report](benchmarks/archive/v1.9.1.md) |
|
|
86
|
+
| v1.9.0 | 2026-03-05 | 228 | 457 | 88% | [Report](benchmarks/archive/v1.9.0.md) |
|
|
87
|
+
| v1.8.0 | 2026-03-02 | 228 | 443 | 88% | [Report](benchmarks/archive/v1.8.0.md) |
|
|
88
88
|
|
|
89
89
|
## � Token Economy & Optimization
|
|
90
90
|
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@ const fs = require("fs-extra");
|
|
|
8
8
|
const path = require("path");
|
|
9
9
|
const yaml = require("js-yaml");
|
|
10
10
|
const zod = require("zod");
|
|
11
|
+
const fetch$1 = require("cross-fetch");
|
|
11
12
|
const child_process = require("child_process");
|
|
12
13
|
class FeedbackService {
|
|
13
14
|
/**
|
|
@@ -867,7 +868,13 @@ class ConfigService {
|
|
|
867
868
|
const allKnownCategories = Object.keys(SKILL_DETECTION_REGISTRY);
|
|
868
869
|
const depsArray = Array.from(projectDeps);
|
|
869
870
|
for (const categoryId of allKnownCategories) {
|
|
871
|
+
const hasMetaFramework = Object.keys(config.skills).some(
|
|
872
|
+
(f) => [Framework.Flutter, Framework.ReactNative].includes(f)
|
|
873
|
+
);
|
|
870
874
|
let category = config.skills[categoryId];
|
|
875
|
+
if (hasMetaFramework && [Framework.Android, Framework.iOS].includes(categoryId)) {
|
|
876
|
+
if (!category) continue;
|
|
877
|
+
}
|
|
871
878
|
const detections = SKILL_DETECTION_REGISTRY[categoryId] || [];
|
|
872
879
|
if (detections.length === 0) continue;
|
|
873
880
|
const isNewCategory = !category;
|
|
@@ -876,8 +883,13 @@ class ConfigService {
|
|
|
876
883
|
(f) => f.id === categoryId
|
|
877
884
|
);
|
|
878
885
|
if (frameworkDef) {
|
|
879
|
-
const hasBaseDeps = frameworkDef.detectionDependencies
|
|
880
|
-
|
|
886
|
+
const hasBaseDeps = frameworkDef.detectionDependencies && frameworkDef.detectionDependencies.length > 0 ? this.hasDependency(
|
|
887
|
+
frameworkDef.detectionDependencies,
|
|
888
|
+
depsArray
|
|
889
|
+
) : false;
|
|
890
|
+
const hasBaseFiles = frameworkDef.detectionFiles && frameworkDef.detectionFiles.length > 0 ? frameworkDef.detectionFiles.some(
|
|
891
|
+
(file) => fs.existsSync(path.join(cwd, file))
|
|
892
|
+
) : false;
|
|
881
893
|
if (!hasBaseDeps && !hasBaseFiles) {
|
|
882
894
|
continue;
|
|
883
895
|
}
|
|
@@ -1275,7 +1287,7 @@ class GithubService {
|
|
|
1275
1287
|
async getRepoTree(owner, repo, ref) {
|
|
1276
1288
|
const url = `${this.baseUrl}/repos/${owner}/${repo}/git/trees/${ref}?recursive=1`;
|
|
1277
1289
|
try {
|
|
1278
|
-
const res = await fetch(url, { headers: this.headers });
|
|
1290
|
+
const res = await fetch$1(url, { headers: this.headers });
|
|
1279
1291
|
if (!res.ok) {
|
|
1280
1292
|
if (res.status === 404) return null;
|
|
1281
1293
|
throw new Error(`GitHub API Error: ${res.status} ${res.statusText}`);
|
|
@@ -1297,7 +1309,7 @@ class GithubService {
|
|
|
1297
1309
|
async getRawFile(owner, repo, ref, path2) {
|
|
1298
1310
|
const url = `${this.rawBaseUrl}/${owner}/${repo}/${ref}/${path2}`;
|
|
1299
1311
|
try {
|
|
1300
|
-
const res = await fetch(url);
|
|
1312
|
+
const res = await fetch$1(url);
|
|
1301
1313
|
if (!res.ok) return null;
|
|
1302
1314
|
return await res.text();
|
|
1303
1315
|
} catch (error) {
|
|
@@ -1312,7 +1324,7 @@ class GithubService {
|
|
|
1312
1324
|
*/
|
|
1313
1325
|
async getLatestReleaseTag(owner, repo) {
|
|
1314
1326
|
try {
|
|
1315
|
-
const res = await fetch(
|
|
1327
|
+
const res = await fetch$1(
|
|
1316
1328
|
`${this.baseUrl}/repos/${owner}/${repo}/releases/latest`,
|
|
1317
1329
|
{
|
|
1318
1330
|
headers: this.headers
|
|
@@ -1333,7 +1345,7 @@ class GithubService {
|
|
|
1333
1345
|
async getRepoInfo(owner, repo) {
|
|
1334
1346
|
const url = `${this.baseUrl}/repos/${owner}/${repo}`;
|
|
1335
1347
|
try {
|
|
1336
|
-
const res = await fetch(url, { headers: this.headers });
|
|
1348
|
+
const res = await fetch$1(url, { headers: this.headers });
|
|
1337
1349
|
if (!res.ok) return null;
|
|
1338
1350
|
return await res.json();
|
|
1339
1351
|
} catch (error) {
|
|
@@ -1650,14 +1662,20 @@ class AgentBridgeService {
|
|
|
1650
1662
|
"This project uses a modular skills library for specialized engineering tasks.",
|
|
1651
1663
|
"",
|
|
1652
1664
|
"> [!IMPORTANT]",
|
|
1653
|
-
">
|
|
1665
|
+
"> **MANDATORY: At the start of EVERY session, read `AGENTS.md` to load the skill index.**",
|
|
1666
|
+
"> Then identify all skills whose triggers match the current task before writing any code.",
|
|
1667
|
+
"",
|
|
1668
|
+
"## Skill Activation Protocol",
|
|
1654
1669
|
"",
|
|
1655
|
-
"
|
|
1670
|
+
"1. **On session start** → Read `AGENTS.md` (skill index with triggers).",
|
|
1671
|
+
"2. **On every task** → Check file globs and keywords against the index.",
|
|
1672
|
+
"3. **On skill match** → Read the full `SKILL.md` file before acting.",
|
|
1673
|
+
"4. **On file write** → Audit against `common/feedback-reporter` skill.",
|
|
1656
1674
|
"",
|
|
1657
1675
|
"## Self-Learning Protocol",
|
|
1658
1676
|
"",
|
|
1659
1677
|
`At the end of any multi-step task with user corrections, load and run **[common/session-retrospective](${prefix}common/session-retrospective/SKILL.md)** to capture skill gaps and prevent repeat rework.`
|
|
1660
|
-
].join("
|
|
1678
|
+
].join("\n");
|
|
1661
1679
|
let detected = false;
|
|
1662
1680
|
for (const file of config.detectionFiles) {
|
|
1663
1681
|
if (await fs.pathExists(path.join(rootDir, file))) {
|
|
@@ -1718,13 +1736,15 @@ class IndexGeneratorService {
|
|
|
1718
1736
|
* @param frameworks List of framework categories to include in the index
|
|
1719
1737
|
* @returns A formatted markdown string representing the index
|
|
1720
1738
|
*/
|
|
1721
|
-
async generate(baseDir
|
|
1722
|
-
const categories = Array.from(/* @__PURE__ */ new Set(["common", ...frameworks]));
|
|
1739
|
+
async generate(baseDir) {
|
|
1723
1740
|
const entries = /* @__PURE__ */ new Set();
|
|
1724
1741
|
const foundationalRules = await this.loadFoundationalRules(baseDir);
|
|
1742
|
+
if (!await fs.pathExists(baseDir)) return this.assembleIndex([]);
|
|
1743
|
+
const categories = await fs.readdir(baseDir);
|
|
1725
1744
|
for (const category of categories) {
|
|
1745
|
+
if (category.startsWith(".")) continue;
|
|
1726
1746
|
const categoryPath = path.join(baseDir, category);
|
|
1727
|
-
if (!await fs.
|
|
1747
|
+
if (!(await fs.stat(categoryPath)).isDirectory()) continue;
|
|
1728
1748
|
const skills = await fs.readdir(categoryPath);
|
|
1729
1749
|
for (const skill of skills) {
|
|
1730
1750
|
const skillPath = path.join(categoryPath, skill, "SKILL.md");
|
|
@@ -2148,8 +2168,7 @@ class SyncService {
|
|
|
2148
2168
|
try {
|
|
2149
2169
|
const generator = new IndexGeneratorService();
|
|
2150
2170
|
const indexContent = await generator.generate(
|
|
2151
|
-
path.join(process.cwd(), agentDef.path)
|
|
2152
|
-
Object.keys(config.skills)
|
|
2171
|
+
path.join(process.cwd(), agentDef.path)
|
|
2153
2172
|
);
|
|
2154
2173
|
await MarkdownUtils.injectIndex(
|
|
2155
2174
|
process.cwd(),
|
|
@@ -2382,7 +2401,7 @@ class SyncCommand {
|
|
|
2382
2401
|
}
|
|
2383
2402
|
}
|
|
2384
2403
|
}
|
|
2385
|
-
const version = "1.
|
|
2404
|
+
const version = "1.9.1";
|
|
2386
2405
|
const pkg = {
|
|
2387
2406
|
version
|
|
2388
2407
|
};
|
|
@@ -2900,7 +2919,7 @@ dotenv.config();
|
|
|
2900
2919
|
const program = new commander.Command();
|
|
2901
2920
|
program.name("agent-skills-standard").description(
|
|
2902
2921
|
"A CLI to manage and sync AI agent skills for Cursor, Claude, Copilot, Windsurf, and more."
|
|
2903
|
-
).version("1.
|
|
2922
|
+
).version("1.9.1");
|
|
2904
2923
|
program.command("init").description("Initialize a .skillsrc configuration file interactively").action(async () => {
|
|
2905
2924
|
const init = new InitCommand();
|
|
2906
2925
|
await init.run();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/services/FeedbackService.ts","../src/commands/feedback.ts","../src/constants/enums.ts","../src/constants/skills.ts","../src/constants/index.ts","../src/services/ConfigService.ts","../src/services/DetectionService.ts","../src/services/InitService.ts","../src/services/GithubService.ts","../src/services/RegistryService.ts","../src/commands/init.ts","../src/services/SkillService.ts","../src/commands/list-skills.ts","../src/services/AgentBridgeService.ts","../src/services/IndexGeneratorService.ts","../src/services/utils/MarkdownUtils.ts","../src/services/SyncService.ts","../src/commands/sync.ts","../src/commands/upgrade.ts","../src/services/GitService.ts","../src/services/SkillDiscoveryService.ts","../src/services/validation/rules.ts","../src/services/SkillValidator.ts","../src/commands/validate-skills.ts","../src/index.ts"],"sourcesContent":["/**\n * Structure of the feedback data payload submitted to the backend.\n * Contains both required issue details and optional context gathered by the AI.\n */\nexport interface FeedbackData {\n /** The specific skill ID that had the issue */\n skill: string;\n /** Detailed description of the problem */\n issue: string;\n\n /** Multi-line context about where the error occurred */\n context?: string;\n /** The AI model used when the issue was detected */\n model?: string;\n /** Proposed fix or improvement */\n suggestion?: string;\n\n /** Exact instruction from the skill that was misinterpreted */\n skillInstruction?: string;\n /** What the AI actually did instead of following the skill */\n actualAction?: string;\n /** Rationale for choosing the incorrect path */\n decisionReason?: string;\n\n /** List of other active skills at the time of the error */\n loadedSkills?: string;\n}\n\n/**\n * Service to handle automated feedback reporting via Proxy Backend.\n * Follows SOLID & KISS: Strictly handles API communication.\n */\nexport class FeedbackService {\n /**\n * Resolves the API URL from environment variables.\n */\n getApiUrl(): string | undefined {\n return process.env.FEEDBACK_API_URL;\n }\n\n /**\n * Submits feedback data to the backend for automatic GitHub Issue creation.\n * Internal proxy handles GitHub tokens, keeping client-side logic tokenless.\n *\n * @param data The feedback payload\n * @returns boolean indicating submission success\n */\n async submit(data: FeedbackData): Promise<boolean> {\n const apiUrl = this.getApiUrl();\n if (!apiUrl) return false;\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'agent-skills-standard-cli',\n },\n body: JSON.stringify(data),\n });\n\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { FeedbackData, FeedbackService } from '../services/FeedbackService';\n\n/**\n * Command for automated skill feedback reporting.\n * Follows KISS: Minimal user output, focusing on functional submission.\n */\nexport class FeedbackCommand {\n private feedbackService: FeedbackService;\n\n constructor(feedbackService?: FeedbackService) {\n this.feedbackService = feedbackService || new FeedbackService();\n }\n\n async run(options: {\n skill?: string;\n issue?: string;\n model?: string;\n context?: string;\n suggestion?: string;\n skillInstruction?: string;\n actualAction?: string;\n decisionReason?: string;\n loadedSkills?: string;\n }) {\n console.log(pc.bold(pc.blue('\\n📣 Agent Skills Feedback Reporter\\n')));\n\n let {\n skill,\n issue,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n } = options;\n\n // Interactive mode if mandatory options are missing\n if (!skill || !issue) {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'skill',\n message:\n 'Which skill ID has the issue? (e.g., flutter/bloc-state-management)',\n when: !skill,\n validate: (input: string) =>\n input.trim().length > 0 || 'Skill ID is required',\n },\n {\n type: 'input',\n name: 'issue',\n message: 'What is the issue? (Brief description)',\n when: !issue,\n validate: (input: string) =>\n input.trim().length > 0 || 'Issue description is required',\n },\n {\n type: 'input',\n name: 'model',\n message: 'AI Model name (optional, e.g., Claude 3.5 Sonnet)',\n when: !model,\n },\n {\n type: 'input',\n name: 'context',\n message: 'Any extra context? (optional, e.g., framework versions)',\n when: !context,\n },\n {\n type: 'input',\n name: 'suggestion',\n message: 'Any suggested improvement? (optional)',\n when: !suggestion,\n },\n {\n type: 'input',\n name: 'skillInstruction',\n message: 'Exact quote from skill (optional)',\n when: !skillInstruction,\n },\n {\n type: 'input',\n name: 'actualAction',\n message: 'What you did instead (optional)',\n when: !actualAction,\n },\n {\n type: 'input',\n name: 'decisionReason',\n message: 'Why you chose this approach (optional)',\n when: !decisionReason,\n },\n {\n type: 'input',\n name: 'loadedSkills',\n message: 'All active skills (optional)',\n when: !loadedSkills,\n },\n ]);\n\n skill = skill || (answers.skill as string);\n issue = issue || (answers.issue as string);\n model = model || (answers.model as string);\n context = context || (answers.context as string);\n suggestion = suggestion || (answers.suggestion as string);\n skillInstruction =\n skillInstruction || (answers.skillInstruction as string);\n actualAction = actualAction || (answers.actualAction as string);\n decisionReason = decisionReason || (answers.decisionReason as string);\n loadedSkills = loadedSkills || (answers.loadedSkills as string);\n\n await this.submit({\n skill: skill!,\n issue: issue!,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n });\n } else {\n await this.submit({\n skill,\n issue,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n });\n }\n }\n\n private async submit(data: FeedbackData) {\n const apiUrl = this.feedbackService.getApiUrl();\n\n if (!apiUrl) {\n console.log(pc.yellow('\\n⚠️ Feedback API not configured.'));\n console.log(\n pc.gray(\n 'Please set the ' +\n pc.bold('FEEDBACK_API_URL') +\n ' environment variable.',\n ),\n );\n return;\n }\n\n console.log(pc.gray(`📤 Sending feedback to ${apiUrl}...`));\n\n const success = await this.feedbackService.submit(data);\n\n if (success) {\n console.log(pc.green('\\n✅ Feedback has been sent successfully!'));\n console.log(\n pc.gray('Thank you for helping improve the Agent Skills Standard.\\n'),\n );\n } else {\n console.log(pc.red('\\n❌ Failed to send feedback.'));\n console.log(\n pc.gray(\n `Please check that the Feedback API is reachable: ${pc.cyan(apiUrl)}\\n`,\n ),\n );\n }\n }\n}\n","export enum Agent {\n Cursor = 'cursor',\n Trae = 'trae',\n Claude = 'claude',\n Copilot = 'copilot',\n Antigravity = 'antigravity',\n OpenAI = 'openai',\n OpenCode = 'opencode',\n Gemini = 'gemini',\n Roo = 'roo',\n Windsurf = 'windsurf',\n Kiro = 'kiro',\n}\n\nexport enum Framework {\n Flutter = 'flutter',\n NestJS = 'nestjs',\n Golang = 'golang',\n NextJS = 'nextjs',\n React = 'react',\n ReactNative = 'react-native',\n Angular = 'angular',\n SpringBoot = 'spring-boot',\n Android = 'android',\n iOS = 'ios',\n Laravel = 'laravel',\n}\n","import { Framework } from './enums';\n\n/**\n * SkillDetection defines how to automatically enable a skill based on project dependencies.\n */\nexport interface SkillDetection {\n /** The skill ID as defined in the registry (e.g., 'riverpod-state-management') */\n id: string;\n /** List of npm or pub packages that indicate this skill is used */\n packages: string[];\n /** Optional list of root folder/file paths (relative to cwd). If any exist, the skill is detected. */\n files?: string[];\n}\n\n/**\n * Registry of automatic skill detection rules grouped by framework.\n */\nexport const SKILL_DETECTION_REGISTRY: Record<string, SkillDetection[]> = {\n [Framework.Flutter]: [\n {\n id: 'riverpod-state-management',\n packages: ['flutter_riverpod', 'riverpod'],\n },\n {\n id: 'bloc-state-management',\n packages: ['flutter_bloc', 'bloc'],\n },\n {\n id: 'auto-route-navigation',\n packages: ['auto_route'],\n },\n {\n id: 'go-router-navigation',\n packages: ['go_router'],\n },\n {\n id: 'getx-navigation',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'getx-state-management',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'localization',\n packages: ['easy_localization'],\n },\n {\n id: 'retrofit-networking',\n packages: ['retrofit'],\n },\n {\n id: 'dependency-injection',\n packages: ['get_it', 'injectable'],\n },\n ],\n [Framework.NestJS]: [\n {\n id: 'caching',\n packages: ['@nestjs/cache-manager', 'cache-manager'],\n },\n {\n id: 'database',\n packages: ['@nestjs/typeorm', '@nestjs/prisma', '@nestjs/mongoose'],\n },\n {\n id: 'security',\n packages: ['@nestjs/passport', 'passport', 'helmet'],\n },\n ],\n [Framework.Android]: [\n {\n id: 'compose',\n packages: ['androidx.compose.ui'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'navigation',\n packages: ['androidx.navigation:navigation-compose'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'legacy-navigation',\n packages: [\n 'androidx.navigation:navigation-fragment',\n 'androidx.navigation:navigation-ui',\n ],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'di',\n packages: ['hilt-android', 'dagger-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'persistence',\n packages: ['androidx.room:room-runtime'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'networking',\n packages: ['retrofit'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'concurrency',\n packages: ['kotlinx-coroutines-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n ],\n [Framework.iOS]: [\n {\n id: 'networking',\n packages: ['Alamofire', 'Moya'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'dependency-injection',\n packages: ['Swinject', 'Resolver'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'persistence',\n packages: ['Realm', 'CoreData', 'SQLite.swift'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'state-management',\n packages: ['ComposableArchitecture', 'CombineRuntime'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ui-navigation',\n packages: ['Coordinator', 'Router'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n ],\n [Framework.ReactNative]: [\n {\n id: 'navigation',\n packages: ['@react-navigation/native'],\n },\n {\n id: 'state-management',\n packages: ['zustand', '@reduxjs/toolkit'],\n },\n {\n id: 'deployment',\n packages: ['react-native-code-push', 'expo-updates'],\n },\n {\n id: 'security',\n packages: ['react-native-keychain', 'react-native-ssl-pinning'],\n },\n {\n id: 'performance',\n packages: ['react-native-fast-image'],\n },\n ],\n [Framework.Laravel]: [\n {\n id: 'api',\n packages: ['laravel/sanctum', 'laravel/passport'],\n },\n {\n id: 'background-processing',\n packages: ['laravel/horizon'],\n },\n {\n id: 'testing',\n packages: ['pestphp/pest', 'phpunit/phpunit'],\n },\n {\n id: 'tooling',\n packages: ['laravel/pint', 'laravel/sail'],\n },\n {\n id: 'database-expert',\n packages: ['laravel/framework'], // Always present, but used for sub-skill mapping\n },\n ],\n [Framework.NextJS]: [\n {\n id: 'pages-router',\n packages: [],\n files: ['pages', 'src/pages'],\n },\n {\n id: 'server-components',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'server-actions',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'data-fetching',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'i18n',\n packages: ['next-intl', 'react-intl', 'next-translate', 'i18next'],\n files: [\n 'middleware.ts',\n 'app/[lang]',\n 'pages/[locale]',\n 'next.config.js',\n ],\n },\n ],\n [Framework.React]: [\n {\n id: 'styling',\n packages: ['tailwind', 'antd', 'sass', 'styled-components', 'emotion'],\n },\n {\n id: 'state-management',\n packages: [\n 'redux',\n '@reduxjs/toolkit',\n 'zustand',\n 'mobx',\n 'recoil',\n 'jotai',\n ],\n },\n {\n id: 'testing',\n packages: [\n 'jest',\n 'vitest',\n '@testing-library/react',\n 'cypress',\n 'playwright',\n ],\n },\n ],\n database: [\n {\n id: 'postgresql',\n packages: ['pg', 'pgx', 'postgres', 'sequelize', 'typeorm', 'prisma'],\n },\n {\n id: 'mongodb',\n packages: ['mongodb', 'mongoose'],\n },\n {\n id: 'redis',\n packages: ['redis', 'ioredis', 'predis'],\n },\n ],\n};\n","import { Agent, Framework } from './enums';\n\nexport { Agent, Framework };\n\nexport const UNIVERSAL_SKILLS = ['common'];\nexport const BACKEND_FRAMEWORKS: Framework[] = [\n Framework.NestJS,\n Framework.Golang,\n Framework.SpringBoot,\n Framework.Laravel,\n];\n\nexport const FRONTEND_FRAMEWORKS: Framework[] = [\n Framework.React,\n Framework.NextJS,\n Framework.Angular,\n];\n\nexport const MOBILE_FRAMEWORKS: Framework[] = [\n Framework.Flutter,\n Framework.Android,\n Framework.iOS,\n Framework.ReactNative,\n];\n\nexport const FRONTEND_REACT_FRAMEWORKS: Framework[] = [\n Framework.NextJS,\n Framework.ReactNative,\n];\n\n/**\n * Sub-skills to exclude from the `common` category based on the selected framework type.\n * Backend: exclude web-only and mobile-only skills.\n * Frontend: exclude backend-only and mobile-only skills.\n * Mobile: exclude web-only and backend-only skills.\n */\nexport const COMMON_SKILL_EXCLUDES: Record<\n 'backend' | 'frontend' | 'mobile',\n string[]\n> = {\n backend: ['accessibility', 'mobile-animation', 'mobile-ux-core'],\n frontend: ['observability', 'mobile-animation', 'mobile-ux-core'],\n mobile: ['accessibility', 'api-design', 'observability'],\n};\n\n/**\n * Classifies a framework ID into its platform type for skill exclusion purposes.\n * Returns null for unknown/hybrid frameworks — no exclusions are applied.\n */\nexport function getFrameworkType(\n framework: string,\n): 'backend' | 'frontend' | 'mobile' | null {\n if (BACKEND_FRAMEWORKS.includes(framework as Framework)) return 'backend';\n if (MOBILE_FRAMEWORKS.includes(framework as Framework)) return 'mobile';\n if (FRONTEND_FRAMEWORKS.includes(framework as Framework)) return 'frontend';\n return null;\n}\n\nexport const DEFAULT_REGISTER =\n 'https://github.com/HoangNguyen0403/agent-skills-standard';\n\nexport const DEFAULT_WORKFLOWS = [\n 'code-review',\n 'codebase-review',\n 'plan-feature',\n 'skill-benchmark',\n];\n\n// Configurable via ENV or hardcoded for production convenience\nexport interface AgentDefinition {\n id: Agent;\n name: string;\n path: string;\n ruleFile: string;\n ruleExtension: string;\n ruleFileName?: string;\n frontmatterStyle: 'cursor' | 'copilot' | 'none';\n detectionFiles: string[];\n}\n\nexport interface FrameworkDefinition {\n id: Framework;\n name: string;\n languages: string[];\n detectionFiles: string[];\n detectionDependencies?: string[];\n languageDetection?: Record<string, string[]>;\n}\n\nexport const getAgentDefinition = (id: Agent): AgentDefinition => {\n switch (id) {\n case Agent.Cursor:\n return {\n id,\n name: 'Cursor',\n path: '.cursor/skills',\n ruleFile: '.cursor/rules',\n ruleExtension: '.mdc',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.cursor', '.cursorrules'],\n };\n case Agent.Trae:\n return {\n id,\n name: 'Trae',\n path: '.trae/skills',\n ruleFile: '.trae/rules',\n ruleExtension: '.mdc',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.trae'],\n };\n case Agent.Claude:\n return {\n id,\n name: 'Claude Code',\n path: '.claude/skills',\n ruleFile: '.', // Root directory for CLAUDE.md\n ruleExtension: '.md',\n ruleFileName: 'CLAUDE.md',\n frontmatterStyle: 'none',\n detectionFiles: ['.claude', 'CLAUDE.md'],\n };\n case Agent.Copilot:\n return {\n id,\n name: 'GitHub Copilot',\n path: '.github/skills',\n ruleFile: '.github/instructions',\n ruleExtension: '.instructions.md',\n frontmatterStyle: 'copilot',\n detectionFiles: ['.github'],\n };\n case Agent.Antigravity:\n return {\n id,\n name: 'Antigravity',\n path: '.agent/skills',\n ruleFile: '.agent/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.agent'],\n };\n case Agent.OpenAI:\n return {\n id,\n name: 'OpenAI',\n path: '.codex/skills',\n ruleFile: '.codex/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.codex'],\n };\n case Agent.OpenCode:\n return {\n id,\n name: 'OpenCode',\n path: '.opencode/skills',\n ruleFile: '.opencode/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.opencode'],\n };\n case Agent.Gemini:\n return {\n id,\n name: 'Gemini',\n path: '.gemini/skills',\n ruleFile: '.gemini/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.gemini'],\n };\n case Agent.Roo:\n return {\n id,\n name: 'Roo Code',\n path: '.roo/skills',\n ruleFile: '.roo/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.roo'],\n };\n case Agent.Windsurf:\n return {\n id,\n name: 'Windsurf',\n path: '.windsurf/skills',\n ruleFile: '.windsurf/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.windsurf', '.windsurfrules'],\n };\n case Agent.Kiro:\n return {\n id,\n name: 'Kiro',\n path: '.kiro/skills',\n ruleFile: '.kiro/rules', // Changed from steering to match AGENT_CONFIGS\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.kiro'],\n };\n }\n};\n\nexport const getFrameworkDefinition = (id: Framework): FrameworkDefinition => {\n switch (id) {\n case Framework.Flutter:\n return {\n id,\n name: 'Flutter',\n languages: ['dart'],\n detectionFiles: ['pubspec.yaml'],\n };\n case Framework.NestJS:\n return {\n id,\n name: 'NestJS',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['nest-cli.json'],\n detectionDependencies: ['@nestjs/core'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.Golang:\n return {\n id,\n name: 'Go (Golang)',\n languages: ['go'],\n detectionFiles: ['go.mod'],\n };\n case Framework.NextJS:\n return {\n id,\n name: 'Next.js',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['next.config.js', 'next.config.mjs'],\n detectionDependencies: ['next'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.React:\n return {\n id,\n name: 'React',\n languages: ['typescript', 'javascript'],\n detectionFiles: [],\n detectionDependencies: ['react', 'react-dom'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.ReactNative:\n return {\n id,\n name: 'React Native',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['metro.config.js'],\n detectionDependencies: ['react-native'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.Angular:\n return {\n id,\n name: 'Angular',\n languages: ['typescript'],\n detectionFiles: ['angular.json'],\n };\n case Framework.SpringBoot:\n return {\n id,\n name: 'Spring Boot',\n languages: ['java', 'kotlin'],\n detectionFiles: ['pom.xml', 'build.gradle', 'build.gradle.kts'],\n languageDetection: {\n kotlin: ['src/main/kotlin', 'build.gradle.kts'],\n java: ['src/main/java'],\n },\n };\n case Framework.Android:\n return {\n id,\n name: 'Android',\n languages: ['kotlin', 'java'],\n detectionFiles: [\n 'build.gradle',\n 'build.gradle.kts',\n 'AndroidManifest.xml',\n ],\n languageDetection: {\n kotlin: ['src/main/kotlin', 'build.gradle.kts'],\n java: ['src/main/java'],\n },\n };\n case Framework.iOS:\n return {\n id,\n name: 'iOS (Swift/SwiftUI)',\n languages: ['swift'],\n detectionFiles: [\n 'Podfile',\n 'Package.swift',\n 'project.pbxproj',\n 'Info.plist',\n ],\n languageDetection: {\n swift: ['.swift'],\n },\n };\n case Framework.Laravel:\n return {\n id,\n name: 'Laravel',\n languages: ['php', 'javascript'],\n detectionFiles: ['composer.json', 'artisan'],\n detectionDependencies: ['laravel/framework'],\n languageDetection: {\n php: ['.php'],\n javascript: ['resources/js', 'vite.config.js'],\n },\n };\n }\n};\n\nexport const SUPPORTED_AGENTS: AgentDefinition[] =\n Object.values(Agent).map(getAgentDefinition);\n\nexport const SUPPORTED_FRAMEWORKS: FrameworkDefinition[] = Object.values(\n Framework,\n).map(getFrameworkDefinition);\n\nexport { SKILL_DETECTION_REGISTRY } from './skills';\nexport type { SkillDetection } from './skills';\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\nimport { z } from 'zod';\nimport {\n Agent,\n BACKEND_FRAMEWORKS,\n COMMON_SKILL_EXCLUDES,\n DEFAULT_REGISTER,\n Framework,\n FrameworkDefinition,\n FRONTEND_REACT_FRAMEWORKS,\n getFrameworkType,\n SKILL_DETECTION_REGISTRY,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\nimport { CategoryConfig, SkillConfig } from '../models/config';\nimport { RegistryMetadata } from '../models/types';\n\nconst SkillConfigSchema = z.object({\n registry: z.string().url(),\n agents: z.array(z.nativeEnum(Agent)).optional(),\n skills: z.record(\n z.string(), // Category name\n z.object({\n ref: z.string().optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n }),\n ),\n custom_overrides: z.array(z.string()).optional(),\n workflows: z.union([z.boolean(), z.array(z.string())]).optional(),\n});\n\n/**\n * Service for managing the `.skillsrc` configuration file.\n * Handles loading, saving, and initial construction of the configuration based on project metadata.\n */\nexport class ConfigService {\n /**\n * Loads and validates the skill configuration from the workspace.\n * @param cwd Current working directory\n * @returns The parsed SkillConfig or null if not found\n * @throws Error if the configuration format is invalid\n */\n async loadConfig(cwd: string = process.cwd()): Promise<SkillConfig | null> {\n const configPath = path.join(cwd, '.skillsrc');\n\n if (!(await fs.pathExists(configPath))) {\n return null;\n }\n\n try {\n const content = await fs.readFile(configPath, 'utf8');\n const rawConfig = yaml.load(content);\n\n // Validate with Zod\n const parsed = SkillConfigSchema.safeParse(rawConfig);\n\n if (!parsed.success) {\n throw new Error(`Invalid .skillsrc format: ${parsed.error.message}`);\n }\n\n return parsed.data as SkillConfig;\n } catch (error) {\n throw new Error(`Failed to load config: ${error}`);\n }\n }\n\n /**\n * Saves the provided configuration to the `.skillsrc` file.\n * @param config The configuration to save\n * @param cwd Current working directory\n */\n async saveConfig(\n config: SkillConfig,\n cwd: string = process.cwd(),\n ): Promise<void> {\n const configPath = path.join(cwd, '.skillsrc');\n await fs.outputFile(configPath, yaml.dump(config));\n }\n\n /**\n * Constructs an initial configuration object based on project analysis.\n * @param framework The primary framework detected\n * @param agents List of enabled AI agents\n * @param registry Registry URL\n * @param metadata Registry metadata for versioning and prefixes\n * @param languages Detected programming languages\n * @param workflows List of workflow names to sync\n * @returns A fresh SkillConfig object\n */\n buildInitialConfig(\n framework: string,\n agents: Agent[],\n registry: string,\n metadata: Partial<RegistryMetadata>,\n languages: string[] = [],\n workflows: string[] = [],\n ): SkillConfig {\n const skills: Record<string, CategoryConfig> = {};\n\n // Add main framework\n skills[framework] = {\n ref: metadata.categories?.[framework]?.version\n ? `${metadata.categories[framework].tag_prefix || ''}${metadata.categories[framework].version}`\n : 'main',\n };\n\n // Specialized Logic: Frontend React-based projects must inherently sync the React category natively.\n if (\n FRONTEND_REACT_FRAMEWORKS.includes(framework as Framework) &&\n metadata.categories?.['react']\n ) {\n skills['react'] = {\n ref: metadata.categories['react'].version\n ? `${metadata.categories['react'].tag_prefix || ''}${metadata.categories['react'].version}`\n : 'main',\n };\n }\n\n // Add associated languages (e.g., typescript, javascript)\n for (const lang of languages) {\n if (metadata.categories?.[lang]) {\n skills[lang] = {\n ref: `${metadata.categories[lang].tag_prefix || ''}${metadata.categories[lang].version}`,\n };\n }\n }\n\n // Add common category if available, with framework-appropriate exclusions\n if (metadata.categories?.['common']) {\n const frameworkType = getFrameworkType(framework);\n const commonExcludes = frameworkType\n ? COMMON_SKILL_EXCLUDES[frameworkType]\n : [];\n\n skills['common'] = {\n ref: `${metadata.categories['common'].tag_prefix || ''}${metadata.categories['common'].version}`,\n ...(commonExcludes.length > 0 && { exclude: commonExcludes }),\n };\n }\n\n // Add database category for backend frameworks\n if (\n BACKEND_FRAMEWORKS.includes(framework as Framework) &&\n metadata.categories?.['database']\n ) {\n skills['database'] = {\n ref: metadata.categories['database'].version\n ? `${metadata.categories['database'].tag_prefix || ''}${metadata.categories['database'].version}`\n : 'main',\n };\n }\n\n return {\n registry,\n agents,\n skills,\n custom_overrides: [],\n workflows: workflows.length > 0 ? workflows : false, // Array if specific, false if empty\n };\n }\n\n /**\n * Identifies sub-skills to exclude based on the absence of their required package dependencies.\n * Scans all categories defined in the config.\n * @param config The current configuration\n * @param projectDeps Current set of project dependencies\n */\n applyDependencyExclusions(\n config: SkillConfig,\n projectDeps: Set<string>,\n cwd: string = process.cwd(),\n ) {\n const depsArray = Array.from(projectDeps);\n\n for (const categoryId in config.skills) {\n const category = config.skills[categoryId];\n const detections = SKILL_DETECTION_REGISTRY[categoryId] || [];\n if (detections.length === 0) continue;\n\n const exclusions = new Set<string>(category.exclude || []);\n\n for (const detection of detections) {\n const hasDeps = this.hasDependency(detection.packages, depsArray);\n const hasDirs = this.hasFiles(detection.files, cwd);\n if (!hasDeps || !hasDirs) {\n exclusions.add(detection.id);\n }\n }\n\n if (exclusions.size > 0) {\n category.exclude = Array.from(exclusions);\n }\n }\n }\n\n /**\n * Automatically re-enables skills that were previously excluded if their dependencies\n * are now present in the project. Scans all categories.\n */\n reconcileDependencies(\n config: SkillConfig,\n projectDeps: Set<string>,\n cwd: string = process.cwd(),\n ): string[] {\n const totalReenabled: string[] = [];\n const allKnownCategories = Object.keys(SKILL_DETECTION_REGISTRY);\n const depsArray = Array.from(projectDeps);\n\n for (const categoryId of allKnownCategories) {\n let category = config.skills[categoryId];\n const detections = SKILL_DETECTION_REGISTRY[categoryId] || [];\n if (detections.length === 0) continue;\n\n const isNewCategory = !category;\n if (isNewCategory) {\n // First check if this is a supported framework and we don't have its base dependencies\n const frameworkDef = SUPPORTED_FRAMEWORKS.find(\n (f: FrameworkDefinition) => f.id === categoryId,\n );\n if (frameworkDef) {\n const hasBaseDeps = frameworkDef.detectionDependencies\n ? this.hasDependency(frameworkDef.detectionDependencies, depsArray)\n : true;\n const hasBaseFiles = this.hasFiles(frameworkDef.detectionFiles, cwd);\n\n if (!hasBaseDeps && !hasBaseFiles) {\n continue; // Skip enabling this category if its base framework isn't detected\n }\n }\n\n const shouldEnableCategory = detections.some(\n (detection) =>\n this.hasDependency(detection.packages, depsArray) &&\n this.hasFiles(detection.files, cwd),\n );\n\n if (shouldEnableCategory) {\n config.skills[categoryId] = { ref: 'main' };\n category = config.skills[categoryId];\n\n const exclusions = detections\n .filter(\n (d) =>\n !this.hasDependency(d.packages, depsArray) ||\n !this.hasFiles(d.files, cwd),\n )\n .map((d) => d.id);\n\n if (exclusions.length > 0) {\n category.exclude = exclusions;\n }\n totalReenabled.push(categoryId);\n }\n continue;\n }\n\n // Existing category reconciliation\n if (!category.exclude) continue;\n\n const currentExclusions = new Set(category.exclude);\n const reenabled: string[] = [];\n\n for (const detection of detections) {\n if (\n currentExclusions.has(detection.id) &&\n this.hasDependency(detection.packages, depsArray) &&\n this.hasFiles(detection.files, cwd)\n ) {\n currentExclusions.delete(detection.id);\n reenabled.push(`${categoryId}/${detection.id}`);\n }\n }\n\n if (reenabled.length > 0) {\n category.exclude =\n currentExclusions.size > 0\n ? Array.from(currentExclusions)\n : undefined;\n totalReenabled.push(...reenabled);\n }\n }\n\n return totalReenabled;\n }\n\n /**\n * Checks if ANY of the required files exist in the project directory.\n */\n private hasFiles(files: string[] | undefined, cwd: string): boolean {\n if (!files || files.length === 0) return true; // If no files required, assume condition met\n for (const file of files) {\n if (fs.existsSync(path.join(cwd, file))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks if ANY of the required dependencies are found in the project.\n */\n private hasDependency(packages: string[], projectDeps: string[]): boolean {\n if (packages.length === 0) return true; // If no packages are required, condition met\n return projectDeps.some((d) =>\n packages.some((pkg) => {\n const depLower = d.toLowerCase();\n const pkgLower = pkg.toLowerCase();\n\n // Exact match\n if (depLower === pkgLower) return true;\n\n // Skip fuzzy matching for short names to avoid noise\n if (pkg.length <= 3) return false;\n\n // Handle scoped packages: @scope/package matches package\n if (depLower.includes('/') && depLower.split('/').pop() === pkgLower)\n return true;\n\n // Handle framework-prefixed packages (e.g. @nestjs/core, flask-cors)\n // Only match if the package is a standalone word in the dependency name\n const parts = depLower.split(/[-/_]/);\n return parts.includes(pkgLower);\n }),\n );\n }\n\n /**\n * Retrieves the registry URL from configuration or returns the default.\n * @param cwd Current working directory\n */\n async getRegistryUrl(cwd: string = process.cwd()): Promise<string> {\n const config = await this.loadConfig(cwd).catch(() => null);\n return config?.registry || DEFAULT_REGISTER;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport {\n FrameworkDefinition,\n SUPPORTED_AGENTS,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\n\n/**\n * Service for detecting project frameworks, languages, AI agents, and dependencies.\n * It uses a combination of file existence checks and package metadata analysis.\n */\nexport class DetectionService {\n /**\n * Detects supported frameworks based on characteristic files and dependencies.\n * @returns A record of framework IDs and their detection status (boolean)\n */\n async detectFrameworks(): Promise<Record<string, boolean>> {\n const packageDepsMap = await this.readPackageJsonDeps(process.cwd());\n\n const detectionPromises = SUPPORTED_FRAMEWORKS.map(async (framework) => {\n // 1. Check characteristic files in parallel\n const fileChecks = framework.detectionFiles.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const fileResults = await Promise.all(fileChecks);\n let detected = fileResults.some((exists) => exists);\n\n // 2. Check dependencies (if not yet detected)\n if (\n !detected &&\n framework.detectionDependencies &&\n framework.detectionDependencies.length > 0\n ) {\n detected = framework.detectionDependencies.some((dep) =>\n Object.prototype.hasOwnProperty.call(packageDepsMap, dep),\n );\n }\n\n return { id: framework.id, detected };\n });\n\n const results = await Promise.all(detectionPromises);\n return results.reduce(\n (acc, { id, detected }) => ({ ...acc, [id]: detected }),\n {},\n );\n }\n\n /**\n * Detects programming languages associated with a specific framework.\n * @param framework The framework definition to use for detection\n * @returns Array of detected language IDs\n */\n async detectLanguages(framework: FrameworkDefinition): Promise<string[]> {\n if (!framework.languageDetection) {\n return framework.languages;\n }\n\n const languageEntries = Object.entries(\n framework.languageDetection as Record<string, string[]>,\n );\n\n const detectionResults = await Promise.all(\n languageEntries.map(async ([lang, files]) => {\n const fileChecks = files.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const results = await Promise.all(fileChecks);\n return { lang, detected: results.some((exists) => exists) };\n }),\n );\n\n const detectedLanguages = detectionResults\n .filter((r) => r.detected)\n .map((r) => r.lang);\n\n return detectedLanguages.length > 0\n ? detectedLanguages\n : framework.languages;\n }\n\n /**\n * Detects enabled AI agents in the workspace by looking for their configuration files.\n * @returns A record of agent IDs and their detection status (boolean)\n */\n async detectAgents(): Promise<Record<string, boolean>> {\n const detectionPromises = SUPPORTED_AGENTS.map(async (agent) => {\n const fileChecks = agent.detectionFiles.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const results = await Promise.all(fileChecks);\n return { id: agent.id, detected: results.some((exists) => exists) };\n });\n\n const results = await Promise.all(detectionPromises);\n return results.reduce(\n (acc, { id, detected }) => ({ ...acc, [id]: detected }),\n {},\n );\n }\n\n /**\n * Aggregates project dependencies from various build systems (NPM, Pub, Gradle, Maven).\n * @returns A set of all detected package names/identifiers\n */\n async getProjectDeps(): Promise<Set<string>> {\n const cwd = process.cwd();\n const results = await Promise.all([\n this.parsePackageJson(cwd),\n this.parsePubspecYaml(cwd),\n this.parseGradleDependencies(cwd),\n this.parseVersionCatalogs(cwd),\n this.parseMavenPom(cwd),\n ]);\n\n const combined = new Set<string>();\n for (const set of results) {\n for (const item of set) combined.add(item);\n }\n return combined;\n }\n\n private async parsePackageJson(cwd: string): Promise<Set<string>> {\n const depsMap = await this.readPackageJsonDeps(cwd);\n return new Set(Object.keys(depsMap));\n }\n\n private async readPackageJsonDeps(\n cwd: string,\n ): Promise<Record<string, string>> {\n const packageJsonPath = path.join(cwd, 'package.json');\n if (!(await fs.pathExists(packageJsonPath))) return {};\n\n try {\n const pkg = await fs.readJson(packageJsonPath);\n return {\n ...(pkg.dependencies || {}),\n ...(pkg.devDependencies || {}),\n };\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to read package.json:', error);\n return {};\n }\n }\n\n private async parsePubspecYaml(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const pubspecPath = path.join(cwd, 'pubspec.yaml');\n if (!(await fs.pathExists(pubspecPath))) return set;\n\n try {\n const content = await fs.readFile(pubspecPath, 'utf8');\n const lines = content.split(/\\r?\\n/);\n let currentSection: string | null = null;\n let sectionIndent: number | null = null;\n\n for (const line of lines) {\n const sectionMatch = line.match(\n /^(\\s*)(dependencies|dev_dependencies)\\s*:/,\n );\n if (sectionMatch) {\n currentSection = sectionMatch[2];\n sectionIndent = sectionMatch[1].length;\n continue;\n }\n\n if (!currentSection || sectionIndent === null) continue;\n const entryMatch = line.match(/^(\\s*)([a-zA-Z0-9_\\-@\\\\/]+)\\s*:/);\n if (!entryMatch) continue;\n\n const indent = entryMatch[1].length;\n const key = entryMatch[2];\n if (indent > sectionIndent && key !== 'sdk' && key !== 'flutter') {\n set.add(key);\n }\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to parse pubspec.yaml:', error);\n }\n return set;\n }\n\n private async parseGradleDependencies(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const gradleRegex =\n /(?:implementation|api|ksp|kapt|annotationProcessor|compileOnly|runtimeOnly)\\s*\\(?\\s*['\"]([^'\":\\s]+)(?::[^'\"]*)?['\"]\\s*\\)?/g;\n\n const scanDir = async (dir: string, depth: number) => {\n if (depth > 2) return; // Reduced depth for performance\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (\n [\n 'node_modules',\n '.git',\n 'build',\n '.gradle',\n 'ios',\n 'macos',\n ].includes(entry.name)\n )\n continue;\n await scanDir(path.join(dir, entry.name), depth + 1);\n } else if (\n entry.name === 'build.gradle' ||\n entry.name === 'build.gradle.kts'\n ) {\n const content = await fs.readFile(\n path.join(dir, entry.name),\n 'utf8',\n );\n let match;\n while ((match = gradleRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n }\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to scan gradle dependencies:', error);\n }\n };\n\n await scanDir(cwd, 0);\n return set;\n }\n\n private async parseVersionCatalogs(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const tomlPaths = [\n path.join(cwd, 'gradle', 'libs.versions.toml'),\n path.join(cwd, 'gradle.libs.versions.toml'),\n ];\n\n for (const tomlPath of tomlPaths) {\n if (!(await fs.pathExists(tomlPath))) continue;\n try {\n const content = await fs.readFile(tomlPath, 'utf8');\n const moduleRegex = /module\\s*=\\s*['\"]([^'\":\\s]+)(?::[^'\"]*)?['\"]/g;\n const groupRegex = /group\\s*=\\s*['\"]([^'\":\\s]+)['\"]/g;\n let match;\n while ((match = moduleRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n while ((match = groupRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to parse version catalogs:', error);\n }\n }\n return set;\n }\n\n private async parseMavenPom(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const pomPath = path.join(cwd, 'pom.xml');\n if (!(await fs.pathExists(pomPath))) return set;\n\n try {\n const content = await fs.readFile(pomPath, 'utf8');\n const regex =\n /<dependency>[\\s\\S]*?<artifactId>([^<]+)<\\/artifactId>[\\s\\S]*?<\\/dependency>/g;\n let match;\n while ((match = regex.exec(content)) !== null) {\n set.add(match[1]);\n }\n } catch (error) {\n if (process.env.DEBUG) console.debug('Failed to parse maven pom:', error);\n }\n return set;\n }\n}\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\nimport {\n Agent,\n DEFAULT_WORKFLOWS,\n SUPPORTED_AGENTS,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\nimport { RegistryMetadata } from '../models/types';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\n\n/**\n * Contextual data gathered during project discovery to inform the initialization prompt.\n */\nexport interface InitContext {\n /** Map of framework IDs and whether they were detected in the workspace */\n frameworkDetection: Record<string, boolean>;\n /** Map of agent IDs and whether they were detected in the workspace */\n agentDetection: Record<string, boolean>;\n}\n/**\n * User responses gathered from the initialization prompt.\n */\nexport interface InitAnswers {\n /** The primary framework ID chosen by the user */\n framework: string;\n /** List of AI agents to enable for the project */\n agents: Agent[];\n /** The URL of the skill registry to use */\n registry: string;\n}\n\n/**\n * Service for orchestrating the project initialization process.\n * Handles environment discovery, prompt choice generation, and initial config creation.\n */\nexport class InitService {\n private detectionService = new DetectionService();\n private configService = new ConfigService();\n\n /**\n * Performs environmental discovery to identify existing frameworks and agents.\n * @returns An InitContext containing detection results\n */\n async getInitializationContext(): Promise<InitContext> {\n const [frameworkDetection, agentDetection] = await Promise.all([\n this.detectionService.detectFrameworks(),\n this.detectionService.detectAgents(),\n ]);\n\n return { frameworkDetection, agentDetection };\n }\n\n /**\n * Transforms the initialization context and registry metadata into choices for the interactive prompt.\n * @param context The discovered initialization context\n * @param supportedCategories List of categories currently supported by the registry\n * @returns Formatted choices and the default framework ID\n */\n getPromptChoices(context: InitContext, supportedCategories: string[]) {\n const frameworkChoices = SUPPORTED_FRAMEWORKS.map((f) => ({\n name: supportedCategories.includes(f.id)\n ? f.name\n : `${f.name} (Coming Soon)`,\n value: f.id,\n }));\n\n const agentChoices = SUPPORTED_AGENTS.map((a) => ({\n name: `${a.name} (${a.path}/)`,\n value: a.id,\n checked: context.agentDetection[a.id] ?? false,\n }));\n\n const defaultFramework =\n SUPPORTED_FRAMEWORKS.find((f) => context.frameworkDetection[f.id])?.id ||\n 'flutter';\n\n return {\n frameworkChoices,\n agentChoices,\n defaultFramework,\n };\n }\n\n /**\n * Orchestrates the construction, validation, and saving of the initial `.skillsrc` configuration.\n * @param answers The user's prompt responses\n * @param metadata Registry metadata for versioning\n * @param cwd Current working directory\n */\n async buildAndSaveConfig(\n answers: InitAnswers,\n metadata: Partial<RegistryMetadata>,\n cwd: string = process.cwd(),\n ) {\n const frameworkId = answers.framework;\n const frameworkDef = SUPPORTED_FRAMEWORKS.find((f) => f.id === frameworkId);\n\n const languages = frameworkDef\n ? await this.detectionService.detectLanguages(frameworkDef)\n : [];\n\n const includeWorkflows = answers.agents.includes(Agent.Antigravity);\n\n const config = this.configService.buildInitialConfig(\n frameworkId,\n answers.agents,\n answers.registry,\n metadata,\n languages,\n includeWorkflows ? DEFAULT_WORKFLOWS : [],\n );\n\n const projectDeps = await this.detectionService.getProjectDeps();\n this.configService.applyDependencyExclusions(config, projectDeps);\n this.configService.reconcileDependencies(config, projectDeps);\n\n const commentHeader = `# Auto-detected configuration generated by agent-skills-standard init\n#\n# Presence in 'skills' list = Active. To disable a skill, remove it from the list.\n# 'exclude': IDs of sub-skills to skip during sync (auto-populated with undetected skills).\n# 'custom_overrides': IDs of skills to PROTECT. Use this if you have modified a standard \n# skill locally and don't want the CLI to overwrite it.\n#\n# Run 'ags list-skills' to view all available skills.\n#\n# TIP: For Jira/Zephyr automation and requirement analysis, manually add:\n# skills:\n# quality-engineering: { ref: quality-engineering-v1.0.0 }\n#\n`;\n const configPath = path.join(cwd, '.skillsrc');\n await fs.outputFile(configPath, commentHeader + yaml.dump(config));\n }\n}\n","import pc from 'picocolors';\nimport { GitHubTreeResponse } from '../models/types';\n\n/**\n * Service for interacting with the GitHub API and fetching raw file content.\n * Handles repository tree discovery, file downloads, and URL parsing.\n */\nexport class GithubService {\n private baseUrl = 'https://api.github.com';\n private rawBaseUrl = 'https://raw.githubusercontent.com';\n\n constructor(private token?: string) {}\n\n private get headers() {\n const h: Record<string, string> = {\n Accept: 'application/vnd.github.v3+json',\n };\n if (this.token) {\n h.Authorization = `token ${this.token}`;\n }\n return h;\n }\n\n /**\n * Fetches the recursive Git tree for a repository.\n * @param owner Repository owner\n * @param repo Repository name\n * @param ref Git reference (branch, tag, or commit SHA)\n * @returns The tree data or null if not found\n */\n async getRepoTree(\n owner: string,\n repo: string,\n ref: string,\n ): Promise<GitHubTreeResponse | null> {\n const url = `${this.baseUrl}/repos/${owner}/${repo}/git/trees/${ref}?recursive=1`;\n try {\n const res = await fetch(url, { headers: this.headers });\n if (!res.ok) {\n if (res.status === 404) return null;\n throw new Error(`GitHub API Error: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as GitHubTreeResponse;\n } catch (error) {\n console.error(pc.red(`Failed to fetch repo tree: ${error}`));\n return null;\n }\n }\n\n /**\n * Fetches the raw content of a file from GitHub using raw.githubusercontent.com.\n * @param owner Repository owner\n * @param repo Repository name\n * @param ref Git reference\n * @param path Path to the file\n * @returns File content as string or null if not found\n */\n async getRawFile(\n owner: string,\n repo: string,\n ref: string,\n path: string,\n ): Promise<string | null> {\n const url = `${this.rawBaseUrl}/${owner}/${repo}/${ref}/${path}`;\n try {\n const res = await fetch(url);\n if (!res.ok) return null;\n return await res.text();\n } catch (error) {\n console.error(pc.red(`Failed to fetch file ${path}: ${error}`));\n return null;\n }\n }\n\n /**\n * Retrieves the latest release tag name for a repository.\n * @param owner Repository owner\n * @param repo Repository name\n */\n async getLatestReleaseTag(\n owner: string,\n repo: string,\n ): Promise<string | null> {\n try {\n const res = await fetch(\n `${this.baseUrl}/repos/${owner}/${repo}/releases/latest`,\n {\n headers: this.headers,\n },\n );\n if (!res.ok) return null;\n const data = (await res.json()) as { tag_name: string };\n return data.tag_name;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetches basic repository information, such as the default branch.\n * @param owner Repository owner\n * @param repo Repository name\n */\n async getRepoInfo(\n owner: string,\n repo: string,\n ): Promise<{ default_branch: string } | null> {\n const url = `${this.baseUrl}/repos/${owner}/${repo}`;\n try {\n const res = await fetch(url, { headers: this.headers });\n if (!res.ok) return null;\n return (await res.json()) as { default_branch: string };\n } catch (error) {\n console.error(pc.red(`Failed to fetch repo info: ${error}`));\n return null;\n }\n }\n\n /**\n * Downloads multiple files concurrently with a limit.\n */\n async downloadFilesConcurrent(\n tasks: { owner: string; repo: string; ref: string; path: string }[],\n concurrency: number = 10,\n ): Promise<{ path: string; content: string }[]> {\n const results: { path: string; content: string }[] = [];\n const pool = [...tasks];\n const executing: Promise<void>[] = [];\n\n const worker = async () => {\n while (pool.length > 0) {\n const task = pool.shift();\n if (!task) break;\n\n const content = await this.getRawFile(\n task.owner,\n task.repo,\n task.ref,\n task.path,\n );\n if (content !== null) {\n results.push({ path: task.path, content });\n }\n }\n };\n\n // Spawn workers\n for (let i = 0; i < Math.min(concurrency, tasks.length); i++) {\n executing.push(worker());\n }\n\n await Promise.all(executing);\n return results;\n }\n\n /**\n * Parses a GitHub URL into owner and repository name.\n * @param url The GitHub URL to parse\n * @returns Object containing owner and repo, or null if invalid\n */\n static parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const m = url.match(/github\\.com\\/([^/]+)\\/([^/]+)/i);\n if (!m) return null;\n return { owner: m[1], repo: m[2].replace(/\\.git$/, '') };\n }\n}\n","import path from 'path';\nimport { GitHubTreeItem, RegistryMetadata } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service for discovering and querying the skill registry (repository).\n * It identifies available categories, metadata, and framework-specific skills.\n */\nexport class RegistryService {\n private githubService: GithubService;\n\n constructor() {\n this.githubService = new GithubService(process.env.GITHUB_TOKEN);\n }\n\n /**\n * Discovers the registry structure by scanning the repository tree.\n * Identifies available categories, global metadata, and workflows.\n * @param registryUrl The GitHub URL of the registry\n * @returns Discovered registry components\n */\n async discoverRegistry(registryUrl: string): Promise<{\n categories: string[];\n metadata: Partial<RegistryMetadata>;\n workflows: string[];\n }> {\n let categories: string[] = ['flutter', 'dart'];\n let metadata: Partial<RegistryMetadata> = {};\n\n try {\n const parsed = GithubService.parseGitHubUrl(registryUrl);\n if (parsed) {\n let branch = 'main';\n const repoInfo = await this.githubService.getRepoInfo(\n parsed.owner,\n parsed.repo,\n );\n if (repoInfo && repoInfo.default_branch) {\n branch = repoInfo.default_branch;\n }\n\n const treeResult = await this.githubService.getRepoTree(\n parsed.owner,\n parsed.repo,\n branch,\n );\n\n if (treeResult && Array.isArray(treeResult.tree)) {\n const allFiles = treeResult.tree || [];\n const foundCategories = new Set<string>();\n allFiles.forEach((f: GitHubTreeItem) => {\n if (f.path.startsWith('skills/') && f.type === 'tree') {\n const parts = f.path.split('/');\n if (parts.length === 2) foundCategories.add(parts[1]);\n }\n });\n if (foundCategories.size > 0)\n categories = Array.from(foundCategories);\n\n const workflows = allFiles\n .filter(\n (f) =>\n f.path.startsWith('.agent/workflows/') &&\n f.path.endsWith('.md'),\n )\n .map((f) => path.basename(f.path, '.md'));\n\n const metaContent = await this.githubService.getRawFile(\n parsed.owner,\n parsed.repo,\n branch,\n 'skills/metadata.json',\n );\n if (metaContent) {\n metadata = JSON.parse(metaContent) as RegistryMetadata;\n }\n\n return { categories, metadata, workflows };\n }\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`[RegistryService] Registry discovery failed: ${error}`);\n }\n }\n\n return { categories, metadata, workflows: [] };\n }\n\n /**\n * Fetches a list of available skill folders for a specific framework.\n * @param registryUrl The GitHub URL of the registry\n * @param framework The framework ID to query\n * @returns List of skill folder names\n */\n async getFrameworkSkills(\n registryUrl: string,\n framework: string,\n ): Promise<string[]> {\n try {\n const parsed = GithubService.parseGitHubUrl(registryUrl);\n if (!parsed) return [];\n\n const treeResult = await this.githubService.getRepoTree(\n parsed.owner,\n parsed.repo,\n 'main',\n );\n\n if (!treeResult || !Array.isArray(treeResult.tree)) return [];\n\n return Array.from(\n new Set(\n treeResult.tree\n .filter((f: GitHubTreeItem) =>\n f.path.startsWith(`skills/${framework}/`),\n )\n .map((f: GitHubTreeItem) => f.path.split('/')[2])\n .filter(Boolean),\n ),\n );\n } catch {\n return [];\n }\n }\n}\n","import fs from 'fs-extra';\nimport inquirer from 'inquirer';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { DEFAULT_REGISTER } from '../constants';\nimport { InitAnswers, InitService } from '../services/InitService';\nimport { RegistryService } from '../services/RegistryService';\n\n/**\n * Command for initializing the agent-skills-standard configuration in a project.\n * It guides the user through environment detection and creates the `.skillsrc` file.\n */\nexport class InitCommand {\n private initService: InitService;\n private registryService: RegistryService;\n\n constructor(initService?: InitService, registryService?: RegistryService) {\n this.initService = initService || new InitService();\n this.registryService = registryService || new RegistryService();\n }\n\n /**\n * Executes the initialization flow.\n * Checks for existing config, discovers the environment, prompts the user, and saves the configuration.\n */\n async run() {\n const configPath = path.join(process.cwd(), '.skillsrc');\n\n // 1. Check for existing config\n if (await fs.pathExists(configPath)) {\n const { overwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'overwrite',\n message: '.skillsrc already exists. Do you want to overwrite it?',\n default: false,\n },\n ]);\n if (!overwrite) {\n console.log(pc.yellow('Aborted.'));\n return;\n }\n }\n\n // 2. Gather context data\n const context = await this.initService.getInitializationContext();\n const { categories, metadata } =\n await this.registryService.discoverRegistry(DEFAULT_REGISTER);\n\n // 3. Prepare Choices\n const { frameworkChoices, agentChoices, defaultFramework } =\n this.initService.getPromptChoices(context, categories);\n\n // 4. Prompt User\n const answers = await inquirer.prompt<InitAnswers>([\n {\n type: 'list',\n name: 'framework',\n message: 'Select Framework:',\n choices: frameworkChoices,\n default: defaultFramework,\n },\n {\n type: 'checkbox',\n name: 'agents',\n message: 'Select AI Agents you use:',\n choices: agentChoices,\n },\n {\n type: 'input',\n name: 'registry',\n message: 'Skills Registry URL:',\n default: DEFAULT_REGISTER,\n },\n ]);\n\n // 5. Build and Save\n await this.initService.buildAndSaveConfig(answers, metadata);\n\n console.log(pc.green('\\n✅ Initialized .skillsrc with your preferences!'));\n console.log(pc.gray(` Selected framework: ${answers.framework}`));\n console.log(\n pc.cyan(\n '\\nNext step: Run `agent-skills-standard sync` to generate rule files.',\n ),\n );\n }\n}\n","import { SKILL_DETECTION_REGISTRY } from '../constants';\nimport { RegistryService } from './RegistryService';\n\n/**\n * Represents a skill with its detection status in the current project.\n */\nexport interface SkillWithStatus {\n /** The name/ID of the skill */\n name: string;\n /**\n * Status of the skill:\n * - detected: Required dependencies found\n * - not-detected: Required dependencies missing\n * - no-rule: No automated detection rule exists for this skill\n */\n status: 'detected' | 'not-detected' | 'no-rule';\n}\n\n/**\n * Service for managing skill status and availability.\n * Maps registry skills to project dependencies to determine detection status.\n */\nexport class SkillService {\n private registryService = new RegistryService();\n\n /**\n * Retrieves a list of skills for a framework with their detection status.\n * @param framework The framework to filter by\n * @param registryUrl The registry URL\n * @param projectDeps Set of detected project dependencies\n * @returns Array of skills with validated status\n */\n async getSkillsWithStatus(\n framework: string,\n registryUrl: string,\n projectDeps: Set<string>,\n ): Promise<SkillWithStatus[]> {\n // 1. Get available skills (Remote + Fallback)\n let skillFolders = await this.registryService.getFrameworkSkills(\n registryUrl,\n framework,\n );\n\n const detectRules = SKILL_DETECTION_REGISTRY[framework] || [];\n\n // Fallback: use detection registry skill ids if remote fetch returned nothing\n if (!skillFolders || skillFolders.length === 0) {\n skillFolders = detectRules.map((s) => s.id);\n }\n\n // 2. Map to Status\n const skills = skillFolders.sort().map((skillName) => {\n const rule = detectRules.find((x) => x.id === skillName);\n\n let status: SkillWithStatus['status'] = 'no-rule';\n if (rule) {\n const isPresent = rule.packages.some((p) =>\n Array.from(projectDeps).some((d) =>\n d.toLowerCase().includes(p.toLowerCase()),\n ),\n );\n status = isPresent ? 'detected' : 'not-detected';\n }\n\n return { name: skillName, status };\n });\n\n return skills;\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { Framework, SUPPORTED_FRAMEWORKS } from '../constants';\nimport { ConfigService } from '../services/ConfigService';\nimport { DetectionService } from '../services/DetectionService';\nimport { SkillService } from '../services/SkillService';\n\n/**\n * Command for listing available skills in the registry.\n * It detects the project's dependencies and identifies which skills have matching rules.\n */\nexport class ListSkillsCommand {\n private configService: ConfigService;\n private detectionService: DetectionService;\n private skillService: SkillService;\n\n constructor(\n configService?: ConfigService,\n detectionService?: DetectionService,\n skillService?: SkillService,\n ) {\n this.configService = configService || new ConfigService();\n this.detectionService = detectionService || new DetectionService();\n this.skillService = skillService || new SkillService();\n }\n\n /**\n * Executes the skill listing flow.\n * Prompts for framework selection, fetches matching skills from the registry, and displays their status.\n */\n async run(options: { framework?: string } = {}) {\n // 1. Get framework choice from user\n let framework = options.framework;\n\n // Validate framework if provided via options\n if (framework) {\n const isSupported = SUPPORTED_FRAMEWORKS.some((f) => f.id === framework);\n if (!isSupported) {\n const validFrameworks = SUPPORTED_FRAMEWORKS.map((f) => f.id).join(\n ', ',\n );\n console.error(\n pc.red(\n `Invalid framework \"${framework}\". Supported frameworks are: ${validFrameworks}.`,\n ),\n );\n process.exit(1);\n }\n }\n\n if (!framework) {\n const choices = SUPPORTED_FRAMEWORKS.map((f) => ({\n name: f.name,\n value: f.id,\n }));\n\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'framework',\n message: 'Select framework to list available skills for:',\n choices,\n default: choices.find((c) => c.value === Framework.Flutter)?.value,\n },\n ]);\n framework = answer.framework;\n }\n\n if (!framework) return;\n\n // 2. Load context\n const projectDeps = await this.detectionService.getProjectDeps();\n const registryUrl = await this.configService.getRegistryUrl();\n\n console.log(pc.green(`\\nAvailable skills for ${framework}:`));\n\n // 3. Fetch skills with status\n const skills = await this.skillService.getSkillsWithStatus(\n framework,\n registryUrl,\n projectDeps,\n );\n\n // 4. Output results\n for (const skill of skills) {\n const mark =\n skill.status === 'no-rule'\n ? pc.yellow('no-rule')\n : skill.status === 'detected'\n ? pc.green('detected')\n : pc.gray('not-detected');\n\n console.log(`- ${skill.name} (${mark})`);\n }\n\n console.log(\n '\\nTip: Use the .skillsrc exclude array to disable/enable sub-skills before running sync.',\n );\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { Agent, getAgentDefinition } from '../constants';\n\n/**\n * Service responsible for bridging native AI agent rule files to AGENTS.md.\n * Creates agent-specific rule files (e.g., .mdc, .instructions.md)\n * in their respective directories.\n */\nexport class AgentBridgeService {\n /**\n * Bridges native agent rule files to AGENTS.md by creating discovery instructions.\n * @param rootDir Project root directory\n * @param agents List of agents to generate rules for\n */\n async bridge(rootDir: string, agents: Agent[]): Promise<void> {\n const fileNameBase = 'agent-skill-standard-rule';\n const commonDescription =\n 'Rule for Agent Skills Standard - Always consult AGENTS.md for consolidated project context and technical triggers.';\n\n for (const agentId of agents) {\n const config = getAgentDefinition(agentId);\n if (!config) continue;\n\n const relativeSkillsPath = path\n .relative(config.ruleFile, config.path)\n .replace(/\\\\/g, '/');\n const prefix = relativeSkillsPath ? `${relativeSkillsPath}/` : '';\n\n const commonBody = [\n '# 🛠 Agent Skills Standard',\n '',\n 'This project uses a modular skills library for specialized engineering tasks.',\n '',\n '> [!IMPORTANT]',\n '> ALWAYS consult the consolidated index in **AGENTS.md** to identify relevant triggers before acting.',\n '',\n 'The `AGENTS.md` file contains mapping between project files and the specific agent skills located in the respective agent-specific folders (e.g., `.cursor/skills`, `.claude/skills`).',\n '',\n '## Self-Learning Protocol',\n '',\n `At the end of any multi-step task with user corrections, load and run **[common/session-retrospective](${prefix}common/session-retrospective/SKILL.md)** to capture skill gaps and prevent repeat rework.`,\n ].join('\\\\n');\n\n // SAFETY: Only write if the agent is detected in the project\n // This prevents creating unused directories.\n let detected = false;\n for (const file of config.detectionFiles) {\n if (await fs.pathExists(path.join(rootDir, file))) {\n detected = true;\n break;\n }\n }\n\n if (!detected) continue;\n\n const ruleFilePath = path.join(\n rootDir,\n config.ruleFile,\n config.ruleFileName || `${fileNameBase}${config.ruleExtension}`,\n );\n\n // Ensure directory exists (e.g. .cursor/rules inside .cursor)\n await fs.ensureDir(path.dirname(ruleFilePath));\n\n let content = '';\n\n switch (config.frontmatterStyle) {\n case 'cursor':\n content += `---\\ndescription: ${commonDescription}\\nglobs: [\"**/*\"]\\nalwaysApply: true\\n---\\n\\n`;\n break;\n case 'copilot':\n content += `---\\ndescription: ${commonDescription}\\napplyTo: \"**/*\"\\n---\\n\\n`;\n break;\n case 'none':\n // No frontmatter\n break;\n }\n\n content += commonBody;\n\n await fs.outputFile(ruleFilePath, content);\n }\n }\n}\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\n\n/**\n * Metadata structure for a skill, extracted from the frontmatter and content of a SKILL.md file.\n */\nexport interface SkillMetadata {\n /** The human-readable name of the skill. */\n name: string;\n /** A brief summary of what the skill covers. */\n description: string;\n /** The priority level (e.g., P0, P1) determining its critical importance. */\n priority: string;\n /** Trigger conditions for when this skill should be activated. */\n triggers: {\n /** Glob patterns of files that trigger this skill. */\n files?: string[];\n /** List of keywords that trigger this skill. */\n keywords?: string[];\n /** Other skill IDs that, when active, also trigger this skill. */\n composite?: string[];\n /** Patterns to explicitly exclude from triggering this skill. */\n exclude?: string[];\n };\n}\n\n/**\n * Service for generating the Agent Skills Index in markdown format.\n * It handles parsing skill metadata and structuring the markdown document.\n *\n * Composite rules are registry-owned: loaded from `skills/metadata.json` at\n * index-generation time. Adding a new foundational skill or pattern requires\n * only a change to `metadata.json` — no CLI source edit or release needed.\n *\n * Injection and bridging are handled by MarkdownUtils and AgentBridgeService respectively.\n */\nexport class IndexGeneratorService {\n /**\n * Loads foundational composite rules from the registry's metadata.json.\n * Falls back to an empty map if the file is missing or malformed.\n */\n private async loadFoundationalRules(\n baseDir: string,\n ): Promise<Record<string, string[]>> {\n try {\n const metaPath = path.join(baseDir, 'metadata.json');\n const raw = await fs.readFile(metaPath, 'utf8');\n const parsed = JSON.parse(raw) as {\n foundational_composite_rules?: Record<string, string[]>;\n };\n return parsed.foundational_composite_rules ?? {};\n } catch {\n return {};\n }\n }\n /**\n * Generates a markdown index of available skills across multiple categories.\n * @param baseDir The base directory containing categories and skills\n * @param frameworks List of framework categories to include in the index\n * @returns A formatted markdown string representing the index\n */\n async generate(baseDir: string, frameworks: string[]): Promise<string> {\n const categories = Array.from(new Set(['common', ...frameworks]));\n const entries = new Set<string>();\n const foundationalRules = await this.loadFoundationalRules(baseDir);\n\n for (const category of categories) {\n const categoryPath = path.join(baseDir, category);\n if (!(await fs.pathExists(categoryPath))) continue;\n\n const skills = await fs.readdir(categoryPath);\n for (const skill of skills) {\n const skillPath = path.join(categoryPath, skill, 'SKILL.md');\n if (!(await fs.pathExists(skillPath))) continue;\n\n const metadata = await this.parseSkill(skillPath);\n if (metadata) {\n const entry = this.formatEntry(\n category,\n skill,\n metadata,\n foundationalRules,\n );\n entries.add(entry);\n }\n }\n }\n\n return this.assembleIndex(Array.from(entries));\n }\n\n /**\n * Assembles the full index markdown including headers and Zero-Trust rules.\n * @param entries List of formatted skill entries\n * @param format The format of the entries ('detailed' or 'compact')\n * @returns Complete markdown index string\n */\n public assembleIndex(entries: string[]): string {\n const header = [\n '# Agent Skills Index',\n '',\n '> [!IMPORTANT]',\n '> **Prefer retrieval-led reasoning over pre-training-led reasoning.**',\n '> Before writing any code, you MUST CHECK if a relevant skill exists in the index below.',\n '> If a skill matches your task, READ the file using `view_file`.',\n '',\n '## **Rule Zero: Zero-Trust Engineering**',\n '',\n '- **Skill Authority:** Loaded skills always override existing code patterns.',\n '- **Audit Before Write:** Audit every file write against the `common/feedback-reporter` skill.',\n '',\n '## **Reading This Index**',\n '',\n 'Each entry lists `(triggers: ...)` conditions. Three trigger types:',\n '- **File globs** (`**/*.ts`) — activate when working with matching files.',\n '- **Keywords** (`auth`, `refactor`) — activate when these appear in the task.',\n '- **Composite** (`+other/skill`) — activate THIS skill whenever `other/skill` is also active. Used by foundational skills to co-load with their framework peers automatically.',\n '',\n ].join('\\n');\n\n return `${header}\\n${entries.join('\\n')}\\n`;\n }\n\n private async parseSkill(skillPath: string): Promise<SkillMetadata | null> {\n try {\n const content = await fs.readFile(skillPath, 'utf8');\n const frontmatterMatch = content.match(\n /^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/,\n );\n\n if (!frontmatterMatch) return null;\n\n const fm = yaml.load(frontmatterMatch[1]) as unknown as {\n name?: string;\n description?: string;\n metadata?: {\n triggers?: {\n files?: string[];\n keywords?: string[];\n composite?: string[];\n exclude?: string[];\n };\n };\n };\n const body = frontmatterMatch[2];\n\n const priorityMatch = body.match(/## \\*\\*Priority:\\s*([^*]+)\\*\\*/);\n const priority = priorityMatch ? priorityMatch[1].trim() : 'P1';\n\n return {\n name: fm.name || '',\n description: fm.description || '',\n priority,\n triggers:\n (fm.metadata?.triggers as {\n files?: string[];\n keywords?: string[];\n composite?: string[];\n exclude?: string[];\n }) || {},\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Derives foundational composite IDs for a skill based on registry-owned naming rules.\n * Only applies to non-common skills. Deduplicates against explicit composites.\n */\n private deriveFoundationalComposites(\n category: string,\n skill: string,\n explicitComposites: string[],\n rules: Record<string, string[]>,\n ): string[] {\n if (category === 'common') return [];\n const derived: string[] = [];\n for (const [foundational, patterns] of Object.entries(rules)) {\n const matches = patterns.some((p) => skill.includes(p));\n if (matches && !explicitComposites.includes(foundational)) {\n derived.push(foundational);\n }\n }\n return derived;\n }\n\n private formatEntry(\n category: string,\n skill: string,\n metadata: SkillMetadata,\n foundationalRules: Record<string, string[]> = {},\n ): string {\n const id = `${category}/${skill}`;\n const prefix = metadata.priority.startsWith('P0') ? '🚨 ' : '';\n\n const explicitComposites = metadata.triggers.composite || [];\n const autoComposites = this.deriveFoundationalComposites(\n category,\n skill,\n explicitComposites,\n foundationalRules,\n );\n const allComposites = [...explicitComposites, ...autoComposites];\n\n const triggers = [\n ...(metadata.triggers.files || []),\n ...(metadata.triggers.keywords || []),\n ...(allComposites.length ? allComposites.map((c) => `+${c}`) : []),\n ...(metadata.triggers.exclude\n ? metadata.triggers.exclude.map((e) => `!${e}`)\n : []),\n ].join(', ');\n\n const triggerText = triggers ? ` (triggers: ${triggers})` : '';\n\n // Format: - **[category/skill]**: 🚨 Description (triggers: file.ts, keyword, +composite, !exclude)\n const content = `${prefix}${metadata.description || ''}`.trim();\n return `- **[${id}]**: ${content}${triggerText}`;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * Utility functions for manipulating markdown content\n */\nexport class MarkdownUtils {\n /**\n * Injects the generated index into target documentation files (e.g., AGENTS.md).\n * It uses HTML comments as markers for safe injection and replacement.\n * @param rootDir Project root directory\n * @param targets Array of target file names\n * @param indexContent The markdown content to inject\n */\n static async injectIndex(\n rootDir: string,\n targets: string[],\n indexContent: string,\n ): Promise<void> {\n for (const target of targets) {\n const targetPath = path.join(rootDir, target);\n let content = '';\n\n if (await fs.pathExists(targetPath)) {\n content = await fs.readFile(targetPath, 'utf8');\n const markerStart = '<!-- SKILLS_INDEX_START -->';\n const markerEnd = '<!-- SKILLS_INDEX_END -->';\n\n const startIndex = content.indexOf(markerStart);\n const endIndex = content.indexOf(markerEnd);\n\n if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {\n // Both markers exist and are in the correct order\n const preMarker = content.substring(\n 0,\n startIndex + markerStart.length,\n );\n const postMarker = content.substring(endIndex);\n content = `${preMarker}\\n${indexContent}\\n${postMarker}`;\n } else if (startIndex !== -1 || endIndex !== -1) {\n // One of the markers is missing or they are out of order\n content = content.replace(markerStart, '').replace(markerEnd, '');\n content =\n content.trimEnd() +\n `\\n\\n${markerStart}\\n${indexContent}\\n${markerEnd}\\n`;\n } else {\n // No markers found\n content =\n content.trimEnd() +\n `\\n\\n${markerStart}\\n${indexContent}\\n${markerEnd}\\n`;\n }\n } else {\n content = `<!-- SKILLS_INDEX_START -->\\n${indexContent}\\n<!-- SKILLS_INDEX_END -->\\n`;\n }\n\n await fs.outputFile(targetPath, content);\n }\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { Agent, DEFAULT_WORKFLOWS, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig, SkillEntry } from '../models/config';\nimport {\n CollectedSkill,\n GitHubTreeItem,\n RegistryMetadata,\n} from '../models/types';\nimport { AgentBridgeService } from './AgentBridgeService';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\nimport { GithubService } from './GithubService';\nimport { IndexGeneratorService } from './IndexGeneratorService';\nimport { MarkdownUtils } from './utils/MarkdownUtils';\n\n/**\n * Service responsible for synchronizing agent skills and workflows from a remote registry\n * to the local workspace. It handles dependency reconciliation, folder identification,\n * and writing files to appropriate agent search paths.\n */\nexport class SyncService {\n private configService = new ConfigService();\n private detectionService = new DetectionService();\n private githubService = new GithubService(process.env.GITHUB_TOKEN);\n\n /**\n * Reconciles configuration based on detected project dependencies.\n * Returns true if the configuration was changed and saved.\n */\n async reconcileConfig(\n config: SkillConfig,\n projectDeps: Set<string>,\n ): Promise<boolean> {\n const reenabled = this.configService.reconcileDependencies(\n config,\n projectDeps,\n );\n const configChanged = reenabled.length > 0;\n\n if (configChanged) {\n console.log(\n pc.yellow(\n `✨ Dynamic Re-detection: Re-enabling [${reenabled.join(', ')}].`,\n ),\n );\n }\n\n return configChanged;\n }\n\n /**\n * Reconciles workflows by discovering new ones in the registry and adding them to the config.\n */\n async reconcileWorkflows(config: SkillConfig): Promise<boolean> {\n if (config.workflows === false) return false;\n\n // Only reconcile workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return false;\n }\n\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return false;\n\n const { owner, repo } = githubMatch;\n const ref =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) return false;\n\n const availableWorkflows = treeData.tree\n .filter(\n (f) => f.path.startsWith('.agent/workflows/') && f.path.endsWith('.md'),\n )\n .map((f) => path.basename(f.path, '.md'));\n\n if (availableWorkflows.length === 0) return false;\n\n let changed = false;\n\n if (Array.isArray(config.workflows)) {\n // If workflows is an array, we respect the user's explicit list.\n // We automatically add new default workflows discovered in the registry.\n const currentWorkflows = config.workflows as string[];\n const newWorkflows = availableWorkflows.filter(\n (wf) =>\n !currentWorkflows.includes(wf) && DEFAULT_WORKFLOWS.includes(wf),\n );\n\n if (newWorkflows.length > 0) {\n config.workflows = [...currentWorkflows, ...newWorkflows];\n console.log(\n pc.yellow(\n `✨ Workflows Discovered: Adding [${newWorkflows.join(', ')}] to .skillsrc.`,\n ),\n );\n changed = true;\n }\n } else if (config.workflows === undefined || config.workflows === true) {\n const agents = await this.resolveTargetAgents(config);\n if (agents.includes(Agent.Antigravity)) {\n const defaultWorkflows = availableWorkflows.filter((wf) =>\n DEFAULT_WORKFLOWS.includes(wf),\n );\n config.workflows = defaultWorkflows;\n console.log(\n pc.yellow(\n `✨ Workflows Initialized: Adding [${defaultWorkflows.join(', ')}] to .skillsrc.`,\n ),\n );\n changed = true;\n }\n }\n\n return changed;\n }\n\n /**\n * Assembles skills from the remote registry based on provided categories and configuration.\n */\n async assembleSkills(\n categories: string[],\n config: SkillConfig,\n ): Promise<CollectedSkill[]> {\n const collected: CollectedSkill[] = [];\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n\n if (!githubMatch) {\n console.log(pc.red('Error: Only GitHub registries supported.'));\n return [];\n }\n\n const { owner, repo } = githubMatch;\n\n for (const category of categories) {\n const catConfig = config.skills[category];\n const ref = catConfig.ref || 'main';\n\n console.log(pc.gray(` - Discovering ${category} (${ref})...`));\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) {\n console.log(pc.red(` ❌ Failed to fetch ${category}@${ref}.`));\n continue;\n }\n\n const foldersToSync = this.identifyFoldersToSync(\n category,\n catConfig,\n treeData.tree,\n );\n\n for (const absOrRelSkill of foldersToSync) {\n const skill = await this.fetchSkill(\n owner,\n repo,\n ref,\n category,\n absOrRelSkill,\n treeData.tree,\n );\n if (skill) collected.push(skill);\n }\n }\n\n return collected;\n }\n\n /**\n * Writes collected skills to target agent paths.\n */\n async writeSkills(skills: CollectedSkill[], config: SkillConfig) {\n const agents = await this.resolveTargetAgents(config);\n const overrides = config.custom_overrides || [];\n\n for (const agentId of agents) {\n const agentDef = SUPPORTED_AGENTS.find((a) => a.id === agentId);\n if (!agentDef || !agentDef.path) continue;\n\n const basePath = agentDef.path;\n await fs.ensureDir(basePath);\n\n for (const skill of skills) {\n await this.writeSkillForAgent(agentId, skill, overrides, basePath);\n }\n console.log(pc.gray(` - Updated ${basePath}/ (${agentDef.name})`));\n }\n }\n\n private async resolveTargetAgents(config: SkillConfig): Promise<Agent[]> {\n if (config.agents !== undefined) {\n return config.agents;\n }\n\n // Fallback to content-based detection\n const agentMap = await this.detectionService.detectAgents();\n const detectedAgents = Object.entries(agentMap)\n .filter(([, detected]) => detected)\n .map(([id]) => id as Agent);\n\n // If detection failed and config is empty, default to all supported agents\n return detectedAgents.length > 0\n ? detectedAgents\n : SUPPORTED_AGENTS.map((a) => a.id as Agent);\n }\n\n private async writeSkillForAgent(\n agentId: string,\n skill: CollectedSkill,\n overrides: string[],\n basePath: string,\n ) {\n const isKiro = agentId === Agent.Kiro;\n const kiroFolder = `${skill.category}-${skill.skill}`;\n const skillPath = isKiro\n ? path.join(basePath, kiroFolder)\n : path.join(basePath, skill.category, skill.skill);\n\n await fs.ensureDir(skillPath);\n\n for (const fileItem of skill.files) {\n const targetFilePath = path.join(skillPath, fileItem.name);\n\n if (this.isOverridden(targetFilePath, overrides)) {\n console.log(\n pc.yellow(\n ` ⚠️ Skipping overridden: ${this.normalizePath(targetFilePath)}`,\n ),\n );\n continue;\n }\n\n if (!this.isPathSafe(targetFilePath, skillPath)) {\n console.log(\n pc.red(` ❌ Security Error: Invalid path ${fileItem.name}`),\n );\n continue;\n }\n\n let content = fileItem.content;\n if (isKiro && fileItem.name === 'SKILL.md') {\n content = this.transformSkillForKiro(content, skill.category);\n }\n\n await fs.outputFile(targetFilePath, content);\n }\n }\n\n /**\n * Assembles workflows from the remote registry.\n */\n async assembleWorkflows(config: SkillConfig): Promise<CollectedSkill[]> {\n if (!config.workflows) return [];\n\n // Only sync workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return [];\n }\n\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return [];\n\n const { owner, repo } = githubMatch;\n const ref =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n\n console.log(pc.gray(` - Discovering workflows (${ref})...`));\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) {\n console.log(pc.red(` ❌ Failed to fetch workflows@${ref}.`));\n return [];\n }\n\n const workflowFiles = treeData.tree.filter((f) => {\n if (!f.path.startsWith('.agent/workflows/') || !f.path.endsWith('.md'))\n return false;\n\n if (typeof config.workflows === 'boolean') return config.workflows;\n if (Array.isArray(config.workflows)) {\n return config.workflows.includes(path.basename(f.path, '.md'));\n }\n return false;\n });\n\n const files = await this.githubService.downloadFilesConcurrent(\n workflowFiles.map((f) => ({ owner, repo, ref, path: f.path })),\n );\n\n if (files.length > 0) {\n console.log(pc.gray(` + Fetched ${files.length} workflows`));\n return [\n {\n category: '.agent',\n skill: 'workflows',\n files: files.map((f) => ({\n name: path.basename(f.path),\n content: f.content,\n })),\n },\n ];\n }\n\n return [];\n }\n\n /**\n * Writes collected workflows to the .agent/workflows directory.\n */\n async writeWorkflows(workflows: CollectedSkill[], config: SkillConfig) {\n if (workflows.length === 0) return;\n\n // Only write workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return;\n }\n\n const workflowPath = path.join(process.cwd(), '.agent', 'workflows');\n const overrides = config.custom_overrides || [];\n await fs.ensureDir(workflowPath);\n\n for (const wf of workflows) {\n if (wf.skill !== 'workflows') continue;\n\n for (const fileItem of wf.files) {\n const targetFilePath = path.join(workflowPath, fileItem.name);\n\n if (this.isOverridden(targetFilePath, overrides)) {\n console.log(\n pc.yellow(\n ` ⚠️ Skipping overridden: ${this.normalizePath(targetFilePath)}`,\n ),\n );\n continue;\n }\n\n await fs.outputFile(targetFilePath, fileItem.content);\n console.log(pc.gray(` + Wrote ${fileItem.name}`));\n }\n }\n console.log(pc.green(` ✅ Workflows synced to .agent/workflows/`));\n }\n\n /**\n * Automatically applies framework-specific indices to AGENTS.md.\n */\n async applyIndices(config: SkillConfig, agentsOverride?: Agent[]) {\n const agents = await this.resolveTargetAgents({\n ...config,\n agents: agentsOverride ?? config.agents,\n });\n if (agents.length === 0) return;\n\n console.log(pc.cyan('🔍 Updating Agent Skills index...'));\n\n const agentDef = SUPPORTED_AGENTS.find((a) => a.id === agents[0]);\n if (!agentDef) {\n console.log(\n pc.yellow(` ⚠️ Agent definition not found for ${agents[0]}.`),\n );\n return;\n }\n\n try {\n const generator = new IndexGeneratorService();\n const indexContent = await generator.generate(\n path.join(process.cwd(), agentDef.path),\n Object.keys(config.skills),\n );\n\n await MarkdownUtils.injectIndex(\n process.cwd(),\n ['AGENTS.md'],\n indexContent,\n );\n\n const bridgeService = new AgentBridgeService();\n await bridgeService.bridge(process.cwd(), agents);\n\n console.log(pc.green(` ✅ AGENTS.md index updated.`));\n } catch (error) {\n console.log(pc.yellow(` ⚠️ Failed to update index: ${error}`));\n }\n }\n\n /**\n * Checks for newer versions of skills in the remote registry.\n */\n async checkForUpdates(\n config: SkillConfig,\n ): Promise<Record<string, string> | null> {\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return null;\n\n const { owner, repo } = githubMatch;\n\n try {\n const branch =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n const metaContent = await this.githubService.getRawFile(\n owner,\n repo,\n branch,\n 'skills/metadata.json',\n );\n\n if (!metaContent) return null;\n\n const metadata = JSON.parse(metaContent) as RegistryMetadata;\n const updates: Record<string, string> = {};\n\n for (const [category, catConfig] of Object.entries(config.skills)) {\n const remoteMeta = metadata.categories[category];\n if (!remoteMeta?.version) continue;\n\n const latestRef = `${remoteMeta.tag_prefix || ''}${remoteMeta.version}`;\n if (catConfig.ref !== latestRef) {\n updates[category] = latestRef;\n }\n }\n\n return Object.keys(updates).length > 0 ? updates : null;\n } catch (error) {\n if (process.env.DEBUG)\n console.warn(`[SyncService] Update check failed: ${error}`);\n return null;\n }\n }\n\n // --- Helper Methods ---\n\n private identifyFoldersToSync(\n category: string,\n catConfig: SkillEntry,\n tree: GitHubTreeItem[],\n ): string[] {\n const skillFolders = new Set(\n tree\n .filter((f) => f.path.startsWith(`skills/${category}/`))\n .map((f) => f.path.split('/')[2])\n .filter(Boolean),\n );\n\n const folders = Array.from(skillFolders).filter((folder) => {\n if (catConfig.include && !catConfig.include.includes(folder))\n return false;\n if (catConfig.exclude && catConfig.exclude.includes(folder)) return false;\n return true;\n });\n\n if (catConfig.include) {\n catConfig.include\n .filter((i) => i.includes('/'))\n .forEach((absSkill) =>\n this.expandAbsoluteInclude(absSkill, folders, tree),\n );\n }\n\n return folders;\n }\n\n private expandAbsoluteInclude(\n absSkill: string,\n folders: string[],\n tree: GitHubTreeItem[],\n ) {\n const [targetCat, targetSkill] = absSkill.split('/');\n if (!targetCat || !targetSkill) return;\n\n if (targetSkill === '*') {\n const catSkills = new Set(\n tree\n .filter((f) => f.path.startsWith(`skills/${targetCat}/`))\n .map((f) => f.path.split('/')[2])\n .filter(Boolean),\n );\n\n catSkills.forEach((s) => {\n const fullPath = `${targetCat}/${s}`;\n if (!folders.includes(fullPath)) folders.push(fullPath);\n });\n } else if (!folders.includes(absSkill)) {\n if (\n tree.some((f) =>\n f.path.startsWith(`skills/${targetCat}/${targetSkill}/`),\n )\n ) {\n folders.push(absSkill);\n } else {\n console.log(\n pc.yellow(\n ` ⚠️ Absolute include ${absSkill} not found in repository.`,\n ),\n );\n }\n }\n }\n\n private async fetchSkill(\n owner: string,\n repo: string,\n ref: string,\n category: string,\n absOrRelSkill: string,\n tree: GitHubTreeItem[],\n ): Promise<CollectedSkill | null> {\n const [sourceCat, skillName] = absOrRelSkill.includes('/')\n ? absOrRelSkill.split('/')\n : [category, absOrRelSkill];\n\n const prefix = `skills/${sourceCat}/${skillName}/`;\n const skillSourceFiles = tree.filter(\n (f) => f.path.startsWith(prefix) && f.type === 'blob',\n );\n\n const downloadTasks = skillSourceFiles\n .filter((f) => {\n const rel = f.path.replace(prefix, '');\n return rel === 'SKILL.md' || /^(references|scripts|assets)\\//.test(rel);\n })\n .map((f) => ({ owner, repo, ref, path: f.path }));\n\n const files =\n await this.githubService.downloadFilesConcurrent(downloadTasks);\n if (files.length === 0) return null;\n\n console.log(\n pc.gray(\n ` + Fetched ${sourceCat}/${skillName} (${files.length} files)`,\n ),\n );\n\n return {\n category: sourceCat,\n skill: skillName,\n files: files.map((f) => ({\n name: f.path.replace(prefix, ''),\n content: f.content,\n })),\n };\n }\n\n private transformSkillForKiro(content: string, category: string): string {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!frontmatterMatch) return content;\n\n const [fullMatch, frontmatter] = frontmatterMatch;\n const body = content.slice(fullMatch.length);\n\n const name = frontmatter.match(/^name:\\s*(.+)$/m)?.[1].trim() || '';\n const description =\n frontmatter.match(/^description:\\s*(.+)$/m)?.[1].trim() || '';\n const displayName = `${category.charAt(0).toUpperCase() + category.slice(1)} - ${name}`;\n\n return `---\\nname: ${displayName}\\ndescription: ${description}\\n---` + body;\n }\n\n private isOverridden(targetPath: string, overrides: string[]): boolean {\n const rel = this.normalizePath(targetPath);\n return overrides.some((o) => {\n const op = o.replace(/\\\\/g, '/');\n return rel === op || rel.startsWith(`${op.replace(/\\/$/, '')}/`);\n });\n }\n\n private isPathSafe(targetPath: string, skillPath: string): boolean {\n return path.resolve(targetPath).startsWith(path.resolve(skillPath));\n }\n\n private normalizePath(p: string): string {\n return path.relative(process.cwd(), p).replace(/\\\\/g, '/');\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { ConfigService } from '../services/ConfigService';\nimport { DetectionService } from '../services/DetectionService';\nimport { SyncService } from '../services/SyncService';\n\n/**\n * Command for synchronizing skills and workflows from the remote registry to the local workspace.\n * It handles configuration re-detection, fetching files, writing to disk, and updating indices.\n */\nexport class SyncCommand {\n private configService: ConfigService;\n private detectionService: DetectionService;\n private syncService: SyncService;\n\n constructor(\n configService?: ConfigService,\n detectionService?: DetectionService,\n syncService?: SyncService,\n ) {\n this.configService = configService || new ConfigService();\n this.detectionService = detectionService || new DetectionService();\n this.syncService = syncService || new SyncService();\n }\n\n /**\n * Executes the synchronization flow.\n * Reconciles dependencies, fetches skills and workflows from the registry, and updates AGENTS.md.\n */\n async run(options: { yes?: boolean } = {}) {\n try {\n // 1. Load Config\n const config = await this.configService.loadConfig();\n if (!config) {\n console.log(pc.red('❌ Error: .skillsrc not found. Run `init` first.'));\n return;\n }\n\n // 2. Dynamic Update Configuration (Re-detection)\n const projectDeps = await this.detectionService.getProjectDeps();\n const skillsChanged = await this.syncService.reconcileConfig(\n config,\n projectDeps,\n );\n const workflowsChanged =\n await this.syncService.reconcileWorkflows(config);\n\n if (skillsChanged || workflowsChanged) {\n await this.configService.saveConfig(config);\n }\n\n // 3. Check for updates\n const updates = await this.syncService.checkForUpdates(config);\n\n if (updates) {\n console.log(pc.yellow('\\n🚀 New skill versions detected:'));\n for (const [cat, ref] of Object.entries(updates)) {\n console.log(\n pc.gray(` - ${cat}: ${config.skills[cat].ref} -> ${ref}`),\n );\n }\n\n let update = options.yes;\n if (update === undefined) {\n if (!process.stdin.isTTY) {\n console.log(\n pc.cyan(\n 'ℹ️ Non-interactive environment detected. Skipping version updates. Use --yes to auto-confirm.',\n ),\n );\n update = false;\n } else {\n const answer = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'update',\n message: 'Do you want to update .skillsrc with these versions?',\n default: true,\n },\n ]);\n update = answer.update;\n }\n }\n\n if (update) {\n for (const [cat, ref] of Object.entries(updates)) {\n config.skills[cat].ref = ref;\n }\n await this.configService.saveConfig(config);\n console.log(pc.green('✅ .skillsrc updated.'));\n } else {\n console.log(\n pc.cyan('ℹ️ Skipping version updates, staying on pinned refs.'),\n );\n }\n }\n\n console.log(pc.cyan(`🚀 Syncing skills from ${config.registry}...`));\n\n // 4. Assemble skills from remote registry\n const enabledCategories = Object.keys(config.skills);\n const skills = await this.syncService.assembleSkills(\n enabledCategories,\n config,\n );\n\n // 4b. Assemble workflows\n const workflows = await this.syncService.assembleWorkflows(config);\n\n // 5. Write skills and workflows to target\n await this.syncService.writeSkills(skills, config);\n await this.syncService.writeWorkflows(workflows, config);\n\n // 6. Automatically apply framework-specific indices to AGENTS.md\n await this.syncService.applyIndices(config, config.agents);\n\n console.log(pc.green('✅ All skills synced successfully!'));\n } catch (error) {\n if (error instanceof Error) {\n console.error(pc.red('❌ Sync failed:'), error.message);\n } else {\n console.error(pc.red('❌ Sync failed:'), String(error));\n }\n }\n }\n}\n","import { execSync } from 'child_process';\nimport pc from 'picocolors';\nimport pkg from '../../package.json';\n\n/**\n * Command for upgrading the `agent-skills-standard` CLI to the latest version.\n * It checks the latest version on npm and performs the upgrade using the detected package manager.\n */\nexport class UpgradeCommand {\n /**\n * Executes the upgrade flow.\n * @param options Command options, including `dryRun` to check for updates without installing.\n */\n async run(options: { dryRun?: boolean }) {\n console.log(pc.cyan('🔍 Checking for updates...'));\n\n const currentVersion = pkg.version;\n let latestVersion: string | null = null;\n\n try {\n latestVersion = execSync('npm view agent-skills-standard version', {\n encoding: 'utf8',\n }).trim();\n } catch {\n console.log(pc.red('❌ Failed to check for updates via npm.'));\n return;\n }\n\n if (!latestVersion) {\n console.log(pc.red('❌ Could not determine latest version.'));\n return;\n }\n\n console.log(pc.gray(` Current version: ${currentVersion}`));\n console.log(pc.gray(` Latest version: ${latestVersion}`));\n\n if (currentVersion === latestVersion) {\n console.log(pc.green('✨ You are already using the latest version!'));\n return;\n }\n\n if (options.dryRun) {\n console.log(\n pc.yellow(\n `🚀 A new version (${latestVersion}) is available! Run without --dry-run to upgrade.`,\n ),\n );\n return;\n }\n\n const pm = this.detectPackageManager();\n const upgradeCmd = this.getUpgradeCommand(pm);\n\n console.log(pc.yellow(`📦 Upgrading to v${latestVersion} using ${pm}...`));\n\n try {\n console.log(pc.gray(` Running: ${upgradeCmd}`));\n\n execSync(upgradeCmd, { stdio: 'inherit' });\n\n console.log(pc.green(`✅ Successfully upgraded to v${latestVersion}!`));\n console.log(\n pc.cyan(\n \"Please restart your terminal if the version doesn't update immediately.\",\n ),\n );\n } catch {\n console.log('\\n' + pc.red('❌ Automatic upgrade failed.'));\n this.printManualInstructions(pm);\n }\n }\n\n private detectPackageManager(): 'npm' | 'pnpm' | 'yarn' {\n const userAgent = process.env.npm_config_user_agent || '';\n if (userAgent.includes('pnpm')) return 'pnpm';\n if (userAgent.includes('yarn')) return 'yarn';\n\n // Fallback: Check for existing binaries\n try {\n execSync('pnpm --version', { stdio: 'ignore' });\n return 'pnpm';\n } catch {\n try {\n execSync('yarn --version', { stdio: 'ignore' });\n return 'yarn';\n } catch {\n return 'npm';\n }\n }\n }\n\n private getUpgradeCommand(pm: 'npm' | 'pnpm' | 'yarn'): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm add -g agent-skills-standard@latest';\n case 'yarn':\n return 'yarn global add agent-skills-standard@latest';\n default:\n return 'npm install -g agent-skills-standard@latest';\n }\n }\n\n private printManualInstructions(pm: 'npm' | 'pnpm' | 'yarn') {\n const isWindows = process.platform === 'win32';\n const sudoPrefix = isWindows ? '' : 'sudo ';\n\n console.log(pc.yellow('Possible reasons:'));\n console.log(pc.gray(' - Permission denied (requires sudo/administrator)'));\n console.log(pc.gray(' - Network connectivity issues'));\n console.log(pc.gray(` - ${pm} is not configured for global installs`));\n\n console.log(\n '\\n' + pc.cyan('👉 Please run the following command manually:'),\n );\n console.log(\n pc.white(pc.bold(` ${sudoPrefix}${this.getUpgradeCommand(pm)}`)),\n );\n\n if (pm !== 'npm') {\n console.log(pc.gray('\\nAlternative (npm):'));\n console.log(\n pc.gray(` ${sudoPrefix}npm install -g agent-skills-standard@latest`),\n );\n }\n\n console.log(pc.gray('\\nOr run via npx (no install required):'));\n console.log(pc.gray(` npx agent-skills-standard@latest sync`));\n }\n}\n","import { execSync } from 'child_process';\nimport fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * Service for handling Git operations within the project.\n * Provides a clean interface for querying changed and untracked files.\n */\nexport class GitService {\n /**\n * Finds the root of the project by looking for .git or pnpm-workspace.yaml.\n */\n findProjectRoot(startDir: string = process.cwd()): string {\n let currentDir = startDir;\n while (currentDir !== path.parse(currentDir).root) {\n if (\n fs.existsSync(path.join(currentDir, 'pnpm-workspace.yaml')) ||\n fs.existsSync(path.join(currentDir, '.git'))\n ) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return startDir;\n }\n\n /**\n * Retrieves a list of files that have changed compared to the base branch or HEAD.\n * Handles both CI (GitHub Actions) and local development environments.\n * @param rootDir The root directory of the repository\n * @returns Array of relative file paths\n */\n getChangedFiles(rootDir: string): string[] {\n try {\n let gitCommand: string;\n\n if (process.env.GITHUB_BASE_REF) {\n // CI environment: Compare against the base branch\n try {\n execSync(\n `git fetch origin ${process.env.GITHUB_BASE_REF} --depth=1`,\n {\n cwd: rootDir,\n stdio: 'ignore',\n },\n );\n } catch {\n // Ignore fetch failures\n }\n gitCommand = `git diff --name-only origin/${process.env.GITHUB_BASE_REF}...HEAD`;\n } else {\n // Local environment: Compare against HEAD\n gitCommand = 'git diff --name-only HEAD';\n }\n\n const output = execSync(gitCommand, { cwd: rootDir, encoding: 'utf8' });\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter((f) => f !== '' && fs.existsSync(path.join(rootDir, f)));\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn('Git failure while getting changed files:', error);\n }\n return [];\n }\n }\n\n /**\n * Retrieves a list of untracked files in the repository.\n * @param rootDir The root directory of the repository\n * @returns Array of relative file paths\n */\n getUntrackedFiles(rootDir: string): string[] {\n try {\n const output = execSync('git ls-files --others --exclude-standard', {\n cwd: rootDir,\n encoding: 'utf8',\n });\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter((f) => f !== '' && fs.existsSync(path.join(rootDir, f)));\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn('Git failure while getting untracked files:', error);\n }\n return [];\n }\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { GitService } from './GitService';\n\n/**\n * Service for discovering skill files within the repository.\n * Handles recursive directory scanning and integration with Git for change detection.\n */\nexport class SkillDiscoveryService {\n private gitService = new GitService();\n\n /**\n * Finds all SKILL.md files in the repository.\n * @param skillsDir The directory to search within\n * @returns Array of absolute paths to skill files\n */\n async findAllSkills(skillsDir: string): Promise<string[]> {\n const skillFiles: string[] = [];\n\n const findRecursive = async (dir: string) => {\n try {\n const items = await fs.readdir(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n try {\n const stat = await fs.stat(fullPath);\n\n if (stat.isDirectory()) {\n await findRecursive(fullPath);\n } else if (item === 'SKILL.md') {\n skillFiles.push(fullPath);\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`Failed to stat path: ${fullPath}`, error);\n }\n }\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`Failed to read directory: ${dir}`, error);\n }\n }\n };\n\n if (await fs.pathExists(skillsDir)) {\n await findRecursive(skillsDir);\n }\n\n return skillFiles;\n }\n\n /**\n * Finds skills that have been changed or are untracked in Git.\n * @returns Array of absolute paths to changed skill files\n */\n async findChangedSkills(): Promise<string[]> {\n const rootDir = this.gitService.findProjectRoot();\n const changedRelative = this.gitService.getChangedFiles(rootDir);\n const untrackedRelative = this.gitService.getUntrackedFiles(rootDir);\n\n const isSkillFile = (file: string) =>\n file.startsWith('skills/') && file.endsWith('SKILL.md');\n\n const allChangedAbsolute = [...changedRelative, ...untrackedRelative]\n .filter(isSkillFile)\n .map((file) => path.join(rootDir, file));\n\n // Simple deduplication\n return Array.from(new Set(allChangedAbsolute));\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { RuleResult, ValidationRule } from './types';\n\n/**\n * Enforces a maximum line count for skill files to ensure token efficiency.\n */\nexport class SizeRule implements ValidationRule {\n name = 'Size Limit';\n constructor(private maxLines: number = 100) {}\n\n async validate(content: string): Promise<RuleResult> {\n const lines = content.split('\\n');\n if (lines.length > this.maxLines) {\n return {\n passed: false,\n errors: [\n `SKILL.md too large (${lines.length} lines > ${this.maxLines} limit)`,\n ],\n warnings: [],\n };\n }\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Validates frontmatter presence and required fields.\n */\nexport class FrontmatterRule implements ValidationRule {\n name = 'Frontmatter';\n\n async validate(content: string): Promise<RuleResult> {\n const result: RuleResult = { passed: true, errors: [], warnings: [] };\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n\n if (!frontmatterMatch) {\n return {\n passed: false,\n errors: ['Missing or invalid frontmatter'],\n warnings: [],\n };\n }\n\n const frontmatter = frontmatterMatch[1];\n\n if (!frontmatter.includes('name:')) {\n result.errors.push('Missing \"name\" field in frontmatter');\n result.passed = false;\n }\n\n if (!frontmatter.includes('description:')) {\n result.errors.push('Missing \"description\" field in frontmatter');\n result.passed = false;\n } else {\n const descMatch = frontmatter.match(/description:\\s*(.+)/);\n if (descMatch && descMatch[1].length > 200) {\n result.errors.push(\n `Description too long (${descMatch[1].length} chars > 200 limit)`,\n );\n result.passed = false;\n }\n }\n\n return result;\n }\n}\n\n/**\n * Recommends imperative mood over conversational style.\n */\nexport class InstructionsStyleRule implements ValidationRule {\n name = 'Instruction Style';\n\n async validate(content: string): Promise<RuleResult> {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n const body = frontmatterMatch ? frontmatterMatch[2] : content;\n const bodyLines = body.split('\\n');\n let isInCodeBlock = false;\n let hasConversationalStyle = false;\n\n const conversationalPatterns =\n /^(?:\\s*[-*+]\\s*|\\s*\\d+\\.\\s*)(?:you should|please|let's|we can|I recommend)/i;\n\n for (const line of bodyLines) {\n if (line.trim().startsWith('```')) {\n isInCodeBlock = !isInCodeBlock;\n continue;\n }\n if (isInCodeBlock) continue;\n\n if (conversationalPatterns.test(line)) {\n hasConversationalStyle = true;\n break;\n }\n }\n\n if (hasConversationalStyle) {\n return {\n passed: true,\n errors: [],\n warnings: [\n 'Consider using imperative mood instead of conversational style in instructions',\n ],\n };\n }\n\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Ensures the mandatory priority section is present.\n */\nexport class PriorityRule implements ValidationRule {\n name = 'Priority Section';\n\n async validate(content: string): Promise<RuleResult> {\n if (!content.includes('## **Priority:')) {\n return {\n passed: false,\n errors: ['Missing priority section'],\n warnings: [],\n };\n }\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Validates the directory structure surrounding the skill file.\n */\nexport class DirectoryStructureRule implements ValidationRule {\n name = 'Directory Structure';\n\n async validate(_content: string, filePath: string): Promise<RuleResult> {\n const result: RuleResult = { passed: true, errors: [], warnings: [] };\n const skillDir = path.dirname(filePath);\n\n // Check scripts\n const scriptsDir = path.join(skillDir, 'scripts');\n if (await fs.pathExists(scriptsDir)) {\n const scriptFiles = await fs.readdir(scriptsDir);\n for (const file of scriptFiles) {\n if (!['.py', '.js', '.ts', '.sh'].includes(path.extname(file))) {\n result.warnings.push(`Script without standard extension: ${file}`);\n }\n }\n }\n\n // Check references\n const refsDir = path.join(skillDir, 'references');\n if (await fs.pathExists(refsDir)) {\n const refFiles = await fs.readdir(refsDir);\n if (refFiles.filter((f) => f.endsWith('.md')).length === 0) {\n result.warnings.push(\n 'References directory exists but contains no .md files',\n );\n }\n }\n\n return result;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { GitService } from './GitService';\nimport { SkillDiscoveryService } from './SkillDiscoveryService';\nimport {\n DirectoryStructureRule,\n FrontmatterRule,\n InstructionsStyleRule,\n PriorityRule,\n SizeRule,\n} from './validation/rules';\nimport { ValidationRule } from './validation/types';\n\n/**\n * Result of validating a single skill file.\n */\nexport interface SkillValidationResult {\n /** Relative path to the skill file. */\n file: string;\n /** List of validation error messages. */\n errors: string[];\n /** List of validation warning messages. */\n warnings: string[];\n /** Whether the file passed all mandatory validation rules. */\n passed: boolean;\n}\n\n/**\n * Aggregated summary of all validation results.\n */\nexport interface ValidationSummary {\n /** Total number of skills validated. */\n total: number;\n /** Number of skills that passed validation. */\n passed: number;\n /** Number of skills that failed validation. */\n failed: number;\n /** Cumulative number of warnings across all skills. */\n warnings: number;\n}\n\n/**\n * Service for validating skill files (SKILL.md) and repository metadata.\n * Enforces size limits, frontmatter requirements, and imperative instruction style.\n * Uses a Rule Pattern for modular validation.\n */\nexport class SkillValidator {\n private results: SkillValidationResult[] = [];\n private skillDiscovery = new SkillDiscoveryService();\n private gitService = new GitService();\n private rules: ValidationRule[] = [\n new SizeRule(),\n new FrontmatterRule(),\n new InstructionsStyleRule(),\n new PriorityRule(),\n new DirectoryStructureRule(),\n ];\n\n /**\n * Runs the complete validation suite.\n * @param validateAll Whether to validate all skills or just changed ones\n * @returns Exit code (0 for success, 1 for failure)\n */\n async run(validateAll: boolean = false): Promise<number> {\n try {\n const summary = await this.validateAllSkills(validateAll);\n this.printSummary(summary);\n return summary.failed > 0 ? 1 : 0;\n } catch (error) {\n console.error(\n pc.red(\n `❌ Validation error: ${error instanceof Error ? error.stack : error}`,\n ),\n );\n return 1;\n }\n }\n\n /**\n * Validates all identified skill files in the repository.\n * @param validateAll Whether to validate all skills or just changed ones\n * @returns Summary of validation results\n */\n async validateAllSkills(\n validateAll: boolean = false,\n ): Promise<ValidationSummary> {\n const rootDir = this.gitService.findProjectRoot();\n const skillsDir = path.join(rootDir, 'skills');\n\n if (!(await fs.pathExists(skillsDir))) {\n throw new Error(`skills/ directory not found (searched at ${skillsDir})`);\n }\n\n const skillFiles = validateAll\n ? await this.skillDiscovery.findAllSkills(skillsDir)\n : await this.skillDiscovery.findChangedSkills();\n\n console.log(\n pc.blue(\n `🔍 Found ${skillFiles.length} ${validateAll ? '' : 'changed '}skills to validate\\n`,\n ),\n );\n\n for (const skillFile of skillFiles) {\n const result = await this.validateSkill(skillFile);\n this.results.push(result);\n\n if (result.passed) {\n console.log(pc.green(`✅ ${result.file}`));\n result.warnings.forEach((warning) =>\n console.log(pc.yellow(` ⚠️ ${warning}`)),\n );\n } else {\n console.log(pc.red(`❌ ${result.file}`));\n result.errors.forEach((error) => console.log(pc.red(` ❌ ${error}`)));\n }\n }\n\n await this.validateMetadata(rootDir);\n\n return this.generateSummary();\n }\n\n private async validateSkill(\n skillFile: string,\n ): Promise<SkillValidationResult> {\n const rootDir = this.gitService.findProjectRoot();\n const result: SkillValidationResult = {\n file: path.relative(rootDir, skillFile),\n errors: [],\n warnings: [],\n passed: true,\n };\n\n try {\n const content = await fs.readFile(skillFile, 'utf8');\n\n for (const rule of this.rules) {\n const ruleResult = await rule.validate(content, skillFile);\n if (!ruleResult.passed) {\n result.passed = false;\n }\n result.errors.push(...ruleResult.errors);\n result.warnings.push(...ruleResult.warnings);\n }\n } catch (error) {\n result.errors.push(\n `Failed to read or validate file: ${error instanceof Error ? error.message : error}`,\n );\n result.passed = false;\n }\n\n return result;\n }\n\n private async validateMetadata(rootDir: string): Promise<void> {\n const metadataPath = path.join(rootDir, 'skills', 'metadata.json');\n\n try {\n if (!(await fs.pathExists(metadataPath))) {\n throw new Error('skills/metadata.json not found');\n }\n\n const metadata = await fs.readJson(metadataPath);\n if (!metadata.categories) {\n throw new Error('metadata.json missing \"categories\" field');\n }\n\n for (const [category, config] of Object.entries(metadata.categories)) {\n const catConfig = config as { version?: string; tag_prefix?: string };\n\n if (!catConfig.version || !catConfig.tag_prefix) {\n throw new Error(\n `Category \"${category}\" missing required fields (version, tag_prefix) in metadata.json`,\n );\n }\n\n console.log(\n pc.green(\n `✅ Category metadata valid: ${category} (v${catConfig.version}, ${catConfig.tag_prefix})`,\n ),\n );\n }\n } catch (error) {\n throw new Error(\n `Metadata validation failed: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n\n private generateSummary(): ValidationSummary {\n const summary: ValidationSummary = {\n total: this.results.length,\n passed: 0,\n failed: 0,\n warnings: 0,\n };\n\n for (const result of this.results) {\n if (result.passed) {\n summary.passed++;\n } else {\n summary.failed++;\n }\n summary.warnings += result.warnings.length;\n }\n\n return summary;\n }\n\n printSummary(summary: ValidationSummary): void {\n console.log('\\n' + '='.repeat(50));\n console.log(pc.blue('📊 VALIDATION SUMMARY'));\n console.log('='.repeat(50));\n\n console.log(pc.green(`Passed: ${summary.passed}`));\n console.log(pc.red(`Failed: ${summary.failed}`));\n\n if (summary.failed > 0) {\n console.log(\n '\\n' + pc.red('❌ Validation failed! Please fix the errors above.'),\n );\n } else {\n console.log('\\n' + pc.green('✅ All skills passed validation!'));\n\n if (summary.warnings > 0) {\n console.log(\n pc.yellow(\n `⚠️ ${summary.warnings} warnings found. Consider addressing them for better token efficiency.`,\n ),\n );\n }\n }\n }\n}\n","import { SkillValidator } from '../services/SkillValidator';\n\n/**\n * Command for validating the integrity and format of skills in the local directory.\n * Useful for development and CI/CD pipelines to ensure skills follow the standard.\n */\nexport class ValidateCommand {\n /**\n * Executes the validation flow.\n * @param options Command options, including `all` to validate all skills instead of only changed ones.\n */\n async run(options: { all?: boolean } = {}) {\n const validator = new SkillValidator();\n const exitCode = await validator.run(options.all ?? false);\n process.exit(exitCode);\n }\n}\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport dotenv from 'dotenv';\nimport { FeedbackCommand } from './commands/feedback';\nimport { InitCommand } from './commands/init';\nimport { ListSkillsCommand } from './commands/list-skills';\nimport { SyncCommand } from './commands/sync';\nimport { UpgradeCommand } from './commands/upgrade';\nimport { ValidateCommand } from './commands/validate-skills';\n\n// Load .env from current directory (for development and other env vars)\ndotenv.config();\n\nconst program = new Command();\n\nprogram\n .name('agent-skills-standard')\n .description(\n 'A CLI to manage and sync AI agent skills for Cursor, Claude, Copilot, Windsurf, and more.',\n )\n .version('1.8.2');\n\nprogram\n .command('init')\n .description('Initialize a .skillsrc configuration file interactively')\n .action(async () => {\n const init = new InitCommand();\n await init.run();\n });\n\nprogram\n .command('sync')\n .description('Sync skills to AI Agent skill directories')\n .option(\n '-y, --yes',\n 'Automatically confirm interactive prompts (e.g. update versions)',\n )\n .action(async (options) => {\n const sync = new SyncCommand();\n await sync.run(options);\n });\n\nprogram\n .command('list-skills')\n .description('List available framework skills and detection status')\n .option('-f, --framework <framework>', 'The framework to list skills for')\n .action(async (options) => {\n const cmd = new ListSkillsCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('validate')\n .description('Validate skill format and token efficiency standards')\n .option('--all', 'Validate all skills instead of only changed ones')\n .action(async (options) => {\n const cmd = new ValidateCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('feedback')\n .description('Report skill improvement opportunities or AI agent mistakes')\n .option(\n '--skill <skill>',\n 'The skill ID (e.g., flutter/bloc-state-management)',\n )\n .option('--issue <issue>', 'Brief description of the issue')\n .option('--model <model>', 'AI agent model (e.g., Claude 3.5 Sonnet)')\n .option('--context <context>', 'Additional context (e.g., framework version)')\n .option('--suggestion <suggestion>', 'Suggested improvement')\n .option(\n '--skill-instruction <instruction>',\n 'Exact quote from skill that was violated (AI auto-report)',\n )\n .option(\n '--actual-action <action>',\n 'What you actually did instead of following skill (AI auto-report)',\n )\n .option(\n '--decision-reason <reason>',\n 'Why you chose this approach instead (AI auto-report)',\n )\n .option(\n '--loaded-skills <skills>',\n 'Comma-separated list of currently loaded skills (platform-provided)',\n )\n .action(async (options: Record<string, string>) => {\n const cmd = new FeedbackCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade the CLI to the latest version')\n .option('--dry-run', 'Check for updates without installing')\n .action(async (options) => {\n const cmd = new UpgradeCommand();\n await cmd.run(options);\n });\n\nprogram.parse();\n"],"names":["Agent","Framework","z","pkg","results","path","agents","execSync","Command"],"mappings":";;;;;;;;;;;AAgCO,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAI3B,YAAgC;AAC9B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAO,MAAsC;AACjD,UAAM,SAAS,KAAK,UAAA;AACpB,QAAI,CAAC,OAAQ,QAAO;AAEpB,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,QAAQ;AAAA,QACnC,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,cAAc;AAAA,QAAA;AAAA,QAEhB,MAAM,KAAK,UAAU,IAAI;AAAA,MAAA,CAC1B;AAED,aAAO,SAAS;AAAA,IAClB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AC1DO,MAAM,gBAAgB;AAAA,EACnB;AAAA,EAER,YAAY,iBAAmC;AAC7C,SAAK,kBAAkB,mBAAmB,IAAI,gBAAA;AAAA,EAChD;AAAA,EAEA,MAAM,IAAI,SAUP;AACD,YAAQ,IAAI,GA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AAC;AAEH,QACG,QAAQ,MAAM,EACd,YAAY,2CAA2C,EACvD;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,OAAO,YAAY;AACzB,QAAM,OAAO,IAAI,YAAA;AACjB,QAAM,KAAK,IAAI,OAAO;AACxB,CAAC;AAEH,QACG,QAAQ,aAAa,EACrB,YAAY,sDAAsD,EAClE,OAAO,+BAA+B,kCAAkC,EACxE,OAAO,OAAO,YAAY;AACzB,QAAM,MAAM,IAAI,kBAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,sDAAsD,EAClE,OAAO,SAAS,kDAAkD,EAClE,OAAO,OAAO,YAAY;AACzB,QAAM,MAAM,IAAI,gBAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,6DAA6D,EACzE;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,mBAAmB,gCAAgC,EAC1D,OAAO,mBAAmB,0CAA0C,EACpE,OAAO,uBAAuB,8CAA8C,EAC5E,OAAO,6BAA6B,uBAAuB,EAC3D;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,OAAO,YAAoC;AACjD,QAAM,MAAM,IAAI,gBAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,SAAS,EACjB,YAAY,uCAAuC,EACnD,OAAO,aAAa,sCAAsC,EAC1D,OAAO,OAAO,YAAY;AACzB,QAAM,MAAM,IAAI,eAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QAAQ,MAAA;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/services/FeedbackService.ts","../src/commands/feedback.ts","../src/constants/enums.ts","../src/constants/skills.ts","../src/constants/index.ts","../src/services/ConfigService.ts","../src/services/DetectionService.ts","../src/services/InitService.ts","../src/services/GithubService.ts","../src/services/RegistryService.ts","../src/commands/init.ts","../src/services/SkillService.ts","../src/commands/list-skills.ts","../src/services/AgentBridgeService.ts","../src/services/IndexGeneratorService.ts","../src/services/utils/MarkdownUtils.ts","../src/services/SyncService.ts","../src/commands/sync.ts","../src/commands/upgrade.ts","../src/services/GitService.ts","../src/services/SkillDiscoveryService.ts","../src/services/validation/rules.ts","../src/services/SkillValidator.ts","../src/commands/validate-skills.ts","../src/index.ts"],"sourcesContent":["/**\n * Structure of the feedback data payload submitted to the backend.\n * Contains both required issue details and optional context gathered by the AI.\n */\nexport interface FeedbackData {\n /** The specific skill ID that had the issue */\n skill: string;\n /** Detailed description of the problem */\n issue: string;\n\n /** Multi-line context about where the error occurred */\n context?: string;\n /** The AI model used when the issue was detected */\n model?: string;\n /** Proposed fix or improvement */\n suggestion?: string;\n\n /** Exact instruction from the skill that was misinterpreted */\n skillInstruction?: string;\n /** What the AI actually did instead of following the skill */\n actualAction?: string;\n /** Rationale for choosing the incorrect path */\n decisionReason?: string;\n\n /** List of other active skills at the time of the error */\n loadedSkills?: string;\n}\n\n/**\n * Service to handle automated feedback reporting via Proxy Backend.\n * Follows SOLID & KISS: Strictly handles API communication.\n */\nexport class FeedbackService {\n /**\n * Resolves the API URL from environment variables.\n */\n getApiUrl(): string | undefined {\n return process.env.FEEDBACK_API_URL;\n }\n\n /**\n * Submits feedback data to the backend for automatic GitHub Issue creation.\n * Internal proxy handles GitHub tokens, keeping client-side logic tokenless.\n *\n * @param data The feedback payload\n * @returns boolean indicating submission success\n */\n async submit(data: FeedbackData): Promise<boolean> {\n const apiUrl = this.getApiUrl();\n if (!apiUrl) return false;\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'agent-skills-standard-cli',\n },\n body: JSON.stringify(data),\n });\n\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { FeedbackData, FeedbackService } from '../services/FeedbackService';\n\n/**\n * Command for automated skill feedback reporting.\n * Follows KISS: Minimal user output, focusing on functional submission.\n */\nexport class FeedbackCommand {\n private feedbackService: FeedbackService;\n\n constructor(feedbackService?: FeedbackService) {\n this.feedbackService = feedbackService || new FeedbackService();\n }\n\n async run(options: {\n skill?: string;\n issue?: string;\n model?: string;\n context?: string;\n suggestion?: string;\n skillInstruction?: string;\n actualAction?: string;\n decisionReason?: string;\n loadedSkills?: string;\n }) {\n console.log(pc.bold(pc.blue('\\n📣 Agent Skills Feedback Reporter\\n')));\n\n let {\n skill,\n issue,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n } = options;\n\n // Interactive mode if mandatory options are missing\n if (!skill || !issue) {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'skill',\n message:\n 'Which skill ID has the issue? (e.g., flutter/bloc-state-management)',\n when: !skill,\n validate: (input: string) =>\n input.trim().length > 0 || 'Skill ID is required',\n },\n {\n type: 'input',\n name: 'issue',\n message: 'What is the issue? (Brief description)',\n when: !issue,\n validate: (input: string) =>\n input.trim().length > 0 || 'Issue description is required',\n },\n {\n type: 'input',\n name: 'model',\n message: 'AI Model name (optional, e.g., Claude 3.5 Sonnet)',\n when: !model,\n },\n {\n type: 'input',\n name: 'context',\n message: 'Any extra context? (optional, e.g., framework versions)',\n when: !context,\n },\n {\n type: 'input',\n name: 'suggestion',\n message: 'Any suggested improvement? (optional)',\n when: !suggestion,\n },\n {\n type: 'input',\n name: 'skillInstruction',\n message: 'Exact quote from skill (optional)',\n when: !skillInstruction,\n },\n {\n type: 'input',\n name: 'actualAction',\n message: 'What you did instead (optional)',\n when: !actualAction,\n },\n {\n type: 'input',\n name: 'decisionReason',\n message: 'Why you chose this approach (optional)',\n when: !decisionReason,\n },\n {\n type: 'input',\n name: 'loadedSkills',\n message: 'All active skills (optional)',\n when: !loadedSkills,\n },\n ]);\n\n skill = skill || (answers.skill as string);\n issue = issue || (answers.issue as string);\n model = model || (answers.model as string);\n context = context || (answers.context as string);\n suggestion = suggestion || (answers.suggestion as string);\n skillInstruction =\n skillInstruction || (answers.skillInstruction as string);\n actualAction = actualAction || (answers.actualAction as string);\n decisionReason = decisionReason || (answers.decisionReason as string);\n loadedSkills = loadedSkills || (answers.loadedSkills as string);\n\n await this.submit({\n skill: skill!,\n issue: issue!,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n });\n } else {\n await this.submit({\n skill,\n issue,\n model,\n context,\n suggestion,\n skillInstruction,\n actualAction,\n decisionReason,\n loadedSkills,\n });\n }\n }\n\n private async submit(data: FeedbackData) {\n const apiUrl = this.feedbackService.getApiUrl();\n\n if (!apiUrl) {\n console.log(pc.yellow('\\n⚠️ Feedback API not configured.'));\n console.log(\n pc.gray(\n 'Please set the ' +\n pc.bold('FEEDBACK_API_URL') +\n ' environment variable.',\n ),\n );\n return;\n }\n\n console.log(pc.gray(`📤 Sending feedback to ${apiUrl}...`));\n\n const success = await this.feedbackService.submit(data);\n\n if (success) {\n console.log(pc.green('\\n✅ Feedback has been sent successfully!'));\n console.log(\n pc.gray('Thank you for helping improve the Agent Skills Standard.\\n'),\n );\n } else {\n console.log(pc.red('\\n❌ Failed to send feedback.'));\n console.log(\n pc.gray(\n `Please check that the Feedback API is reachable: ${pc.cyan(apiUrl)}\\n`,\n ),\n );\n }\n }\n}\n","export enum Agent {\n Cursor = 'cursor',\n Trae = 'trae',\n Claude = 'claude',\n Copilot = 'copilot',\n Antigravity = 'antigravity',\n OpenAI = 'openai',\n OpenCode = 'opencode',\n Gemini = 'gemini',\n Roo = 'roo',\n Windsurf = 'windsurf',\n Kiro = 'kiro',\n}\n\nexport enum Framework {\n Flutter = 'flutter',\n NestJS = 'nestjs',\n Golang = 'golang',\n NextJS = 'nextjs',\n React = 'react',\n ReactNative = 'react-native',\n Angular = 'angular',\n SpringBoot = 'spring-boot',\n Android = 'android',\n iOS = 'ios',\n Laravel = 'laravel',\n}\n","import { Framework } from './enums';\n\n/**\n * SkillDetection defines how to automatically enable a skill based on project dependencies.\n */\nexport interface SkillDetection {\n /** The skill ID as defined in the registry (e.g., 'riverpod-state-management') */\n id: string;\n /** List of npm or pub packages that indicate this skill is used */\n packages: string[];\n /** Optional list of root folder/file paths (relative to cwd). If any exist, the skill is detected. */\n files?: string[];\n}\n\n/**\n * Registry of automatic skill detection rules grouped by framework.\n */\nexport const SKILL_DETECTION_REGISTRY: Record<string, SkillDetection[]> = {\n [Framework.Flutter]: [\n {\n id: 'riverpod-state-management',\n packages: ['flutter_riverpod', 'riverpod'],\n },\n {\n id: 'bloc-state-management',\n packages: ['flutter_bloc', 'bloc'],\n },\n {\n id: 'auto-route-navigation',\n packages: ['auto_route'],\n },\n {\n id: 'go-router-navigation',\n packages: ['go_router'],\n },\n {\n id: 'getx-navigation',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'getx-state-management',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'localization',\n packages: ['easy_localization'],\n },\n {\n id: 'retrofit-networking',\n packages: ['retrofit'],\n },\n {\n id: 'dependency-injection',\n packages: ['get_it', 'injectable'],\n },\n ],\n [Framework.NestJS]: [\n {\n id: 'caching',\n packages: ['@nestjs/cache-manager', 'cache-manager'],\n },\n {\n id: 'database',\n packages: ['@nestjs/typeorm', '@nestjs/prisma', '@nestjs/mongoose'],\n },\n {\n id: 'security',\n packages: ['@nestjs/passport', 'passport', 'helmet'],\n },\n ],\n [Framework.Android]: [\n {\n id: 'compose',\n packages: ['androidx.compose.ui'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'navigation',\n packages: ['androidx.navigation:navigation-compose'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'legacy-navigation',\n packages: [\n 'androidx.navigation:navigation-fragment',\n 'androidx.navigation:navigation-ui',\n ],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'di',\n packages: ['hilt-android', 'dagger-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'persistence',\n packages: ['androidx.room:room-runtime'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'networking',\n packages: ['retrofit'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'concurrency',\n packages: ['kotlinx-coroutines-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n ],\n [Framework.iOS]: [\n {\n id: 'networking',\n packages: ['Alamofire', 'Moya'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'dependency-injection',\n packages: ['Swinject', 'Resolver'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'persistence',\n packages: ['Realm', 'CoreData', 'SQLite.swift'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'state-management',\n packages: ['ComposableArchitecture', 'CombineRuntime'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ui-navigation',\n packages: ['Coordinator', 'Router'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n ],\n [Framework.ReactNative]: [\n {\n id: 'navigation',\n packages: ['@react-navigation/native'],\n },\n {\n id: 'state-management',\n packages: ['zustand', '@reduxjs/toolkit'],\n },\n {\n id: 'deployment',\n packages: ['react-native-code-push', 'expo-updates'],\n },\n {\n id: 'security',\n packages: ['react-native-keychain', 'react-native-ssl-pinning'],\n },\n {\n id: 'performance',\n packages: ['react-native-fast-image'],\n },\n ],\n [Framework.Laravel]: [\n {\n id: 'api',\n packages: ['laravel/sanctum', 'laravel/passport'],\n },\n {\n id: 'background-processing',\n packages: ['laravel/horizon'],\n },\n {\n id: 'testing',\n packages: ['pestphp/pest', 'phpunit/phpunit'],\n },\n {\n id: 'tooling',\n packages: ['laravel/pint', 'laravel/sail'],\n },\n {\n id: 'database-expert',\n packages: ['laravel/framework'], // Always present, but used for sub-skill mapping\n },\n ],\n [Framework.NextJS]: [\n {\n id: 'pages-router',\n packages: [],\n files: ['pages', 'src/pages'],\n },\n {\n id: 'server-components',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'server-actions',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'data-fetching',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'i18n',\n packages: ['next-intl', 'react-intl', 'next-translate', 'i18next'],\n files: [\n 'middleware.ts',\n 'app/[lang]',\n 'pages/[locale]',\n 'next.config.js',\n ],\n },\n ],\n [Framework.React]: [\n {\n id: 'styling',\n packages: ['tailwind', 'antd', 'sass', 'styled-components', 'emotion'],\n },\n {\n id: 'state-management',\n packages: [\n 'redux',\n '@reduxjs/toolkit',\n 'zustand',\n 'mobx',\n 'recoil',\n 'jotai',\n ],\n },\n {\n id: 'testing',\n packages: [\n 'jest',\n 'vitest',\n '@testing-library/react',\n 'cypress',\n 'playwright',\n ],\n },\n ],\n database: [\n {\n id: 'postgresql',\n packages: ['pg', 'pgx', 'postgres', 'sequelize', 'typeorm', 'prisma'],\n },\n {\n id: 'mongodb',\n packages: ['mongodb', 'mongoose'],\n },\n {\n id: 'redis',\n packages: ['redis', 'ioredis', 'predis'],\n },\n ],\n};\n","import { Agent, Framework } from './enums';\n\nexport { Agent, Framework };\n\nexport const UNIVERSAL_SKILLS = ['common'];\nexport const BACKEND_FRAMEWORKS: Framework[] = [\n Framework.NestJS,\n Framework.Golang,\n Framework.SpringBoot,\n Framework.Laravel,\n];\n\nexport const FRONTEND_FRAMEWORKS: Framework[] = [\n Framework.React,\n Framework.NextJS,\n Framework.Angular,\n];\n\nexport const MOBILE_FRAMEWORKS: Framework[] = [\n Framework.Flutter,\n Framework.Android,\n Framework.iOS,\n Framework.ReactNative,\n];\n\nexport const FRONTEND_REACT_FRAMEWORKS: Framework[] = [\n Framework.NextJS,\n Framework.ReactNative,\n];\n\n/**\n * Sub-skills to exclude from the `common` category based on the selected framework type.\n * Backend: exclude web-only and mobile-only skills.\n * Frontend: exclude backend-only and mobile-only skills.\n * Mobile: exclude web-only and backend-only skills.\n */\nexport const COMMON_SKILL_EXCLUDES: Record<\n 'backend' | 'frontend' | 'mobile',\n string[]\n> = {\n backend: ['accessibility', 'mobile-animation', 'mobile-ux-core'],\n frontend: ['observability', 'mobile-animation', 'mobile-ux-core'],\n mobile: ['accessibility', 'api-design', 'observability'],\n};\n\n/**\n * Classifies a framework ID into its platform type for skill exclusion purposes.\n * Returns null for unknown/hybrid frameworks — no exclusions are applied.\n */\nexport function getFrameworkType(\n framework: string,\n): 'backend' | 'frontend' | 'mobile' | null {\n if (BACKEND_FRAMEWORKS.includes(framework as Framework)) return 'backend';\n if (MOBILE_FRAMEWORKS.includes(framework as Framework)) return 'mobile';\n if (FRONTEND_FRAMEWORKS.includes(framework as Framework)) return 'frontend';\n return null;\n}\n\nexport const DEFAULT_REGISTER =\n 'https://github.com/HoangNguyen0403/agent-skills-standard';\n\nexport const DEFAULT_WORKFLOWS = [\n 'code-review',\n 'codebase-review',\n 'plan-feature',\n 'skill-benchmark',\n];\n\n// Configurable via ENV or hardcoded for production convenience\nexport interface AgentDefinition {\n id: Agent;\n name: string;\n path: string;\n ruleFile: string;\n ruleExtension: string;\n ruleFileName?: string;\n frontmatterStyle: 'cursor' | 'copilot' | 'none';\n detectionFiles: string[];\n}\n\nexport interface FrameworkDefinition {\n id: Framework;\n name: string;\n languages: string[];\n detectionFiles: string[];\n detectionDependencies?: string[];\n languageDetection?: Record<string, string[]>;\n}\n\nexport const getAgentDefinition = (id: Agent): AgentDefinition => {\n switch (id) {\n case Agent.Cursor:\n return {\n id,\n name: 'Cursor',\n path: '.cursor/skills',\n ruleFile: '.cursor/rules',\n ruleExtension: '.mdc',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.cursor', '.cursorrules'],\n };\n case Agent.Trae:\n return {\n id,\n name: 'Trae',\n path: '.trae/skills',\n ruleFile: '.trae/rules',\n ruleExtension: '.mdc',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.trae'],\n };\n case Agent.Claude:\n return {\n id,\n name: 'Claude Code',\n path: '.claude/skills',\n ruleFile: '.', // Root directory for CLAUDE.md\n ruleExtension: '.md',\n ruleFileName: 'CLAUDE.md',\n frontmatterStyle: 'none',\n detectionFiles: ['.claude', 'CLAUDE.md'],\n };\n case Agent.Copilot:\n return {\n id,\n name: 'GitHub Copilot',\n path: '.github/skills',\n ruleFile: '.github/instructions',\n ruleExtension: '.instructions.md',\n frontmatterStyle: 'copilot',\n detectionFiles: ['.github'],\n };\n case Agent.Antigravity:\n return {\n id,\n name: 'Antigravity',\n path: '.agent/skills',\n ruleFile: '.agent/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.agent'],\n };\n case Agent.OpenAI:\n return {\n id,\n name: 'OpenAI',\n path: '.codex/skills',\n ruleFile: '.codex/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.codex'],\n };\n case Agent.OpenCode:\n return {\n id,\n name: 'OpenCode',\n path: '.opencode/skills',\n ruleFile: '.opencode/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.opencode'],\n };\n case Agent.Gemini:\n return {\n id,\n name: 'Gemini',\n path: '.gemini/skills',\n ruleFile: '.gemini/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.gemini'],\n };\n case Agent.Roo:\n return {\n id,\n name: 'Roo Code',\n path: '.roo/skills',\n ruleFile: '.roo/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.roo'],\n };\n case Agent.Windsurf:\n return {\n id,\n name: 'Windsurf',\n path: '.windsurf/skills',\n ruleFile: '.windsurf/rules',\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.windsurf', '.windsurfrules'],\n };\n case Agent.Kiro:\n return {\n id,\n name: 'Kiro',\n path: '.kiro/skills',\n ruleFile: '.kiro/rules', // Changed from steering to match AGENT_CONFIGS\n ruleExtension: '.md',\n frontmatterStyle: 'cursor',\n detectionFiles: ['.kiro'],\n };\n }\n};\n\nexport const getFrameworkDefinition = (id: Framework): FrameworkDefinition => {\n switch (id) {\n case Framework.Flutter:\n return {\n id,\n name: 'Flutter',\n languages: ['dart'],\n detectionFiles: ['pubspec.yaml'],\n };\n case Framework.NestJS:\n return {\n id,\n name: 'NestJS',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['nest-cli.json'],\n detectionDependencies: ['@nestjs/core'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.Golang:\n return {\n id,\n name: 'Go (Golang)',\n languages: ['go'],\n detectionFiles: ['go.mod'],\n };\n case Framework.NextJS:\n return {\n id,\n name: 'Next.js',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['next.config.js', 'next.config.mjs'],\n detectionDependencies: ['next'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.React:\n return {\n id,\n name: 'React',\n languages: ['typescript', 'javascript'],\n detectionFiles: [],\n detectionDependencies: ['react', 'react-dom'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.ReactNative:\n return {\n id,\n name: 'React Native',\n languages: ['typescript', 'javascript'],\n detectionFiles: ['metro.config.js'],\n detectionDependencies: ['react-native'],\n languageDetection: {\n typescript: ['tsconfig.json'],\n javascript: ['jsconfig.json'],\n },\n };\n case Framework.Angular:\n return {\n id,\n name: 'Angular',\n languages: ['typescript'],\n detectionFiles: ['angular.json'],\n };\n case Framework.SpringBoot:\n return {\n id,\n name: 'Spring Boot',\n languages: ['java', 'kotlin'],\n detectionFiles: ['pom.xml', 'build.gradle', 'build.gradle.kts'],\n languageDetection: {\n kotlin: ['src/main/kotlin', 'build.gradle.kts'],\n java: ['src/main/java'],\n },\n };\n case Framework.Android:\n return {\n id,\n name: 'Android',\n languages: ['kotlin', 'java'],\n detectionFiles: [\n 'build.gradle',\n 'build.gradle.kts',\n 'AndroidManifest.xml',\n ],\n languageDetection: {\n kotlin: ['src/main/kotlin', 'build.gradle.kts'],\n java: ['src/main/java'],\n },\n };\n case Framework.iOS:\n return {\n id,\n name: 'iOS (Swift/SwiftUI)',\n languages: ['swift'],\n detectionFiles: [\n 'Podfile',\n 'Package.swift',\n 'project.pbxproj',\n 'Info.plist',\n ],\n languageDetection: {\n swift: ['.swift'],\n },\n };\n case Framework.Laravel:\n return {\n id,\n name: 'Laravel',\n languages: ['php', 'javascript'],\n detectionFiles: ['composer.json', 'artisan'],\n detectionDependencies: ['laravel/framework'],\n languageDetection: {\n php: ['.php'],\n javascript: ['resources/js', 'vite.config.js'],\n },\n };\n }\n};\n\nexport const SUPPORTED_AGENTS: AgentDefinition[] =\n Object.values(Agent).map(getAgentDefinition);\n\nexport const SUPPORTED_FRAMEWORKS: FrameworkDefinition[] = Object.values(\n Framework,\n).map(getFrameworkDefinition);\n\nexport { SKILL_DETECTION_REGISTRY } from './skills';\nexport type { SkillDetection } from './skills';\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\nimport { z } from 'zod';\nimport {\n Agent,\n BACKEND_FRAMEWORKS,\n COMMON_SKILL_EXCLUDES,\n DEFAULT_REGISTER,\n Framework,\n FrameworkDefinition,\n FRONTEND_REACT_FRAMEWORKS,\n getFrameworkType,\n SKILL_DETECTION_REGISTRY,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\nimport { CategoryConfig, SkillConfig } from '../models/config';\nimport { RegistryMetadata } from '../models/types';\n\nconst SkillConfigSchema = z.object({\n registry: z.string().url(),\n agents: z.array(z.nativeEnum(Agent)).optional(),\n skills: z.record(\n z.string(), // Category name\n z.object({\n ref: z.string().optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n }),\n ),\n custom_overrides: z.array(z.string()).optional(),\n workflows: z.union([z.boolean(), z.array(z.string())]).optional(),\n});\n\n/**\n * Service for managing the `.skillsrc` configuration file.\n * Handles loading, saving, and initial construction of the configuration based on project metadata.\n */\nexport class ConfigService {\n /**\n * Loads and validates the skill configuration from the workspace.\n * @param cwd Current working directory\n * @returns The parsed SkillConfig or null if not found\n * @throws Error if the configuration format is invalid\n */\n async loadConfig(cwd: string = process.cwd()): Promise<SkillConfig | null> {\n const configPath = path.join(cwd, '.skillsrc');\n\n if (!(await fs.pathExists(configPath))) {\n return null;\n }\n\n try {\n const content = await fs.readFile(configPath, 'utf8');\n const rawConfig = yaml.load(content);\n\n // Validate with Zod\n const parsed = SkillConfigSchema.safeParse(rawConfig);\n\n if (!parsed.success) {\n throw new Error(`Invalid .skillsrc format: ${parsed.error.message}`);\n }\n\n return parsed.data as SkillConfig;\n } catch (error) {\n throw new Error(`Failed to load config: ${error}`);\n }\n }\n\n /**\n * Saves the provided configuration to the `.skillsrc` file.\n * @param config The configuration to save\n * @param cwd Current working directory\n */\n async saveConfig(\n config: SkillConfig,\n cwd: string = process.cwd(),\n ): Promise<void> {\n const configPath = path.join(cwd, '.skillsrc');\n await fs.outputFile(configPath, yaml.dump(config));\n }\n\n /**\n * Constructs an initial configuration object based on project analysis.\n * @param framework The primary framework detected\n * @param agents List of enabled AI agents\n * @param registry Registry URL\n * @param metadata Registry metadata for versioning and prefixes\n * @param languages Detected programming languages\n * @param workflows List of workflow names to sync\n * @returns A fresh SkillConfig object\n */\n buildInitialConfig(\n framework: string,\n agents: Agent[],\n registry: string,\n metadata: Partial<RegistryMetadata>,\n languages: string[] = [],\n workflows: string[] = [],\n ): SkillConfig {\n const skills: Record<string, CategoryConfig> = {};\n\n // Add main framework\n skills[framework] = {\n ref: metadata.categories?.[framework]?.version\n ? `${metadata.categories[framework].tag_prefix || ''}${metadata.categories[framework].version}`\n : 'main',\n };\n\n // Specialized Logic: Frontend React-based projects must inherently sync the React category natively.\n if (\n FRONTEND_REACT_FRAMEWORKS.includes(framework as Framework) &&\n metadata.categories?.['react']\n ) {\n skills['react'] = {\n ref: metadata.categories['react'].version\n ? `${metadata.categories['react'].tag_prefix || ''}${metadata.categories['react'].version}`\n : 'main',\n };\n }\n\n // Add associated languages (e.g., typescript, javascript)\n for (const lang of languages) {\n if (metadata.categories?.[lang]) {\n skills[lang] = {\n ref: `${metadata.categories[lang].tag_prefix || ''}${metadata.categories[lang].version}`,\n };\n }\n }\n\n // Add common category if available, with framework-appropriate exclusions\n if (metadata.categories?.['common']) {\n const frameworkType = getFrameworkType(framework);\n const commonExcludes = frameworkType\n ? COMMON_SKILL_EXCLUDES[frameworkType]\n : [];\n\n skills['common'] = {\n ref: `${metadata.categories['common'].tag_prefix || ''}${metadata.categories['common'].version}`,\n ...(commonExcludes.length > 0 && { exclude: commonExcludes }),\n };\n }\n\n // Add database category for backend frameworks\n if (\n BACKEND_FRAMEWORKS.includes(framework as Framework) &&\n metadata.categories?.['database']\n ) {\n skills['database'] = {\n ref: metadata.categories['database'].version\n ? `${metadata.categories['database'].tag_prefix || ''}${metadata.categories['database'].version}`\n : 'main',\n };\n }\n\n return {\n registry,\n agents,\n skills,\n custom_overrides: [],\n workflows: workflows.length > 0 ? workflows : false, // Array if specific, false if empty\n };\n }\n\n /**\n * Identifies sub-skills to exclude based on the absence of their required package dependencies.\n * Scans all categories defined in the config.\n * @param config The current configuration\n * @param projectDeps Current set of project dependencies\n */\n applyDependencyExclusions(\n config: SkillConfig,\n projectDeps: Set<string>,\n cwd: string = process.cwd(),\n ) {\n const depsArray = Array.from(projectDeps);\n\n for (const categoryId in config.skills) {\n const category = config.skills[categoryId];\n const detections = SKILL_DETECTION_REGISTRY[categoryId] || [];\n if (detections.length === 0) continue;\n\n const exclusions = new Set<string>(category.exclude || []);\n\n for (const detection of detections) {\n const hasDeps = this.hasDependency(detection.packages, depsArray);\n const hasDirs = this.hasFiles(detection.files, cwd);\n if (!hasDeps || !hasDirs) {\n exclusions.add(detection.id);\n }\n }\n\n if (exclusions.size > 0) {\n category.exclude = Array.from(exclusions);\n }\n }\n }\n\n /**\n * Automatically re-enables skills that were previously excluded if their dependencies\n * are now present in the project. Scans all categories.\n */\n reconcileDependencies(\n config: SkillConfig,\n projectDeps: Set<string>,\n cwd: string = process.cwd(),\n ): string[] {\n const totalReenabled: string[] = [];\n const allKnownCategories = Object.keys(SKILL_DETECTION_REGISTRY);\n const depsArray = Array.from(projectDeps);\n\n for (const categoryId of allKnownCategories) {\n const hasMetaFramework = Object.keys(config.skills).some((f) =>\n [Framework.Flutter, Framework.ReactNative].includes(f as Framework),\n );\n\n let category = config.skills[categoryId];\n\n // Skip platform-specific categories if a meta-framework is already present\n // unless the category is already active (we still want to reconcile its sub-skills)\n if (\n hasMetaFramework &&\n [Framework.Android, Framework.iOS].includes(categoryId as Framework)\n ) {\n if (!category) continue;\n }\n\n const detections = SKILL_DETECTION_REGISTRY[categoryId] || [];\n if (detections.length === 0) continue;\n\n const isNewCategory = !category;\n if (isNewCategory) {\n // First check if this is a supported framework and we don't have its base dependencies\n const frameworkDef = SUPPORTED_FRAMEWORKS.find(\n (f: FrameworkDefinition) => f.id === categoryId,\n );\n if (frameworkDef) {\n const hasBaseDeps =\n frameworkDef.detectionDependencies &&\n frameworkDef.detectionDependencies.length > 0\n ? this.hasDependency(\n frameworkDef.detectionDependencies,\n depsArray,\n )\n : false;\n\n const hasBaseFiles =\n frameworkDef.detectionFiles &&\n frameworkDef.detectionFiles.length > 0\n ? frameworkDef.detectionFiles.some((file) =>\n fs.existsSync(path.join(cwd, file)),\n )\n : false;\n\n if (!hasBaseDeps && !hasBaseFiles) {\n continue; // Skip enabling this category if its base framework isn't detected\n }\n }\n\n const shouldEnableCategory = detections.some(\n (detection) =>\n this.hasDependency(detection.packages, depsArray) &&\n this.hasFiles(detection.files, cwd),\n );\n\n if (shouldEnableCategory) {\n config.skills[categoryId] = { ref: 'main' };\n category = config.skills[categoryId];\n\n const exclusions = detections\n .filter(\n (d) =>\n !this.hasDependency(d.packages, depsArray) ||\n !this.hasFiles(d.files, cwd),\n )\n .map((d) => d.id);\n\n if (exclusions.length > 0) {\n category.exclude = exclusions;\n }\n totalReenabled.push(categoryId);\n }\n continue;\n }\n\n // Existing category reconciliation\n if (!category.exclude) continue;\n\n const currentExclusions = new Set(category.exclude);\n const reenabled: string[] = [];\n\n for (const detection of detections) {\n if (\n currentExclusions.has(detection.id) &&\n this.hasDependency(detection.packages, depsArray) &&\n this.hasFiles(detection.files, cwd)\n ) {\n currentExclusions.delete(detection.id);\n reenabled.push(`${categoryId}/${detection.id}`);\n }\n }\n\n if (reenabled.length > 0) {\n category.exclude =\n currentExclusions.size > 0\n ? Array.from(currentExclusions)\n : undefined;\n totalReenabled.push(...reenabled);\n }\n }\n\n return totalReenabled;\n }\n\n /**\n * Checks if ANY of the required files exist in the project directory.\n */\n private hasFiles(files: string[] | undefined, cwd: string): boolean {\n if (!files || files.length === 0) return true; // If no files required, assume condition met\n for (const file of files) {\n if (fs.existsSync(path.join(cwd, file))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks if ANY of the required dependencies are found in the project.\n */\n private hasDependency(packages: string[], projectDeps: string[]): boolean {\n if (packages.length === 0) return true; // If no packages are required, condition met\n return projectDeps.some((d) =>\n packages.some((pkg) => {\n const depLower = d.toLowerCase();\n const pkgLower = pkg.toLowerCase();\n\n // Exact match\n if (depLower === pkgLower) return true;\n\n // Skip fuzzy matching for short names to avoid noise\n if (pkg.length <= 3) return false;\n\n // Handle scoped packages: @scope/package matches package\n if (depLower.includes('/') && depLower.split('/').pop() === pkgLower)\n return true;\n\n // Handle framework-prefixed packages (e.g. @nestjs/core, flask-cors)\n // Only match if the package is a standalone word in the dependency name\n const parts = depLower.split(/[-/_]/);\n return parts.includes(pkgLower);\n }),\n );\n }\n\n /**\n * Retrieves the registry URL from configuration or returns the default.\n * @param cwd Current working directory\n */\n async getRegistryUrl(cwd: string = process.cwd()): Promise<string> {\n const config = await this.loadConfig(cwd).catch(() => null);\n return config?.registry || DEFAULT_REGISTER;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport {\n FrameworkDefinition,\n SUPPORTED_AGENTS,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\n\n/**\n * Service for detecting project frameworks, languages, AI agents, and dependencies.\n * It uses a combination of file existence checks and package metadata analysis.\n */\nexport class DetectionService {\n /**\n * Detects supported frameworks based on characteristic files and dependencies.\n * @returns A record of framework IDs and their detection status (boolean)\n */\n async detectFrameworks(): Promise<Record<string, boolean>> {\n const packageDepsMap = await this.readPackageJsonDeps(process.cwd());\n\n const detectionPromises = SUPPORTED_FRAMEWORKS.map(async (framework) => {\n // 1. Check characteristic files in parallel\n const fileChecks = framework.detectionFiles.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const fileResults = await Promise.all(fileChecks);\n let detected = fileResults.some((exists) => exists);\n\n // 2. Check dependencies (if not yet detected)\n if (\n !detected &&\n framework.detectionDependencies &&\n framework.detectionDependencies.length > 0\n ) {\n detected = framework.detectionDependencies.some((dep) =>\n Object.prototype.hasOwnProperty.call(packageDepsMap, dep),\n );\n }\n\n return { id: framework.id, detected };\n });\n\n const results = await Promise.all(detectionPromises);\n return results.reduce(\n (acc, { id, detected }) => ({ ...acc, [id]: detected }),\n {},\n );\n }\n\n /**\n * Detects programming languages associated with a specific framework.\n * @param framework The framework definition to use for detection\n * @returns Array of detected language IDs\n */\n async detectLanguages(framework: FrameworkDefinition): Promise<string[]> {\n if (!framework.languageDetection) {\n return framework.languages;\n }\n\n const languageEntries = Object.entries(\n framework.languageDetection as Record<string, string[]>,\n );\n\n const detectionResults = await Promise.all(\n languageEntries.map(async ([lang, files]) => {\n const fileChecks = files.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const results = await Promise.all(fileChecks);\n return { lang, detected: results.some((exists) => exists) };\n }),\n );\n\n const detectedLanguages = detectionResults\n .filter((r) => r.detected)\n .map((r) => r.lang);\n\n return detectedLanguages.length > 0\n ? detectedLanguages\n : framework.languages;\n }\n\n /**\n * Detects enabled AI agents in the workspace by looking for their configuration files.\n * @returns A record of agent IDs and their detection status (boolean)\n */\n async detectAgents(): Promise<Record<string, boolean>> {\n const detectionPromises = SUPPORTED_AGENTS.map(async (agent) => {\n const fileChecks = agent.detectionFiles.map((file) =>\n fs.pathExists(path.join(process.cwd(), file)),\n );\n const results = await Promise.all(fileChecks);\n return { id: agent.id, detected: results.some((exists) => exists) };\n });\n\n const results = await Promise.all(detectionPromises);\n return results.reduce(\n (acc, { id, detected }) => ({ ...acc, [id]: detected }),\n {},\n );\n }\n\n /**\n * Aggregates project dependencies from various build systems (NPM, Pub, Gradle, Maven).\n * @returns A set of all detected package names/identifiers\n */\n async getProjectDeps(): Promise<Set<string>> {\n const cwd = process.cwd();\n const results = await Promise.all([\n this.parsePackageJson(cwd),\n this.parsePubspecYaml(cwd),\n this.parseGradleDependencies(cwd),\n this.parseVersionCatalogs(cwd),\n this.parseMavenPom(cwd),\n ]);\n\n const combined = new Set<string>();\n for (const set of results) {\n for (const item of set) combined.add(item);\n }\n return combined;\n }\n\n private async parsePackageJson(cwd: string): Promise<Set<string>> {\n const depsMap = await this.readPackageJsonDeps(cwd);\n return new Set(Object.keys(depsMap));\n }\n\n private async readPackageJsonDeps(\n cwd: string,\n ): Promise<Record<string, string>> {\n const packageJsonPath = path.join(cwd, 'package.json');\n if (!(await fs.pathExists(packageJsonPath))) return {};\n\n try {\n const pkg = await fs.readJson(packageJsonPath);\n return {\n ...(pkg.dependencies || {}),\n ...(pkg.devDependencies || {}),\n };\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to read package.json:', error);\n return {};\n }\n }\n\n private async parsePubspecYaml(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const pubspecPath = path.join(cwd, 'pubspec.yaml');\n if (!(await fs.pathExists(pubspecPath))) return set;\n\n try {\n const content = await fs.readFile(pubspecPath, 'utf8');\n const lines = content.split(/\\r?\\n/);\n let currentSection: string | null = null;\n let sectionIndent: number | null = null;\n\n for (const line of lines) {\n const sectionMatch = line.match(\n /^(\\s*)(dependencies|dev_dependencies)\\s*:/,\n );\n if (sectionMatch) {\n currentSection = sectionMatch[2];\n sectionIndent = sectionMatch[1].length;\n continue;\n }\n\n if (!currentSection || sectionIndent === null) continue;\n const entryMatch = line.match(/^(\\s*)([a-zA-Z0-9_\\-@\\\\/]+)\\s*:/);\n if (!entryMatch) continue;\n\n const indent = entryMatch[1].length;\n const key = entryMatch[2];\n if (indent > sectionIndent && key !== 'sdk' && key !== 'flutter') {\n set.add(key);\n }\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to parse pubspec.yaml:', error);\n }\n return set;\n }\n\n private async parseGradleDependencies(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const gradleRegex =\n /(?:implementation|api|ksp|kapt|annotationProcessor|compileOnly|runtimeOnly)\\s*\\(?\\s*['\"]([^'\":\\s]+)(?::[^'\"]*)?['\"]\\s*\\)?/g;\n\n const scanDir = async (dir: string, depth: number) => {\n if (depth > 2) return; // Reduced depth for performance\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (\n [\n 'node_modules',\n '.git',\n 'build',\n '.gradle',\n 'ios',\n 'macos',\n ].includes(entry.name)\n )\n continue;\n await scanDir(path.join(dir, entry.name), depth + 1);\n } else if (\n entry.name === 'build.gradle' ||\n entry.name === 'build.gradle.kts'\n ) {\n const content = await fs.readFile(\n path.join(dir, entry.name),\n 'utf8',\n );\n let match;\n while ((match = gradleRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n }\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to scan gradle dependencies:', error);\n }\n };\n\n await scanDir(cwd, 0);\n return set;\n }\n\n private async parseVersionCatalogs(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const tomlPaths = [\n path.join(cwd, 'gradle', 'libs.versions.toml'),\n path.join(cwd, 'gradle.libs.versions.toml'),\n ];\n\n for (const tomlPath of tomlPaths) {\n if (!(await fs.pathExists(tomlPath))) continue;\n try {\n const content = await fs.readFile(tomlPath, 'utf8');\n const moduleRegex = /module\\s*=\\s*['\"]([^'\":\\s]+)(?::[^'\"]*)?['\"]/g;\n const groupRegex = /group\\s*=\\s*['\"]([^'\":\\s]+)['\"]/g;\n let match;\n while ((match = moduleRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n while ((match = groupRegex.exec(content)) !== null) {\n set.add(match[1]);\n }\n } catch (error) {\n if (process.env.DEBUG)\n console.debug('Failed to parse version catalogs:', error);\n }\n }\n return set;\n }\n\n private async parseMavenPom(cwd: string): Promise<Set<string>> {\n const set = new Set<string>();\n const pomPath = path.join(cwd, 'pom.xml');\n if (!(await fs.pathExists(pomPath))) return set;\n\n try {\n const content = await fs.readFile(pomPath, 'utf8');\n const regex =\n /<dependency>[\\s\\S]*?<artifactId>([^<]+)<\\/artifactId>[\\s\\S]*?<\\/dependency>/g;\n let match;\n while ((match = regex.exec(content)) !== null) {\n set.add(match[1]);\n }\n } catch (error) {\n if (process.env.DEBUG) console.debug('Failed to parse maven pom:', error);\n }\n return set;\n }\n}\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\nimport {\n Agent,\n DEFAULT_WORKFLOWS,\n SUPPORTED_AGENTS,\n SUPPORTED_FRAMEWORKS,\n} from '../constants';\nimport { RegistryMetadata } from '../models/types';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\n\n/**\n * Contextual data gathered during project discovery to inform the initialization prompt.\n */\nexport interface InitContext {\n /** Map of framework IDs and whether they were detected in the workspace */\n frameworkDetection: Record<string, boolean>;\n /** Map of agent IDs and whether they were detected in the workspace */\n agentDetection: Record<string, boolean>;\n}\n/**\n * User responses gathered from the initialization prompt.\n */\nexport interface InitAnswers {\n /** The primary framework ID chosen by the user */\n framework: string;\n /** List of AI agents to enable for the project */\n agents: Agent[];\n /** The URL of the skill registry to use */\n registry: string;\n}\n\n/**\n * Service for orchestrating the project initialization process.\n * Handles environment discovery, prompt choice generation, and initial config creation.\n */\nexport class InitService {\n private detectionService = new DetectionService();\n private configService = new ConfigService();\n\n /**\n * Performs environmental discovery to identify existing frameworks and agents.\n * @returns An InitContext containing detection results\n */\n async getInitializationContext(): Promise<InitContext> {\n const [frameworkDetection, agentDetection] = await Promise.all([\n this.detectionService.detectFrameworks(),\n this.detectionService.detectAgents(),\n ]);\n\n return { frameworkDetection, agentDetection };\n }\n\n /**\n * Transforms the initialization context and registry metadata into choices for the interactive prompt.\n * @param context The discovered initialization context\n * @param supportedCategories List of categories currently supported by the registry\n * @returns Formatted choices and the default framework ID\n */\n getPromptChoices(context: InitContext, supportedCategories: string[]) {\n const frameworkChoices = SUPPORTED_FRAMEWORKS.map((f) => ({\n name: supportedCategories.includes(f.id)\n ? f.name\n : `${f.name} (Coming Soon)`,\n value: f.id,\n }));\n\n const agentChoices = SUPPORTED_AGENTS.map((a) => ({\n name: `${a.name} (${a.path}/)`,\n value: a.id,\n checked: context.agentDetection[a.id] ?? false,\n }));\n\n const defaultFramework =\n SUPPORTED_FRAMEWORKS.find((f) => context.frameworkDetection[f.id])?.id ||\n 'flutter';\n\n return {\n frameworkChoices,\n agentChoices,\n defaultFramework,\n };\n }\n\n /**\n * Orchestrates the construction, validation, and saving of the initial `.skillsrc` configuration.\n * @param answers The user's prompt responses\n * @param metadata Registry metadata for versioning\n * @param cwd Current working directory\n */\n async buildAndSaveConfig(\n answers: InitAnswers,\n metadata: Partial<RegistryMetadata>,\n cwd: string = process.cwd(),\n ) {\n const frameworkId = answers.framework;\n const frameworkDef = SUPPORTED_FRAMEWORKS.find((f) => f.id === frameworkId);\n\n const languages = frameworkDef\n ? await this.detectionService.detectLanguages(frameworkDef)\n : [];\n\n const includeWorkflows = answers.agents.includes(Agent.Antigravity);\n\n const config = this.configService.buildInitialConfig(\n frameworkId,\n answers.agents,\n answers.registry,\n metadata,\n languages,\n includeWorkflows ? DEFAULT_WORKFLOWS : [],\n );\n\n const projectDeps = await this.detectionService.getProjectDeps();\n this.configService.applyDependencyExclusions(config, projectDeps);\n this.configService.reconcileDependencies(config, projectDeps);\n\n const commentHeader = `# Auto-detected configuration generated by agent-skills-standard init\n#\n# Presence in 'skills' list = Active. To disable a skill, remove it from the list.\n# 'exclude': IDs of sub-skills to skip during sync (auto-populated with undetected skills).\n# 'custom_overrides': IDs of skills to PROTECT. Use this if you have modified a standard \n# skill locally and don't want the CLI to overwrite it.\n#\n# Run 'ags list-skills' to view all available skills.\n#\n# TIP: For Jira/Zephyr automation and requirement analysis, manually add:\n# skills:\n# quality-engineering: { ref: quality-engineering-v1.0.0 }\n#\n`;\n const configPath = path.join(cwd, '.skillsrc');\n await fs.outputFile(configPath, commentHeader + yaml.dump(config));\n }\n}\n","import fetch from 'cross-fetch';\nimport pc from 'picocolors';\nimport { GitHubTreeResponse } from '../models/types';\n\n/**\n * Service for interacting with the GitHub API and fetching raw file content.\n * Handles repository tree discovery, file downloads, and URL parsing.\n */\nexport class GithubService {\n private baseUrl = 'https://api.github.com';\n private rawBaseUrl = 'https://raw.githubusercontent.com';\n\n constructor(private token?: string) {}\n\n private get headers() {\n const h: Record<string, string> = {\n Accept: 'application/vnd.github.v3+json',\n };\n if (this.token) {\n h.Authorization = `token ${this.token}`;\n }\n return h;\n }\n\n /**\n * Fetches the recursive Git tree for a repository.\n * @param owner Repository owner\n * @param repo Repository name\n * @param ref Git reference (branch, tag, or commit SHA)\n * @returns The tree data or null if not found\n */\n async getRepoTree(\n owner: string,\n repo: string,\n ref: string,\n ): Promise<GitHubTreeResponse | null> {\n const url = `${this.baseUrl}/repos/${owner}/${repo}/git/trees/${ref}?recursive=1`;\n try {\n const res = await fetch(url, { headers: this.headers });\n if (!res.ok) {\n if (res.status === 404) return null;\n throw new Error(`GitHub API Error: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as GitHubTreeResponse;\n } catch (error) {\n console.error(pc.red(`Failed to fetch repo tree: ${error}`));\n return null;\n }\n }\n\n /**\n * Fetches the raw content of a file from GitHub using raw.githubusercontent.com.\n * @param owner Repository owner\n * @param repo Repository name\n * @param ref Git reference\n * @param path Path to the file\n * @returns File content as string or null if not found\n */\n async getRawFile(\n owner: string,\n repo: string,\n ref: string,\n path: string,\n ): Promise<string | null> {\n const url = `${this.rawBaseUrl}/${owner}/${repo}/${ref}/${path}`;\n try {\n const res = await fetch(url);\n if (!res.ok) return null;\n return await res.text();\n } catch (error) {\n console.error(pc.red(`Failed to fetch file ${path}: ${error}`));\n return null;\n }\n }\n\n /**\n * Retrieves the latest release tag name for a repository.\n * @param owner Repository owner\n * @param repo Repository name\n */\n async getLatestReleaseTag(\n owner: string,\n repo: string,\n ): Promise<string | null> {\n try {\n const res = await fetch(\n `${this.baseUrl}/repos/${owner}/${repo}/releases/latest`,\n {\n headers: this.headers,\n },\n );\n if (!res.ok) return null;\n const data = (await res.json()) as { tag_name: string };\n return data.tag_name;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetches basic repository information, such as the default branch.\n * @param owner Repository owner\n * @param repo Repository name\n */\n async getRepoInfo(\n owner: string,\n repo: string,\n ): Promise<{ default_branch: string } | null> {\n const url = `${this.baseUrl}/repos/${owner}/${repo}`;\n try {\n const res = await fetch(url, { headers: this.headers });\n if (!res.ok) return null;\n return (await res.json()) as { default_branch: string };\n } catch (error) {\n console.error(pc.red(`Failed to fetch repo info: ${error}`));\n return null;\n }\n }\n\n /**\n * Downloads multiple files concurrently with a limit.\n */\n async downloadFilesConcurrent(\n tasks: { owner: string; repo: string; ref: string; path: string }[],\n concurrency: number = 10,\n ): Promise<{ path: string; content: string }[]> {\n const results: { path: string; content: string }[] = [];\n const pool = [...tasks];\n const executing: Promise<void>[] = [];\n\n const worker = async () => {\n while (pool.length > 0) {\n const task = pool.shift();\n if (!task) break;\n\n const content = await this.getRawFile(\n task.owner,\n task.repo,\n task.ref,\n task.path,\n );\n if (content !== null) {\n results.push({ path: task.path, content });\n }\n }\n };\n\n // Spawn workers\n for (let i = 0; i < Math.min(concurrency, tasks.length); i++) {\n executing.push(worker());\n }\n\n await Promise.all(executing);\n return results;\n }\n\n /**\n * Parses a GitHub URL into owner and repository name.\n * @param url The GitHub URL to parse\n * @returns Object containing owner and repo, or null if invalid\n */\n static parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const m = url.match(/github\\.com\\/([^/]+)\\/([^/]+)/i);\n if (!m) return null;\n return { owner: m[1], repo: m[2].replace(/\\.git$/, '') };\n }\n}\n","import path from 'path';\nimport { GitHubTreeItem, RegistryMetadata } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service for discovering and querying the skill registry (repository).\n * It identifies available categories, metadata, and framework-specific skills.\n */\nexport class RegistryService {\n private githubService: GithubService;\n\n constructor() {\n this.githubService = new GithubService(process.env.GITHUB_TOKEN);\n }\n\n /**\n * Discovers the registry structure by scanning the repository tree.\n * Identifies available categories, global metadata, and workflows.\n * @param registryUrl The GitHub URL of the registry\n * @returns Discovered registry components\n */\n async discoverRegistry(registryUrl: string): Promise<{\n categories: string[];\n metadata: Partial<RegistryMetadata>;\n workflows: string[];\n }> {\n let categories: string[] = ['flutter', 'dart'];\n let metadata: Partial<RegistryMetadata> = {};\n\n try {\n const parsed = GithubService.parseGitHubUrl(registryUrl);\n if (parsed) {\n let branch = 'main';\n const repoInfo = await this.githubService.getRepoInfo(\n parsed.owner,\n parsed.repo,\n );\n if (repoInfo && repoInfo.default_branch) {\n branch = repoInfo.default_branch;\n }\n\n const treeResult = await this.githubService.getRepoTree(\n parsed.owner,\n parsed.repo,\n branch,\n );\n\n if (treeResult && Array.isArray(treeResult.tree)) {\n const allFiles = treeResult.tree || [];\n const foundCategories = new Set<string>();\n allFiles.forEach((f: GitHubTreeItem) => {\n if (f.path.startsWith('skills/') && f.type === 'tree') {\n const parts = f.path.split('/');\n if (parts.length === 2) foundCategories.add(parts[1]);\n }\n });\n if (foundCategories.size > 0)\n categories = Array.from(foundCategories);\n\n const workflows = allFiles\n .filter(\n (f) =>\n f.path.startsWith('.agent/workflows/') &&\n f.path.endsWith('.md'),\n )\n .map((f) => path.basename(f.path, '.md'));\n\n const metaContent = await this.githubService.getRawFile(\n parsed.owner,\n parsed.repo,\n branch,\n 'skills/metadata.json',\n );\n if (metaContent) {\n metadata = JSON.parse(metaContent) as RegistryMetadata;\n }\n\n return { categories, metadata, workflows };\n }\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`[RegistryService] Registry discovery failed: ${error}`);\n }\n }\n\n return { categories, metadata, workflows: [] };\n }\n\n /**\n * Fetches a list of available skill folders for a specific framework.\n * @param registryUrl The GitHub URL of the registry\n * @param framework The framework ID to query\n * @returns List of skill folder names\n */\n async getFrameworkSkills(\n registryUrl: string,\n framework: string,\n ): Promise<string[]> {\n try {\n const parsed = GithubService.parseGitHubUrl(registryUrl);\n if (!parsed) return [];\n\n const treeResult = await this.githubService.getRepoTree(\n parsed.owner,\n parsed.repo,\n 'main',\n );\n\n if (!treeResult || !Array.isArray(treeResult.tree)) return [];\n\n return Array.from(\n new Set(\n treeResult.tree\n .filter((f: GitHubTreeItem) =>\n f.path.startsWith(`skills/${framework}/`),\n )\n .map((f: GitHubTreeItem) => f.path.split('/')[2])\n .filter(Boolean),\n ),\n );\n } catch {\n return [];\n }\n }\n}\n","import fs from 'fs-extra';\nimport inquirer from 'inquirer';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { DEFAULT_REGISTER } from '../constants';\nimport { InitAnswers, InitService } from '../services/InitService';\nimport { RegistryService } from '../services/RegistryService';\n\n/**\n * Command for initializing the agent-skills-standard configuration in a project.\n * It guides the user through environment detection and creates the `.skillsrc` file.\n */\nexport class InitCommand {\n private initService: InitService;\n private registryService: RegistryService;\n\n constructor(initService?: InitService, registryService?: RegistryService) {\n this.initService = initService || new InitService();\n this.registryService = registryService || new RegistryService();\n }\n\n /**\n * Executes the initialization flow.\n * Checks for existing config, discovers the environment, prompts the user, and saves the configuration.\n */\n async run() {\n const configPath = path.join(process.cwd(), '.skillsrc');\n\n // 1. Check for existing config\n if (await fs.pathExists(configPath)) {\n const { overwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'overwrite',\n message: '.skillsrc already exists. Do you want to overwrite it?',\n default: false,\n },\n ]);\n if (!overwrite) {\n console.log(pc.yellow('Aborted.'));\n return;\n }\n }\n\n // 2. Gather context data\n const context = await this.initService.getInitializationContext();\n const { categories, metadata } =\n await this.registryService.discoverRegistry(DEFAULT_REGISTER);\n\n // 3. Prepare Choices\n const { frameworkChoices, agentChoices, defaultFramework } =\n this.initService.getPromptChoices(context, categories);\n\n // 4. Prompt User\n const answers = await inquirer.prompt<InitAnswers>([\n {\n type: 'list',\n name: 'framework',\n message: 'Select Framework:',\n choices: frameworkChoices,\n default: defaultFramework,\n },\n {\n type: 'checkbox',\n name: 'agents',\n message: 'Select AI Agents you use:',\n choices: agentChoices,\n },\n {\n type: 'input',\n name: 'registry',\n message: 'Skills Registry URL:',\n default: DEFAULT_REGISTER,\n },\n ]);\n\n // 5. Build and Save\n await this.initService.buildAndSaveConfig(answers, metadata);\n\n console.log(pc.green('\\n✅ Initialized .skillsrc with your preferences!'));\n console.log(pc.gray(` Selected framework: ${answers.framework}`));\n console.log(\n pc.cyan(\n '\\nNext step: Run `agent-skills-standard sync` to generate rule files.',\n ),\n );\n }\n}\n","import { SKILL_DETECTION_REGISTRY } from '../constants';\nimport { RegistryService } from './RegistryService';\n\n/**\n * Represents a skill with its detection status in the current project.\n */\nexport interface SkillWithStatus {\n /** The name/ID of the skill */\n name: string;\n /**\n * Status of the skill:\n * - detected: Required dependencies found\n * - not-detected: Required dependencies missing\n * - no-rule: No automated detection rule exists for this skill\n */\n status: 'detected' | 'not-detected' | 'no-rule';\n}\n\n/**\n * Service for managing skill status and availability.\n * Maps registry skills to project dependencies to determine detection status.\n */\nexport class SkillService {\n private registryService = new RegistryService();\n\n /**\n * Retrieves a list of skills for a framework with their detection status.\n * @param framework The framework to filter by\n * @param registryUrl The registry URL\n * @param projectDeps Set of detected project dependencies\n * @returns Array of skills with validated status\n */\n async getSkillsWithStatus(\n framework: string,\n registryUrl: string,\n projectDeps: Set<string>,\n ): Promise<SkillWithStatus[]> {\n // 1. Get available skills (Remote + Fallback)\n let skillFolders = await this.registryService.getFrameworkSkills(\n registryUrl,\n framework,\n );\n\n const detectRules = SKILL_DETECTION_REGISTRY[framework] || [];\n\n // Fallback: use detection registry skill ids if remote fetch returned nothing\n if (!skillFolders || skillFolders.length === 0) {\n skillFolders = detectRules.map((s) => s.id);\n }\n\n // 2. Map to Status\n const skills = skillFolders.sort().map((skillName) => {\n const rule = detectRules.find((x) => x.id === skillName);\n\n let status: SkillWithStatus['status'] = 'no-rule';\n if (rule) {\n const isPresent = rule.packages.some((p) =>\n Array.from(projectDeps).some((d) =>\n d.toLowerCase().includes(p.toLowerCase()),\n ),\n );\n status = isPresent ? 'detected' : 'not-detected';\n }\n\n return { name: skillName, status };\n });\n\n return skills;\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { Framework, SUPPORTED_FRAMEWORKS } from '../constants';\nimport { ConfigService } from '../services/ConfigService';\nimport { DetectionService } from '../services/DetectionService';\nimport { SkillService } from '../services/SkillService';\n\n/**\n * Command for listing available skills in the registry.\n * It detects the project's dependencies and identifies which skills have matching rules.\n */\nexport class ListSkillsCommand {\n private configService: ConfigService;\n private detectionService: DetectionService;\n private skillService: SkillService;\n\n constructor(\n configService?: ConfigService,\n detectionService?: DetectionService,\n skillService?: SkillService,\n ) {\n this.configService = configService || new ConfigService();\n this.detectionService = detectionService || new DetectionService();\n this.skillService = skillService || new SkillService();\n }\n\n /**\n * Executes the skill listing flow.\n * Prompts for framework selection, fetches matching skills from the registry, and displays their status.\n */\n async run(options: { framework?: string } = {}) {\n // 1. Get framework choice from user\n let framework = options.framework;\n\n // Validate framework if provided via options\n if (framework) {\n const isSupported = SUPPORTED_FRAMEWORKS.some((f) => f.id === framework);\n if (!isSupported) {\n const validFrameworks = SUPPORTED_FRAMEWORKS.map((f) => f.id).join(\n ', ',\n );\n console.error(\n pc.red(\n `Invalid framework \"${framework}\". Supported frameworks are: ${validFrameworks}.`,\n ),\n );\n process.exit(1);\n }\n }\n\n if (!framework) {\n const choices = SUPPORTED_FRAMEWORKS.map((f) => ({\n name: f.name,\n value: f.id,\n }));\n\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'framework',\n message: 'Select framework to list available skills for:',\n choices,\n default: choices.find((c) => c.value === Framework.Flutter)?.value,\n },\n ]);\n framework = answer.framework;\n }\n\n if (!framework) return;\n\n // 2. Load context\n const projectDeps = await this.detectionService.getProjectDeps();\n const registryUrl = await this.configService.getRegistryUrl();\n\n console.log(pc.green(`\\nAvailable skills for ${framework}:`));\n\n // 3. Fetch skills with status\n const skills = await this.skillService.getSkillsWithStatus(\n framework,\n registryUrl,\n projectDeps,\n );\n\n // 4. Output results\n for (const skill of skills) {\n const mark =\n skill.status === 'no-rule'\n ? pc.yellow('no-rule')\n : skill.status === 'detected'\n ? pc.green('detected')\n : pc.gray('not-detected');\n\n console.log(`- ${skill.name} (${mark})`);\n }\n\n console.log(\n '\\nTip: Use the .skillsrc exclude array to disable/enable sub-skills before running sync.',\n );\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { Agent, getAgentDefinition } from '../constants';\n\n/**\n * Service responsible for bridging native AI agent rule files to AGENTS.md.\n * Creates agent-specific rule files (e.g., .mdc, .instructions.md)\n * in their respective directories.\n */\nexport class AgentBridgeService {\n /**\n * Bridges native agent rule files to AGENTS.md by creating discovery instructions.\n * @param rootDir Project root directory\n * @param agents List of agents to generate rules for\n */\n async bridge(rootDir: string, agents: Agent[]): Promise<void> {\n const fileNameBase = 'agent-skill-standard-rule';\n const commonDescription =\n 'Rule for Agent Skills Standard - Always consult AGENTS.md for consolidated project context and technical triggers.';\n\n for (const agentId of agents) {\n const config = getAgentDefinition(agentId);\n if (!config) continue;\n\n const relativeSkillsPath = path\n .relative(config.ruleFile, config.path)\n .replace(/\\\\/g, '/');\n const prefix = relativeSkillsPath ? `${relativeSkillsPath}/` : '';\n\n const commonBody = [\n '# 🛠 Agent Skills Standard',\n '',\n 'This project uses a modular skills library for specialized engineering tasks.',\n '',\n '> [!IMPORTANT]',\n '> **MANDATORY: At the start of EVERY session, read `AGENTS.md` to load the skill index.**',\n '> Then identify all skills whose triggers match the current task before writing any code.',\n '',\n '## Skill Activation Protocol',\n '',\n '1. **On session start** → Read `AGENTS.md` (skill index with triggers).',\n '2. **On every task** → Check file globs and keywords against the index.',\n '3. **On skill match** → Read the full `SKILL.md` file before acting.',\n '4. **On file write** → Audit against `common/feedback-reporter` skill.',\n '',\n '## Self-Learning Protocol',\n '',\n `At the end of any multi-step task with user corrections, load and run **[common/session-retrospective](${prefix}common/session-retrospective/SKILL.md)** to capture skill gaps and prevent repeat rework.`,\n ].join('\\n');\n\n // SAFETY: Only write if the agent is detected in the project\n // This prevents creating unused directories.\n let detected = false;\n for (const file of config.detectionFiles) {\n if (await fs.pathExists(path.join(rootDir, file))) {\n detected = true;\n break;\n }\n }\n\n if (!detected) continue;\n\n const ruleFilePath = path.join(\n rootDir,\n config.ruleFile,\n config.ruleFileName || `${fileNameBase}${config.ruleExtension}`,\n );\n\n // Ensure directory exists (e.g. .cursor/rules inside .cursor)\n await fs.ensureDir(path.dirname(ruleFilePath));\n\n let content = '';\n\n switch (config.frontmatterStyle) {\n case 'cursor':\n content += `---\\ndescription: ${commonDescription}\\nglobs: [\"**/*\"]\\nalwaysApply: true\\n---\\n\\n`;\n break;\n case 'copilot':\n content += `---\\ndescription: ${commonDescription}\\napplyTo: \"**/*\"\\n---\\n\\n`;\n break;\n case 'none':\n // No frontmatter\n break;\n }\n\n content += commonBody;\n\n await fs.outputFile(ruleFilePath, content);\n }\n }\n}\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\n\n/**\n * Metadata structure for a skill, extracted from the frontmatter and content of a SKILL.md file.\n */\nexport interface SkillMetadata {\n /** The human-readable name of the skill. */\n name: string;\n /** A brief summary of what the skill covers. */\n description: string;\n /** The priority level (e.g., P0, P1) determining its critical importance. */\n priority: string;\n /** Trigger conditions for when this skill should be activated. */\n triggers: {\n /** Glob patterns of files that trigger this skill. */\n files?: string[];\n /** List of keywords that trigger this skill. */\n keywords?: string[];\n /** Other skill IDs that, when active, also trigger this skill. */\n composite?: string[];\n /** Patterns to explicitly exclude from triggering this skill. */\n exclude?: string[];\n };\n}\n\n/**\n * Service for generating the Agent Skills Index in markdown format.\n * It handles parsing skill metadata and structuring the markdown document.\n *\n * Composite rules are registry-owned: loaded from `skills/metadata.json` at\n * index-generation time. Adding a new foundational skill or pattern requires\n * only a change to `metadata.json` — no CLI source edit or release needed.\n *\n * Injection and bridging are handled by MarkdownUtils and AgentBridgeService respectively.\n */\nexport class IndexGeneratorService {\n /**\n * Loads foundational composite rules from the registry's metadata.json.\n * Falls back to an empty map if the file is missing or malformed.\n */\n private async loadFoundationalRules(\n baseDir: string,\n ): Promise<Record<string, string[]>> {\n try {\n const metaPath = path.join(baseDir, 'metadata.json');\n const raw = await fs.readFile(metaPath, 'utf8');\n const parsed = JSON.parse(raw) as {\n foundational_composite_rules?: Record<string, string[]>;\n };\n return parsed.foundational_composite_rules ?? {};\n } catch {\n return {};\n }\n }\n /**\n * Generates a markdown index of available skills across multiple categories.\n * @param baseDir The base directory containing categories and skills\n * @param frameworks List of framework categories to include in the index\n * @returns A formatted markdown string representing the index\n */\n async generate(baseDir: string): Promise<string> {\n const entries = new Set<string>();\n const foundationalRules = await this.loadFoundationalRules(baseDir);\n\n if (!(await fs.pathExists(baseDir))) return this.assembleIndex([]);\n\n const categories = await fs.readdir(baseDir);\n\n for (const category of categories) {\n // Skip hidden directories (like .cursor, .agent, etc.)\n if (category.startsWith('.')) continue;\n\n const categoryPath = path.join(baseDir, category);\n if (!(await fs.stat(categoryPath)).isDirectory()) continue;\n\n const skills = await fs.readdir(categoryPath);\n for (const skill of skills) {\n const skillPath = path.join(categoryPath, skill, 'SKILL.md');\n if (!(await fs.pathExists(skillPath))) continue;\n\n const metadata = await this.parseSkill(skillPath);\n if (metadata) {\n const entry = this.formatEntry(\n category,\n skill,\n metadata,\n foundationalRules,\n );\n entries.add(entry);\n }\n }\n }\n\n return this.assembleIndex(Array.from(entries));\n }\n\n /**\n * Assembles the full index markdown including headers and Zero-Trust rules.\n * @param entries List of formatted skill entries\n * @param format The format of the entries ('detailed' or 'compact')\n * @returns Complete markdown index string\n */\n public assembleIndex(entries: string[]): string {\n const header = [\n '# Agent Skills Index',\n '',\n '> [!IMPORTANT]',\n '> **Prefer retrieval-led reasoning over pre-training-led reasoning.**',\n '> Before writing any code, you MUST CHECK if a relevant skill exists in the index below.',\n '> If a skill matches your task, READ the file using `view_file`.',\n '',\n '## **Rule Zero: Zero-Trust Engineering**',\n '',\n '- **Skill Authority:** Loaded skills always override existing code patterns.',\n '- **Audit Before Write:** Audit every file write against the `common/feedback-reporter` skill.',\n '',\n '## **Reading This Index**',\n '',\n 'Each entry lists `(triggers: ...)` conditions. Three trigger types:',\n '- **File globs** (`**/*.ts`) — activate when working with matching files.',\n '- **Keywords** (`auth`, `refactor`) — activate when these appear in the task.',\n '- **Composite** (`+other/skill`) — activate THIS skill whenever `other/skill` is also active. Used by foundational skills to co-load with their framework peers automatically.',\n '',\n ].join('\\n');\n\n return `${header}\\n${entries.join('\\n')}\\n`;\n }\n\n private async parseSkill(skillPath: string): Promise<SkillMetadata | null> {\n try {\n const content = await fs.readFile(skillPath, 'utf8');\n const frontmatterMatch = content.match(\n /^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/,\n );\n\n if (!frontmatterMatch) return null;\n\n const fm = yaml.load(frontmatterMatch[1]) as unknown as {\n name?: string;\n description?: string;\n metadata?: {\n triggers?: {\n files?: string[];\n keywords?: string[];\n composite?: string[];\n exclude?: string[];\n };\n };\n };\n const body = frontmatterMatch[2];\n\n const priorityMatch = body.match(/## \\*\\*Priority:\\s*([^*]+)\\*\\*/);\n const priority = priorityMatch ? priorityMatch[1].trim() : 'P1';\n\n return {\n name: fm.name || '',\n description: fm.description || '',\n priority,\n triggers:\n (fm.metadata?.triggers as {\n files?: string[];\n keywords?: string[];\n composite?: string[];\n exclude?: string[];\n }) || {},\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Derives foundational composite IDs for a skill based on registry-owned naming rules.\n * Only applies to non-common skills. Deduplicates against explicit composites.\n */\n private deriveFoundationalComposites(\n category: string,\n skill: string,\n explicitComposites: string[],\n rules: Record<string, string[]>,\n ): string[] {\n if (category === 'common') return [];\n const derived: string[] = [];\n for (const [foundational, patterns] of Object.entries(rules)) {\n const matches = patterns.some((p) => skill.includes(p));\n if (matches && !explicitComposites.includes(foundational)) {\n derived.push(foundational);\n }\n }\n return derived;\n }\n\n private formatEntry(\n category: string,\n skill: string,\n metadata: SkillMetadata,\n foundationalRules: Record<string, string[]> = {},\n ): string {\n const id = `${category}/${skill}`;\n const prefix = metadata.priority.startsWith('P0') ? '🚨 ' : '';\n\n const explicitComposites = metadata.triggers.composite || [];\n const autoComposites = this.deriveFoundationalComposites(\n category,\n skill,\n explicitComposites,\n foundationalRules,\n );\n const allComposites = [...explicitComposites, ...autoComposites];\n\n const triggers = [\n ...(metadata.triggers.files || []),\n ...(metadata.triggers.keywords || []),\n ...(allComposites.length ? allComposites.map((c) => `+${c}`) : []),\n ...(metadata.triggers.exclude\n ? metadata.triggers.exclude.map((e) => `!${e}`)\n : []),\n ].join(', ');\n\n const triggerText = triggers ? ` (triggers: ${triggers})` : '';\n\n // Format: - **[category/skill]**: 🚨 Description (triggers: file.ts, keyword, +composite, !exclude)\n const content = `${prefix}${metadata.description || ''}`.trim();\n return `- **[${id}]**: ${content}${triggerText}`;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * Utility functions for manipulating markdown content\n */\nexport class MarkdownUtils {\n /**\n * Injects the generated index into target documentation files (e.g., AGENTS.md).\n * It uses HTML comments as markers for safe injection and replacement.\n * @param rootDir Project root directory\n * @param targets Array of target file names\n * @param indexContent The markdown content to inject\n */\n static async injectIndex(\n rootDir: string,\n targets: string[],\n indexContent: string,\n ): Promise<void> {\n for (const target of targets) {\n const targetPath = path.join(rootDir, target);\n let content = '';\n\n if (await fs.pathExists(targetPath)) {\n content = await fs.readFile(targetPath, 'utf8');\n const markerStart = '<!-- SKILLS_INDEX_START -->';\n const markerEnd = '<!-- SKILLS_INDEX_END -->';\n\n const startIndex = content.indexOf(markerStart);\n const endIndex = content.indexOf(markerEnd);\n\n if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {\n // Both markers exist and are in the correct order\n const preMarker = content.substring(\n 0,\n startIndex + markerStart.length,\n );\n const postMarker = content.substring(endIndex);\n content = `${preMarker}\\n${indexContent}\\n${postMarker}`;\n } else if (startIndex !== -1 || endIndex !== -1) {\n // One of the markers is missing or they are out of order\n content = content.replace(markerStart, '').replace(markerEnd, '');\n content =\n content.trimEnd() +\n `\\n\\n${markerStart}\\n${indexContent}\\n${markerEnd}\\n`;\n } else {\n // No markers found\n content =\n content.trimEnd() +\n `\\n\\n${markerStart}\\n${indexContent}\\n${markerEnd}\\n`;\n }\n } else {\n content = `<!-- SKILLS_INDEX_START -->\\n${indexContent}\\n<!-- SKILLS_INDEX_END -->\\n`;\n }\n\n await fs.outputFile(targetPath, content);\n }\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { Agent, DEFAULT_WORKFLOWS, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig, SkillEntry } from '../models/config';\nimport {\n CollectedSkill,\n GitHubTreeItem,\n RegistryMetadata,\n} from '../models/types';\nimport { AgentBridgeService } from './AgentBridgeService';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\nimport { GithubService } from './GithubService';\nimport { IndexGeneratorService } from './IndexGeneratorService';\nimport { MarkdownUtils } from './utils/MarkdownUtils';\n\n/**\n * Service responsible for synchronizing agent skills and workflows from a remote registry\n * to the local workspace. It handles dependency reconciliation, folder identification,\n * and writing files to appropriate agent search paths.\n */\nexport class SyncService {\n private configService = new ConfigService();\n private detectionService = new DetectionService();\n private githubService = new GithubService(process.env.GITHUB_TOKEN);\n\n /**\n * Reconciles configuration based on detected project dependencies.\n * Returns true if the configuration was changed and saved.\n */\n async reconcileConfig(\n config: SkillConfig,\n projectDeps: Set<string>,\n ): Promise<boolean> {\n const reenabled = this.configService.reconcileDependencies(\n config,\n projectDeps,\n );\n const configChanged = reenabled.length > 0;\n\n if (configChanged) {\n console.log(\n pc.yellow(\n `✨ Dynamic Re-detection: Re-enabling [${reenabled.join(', ')}].`,\n ),\n );\n }\n\n return configChanged;\n }\n\n /**\n * Reconciles workflows by discovering new ones in the registry and adding them to the config.\n */\n async reconcileWorkflows(config: SkillConfig): Promise<boolean> {\n if (config.workflows === false) return false;\n\n // Only reconcile workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return false;\n }\n\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return false;\n\n const { owner, repo } = githubMatch;\n const ref =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) return false;\n\n const availableWorkflows = treeData.tree\n .filter(\n (f) => f.path.startsWith('.agent/workflows/') && f.path.endsWith('.md'),\n )\n .map((f) => path.basename(f.path, '.md'));\n\n if (availableWorkflows.length === 0) return false;\n\n let changed = false;\n\n if (Array.isArray(config.workflows)) {\n // If workflows is an array, we respect the user's explicit list.\n // We automatically add new default workflows discovered in the registry.\n const currentWorkflows = config.workflows as string[];\n const newWorkflows = availableWorkflows.filter(\n (wf) =>\n !currentWorkflows.includes(wf) && DEFAULT_WORKFLOWS.includes(wf),\n );\n\n if (newWorkflows.length > 0) {\n config.workflows = [...currentWorkflows, ...newWorkflows];\n console.log(\n pc.yellow(\n `✨ Workflows Discovered: Adding [${newWorkflows.join(', ')}] to .skillsrc.`,\n ),\n );\n changed = true;\n }\n } else if (config.workflows === undefined || config.workflows === true) {\n const agents = await this.resolveTargetAgents(config);\n if (agents.includes(Agent.Antigravity)) {\n const defaultWorkflows = availableWorkflows.filter((wf) =>\n DEFAULT_WORKFLOWS.includes(wf),\n );\n config.workflows = defaultWorkflows;\n console.log(\n pc.yellow(\n `✨ Workflows Initialized: Adding [${defaultWorkflows.join(', ')}] to .skillsrc.`,\n ),\n );\n changed = true;\n }\n }\n\n return changed;\n }\n\n /**\n * Assembles skills from the remote registry based on provided categories and configuration.\n */\n async assembleSkills(\n categories: string[],\n config: SkillConfig,\n ): Promise<CollectedSkill[]> {\n const collected: CollectedSkill[] = [];\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n\n if (!githubMatch) {\n console.log(pc.red('Error: Only GitHub registries supported.'));\n return [];\n }\n\n const { owner, repo } = githubMatch;\n\n for (const category of categories) {\n const catConfig = config.skills[category];\n const ref = catConfig.ref || 'main';\n\n console.log(pc.gray(` - Discovering ${category} (${ref})...`));\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) {\n console.log(pc.red(` ❌ Failed to fetch ${category}@${ref}.`));\n continue;\n }\n\n const foldersToSync = this.identifyFoldersToSync(\n category,\n catConfig,\n treeData.tree,\n );\n\n for (const absOrRelSkill of foldersToSync) {\n const skill = await this.fetchSkill(\n owner,\n repo,\n ref,\n category,\n absOrRelSkill,\n treeData.tree,\n );\n if (skill) collected.push(skill);\n }\n }\n\n return collected;\n }\n\n /**\n * Writes collected skills to target agent paths.\n */\n async writeSkills(skills: CollectedSkill[], config: SkillConfig) {\n const agents = await this.resolveTargetAgents(config);\n const overrides = config.custom_overrides || [];\n\n for (const agentId of agents) {\n const agentDef = SUPPORTED_AGENTS.find((a) => a.id === agentId);\n if (!agentDef || !agentDef.path) continue;\n\n const basePath = agentDef.path;\n await fs.ensureDir(basePath);\n\n for (const skill of skills) {\n await this.writeSkillForAgent(agentId, skill, overrides, basePath);\n }\n console.log(pc.gray(` - Updated ${basePath}/ (${agentDef.name})`));\n }\n }\n\n private async resolveTargetAgents(config: SkillConfig): Promise<Agent[]> {\n if (config.agents !== undefined) {\n return config.agents;\n }\n\n // Fallback to content-based detection\n const agentMap = await this.detectionService.detectAgents();\n const detectedAgents = Object.entries(agentMap)\n .filter(([, detected]) => detected)\n .map(([id]) => id as Agent);\n\n // If detection failed and config is empty, default to all supported agents\n return detectedAgents.length > 0\n ? detectedAgents\n : SUPPORTED_AGENTS.map((a) => a.id as Agent);\n }\n\n private async writeSkillForAgent(\n agentId: string,\n skill: CollectedSkill,\n overrides: string[],\n basePath: string,\n ) {\n const isKiro = agentId === Agent.Kiro;\n const kiroFolder = `${skill.category}-${skill.skill}`;\n const skillPath = isKiro\n ? path.join(basePath, kiroFolder)\n : path.join(basePath, skill.category, skill.skill);\n\n await fs.ensureDir(skillPath);\n\n for (const fileItem of skill.files) {\n const targetFilePath = path.join(skillPath, fileItem.name);\n\n if (this.isOverridden(targetFilePath, overrides)) {\n console.log(\n pc.yellow(\n ` ⚠️ Skipping overridden: ${this.normalizePath(targetFilePath)}`,\n ),\n );\n continue;\n }\n\n if (!this.isPathSafe(targetFilePath, skillPath)) {\n console.log(\n pc.red(` ❌ Security Error: Invalid path ${fileItem.name}`),\n );\n continue;\n }\n\n let content = fileItem.content;\n if (isKiro && fileItem.name === 'SKILL.md') {\n content = this.transformSkillForKiro(content, skill.category);\n }\n\n await fs.outputFile(targetFilePath, content);\n }\n }\n\n /**\n * Assembles workflows from the remote registry.\n */\n async assembleWorkflows(config: SkillConfig): Promise<CollectedSkill[]> {\n if (!config.workflows) return [];\n\n // Only sync workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return [];\n }\n\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return [];\n\n const { owner, repo } = githubMatch;\n const ref =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n\n console.log(pc.gray(` - Discovering workflows (${ref})...`));\n\n const treeData = await this.githubService.getRepoTree(owner, repo, ref);\n if (!treeData) {\n console.log(pc.red(` ❌ Failed to fetch workflows@${ref}.`));\n return [];\n }\n\n const workflowFiles = treeData.tree.filter((f) => {\n if (!f.path.startsWith('.agent/workflows/') || !f.path.endsWith('.md'))\n return false;\n\n if (typeof config.workflows === 'boolean') return config.workflows;\n if (Array.isArray(config.workflows)) {\n return config.workflows.includes(path.basename(f.path, '.md'));\n }\n return false;\n });\n\n const files = await this.githubService.downloadFilesConcurrent(\n workflowFiles.map((f) => ({ owner, repo, ref, path: f.path })),\n );\n\n if (files.length > 0) {\n console.log(pc.gray(` + Fetched ${files.length} workflows`));\n return [\n {\n category: '.agent',\n skill: 'workflows',\n files: files.map((f) => ({\n name: path.basename(f.path),\n content: f.content,\n })),\n },\n ];\n }\n\n return [];\n }\n\n /**\n * Writes collected workflows to the .agent/workflows directory.\n */\n async writeWorkflows(workflows: CollectedSkill[], config: SkillConfig) {\n if (workflows.length === 0) return;\n\n // Only write workflows if Antigravity agent is enabled\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) {\n return;\n }\n\n const workflowPath = path.join(process.cwd(), '.agent', 'workflows');\n const overrides = config.custom_overrides || [];\n await fs.ensureDir(workflowPath);\n\n for (const wf of workflows) {\n if (wf.skill !== 'workflows') continue;\n\n for (const fileItem of wf.files) {\n const targetFilePath = path.join(workflowPath, fileItem.name);\n\n if (this.isOverridden(targetFilePath, overrides)) {\n console.log(\n pc.yellow(\n ` ⚠️ Skipping overridden: ${this.normalizePath(targetFilePath)}`,\n ),\n );\n continue;\n }\n\n await fs.outputFile(targetFilePath, fileItem.content);\n console.log(pc.gray(` + Wrote ${fileItem.name}`));\n }\n }\n console.log(pc.green(` ✅ Workflows synced to .agent/workflows/`));\n }\n\n /**\n * Automatically applies framework-specific indices to AGENTS.md.\n */\n async applyIndices(config: SkillConfig, agentsOverride?: Agent[]) {\n const agents = await this.resolveTargetAgents({\n ...config,\n agents: agentsOverride ?? config.agents,\n });\n if (agents.length === 0) return;\n\n console.log(pc.cyan('🔍 Updating Agent Skills index...'));\n\n const agentDef = SUPPORTED_AGENTS.find((a) => a.id === agents[0]);\n if (!agentDef) {\n console.log(\n pc.yellow(` ⚠️ Agent definition not found for ${agents[0]}.`),\n );\n return;\n }\n\n try {\n const generator = new IndexGeneratorService();\n const indexContent = await generator.generate(\n path.join(process.cwd(), agentDef.path),\n );\n\n await MarkdownUtils.injectIndex(\n process.cwd(),\n ['AGENTS.md'],\n indexContent,\n );\n\n const bridgeService = new AgentBridgeService();\n await bridgeService.bridge(process.cwd(), agents);\n\n console.log(pc.green(` ✅ AGENTS.md index updated.`));\n } catch (error) {\n console.log(pc.yellow(` ⚠️ Failed to update index: ${error}`));\n }\n }\n\n /**\n * Checks for newer versions of skills in the remote registry.\n */\n async checkForUpdates(\n config: SkillConfig,\n ): Promise<Record<string, string> | null> {\n const githubMatch = GithubService.parseGitHubUrl(config.registry);\n if (!githubMatch) return null;\n\n const { owner, repo } = githubMatch;\n\n try {\n const branch =\n (await this.githubService.getRepoInfo(owner, repo))?.default_branch ||\n 'main';\n const metaContent = await this.githubService.getRawFile(\n owner,\n repo,\n branch,\n 'skills/metadata.json',\n );\n\n if (!metaContent) return null;\n\n const metadata = JSON.parse(metaContent) as RegistryMetadata;\n const updates: Record<string, string> = {};\n\n for (const [category, catConfig] of Object.entries(config.skills)) {\n const remoteMeta = metadata.categories[category];\n if (!remoteMeta?.version) continue;\n\n const latestRef = `${remoteMeta.tag_prefix || ''}${remoteMeta.version}`;\n if (catConfig.ref !== latestRef) {\n updates[category] = latestRef;\n }\n }\n\n return Object.keys(updates).length > 0 ? updates : null;\n } catch (error) {\n if (process.env.DEBUG)\n console.warn(`[SyncService] Update check failed: ${error}`);\n return null;\n }\n }\n\n // --- Helper Methods ---\n\n private identifyFoldersToSync(\n category: string,\n catConfig: SkillEntry,\n tree: GitHubTreeItem[],\n ): string[] {\n const skillFolders = new Set(\n tree\n .filter((f) => f.path.startsWith(`skills/${category}/`))\n .map((f) => f.path.split('/')[2])\n .filter(Boolean),\n );\n\n const folders = Array.from(skillFolders).filter((folder) => {\n if (catConfig.include && !catConfig.include.includes(folder))\n return false;\n if (catConfig.exclude && catConfig.exclude.includes(folder)) return false;\n return true;\n });\n\n if (catConfig.include) {\n catConfig.include\n .filter((i) => i.includes('/'))\n .forEach((absSkill) =>\n this.expandAbsoluteInclude(absSkill, folders, tree),\n );\n }\n\n return folders;\n }\n\n private expandAbsoluteInclude(\n absSkill: string,\n folders: string[],\n tree: GitHubTreeItem[],\n ) {\n const [targetCat, targetSkill] = absSkill.split('/');\n if (!targetCat || !targetSkill) return;\n\n if (targetSkill === '*') {\n const catSkills = new Set(\n tree\n .filter((f) => f.path.startsWith(`skills/${targetCat}/`))\n .map((f) => f.path.split('/')[2])\n .filter(Boolean),\n );\n\n catSkills.forEach((s) => {\n const fullPath = `${targetCat}/${s}`;\n if (!folders.includes(fullPath)) folders.push(fullPath);\n });\n } else if (!folders.includes(absSkill)) {\n if (\n tree.some((f) =>\n f.path.startsWith(`skills/${targetCat}/${targetSkill}/`),\n )\n ) {\n folders.push(absSkill);\n } else {\n console.log(\n pc.yellow(\n ` ⚠️ Absolute include ${absSkill} not found in repository.`,\n ),\n );\n }\n }\n }\n\n private async fetchSkill(\n owner: string,\n repo: string,\n ref: string,\n category: string,\n absOrRelSkill: string,\n tree: GitHubTreeItem[],\n ): Promise<CollectedSkill | null> {\n const [sourceCat, skillName] = absOrRelSkill.includes('/')\n ? absOrRelSkill.split('/')\n : [category, absOrRelSkill];\n\n const prefix = `skills/${sourceCat}/${skillName}/`;\n const skillSourceFiles = tree.filter(\n (f) => f.path.startsWith(prefix) && f.type === 'blob',\n );\n\n const downloadTasks = skillSourceFiles\n .filter((f) => {\n const rel = f.path.replace(prefix, '');\n return rel === 'SKILL.md' || /^(references|scripts|assets)\\//.test(rel);\n })\n .map((f) => ({ owner, repo, ref, path: f.path }));\n\n const files =\n await this.githubService.downloadFilesConcurrent(downloadTasks);\n if (files.length === 0) return null;\n\n console.log(\n pc.gray(\n ` + Fetched ${sourceCat}/${skillName} (${files.length} files)`,\n ),\n );\n\n return {\n category: sourceCat,\n skill: skillName,\n files: files.map((f) => ({\n name: f.path.replace(prefix, ''),\n content: f.content,\n })),\n };\n }\n\n private transformSkillForKiro(content: string, category: string): string {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!frontmatterMatch) return content;\n\n const [fullMatch, frontmatter] = frontmatterMatch;\n const body = content.slice(fullMatch.length);\n\n const name = frontmatter.match(/^name:\\s*(.+)$/m)?.[1].trim() || '';\n const description =\n frontmatter.match(/^description:\\s*(.+)$/m)?.[1].trim() || '';\n const displayName = `${category.charAt(0).toUpperCase() + category.slice(1)} - ${name}`;\n\n return `---\\nname: ${displayName}\\ndescription: ${description}\\n---` + body;\n }\n\n private isOverridden(targetPath: string, overrides: string[]): boolean {\n const rel = this.normalizePath(targetPath);\n return overrides.some((o) => {\n const op = o.replace(/\\\\/g, '/');\n return rel === op || rel.startsWith(`${op.replace(/\\/$/, '')}/`);\n });\n }\n\n private isPathSafe(targetPath: string, skillPath: string): boolean {\n return path.resolve(targetPath).startsWith(path.resolve(skillPath));\n }\n\n private normalizePath(p: string): string {\n return path.relative(process.cwd(), p).replace(/\\\\/g, '/');\n }\n}\n","import inquirer from 'inquirer';\nimport pc from 'picocolors';\nimport { ConfigService } from '../services/ConfigService';\nimport { DetectionService } from '../services/DetectionService';\nimport { SyncService } from '../services/SyncService';\n\n/**\n * Command for synchronizing skills and workflows from the remote registry to the local workspace.\n * It handles configuration re-detection, fetching files, writing to disk, and updating indices.\n */\nexport class SyncCommand {\n private configService: ConfigService;\n private detectionService: DetectionService;\n private syncService: SyncService;\n\n constructor(\n configService?: ConfigService,\n detectionService?: DetectionService,\n syncService?: SyncService,\n ) {\n this.configService = configService || new ConfigService();\n this.detectionService = detectionService || new DetectionService();\n this.syncService = syncService || new SyncService();\n }\n\n /**\n * Executes the synchronization flow.\n * Reconciles dependencies, fetches skills and workflows from the registry, and updates AGENTS.md.\n */\n async run(options: { yes?: boolean } = {}) {\n try {\n // 1. Load Config\n const config = await this.configService.loadConfig();\n if (!config) {\n console.log(pc.red('❌ Error: .skillsrc not found. Run `init` first.'));\n return;\n }\n\n // 2. Dynamic Update Configuration (Re-detection)\n const projectDeps = await this.detectionService.getProjectDeps();\n const skillsChanged = await this.syncService.reconcileConfig(\n config,\n projectDeps,\n );\n const workflowsChanged =\n await this.syncService.reconcileWorkflows(config);\n\n if (skillsChanged || workflowsChanged) {\n await this.configService.saveConfig(config);\n }\n\n // 3. Check for updates\n const updates = await this.syncService.checkForUpdates(config);\n\n if (updates) {\n console.log(pc.yellow('\\n🚀 New skill versions detected:'));\n for (const [cat, ref] of Object.entries(updates)) {\n console.log(\n pc.gray(` - ${cat}: ${config.skills[cat].ref} -> ${ref}`),\n );\n }\n\n let update = options.yes;\n if (update === undefined) {\n if (!process.stdin.isTTY) {\n console.log(\n pc.cyan(\n 'ℹ️ Non-interactive environment detected. Skipping version updates. Use --yes to auto-confirm.',\n ),\n );\n update = false;\n } else {\n const answer = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'update',\n message: 'Do you want to update .skillsrc with these versions?',\n default: true,\n },\n ]);\n update = answer.update;\n }\n }\n\n if (update) {\n for (const [cat, ref] of Object.entries(updates)) {\n config.skills[cat].ref = ref;\n }\n await this.configService.saveConfig(config);\n console.log(pc.green('✅ .skillsrc updated.'));\n } else {\n console.log(\n pc.cyan('ℹ️ Skipping version updates, staying on pinned refs.'),\n );\n }\n }\n\n console.log(pc.cyan(`🚀 Syncing skills from ${config.registry}...`));\n\n // 4. Assemble skills from remote registry\n const enabledCategories = Object.keys(config.skills);\n const skills = await this.syncService.assembleSkills(\n enabledCategories,\n config,\n );\n\n // 4b. Assemble workflows\n const workflows = await this.syncService.assembleWorkflows(config);\n\n // 5. Write skills and workflows to target\n await this.syncService.writeSkills(skills, config);\n await this.syncService.writeWorkflows(workflows, config);\n\n // 6. Automatically apply framework-specific indices to AGENTS.md\n await this.syncService.applyIndices(config, config.agents);\n\n console.log(pc.green('✅ All skills synced successfully!'));\n } catch (error) {\n if (error instanceof Error) {\n console.error(pc.red('❌ Sync failed:'), error.message);\n } else {\n console.error(pc.red('❌ Sync failed:'), String(error));\n }\n }\n }\n}\n","import { execSync } from 'child_process';\nimport pc from 'picocolors';\nimport pkg from '../../package.json';\n\n/**\n * Command for upgrading the `agent-skills-standard` CLI to the latest version.\n * It checks the latest version on npm and performs the upgrade using the detected package manager.\n */\nexport class UpgradeCommand {\n /**\n * Executes the upgrade flow.\n * @param options Command options, including `dryRun` to check for updates without installing.\n */\n async run(options: { dryRun?: boolean }) {\n console.log(pc.cyan('🔍 Checking for updates...'));\n\n const currentVersion = pkg.version;\n let latestVersion: string | null = null;\n\n try {\n latestVersion = execSync('npm view agent-skills-standard version', {\n encoding: 'utf8',\n }).trim();\n } catch {\n console.log(pc.red('❌ Failed to check for updates via npm.'));\n return;\n }\n\n if (!latestVersion) {\n console.log(pc.red('❌ Could not determine latest version.'));\n return;\n }\n\n console.log(pc.gray(` Current version: ${currentVersion}`));\n console.log(pc.gray(` Latest version: ${latestVersion}`));\n\n if (currentVersion === latestVersion) {\n console.log(pc.green('✨ You are already using the latest version!'));\n return;\n }\n\n if (options.dryRun) {\n console.log(\n pc.yellow(\n `🚀 A new version (${latestVersion}) is available! Run without --dry-run to upgrade.`,\n ),\n );\n return;\n }\n\n const pm = this.detectPackageManager();\n const upgradeCmd = this.getUpgradeCommand(pm);\n\n console.log(pc.yellow(`📦 Upgrading to v${latestVersion} using ${pm}...`));\n\n try {\n console.log(pc.gray(` Running: ${upgradeCmd}`));\n\n execSync(upgradeCmd, { stdio: 'inherit' });\n\n console.log(pc.green(`✅ Successfully upgraded to v${latestVersion}!`));\n console.log(\n pc.cyan(\n \"Please restart your terminal if the version doesn't update immediately.\",\n ),\n );\n } catch {\n console.log('\\n' + pc.red('❌ Automatic upgrade failed.'));\n this.printManualInstructions(pm);\n }\n }\n\n private detectPackageManager(): 'npm' | 'pnpm' | 'yarn' {\n const userAgent = process.env.npm_config_user_agent || '';\n if (userAgent.includes('pnpm')) return 'pnpm';\n if (userAgent.includes('yarn')) return 'yarn';\n\n // Fallback: Check for existing binaries\n try {\n execSync('pnpm --version', { stdio: 'ignore' });\n return 'pnpm';\n } catch {\n try {\n execSync('yarn --version', { stdio: 'ignore' });\n return 'yarn';\n } catch {\n return 'npm';\n }\n }\n }\n\n private getUpgradeCommand(pm: 'npm' | 'pnpm' | 'yarn'): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm add -g agent-skills-standard@latest';\n case 'yarn':\n return 'yarn global add agent-skills-standard@latest';\n default:\n return 'npm install -g agent-skills-standard@latest';\n }\n }\n\n private printManualInstructions(pm: 'npm' | 'pnpm' | 'yarn') {\n const isWindows = process.platform === 'win32';\n const sudoPrefix = isWindows ? '' : 'sudo ';\n\n console.log(pc.yellow('Possible reasons:'));\n console.log(pc.gray(' - Permission denied (requires sudo/administrator)'));\n console.log(pc.gray(' - Network connectivity issues'));\n console.log(pc.gray(` - ${pm} is not configured for global installs`));\n\n console.log(\n '\\n' + pc.cyan('👉 Please run the following command manually:'),\n );\n console.log(\n pc.white(pc.bold(` ${sudoPrefix}${this.getUpgradeCommand(pm)}`)),\n );\n\n if (pm !== 'npm') {\n console.log(pc.gray('\\nAlternative (npm):'));\n console.log(\n pc.gray(` ${sudoPrefix}npm install -g agent-skills-standard@latest`),\n );\n }\n\n console.log(pc.gray('\\nOr run via npx (no install required):'));\n console.log(pc.gray(` npx agent-skills-standard@latest sync`));\n }\n}\n","import { execSync } from 'child_process';\nimport fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * Service for handling Git operations within the project.\n * Provides a clean interface for querying changed and untracked files.\n */\nexport class GitService {\n /**\n * Finds the root of the project by looking for .git or pnpm-workspace.yaml.\n */\n findProjectRoot(startDir: string = process.cwd()): string {\n let currentDir = startDir;\n while (currentDir !== path.parse(currentDir).root) {\n if (\n fs.existsSync(path.join(currentDir, 'pnpm-workspace.yaml')) ||\n fs.existsSync(path.join(currentDir, '.git'))\n ) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return startDir;\n }\n\n /**\n * Retrieves a list of files that have changed compared to the base branch or HEAD.\n * Handles both CI (GitHub Actions) and local development environments.\n * @param rootDir The root directory of the repository\n * @returns Array of relative file paths\n */\n getChangedFiles(rootDir: string): string[] {\n try {\n let gitCommand: string;\n\n if (process.env.GITHUB_BASE_REF) {\n // CI environment: Compare against the base branch\n try {\n execSync(\n `git fetch origin ${process.env.GITHUB_BASE_REF} --depth=1`,\n {\n cwd: rootDir,\n stdio: 'ignore',\n },\n );\n } catch {\n // Ignore fetch failures\n }\n gitCommand = `git diff --name-only origin/${process.env.GITHUB_BASE_REF}...HEAD`;\n } else {\n // Local environment: Compare against HEAD\n gitCommand = 'git diff --name-only HEAD';\n }\n\n const output = execSync(gitCommand, { cwd: rootDir, encoding: 'utf8' });\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter((f) => f !== '' && fs.existsSync(path.join(rootDir, f)));\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn('Git failure while getting changed files:', error);\n }\n return [];\n }\n }\n\n /**\n * Retrieves a list of untracked files in the repository.\n * @param rootDir The root directory of the repository\n * @returns Array of relative file paths\n */\n getUntrackedFiles(rootDir: string): string[] {\n try {\n const output = execSync('git ls-files --others --exclude-standard', {\n cwd: rootDir,\n encoding: 'utf8',\n });\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter((f) => f !== '' && fs.existsSync(path.join(rootDir, f)));\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn('Git failure while getting untracked files:', error);\n }\n return [];\n }\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { GitService } from './GitService';\n\n/**\n * Service for discovering skill files within the repository.\n * Handles recursive directory scanning and integration with Git for change detection.\n */\nexport class SkillDiscoveryService {\n private gitService = new GitService();\n\n /**\n * Finds all SKILL.md files in the repository.\n * @param skillsDir The directory to search within\n * @returns Array of absolute paths to skill files\n */\n async findAllSkills(skillsDir: string): Promise<string[]> {\n const skillFiles: string[] = [];\n\n const findRecursive = async (dir: string) => {\n try {\n const items = await fs.readdir(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n try {\n const stat = await fs.stat(fullPath);\n\n if (stat.isDirectory()) {\n await findRecursive(fullPath);\n } else if (item === 'SKILL.md') {\n skillFiles.push(fullPath);\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`Failed to stat path: ${fullPath}`, error);\n }\n }\n }\n } catch (error) {\n if (process.env.DEBUG) {\n console.warn(`Failed to read directory: ${dir}`, error);\n }\n }\n };\n\n if (await fs.pathExists(skillsDir)) {\n await findRecursive(skillsDir);\n }\n\n return skillFiles;\n }\n\n /**\n * Finds skills that have been changed or are untracked in Git.\n * @returns Array of absolute paths to changed skill files\n */\n async findChangedSkills(): Promise<string[]> {\n const rootDir = this.gitService.findProjectRoot();\n const changedRelative = this.gitService.getChangedFiles(rootDir);\n const untrackedRelative = this.gitService.getUntrackedFiles(rootDir);\n\n const isSkillFile = (file: string) =>\n file.startsWith('skills/') && file.endsWith('SKILL.md');\n\n const allChangedAbsolute = [...changedRelative, ...untrackedRelative]\n .filter(isSkillFile)\n .map((file) => path.join(rootDir, file));\n\n // Simple deduplication\n return Array.from(new Set(allChangedAbsolute));\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport { RuleResult, ValidationRule } from './types';\n\n/**\n * Enforces a maximum line count for skill files to ensure token efficiency.\n */\nexport class SizeRule implements ValidationRule {\n name = 'Size Limit';\n constructor(private maxLines: number = 100) {}\n\n async validate(content: string): Promise<RuleResult> {\n const lines = content.split('\\n');\n if (lines.length > this.maxLines) {\n return {\n passed: false,\n errors: [\n `SKILL.md too large (${lines.length} lines > ${this.maxLines} limit)`,\n ],\n warnings: [],\n };\n }\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Validates frontmatter presence and required fields.\n */\nexport class FrontmatterRule implements ValidationRule {\n name = 'Frontmatter';\n\n async validate(content: string): Promise<RuleResult> {\n const result: RuleResult = { passed: true, errors: [], warnings: [] };\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n\n if (!frontmatterMatch) {\n return {\n passed: false,\n errors: ['Missing or invalid frontmatter'],\n warnings: [],\n };\n }\n\n const frontmatter = frontmatterMatch[1];\n\n if (!frontmatter.includes('name:')) {\n result.errors.push('Missing \"name\" field in frontmatter');\n result.passed = false;\n }\n\n if (!frontmatter.includes('description:')) {\n result.errors.push('Missing \"description\" field in frontmatter');\n result.passed = false;\n } else {\n const descMatch = frontmatter.match(/description:\\s*(.+)/);\n if (descMatch && descMatch[1].length > 200) {\n result.errors.push(\n `Description too long (${descMatch[1].length} chars > 200 limit)`,\n );\n result.passed = false;\n }\n }\n\n return result;\n }\n}\n\n/**\n * Recommends imperative mood over conversational style.\n */\nexport class InstructionsStyleRule implements ValidationRule {\n name = 'Instruction Style';\n\n async validate(content: string): Promise<RuleResult> {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n const body = frontmatterMatch ? frontmatterMatch[2] : content;\n const bodyLines = body.split('\\n');\n let isInCodeBlock = false;\n let hasConversationalStyle = false;\n\n const conversationalPatterns =\n /^(?:\\s*[-*+]\\s*|\\s*\\d+\\.\\s*)(?:you should|please|let's|we can|I recommend)/i;\n\n for (const line of bodyLines) {\n if (line.trim().startsWith('```')) {\n isInCodeBlock = !isInCodeBlock;\n continue;\n }\n if (isInCodeBlock) continue;\n\n if (conversationalPatterns.test(line)) {\n hasConversationalStyle = true;\n break;\n }\n }\n\n if (hasConversationalStyle) {\n return {\n passed: true,\n errors: [],\n warnings: [\n 'Consider using imperative mood instead of conversational style in instructions',\n ],\n };\n }\n\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Ensures the mandatory priority section is present.\n */\nexport class PriorityRule implements ValidationRule {\n name = 'Priority Section';\n\n async validate(content: string): Promise<RuleResult> {\n if (!content.includes('## **Priority:')) {\n return {\n passed: false,\n errors: ['Missing priority section'],\n warnings: [],\n };\n }\n return { passed: true, errors: [], warnings: [] };\n }\n}\n\n/**\n * Validates the directory structure surrounding the skill file.\n */\nexport class DirectoryStructureRule implements ValidationRule {\n name = 'Directory Structure';\n\n async validate(_content: string, filePath: string): Promise<RuleResult> {\n const result: RuleResult = { passed: true, errors: [], warnings: [] };\n const skillDir = path.dirname(filePath);\n\n // Check scripts\n const scriptsDir = path.join(skillDir, 'scripts');\n if (await fs.pathExists(scriptsDir)) {\n const scriptFiles = await fs.readdir(scriptsDir);\n for (const file of scriptFiles) {\n if (!['.py', '.js', '.ts', '.sh'].includes(path.extname(file))) {\n result.warnings.push(`Script without standard extension: ${file}`);\n }\n }\n }\n\n // Check references\n const refsDir = path.join(skillDir, 'references');\n if (await fs.pathExists(refsDir)) {\n const refFiles = await fs.readdir(refsDir);\n if (refFiles.filter((f) => f.endsWith('.md')).length === 0) {\n result.warnings.push(\n 'References directory exists but contains no .md files',\n );\n }\n }\n\n return result;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { GitService } from './GitService';\nimport { SkillDiscoveryService } from './SkillDiscoveryService';\nimport {\n DirectoryStructureRule,\n FrontmatterRule,\n InstructionsStyleRule,\n PriorityRule,\n SizeRule,\n} from './validation/rules';\nimport { ValidationRule } from './validation/types';\n\n/**\n * Result of validating a single skill file.\n */\nexport interface SkillValidationResult {\n /** Relative path to the skill file. */\n file: string;\n /** List of validation error messages. */\n errors: string[];\n /** List of validation warning messages. */\n warnings: string[];\n /** Whether the file passed all mandatory validation rules. */\n passed: boolean;\n}\n\n/**\n * Aggregated summary of all validation results.\n */\nexport interface ValidationSummary {\n /** Total number of skills validated. */\n total: number;\n /** Number of skills that passed validation. */\n passed: number;\n /** Number of skills that failed validation. */\n failed: number;\n /** Cumulative number of warnings across all skills. */\n warnings: number;\n}\n\n/**\n * Service for validating skill files (SKILL.md) and repository metadata.\n * Enforces size limits, frontmatter requirements, and imperative instruction style.\n * Uses a Rule Pattern for modular validation.\n */\nexport class SkillValidator {\n private results: SkillValidationResult[] = [];\n private skillDiscovery = new SkillDiscoveryService();\n private gitService = new GitService();\n private rules: ValidationRule[] = [\n new SizeRule(),\n new FrontmatterRule(),\n new InstructionsStyleRule(),\n new PriorityRule(),\n new DirectoryStructureRule(),\n ];\n\n /**\n * Runs the complete validation suite.\n * @param validateAll Whether to validate all skills or just changed ones\n * @returns Exit code (0 for success, 1 for failure)\n */\n async run(validateAll: boolean = false): Promise<number> {\n try {\n const summary = await this.validateAllSkills(validateAll);\n this.printSummary(summary);\n return summary.failed > 0 ? 1 : 0;\n } catch (error) {\n console.error(\n pc.red(\n `❌ Validation error: ${error instanceof Error ? error.stack : error}`,\n ),\n );\n return 1;\n }\n }\n\n /**\n * Validates all identified skill files in the repository.\n * @param validateAll Whether to validate all skills or just changed ones\n * @returns Summary of validation results\n */\n async validateAllSkills(\n validateAll: boolean = false,\n ): Promise<ValidationSummary> {\n const rootDir = this.gitService.findProjectRoot();\n const skillsDir = path.join(rootDir, 'skills');\n\n if (!(await fs.pathExists(skillsDir))) {\n throw new Error(`skills/ directory not found (searched at ${skillsDir})`);\n }\n\n const skillFiles = validateAll\n ? await this.skillDiscovery.findAllSkills(skillsDir)\n : await this.skillDiscovery.findChangedSkills();\n\n console.log(\n pc.blue(\n `🔍 Found ${skillFiles.length} ${validateAll ? '' : 'changed '}skills to validate\\n`,\n ),\n );\n\n for (const skillFile of skillFiles) {\n const result = await this.validateSkill(skillFile);\n this.results.push(result);\n\n if (result.passed) {\n console.log(pc.green(`✅ ${result.file}`));\n result.warnings.forEach((warning) =>\n console.log(pc.yellow(` ⚠️ ${warning}`)),\n );\n } else {\n console.log(pc.red(`❌ ${result.file}`));\n result.errors.forEach((error) => console.log(pc.red(` ❌ ${error}`)));\n }\n }\n\n await this.validateMetadata(rootDir);\n\n return this.generateSummary();\n }\n\n private async validateSkill(\n skillFile: string,\n ): Promise<SkillValidationResult> {\n const rootDir = this.gitService.findProjectRoot();\n const result: SkillValidationResult = {\n file: path.relative(rootDir, skillFile),\n errors: [],\n warnings: [],\n passed: true,\n };\n\n try {\n const content = await fs.readFile(skillFile, 'utf8');\n\n for (const rule of this.rules) {\n const ruleResult = await rule.validate(content, skillFile);\n if (!ruleResult.passed) {\n result.passed = false;\n }\n result.errors.push(...ruleResult.errors);\n result.warnings.push(...ruleResult.warnings);\n }\n } catch (error) {\n result.errors.push(\n `Failed to read or validate file: ${error instanceof Error ? error.message : error}`,\n );\n result.passed = false;\n }\n\n return result;\n }\n\n private async validateMetadata(rootDir: string): Promise<void> {\n const metadataPath = path.join(rootDir, 'skills', 'metadata.json');\n\n try {\n if (!(await fs.pathExists(metadataPath))) {\n throw new Error('skills/metadata.json not found');\n }\n\n const metadata = await fs.readJson(metadataPath);\n if (!metadata.categories) {\n throw new Error('metadata.json missing \"categories\" field');\n }\n\n for (const [category, config] of Object.entries(metadata.categories)) {\n const catConfig = config as { version?: string; tag_prefix?: string };\n\n if (!catConfig.version || !catConfig.tag_prefix) {\n throw new Error(\n `Category \"${category}\" missing required fields (version, tag_prefix) in metadata.json`,\n );\n }\n\n console.log(\n pc.green(\n `✅ Category metadata valid: ${category} (v${catConfig.version}, ${catConfig.tag_prefix})`,\n ),\n );\n }\n } catch (error) {\n throw new Error(\n `Metadata validation failed: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n\n private generateSummary(): ValidationSummary {\n const summary: ValidationSummary = {\n total: this.results.length,\n passed: 0,\n failed: 0,\n warnings: 0,\n };\n\n for (const result of this.results) {\n if (result.passed) {\n summary.passed++;\n } else {\n summary.failed++;\n }\n summary.warnings += result.warnings.length;\n }\n\n return summary;\n }\n\n printSummary(summary: ValidationSummary): void {\n console.log('\\n' + '='.repeat(50));\n console.log(pc.blue('📊 VALIDATION SUMMARY'));\n console.log('='.repeat(50));\n\n console.log(pc.green(`Passed: ${summary.passed}`));\n console.log(pc.red(`Failed: ${summary.failed}`));\n\n if (summary.failed > 0) {\n console.log(\n '\\n' + pc.red('❌ Validation failed! Please fix the errors above.'),\n );\n } else {\n console.log('\\n' + pc.green('✅ All skills passed validation!'));\n\n if (summary.warnings > 0) {\n console.log(\n pc.yellow(\n `⚠️ ${summary.warnings} warnings found. Consider addressing them for better token efficiency.`,\n ),\n );\n }\n }\n }\n}\n","import { SkillValidator } from '../services/SkillValidator';\n\n/**\n * Command for validating the integrity and format of skills in the local directory.\n * Useful for development and CI/CD pipelines to ensure skills follow the standard.\n */\nexport class ValidateCommand {\n /**\n * Executes the validation flow.\n * @param options Command options, including `all` to validate all skills instead of only changed ones.\n */\n async run(options: { all?: boolean } = {}) {\n const validator = new SkillValidator();\n const exitCode = await validator.run(options.all ?? false);\n process.exit(exitCode);\n }\n}\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport dotenv from 'dotenv';\nimport { FeedbackCommand } from './commands/feedback';\nimport { InitCommand } from './commands/init';\nimport { ListSkillsCommand } from './commands/list-skills';\nimport { SyncCommand } from './commands/sync';\nimport { UpgradeCommand } from './commands/upgrade';\nimport { ValidateCommand } from './commands/validate-skills';\n\n// Load .env from current directory (for development and other env vars)\ndotenv.config();\n\nconst program = new Command();\n\nprogram\n .name('agent-skills-standard')\n .description(\n 'A CLI to manage and sync AI agent skills for Cursor, Claude, Copilot, Windsurf, and more.',\n )\n .version('1.9.1');\n\nprogram\n .command('init')\n .description('Initialize a .skillsrc configuration file interactively')\n .action(async () => {\n const init = new InitCommand();\n await init.run();\n });\n\nprogram\n .command('sync')\n .description('Sync skills to AI Agent skill directories')\n .option(\n '-y, --yes',\n 'Automatically confirm interactive prompts (e.g. update versions)',\n )\n .action(async (options) => {\n const sync = new SyncCommand();\n await sync.run(options);\n });\n\nprogram\n .command('list-skills')\n .description('List available framework skills and detection status')\n .option('-f, --framework <framework>', 'The framework to list skills for')\n .action(async (options) => {\n const cmd = new ListSkillsCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('validate')\n .description('Validate skill format and token efficiency standards')\n .option('--all', 'Validate all skills instead of only changed ones')\n .action(async (options) => {\n const cmd = new ValidateCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('feedback')\n .description('Report skill improvement opportunities or AI agent mistakes')\n .option(\n '--skill <skill>',\n 'The skill ID (e.g., flutter/bloc-state-management)',\n )\n .option('--issue <issue>', 'Brief description of the issue')\n .option('--model <model>', 'AI agent model (e.g., Claude 3.5 Sonnet)')\n .option('--context <context>', 'Additional context (e.g., framework version)')\n .option('--suggestion <suggestion>', 'Suggested improvement')\n .option(\n '--skill-instruction <instruction>',\n 'Exact quote from skill that was violated (AI auto-report)',\n )\n .option(\n '--actual-action <action>',\n 'What you actually did instead of following skill (AI auto-report)',\n )\n .option(\n '--decision-reason <reason>',\n 'Why you chose this approach instead (AI auto-report)',\n )\n .option(\n '--loaded-skills <skills>',\n 'Comma-separated list of currently loaded skills (platform-provided)',\n )\n .action(async (options: Record<string, string>) => {\n const cmd = new FeedbackCommand();\n await cmd.run(options);\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade the CLI to the latest version')\n .option('--dry-run', 'Check for updates without installing')\n .action(async (options) => {\n const cmd = new UpgradeCommand();\n await cmd.run(options);\n });\n\nprogram.parse();\n"],"names":["Agent","Framework","z","pkg","results","fetch","path","agents","execSync","Command"],"mappings":";;;;;;;;;;;;AAgCO,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAI3B,YAAgC;AAC9B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAO,MAAsC;AACjD,UAAM,SAAS,KAAK,UAAA;AACpB,QAAI,CAAC,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A;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,sDAAsD,EAClE,OAAO,SAAS,kDAAkD,EAClE,OAAO,OAAO,YAAY;AACzB,QAAM,MAAM,IAAI,gBAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,6DAA6D,EACzE;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,mBAAmB,gCAAgC,EAC1D,OAAO,mBAAmB,0CAA0C,EACpE,OAAO,uBAAuB,8CAA8C,EAC5E,OAAO,6BAA6B,uBAAuB,EAC3D;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,OAAO,YAAoC;AACjD,QAAM,MAAM,IAAI,gBAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QACG,QAAQ,SAAS,EACjB,YAAY,uCAAuC,EACnD,OAAO,aAAa,sCAAsC,EAC1D,OAAO,OAAO,YAAY;AACzB,QAAM,MAAM,IAAI,eAAA;AAChB,QAAM,IAAI,IAAI,OAAO;AACvB,CAAC;AAEH,QAAQ,MAAA;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-skills-standard",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.1",
|
|
4
4
|
"description": "A CLI to manage and sync AI agent skills standard for Cursor, Claude, Copilot, Windsurf, and more.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"license": "MIT",
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"commander": "^11.1.0",
|
|
41
|
+
"cross-fetch": "^4.1.0",
|
|
41
42
|
"dotenv": "^17.2.3",
|
|
42
43
|
"fs-extra": "^11.2.0",
|
|
43
44
|
"inquirer": "^8.2.5",
|