agent-skills-standard 1.10.4 → 2.0.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 +6 -5
- package/dist/index.js +50 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -141,8 +141,9 @@ No. If you have custom rules in <code>.cursorrules</code> or other files, you ca
|
|
|
141
141
|
|
|
142
142
|
### 📜 Benchmark History
|
|
143
143
|
|
|
144
|
-
| Version | Date
|
|
145
|
-
|
|
|
146
|
-
|
|
|
147
|
-
|
|
|
148
|
-
| v1.10.
|
|
144
|
+
| Version | Date | Skills | Avg Tokens | Savings (%) | Report |
|
|
145
|
+
| ------- | ---------- | ------ | ---------- | ----------- | --------------------------------------- |
|
|
146
|
+
| v2.0.1 | 2026-03-30 | 238 | 527 | 86% | [Report](benchmarks/archive/v2.0.1.md) |
|
|
147
|
+
| v2.0.0 | 2026-03-25 | 235 | 523 | 86% | [Report](benchmarks/archive/v2.0.0.md) |
|
|
148
|
+
| v1.10.3 | 2026-03-21 | 234 | 505 | 86% | [Report](benchmarks/archive/v1.10.3.md) |
|
|
149
|
+
| v1.10.1 | 2026-03-16 | 229 | 428 | 88% | [Report](benchmarks/archive/v1.10.1.md) |
|
package/dist/index.js
CHANGED
|
@@ -476,15 +476,22 @@ const COMMON_SKILL_EXCLUDES = {
|
|
|
476
476
|
backend: [
|
|
477
477
|
"common-accessibility",
|
|
478
478
|
"common-mobile-animation",
|
|
479
|
-
"common-mobile-ux-core"
|
|
479
|
+
"common-mobile-ux-core",
|
|
480
|
+
"common-store-changelog",
|
|
481
|
+
"common-ui-design"
|
|
480
482
|
],
|
|
481
483
|
frontend: [
|
|
482
484
|
"common-observability",
|
|
483
485
|
"common-mobile-animation",
|
|
484
486
|
"common-mobile-ux-core",
|
|
485
|
-
"common-
|
|
487
|
+
"common-store-changelog"
|
|
486
488
|
],
|
|
487
|
-
mobile: [
|
|
489
|
+
mobile: [
|
|
490
|
+
"common-accessibility",
|
|
491
|
+
"common-api-design",
|
|
492
|
+
"common-observability",
|
|
493
|
+
"common-system-design"
|
|
494
|
+
]
|
|
488
495
|
};
|
|
489
496
|
function getFrameworkType(framework) {
|
|
490
497
|
if (BACKEND_FRAMEWORKS.includes(framework)) return "backend";
|
|
@@ -497,7 +504,8 @@ const DEFAULT_WORKFLOWS = [
|
|
|
497
504
|
"code-review",
|
|
498
505
|
"codebase-review",
|
|
499
506
|
"plan-feature",
|
|
500
|
-
"skill-benchmark"
|
|
507
|
+
"skill-benchmark",
|
|
508
|
+
"pentest"
|
|
501
509
|
];
|
|
502
510
|
const getAgentDefinition = (id) => {
|
|
503
511
|
switch (id) {
|
|
@@ -1760,6 +1768,13 @@ applyTo: '**/*'
|
|
|
1760
1768
|
}
|
|
1761
1769
|
}
|
|
1762
1770
|
}
|
|
1771
|
+
const INJECTION_PATTERNS = [
|
|
1772
|
+
/ignore\s+(?:all\s+|previous\s+|prior\s+)*(?:instructions?|rules?|guidance)/gi,
|
|
1773
|
+
/you\s+(?:must|should|shall|will)\s+(?:now|immediately)\b/gi,
|
|
1774
|
+
/^(?:system|user|assistant)\s*:/gim,
|
|
1775
|
+
/(?:^|\n)-{3,}(?:\n|$)/g,
|
|
1776
|
+
/<(?:script|iframe|style)[^>]*\s*>[\s\S]*?<\/(?:script|iframe|style)[^>]*\s*>/gi
|
|
1777
|
+
];
|
|
1763
1778
|
class IndexGeneratorService {
|
|
1764
1779
|
/**
|
|
1765
1780
|
* Loads foundational composite rules from the registry's metadata.json.
|
|
@@ -1915,6 +1930,32 @@ ${entries.join("\n")}
|
|
|
1915
1930
|
}
|
|
1916
1931
|
return derived;
|
|
1917
1932
|
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Sanitizes a skill description to prevent indirect prompt injection.
|
|
1935
|
+
* Strips known instruction-hijack patterns and replaces them with [REDACTED].
|
|
1936
|
+
* Logs a stderr warning for every skill that required sanitisation.
|
|
1937
|
+
* @param desc The raw description string from skill frontmatter
|
|
1938
|
+
* @param skillId The skill identifier (category/skill) for log context
|
|
1939
|
+
* @returns Sanitised description safe to embed in AGENTS.md
|
|
1940
|
+
*/
|
|
1941
|
+
sanitizeDescription(desc, skillId = "unknown") {
|
|
1942
|
+
let sanitized = desc;
|
|
1943
|
+
let wasModified = false;
|
|
1944
|
+
for (const pattern of INJECTION_PATTERNS) {
|
|
1945
|
+
if (pattern.test(sanitized)) {
|
|
1946
|
+
wasModified = true;
|
|
1947
|
+
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
1948
|
+
}
|
|
1949
|
+
pattern.lastIndex = 0;
|
|
1950
|
+
}
|
|
1951
|
+
if (wasModified) {
|
|
1952
|
+
process.stderr.write(
|
|
1953
|
+
`[SECURITY] Prompt injection pattern stripped from skill description: ${skillId}
|
|
1954
|
+
`
|
|
1955
|
+
);
|
|
1956
|
+
}
|
|
1957
|
+
return sanitized;
|
|
1958
|
+
}
|
|
1918
1959
|
formatEntry(category, skill, metadata, foundationalRules = {}) {
|
|
1919
1960
|
const id = `${category}/${skill}`;
|
|
1920
1961
|
const prefix = metadata.priority.startsWith("P0") ? "🚨 " : "";
|
|
@@ -1933,7 +1974,7 @@ ${entries.join("\n")}
|
|
|
1933
1974
|
...metadata.triggers.exclude ? metadata.triggers.exclude.map((e) => `!${e}`) : []
|
|
1934
1975
|
].join(", ");
|
|
1935
1976
|
const triggerText = triggers ? ` (triggers: \`${triggers}\`)` : "";
|
|
1936
|
-
let desc = metadata.description || "";
|
|
1977
|
+
let desc = this.sanitizeDescription(metadata.description || "", id);
|
|
1937
1978
|
desc = desc.replace(/\(triggers:\s*`?(.*?)`?\)/g, "(triggers: `$1`)");
|
|
1938
1979
|
const content = `${prefix}${desc}`.trim();
|
|
1939
1980
|
return `- **[${id}]**: ${content}${triggerText}`;
|
|
@@ -2139,7 +2180,8 @@ description: ${description}
|
|
|
2139
2180
|
});
|
|
2140
2181
|
}
|
|
2141
2182
|
isPathSafe(targetPath, skillPath) {
|
|
2142
|
-
|
|
2183
|
+
const resolvedBase = path.resolve(skillPath) + path.sep;
|
|
2184
|
+
return path.resolve(targetPath).startsWith(resolvedBase);
|
|
2143
2185
|
}
|
|
2144
2186
|
normalizePath(p) {
|
|
2145
2187
|
return path.relative(process.cwd(), p).replace(/\\/g, "/");
|
|
@@ -2529,7 +2571,7 @@ class SyncCommand {
|
|
|
2529
2571
|
}
|
|
2530
2572
|
}
|
|
2531
2573
|
}
|
|
2532
|
-
const version = "
|
|
2574
|
+
const version = "2.0.1";
|
|
2533
2575
|
const pkg = {
|
|
2534
2576
|
version
|
|
2535
2577
|
};
|
|
@@ -3047,7 +3089,7 @@ dotenv.config();
|
|
|
3047
3089
|
const program = new commander.Command();
|
|
3048
3090
|
program.name("agent-skills-standard").description(
|
|
3049
3091
|
"A CLI to manage and sync AI agent skills for Cursor, Claude, Copilot, Windsurf, and more."
|
|
3050
|
-
).version("
|
|
3092
|
+
).version("2.0.1");
|
|
3051
3093
|
program.command("init").description("Initialize a .skillsrc configuration file interactively").action(async () => {
|
|
3052
3094
|
const init = new InitCommand();
|
|
3053
3095
|
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/SkillSyncService.ts","../src/services/WorkflowSyncService.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: 'flutter-riverpod-state-management',\n packages: ['flutter_riverpod', 'riverpod'],\n },\n {\n id: 'flutter-bloc-state-management',\n packages: ['flutter_bloc', 'bloc'],\n },\n {\n id: 'flutter-auto-route-navigation',\n packages: ['auto_route'],\n },\n {\n id: 'flutter-go-router-navigation',\n packages: ['go_router'],\n },\n {\n id: 'flutter-getx-navigation',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'flutter-getx-state-management',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'flutter-localization',\n packages: ['easy_localization'],\n },\n {\n id: 'flutter-retrofit-networking',\n packages: ['retrofit'],\n },\n {\n id: 'flutter-dependency-injection',\n packages: ['get_it', 'injectable'],\n },\n ],\n [Framework.NestJS]: [\n {\n id: 'nestjs-caching',\n packages: ['@nestjs/cache-manager', 'cache-manager'],\n },\n {\n id: 'nestjs-database',\n packages: ['@nestjs/typeorm', '@nestjs/prisma', '@nestjs/mongoose'],\n },\n {\n id: 'nestjs-security',\n packages: ['@nestjs/passport', 'passport', 'helmet'],\n },\n ],\n [Framework.Android]: [\n {\n id: 'android-compose',\n packages: ['androidx.compose.ui'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-navigation',\n packages: ['androidx.navigation:navigation-compose'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-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: 'android-di',\n packages: ['hilt-android', 'dagger-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-persistence',\n packages: ['androidx.room:room-runtime'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-networking',\n packages: ['retrofit'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-concurrency',\n packages: ['kotlinx-coroutines-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n ],\n [Framework.iOS]: [\n {\n id: 'ios-networking',\n packages: ['Alamofire', 'Moya'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-dependency-injection',\n packages: ['Swinject', 'Resolver'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-persistence',\n packages: ['Realm', 'CoreData', 'SQLite.swift'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-state-management',\n packages: ['ComposableArchitecture', 'CombineRuntime'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-ui-navigation',\n packages: ['Coordinator', 'Router'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n ],\n [Framework.ReactNative]: [\n {\n id: 'react-native-navigation',\n packages: ['@react-navigation/native'],\n },\n {\n id: 'react-native-state-management',\n packages: ['zustand', '@reduxjs/toolkit'],\n },\n {\n id: 'react-native-deployment',\n packages: ['react-native-code-push', 'expo-updates'],\n },\n {\n id: 'react-native-security',\n packages: ['react-native-keychain', 'react-native-ssl-pinning'],\n },\n {\n id: 'react-native-performance',\n packages: ['react-native-fast-image'],\n },\n ],\n [Framework.Laravel]: [\n {\n id: 'laravel-api',\n packages: ['laravel/sanctum', 'laravel/passport'],\n },\n {\n id: 'laravel-background-processing',\n packages: ['laravel/horizon'],\n },\n {\n id: 'laravel-testing',\n packages: ['pestphp/pest', 'phpunit/phpunit'],\n },\n {\n id: 'laravel-tooling',\n packages: ['laravel/pint', 'laravel/sail'],\n },\n {\n id: 'laravel-database-expert',\n packages: ['laravel/framework'], // Always present, but used for sub-skill mapping\n },\n ],\n [Framework.NextJS]: [\n {\n id: 'nextjs-pages-router',\n packages: [],\n files: ['pages', 'src/pages'],\n },\n {\n id: 'nextjs-server-components',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-server-actions',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-data-fetching',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-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: 'react-styling',\n packages: ['tailwind', 'antd', 'sass', 'styled-components', 'emotion'],\n },\n {\n id: 'react-state-management',\n packages: [\n 'redux',\n '@reduxjs/toolkit',\n 'zustand',\n 'mobx',\n 'recoil',\n 'jotai',\n ],\n },\n {\n id: 'react-testing',\n packages: [\n 'jest',\n 'vitest',\n '@testing-library/react',\n 'cypress',\n 'playwright',\n ],\n },\n ],\n database: [\n {\n id: 'database-postgresql',\n packages: ['pg', 'pgx', 'postgres', 'sequelize', 'typeorm', 'prisma'],\n },\n {\n id: 'database-mongodb',\n packages: ['mongodb', 'mongoose'],\n },\n {\n id: 'database-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: [\n 'common-accessibility',\n 'common-mobile-animation',\n 'common-mobile-ux-core',\n ],\n frontend: [\n 'common-observability',\n 'common-mobile-animation',\n 'common-mobile-ux-core',\n 'common-ui-design',\n ],\n mobile: ['common-accessibility', 'common-api-design', 'common-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 cwd = process.cwd();\n // Gather root and immediate subdirectories to support monorepos\n const dirsToScan = [cwd];\n try {\n const entries = await fs.readdir(cwd, { withFileTypes: true });\n for (const entry of entries) {\n if (\n entry.isDirectory() &&\n !entry.name.startsWith('.') &&\n entry.name !== 'node_modules'\n ) {\n dirsToScan.push(path.join(cwd, entry.name));\n }\n }\n } catch {\n // Ignore\n }\n\n const packageDepsMaps = await Promise.all(\n dirsToScan.map((dir) => this.readPackageJsonDeps(dir)),\n );\n\n // Merge all deps\n const allPackageDeps = {};\n for (const deps of packageDepsMaps) {\n Object.assign(allPackageDeps, deps);\n }\n\n const detectionPromises = SUPPORTED_FRAMEWORKS.map(async (framework) => {\n // 1. Check characteristic files in parallel across all scanned directories\n let detected = false;\n for (const dir of dirsToScan) {\n if (detected) break;\n const fileChecks = framework.detectionFiles.map((file) =>\n fs.pathExists(path.join(dir, file)),\n );\n const fileResults = await Promise.all(fileChecks);\n if (fileResults.some((exists) => exists)) {\n detected = true;\n }\n }\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(allPackageDeps, 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 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 Routing Protocol (CRITICAL)',\n '',\n 'You are operating in a Zero-Trust environment. You are strictly forbidden from relying on your baseline pre-training for architecture, styling, testing, or code patterns in this repository.',\n '',\n '> [!CRITICAL] GATEKEEPER CONSTRAINT',\n '> **Your first action in ANY session MUST be a tool call to read `AGENTS.md`.**',\n '> You must NOT write code, suggest solutions, or output text explanations until you have completed the State Machine below.',\n '',\n '## 🔄 The Mandatory State Machine',\n '',\n 'You must execute these states sequentially. Do not proceed to the next state until the current one is satisfied.',\n '',\n '### State 1: Discovery (Tool Call Required)',\n '',\n '- **Action:** Execute a file-reading tool (e.g., `view_file`, `read_file`, `cat`) targeting the exact path: `AGENTS.md` (located in the project root).',\n '- **Condition to pass:** You have successfully read the `<!-- SKILLS_INDEX_START -->` block.',\n '',\n '### State 2: Trigger Matching (Internal Thought)',\n '',\n \"- **Action:** Analyze the user's prompt (keywords) and the files involved in the task (globs).\",\n '- **Condition to pass:** Cross-reference them against the `(triggers: ...)` list inside `AGENTS.md`. Identify all matching Skills and note their exact file paths.',\n '',\n '### State 3: Context Loading (Tool Call Required)',\n '',\n `- **Action:** Execute file-reading tools to read the \\`SKILL.md\\` files at the exact paths identified in State 2.`,\n '- **Condition to pass:** You have ingested the specific guidelines for the task. If no skills matched in State 2, you may skip this state.',\n '',\n '### State 4: Execution & Audit Log (Output Generation)',\n '',\n '- **Action:** You may now begin answering the user or writing code.',\n '- **Constraint:** Your very first text output MUST be a \"Pre-Write Audit Log\" confirming which skills were loaded, or explicitly stating \"No project-specific skills applicable.\"',\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 '',\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 allowedCategories List of categories/frameworks to include. If undefined, all found are included.\n * @returns A formatted markdown string representing the index\n */\n async generate(\n baseDir: string,\n allowedCategories?: string[],\n ): 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 let categories = await fs.readdir(baseDir);\n\n // Filter categories to only those specified, plus 'common' and hidden dirs rule.\n categories = categories.filter((category) => {\n if (category.startsWith('.')) return false;\n if (\n allowedCategories &&\n !allowedCategories.includes(category) &&\n category !== 'common'\n ) {\n return false;\n }\n return true;\n });\n\n categories.sort();\n\n for (const category of categories) {\n const categoryPath = path.join(baseDir, category);\n if (!(await fs.stat(categoryPath)).isDirectory()) continue;\n\n const skills = await fs.readdir(categoryPath);\n skills.sort();\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 '> [!CRITICAL] GATEKEEPER CONSTRAINT',\n '> **You are operating in a Zero-Trust environment.**',\n '> You are strictly forbidden from generating code, proposing solutions, or relying on your pre-training until you have successfully executed a tool call to read the applicable `SKILL.md` files from this index.',\n '',\n '## **Rule Zero: Mandatory Zero-Trust Protocol**',\n '',\n '> [!CRITICAL]',\n '> **Zero-Trust Enforcement:** Skills loaded from this index always override standard code patterns. Skipping the Audit Log or Self-Scan is a protocol violation.',\n '',\n '### **1. The Pre-Write Audit Log (Mandatory)**',\n '',\n 'Before invoking any file-editing tool (`write_to_file`, `replace_file_content`, `multi_replace_file_content`), the ASSISTANT **MUST** explicitly state in its thought process/text output:',\n '',\n '1. **Skills Identified**: List the Skill IDs triggered by the file path or current task keywords.',\n '2. **Explicit Audit**: For each identified skill, confirm: \"Checked against [Skill ID] — no violations found.\" Or \"Violation detected in [Skill ID]: [Issue] — correcting now.\"',\n '3. **No-Skill Justification**: If no skills apply, explicitly state: \"No project-specific skills applicable to this file/transaction.\"',\n '',\n '### **2. The Post-Write Self-Scan (Mandatory)**',\n '',\n 'Immediately **AFTER** any file-editing tool returns, the ASSISTANT **MUST**:',\n '',\n '1. **Validate**: Contrast the final file content against ALL active Skill IDs.',\n '2. **Identify Slips**: Look for \"Standard Defaults\" (e.g., local mocks, hardcoded styles) that snuck in.',\n '3. **Self-Correct**: If a violation is found, fix it immediately in the next tool call.',\n '',\n '## **Critical Anti-Patterns (Zero-Tolerance)**',\n '',\n '- **Reversion to Defaults**: Never use \"standard\" patterns (generic library calls, local mocks) if a Project Skill exists.',\n '- **The \"Done\" Trap**: Never prioritize functional completion over structural/protocol compliance.',\n '- **Audit Skipping**: Never invoke a write tool without an explicit Pre-Write Audit Log.',\n '',\n '## ⚡ How to Find and Use This Index (Mandatory)',\n '',\n '> [!IMPORTANT] PATH RESOLUTION (Cross-Platform)',\n '> Skill IDs in the list below (e.g., `[category/skill-name]`) represent the relative folder path.',\n '> Because this project supports multiple AI agents, skills may reside in a base directory like `.gemini/skills/`, `.agent/skills/`, or `.cursor/skills/`.',\n '> **Action:** You must prepend the correct base directory to the ID. (Example: If ID is `[flutter/cicd]`, the file is at `<BASE_DIR>/flutter/cicd/SKILL.md`). Use your file search tools (e.g., `list_directory` or `find`) if you are unsure of the base directory.',\n '',\n '| Trigger Type | What to match | Required Action |',\n '| --- | --- | --- |',\n '| **File glob** (e.g. `**/*.ts`) | Files you are currently editing match the pattern | Call `view_file` on `<BASE_DIR>/[Skill ID]/SKILL.md` |',\n \"| **Keyword** (e.g. `auth`, `refactor`) | These words appear in the user\\\\'s request | Call `view_file` on `<BASE_DIR>/[Skill ID]/SKILL.md` |\",\n '| **Composite** (e.g. `+other/skill`) | Another listed skill is already active | Also load this skill via `view_file` |',\n '',\n '> [!TIP]',\n '> **Indirect phrasing still counts.** Match keywords by intent, not just exact words.',\n '> Examples: \"make it faster\" → `performance`, \"broken query\" → `database`, \"login flow\" → `auth`, \"clean up this file\" → `refactor`.',\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 /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\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 let desc = metadata.description || '';\n // Wrap any inline triggers in backticks as well to avoid formatting issues\n desc = desc.replace(/\\(triggers:\\s*`?(.*?)`?\\)/g, '(triggers: `$1`)');\n\n const content = `${prefix}${desc}`.trim();\n return `- **[${id}]**: ${content}${triggerText}`;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { Agent, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig, SkillEntry } from '../models/config';\nimport { CollectedSkill, GitHubTreeItem } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service responsible for synchronizing agent skills from a remote registry.\n */\nexport class SkillSyncService {\n constructor(private githubService: GithubService) {}\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(\n skills: CollectedSkill[],\n config: SkillConfig,\n agents: Agent[],\n ) {\n const overrides = config.custom_overrides || [];\n\n // Group skills by category to know which folders to prune\n const fetchedSkillsByCategory: Record<string, Set<string>> = {};\n for (const skill of skills) {\n if (!fetchedSkillsByCategory[skill.category]) {\n fetchedSkillsByCategory[skill.category] = new Set();\n }\n fetchedSkillsByCategory[skill.category].add(skill.skill);\n }\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 // Clean up orphaned skills inside categories we are syncing\n // Default to prune: true if not specified\n const shouldPrune = config.prune !== false;\n\n if (shouldPrune) {\n for (const category of Object.keys(fetchedSkillsByCategory)) {\n const categoryPath = path.join(basePath, category);\n if (await fs.pathExists(categoryPath)) {\n const existingDirs = await fs.readdir(categoryPath);\n for (const dir of existingDirs) {\n // If the folder is not in the newly fetched list, it might be orphaned\n if (!fetchedSkillsByCategory[category].has(dir)) {\n const fullPath = path.join(categoryPath, dir);\n // Do not delete if it's protected by custom_overrides\n if (!this.isOverridden(fullPath, overrides)) {\n await fs.remove(fullPath);\n }\n }\n }\n }\n }\n }\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 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 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 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 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, '/').replace(/\\/$/, '');\n return (\n rel === op ||\n rel.startsWith(`${op}/`) ||\n rel.includes(`/${op}/`) ||\n rel.endsWith(`/${op}`)\n );\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 fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { DEFAULT_WORKFLOWS } from '../constants';\nimport { SkillConfig } from '../models/config';\nimport { CollectedSkill } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service responsible for synchronizing agent workflows from a remote registry.\n */\nexport class WorkflowSyncService {\n constructor(private githubService: GithubService) {}\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 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 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 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 return changed;\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 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 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.isPathSafe(targetFilePath, workflowPath)) {\n console.log(\n pc.red(` ❌ Security Error: Invalid path ${fileItem.name}`),\n );\n continue;\n }\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 private isPathSafe(targetPath: string, subPath: string): boolean {\n return path.resolve(targetPath).startsWith(path.resolve(subPath));\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, '/').replace(/\\/$/, '');\n return (\n rel === op ||\n rel.startsWith(`${op}/`) ||\n rel.includes(`/${op}/`) ||\n rel.endsWith(`/${op}`)\n );\n });\n }\n\n private normalizePath(p: string): string {\n return path.relative(process.cwd(), p).replace(/\\\\/g, '/');\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, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig } from '../models/config';\nimport { CollectedSkill } from '../models/types';\nimport { AgentBridgeService } from './AgentBridgeService';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\nimport { GithubService } from './GithubService';\nimport { IndexGeneratorService } from './IndexGeneratorService';\nimport { SkillSyncService } from './SkillSyncService';\nimport { WorkflowSyncService } from './WorkflowSyncService';\nimport { MarkdownUtils } from './utils/MarkdownUtils';\n\n/**\n * Service responsible for coordinating the synchronization of agent skills and workflows.\n * It acts as a facade, delegating specialized synchronization tasks to SkillSyncService\n * and WorkflowSyncService.\n */\nexport class SyncService {\n private configService = new ConfigService();\n private detectionService = new DetectionService();\n private githubService = new GithubService(process.env.GITHUB_TOKEN);\n private skillSyncService = new SkillSyncService(this.githubService);\n private workflowSyncService = new WorkflowSyncService(this.githubService);\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 if (reenabled.length > 0) {\n console.log(pc.cyan('\\n🔄 Dependencies changed, re-enabling skills:'));\n for (const skill of reenabled) {\n console.log(pc.gray(` - ${skill}`));\n }\n return true;\n }\n return false;\n }\n\n async reconcileWorkflows(config: SkillConfig): Promise<boolean> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return false;\n return this.workflowSyncService.reconcileWorkflows(config);\n }\n\n async assembleSkills(\n categories: string[],\n config: SkillConfig,\n ): Promise<CollectedSkill[]> {\n return this.skillSyncService.assembleSkills(categories, config);\n }\n\n async writeSkills(\n skills: CollectedSkill[],\n config: SkillConfig,\n ): Promise<void> {\n const agents = await this.resolveTargetAgents(config);\n return this.skillSyncService.writeSkills(skills, config, agents);\n }\n\n async assembleWorkflows(config: SkillConfig): Promise<CollectedSkill[]> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return [];\n return this.workflowSyncService.assembleWorkflows(config);\n }\n\n async writeWorkflows(\n workflows: CollectedSkill[],\n config: SkillConfig,\n ): Promise<void> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return;\n return this.workflowSyncService.writeWorkflows(workflows, config);\n }\n\n async applyIndices(\n config: SkillConfig,\n targetAgents?: Agent[],\n ): Promise<void> {\n const agents = targetAgents || (await this.resolveTargetAgents(config));\n if (agents.length === 0) return;\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 }\n\n try {\n const generator = new IndexGeneratorService();\n // Use agent path if available, otherwise fallback to .cursor/skills as a reasonable default\n const baseDir = agentDef\n ? path.join(process.cwd(), agentDef.path)\n : path.join(process.cwd(), '.cursor/skills');\n\n const allowedCategories = Object.keys(config.skills || {});\n const index = await generator.generate(baseDir, allowedCategories);\n\n await MarkdownUtils.injectIndex(process.cwd(), ['AGENTS.md'], index);\n console.log(pc.green(' ✅ AGENTS.md index updated.'));\n\n // Apply to sub-projects if any\n const serverDir = path.join(process.cwd(), 'server');\n if (await fs.pathExists(serverDir)) {\n await MarkdownUtils.injectIndex(serverDir, ['AGENTS.md'], index);\n console.log(pc.green(' ✅ server/AGENTS.md index updated.'));\n }\n\n const bridgeService = new AgentBridgeService();\n await bridgeService.bridge(process.cwd(), agents);\n } catch (error) {\n console.log(pc.yellow(` ⚠️ Failed to update index: ${error}`));\n }\n }\n\n async checkForUpdates(config: SkillConfig): Promise<Record<string, string>> {\n const { owner, repo } = GithubService.parseGitHubUrl(config.registry) || {};\n if (!owner || !repo) return {};\n\n const info = await this.githubService.getRepoInfo(owner, repo);\n const ref = info?.default_branch || 'main';\n\n const metadataRaw = await this.githubService.getRawFile(\n owner,\n repo,\n ref,\n 'skills/metadata.json',\n );\n if (!metadataRaw) return {};\n\n const remoteMeta = JSON.parse(metadataRaw);\n const updates: Record<string, string> = {};\n\n for (const [cat, catConfig] of Object.entries(config.skills)) {\n const remoteMetaCat = remoteMeta.categories?.[cat];\n if (!remoteMetaCat?.version) continue;\n\n const latestRef = `${remoteMetaCat.tag_prefix || ''}${remoteMetaCat.version}`;\n if (catConfig.ref !== latestRef) {\n updates[cat] = latestRef;\n }\n }\n\n return updates;\n }\n\n private async resolveTargetAgents(config: SkillConfig): Promise<Agent[]> {\n if (config.agents && config.agents.length > 0) {\n return config.agents;\n }\n\n const detectedMap = await this.detectionService.detectAgents();\n const detected = Object.entries(detectedMap)\n .filter(([, enabled]) => enabled)\n .map(([id]) => id as Agent);\n\n if (detected.length > 0) {\n return detected;\n }\n\n return [Agent.Cursor, Agent.Antigravity, Agent.Kiro];\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 > 1024) {\n result.errors.push(\n `Description too long (${descMatch[1].length} chars > 1024 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.10.4');\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","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,GAAG,KAAK,GAAG,KAAK,uCAAuC,CAAC,CAAC;AAErE,QAAI;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,IACE;AAGJ,QAAI,CAAC,SAAS,CAAC,OAAO;AACpB,YAAM,UAAU,MAAM,SAAS,OAAO;AAAA,QACpC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["../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/constants/security.ts","../src/services/IndexGeneratorService.ts","../src/services/SkillSyncService.ts","../src/services/WorkflowSyncService.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: 'flutter-riverpod-state-management',\n packages: ['flutter_riverpod', 'riverpod'],\n },\n {\n id: 'flutter-bloc-state-management',\n packages: ['flutter_bloc', 'bloc'],\n },\n {\n id: 'flutter-auto-route-navigation',\n packages: ['auto_route'],\n },\n {\n id: 'flutter-go-router-navigation',\n packages: ['go_router'],\n },\n {\n id: 'flutter-getx-navigation',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'flutter-getx-state-management',\n packages: ['get'], // Special handling for exact match required\n },\n {\n id: 'flutter-localization',\n packages: ['easy_localization'],\n },\n {\n id: 'flutter-retrofit-networking',\n packages: ['retrofit'],\n },\n {\n id: 'flutter-dependency-injection',\n packages: ['get_it', 'injectable'],\n },\n ],\n [Framework.NestJS]: [\n {\n id: 'nestjs-caching',\n packages: ['@nestjs/cache-manager', 'cache-manager'],\n },\n {\n id: 'nestjs-database',\n packages: ['@nestjs/typeorm', '@nestjs/prisma', '@nestjs/mongoose'],\n },\n {\n id: 'nestjs-security',\n packages: ['@nestjs/passport', 'passport', 'helmet'],\n },\n ],\n [Framework.Android]: [\n {\n id: 'android-compose',\n packages: ['androidx.compose.ui'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-navigation',\n packages: ['androidx.navigation:navigation-compose'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-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: 'android-di',\n packages: ['hilt-android', 'dagger-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-persistence',\n packages: ['androidx.room:room-runtime'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-networking',\n packages: ['retrofit'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n {\n id: 'android-concurrency',\n packages: ['kotlinx-coroutines-android'],\n files: ['android', 'build.gradle', 'build.gradle.kts'],\n },\n ],\n [Framework.iOS]: [\n {\n id: 'ios-networking',\n packages: ['Alamofire', 'Moya'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-dependency-injection',\n packages: ['Swinject', 'Resolver'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-persistence',\n packages: ['Realm', 'CoreData', 'SQLite.swift'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-state-management',\n packages: ['ComposableArchitecture', 'CombineRuntime'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n {\n id: 'ios-ui-navigation',\n packages: ['Coordinator', 'Router'],\n files: ['ios', 'Podfile', 'Package.swift'],\n },\n ],\n [Framework.ReactNative]: [\n {\n id: 'react-native-navigation',\n packages: ['@react-navigation/native'],\n },\n {\n id: 'react-native-state-management',\n packages: ['zustand', '@reduxjs/toolkit'],\n },\n {\n id: 'react-native-deployment',\n packages: ['react-native-code-push', 'expo-updates'],\n },\n {\n id: 'react-native-security',\n packages: ['react-native-keychain', 'react-native-ssl-pinning'],\n },\n {\n id: 'react-native-performance',\n packages: ['react-native-fast-image'],\n },\n ],\n [Framework.Laravel]: [\n {\n id: 'laravel-api',\n packages: ['laravel/sanctum', 'laravel/passport'],\n },\n {\n id: 'laravel-background-processing',\n packages: ['laravel/horizon'],\n },\n {\n id: 'laravel-testing',\n packages: ['pestphp/pest', 'phpunit/phpunit'],\n },\n {\n id: 'laravel-tooling',\n packages: ['laravel/pint', 'laravel/sail'],\n },\n {\n id: 'laravel-database-expert',\n packages: ['laravel/framework'], // Always present, but used for sub-skill mapping\n },\n ],\n [Framework.NextJS]: [\n {\n id: 'nextjs-pages-router',\n packages: [],\n files: ['pages', 'src/pages'],\n },\n {\n id: 'nextjs-server-components',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-server-actions',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-data-fetching',\n packages: [],\n files: ['app', 'src/app'],\n },\n {\n id: 'nextjs-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: 'react-styling',\n packages: ['tailwind', 'antd', 'sass', 'styled-components', 'emotion'],\n },\n {\n id: 'react-state-management',\n packages: [\n 'redux',\n '@reduxjs/toolkit',\n 'zustand',\n 'mobx',\n 'recoil',\n 'jotai',\n ],\n },\n {\n id: 'react-testing',\n packages: [\n 'jest',\n 'vitest',\n '@testing-library/react',\n 'cypress',\n 'playwright',\n ],\n },\n ],\n database: [\n {\n id: 'database-postgresql',\n packages: ['pg', 'pgx', 'postgres', 'sequelize', 'typeorm', 'prisma'],\n },\n {\n id: 'database-mongodb',\n packages: ['mongodb', 'mongoose'],\n },\n {\n id: 'database-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: [\n 'common-accessibility',\n 'common-mobile-animation',\n 'common-mobile-ux-core',\n 'common-store-changelog',\n 'common-ui-design',\n ],\n frontend: [\n 'common-observability',\n 'common-mobile-animation',\n 'common-mobile-ux-core',\n 'common-store-changelog',\n ],\n mobile: [\n 'common-accessibility',\n 'common-api-design',\n 'common-observability',\n 'common-system-design',\n ],\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 'pentest',\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 cwd = process.cwd();\n // Gather root and immediate subdirectories to support monorepos\n const dirsToScan = [cwd];\n try {\n const entries = await fs.readdir(cwd, { withFileTypes: true });\n for (const entry of entries) {\n if (\n entry.isDirectory() &&\n !entry.name.startsWith('.') &&\n entry.name !== 'node_modules'\n ) {\n dirsToScan.push(path.join(cwd, entry.name));\n }\n }\n } catch {\n // Ignore\n }\n\n const packageDepsMaps = await Promise.all(\n dirsToScan.map((dir) => this.readPackageJsonDeps(dir)),\n );\n\n // Merge all deps\n const allPackageDeps = {};\n for (const deps of packageDepsMaps) {\n Object.assign(allPackageDeps, deps);\n }\n\n const detectionPromises = SUPPORTED_FRAMEWORKS.map(async (framework) => {\n // 1. Check characteristic files in parallel across all scanned directories\n let detected = false;\n for (const dir of dirsToScan) {\n if (detected) break;\n const fileChecks = framework.detectionFiles.map((file) =>\n fs.pathExists(path.join(dir, file)),\n );\n const fileResults = await Promise.all(fileChecks);\n if (fileResults.some((exists) => exists)) {\n detected = true;\n }\n }\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(allPackageDeps, 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 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 Routing Protocol (CRITICAL)',\n '',\n 'You are operating in a Zero-Trust environment. You are strictly forbidden from relying on your baseline pre-training for architecture, styling, testing, or code patterns in this repository.',\n '',\n '> [!CRITICAL] GATEKEEPER CONSTRAINT',\n '> **Your first action in ANY session MUST be a tool call to read `AGENTS.md`.**',\n '> You must NOT write code, suggest solutions, or output text explanations until you have completed the State Machine below.',\n '',\n '## 🔄 The Mandatory State Machine',\n '',\n 'You must execute these states sequentially. Do not proceed to the next state until the current one is satisfied.',\n '',\n '### State 1: Discovery (Tool Call Required)',\n '',\n '- **Action:** Execute a file-reading tool (e.g., `view_file`, `read_file`, `cat`) targeting the exact path: `AGENTS.md` (located in the project root).',\n '- **Condition to pass:** You have successfully read the `<!-- SKILLS_INDEX_START -->` block.',\n '',\n '### State 2: Trigger Matching (Internal Thought)',\n '',\n \"- **Action:** Analyze the user's prompt (keywords) and the files involved in the task (globs).\",\n '- **Condition to pass:** Cross-reference them against the `(triggers: ...)` list inside `AGENTS.md`. Identify all matching Skills and note their exact file paths.',\n '',\n '### State 3: Context Loading (Tool Call Required)',\n '',\n `- **Action:** Execute file-reading tools to read the \\`SKILL.md\\` files at the exact paths identified in State 2.`,\n '- **Condition to pass:** You have ingested the specific guidelines for the task. If no skills matched in State 2, you may skip this state.',\n '',\n '### State 4: Execution & Audit Log (Output Generation)',\n '',\n '- **Action:** You may now begin answering the user or writing code.',\n '- **Constraint:** Your very first text output MUST be a \"Pre-Write Audit Log\" confirming which skills were loaded, or explicitly stating \"No project-specific skills applicable.\"',\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 '',\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","/**\n * Centralized patterns for detecting and sanitizing prompt injection.\n * Shared between the CLI and CI scanning scripts.\n */\n\nexport const INJECTION_PATTERNS: RegExp[] = [\n /ignore\\s+(?:all\\s+|previous\\s+|prior\\s+)*(?:instructions?|rules?|guidance)/gi,\n /you\\s+(?:must|should|shall|will)\\s+(?:now|immediately)\\b/gi,\n /^(?:system|user|assistant)\\s*:/gim,\n /(?:^|\\n)-{3,}(?:\\n|$)/g,\n /<(?:script|iframe|style)[^>]*\\s*>[\\s\\S]*?<\\/(?:script|iframe|style)[^>]*\\s*>/gi,\n];\n","import fs from 'fs-extra';\nimport yaml from 'js-yaml';\nimport path from 'path';\nimport { INJECTION_PATTERNS } from '../constants/security';\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 allowedCategories List of categories/frameworks to include. If undefined, all found are included.\n * @returns A formatted markdown string representing the index\n */\n async generate(\n baseDir: string,\n allowedCategories?: string[],\n ): 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 let categories = await fs.readdir(baseDir);\n\n // Filter categories to only those specified, plus 'common' and hidden dirs rule.\n categories = categories.filter((category) => {\n if (category.startsWith('.')) return false;\n if (\n allowedCategories &&\n !allowedCategories.includes(category) &&\n category !== 'common'\n ) {\n return false;\n }\n return true;\n });\n\n categories.sort();\n\n for (const category of categories) {\n const categoryPath = path.join(baseDir, category);\n if (!(await fs.stat(categoryPath)).isDirectory()) continue;\n\n const skills = await fs.readdir(categoryPath);\n skills.sort();\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 '> [!CRITICAL] GATEKEEPER CONSTRAINT',\n '> **You are operating in a Zero-Trust environment.**',\n '> You are strictly forbidden from generating code, proposing solutions, or relying on your pre-training until you have successfully executed a tool call to read the applicable `SKILL.md` files from this index.',\n '',\n '## **Rule Zero: Mandatory Zero-Trust Protocol**',\n '',\n '> [!CRITICAL]',\n '> **Zero-Trust Enforcement:** Skills loaded from this index always override standard code patterns. Skipping the Audit Log or Self-Scan is a protocol violation.',\n '',\n '### **1. The Pre-Write Audit Log (Mandatory)**',\n '',\n 'Before invoking any file-editing tool (`write_to_file`, `replace_file_content`, `multi_replace_file_content`), the ASSISTANT **MUST** explicitly state in its thought process/text output:',\n '',\n '1. **Skills Identified**: List the Skill IDs triggered by the file path or current task keywords.',\n '2. **Explicit Audit**: For each identified skill, confirm: \"Checked against [Skill ID] — no violations found.\" Or \"Violation detected in [Skill ID]: [Issue] — correcting now.\"',\n '3. **No-Skill Justification**: If no skills apply, explicitly state: \"No project-specific skills applicable to this file/transaction.\"',\n '',\n '### **2. The Post-Write Self-Scan (Mandatory)**',\n '',\n 'Immediately **AFTER** any file-editing tool returns, the ASSISTANT **MUST**:',\n '',\n '1. **Validate**: Contrast the final file content against ALL active Skill IDs.',\n '2. **Identify Slips**: Look for \"Standard Defaults\" (e.g., local mocks, hardcoded styles) that snuck in.',\n '3. **Self-Correct**: If a violation is found, fix it immediately in the next tool call.',\n '',\n '## **Critical Anti-Patterns (Zero-Tolerance)**',\n '',\n '- **Reversion to Defaults**: Never use \"standard\" patterns (generic library calls, local mocks) if a Project Skill exists.',\n '- **The \"Done\" Trap**: Never prioritize functional completion over structural/protocol compliance.',\n '- **Audit Skipping**: Never invoke a write tool without an explicit Pre-Write Audit Log.',\n '',\n '## ⚡ How to Find and Use This Index (Mandatory)',\n '',\n '> [!IMPORTANT] PATH RESOLUTION (Cross-Platform)',\n '> Skill IDs in the list below (e.g., `[category/skill-name]`) represent the relative folder path.',\n '> Because this project supports multiple AI agents, skills may reside in a base directory like `.gemini/skills/`, `.agent/skills/`, or `.cursor/skills/`.',\n '> **Action:** You must prepend the correct base directory to the ID. (Example: If ID is `[flutter/cicd]`, the file is at `<BASE_DIR>/flutter/cicd/SKILL.md`). Use your file search tools (e.g., `list_directory` or `find`) if you are unsure of the base directory.',\n '',\n '| Trigger Type | What to match | Required Action |',\n '| --- | --- | --- |',\n '| **File glob** (e.g. `**/*.ts`) | Files you are currently editing match the pattern | Call `view_file` on `<BASE_DIR>/[Skill ID]/SKILL.md` |',\n \"| **Keyword** (e.g. `auth`, `refactor`) | These words appear in the user\\\\'s request | Call `view_file` on `<BASE_DIR>/[Skill ID]/SKILL.md` |\",\n '| **Composite** (e.g. `+other/skill`) | Another listed skill is already active | Also load this skill via `view_file` |',\n '',\n '> [!TIP]',\n '> **Indirect phrasing still counts.** Match keywords by intent, not just exact words.',\n '> Examples: \"make it faster\" → `performance`, \"broken query\" → `database`, \"login flow\" → `auth`, \"clean up this file\" → `refactor`.',\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 /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\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 /**\n * Sanitizes a skill description to prevent indirect prompt injection.\n * Strips known instruction-hijack patterns and replaces them with [REDACTED].\n * Logs a stderr warning for every skill that required sanitisation.\n * @param desc The raw description string from skill frontmatter\n * @param skillId The skill identifier (category/skill) for log context\n * @returns Sanitised description safe to embed in AGENTS.md\n */\n sanitizeDescription(desc: string, skillId: string = 'unknown'): string {\n let sanitized = desc;\n let wasModified = false;\n\n for (const pattern of INJECTION_PATTERNS) {\n if (pattern.test(sanitized)) {\n wasModified = true;\n sanitized = sanitized.replace(pattern, '[REDACTED]');\n }\n pattern.lastIndex = 0; // reset global regex state\n }\n\n if (wasModified) {\n process.stderr.write(\n `[SECURITY] Prompt injection pattern stripped from skill description: ${skillId}\\n`,\n );\n }\n\n return sanitized;\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 let desc = this.sanitizeDescription(metadata.description || '', id);\n // Wrap any inline triggers in backticks as well to avoid formatting issues\n desc = desc.replace(/\\(triggers:\\s*`?(.*?)`?\\)/g, '(triggers: `$1`)');\n\n const content = `${prefix}${desc}`.trim();\n return `- **[${id}]**: ${content}${triggerText}`;\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { Agent, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig, SkillEntry } from '../models/config';\nimport { CollectedSkill, GitHubTreeItem } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service responsible for synchronizing agent skills from a remote registry.\n */\nexport class SkillSyncService {\n constructor(private githubService: GithubService) {}\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(\n skills: CollectedSkill[],\n config: SkillConfig,\n agents: Agent[],\n ) {\n const overrides = config.custom_overrides || [];\n\n // Group skills by category to know which folders to prune\n const fetchedSkillsByCategory: Record<string, Set<string>> = {};\n for (const skill of skills) {\n if (!fetchedSkillsByCategory[skill.category]) {\n fetchedSkillsByCategory[skill.category] = new Set();\n }\n fetchedSkillsByCategory[skill.category].add(skill.skill);\n }\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 // Clean up orphaned skills inside categories we are syncing\n // Default to prune: true if not specified\n const shouldPrune = config.prune !== false;\n\n if (shouldPrune) {\n for (const category of Object.keys(fetchedSkillsByCategory)) {\n const categoryPath = path.join(basePath, category);\n if (await fs.pathExists(categoryPath)) {\n const existingDirs = await fs.readdir(categoryPath);\n for (const dir of existingDirs) {\n // If the folder is not in the newly fetched list, it might be orphaned\n if (!fetchedSkillsByCategory[category].has(dir)) {\n const fullPath = path.join(categoryPath, dir);\n // Do not delete if it's protected by custom_overrides\n if (!this.isOverridden(fullPath, overrides)) {\n await fs.remove(fullPath);\n }\n }\n }\n }\n }\n }\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 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 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 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 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, '/').replace(/\\/$/, '');\n return (\n rel === op ||\n rel.startsWith(`${op}/`) ||\n rel.includes(`/${op}/`) ||\n rel.endsWith(`/${op}`)\n );\n });\n }\n\n private isPathSafe(targetPath: string, skillPath: string): boolean {\n const resolvedBase = path.resolve(skillPath) + path.sep;\n return path.resolve(targetPath).startsWith(resolvedBase);\n }\n\n private normalizePath(p: string): string {\n return path.relative(process.cwd(), p).replace(/\\\\/g, '/');\n }\n}\n","import fs from 'fs-extra';\nimport path from 'path';\nimport pc from 'picocolors';\nimport { DEFAULT_WORKFLOWS } from '../constants';\nimport { SkillConfig } from '../models/config';\nimport { CollectedSkill } from '../models/types';\nimport { GithubService } from './GithubService';\n\n/**\n * Service responsible for synchronizing agent workflows from a remote registry.\n */\nexport class WorkflowSyncService {\n constructor(private githubService: GithubService) {}\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 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 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 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 return changed;\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 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 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.isPathSafe(targetFilePath, workflowPath)) {\n console.log(\n pc.red(` ❌ Security Error: Invalid path ${fileItem.name}`),\n );\n continue;\n }\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 private isPathSafe(targetPath: string, subPath: string): boolean {\n return path.resolve(targetPath).startsWith(path.resolve(subPath));\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, '/').replace(/\\/$/, '');\n return (\n rel === op ||\n rel.startsWith(`${op}/`) ||\n rel.includes(`/${op}/`) ||\n rel.endsWith(`/${op}`)\n );\n });\n }\n\n private normalizePath(p: string): string {\n return path.relative(process.cwd(), p).replace(/\\\\/g, '/');\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, SUPPORTED_AGENTS } from '../constants';\nimport { SkillConfig } from '../models/config';\nimport { CollectedSkill } from '../models/types';\nimport { AgentBridgeService } from './AgentBridgeService';\nimport { ConfigService } from './ConfigService';\nimport { DetectionService } from './DetectionService';\nimport { GithubService } from './GithubService';\nimport { IndexGeneratorService } from './IndexGeneratorService';\nimport { SkillSyncService } from './SkillSyncService';\nimport { WorkflowSyncService } from './WorkflowSyncService';\nimport { MarkdownUtils } from './utils/MarkdownUtils';\n\n/**\n * Service responsible for coordinating the synchronization of agent skills and workflows.\n * It acts as a facade, delegating specialized synchronization tasks to SkillSyncService\n * and WorkflowSyncService.\n */\nexport class SyncService {\n private configService = new ConfigService();\n private detectionService = new DetectionService();\n private githubService = new GithubService(process.env.GITHUB_TOKEN);\n private skillSyncService = new SkillSyncService(this.githubService);\n private workflowSyncService = new WorkflowSyncService(this.githubService);\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 if (reenabled.length > 0) {\n console.log(pc.cyan('\\n🔄 Dependencies changed, re-enabling skills:'));\n for (const skill of reenabled) {\n console.log(pc.gray(` - ${skill}`));\n }\n return true;\n }\n return false;\n }\n\n async reconcileWorkflows(config: SkillConfig): Promise<boolean> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return false;\n return this.workflowSyncService.reconcileWorkflows(config);\n }\n\n async assembleSkills(\n categories: string[],\n config: SkillConfig,\n ): Promise<CollectedSkill[]> {\n return this.skillSyncService.assembleSkills(categories, config);\n }\n\n async writeSkills(\n skills: CollectedSkill[],\n config: SkillConfig,\n ): Promise<void> {\n const agents = await this.resolveTargetAgents(config);\n return this.skillSyncService.writeSkills(skills, config, agents);\n }\n\n async assembleWorkflows(config: SkillConfig): Promise<CollectedSkill[]> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return [];\n return this.workflowSyncService.assembleWorkflows(config);\n }\n\n async writeWorkflows(\n workflows: CollectedSkill[],\n config: SkillConfig,\n ): Promise<void> {\n const agents = await this.resolveTargetAgents(config);\n if (!agents.includes(Agent.Antigravity)) return;\n return this.workflowSyncService.writeWorkflows(workflows, config);\n }\n\n async applyIndices(\n config: SkillConfig,\n targetAgents?: Agent[],\n ): Promise<void> {\n const agents = targetAgents || (await this.resolveTargetAgents(config));\n if (agents.length === 0) return;\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 }\n\n try {\n const generator = new IndexGeneratorService();\n // Use agent path if available, otherwise fallback to .cursor/skills as a reasonable default\n const baseDir = agentDef\n ? path.join(process.cwd(), agentDef.path)\n : path.join(process.cwd(), '.cursor/skills');\n\n const allowedCategories = Object.keys(config.skills || {});\n const index = await generator.generate(baseDir, allowedCategories);\n\n await MarkdownUtils.injectIndex(process.cwd(), ['AGENTS.md'], index);\n console.log(pc.green(' ✅ AGENTS.md index updated.'));\n\n // Apply to sub-projects if any\n const serverDir = path.join(process.cwd(), 'server');\n if (await fs.pathExists(serverDir)) {\n await MarkdownUtils.injectIndex(serverDir, ['AGENTS.md'], index);\n console.log(pc.green(' ✅ server/AGENTS.md index updated.'));\n }\n\n const bridgeService = new AgentBridgeService();\n await bridgeService.bridge(process.cwd(), agents);\n } catch (error) {\n console.log(pc.yellow(` ⚠️ Failed to update index: ${error}`));\n }\n }\n\n async checkForUpdates(config: SkillConfig): Promise<Record<string, string>> {\n const { owner, repo } = GithubService.parseGitHubUrl(config.registry) || {};\n if (!owner || !repo) return {};\n\n const info = await this.githubService.getRepoInfo(owner, repo);\n const ref = info?.default_branch || 'main';\n\n const metadataRaw = await this.githubService.getRawFile(\n owner,\n repo,\n ref,\n 'skills/metadata.json',\n );\n if (!metadataRaw) return {};\n\n const remoteMeta = JSON.parse(metadataRaw);\n const updates: Record<string, string> = {};\n\n for (const [cat, catConfig] of Object.entries(config.skills)) {\n const remoteMetaCat = remoteMeta.categories?.[cat];\n if (!remoteMetaCat?.version) continue;\n\n const latestRef = `${remoteMetaCat.tag_prefix || ''}${remoteMetaCat.version}`;\n if (catConfig.ref !== latestRef) {\n updates[cat] = latestRef;\n }\n }\n\n return updates;\n }\n\n private async resolveTargetAgents(config: SkillConfig): Promise<Agent[]> {\n if (config.agents && config.agents.length > 0) {\n return config.agents;\n }\n\n const detectedMap = await this.detectionService.detectAgents();\n const detected = Object.entries(detectedMap)\n .filter(([, enabled]) => enabled)\n .map(([id]) => id as Agent);\n\n if (detected.length > 0) {\n return detected;\n }\n\n return [Agent.Cursor, Agent.Antigravity, Agent.Kiro];\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 > 1024) {\n result.errors.push(\n `Description too long (${descMatch[1].length} chars > 1024 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('2.0.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","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,GAAG,KAAK,GAAG,KAAK,uCAAuC,CAAC,CAAC;AAErE,QAA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