mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-20 12:23:29 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fc62f4e42 | ||
|
|
b3ba8eb59e | ||
|
|
44ed5c2485 | ||
|
|
3d0195f180 | ||
|
|
e74f7d6b57 |
@@ -7,7 +7,6 @@ on:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
# Unit tests run on all Node versions
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -36,55 +35,5 @@ jobs:
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Unit Tests
|
||||
- name: Test
|
||||
run: pnpm test
|
||||
|
||||
# E2E tests run on latest Node only (to save CI time)
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test # Run after unit tests pass
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Use Node.js 22
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: E2E Tests
|
||||
run: pnpm test:e2e
|
||||
|
||||
- name: Upload E2E Test Results
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-test-results
|
||||
path: |
|
||||
e2e/**/*.log
|
||||
/tmp/skillkit-e2e-*
|
||||
retention-days: 7
|
||||
|
||||
# Final status check for branch protection
|
||||
ci-success:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [test, e2e]
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check all jobs passed
|
||||
run: |
|
||||
if [[ "${{ needs.test.result }}" != "success" ]] || [[ "${{ needs.e2e.result }}" != "success" ]]; then
|
||||
echo "One or more jobs failed"
|
||||
exit 1
|
||||
fi
|
||||
echo "All CI checks passed!"
|
||||
|
||||
+1
-5
@@ -59,8 +59,4 @@ skillkit.yaml
|
||||
.skillkit/
|
||||
|
||||
# Turbo cache
|
||||
.turbo/
|
||||
|
||||
# Project documentation (not for version control)
|
||||
CLAUDE.md
|
||||
prd.md
|
||||
.turbo/
|
||||
@@ -5,23 +5,31 @@
|
||||
[](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
## Supercharge Every AI Coding Agent
|
||||
## One CLI. 17 AI Agents. Zero Lock-in.
|
||||
|
||||
**Give your AI agents new abilities with portable, reusable skills.** Install from a curated marketplace, create your own, and use them across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more agents.
|
||||
|
||||
> **What are AI Agent Skills?** Skills are instruction files that teach AI coding agents how to handle specific tasks - like processing PDFs, following React best practices, or enforcing security patterns. Think of them as plugins for your AI assistant.
|
||||
**Write skills once, use everywhere.** SkillKit is the universal platform that lets your AI coding skills work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more agents.
|
||||
|
||||
```bash
|
||||
npm install -g skillkit
|
||||
```
|
||||
|
||||
## Why SkillKit?
|
||||
## What's New in v1.5.0
|
||||
|
||||
**The problem:** You've built amazing skills for Claude Code. Now you want to try Cursor. Or your team uses different agents. Each agent has different formats and directories. Without SkillKit, you either rewrite everything, lock yourself into one agent, or give up on skills entirely.
|
||||
- **Team Collaboration**: Share skill bundles with your team via Git
|
||||
- **Plugin System**: Extend SkillKit with custom translators, providers, and commands
|
||||
- **Methodologies**: 5 ready-to-use development frameworks (Agile, TDD, DevOps, etc.)
|
||||
- **Agent Orchestration**: Coordinate multiple AI agents working together
|
||||
- **Hooks & Automation**: Auto-trigger skills on git commits, file changes
|
||||
|
||||
**The solution:** SkillKit translates skills between all 17 agents automatically. Write once, use everywhere.
|
||||
## The Problem
|
||||
|
||||
## See It In Action
|
||||
You've built amazing skills for Claude Code. Now you want to try Cursor. Or your team uses different agents. Your options:
|
||||
|
||||
1. **Rewrite everything** - each agent has different formats, directories, and conventions
|
||||
2. **Pick one agent** - lock yourself in, miss out on innovations
|
||||
3. **Give up on skills** - lose the productivity gains
|
||||
|
||||
## The Solution
|
||||
|
||||
```bash
|
||||
# Install a skill for ALL your agents at once
|
||||
@@ -51,16 +59,6 @@ skillkit recommend
|
||||
| **Session Memory** | Knowledge dies with each session | Persistent learning across agents |
|
||||
| **Skill Testing** | Hope it works | Test framework with assertions |
|
||||
|
||||
## What's New in v1.6
|
||||
|
||||
- **Recursive Agent Translation**: Batch translate entire directories of agents with `--recursive` flag
|
||||
- **Custom AI Sub-Agents**: Create, translate, sync, and validate custom AI sub-agents across 17 coding agents
|
||||
- **Methodology Framework**: 5 ready-to-use frameworks (Agile, TDD, DevOps, Security-First, Documentation-First)
|
||||
- **Hooks System**: Event-driven skill triggers - auto-activate on commits, file changes, builds
|
||||
- **Agent Orchestration**: Multi-agent team coordination with leader/teammate roles
|
||||
- **Plan System**: Parse, validate, and execute structured development plans
|
||||
- **Slash Commands**: Generate agent-native `/commands` from natural language
|
||||
|
||||
## 5-Minute Quick Start
|
||||
|
||||
```bash
|
||||
@@ -97,12 +95,6 @@ skillkit translate --all --to windsurf
|
||||
|
||||
# Preview translation without writing
|
||||
skillkit translate my-skill --to codex --dry-run
|
||||
|
||||
# Batch translate from a custom source directory
|
||||
skillkit agent translate --source ./my-skills --to cursor
|
||||
|
||||
# Recursively translate nested agent directories
|
||||
skillkit agent translate --source ./kubernetes-skills --to cursor --recursive
|
||||
```
|
||||
|
||||
**Supported Agents:** Claude Code, Cursor, Codex, Gemini CLI, OpenCode, Antigravity, Amp, Clawdbot, Droid, GitHub Copilot, Goose, Kilo, Kiro, Roo, Trae, Windsurf, Universal
|
||||
@@ -238,7 +230,7 @@ skillkit cicd pre-commit
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.amp/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` or `~/.clawdbot/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` |
|
||||
@@ -280,21 +272,6 @@ skillkit context init # Initialize project context
|
||||
skillkit context sync # Sync context to agents
|
||||
```
|
||||
|
||||
### Custom AI Sub-Agents
|
||||
|
||||
```bash
|
||||
skillkit agent list # List all installed agents
|
||||
skillkit agent show <name> # Show agent details
|
||||
skillkit agent create <name> # Create a new agent
|
||||
skillkit agent translate # Translate agents between formats
|
||||
--source ./path # Source directory or file
|
||||
--to cursor # Target agent format
|
||||
--recursive # Scan subdirectories recursively
|
||||
--dry-run # Preview without writing
|
||||
skillkit agent sync # Sync agents to target AI agent
|
||||
skillkit agent validate # Validate agent definitions
|
||||
```
|
||||
|
||||
### Memory System
|
||||
|
||||
```bash
|
||||
@@ -443,6 +420,16 @@ disabledSkills:
|
||||
- deprecated-skill
|
||||
```
|
||||
|
||||
## Why SkillKit Exists
|
||||
|
||||
AI coding agents are amazing, but the ecosystem is fragmented:
|
||||
- **Skills don't transfer** between agents
|
||||
- **Knowledge dies** when sessions end
|
||||
- **No standard** for skill quality or testing
|
||||
- **Manual discovery** of useful skills
|
||||
|
||||
SkillKit solves these problems with a universal platform that works across all major AI coding agents.
|
||||
|
||||
## License
|
||||
|
||||
Apache License 2.0 - see [LICENSE](LICENSE) for details.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.6.4",
|
||||
"description": "Supercharge AI coding agents with portable skills. Install, translate, and share skills across Claude Code, Cursor, Codex, Copilot & 13 more",
|
||||
"version": "1.5.0",
|
||||
"description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"skillkit": "./dist/cli.js",
|
||||
|
||||
@@ -39,13 +39,6 @@ import {
|
||||
CommandCmd,
|
||||
AICommand,
|
||||
AuditCommand,
|
||||
AgentCommand,
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
@@ -98,12 +91,5 @@ cli.register(PlanCommand);
|
||||
cli.register(CommandCmd);
|
||||
cli.register(AICommand);
|
||||
cli.register(AuditCommand);
|
||||
cli.register(AgentCommand);
|
||||
cli.register(AgentListCommand);
|
||||
cli.register(AgentShowCommand);
|
||||
cli.register(AgentCreateCommand);
|
||||
cli.register(AgentTranslateCommand);
|
||||
cli.register(AgentSyncCommand);
|
||||
cli.register(AgentValidateCommand);
|
||||
|
||||
cli.runExit(process.argv.slice(2));
|
||||
|
||||
@@ -1,458 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Commands, Settings, and Advanced Features
|
||||
*
|
||||
* Tests for: command generate/export/merge, settings, memory, audit, ai, cicd
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Slash Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'commands-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'command-skill', {
|
||||
description: 'A skill for testing slash command generation',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit command generate', () => {
|
||||
it('should generate slash commands from skills', async () => {
|
||||
const result = await runCli(['command', 'generate'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('command') ||
|
||||
output.includes('generate') ||
|
||||
output.includes('slash') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate commands for specific agent', async () => {
|
||||
const result = await runCli(['command', 'generate', '--agent', 'claude-code'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should generate from natural language prompt', async () => {
|
||||
const result = await runCli(
|
||||
['command', 'generate', '--prompt', 'Create a command to run tests'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit command export', () => {
|
||||
it('should export generated commands', async () => {
|
||||
// Generate first
|
||||
await runCli(['command', 'generate'], { cwd: testDir });
|
||||
|
||||
const outputPath = join(testDir, 'commands-export');
|
||||
const result = await runCli(['command', 'export', '--output', outputPath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export in different formats', async () => {
|
||||
await runCli(['command', 'generate'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['command', 'export', '--format', 'json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit command merge', () => {
|
||||
it('should merge multiple command files', async () => {
|
||||
// Create two command files
|
||||
mkdirSync(join(testDir, 'commands'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(testDir, 'commands', 'cmd1.json'),
|
||||
JSON.stringify({ commands: [{ name: 'test1' }] }, null, 2)
|
||||
);
|
||||
writeFileSync(
|
||||
join(testDir, 'commands', 'cmd2.json'),
|
||||
JSON.stringify({ commands: [{ name: 'test2' }] }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(
|
||||
[
|
||||
'command',
|
||||
'merge',
|
||||
join(testDir, 'commands', 'cmd1.json'),
|
||||
join(testDir, 'commands', 'cmd2.json'),
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Settings Management', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'settings-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit settings', () => {
|
||||
it('should show current settings', async () => {
|
||||
const result = await runCli(['settings'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('setting') ||
|
||||
output.includes('config') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should set a configuration value', async () => {
|
||||
const result = await runCli(['settings', '--set', 'defaultAgent=claude-code'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should get a specific setting', async () => {
|
||||
await runCli(['settings', '--set', 'testKey=testValue'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['settings', '--get', 'testKey'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should unset a configuration value', async () => {
|
||||
await runCli(['settings', '--set', 'removeKey=value'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['settings', '--unset', 'removeKey'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['settings', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should reset all settings', async () => {
|
||||
const result = await runCli(['settings', '--reset'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Memory System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'memory-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit memory', () => {
|
||||
it('should show memory status', async () => {
|
||||
const result = await runCli(['memory'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('memory') ||
|
||||
output.includes('session') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should store observation', async () => {
|
||||
const result = await runCli(['memory', 'store', '--observation', 'User prefers TypeScript'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should retrieve memories', async () => {
|
||||
await runCli(['memory', 'store', '--observation', 'Test observation for retrieval'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['memory', 'retrieve'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should clear memory', async () => {
|
||||
const result = await runCli(['memory', 'clear'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should compress memory', async () => {
|
||||
// Store some memories
|
||||
await runCli(['memory', 'store', '--observation', 'Observation 1'], { cwd: testDir });
|
||||
await runCli(['memory', 'store', '--observation', 'Observation 2'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['memory', 'compress'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['memory', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('{') || result.stdout.trim().startsWith('[')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Audit System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'audit-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'audit-skill', {
|
||||
description: 'A skill for testing audit logging',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit audit', () => {
|
||||
it('should show audit log', async () => {
|
||||
// Perform some actions to generate audit entries
|
||||
await runCli(['list'], { cwd: testDir });
|
||||
await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['audit'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('audit') ||
|
||||
output.includes('log') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should filter audit by date range', async () => {
|
||||
const result = await runCli(['audit', '--since', '2024-01-01'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter audit by action type', async () => {
|
||||
const result = await runCli(['audit', '--action', 'sync'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export audit log', async () => {
|
||||
const outputPath = join(testDir, 'audit-export.json');
|
||||
const result = await runCli(['audit', '--export', outputPath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should clear audit log', async () => {
|
||||
const result = await runCli(['audit', '--clear'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: AI Features', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'ai-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit ai', () => {
|
||||
it('should show AI status', async () => {
|
||||
const result = await runCli(['ai'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('ai') ||
|
||||
output.includes('API') ||
|
||||
output.includes('status') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should configure AI provider', async () => {
|
||||
const result = await runCli(['ai', 'configure', '--provider', 'openai'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should test AI connection', async () => {
|
||||
const result = await runCli(['ai', 'test'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: CI/CD Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'cicd-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, '.git'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit cicd init', () => {
|
||||
it('should generate GitHub Actions workflow', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'github'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('cicd') ||
|
||||
output.includes('github') ||
|
||||
output.includes('workflow') ||
|
||||
output.includes('created') ||
|
||||
testFileExists(testDir, '.github', 'workflows') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate GitLab CI config', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'gitlab'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should generate CircleCI config', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'circleci'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --dry-run', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'github', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle unknown provider gracefully', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'unknown-ci'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('unknown') ||
|
||||
output.includes('not supported') ||
|
||||
output.includes('error') ||
|
||||
!result.success ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Workflow Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'workflow-test',
|
||||
version: '1.0.0',
|
||||
scripts: {
|
||||
test: 'echo "test passed"',
|
||||
build: 'echo "build completed"',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit workflow-create', () => {
|
||||
it('should create a new workflow', async () => {
|
||||
const result = await runCli(['workflow-create', '--name', 'test-workflow'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should create workflow with steps', async () => {
|
||||
const result = await runCli(
|
||||
['workflow-create', '--name', 'stepped-workflow', '--steps', 'build,test,deploy'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit workflow-list', () => {
|
||||
it('should list available workflows', async () => {
|
||||
const result = await runCli(['workflow-list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit workflow-run', () => {
|
||||
it('should run a workflow', async () => {
|
||||
await runCli(['workflow-create', '--name', 'runnable-workflow'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['workflow-run', 'runnable-workflow'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should run workflow with --dry-run', async () => {
|
||||
const result = await runCli(['workflow-run', 'test', '--dry-run'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,292 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Core CLI Commands
|
||||
*
|
||||
* Tests for: init, list, install, enable, disable, remove, update, sync, read, validate
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
createTestProject,
|
||||
readTestFile,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Core CLI Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit --version', () => {
|
||||
it('should display version number', async () => {
|
||||
const result = await runCli(['--version']);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.stdout).toMatch(/\d+\.\d+\.\d+/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit --help', () => {
|
||||
it('should display help information', async () => {
|
||||
const result = await runCli(['--help']);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.stdout).toContain('skillkit');
|
||||
});
|
||||
|
||||
it('should list available commands', async () => {
|
||||
const result = await runCli(['--help']);
|
||||
expect(result.stdout + result.stderr).toMatch(/init|list|install|sync/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit init', () => {
|
||||
it('should initialize skillkit in a new project', async () => {
|
||||
const result = await runCli(['init'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Check for concrete successful outcome - any of these directories
|
||||
const hasSkillsDir = testFileExists(testDir, 'skills');
|
||||
const hasSkillkitDir = testFileExists(testDir, '.skillkit');
|
||||
const hasClaudeSkills = testFileExists(testDir, '.claude/skills');
|
||||
const hasAgentSkills = testFileExists(testDir, '.agent/skills');
|
||||
const hasAnyDir = hasSkillsDir || hasSkillkitDir || hasClaudeSkills || hasAgentSkills;
|
||||
|
||||
// Either a directory was created OR the command completed successfully with output
|
||||
if (!hasAnyDir && result.exitCode !== 0) {
|
||||
// Fail with debugging info
|
||||
expect.fail(`Init failed. Exit code: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasAnyDir || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create skills directory structure', async () => {
|
||||
const result = await runCli(['init'], { cwd: testDir });
|
||||
|
||||
// Verify expected structure actually exists - any of these directories
|
||||
const hasSkillsDir = testFileExists(testDir, 'skills');
|
||||
const hasSkillkitDir = testFileExists(testDir, '.skillkit');
|
||||
const hasClaudeSkills = testFileExists(testDir, '.claude/skills');
|
||||
const hasAgentSkills = testFileExists(testDir, '.agent/skills');
|
||||
const hasAnySkillDir = hasSkillsDir || hasSkillkitDir || hasClaudeSkills || hasAgentSkills;
|
||||
|
||||
// Strict assertion - init should create at least one directory
|
||||
if (!hasAnySkillDir) {
|
||||
const output = result.stdout + result.stderr;
|
||||
expect.fail(`Init did not create expected directories.\nExit code: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasAnySkillDir).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit list', () => {
|
||||
it('should list no skills in empty project', async () => {
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
// Should complete without error even if no skills
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should list discovered skills', async () => {
|
||||
// Create some test skills
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'my-skill');
|
||||
createTestSkill(skillsDir, 'another-skill');
|
||||
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should find the skills or report none
|
||||
expect(output.includes('my-skill') || output.includes('skill') || output.includes('0')).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('should support --json output format', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'json-test-skill');
|
||||
|
||||
const result = await runCli(['list', '--json'], { cwd: testDir });
|
||||
// If JSON format is supported, output should be parseable
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit read', () => {
|
||||
it('should read skill content', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'readable-skill', {
|
||||
content: 'This skill has specific content for reading.',
|
||||
});
|
||||
|
||||
const result = await runCli(['read', 'readable-skill'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should either show the skill or report not found
|
||||
expect(
|
||||
output.includes('readable-skill') ||
|
||||
output.includes('specific content') ||
|
||||
output.includes('not found') ||
|
||||
output.includes('No skill')
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle non-existent skill gracefully', async () => {
|
||||
const result = await runCli(['read', 'nonexistent-skill'], { cwd: testDir });
|
||||
// Should not crash, may report error
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit validate', () => {
|
||||
it('should validate a correct skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
const skillPath = createTestSkill(skillsDir, 'valid-skill', {
|
||||
description: 'A properly formatted skill with sufficient description length for validation',
|
||||
});
|
||||
|
||||
const result = await runCli(['validate', skillPath], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(output.includes('valid') || output.includes('success') || result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should report errors for invalid skill', async () => {
|
||||
const skillDir = join(testDir, 'invalid-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
// Create skill without frontmatter
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), '# No Frontmatter\n\nJust content.');
|
||||
|
||||
const result = await runCli(['validate', skillDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should report validation issues
|
||||
expect(
|
||||
output.includes('error') ||
|
||||
output.includes('invalid') ||
|
||||
output.includes('missing') ||
|
||||
!result.success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate skill with all Agent Skills spec fields', async () => {
|
||||
const skillDir = join(testDir, 'full-spec-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
`---
|
||||
name: full-spec-skill
|
||||
description: A skill that uses all Agent Skills specification fields for complete validation testing
|
||||
license: MIT
|
||||
compatibility: Node.js 18+, requires npm
|
||||
allowed-tools: Bash(npm:*) Read Write Edit
|
||||
metadata:
|
||||
author: test-org
|
||||
version: "1.0.0"
|
||||
tags:
|
||||
- testing
|
||||
- e2e
|
||||
---
|
||||
|
||||
# Full Spec Skill
|
||||
|
||||
This skill uses all available frontmatter fields.
|
||||
`
|
||||
);
|
||||
|
||||
const result = await runCli(['validate', skillDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should complete validation - either valid or show specific validation messages
|
||||
expect(
|
||||
result.success ||
|
||||
output.includes('valid') ||
|
||||
output.includes('full-spec-skill') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit enable/disable', () => {
|
||||
it('should enable a skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'toggle-skill');
|
||||
|
||||
const result = await runCli(['enable', 'toggle-skill'], { cwd: testDir });
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should disable a skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'toggle-skill');
|
||||
|
||||
// First enable, then disable
|
||||
await runCli(['enable', 'toggle-skill'], { cwd: testDir });
|
||||
const result = await runCli(['disable', 'toggle-skill'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit sync', () => {
|
||||
it('should sync skills to agent config', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'sync-test-skill');
|
||||
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should attempt sync operation
|
||||
expect(
|
||||
output.includes('sync') ||
|
||||
output.includes('claude') ||
|
||||
output.includes('skill') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit status', () => {
|
||||
it('should show current skillkit status', async () => {
|
||||
const result = await runCli(['status'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should show some status information
|
||||
expect(
|
||||
output.includes('status') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('agent') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit remove', () => {
|
||||
it('should remove an installed skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'removable-skill');
|
||||
|
||||
// First ensure it exists
|
||||
expect(testFileExists(testDir, 'skills', 'removable-skill', 'SKILL.md')).toBe(true);
|
||||
|
||||
const result = await runCli(['remove', 'removable-skill'], { cwd: testDir });
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,285 +0,0 @@
|
||||
/**
|
||||
* E2E Test CLI Runner
|
||||
* Executes skillkit CLI commands and captures output for testing
|
||||
*/
|
||||
|
||||
import { spawn, execFileSync } from 'node:child_process';
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { mkdirSync, rmSync, existsSync, writeFileSync, readFileSync, mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
// ESM-compatible __dirname equivalent
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
export interface CliResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
success: boolean;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
cwd?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
timeout?: number;
|
||||
input?: string;
|
||||
}
|
||||
|
||||
const ROOT_DIR = resolve(__dirname, '../..');
|
||||
const CLI_PATH = join(ROOT_DIR, 'apps/skillkit/dist/cli.js');
|
||||
|
||||
/**
|
||||
* Run a skillkit CLI command and capture the result
|
||||
*/
|
||||
export async function runCli(args: string[], options: RunOptions = {}): Promise<CliResult> {
|
||||
const startTime = Date.now();
|
||||
const cwd = options.cwd || ROOT_DIR;
|
||||
const timeout = options.timeout || 30000;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn('node', [CLI_PATH, ...args], {
|
||||
cwd,
|
||||
env: { ...process.env, ...options.env, NO_COLOR: '1', FORCE_COLOR: '0' },
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let killed = false;
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
killed = true;
|
||||
child.kill('SIGTERM');
|
||||
}, timeout);
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
if (options.input) {
|
||||
child.stdin?.write(options.input);
|
||||
child.stdin?.end();
|
||||
}
|
||||
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timeoutId);
|
||||
const duration = Date.now() - startTime;
|
||||
const exitCode = killed ? -1 : (code ?? 1);
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode,
|
||||
success: exitCode === 0,
|
||||
duration,
|
||||
});
|
||||
});
|
||||
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
const duration = Date.now() - startTime;
|
||||
resolve({
|
||||
stdout,
|
||||
stderr: stderr + err.message,
|
||||
exitCode: 1,
|
||||
success: false,
|
||||
duration,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run skillkit CLI synchronously (for simpler tests)
|
||||
* Uses execFileSync to avoid shell injection vulnerabilities
|
||||
*/
|
||||
export function runCliSync(args: string[], options: RunOptions = {}): CliResult {
|
||||
const startTime = Date.now();
|
||||
const cwd = options.cwd || ROOT_DIR;
|
||||
|
||||
try {
|
||||
const result = execFileSync('node', [CLI_PATH, ...args], {
|
||||
cwd,
|
||||
env: { ...process.env, ...options.env, NO_COLOR: '1', FORCE_COLOR: '0' },
|
||||
encoding: 'utf-8',
|
||||
timeout: options.timeout || 30000,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: result,
|
||||
stderr: '',
|
||||
exitCode: 0,
|
||||
success: true,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
stdout: error.stdout || '',
|
||||
stderr: error.stderr || error.message,
|
||||
exitCode: error.status || 1,
|
||||
success: false,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary test directory
|
||||
*/
|
||||
export function createTestDir(prefix = 'skillkit-e2e-'): string {
|
||||
return mkdtempSync(join(tmpdir(), prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up a test directory
|
||||
*/
|
||||
export function cleanupTestDir(dir: string): void {
|
||||
if (existsSync(dir)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a test skill in a directory
|
||||
*/
|
||||
export function createTestSkill(
|
||||
dir: string,
|
||||
name: string,
|
||||
options: {
|
||||
description?: string;
|
||||
content?: string;
|
||||
additionalFrontmatter?: Record<string, unknown>;
|
||||
} = {}
|
||||
): string {
|
||||
const skillDir = join(dir, name);
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
|
||||
const frontmatter: Record<string, unknown> = {
|
||||
name,
|
||||
description: options.description || `Test skill: ${name} for E2E testing`,
|
||||
...options.additionalFrontmatter,
|
||||
};
|
||||
|
||||
const frontmatterStr = Object.entries(frontmatter)
|
||||
.map(([key, value]) => {
|
||||
if (typeof value === 'object') {
|
||||
return `${key}:\n${Object.entries(value as Record<string, unknown>)
|
||||
.map(([k, v]) => ` ${k}: ${JSON.stringify(v)}`)
|
||||
.join('\n')}`;
|
||||
}
|
||||
return `${key}: ${value}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const content = `---
|
||||
${frontmatterStr}
|
||||
---
|
||||
|
||||
# ${name}
|
||||
|
||||
${options.content || `This is a test skill named ${name}.`}
|
||||
`;
|
||||
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), content);
|
||||
return skillDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a test project with common setup
|
||||
*/
|
||||
export function createTestProject(options: {
|
||||
withSkills?: boolean;
|
||||
skillCount?: number;
|
||||
withGit?: boolean;
|
||||
projectType?: 'node' | 'python' | 'rust' | 'go';
|
||||
} = {}): { dir: string; cleanup: () => void } {
|
||||
const dir = createTestDir();
|
||||
|
||||
if (options.withGit) {
|
||||
mkdirSync(join(dir, '.git'), { recursive: true });
|
||||
writeFileSync(join(dir, '.git', 'config'), '[core]\n\trepositoryformatversion = 0');
|
||||
}
|
||||
|
||||
if (options.projectType === 'node') {
|
||||
writeFileSync(
|
||||
join(dir, 'package.json'),
|
||||
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
} else if (options.projectType === 'python') {
|
||||
writeFileSync(join(dir, 'requirements.txt'), 'pytest>=7.0.0\n');
|
||||
} else if (options.projectType === 'rust') {
|
||||
writeFileSync(join(dir, 'Cargo.toml'), '[package]\nname = "test"\nversion = "0.1.0"');
|
||||
} else if (options.projectType === 'go') {
|
||||
writeFileSync(join(dir, 'go.mod'), 'module test\n\ngo 1.21');
|
||||
}
|
||||
|
||||
if (options.withSkills) {
|
||||
const skillsDir = join(dir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
// Use nullish coalescing to respect explicit 0
|
||||
const count = options.skillCount ?? 3;
|
||||
for (let i = 1; i <= count; i++) {
|
||||
createTestSkill(skillsDir, `test-skill-${i}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dir,
|
||||
cleanup: () => cleanupTestDir(dir),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read file content from test directory
|
||||
*/
|
||||
export function readTestFile(dir: string, ...paths: string[]): string {
|
||||
return readFileSync(join(dir, ...paths), 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file exists in test directory
|
||||
*/
|
||||
export function testFileExists(dir: string, ...paths: string[]): boolean {
|
||||
return existsSync(join(dir, ...paths));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write file in test directory
|
||||
*/
|
||||
export function writeTestFile(dir: string, path: string, content: string): void {
|
||||
const fullPath = join(dir, path);
|
||||
mkdirSync(join(fullPath, '..'), { recursive: true });
|
||||
writeFileSync(fullPath, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert CLI output contains expected text
|
||||
*/
|
||||
export function assertContains(result: CliResult, expected: string, message?: string): void {
|
||||
const combined = result.stdout + result.stderr;
|
||||
if (!combined.includes(expected)) {
|
||||
throw new Error(
|
||||
message || `Expected output to contain "${expected}"\nActual output:\n${combined}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert CLI output matches regex
|
||||
*/
|
||||
export function assertMatches(result: CliResult, pattern: RegExp, message?: string): void {
|
||||
const combined = result.stdout + result.stderr;
|
||||
if (!pattern.test(combined)) {
|
||||
throw new Error(
|
||||
message || `Expected output to match ${pattern}\nActual output:\n${combined}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
/**
|
||||
* E2E Test Helpers - Barrel Export
|
||||
*/
|
||||
|
||||
export * from './cli-runner.js';
|
||||
@@ -1,400 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Hooks System and Agent Orchestration
|
||||
*
|
||||
* Tests for: hook register/list/trigger/remove, orchestrator commands
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// Available hook events
|
||||
const HOOK_EVENTS = [
|
||||
'pre-commit',
|
||||
'post-commit',
|
||||
'file-change',
|
||||
'build',
|
||||
'test',
|
||||
'deploy',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Hooks System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a git repo structure for commit hooks
|
||||
mkdirSync(join(testDir, '.git', 'hooks'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]\n\trepositoryformatversion = 0');
|
||||
// Create project files
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'hooks-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
// Create a skill that can be triggered
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'hookable-skill', {
|
||||
description: 'A skill that can be triggered by hooks for E2E testing',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit hook register', () => {
|
||||
it('should register a pre-commit hook', async () => {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', 'pre-commit', '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must have meaningful output about the registration
|
||||
const hasRelevantOutput =
|
||||
output.includes('register') ||
|
||||
output.includes('hook') ||
|
||||
output.includes('pre-commit') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook registration failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should register hooks for all event types', async () => {
|
||||
for (const event of HOOK_EVENTS) {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', event, '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout (-1 exit code)
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
// Command should complete (exit code 0 or 1 for expected behavior)
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('should register hook with custom name', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'hook',
|
||||
'register',
|
||||
'--event',
|
||||
'test',
|
||||
'--skill',
|
||||
'hookable-skill',
|
||||
'--name',
|
||||
'my-test-hook',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
// Command should complete successfully or with expected exit
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should register hook with condition', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'hook',
|
||||
'register',
|
||||
'--event',
|
||||
'file-change',
|
||||
'--skill',
|
||||
'hookable-skill',
|
||||
'--pattern',
|
||||
'*.ts',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle invalid event gracefully', async () => {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', 'invalid-event', '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should either fail or show an error message
|
||||
const showsError =
|
||||
output.includes('invalid') ||
|
||||
output.includes('unknown') ||
|
||||
output.includes('error') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook list', () => {
|
||||
it('should list registered hooks', async () => {
|
||||
// Register a hook first
|
||||
await runCli(['hook', 'register', '--event', 'build', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show hooks or indicate none
|
||||
const hasRelevantOutput =
|
||||
output.includes('hook') ||
|
||||
output.includes('build') ||
|
||||
output.includes('hookable-skill') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['hook', 'list', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should filter by event type', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'list', '--event', 'test'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook trigger', () => {
|
||||
it('should trigger a hook manually', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'test'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
|
||||
// Should show trigger-related output
|
||||
const hasRelevantOutput =
|
||||
output.includes('trigger') ||
|
||||
output.includes('test') ||
|
||||
output.includes('hook') ||
|
||||
output.includes('executed');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook trigger failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should trigger with --dry-run', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'deploy', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'deploy', '--dry-run'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle missing hook gracefully', async () => {
|
||||
const result = await runCli(['hook', 'trigger', 'nonexistent-event'], { cwd: testDir });
|
||||
// Fail explicitly on timeout, should complete without crashing
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook remove', () => {
|
||||
it('should remove a registered hook', async () => {
|
||||
// Register then remove
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'hookable-skill', '--name', 'my-hook'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['hook', 'remove', 'my-hook'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show removal confirmation
|
||||
const hasRelevantOutput =
|
||||
output.includes('remove') ||
|
||||
output.includes('my-hook') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook remove failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should remove all hooks for an event', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'remove', '--event', 'test', '--all'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Agent Orchestration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'orchestration-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'orchestrated-skill', {
|
||||
description: 'A skill for testing multi-agent orchestration features',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('multi-agent sync', () => {
|
||||
it('should sync to multiple agents simultaneously', async () => {
|
||||
const result = await runCli(['sync', '--agents', 'claude-code,cursor,windsurf'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should sync to all supported agents', async () => {
|
||||
const result = await runCli(['sync', '--all-agents'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('team orchestration', () => {
|
||||
it('should configure team with leader and teammates', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(
|
||||
['team', 'init', '--leader', 'claude-code', '--teammates', 'cursor,windsurf'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should delegate tasks to team members', async () => {
|
||||
await runCli(['team', 'init', '--leader', 'claude-code'], { cwd: testDir });
|
||||
|
||||
// This tests the delegation feature if available
|
||||
const result = await runCli(['team', 'sync', '--delegate'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('workflow integration', () => {
|
||||
it('should trigger hooks during workflow execution', async () => {
|
||||
// Register a build hook
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'orchestrated-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
// Run workflow that triggers build
|
||||
const result = await runCli(['workflow', 'run', 'build'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should chain multiple hooks in sequence', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'orchestrated-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'orchestrated-skill', '--after', 'test'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'test', '--chain'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Hook + Skill Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
mkdirSync(join(testDir, '.git', 'hooks'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]');
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
|
||||
// Create a skill with specific trigger configuration
|
||||
const skillDir = join(testDir, 'skills', 'auto-trigger-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
`---
|
||||
name: auto-trigger-skill
|
||||
description: A skill that auto-triggers on specific events for E2E testing
|
||||
triggers:
|
||||
- event: pre-commit
|
||||
- event: file-change
|
||||
pattern: "*.ts"
|
||||
---
|
||||
|
||||
# Auto-Trigger Skill
|
||||
|
||||
This skill automatically activates on:
|
||||
- Pre-commit hooks
|
||||
- TypeScript file changes
|
||||
`
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should auto-register hooks from skill metadata', async () => {
|
||||
const result = await runCli(['hook', 'auto-register'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should detect and apply skill triggers', async () => {
|
||||
const result = await runCli(['sync', '--with-hooks'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -1,424 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Methodology and Plan System
|
||||
*
|
||||
* Tests for: methodology list/load/apply/validate, plan create/validate/execute/list/status
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// Available methodology packs
|
||||
const METHODOLOGY_PACKS = [
|
||||
'agile',
|
||||
'tdd',
|
||||
'devops',
|
||||
'security-first',
|
||||
'documentation-first',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Methodology Framework', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a basic project structure
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'src'), { recursive: true });
|
||||
writeFileSync(join(testDir, 'src', 'index.ts'), 'export const main = () => {};\n');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit methodology list', () => {
|
||||
it('should list available methodology packs', async () => {
|
||||
const result = await runCli(['methodology', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must complete successfully and show relevant output
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should contain methodology-related content
|
||||
const hasRelevantOutput =
|
||||
output.includes('methodology') ||
|
||||
output.includes('agile') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Methodology list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['methodology', 'list', '--json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should show methodology details with --verbose', async () => {
|
||||
const result = await runCli(['methodology', 'list', '--verbose'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology install', () => {
|
||||
describe.each(METHODOLOGY_PACKS)('loading %s methodology', (pack) => {
|
||||
it(`should load ${pack} methodology pack`, async () => {
|
||||
const result = await runCli(['methodology', 'install', pack], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should have relevant output
|
||||
const hasRelevantOutput =
|
||||
output.includes(pack) ||
|
||||
output.includes('installed') ||
|
||||
output.includes('success') ||
|
||||
output.includes('methodology');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Load ${pack} failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle unknown methodology gracefully', async () => {
|
||||
const result = await runCli(['methodology', 'install', 'nonexistent-methodology'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show error or fail
|
||||
const showsError =
|
||||
output.includes('not found') ||
|
||||
output.includes('unknown') ||
|
||||
output.includes('error') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
|
||||
it('should load multiple methodologies', async () => {
|
||||
const result = await runCli(['methodology', 'install', 'tdd', 'security-first'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology sync', () => {
|
||||
it('should sync installed methodology to project', async () => {
|
||||
// Install a methodology first
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['methodology', 'sync'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('sync') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Sync methodology failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should sync specific methodology', async () => {
|
||||
const result = await runCli(['methodology', 'sync', 'agile'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology info', () => {
|
||||
it('should show methodology information', async () => {
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['methodology', 'info', 'tdd'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('info') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('methodology') ||
|
||||
output.includes('description');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Methodology info failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should show info for specific methodology', async () => {
|
||||
const result = await runCli(['methodology', 'info', 'security-first'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Plan System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plan-test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'src'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit plan create', () => {
|
||||
it('should create a new plan', async () => {
|
||||
const result = await runCli(['plan', 'create', '--name', 'test-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('plan') ||
|
||||
output.includes('test-plan') ||
|
||||
output.includes('created');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan create failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create plan with description', async () => {
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'described-plan', '--description', 'A test plan for E2E'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should create plan from template', async () => {
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'template-plan', '--template', 'feature'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should create plan with steps', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'plan',
|
||||
'create',
|
||||
'--name',
|
||||
'stepped-plan',
|
||||
'--steps',
|
||||
'Step 1: Setup,Step 2: Implement,Step 3: Test',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan templates', () => {
|
||||
it('should list available plan templates', async () => {
|
||||
const result = await runCli(['plan', 'templates'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('template') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('available') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan templates failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['plan', 'templates', '--json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan validate', () => {
|
||||
it('should validate plan structure', async () => {
|
||||
// Create a plan
|
||||
await runCli(['plan', 'create', '--name', 'validate-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'validate-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('valid') ||
|
||||
output.includes('validate') ||
|
||||
output.includes('plan');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan validate failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should report validation errors', async () => {
|
||||
// Create an invalid plan file manually
|
||||
const plansDir = join(testDir, '.skillkit', 'plans');
|
||||
mkdirSync(plansDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(plansDir, 'invalid-plan.json'),
|
||||
JSON.stringify({ name: 'invalid' }) // Missing required fields
|
||||
);
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'invalid-plan'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan generate', () => {
|
||||
it('should generate a plan from a template', async () => {
|
||||
const result = await runCli(['plan', 'generate', '--template', 'feature'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('generate') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('template') ||
|
||||
output.includes('feature');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan generate failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan execute', () => {
|
||||
it('should execute a plan', async () => {
|
||||
await runCli(['plan', 'create', '--name', 'exec-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'exec-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('execute') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('exec-plan') ||
|
||||
output.includes('running');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan execute failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should execute with --dry-run', async () => {
|
||||
await runCli(['plan', 'create', '--name', 'dry-run-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'dry-run-plan', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should execute specific step', async () => {
|
||||
await runCli(
|
||||
['plan', 'create', '--name', 'step-plan', '--steps', 'Step1,Step2,Step3'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'step-plan', '--step', '1'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Methodology + Plan Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'integration-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should create plan based on methodology', async () => {
|
||||
// Load TDD methodology
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
// Create plan using TDD approach
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'tdd-feature-plan', '--methodology', 'tdd'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should validate plan against methodology constraints', async () => {
|
||||
await runCli(['methodology', 'install', 'security-first'], { cwd: testDir });
|
||||
await runCli(['plan', 'create', '--name', 'secure-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'secure-plan', '--methodology'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -1,397 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Plugin System
|
||||
*
|
||||
* Tests for: plugin list/install/uninstall/enable/disable/info
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Plugin System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plugin-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
// Create .skillkit directory for plugin storage
|
||||
mkdirSync(join(testDir, '.skillkit', 'plugins'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit plugin list', () => {
|
||||
it('should list installed plugins', async () => {
|
||||
const result = await runCli(['plugin', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('plugin') ||
|
||||
output.includes('No') ||
|
||||
output.includes('installed') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should show available plugins from marketplace', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--available'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter enabled/disabled plugins', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--enabled'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin install', () => {
|
||||
it('should install plugin from local path', async () => {
|
||||
// Create a mock plugin
|
||||
const pluginDir = join(testDir, 'my-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'my-plugin',
|
||||
version: '1.0.0',
|
||||
description: 'A test plugin for E2E testing',
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
writeFileSync(join(pluginDir, 'index.js'), 'module.exports = { init: () => {} };');
|
||||
|
||||
const result = await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('install') ||
|
||||
output.includes('my-plugin') ||
|
||||
output.includes('success') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should install plugin from npm-style name', async () => {
|
||||
// This may fail if plugin doesn't exist, but shouldn't crash
|
||||
const result = await runCli(['plugin', 'install', 'skillkit-plugin-example'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle non-existent plugin gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'install', 'nonexistent-plugin-12345'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('not found') ||
|
||||
output.includes('error') ||
|
||||
output.includes('fail') ||
|
||||
!result.success ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should install with --force option', async () => {
|
||||
const pluginDir = join(testDir, 'force-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'force-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
// Install twice with force
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
const result = await runCli(['plugin', 'install', pluginDir, '--force'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin uninstall', () => {
|
||||
it('should uninstall an installed plugin', async () => {
|
||||
// First install a plugin
|
||||
const pluginDir = join(testDir, 'uninstall-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'uninstall-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// Then uninstall
|
||||
const result = await runCli(['plugin', 'uninstall', 'uninstall-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('uninstall') ||
|
||||
output.includes('remove') ||
|
||||
output.includes('success') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle uninstalling non-installed plugin gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'uninstall', 'not-installed-plugin'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin enable/disable', () => {
|
||||
beforeEach(async () => {
|
||||
// Install a test plugin
|
||||
const pluginDir = join(testDir, 'toggle-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'toggle-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
});
|
||||
|
||||
it('should enable a disabled plugin', async () => {
|
||||
// First disable
|
||||
await runCli(['plugin', 'disable', 'toggle-plugin'], { cwd: testDir });
|
||||
|
||||
// Then enable
|
||||
const result = await runCli(['plugin', 'enable', 'toggle-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('enable') ||
|
||||
output.includes('toggle-plugin') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should disable an enabled plugin', async () => {
|
||||
const result = await runCli(['plugin', 'disable', 'toggle-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('disable') ||
|
||||
output.includes('toggle-plugin') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin info', () => {
|
||||
it('should show plugin information', async () => {
|
||||
// Install a plugin first
|
||||
const pluginDir = join(testDir, 'info-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'info-plugin',
|
||||
version: '2.0.0',
|
||||
description: 'A plugin with detailed info for testing',
|
||||
author: 'Test Author',
|
||||
homepage: 'https://example.com',
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'info', 'info-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('info-plugin') ||
|
||||
output.includes('2.0.0') ||
|
||||
output.includes('info') ||
|
||||
output.includes('description') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle non-existent plugin info gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'info', 'nonexistent-plugin'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const pluginDir = join(testDir, 'json-info-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'json-info-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'info', 'json-info-plugin', '--json'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Plugin Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plugin-integration', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, '.skillkit', 'plugins'), { recursive: true });
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should load plugin skills into skill list', async () => {
|
||||
// Create a plugin with skills
|
||||
const pluginDir = join(testDir, 'skills-plugin');
|
||||
mkdirSync(join(pluginDir, 'skills', 'plugin-skill'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'skills-plugin',
|
||||
version: '1.0.0',
|
||||
skills: ['skills/plugin-skill'],
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
writeFileSync(
|
||||
join(pluginDir, 'skills', 'plugin-skill', 'SKILL.md'),
|
||||
`---
|
||||
name: plugin-skill
|
||||
description: A skill provided by a plugin for E2E testing
|
||||
---
|
||||
|
||||
# Plugin Skill
|
||||
`
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// List should include plugin skill
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle plugin hooks', async () => {
|
||||
// Create a plugin with hooks
|
||||
const pluginDir = join(testDir, 'hooks-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'hooks-plugin',
|
||||
version: '1.0.0',
|
||||
hooks: {
|
||||
'pre-sync': 'echo "pre-sync from plugin"',
|
||||
'post-sync': 'echo "post-sync from plugin"',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// Sync should trigger plugin hooks
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should respect plugin priority order', async () => {
|
||||
// Create two plugins with different priorities
|
||||
const plugin1Dir = join(testDir, 'priority-plugin-1');
|
||||
const plugin2Dir = join(testDir, 'priority-plugin-2');
|
||||
|
||||
mkdirSync(plugin1Dir, { recursive: true });
|
||||
mkdirSync(plugin2Dir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(plugin1Dir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'priority-plugin-1', version: '1.0.0', priority: 10 }, null, 2)
|
||||
);
|
||||
writeFileSync(
|
||||
join(plugin2Dir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'priority-plugin-2', version: '1.0.0', priority: 20 }, null, 2)
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', plugin1Dir], { cwd: testDir });
|
||||
await runCli(['plugin', 'install', plugin2Dir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Marketplace Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'marketplace-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit marketplace', () => {
|
||||
it('should list marketplace skills', async () => {
|
||||
const result = await runCli(['marketplace'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('marketplace') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('available') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should search marketplace', async () => {
|
||||
const result = await runCli(['marketplace', '--search', 'typescript'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter by category', async () => {
|
||||
const result = await runCli(['marketplace', '--category', 'testing'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should show skill details', async () => {
|
||||
const result = await runCli(['marketplace', '--info', 'some-skill'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,761 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Skill Translator
|
||||
*
|
||||
* End-to-end tests for cross-agent skill translation.
|
||||
* Tests the complete workflow of parsing, translating, and writing skills.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
readTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
import {
|
||||
parseSkillToCanonical,
|
||||
parseSkillContentToCanonical,
|
||||
translateSkillToAgent,
|
||||
translateSkillToAll,
|
||||
writeTranslatedSkill,
|
||||
generateSkillsConfig,
|
||||
getAgentSkillsDir,
|
||||
getAgentConfigFile,
|
||||
AGENT_SKILL_FORMATS,
|
||||
type CrossAgentSkill,
|
||||
} from '@skillkit/core';
|
||||
|
||||
// All 17 supported agents
|
||||
const SUPPORTED_AGENTS = [
|
||||
'claude-code',
|
||||
'cursor',
|
||||
'codex',
|
||||
'gemini-cli',
|
||||
'opencode',
|
||||
'antigravity',
|
||||
'amp',
|
||||
'clawdbot',
|
||||
'droid',
|
||||
'github-copilot',
|
||||
'goose',
|
||||
'kilo',
|
||||
'kiro-cli',
|
||||
'roo',
|
||||
'trae',
|
||||
'windsurf',
|
||||
'universal',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Skill Translator - Parsing', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir('skillkit-translator-');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('parseSkillToCanonical', () => {
|
||||
it('should parse a complete SKILL.md with all frontmatter fields', () => {
|
||||
const skillDir = join(testDir, 'complete-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: complete-skill
|
||||
description: A comprehensive skill for E2E testing
|
||||
version: "2.0.0"
|
||||
author: SkillKit Team
|
||||
tags:
|
||||
- testing
|
||||
- e2e
|
||||
- comprehensive
|
||||
allowed-tools: Read, Write, Bash(npm:*)
|
||||
---
|
||||
# Complete Skill
|
||||
|
||||
This skill tests all parsing capabilities.
|
||||
|
||||
## Features
|
||||
|
||||
- Full frontmatter parsing
|
||||
- Content extraction
|
||||
- Agent-specific field handling
|
||||
|
||||
## Usage
|
||||
|
||||
\`\`\`bash
|
||||
skillkit read complete-skill
|
||||
\`\`\`
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe('complete-skill');
|
||||
expect(result?.description).toBe('A comprehensive skill for E2E testing');
|
||||
expect(result?.version).toBe('2.0.0');
|
||||
expect(result?.author).toBe('SkillKit Team');
|
||||
expect(result?.tags).toEqual(['testing', 'e2e', 'comprehensive']);
|
||||
expect(result?.allowedTools).toEqual(['Read', 'Write', 'Bash(npm:*)']);
|
||||
expect(result?.content).toContain('# Complete Skill');
|
||||
expect(result?.content).toContain('## Features');
|
||||
});
|
||||
|
||||
it('should handle SKILL.md with minimal frontmatter', () => {
|
||||
const skillDir = join(testDir, 'minimal-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: minimal-skill
|
||||
description: Just the basics
|
||||
---
|
||||
# Minimal Skill
|
||||
|
||||
Simple content.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe('minimal-skill');
|
||||
expect(result?.description).toBe('Just the basics');
|
||||
expect(result?.version).toBeUndefined();
|
||||
expect(result?.author).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should extract description from content when not in frontmatter', () => {
|
||||
const skillDir = join(testDir, 'no-desc-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: no-desc-skill
|
||||
---
|
||||
This is the first paragraph which should become the description automatically.
|
||||
|
||||
## More Content
|
||||
|
||||
Additional content here.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.description).toContain('This is the first paragraph');
|
||||
});
|
||||
|
||||
it('should handle SKILL.md without any frontmatter', () => {
|
||||
const skillDir = join(testDir, 'no-frontmatter');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `# No Frontmatter Skill
|
||||
|
||||
This skill has no YAML frontmatter at all.
|
||||
|
||||
## Usage
|
||||
|
||||
Just use it directly.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
// Name should be derived from directory
|
||||
expect(result?.name).toBe('no-frontmatter');
|
||||
expect(result?.content).toContain('# No Frontmatter Skill');
|
||||
});
|
||||
|
||||
it('should return null for non-existent skill directory', () => {
|
||||
const result = parseSkillToCanonical(join(testDir, 'does-not-exist'));
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for directory without SKILL.md', () => {
|
||||
const emptyDir = join(testDir, 'empty-dir');
|
||||
mkdirSync(emptyDir, { recursive: true });
|
||||
writeFileSync(join(emptyDir, 'README.md'), '# Not a skill');
|
||||
|
||||
const result = parseSkillToCanonical(emptyDir);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSkillContentToCanonical', () => {
|
||||
it('should parse content with Claude Code specific fields', () => {
|
||||
const content = `---
|
||||
name: claude-specific
|
||||
description: Skill with Claude Code specific fields
|
||||
model: opus
|
||||
context: fork
|
||||
disable-model-invocation: true
|
||||
---
|
||||
# Claude Specific Skill
|
||||
|
||||
Use with Claude Code for best results.
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'claude-code');
|
||||
|
||||
expect(result?.name).toBe('claude-specific');
|
||||
expect(result?.agentFields?.model).toBe('opus');
|
||||
expect(result?.agentFields?.context).toBe('fork');
|
||||
expect(result?.agentFields?.['disable-model-invocation']).toBe(true);
|
||||
expect(result?.sourceAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('should parse content with Cursor specific fields', () => {
|
||||
const content = `---
|
||||
name: cursor-specific
|
||||
description: Skill with Cursor specific fields
|
||||
globs: "**/*.ts"
|
||||
alwaysApply: true
|
||||
---
|
||||
# Cursor Specific Skill
|
||||
|
||||
Optimized for Cursor.
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'cursor');
|
||||
|
||||
expect(result?.name).toBe('cursor-specific');
|
||||
expect(result?.agentFields?.globs).toBe('**/*.ts');
|
||||
expect(result?.agentFields?.alwaysApply).toBe(true);
|
||||
expect(result?.sourceAgent).toBe('cursor');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Skill Translator - Translation', () => {
|
||||
let testDir: string;
|
||||
let testSkill: CrossAgentSkill;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir('skillkit-translate-');
|
||||
testSkill = {
|
||||
name: 'translation-test',
|
||||
description: 'A skill designed for testing cross-agent translation',
|
||||
content: `# Translation Test Skill
|
||||
|
||||
This skill is used to verify that translation works correctly across all supported agents.
|
||||
|
||||
## Features
|
||||
|
||||
- Cross-agent compatibility
|
||||
- Frontmatter preservation
|
||||
- Content integrity
|
||||
|
||||
## Usage
|
||||
|
||||
\`\`\`bash
|
||||
skillkit read translation-test
|
||||
\`\`\`
|
||||
`,
|
||||
frontmatter: {
|
||||
name: 'translation-test',
|
||||
description: 'A skill designed for testing cross-agent translation',
|
||||
version: '1.0.0',
|
||||
author: 'SkillKit E2E Tests',
|
||||
tags: ['testing', 'translation'],
|
||||
},
|
||||
sourcePath: join(testDir, 'translation-test'),
|
||||
sourceAgent: 'claude-code',
|
||||
version: '1.0.0',
|
||||
author: 'SkillKit E2E Tests',
|
||||
tags: ['testing', 'translation'],
|
||||
allowedTools: ['Read', 'Write', 'Bash'],
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('translateSkillToAgent', () => {
|
||||
it.each(SUPPORTED_AGENTS)('should translate skill to %s format', (agent) => {
|
||||
const result = translateSkillToAgent(testSkill, agent);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.targetAgent).toBe(agent);
|
||||
expect(result.content).toBeTruthy();
|
||||
expect(result.content).toContain('translation-test');
|
||||
expect(typeof result.filename).toBe('string');
|
||||
});
|
||||
|
||||
it('should preserve skill name and description across translations', () => {
|
||||
for (const agent of SUPPORTED_AGENTS) {
|
||||
const result = translateSkillToAgent(testSkill, agent);
|
||||
expect(result.content).toContain('translation-test');
|
||||
}
|
||||
});
|
||||
|
||||
it('should add translation metadata when requested', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'cursor', { addMetadata: true });
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('_translated-from: claude-code');
|
||||
expect(result.content).toContain('_translated-at:');
|
||||
});
|
||||
|
||||
it('should not add metadata by default', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'cursor');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).not.toContain('_translated-from');
|
||||
});
|
||||
|
||||
it('should preserve Claude Code specific fields when translating back to Claude Code', () => {
|
||||
const claudeSkill: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
model: 'opus',
|
||||
context: 'fork',
|
||||
'disable-model-invocation': true,
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(claudeSkill, 'claude-code');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('model: opus');
|
||||
expect(result.content).toContain('context: fork');
|
||||
expect(result.content).toContain('disable-model-invocation: true');
|
||||
});
|
||||
|
||||
it('should report incompatible features when translating hooks to non-Claude agents', () => {
|
||||
const skillWithHooks: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
hooks: [{ type: 'PreToolUse', command: 'echo test' }],
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(skillWithHooks, 'cursor');
|
||||
|
||||
expect(result.incompatible).toContain('hooks (only supported in Claude Code)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateSkillToAll', () => {
|
||||
it('should translate skill to all agents except source', () => {
|
||||
const skillDir = join(testDir, 'all-agents-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: all-agents
|
||||
description: Skill for all agents testing
|
||||
version: "1.0.0"
|
||||
---
|
||||
# All Agents Skill
|
||||
|
||||
Universal skill content.
|
||||
`);
|
||||
|
||||
const results = translateSkillToAll(skillDir, 'claude-code');
|
||||
|
||||
// Should have translations for all agents except source
|
||||
expect(results.size).toBe(SUPPORTED_AGENTS.length - 1);
|
||||
expect(results.has('claude-code')).toBe(false);
|
||||
|
||||
for (const agent of SUPPORTED_AGENTS) {
|
||||
if (agent !== 'claude-code') {
|
||||
expect(results.has(agent)).toBe(true);
|
||||
const result = results.get(agent);
|
||||
expect(result?.success).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should return empty map for non-existent skill', () => {
|
||||
const results = translateSkillToAll(join(testDir, 'non-existent'));
|
||||
expect(results.size).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Skill Translator - Writing', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir('skillkit-write-');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('writeTranslatedSkill', () => {
|
||||
it('should write translated skill to correct location', () => {
|
||||
const translationResult = {
|
||||
success: true,
|
||||
content: `---
|
||||
name: written-skill
|
||||
description: A skill that was written to disk
|
||||
---
|
||||
# Written Skill
|
||||
|
||||
Content here.
|
||||
`,
|
||||
filename: 'SKILL.md',
|
||||
targetDir: 'written-skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'claude-code' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(translationResult, testDir);
|
||||
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(writeResult.path)).toBe(true);
|
||||
|
||||
const writtenContent = readFileSync(writeResult.path, 'utf-8');
|
||||
expect(writtenContent).toContain('name: written-skill');
|
||||
expect(writtenContent).toContain('# Written Skill');
|
||||
});
|
||||
|
||||
it('should create nested directories as needed', () => {
|
||||
const translationResult = {
|
||||
success: true,
|
||||
content: '---\nname: nested\n---\n# Content',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: '.cursor/skills/deeply/nested/skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'cursor' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(translationResult, testDir);
|
||||
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(join(testDir, '.cursor/skills/deeply/nested/skill/SKILL.md'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle failed translation results gracefully', () => {
|
||||
const failedResult = {
|
||||
success: false,
|
||||
content: '',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: 'failed-skill',
|
||||
warnings: ['Translation failed'],
|
||||
incompatible: [],
|
||||
targetAgent: 'cursor' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(failedResult, testDir);
|
||||
|
||||
expect(writeResult.success).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Skill Translator - Config Generation', () => {
|
||||
const testSkills = [
|
||||
{ name: 'skill-alpha', description: 'First test skill', path: '/skills/alpha', location: 'project' as const, enabled: true },
|
||||
{ name: 'skill-beta', description: 'Second test skill', path: '/skills/beta', location: 'project' as const, enabled: true },
|
||||
{ name: 'skill-gamma', description: 'Third test skill', path: '/skills/gamma', location: 'global' as const, enabled: true },
|
||||
{ name: 'skill-disabled', description: 'Disabled skill', path: '/skills/disabled', location: 'project' as const, enabled: false },
|
||||
];
|
||||
|
||||
describe('generateSkillsConfig', () => {
|
||||
it('should generate XML config for Claude Code', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'claude-code');
|
||||
|
||||
expect(config).toContain('<skills_system');
|
||||
expect(config).toContain('<name>skill-alpha</name>');
|
||||
expect(config).toContain('<name>skill-beta</name>');
|
||||
expect(config).toContain('<name>skill-gamma</name>');
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
expect(config).toContain('<description>First test skill</description>');
|
||||
expect(config).toContain('skillkit read');
|
||||
});
|
||||
|
||||
it('should generate MDC config for Cursor', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'cursor');
|
||||
|
||||
expect(config).toContain('---');
|
||||
expect(config).toContain('description:');
|
||||
expect(config).toContain('globs:');
|
||||
expect(config).toContain('alwaysApply: true');
|
||||
expect(config).toContain('**skill-alpha**');
|
||||
expect(config).toContain('**skill-beta**');
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
});
|
||||
|
||||
it('should generate Markdown table config for Codex', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'codex');
|
||||
|
||||
expect(config).toContain('| Skill | Description | Command |');
|
||||
expect(config).toContain('| skill-alpha |');
|
||||
expect(config).toContain('| skill-beta |');
|
||||
expect(config).toContain('First test skill');
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
});
|
||||
|
||||
it('should generate JSON config for Gemini CLI', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'gemini-cli');
|
||||
|
||||
expect(config).toContain('```json');
|
||||
expect(config).toContain('"name": "skill-alpha"');
|
||||
expect(config).toContain('"name": "skill-beta"');
|
||||
expect(config).toContain('"description": "First test skill"');
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
});
|
||||
|
||||
it('should generate Markdown config for Windsurf', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'windsurf');
|
||||
|
||||
expect(config).toContain('### skill-alpha');
|
||||
expect(config).toContain('### skill-beta');
|
||||
expect(config).toContain('**Invoke:**');
|
||||
expect(config).toContain('`skillkit read skill-alpha`');
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
});
|
||||
|
||||
it('should generate XML config for Roo', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'roo');
|
||||
|
||||
expect(config).toContain('<skills_system');
|
||||
expect(config).toContain('<name>skill-alpha</name>');
|
||||
});
|
||||
|
||||
it('should generate Markdown config for Trae', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'trae');
|
||||
|
||||
expect(config).toContain('### skill-alpha');
|
||||
expect(config).toContain('### skill-beta');
|
||||
});
|
||||
|
||||
it('should generate Markdown config for GitHub Copilot', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'github-copilot');
|
||||
|
||||
expect(config).toContain('### skill-alpha');
|
||||
expect(config).toContain('### skill-beta');
|
||||
});
|
||||
|
||||
it('should return empty string when no skills are enabled', () => {
|
||||
const disabledOnlySkills = [
|
||||
{ name: 'disabled-1', description: 'Disabled', path: '/d1', location: 'project' as const, enabled: false },
|
||||
{ name: 'disabled-2', description: 'Also disabled', path: '/d2', location: 'project' as const, enabled: false },
|
||||
];
|
||||
|
||||
const config = generateSkillsConfig(disabledOnlySkills, 'claude-code');
|
||||
expect(config).toBe('');
|
||||
});
|
||||
|
||||
it('should exclude disabled skills from all agent configs', () => {
|
||||
for (const agent of SUPPORTED_AGENTS) {
|
||||
const config = generateSkillsConfig(testSkills, agent);
|
||||
expect(config).not.toContain('skill-disabled');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Skill Translator - Utility Functions', () => {
|
||||
describe('getAgentSkillsDir', () => {
|
||||
it.each(SUPPORTED_AGENTS)('should return valid skills directory for %s', (agent) => {
|
||||
const dir = getAgentSkillsDir(agent);
|
||||
expect(typeof dir).toBe('string');
|
||||
expect(dir.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should return correct paths for major agents', () => {
|
||||
expect(getAgentSkillsDir('claude-code')).toBe('.claude/skills');
|
||||
expect(getAgentSkillsDir('cursor')).toBe('.cursor/skills');
|
||||
expect(getAgentSkillsDir('windsurf')).toBe('.windsurf/skills');
|
||||
expect(getAgentSkillsDir('github-copilot')).toBe('.github/skills');
|
||||
expect(getAgentSkillsDir('codex')).toBe('.codex/skills');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentConfigFile', () => {
|
||||
it.each(SUPPORTED_AGENTS)('should return valid config file for %s', (agent) => {
|
||||
const file = getAgentConfigFile(agent);
|
||||
expect(typeof file).toBe('string');
|
||||
expect(file.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should return correct config files for major agents', () => {
|
||||
expect(getAgentConfigFile('claude-code')).toBe('CLAUDE.md');
|
||||
expect(getAgentConfigFile('cursor')).toBe('.cursor/rules/skills.mdc');
|
||||
expect(getAgentConfigFile('windsurf')).toBe('.windsurf/rules/skills.md');
|
||||
expect(getAgentConfigFile('github-copilot')).toBe('.github/copilot-instructions.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AGENT_SKILL_FORMATS', () => {
|
||||
it('should have configuration for all supported agents', () => {
|
||||
for (const agent of SUPPORTED_AGENTS) {
|
||||
expect(AGENT_SKILL_FORMATS[agent]).toBeDefined();
|
||||
expect(AGENT_SKILL_FORMATS[agent].skillsDir).toBeTruthy();
|
||||
expect(AGENT_SKILL_FORMATS[agent].configFile).toBeTruthy();
|
||||
expect(AGENT_SKILL_FORMATS[agent].invokeCommand).toBe('skillkit read');
|
||||
}
|
||||
});
|
||||
|
||||
it('should have correct config formats for each agent', () => {
|
||||
expect(AGENT_SKILL_FORMATS['claude-code'].configFormat).toBe('xml');
|
||||
expect(AGENT_SKILL_FORMATS.cursor.configFormat).toBe('mdc');
|
||||
expect(AGENT_SKILL_FORMATS.windsurf.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS.codex.configFormat).toBe('markdown-table');
|
||||
expect(AGENT_SKILL_FORMATS['gemini-cli'].configFormat).toBe('json');
|
||||
expect(AGENT_SKILL_FORMATS['github-copilot'].configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS.trae.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS.roo.configFormat).toBe('xml');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Skill Translator - Complete Workflow', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir('skillkit-workflow-');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should complete full translation workflow from Claude Code to all agents', () => {
|
||||
// Create a Claude Code skill
|
||||
const skillDir = join(testDir, 'workflow-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: workflow-skill
|
||||
description: Complete workflow test skill
|
||||
version: "1.0.0"
|
||||
author: E2E Test Suite
|
||||
tags:
|
||||
- workflow
|
||||
- testing
|
||||
allowed-tools: Read, Write
|
||||
---
|
||||
# Workflow Test Skill
|
||||
|
||||
This skill tests the complete translation workflow.
|
||||
|
||||
## Instructions
|
||||
|
||||
1. Parse the SKILL.md file
|
||||
2. Translate to target agent format
|
||||
3. Write the translated skill
|
||||
4. Generate config
|
||||
|
||||
## Usage
|
||||
|
||||
Use \`skillkit read workflow-skill\` to load this skill.
|
||||
`);
|
||||
|
||||
// Step 1: Parse to canonical format
|
||||
const canonicalSkill = parseSkillToCanonical(skillDir);
|
||||
expect(canonicalSkill).not.toBeNull();
|
||||
expect(canonicalSkill?.name).toBe('workflow-skill');
|
||||
|
||||
// Step 2: Translate to all agents
|
||||
const translations = translateSkillToAll(skillDir, 'claude-code');
|
||||
expect(translations.size).toBeGreaterThan(0);
|
||||
|
||||
// Step 3: Verify translations for key agents
|
||||
const cursorTranslation = translations.get('cursor');
|
||||
expect(cursorTranslation?.success).toBe(true);
|
||||
expect(cursorTranslation?.content).toContain('workflow-skill');
|
||||
|
||||
const windsurfTranslation = translations.get('windsurf');
|
||||
expect(windsurfTranslation?.success).toBe(true);
|
||||
expect(windsurfTranslation?.content).toContain('workflow-skill');
|
||||
|
||||
const copilotTranslation = translations.get('github-copilot');
|
||||
expect(copilotTranslation?.success).toBe(true);
|
||||
expect(copilotTranslation?.content).toContain('workflow-skill');
|
||||
|
||||
// Step 4: Write a translation to disk
|
||||
const outputDir = join(testDir, 'output');
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
|
||||
if (cursorTranslation) {
|
||||
const writeResult = writeTranslatedSkill(cursorTranslation, outputDir);
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(writeResult.path)).toBe(true);
|
||||
}
|
||||
|
||||
// Step 5: Generate config for installed skills
|
||||
const installedSkills = [
|
||||
{ name: 'workflow-skill', description: 'Complete workflow test skill', path: skillDir, location: 'project' as const, enabled: true },
|
||||
];
|
||||
|
||||
const claudeConfig = generateSkillsConfig(installedSkills, 'claude-code');
|
||||
expect(claudeConfig).toContain('<name>workflow-skill</name>');
|
||||
|
||||
const cursorConfig = generateSkillsConfig(installedSkills, 'cursor');
|
||||
expect(cursorConfig).toContain('**workflow-skill**');
|
||||
});
|
||||
|
||||
it('should handle skill with agent-specific features during translation', () => {
|
||||
// Create a CrossAgentSkill directly with hooks in agentFields
|
||||
// This is more reliable than parsing from YAML
|
||||
const skillWithHooks: CrossAgentSkill = {
|
||||
name: 'agent-specific',
|
||||
description: 'Skill with agent-specific features',
|
||||
content: '# Agent Specific Skill\n\nThis skill has Claude Code specific features.',
|
||||
frontmatter: { name: 'agent-specific', description: 'Skill with agent-specific features' },
|
||||
sourcePath: join(testDir, 'agent-specific'),
|
||||
sourceAgent: 'claude-code',
|
||||
agentFields: {
|
||||
model: 'opus',
|
||||
context: 'fork',
|
||||
hooks: [
|
||||
{ type: 'PreToolUse', command: 'echo "Before tool use"' },
|
||||
{ type: 'PostToolUse', command: 'echo "After tool use"' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
// Translate to Claude Code (should preserve features)
|
||||
const claudeResult = translateSkillToAgent(skillWithHooks, 'claude-code');
|
||||
expect(claudeResult.success).toBe(true);
|
||||
expect(claudeResult.incompatible).toHaveLength(0);
|
||||
|
||||
// Translate to Cursor (should report incompatible features)
|
||||
const cursorResult = translateSkillToAgent(skillWithHooks, 'cursor');
|
||||
expect(cursorResult.success).toBe(true);
|
||||
// Hooks are not supported in Cursor
|
||||
expect(cursorResult.incompatible.some(i => i.includes('hooks'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should maintain content integrity across multiple translations', () => {
|
||||
const originalContent = `## Important Section
|
||||
|
||||
This content must be preserved exactly.
|
||||
|
||||
\`\`\`typescript
|
||||
const important = "code";
|
||||
console.log(important);
|
||||
\`\`\`
|
||||
|
||||
### Subsection
|
||||
|
||||
- Bullet point 1
|
||||
- Bullet point 2
|
||||
- Bullet point 3
|
||||
`;
|
||||
|
||||
const skillDir = join(testDir, 'content-integrity');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: content-integrity
|
||||
description: Tests content preservation
|
||||
---
|
||||
${originalContent}`);
|
||||
|
||||
const canonicalSkill = parseSkillToCanonical(skillDir);
|
||||
expect(canonicalSkill).not.toBeNull();
|
||||
|
||||
// Verify content is preserved in translations
|
||||
for (const agent of ['cursor', 'windsurf', 'github-copilot', 'codex'] as const) {
|
||||
const result = translateSkillToAgent(canonicalSkill!, agent);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('## Important Section');
|
||||
expect(result.content).toContain('const important = "code"');
|
||||
expect(result.content).toContain('- Bullet point 1');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,333 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Team Collaboration Features
|
||||
*
|
||||
* Tests for: team init, team share, team import, team list, team sync, team remove, team bundle-*
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Team Collaboration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create base project structure
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'team-skill-one', {
|
||||
description: 'First skill for team collaboration testing',
|
||||
});
|
||||
createTestSkill(join(testDir, 'skills'), 'team-skill-two', {
|
||||
description: 'Second skill for team collaboration testing',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit team init', () => {
|
||||
it('should initialize team configuration', async () => {
|
||||
const result = await runCli(['team', 'init'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must complete successfully and show relevant output
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should initialize team structure or report status
|
||||
const hasRelevantOutput =
|
||||
output.includes('team') ||
|
||||
output.includes('init') ||
|
||||
output.includes('created') ||
|
||||
testFileExists(testDir, '.skillkit/team.json') ||
|
||||
testFileExists(testDir, '.skillkit');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team init failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create team configuration file', async () => {
|
||||
const result = await runCli(
|
||||
['team', 'init', '--name', 'test-team', '--registry', 'local'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
// Check for team config in various possible locations
|
||||
const hasTeamConfig =
|
||||
testFileExists(testDir, '.skillkit/team.json') ||
|
||||
testFileExists(testDir, '.skillkit/team.yaml') ||
|
||||
testFileExists(testDir, 'team.json') ||
|
||||
testFileExists(testDir, '.skillkit');
|
||||
|
||||
// Strict assertion - either created config or command succeeded
|
||||
if (!hasTeamConfig && result.exitCode !== 0) {
|
||||
const output = result.stdout + result.stderr;
|
||||
expect.fail(`Team init did not create config. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasTeamConfig || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept team name option', async () => {
|
||||
const result = await runCli(['team', 'init', '--name', 'test-team'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team list', () => {
|
||||
it('should list team skills', async () => {
|
||||
// Initialize team first
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should list skills or indicate none
|
||||
const hasRelevantOutput =
|
||||
output.includes('skill') ||
|
||||
output.includes('team') ||
|
||||
output.includes('No') ||
|
||||
output.includes('empty');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
const result = await runCli(['team', 'list', '--json'], { cwd: testDir });
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team share', () => {
|
||||
it('should share a skill with team', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should share skill or report status
|
||||
const hasRelevantOutput =
|
||||
output.includes('share') ||
|
||||
output.includes('team-skill-one') ||
|
||||
output.includes('success') ||
|
||||
output.includes('added');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team share failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should share multiple skills', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'team-skill-one', 'team-skill-two'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle non-existent skill gracefully', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'nonexistent-skill'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should report error or warning about missing skill
|
||||
const showsError =
|
||||
output.includes('not found') ||
|
||||
output.includes('error') ||
|
||||
output.includes('No') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team sync', () => {
|
||||
it('should sync team skills', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'sync'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('sync') ||
|
||||
output.includes('team') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team sync failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should sync with specific agent', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team remove', () => {
|
||||
it('should remove a shared skill from team', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'remove', 'team-skill-one'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('remove') ||
|
||||
output.includes('team-skill-one') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team remove failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team import', () => {
|
||||
it('should import skills from team bundle', async () => {
|
||||
// Create a mock team bundle
|
||||
const bundleDir = join(testDir, 'team-bundle');
|
||||
mkdirSync(bundleDir, { recursive: true });
|
||||
createTestSkill(bundleDir, 'imported-skill', {
|
||||
description: 'A skill to be imported from a team bundle file',
|
||||
});
|
||||
|
||||
const result = await runCli(['team', 'import', bundleDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('import') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team import failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team bundle-*', () => {
|
||||
it('should create team bundle (bundle-create)', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const bundlePath = join(testDir, 'my-bundle.skillkit');
|
||||
const result = await runCli(['team', 'bundle-create', '--output', bundlePath], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should list bundle contents (bundle-list)', async () => {
|
||||
// Create a bundle first
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const bundlePath = join(testDir, 'test-bundle.skillkit');
|
||||
await runCli(['team', 'bundle-create', '--output', bundlePath], { cwd: testDir });
|
||||
|
||||
// Now list it
|
||||
const result = await runCli(['team', 'bundle-list', bundlePath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should extract bundle (bundle-extract)', async () => {
|
||||
// Create bundle
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const bundlePath = join(testDir, 'extract-bundle.skillkit');
|
||||
await runCli(['team', 'bundle-create', '--output', bundlePath], { cwd: testDir });
|
||||
|
||||
// Extract to new location
|
||||
const extractDir = join(testDir, 'extracted');
|
||||
const result = await runCli(['team', 'bundle-extract', bundlePath, '--output', extractDir], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Team Orchestration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'orchestration-skill', {
|
||||
description: 'A skill for testing multi-agent team orchestration features',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should configure team roles', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
// Configure team with roles
|
||||
const result = await runCli(['team', 'init', '--role', 'leader:claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should support multi-agent configuration', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(
|
||||
['team', 'init', '--agents', 'claude-code,cursor,github-copilot'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle team task delegation', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
// This tests the orchestration task feature if available
|
||||
const result = await runCli(['team', 'sync', '--all-agents'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -1,345 +0,0 @@
|
||||
/**
|
||||
* E2E Tests: Skill Translation Commands
|
||||
*
|
||||
* Tests for: translate, context, recommend
|
||||
* Validates translation to all 17 supported agents
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// All 17 supported agents
|
||||
const SUPPORTED_AGENTS = [
|
||||
'claude-code',
|
||||
'cursor',
|
||||
'codex',
|
||||
'gemini-cli',
|
||||
'opencode',
|
||||
'antigravity',
|
||||
'amp',
|
||||
'clawdbot',
|
||||
'droid',
|
||||
'github-copilot',
|
||||
'goose',
|
||||
'kilo',
|
||||
'kiro-cli',
|
||||
'roo',
|
||||
'trae',
|
||||
'windsurf',
|
||||
'universal',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Skill Translation', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a skill for translation tests
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'translation-test', {
|
||||
description: 'A skill designed for testing translation across multiple AI coding agents',
|
||||
content: `## Usage
|
||||
|
||||
Run this command to test the skill:
|
||||
|
||||
\`\`\`bash
|
||||
npm test
|
||||
\`\`\`
|
||||
|
||||
## Features
|
||||
|
||||
- Feature A: Does something useful
|
||||
- Feature B: Does something else
|
||||
`,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit translate', () => {
|
||||
it('should translate skill to claude-code format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should complete translation or show relevant output
|
||||
expect(
|
||||
output.includes('claude') ||
|
||||
output.includes('translate') ||
|
||||
output.includes('CLAUDE.md') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to cursor format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'cursor'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('cursor') ||
|
||||
output.includes('.cursorrules') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to windsurf format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'windsurf'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('windsurf') ||
|
||||
output.includes('.windsurfrules') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to github-copilot format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'github-copilot'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('copilot') ||
|
||||
output.includes('.github') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support universal format for all agents', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'universal'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
// Test all agents can at least attempt translation
|
||||
describe.each(SUPPORTED_AGENTS)('translation to %s', (agent) => {
|
||||
it(`should handle translation to ${agent}`, async () => {
|
||||
const result = await runCli(['translate', '--agent', agent], { cwd: testDir });
|
||||
// Should not crash - either succeeds or reports error gracefully
|
||||
expect(result.exitCode).toBeDefined();
|
||||
expect(typeof result.stdout).toBe('string');
|
||||
expect(typeof result.stderr).toBe('string');
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle unknown agent gracefully', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'nonexistent-agent'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should report error about unknown agent
|
||||
expect(
|
||||
output.toLowerCase().includes('unknown') ||
|
||||
output.toLowerCase().includes('not supported') ||
|
||||
output.toLowerCase().includes('invalid') ||
|
||||
output.toLowerCase().includes('error') ||
|
||||
!result.success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate with --output option', async () => {
|
||||
const outputPath = join(testDir, 'translated-output');
|
||||
mkdirSync(outputPath, { recursive: true });
|
||||
|
||||
const result = await runCli(['translate', '--agent', 'claude-code', '--output', outputPath], {
|
||||
cwd: testDir,
|
||||
});
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should translate with --dry-run option', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'cursor', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
// Dry run should show what would be done without making changes
|
||||
expect(result.exitCode !== undefined || output.length > 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit context', () => {
|
||||
it('should detect project context', async () => {
|
||||
// Create a Node.js project
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'test-project',
|
||||
version: '1.0.0',
|
||||
dependencies: { express: '^4.18.0' },
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should detect the project type
|
||||
expect(
|
||||
output.includes('node') ||
|
||||
output.includes('javascript') ||
|
||||
output.includes('typescript') ||
|
||||
output.includes('context') ||
|
||||
output.includes('project') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Python project', async () => {
|
||||
// Create a Python project
|
||||
writeFileSync(join(testDir, 'requirements.txt'), 'flask>=2.0.0\npytest>=7.0.0\n');
|
||||
writeFileSync(join(testDir, 'main.py'), 'print("Hello")\n');
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('python') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Rust project', async () => {
|
||||
// Create a Rust project
|
||||
writeFileSync(
|
||||
join(testDir, 'Cargo.toml'),
|
||||
'[package]\nname = "test"\nversion = "0.1.0"\nedition = "2021"'
|
||||
);
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('rust') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Go project', async () => {
|
||||
// Create a Go project
|
||||
writeFileSync(join(testDir, 'go.mod'), 'module example.com/test\n\ngo 1.21');
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('go') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(['context', '--json'], { cwd: testDir });
|
||||
// If JSON is supported, should be parseable
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit recommend', () => {
|
||||
it('should recommend skills for a project', async () => {
|
||||
// Create a Node.js project with common patterns
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'web-app',
|
||||
version: '1.0.0',
|
||||
dependencies: {
|
||||
express: '^4.18.0',
|
||||
typescript: '^5.0.0',
|
||||
jest: '^29.0.0',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
const result = await runCli(['recommend'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should provide recommendations or indicate none available
|
||||
expect(
|
||||
output.includes('recommend') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('suggest') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle empty project gracefully', async () => {
|
||||
const result = await runCli(['recommend'], { cwd: testDir });
|
||||
// Should not crash
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --limit option', async () => {
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(['recommend', '--limit', '5'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Agent Config Generation', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'config-test-skill', {
|
||||
description: 'A skill for testing agent configuration generation across all agents',
|
||||
additionalFrontmatter: {
|
||||
'allowed-tools': 'Bash(npm:*) Read Write Edit',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should generate valid claude-code config (CLAUDE.md)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
// Check if CLAUDE.md was created or would be created
|
||||
const claudeMdExists = testFileExists(testDir, 'CLAUDE.md');
|
||||
expect(result.exitCode !== undefined || claudeMdExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate valid cursor config (.cursorrules)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'cursor'], { cwd: testDir });
|
||||
const cursorRulesExists = testFileExists(testDir, '.cursorrules');
|
||||
expect(result.exitCode !== undefined || cursorRulesExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate valid windsurf config (.windsurfrules)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'windsurf'], { cwd: testDir });
|
||||
const windsurfRulesExists = testFileExists(testDir, '.windsurfrules');
|
||||
expect(result.exitCode !== undefined || windsurfRulesExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should preserve allowed-tools in translation', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Output or generated file should mention tools
|
||||
expect(
|
||||
output.includes('tool') ||
|
||||
output.includes('Bash') ||
|
||||
output.includes('permission') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": false,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"types": ["node", "vitest/globals"]
|
||||
},
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['**/*.e2e.test.ts'],
|
||||
testTimeout: 60000, // E2E tests need more time
|
||||
hookTimeout: 30000,
|
||||
retry: 1, // Retry failed tests once for flaky network/fs operations
|
||||
sequence: {
|
||||
shuffle: false, // Run tests in order for debugging
|
||||
},
|
||||
pool: 'forks', // Use forks for better isolation
|
||||
poolOptions: {
|
||||
forks: {
|
||||
singleFork: false,
|
||||
isolate: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@skillkit/core': resolve(__dirname, '../packages/core/src/index.ts'),
|
||||
'@skillkit/agents': resolve(__dirname, '../packages/agents/src/index.ts'),
|
||||
},
|
||||
},
|
||||
});
|
||||
Generated
+1822
-108
File diff suppressed because it is too large
Load Diff
+1
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "skillkit-monorepo",
|
||||
"version": "1.6.4",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"description": "Universal skills loader for AI coding agents - Monorepo",
|
||||
"type": "module",
|
||||
@@ -10,9 +10,6 @@
|
||||
"test": "turbo run test",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "vitest run --config e2e/vitest.config.ts",
|
||||
"test:e2e:watch": "vitest --config e2e/vitest.config.ts",
|
||||
"test:all": "pnpm test && pnpm test:e2e",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "turbo run lint",
|
||||
"clean": "rm -rf node_modules packages/*/node_modules apps/*/node_modules packages/*/dist apps/*/dist"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/agents",
|
||||
"version": "1.6.4",
|
||||
"version": "1.5.0",
|
||||
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -1,412 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { ClawdbotAdapter } from '../clawdbot.js';
|
||||
import type { Skill } from '@skillkit/core';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
// Mock filesystem functions
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('ClawdbotAdapter', () => {
|
||||
let adapter: ClawdbotAdapter;
|
||||
const mockExistsSync = vi.mocked(existsSync);
|
||||
|
||||
beforeEach(() => {
|
||||
adapter = new ClawdbotAdapter();
|
||||
mockExistsSync.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('configuration', () => {
|
||||
it('should have correct type', () => {
|
||||
expect(adapter.type).toBe('clawdbot');
|
||||
});
|
||||
|
||||
it('should have correct name', () => {
|
||||
expect(adapter.name).toBe('Clawdbot');
|
||||
});
|
||||
|
||||
it('should have correct skillsDir', () => {
|
||||
expect(adapter.skillsDir).toBe('.clawdbot/skills');
|
||||
});
|
||||
|
||||
it('should have correct configFile', () => {
|
||||
expect(adapter.configFile).toBe('AGENTS.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateConfig', () => {
|
||||
it('should return empty string for no enabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: false,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
expect(config).toBe('');
|
||||
});
|
||||
|
||||
it('should generate config with enabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
description: 'A test skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<skills_system priority="1">');
|
||||
expect(config).toContain('## Available Skills');
|
||||
expect(config).toContain('<name>test-skill</name>');
|
||||
expect(config).toContain('<description>A test skill</description>');
|
||||
expect(config).toContain('skillkit read <skill-name>');
|
||||
});
|
||||
|
||||
it('should generate config with multiple skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'skill-1',
|
||||
description: 'First skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill1',
|
||||
content: '# Skill 1',
|
||||
},
|
||||
{
|
||||
name: 'skill-2',
|
||||
description: 'Second skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill2',
|
||||
content: '# Skill 2',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>skill-1</name>');
|
||||
expect(config).toContain('<name>skill-2</name>');
|
||||
expect(config).toContain('<description>First skill</description>');
|
||||
expect(config).toContain('<description>Second skill</description>');
|
||||
});
|
||||
|
||||
it('should filter out disabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'enabled-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/enabled',
|
||||
content: '# Enabled',
|
||||
},
|
||||
{
|
||||
name: 'disabled-skill',
|
||||
enabled: false,
|
||||
path: '/path/to/disabled',
|
||||
content: '# Disabled',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('enabled-skill');
|
||||
expect(config).not.toContain('disabled-skill');
|
||||
});
|
||||
|
||||
it('should include usage notes', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<usage>');
|
||||
expect(config).toContain('When users ask you to perform tasks');
|
||||
expect(config).toContain('How to use skills:');
|
||||
expect(config).toContain('- Invoke:');
|
||||
expect(config).toContain('Usage notes:');
|
||||
});
|
||||
|
||||
it('should include available_skills section', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<available_skills>');
|
||||
expect(config).toContain('</available_skills>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseConfig', () => {
|
||||
it('should parse skill names from config', () => {
|
||||
const config = `
|
||||
<skills_system>
|
||||
<available_skills>
|
||||
<skill>
|
||||
<name>skill-1</name>
|
||||
<description>Test skill 1</description>
|
||||
</skill>
|
||||
<skill>
|
||||
<name>skill-2</name>
|
||||
<description>Test skill 2</description>
|
||||
</skill>
|
||||
</available_skills>
|
||||
</skills_system>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-1', 'skill-2']);
|
||||
});
|
||||
|
||||
it('should return empty array for no skills', () => {
|
||||
const config = '<skills_system></skills_system>';
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle whitespace in skill names', () => {
|
||||
const config = `
|
||||
<skill>
|
||||
<name> skill-with-spaces </name>
|
||||
</skill>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-with-spaces']);
|
||||
});
|
||||
|
||||
it('should handle multiple name tags', () => {
|
||||
const config = `
|
||||
<name>skill-1</name>
|
||||
<name>skill-2</name>
|
||||
<name>skill-3</name>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-1', 'skill-2', 'skill-3']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInvokeCommand', () => {
|
||||
it('should return correct invoke command', () => {
|
||||
const command = adapter.getInvokeCommand('test-skill');
|
||||
|
||||
expect(command).toBe('skillkit read test-skill');
|
||||
});
|
||||
|
||||
it('should work with skill names containing hyphens', () => {
|
||||
const command = adapter.getInvokeCommand('my-test-skill');
|
||||
|
||||
expect(command).toBe('skillkit read my-test-skill');
|
||||
});
|
||||
|
||||
it('should work with skill names containing underscores', () => {
|
||||
const command = adapter.getInvokeCommand('my_test_skill');
|
||||
|
||||
expect(command).toBe('skillkit read my_test_skill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDetected', () => {
|
||||
it('should detect Clawdbot from workspace skills directory', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(process.cwd(), 'skills');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Clawdbot from global directory', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(homedir(), '.clawdbot');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Clawdbot from config file', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(process.cwd(), 'clawdbot.json');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should not detect Clawdbot when no indicators present', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect when multiple indicators are present', async () => {
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should check all expected paths', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
|
||||
await adapter.isDetected();
|
||||
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(process.cwd(), 'skills'));
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(homedir(), '.clawdbot'));
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(process.cwd(), 'clawdbot.json'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('integration', () => {
|
||||
it('should work end-to-end with typical workflow', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'react-patterns',
|
||||
description: 'React best practices',
|
||||
enabled: true,
|
||||
path: '/skills/react-patterns',
|
||||
content: '# React Patterns\n\nBest practices...',
|
||||
},
|
||||
{
|
||||
name: 'typescript-strict',
|
||||
description: 'TypeScript strict mode',
|
||||
enabled: true,
|
||||
path: '/skills/typescript-strict',
|
||||
content: '# TypeScript Strict\n\nUse strict mode...',
|
||||
},
|
||||
];
|
||||
|
||||
// Generate config
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
// Parse config
|
||||
const parsedSkills = adapter.parseConfig(config);
|
||||
|
||||
// Verify round-trip
|
||||
expect(parsedSkills).toEqual(['react-patterns', 'typescript-strict']);
|
||||
|
||||
// Get invoke commands
|
||||
const command1 = adapter.getInvokeCommand('react-patterns');
|
||||
const command2 = adapter.getInvokeCommand('typescript-strict');
|
||||
|
||||
expect(command1).toBe('skillkit read react-patterns');
|
||||
expect(command2).toBe('skillkit read typescript-strict');
|
||||
});
|
||||
|
||||
it('should preserve skill order during generation and parsing', () => {
|
||||
const skills: Skill[] = [
|
||||
{ name: 'a-skill', enabled: true, path: '/a', content: '' },
|
||||
{ name: 'z-skill', enabled: true, path: '/z', content: '' },
|
||||
{ name: 'm-skill', enabled: true, path: '/m', content: '' },
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
const parsed = adapter.parseConfig(config);
|
||||
|
||||
expect(parsed).toEqual(['a-skill', 'z-skill', 'm-skill']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle empty skills array', () => {
|
||||
const config = adapter.generateConfig([]);
|
||||
expect(config).toBe('');
|
||||
});
|
||||
|
||||
it('should handle skills without descriptions', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'no-desc-skill',
|
||||
enabled: true,
|
||||
path: '/path',
|
||||
content: '# No description',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>no-desc-skill</name>');
|
||||
expect(config).toContain('<description></description>');
|
||||
});
|
||||
|
||||
it('should handle special characters in skill names', () => {
|
||||
const command = adapter.getInvokeCommand('skill-with-special_chars.123');
|
||||
|
||||
expect(command).toBe('skillkit read skill-with-special_chars.123');
|
||||
});
|
||||
|
||||
it('should handle empty config string during parsing', () => {
|
||||
const parsed = adapter.parseConfig('');
|
||||
|
||||
expect(parsed).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle malformed XML during parsing', () => {
|
||||
const config = '<name>skill-1<name>broken</name>';
|
||||
|
||||
const parsed = adapter.parseConfig(config);
|
||||
|
||||
// Should still extract valid names
|
||||
expect(parsed).toContain('broken');
|
||||
});
|
||||
});
|
||||
|
||||
describe('metadata handling', () => {
|
||||
it('should include skill metadata in generated config', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'meta-skill',
|
||||
description: 'Has metadata',
|
||||
enabled: true,
|
||||
path: '/path',
|
||||
content: '# Meta',
|
||||
metadata: {
|
||||
version: '1.0.0',
|
||||
author: 'Test Author',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>meta-skill</name>');
|
||||
expect(config).toContain('<description>Has metadata</description>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.amp;
|
||||
|
||||
export class AmpAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'amp';
|
||||
readonly name = 'Amp';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.agents/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -69,9 +66,9 @@ ${skillsXml}
|
||||
}
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectAmp = join(process.cwd(), '.amp');
|
||||
const globalAmp = join(homedir(), '.amp');
|
||||
const projectAgents = join(process.cwd(), '.agents');
|
||||
const globalAgents = join(homedir(), '.config', 'agents');
|
||||
|
||||
return existsSync(projectAmp) || existsSync(globalAmp);
|
||||
return existsSync(projectAgents) || existsSync(globalAgents);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,12 @@ import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.antigravity;
|
||||
|
||||
export class AntigravityAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'antigravity';
|
||||
readonly name = 'Antigravity';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.antigravity/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -20,8 +20,7 @@ export function createSkillXml(skill: Skill): string {
|
||||
</skill>`;
|
||||
}
|
||||
|
||||
export function escapeXml(text: string | undefined): string {
|
||||
if (!text) return '';
|
||||
export function escapeXml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG['claude-code'];
|
||||
|
||||
export class ClaudeCodeAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'claude-code';
|
||||
readonly name = 'Claude Code';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.claude/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.clawdbot;
|
||||
|
||||
export class ClawdbotAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'clawdbot';
|
||||
readonly name = 'Clawdbot';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = 'skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -71,8 +68,7 @@ ${skillsXml}
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectSkills = join(process.cwd(), 'skills');
|
||||
const globalClawdbot = join(homedir(), '.clawdbot');
|
||||
const clawdbotConfig = join(process.cwd(), 'clawdbot.json');
|
||||
|
||||
return existsSync(projectSkills) || existsSync(globalClawdbot) || existsSync(clawdbotConfig);
|
||||
return existsSync(globalClawdbot) || (existsSync(projectSkills) && existsSync(join(process.cwd(), '.clawdbot')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,12 @@ import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.codex;
|
||||
|
||||
export class CodexAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'codex';
|
||||
readonly name = 'OpenAI Codex CLI';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.codex/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.cursor;
|
||||
|
||||
export class CursorAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'cursor';
|
||||
readonly name = 'Cursor';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.cursor/skills';
|
||||
readonly configFile = '.cursorrules';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -27,12 +23,7 @@ export class CursorAdapter implements AgentAdapter {
|
||||
|
||||
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
|
||||
|
||||
return `---
|
||||
description: SkillKit skills integration - provides specialized capabilities and domain knowledge
|
||||
globs: "**/*"
|
||||
alwaysApply: true
|
||||
---
|
||||
# Skills System
|
||||
return `# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed.
|
||||
|
||||
@@ -72,14 +63,9 @@ ${skillsXml}
|
||||
}
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const cursorRules = join(process.cwd(), '.cursorrules');
|
||||
const cursorDir = join(process.cwd(), '.cursor');
|
||||
const cursorRulesDir = join(process.cwd(), '.cursor', 'rules');
|
||||
// Legacy .cursorrules file (deprecated but still supported)
|
||||
const cursorRulesFile = join(process.cwd(), '.cursorrules');
|
||||
// Global Cursor config
|
||||
const globalCursor = join(homedir(), '.cursor');
|
||||
|
||||
return existsSync(cursorDir) || existsSync(cursorRulesDir) ||
|
||||
existsSync(cursorRulesFile) || existsSync(globalCursor);
|
||||
return existsSync(cursorRules) || existsSync(cursorDir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.droid;
|
||||
|
||||
export class DroidAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'droid';
|
||||
readonly name = 'Droid (Factory)';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.factory/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -3,15 +3,12 @@ import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG['gemini-cli'];
|
||||
|
||||
export class GeminiCliAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'gemini-cli';
|
||||
readonly name = 'Gemini CLI';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.gemini/skills';
|
||||
readonly configFile = 'GEMINI.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -67,7 +64,7 @@ ${JSON.stringify(skillsJson, null, 2)}
|
||||
}
|
||||
|
||||
if (skillNames.length === 0) {
|
||||
const headerRegex = /^###\s+(.+?)\s*$/gm;
|
||||
const headerRegex = /^### ([a-z0-9-]+)$/gm;
|
||||
let match;
|
||||
while ((match = headerRegex.exec(content)) !== null) {
|
||||
skillNames.push(match[1].trim());
|
||||
|
||||
@@ -2,16 +2,14 @@ import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG['github-copilot'];
|
||||
|
||||
export class GitHubCopilotAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'github-copilot';
|
||||
readonly name = 'GitHub Copilot';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.github/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -20,38 +18,43 @@ export class GitHubCopilotAdapter implements AgentAdapter {
|
||||
return '';
|
||||
}
|
||||
|
||||
const skillsList = enabledSkills
|
||||
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
|
||||
.join('\n\n');
|
||||
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
|
||||
|
||||
return `# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks.
|
||||
Skills provide domain-specific knowledge and step-by-step instructions.
|
||||
return `<skills_system priority="1">
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skillsList}
|
||||
<!-- SKILLS_TABLE_START -->
|
||||
<usage>
|
||||
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
||||
|
||||
## How to Use Skills
|
||||
How to use skills:
|
||||
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
|
||||
- The skill content will load with detailed instructions on how to complete the task
|
||||
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
|
||||
|
||||
When a task matches a skill's description, load it using the terminal:
|
||||
Usage notes:
|
||||
- Only use skills listed in <available_skills> below
|
||||
- Do not invoke a skill that is already loaded in your context
|
||||
- Each skill invocation is stateless
|
||||
</usage>
|
||||
|
||||
\`\`\`bash
|
||||
skillkit read <skill-name>
|
||||
\`\`\`
|
||||
<available_skills>
|
||||
|
||||
The skill content will load with detailed instructions.
|
||||
Each skill is self-contained with its own resources.
|
||||
`;
|
||||
${skillsXml}
|
||||
|
||||
</available_skills>
|
||||
<!-- SKILLS_TABLE_END -->
|
||||
|
||||
</skills_system>`;
|
||||
}
|
||||
|
||||
parseConfig(content: string): string[] {
|
||||
const skillNames: string[] = [];
|
||||
const headerRegex = /^###\s+(.+?)\s*$/gm;
|
||||
const skillRegex = /<name>([^<]+)<\/name>/g;
|
||||
let match;
|
||||
|
||||
while ((match = headerRegex.exec(content)) !== null) {
|
||||
while ((match = skillRegex.exec(content)) !== null) {
|
||||
skillNames.push(match[1].trim());
|
||||
}
|
||||
|
||||
@@ -63,11 +66,9 @@ Each skill is self-contained with its own resources.
|
||||
}
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const copilotInstructions = join(process.cwd(), '.github', 'copilot-instructions.md');
|
||||
const githubInstructions = join(process.cwd(), '.github', 'instructions');
|
||||
const projectGithub = join(process.cwd(), '.github', 'skills');
|
||||
const globalCopilot = join(homedir(), '.copilot');
|
||||
|
||||
return existsSync(copilotInstructions) ||
|
||||
existsSync(githubInstructions) || existsSync(globalCopilot);
|
||||
return existsSync(projectGithub) || existsSync(globalCopilot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.goose;
|
||||
|
||||
export class GooseAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'goose';
|
||||
readonly name = 'Goose';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.goose/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -99,5 +99,10 @@ export async function detectAgent(): Promise<AgentType> {
|
||||
return 'universal';
|
||||
}
|
||||
|
||||
// getSkillsDir and getConfigFile are now re-exported from @skillkit/core above
|
||||
// This ensures a single source of truth for agent configurations
|
||||
export function getSkillsDir(type: AgentType): string {
|
||||
return adapters[type].skillsDir;
|
||||
}
|
||||
|
||||
export function getConfigFile(type: AgentType): string {
|
||||
return adapters[type].configFile;
|
||||
}
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.kilo;
|
||||
|
||||
export class KiloAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'kilo';
|
||||
readonly name = 'Kilo Code';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.kilocode/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -71,8 +68,7 @@ ${skillsXml}
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectKilo = join(process.cwd(), '.kilocode');
|
||||
const globalKilo = join(homedir(), '.kilocode');
|
||||
const kiloModes = join(process.cwd(), '.kilocode', 'modes');
|
||||
|
||||
return existsSync(projectKilo) || existsSync(globalKilo) || existsSync(kiloModes);
|
||||
return existsSync(projectKilo) || existsSync(globalKilo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG['kiro-cli'];
|
||||
|
||||
export class KiroCliAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'kiro-cli';
|
||||
readonly name = 'Kiro CLI';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.kiro/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.opencode;
|
||||
|
||||
export class OpenCodeAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'opencode';
|
||||
readonly name = 'OpenCode';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.opencode/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -63,10 +60,8 @@ This loads the skill's instructions into context.
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const opencodeDir = join(process.cwd(), '.opencode');
|
||||
const globalOpencode = join(homedir(), '.config', 'opencode');
|
||||
const opencodeJson = join(process.cwd(), 'opencode.json');
|
||||
const globalOpencode = join(homedir(), '.opencode');
|
||||
|
||||
return existsSync(opencodeDir) || existsSync(globalOpencode) ||
|
||||
existsSync(opencodeJson);
|
||||
return existsSync(opencodeDir) || existsSync(globalOpencode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,12 @@ import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.roo;
|
||||
|
||||
export class RooAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'roo';
|
||||
readonly name = 'Roo Code';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.roo/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -71,8 +68,7 @@ ${skillsXml}
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectRoo = join(process.cwd(), '.roo');
|
||||
const globalRoo = join(homedir(), '.roo');
|
||||
const rooModes = join(process.cwd(), '.roo', 'modes');
|
||||
|
||||
return existsSync(projectRoo) || existsSync(globalRoo) || existsSync(rooModes);
|
||||
return existsSync(projectRoo) || existsSync(globalRoo);
|
||||
}
|
||||
}
|
||||
|
||||
+27
-29
@@ -2,16 +2,14 @@ import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.trae;
|
||||
|
||||
export class TraeAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'trae';
|
||||
readonly name = 'Trae';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.trae/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -20,42 +18,43 @@ export class TraeAdapter implements AgentAdapter {
|
||||
return '';
|
||||
}
|
||||
|
||||
const skillsList = enabledSkills
|
||||
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
|
||||
.join('\n\n');
|
||||
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
|
||||
|
||||
return `---
|
||||
alwaysApply: true
|
||||
description: SkillKit skills integration for Trae
|
||||
globs: ["**/*"]
|
||||
---
|
||||
# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks.
|
||||
When a task matches a skill's description, load it using the skillkit CLI.
|
||||
return `<skills_system priority="1">
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skillsList}
|
||||
<!-- SKILLS_TABLE_START -->
|
||||
<usage>
|
||||
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
||||
|
||||
## How to Use Skills
|
||||
How to use skills:
|
||||
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
|
||||
- The skill content will load with detailed instructions on how to complete the task
|
||||
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
|
||||
|
||||
When a task matches a skill's description, load it:
|
||||
Usage notes:
|
||||
- Only use skills listed in <available_skills> below
|
||||
- Do not invoke a skill that is already loaded in your context
|
||||
- Each skill invocation is stateless
|
||||
</usage>
|
||||
|
||||
\`\`\`bash
|
||||
skillkit read <skill-name>
|
||||
\`\`\`
|
||||
<available_skills>
|
||||
|
||||
Skills provide detailed instructions for completing complex tasks.
|
||||
`;
|
||||
${skillsXml}
|
||||
|
||||
</available_skills>
|
||||
<!-- SKILLS_TABLE_END -->
|
||||
|
||||
</skills_system>`;
|
||||
}
|
||||
|
||||
parseConfig(content: string): string[] {
|
||||
const skillNames: string[] = [];
|
||||
const headerRegex = /^###\s+(.+?)\s*$/gm;
|
||||
const skillRegex = /<name>([^<]+)<\/name>/g;
|
||||
let match;
|
||||
|
||||
while ((match = headerRegex.exec(content)) !== null) {
|
||||
while ((match = skillRegex.exec(content)) !== null) {
|
||||
skillNames.push(match[1].trim());
|
||||
}
|
||||
|
||||
@@ -68,9 +67,8 @@ Skills provide detailed instructions for completing complex tasks.
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectTrae = join(process.cwd(), '.trae');
|
||||
const traeRulesDir = join(process.cwd(), '.trae', 'rules');
|
||||
const globalTrae = join(homedir(), '.trae');
|
||||
|
||||
return existsSync(projectTrae) || existsSync(traeRulesDir) || existsSync(globalTrae);
|
||||
return existsSync(projectTrae) || existsSync(globalTrae);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,12 @@ import { join } from 'node:path';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.universal;
|
||||
|
||||
export class UniversalAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'universal';
|
||||
readonly name = 'Universal (Any Agent)';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.agent/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
@@ -2,16 +2,14 @@ import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type { AgentAdapter } from './base.js';
|
||||
import { createSkillXml } from './base.js';
|
||||
import type { Skill, AgentType } from '@skillkit/core';
|
||||
import { AGENT_CONFIG } from '@skillkit/core';
|
||||
|
||||
const config = AGENT_CONFIG.windsurf;
|
||||
|
||||
export class WindsurfAdapter implements AgentAdapter {
|
||||
readonly type: AgentType = 'windsurf';
|
||||
readonly name = 'Windsurf';
|
||||
readonly skillsDir = config.skillsDir;
|
||||
readonly configFile = config.configFile;
|
||||
readonly skillsDir = '.windsurf/skills';
|
||||
readonly configFile = 'AGENTS.md';
|
||||
|
||||
generateConfig(skills: Skill[]): string {
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
@@ -20,42 +18,43 @@ export class WindsurfAdapter implements AgentAdapter {
|
||||
return '';
|
||||
}
|
||||
|
||||
const skillsList = enabledSkills
|
||||
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
|
||||
.join('\n\n');
|
||||
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
|
||||
|
||||
return `---
|
||||
name: "skillkit-skills"
|
||||
mode: "model-decision"
|
||||
---
|
||||
# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks.
|
||||
When a task matches a skill's description, load it using the skillkit CLI.
|
||||
return `<skills_system priority="1">
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skillsList}
|
||||
<!-- SKILLS_TABLE_START -->
|
||||
<usage>
|
||||
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
||||
|
||||
## How to Use Skills
|
||||
How to use skills:
|
||||
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
|
||||
- The skill content will load with detailed instructions on how to complete the task
|
||||
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
|
||||
|
||||
When a task matches a skill's description, load it:
|
||||
Usage notes:
|
||||
- Only use skills listed in <available_skills> below
|
||||
- Do not invoke a skill that is already loaded in your context
|
||||
- Each skill invocation is stateless
|
||||
</usage>
|
||||
|
||||
\`\`\`bash
|
||||
skillkit read <skill-name>
|
||||
\`\`\`
|
||||
<available_skills>
|
||||
|
||||
Skills provide detailed instructions for completing complex tasks.
|
||||
Each skill is self-contained with its own resources.
|
||||
`;
|
||||
${skillsXml}
|
||||
|
||||
</available_skills>
|
||||
<!-- SKILLS_TABLE_END -->
|
||||
|
||||
</skills_system>`;
|
||||
}
|
||||
|
||||
parseConfig(content: string): string[] {
|
||||
const skillNames: string[] = [];
|
||||
const headerRegex = /^###\s+(.+?)\s*$/gm;
|
||||
const skillRegex = /<name>([^<]+)<\/name>/g;
|
||||
let match;
|
||||
|
||||
while ((match = headerRegex.exec(content)) !== null) {
|
||||
while ((match = skillRegex.exec(content)) !== null) {
|
||||
skillNames.push(match[1].trim());
|
||||
}
|
||||
|
||||
@@ -68,10 +67,8 @@ Each skill is self-contained with its own resources.
|
||||
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectWindsurf = join(process.cwd(), '.windsurf');
|
||||
const projectRulesDir = join(process.cwd(), '.windsurf', 'rules');
|
||||
const globalWindsurf = join(homedir(), '.codeium', 'windsurf');
|
||||
|
||||
return existsSync(projectWindsurf) || existsSync(projectRulesDir) ||
|
||||
existsSync(globalWindsurf);
|
||||
return existsSync(projectWindsurf) || existsSync(globalWindsurf);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/cli",
|
||||
"version": "1.6.4",
|
||||
"version": "1.5.0",
|
||||
"description": "CLI commands for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -1,631 +0,0 @@
|
||||
/**
|
||||
* Agent Command
|
||||
*
|
||||
* Manage custom AI sub-agents (e.g., .claude/agents/*.md)
|
||||
*/
|
||||
|
||||
import chalk from 'chalk';
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import {
|
||||
findAllAgents,
|
||||
findAgent,
|
||||
discoverAgents,
|
||||
discoverAgentsFromPath,
|
||||
validateAgent,
|
||||
translateAgent,
|
||||
getAgentTargetDirectory,
|
||||
type CustomAgent,
|
||||
type AgentType,
|
||||
} from '@skillkit/core';
|
||||
// Agent discovery uses root directories, not skill directories
|
||||
|
||||
export class AgentCommand extends Command {
|
||||
static override paths = [['agent']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage custom AI sub-agents',
|
||||
details: `
|
||||
This command manages custom AI sub-agents that can be used with
|
||||
Claude Code, Cursor, and other AI coding agents.
|
||||
|
||||
Agents are specialized personas (like architects, testers, reviewers)
|
||||
that can be invoked with @mentions or the --agent flag.
|
||||
|
||||
Sub-commands:
|
||||
agent list - List all installed agents
|
||||
agent show - Show agent details
|
||||
agent create - Create a new agent
|
||||
agent translate - Translate agents between formats
|
||||
agent sync - Sync agents to target AI agent
|
||||
agent validate - Validate agent definitions
|
||||
`,
|
||||
examples: [
|
||||
['List all agents', '$0 agent list'],
|
||||
['Show agent details', '$0 agent show architect'],
|
||||
['Create new agent', '$0 agent create security-reviewer'],
|
||||
['Translate to Cursor format', '$0 agent translate --to cursor'],
|
||||
['Sync agents', '$0 agent sync --agent claude-code'],
|
||||
],
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
console.log(chalk.cyan('Agent management commands:\n'));
|
||||
console.log(' agent list List all installed agents');
|
||||
console.log(' agent show <name> Show agent details');
|
||||
console.log(' agent create <name> Create a new agent');
|
||||
console.log(' agent translate Translate agents between formats');
|
||||
console.log(' agent sync Sync agents to target AI agent');
|
||||
console.log(' agent validate [path] Validate agent definitions');
|
||||
console.log();
|
||||
console.log(chalk.dim('Run `skillkit agent <subcommand> --help` for more info'));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentListCommand extends Command {
|
||||
static override paths = [['agent', 'list'], ['agent', 'ls']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'List all installed agents',
|
||||
examples: [
|
||||
['List all agents', '$0 agent list'],
|
||||
['Show JSON output', '$0 agent list --json'],
|
||||
['Show only project agents', '$0 agent list --project'],
|
||||
],
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
project = Option.Boolean('--project,-p', false, {
|
||||
description: 'Show only project agents',
|
||||
});
|
||||
|
||||
global = Option.Boolean('--global,-g', false, {
|
||||
description: 'Show only global agents',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const searchDirs = [process.cwd()];
|
||||
let agents = findAllAgents(searchDirs);
|
||||
|
||||
if (this.project) {
|
||||
agents = agents.filter((a: CustomAgent) => a.location === 'project');
|
||||
} else if (this.global) {
|
||||
agents = agents.filter((a: CustomAgent) => a.location === 'global');
|
||||
}
|
||||
|
||||
agents.sort((a: CustomAgent, b: CustomAgent) => {
|
||||
if (a.location !== b.location) {
|
||||
return a.location === 'project' ? -1 : 1;
|
||||
}
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(agents.map((a: CustomAgent) => ({
|
||||
name: a.name,
|
||||
description: a.description,
|
||||
path: a.path,
|
||||
location: a.location,
|
||||
enabled: a.enabled,
|
||||
model: a.frontmatter.model,
|
||||
permissionMode: a.frontmatter.permissionMode,
|
||||
})), null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (agents.length === 0) {
|
||||
console.log(chalk.yellow('No agents found'));
|
||||
console.log(chalk.dim('Create an agent with: skillkit agent create <name>'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Installed agents (${agents.length}):\n`));
|
||||
|
||||
const projectAgents = agents.filter((a: CustomAgent) => a.location === 'project');
|
||||
const globalAgents = agents.filter((a: CustomAgent) => a.location === 'global');
|
||||
|
||||
if (projectAgents.length > 0) {
|
||||
console.log(chalk.blue('Project agents:'));
|
||||
for (const agent of projectAgents) {
|
||||
printAgent(agent);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (globalAgents.length > 0) {
|
||||
console.log(chalk.dim('Global agents:'));
|
||||
for (const agent of globalAgents) {
|
||||
printAgent(agent);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
console.log(
|
||||
chalk.dim(`${projectAgents.length} project, ${globalAgents.length} global`)
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentShowCommand extends Command {
|
||||
static override paths = [['agent', 'show'], ['agent', 'info']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Show details for a specific agent',
|
||||
examples: [
|
||||
['Show agent details', '$0 agent show architect'],
|
||||
],
|
||||
});
|
||||
|
||||
name = Option.String({ required: true });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const searchDirs = [process.cwd()];
|
||||
const agent = findAgent(this.name, searchDirs);
|
||||
|
||||
if (!agent) {
|
||||
console.log(chalk.red(`Agent not found: ${this.name}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Agent: ${agent.name}\n`));
|
||||
console.log(`${chalk.dim('Description:')} ${agent.description}`);
|
||||
console.log(`${chalk.dim('Location:')} ${agent.location} (${agent.path})`);
|
||||
console.log(`${chalk.dim('Enabled:')} ${agent.enabled ? chalk.green('yes') : chalk.red('no')}`);
|
||||
|
||||
const fm = agent.frontmatter;
|
||||
if (fm.model) {
|
||||
console.log(`${chalk.dim('Model:')} ${fm.model}`);
|
||||
}
|
||||
if (fm.permissionMode) {
|
||||
console.log(`${chalk.dim('Permission Mode:')} ${fm.permissionMode}`);
|
||||
}
|
||||
if (fm.context) {
|
||||
console.log(`${chalk.dim('Context:')} ${fm.context}`);
|
||||
}
|
||||
if (fm.disallowedTools && fm.disallowedTools.length > 0) {
|
||||
console.log(`${chalk.dim('Disallowed Tools:')} ${fm.disallowedTools.join(', ')}`);
|
||||
}
|
||||
if (fm.skills && fm.skills.length > 0) {
|
||||
console.log(`${chalk.dim('Skills:')} ${fm.skills.join(', ')}`);
|
||||
}
|
||||
if (fm.hooks && fm.hooks.length > 0) {
|
||||
console.log(`${chalk.dim('Hooks:')} ${fm.hooks.length} defined`);
|
||||
}
|
||||
if (fm.tags && fm.tags.length > 0) {
|
||||
console.log(`${chalk.dim('Tags:')} ${fm.tags.join(', ')}`);
|
||||
}
|
||||
if (fm.author) {
|
||||
console.log(`${chalk.dim('Author:')} ${fm.author}`);
|
||||
}
|
||||
if (fm.version) {
|
||||
console.log(`${chalk.dim('Version:')} ${fm.version}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('Content preview:'));
|
||||
console.log(chalk.dim('─'.repeat(40)));
|
||||
const preview = agent.content.slice(0, 500);
|
||||
console.log(preview + (agent.content.length > 500 ? '\n...' : ''));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentCreateCommand extends Command {
|
||||
static override paths = [['agent', 'create'], ['agent', 'new']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Create a new agent',
|
||||
examples: [
|
||||
['Create an agent', '$0 agent create security-reviewer'],
|
||||
['Create with model', '$0 agent create architect --model opus'],
|
||||
['Create globally', '$0 agent create my-agent --global'],
|
||||
],
|
||||
});
|
||||
|
||||
name = Option.String({ required: true });
|
||||
|
||||
model = Option.String('--model,-m', {
|
||||
description: 'Model to use (opus, sonnet, haiku)',
|
||||
});
|
||||
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Agent description',
|
||||
});
|
||||
|
||||
global = Option.Boolean('--global,-g', false, {
|
||||
description: 'Create in global agents directory',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
// Validate agent name format
|
||||
const namePattern = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!namePattern.test(this.name)) {
|
||||
console.log(chalk.red('Invalid agent name: must be lowercase alphanumeric with hyphens'));
|
||||
console.log(chalk.dim('Examples: my-agent, code-reviewer, security-expert'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Determine target directory
|
||||
let targetDir: string;
|
||||
if (this.global) {
|
||||
targetDir = join(homedir(), '.claude', 'agents');
|
||||
} else {
|
||||
targetDir = join(process.cwd(), '.claude', 'agents');
|
||||
}
|
||||
|
||||
// Create directory if needed
|
||||
if (!existsSync(targetDir)) {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Check if agent already exists
|
||||
const agentPath = join(targetDir, `${this.name}.md`);
|
||||
if (existsSync(agentPath)) {
|
||||
console.log(chalk.red(`Agent already exists: ${agentPath}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Generate content
|
||||
const description = this.description || `${this.name} agent`;
|
||||
const content = generateAgentTemplate(this.name, description, this.model);
|
||||
|
||||
// Write file
|
||||
writeFileSync(agentPath, content);
|
||||
|
||||
console.log(chalk.green(`Created agent: ${agentPath}`));
|
||||
console.log();
|
||||
console.log(chalk.dim('Edit the file to customize the agent system prompt.'));
|
||||
console.log(chalk.dim(`Invoke with: @${this.name}`));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentTranslateCommand extends Command {
|
||||
static override paths = [['agent', 'translate']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Translate agents between AI coding agent formats',
|
||||
details: `
|
||||
Translates agent definitions between different AI coding agent formats.
|
||||
Supports recursive translation for directories with multiple agents.
|
||||
|
||||
Use --source to specify a custom source directory with agents.
|
||||
Use --recursive to scan all subdirectories for agents.
|
||||
`,
|
||||
examples: [
|
||||
['Translate all to Cursor', '$0 agent translate --to cursor'],
|
||||
['Translate specific agent', '$0 agent translate architect --to cursor'],
|
||||
['Translate from source directory', '$0 agent translate --source ./my-agents --to cursor'],
|
||||
['Recursive translation', '$0 agent translate --source ./skills --to cursor --recursive'],
|
||||
['Dry run', '$0 agent translate --to cursor --dry-run'],
|
||||
],
|
||||
});
|
||||
|
||||
name = Option.String({ required: false });
|
||||
|
||||
to = Option.String('--to,-t', {
|
||||
description: 'Target AI agent (claude-code, cursor, codex, etc.)',
|
||||
required: true,
|
||||
});
|
||||
|
||||
source = Option.String('--source,-s', {
|
||||
description: 'Source directory or file to translate from',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output directory',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run,-n', false, {
|
||||
description: 'Show what would be done without writing files',
|
||||
});
|
||||
|
||||
all = Option.Boolean('--all,-a', false, {
|
||||
description: 'Translate all agents',
|
||||
});
|
||||
|
||||
recursive = Option.Boolean('--recursive,-r', false, {
|
||||
description: 'Recursively scan directories for agents',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const searchDirs = [process.cwd()];
|
||||
const targetAgent = this.to as AgentType;
|
||||
|
||||
// Get agents to translate
|
||||
let agents: CustomAgent[];
|
||||
|
||||
if (this.source) {
|
||||
// Translate from custom source path
|
||||
const sourcePath = this.source.startsWith('/')
|
||||
? this.source
|
||||
: join(process.cwd(), this.source);
|
||||
|
||||
if (!existsSync(sourcePath)) {
|
||||
console.log(chalk.red(`Source path not found: ${sourcePath}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
agents = discoverAgentsFromPath(sourcePath, this.recursive);
|
||||
|
||||
if (agents.length === 0) {
|
||||
console.log(chalk.yellow(`No agents found in: ${sourcePath}`));
|
||||
if (!this.recursive) {
|
||||
console.log(chalk.dim('Tip: Use --recursive to scan subdirectories'));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
} else if (this.name) {
|
||||
const agent = findAgent(this.name, searchDirs);
|
||||
if (!agent) {
|
||||
console.log(chalk.red(`Agent not found: ${this.name}`));
|
||||
return 1;
|
||||
}
|
||||
agents = [agent];
|
||||
} else if (this.all) {
|
||||
agents = findAllAgents(searchDirs);
|
||||
} else {
|
||||
agents = discoverAgents(process.cwd());
|
||||
}
|
||||
|
||||
if (agents.length === 0) {
|
||||
console.log(chalk.yellow('No agents found to translate'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Determine output directory
|
||||
const outputDir = this.output || getAgentTargetDirectory(process.cwd(), targetAgent);
|
||||
|
||||
console.log(chalk.cyan(`Translating ${agents.length} agent(s) to ${targetAgent} format...\n`));
|
||||
|
||||
let successCount = 0;
|
||||
let errorCount = 0;
|
||||
|
||||
for (const agent of agents) {
|
||||
try {
|
||||
const result = translateAgent(agent, targetAgent, { addMetadata: true });
|
||||
|
||||
if (!result.success) {
|
||||
console.log(chalk.red(`✗ ${agent.name}: Translation failed`));
|
||||
errorCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const outputPath = join(outputDir, result.filename);
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.blue(`Would write: ${outputPath}`));
|
||||
if (result.warnings.length > 0) {
|
||||
for (const warning of result.warnings) {
|
||||
console.log(chalk.yellow(` ⚠ ${warning}`));
|
||||
}
|
||||
}
|
||||
if (result.incompatible.length > 0) {
|
||||
for (const incompat of result.incompatible) {
|
||||
console.log(chalk.dim(` ○ ${incompat}`));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Create directory if needed
|
||||
if (!existsSync(outputDir)) {
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
writeFileSync(outputPath, result.content);
|
||||
console.log(chalk.green(`✓ ${agent.name} → ${outputPath}`));
|
||||
}
|
||||
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.log(chalk.red(`✗ ${agent.name}: ${error instanceof Error ? error.message : 'Unknown error'}`));
|
||||
errorCount++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.dim(`Would translate ${successCount} agent(s)`));
|
||||
} else {
|
||||
console.log(chalk.dim(`Translated ${successCount} agent(s)${errorCount > 0 ? `, ${errorCount} failed` : ''}`));
|
||||
}
|
||||
|
||||
return errorCount > 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentSyncCommand extends Command {
|
||||
static override paths = [['agent', 'sync']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Sync agents to target AI coding agent',
|
||||
examples: [
|
||||
['Sync to Claude Code', '$0 agent sync --agent claude-code'],
|
||||
['Sync to multiple agents', '$0 agent sync --agent claude-code,cursor'],
|
||||
],
|
||||
});
|
||||
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Target AI agent(s) (comma-separated)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const searchDirs = [process.cwd()];
|
||||
const agents = findAllAgents(searchDirs);
|
||||
|
||||
if (agents.length === 0) {
|
||||
console.log(chalk.yellow('No agents found to sync'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const targetAgents = this.agent
|
||||
? this.agent.split(',').map(a => a.trim() as AgentType)
|
||||
: ['claude-code' as AgentType];
|
||||
|
||||
console.log(chalk.cyan(`Syncing ${agents.length} agent(s)...\n`));
|
||||
|
||||
for (const targetAgent of targetAgents) {
|
||||
const outputDir = getAgentTargetDirectory(process.cwd(), targetAgent);
|
||||
|
||||
console.log(chalk.blue(`→ ${targetAgent} (${outputDir})`));
|
||||
|
||||
if (!existsSync(outputDir)) {
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
for (const agent of agents) {
|
||||
const result = translateAgent(agent, targetAgent);
|
||||
if (result.success) {
|
||||
const outputPath = join(outputDir, result.filename);
|
||||
writeFileSync(outputPath, result.content);
|
||||
console.log(chalk.green(` ✓ ${agent.name}`));
|
||||
} else {
|
||||
console.log(chalk.red(` ✗ ${agent.name}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('Sync complete'));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentValidateCommand extends Command {
|
||||
static override paths = [['agent', 'validate']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Validate agent definitions',
|
||||
examples: [
|
||||
['Validate specific agent', '$0 agent validate ./my-agent.md'],
|
||||
['Validate all agents', '$0 agent validate --all'],
|
||||
],
|
||||
});
|
||||
|
||||
agentPath = Option.String({ required: false });
|
||||
|
||||
all = Option.Boolean('--all,-a', false, {
|
||||
description: 'Validate all discovered agents',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
let hasErrors = false;
|
||||
|
||||
if (this.agentPath) {
|
||||
// Validate specific path
|
||||
const result = validateAgent(this.agentPath);
|
||||
printValidationResult(this.agentPath, result);
|
||||
hasErrors = !result.valid;
|
||||
} else if (this.all) {
|
||||
// Validate all agents
|
||||
const searchDirs = [process.cwd()];
|
||||
const agents = findAllAgents(searchDirs);
|
||||
|
||||
if (agents.length === 0) {
|
||||
console.log(chalk.yellow('No agents found'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Validating ${agents.length} agent(s)...\n`));
|
||||
|
||||
for (const agent of agents) {
|
||||
const result = validateAgent(agent.path);
|
||||
printValidationResult(agent.name, result);
|
||||
if (!result.valid) hasErrors = true;
|
||||
}
|
||||
} else {
|
||||
console.log(chalk.yellow('Specify a path or use --all to validate all agents'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
return hasErrors ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
function printAgent(agent: CustomAgent): void {
|
||||
const status = agent.enabled ? chalk.green('✓') : chalk.red('○');
|
||||
const name = agent.enabled ? agent.name : chalk.dim(agent.name);
|
||||
const model = agent.frontmatter.model ? chalk.blue(`[${agent.frontmatter.model}]`) : '';
|
||||
const desc = chalk.dim(truncate(agent.description, 40));
|
||||
|
||||
console.log(` ${status} ${name} ${model}`);
|
||||
if (agent.description) {
|
||||
console.log(` ${desc}`);
|
||||
}
|
||||
}
|
||||
|
||||
function printValidationResult(
|
||||
name: string,
|
||||
result: { valid: boolean; errors: string[]; warnings: string[] }
|
||||
): void {
|
||||
if (result.valid) {
|
||||
console.log(chalk.green(`✓ ${name}`));
|
||||
for (const warning of result.warnings) {
|
||||
console.log(chalk.yellow(` ⚠ ${warning}`));
|
||||
}
|
||||
} else {
|
||||
console.log(chalk.red(`✗ ${name}`));
|
||||
for (const error of result.errors) {
|
||||
console.log(chalk.red(` • ${error}`));
|
||||
}
|
||||
for (const warning of result.warnings) {
|
||||
console.log(chalk.yellow(` ⚠ ${warning}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen - 3) + '...';
|
||||
}
|
||||
|
||||
function generateAgentTemplate(name: string, description: string, model?: string): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('---');
|
||||
lines.push(`name: ${name}`);
|
||||
lines.push(`description: ${description}`);
|
||||
if (model) {
|
||||
lines.push(`model: ${model}`);
|
||||
}
|
||||
lines.push('# permissionMode: default');
|
||||
lines.push('# disallowedTools: []');
|
||||
lines.push('# skills: []');
|
||||
lines.push('# context: fork');
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
lines.push(`# ${formatAgentName(name)}`);
|
||||
lines.push('');
|
||||
lines.push('You are a specialized AI assistant.');
|
||||
lines.push('');
|
||||
lines.push('## Responsibilities');
|
||||
lines.push('');
|
||||
lines.push('- TODO: Define what this agent is responsible for');
|
||||
lines.push('- TODO: Add specific tasks and behaviors');
|
||||
lines.push('');
|
||||
lines.push('## Guidelines');
|
||||
lines.push('');
|
||||
lines.push('- TODO: Add guidelines for how this agent should behave');
|
||||
lines.push('- TODO: Define any constraints or preferences');
|
||||
lines.push('');
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function formatAgentName(name: string): string {
|
||||
return name
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
@@ -31,12 +31,3 @@ export { PlanCommand } from './plan.js';
|
||||
export { CommandCmd } from './command.js';
|
||||
export { AICommand } from './ai.js';
|
||||
export { AuditCommand } from './audit.js';
|
||||
export {
|
||||
AgentCommand,
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
} from './agent.js';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/core",
|
||||
"version": "1.6.4",
|
||||
"version": "1.5.0",
|
||||
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -1,432 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import {
|
||||
AGENT_SKILL_FORMATS,
|
||||
parseSkillToCanonical,
|
||||
parseSkillContentToCanonical,
|
||||
translateSkillToAgent,
|
||||
translateSkillToAll,
|
||||
writeTranslatedSkill,
|
||||
generateSkillsConfig,
|
||||
getAgentSkillsDir,
|
||||
getAgentConfigFile,
|
||||
supportsAutoDiscovery,
|
||||
getAllSkillsDirs,
|
||||
getGlobalSkillsDir,
|
||||
type CrossAgentSkill,
|
||||
type SkillTranslationOptions,
|
||||
} from '../skill-translator.js';
|
||||
|
||||
describe('Skill Translator', () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = join(tmpdir(), `skillkit-test-${Date.now()}`);
|
||||
mkdirSync(tempDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('AGENT_SKILL_FORMATS', () => {
|
||||
it('should have configurations for all supported agents', () => {
|
||||
const expectedAgents = [
|
||||
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
|
||||
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
|
||||
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
|
||||
];
|
||||
|
||||
for (const agent of expectedAgents) {
|
||||
expect(AGENT_SKILL_FORMATS[agent as keyof typeof AGENT_SKILL_FORMATS]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should have valid skillsDir for each agent', () => {
|
||||
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.skillsDir).toBeTruthy();
|
||||
expect(typeof format.skillsDir).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('should have valid configFile for each agent', () => {
|
||||
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.configFile).toBeTruthy();
|
||||
expect(typeof format.configFile).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('should have correct Cursor MDC format', () => {
|
||||
const cursor = AGENT_SKILL_FORMATS.cursor;
|
||||
expect(cursor.skillsDir).toBe('.cursor/skills');
|
||||
expect(cursor.configFile).toBe('.cursor/rules/skills.mdc');
|
||||
expect(cursor.configFormat).toBe('mdc');
|
||||
});
|
||||
|
||||
it('should have correct Windsurf format', () => {
|
||||
const windsurf = AGENT_SKILL_FORMATS.windsurf;
|
||||
expect(windsurf.skillsDir).toBe('.windsurf/skills');
|
||||
expect(windsurf.configFile).toBe('.windsurf/rules/skills.md');
|
||||
expect(windsurf.configFormat).toBe('markdown');
|
||||
expect(windsurf.globalSkillsDir).toBe('~/.codeium/windsurf/skills');
|
||||
});
|
||||
|
||||
it('should have correct GitHub Copilot format', () => {
|
||||
const copilot = AGENT_SKILL_FORMATS['github-copilot'];
|
||||
expect(copilot.skillsDir).toBe('.github/skills');
|
||||
expect(copilot.configFile).toBe('.github/copilot-instructions.md');
|
||||
expect(copilot.configFormat).toBe('markdown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSkillToCanonical', () => {
|
||||
it('should parse a valid SKILL.md file', () => {
|
||||
const skillDir = join(tempDir, 'test-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: test-skill
|
||||
description: A test skill for unit testing
|
||||
version: "1.0.0"
|
||||
author: Test Author
|
||||
tags:
|
||||
- testing
|
||||
- unit-test
|
||||
---
|
||||
# Test Skill
|
||||
|
||||
This is a test skill for unit testing purposes.
|
||||
|
||||
## Usage
|
||||
|
||||
Use this skill when you need to test something.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe('test-skill');
|
||||
expect(result?.description).toBe('A test skill for unit testing');
|
||||
expect(result?.version).toBe('1.0.0');
|
||||
expect(result?.author).toBe('Test Author');
|
||||
expect(result?.tags).toEqual(['testing', 'unit-test']);
|
||||
expect(result?.content).toContain('# Test Skill');
|
||||
});
|
||||
|
||||
it('should return null for non-existent skill', () => {
|
||||
const result = parseSkillToCanonical(join(tempDir, 'non-existent'));
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle SKILL.md without frontmatter', () => {
|
||||
const skillDir = join(tempDir, 'no-frontmatter-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `# Simple Skill
|
||||
|
||||
Just some content without frontmatter.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result).not.toBeNull();
|
||||
// Without frontmatter, name is derived from directory name
|
||||
expect(result?.name).toBe('no-frontmatter-skill');
|
||||
});
|
||||
|
||||
it('should extract allowed-tools from frontmatter', () => {
|
||||
const skillDir = join(tempDir, 'tools-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: tools-skill
|
||||
description: Skill with allowed tools
|
||||
allowed-tools: Read, Write, Bash
|
||||
---
|
||||
Content here.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result?.allowedTools).toEqual(['Read', 'Write', 'Bash']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSkillContentToCanonical', () => {
|
||||
it('should parse skill content with full frontmatter', () => {
|
||||
const content = `---
|
||||
name: content-skill
|
||||
description: Parsed from content
|
||||
model: opus
|
||||
context: fork
|
||||
disable-model-invocation: true
|
||||
---
|
||||
# Content Skill
|
||||
|
||||
Instructions here.
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'claude-code');
|
||||
expect(result?.name).toBe('content-skill');
|
||||
expect(result?.description).toBe('Parsed from content');
|
||||
expect(result?.agentFields?.['model']).toBe('opus');
|
||||
expect(result?.agentFields?.['context']).toBe('fork');
|
||||
expect(result?.agentFields?.['disable-model-invocation']).toBe(true);
|
||||
expect(result?.sourceAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('should extract description from content when not in frontmatter', () => {
|
||||
const content = `---
|
||||
name: no-desc
|
||||
---
|
||||
This is a longer paragraph that should be used as the description when none is provided in frontmatter.
|
||||
|
||||
## More Content
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill');
|
||||
expect(result?.description).toContain('This is a longer paragraph');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateSkillToAgent', () => {
|
||||
const testSkill: CrossAgentSkill = {
|
||||
name: 'translate-test',
|
||||
description: 'A skill to test translation',
|
||||
content: '# Translate Test\n\nTest content for translation.',
|
||||
frontmatter: { name: 'translate-test', description: 'A skill to test translation' },
|
||||
sourcePath: '/test/path',
|
||||
sourceAgent: 'claude-code',
|
||||
version: '1.0.0',
|
||||
author: 'Test',
|
||||
tags: ['test'],
|
||||
};
|
||||
|
||||
it('should translate to Claude Code format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'claude-code');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('name: translate-test');
|
||||
expect(result.content).toContain('description: A skill to test translation');
|
||||
expect(result.targetAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('should translate to Cursor format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'cursor');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('name: translate-test');
|
||||
expect(result.targetAgent).toBe('cursor');
|
||||
});
|
||||
|
||||
it('should translate to Windsurf format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'windsurf');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.targetAgent).toBe('windsurf');
|
||||
});
|
||||
|
||||
it('should include translation metadata when requested', () => {
|
||||
const options: SkillTranslationOptions = { addMetadata: true };
|
||||
const result = translateSkillToAgent(testSkill, 'cursor', options);
|
||||
expect(result.content).toContain('_translated-from: claude-code');
|
||||
expect(result.content).toContain('_translated-at:');
|
||||
});
|
||||
|
||||
it('should preserve agent-specific fields for Claude Code', () => {
|
||||
const skillWithFields: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
model: 'opus',
|
||||
context: 'fork',
|
||||
'disable-model-invocation': true,
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(skillWithFields, 'claude-code');
|
||||
expect(result.content).toContain('model: opus');
|
||||
expect(result.content).toContain('context: fork');
|
||||
expect(result.content).toContain('disable-model-invocation: true');
|
||||
});
|
||||
|
||||
it('should report incompatible features', () => {
|
||||
const skillWithHooks: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
hooks: [{ type: 'PreToolUse', command: 'echo test' }],
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(skillWithHooks, 'cursor');
|
||||
expect(result.incompatible).toContain('hooks (only supported in Claude Code)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateSkillToAll', () => {
|
||||
it('should translate skill to all supported agents', () => {
|
||||
const skillDir = join(tempDir, 'all-agents-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: all-agents
|
||||
description: Skill for all agents
|
||||
---
|
||||
# All Agents Skill
|
||||
`);
|
||||
|
||||
const results = translateSkillToAll(skillDir, 'claude-code');
|
||||
expect(results.size).toBeGreaterThan(0);
|
||||
|
||||
// Should not include source agent
|
||||
expect(results.has('claude-code')).toBe(false);
|
||||
|
||||
// Should include other agents
|
||||
expect(results.has('cursor')).toBe(true);
|
||||
expect(results.has('windsurf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return empty map for non-existent skill', () => {
|
||||
const results = translateSkillToAll(join(tempDir, 'non-existent'));
|
||||
expect(results.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeTranslatedSkill', () => {
|
||||
it('should write translated skill to disk', () => {
|
||||
const result = {
|
||||
success: true,
|
||||
content: '---\nname: written-skill\n---\n# Content',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: 'test-skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'claude-code' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(result, tempDir);
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(writeResult.path)).toBe(true);
|
||||
});
|
||||
|
||||
it('should create nested directories', () => {
|
||||
const result = {
|
||||
success: true,
|
||||
content: '---\nname: nested\n---\n# Content',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: '.cursor/skills/nested-skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'cursor' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(result, tempDir);
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(join(tempDir, '.cursor/skills/nested-skill/SKILL.md'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkillsConfig', () => {
|
||||
const testSkills = [
|
||||
{ name: 'skill-one', description: 'First skill', path: '/path/one', location: 'project' as const, enabled: true },
|
||||
{ name: 'skill-two', description: 'Second skill', path: '/path/two', location: 'project' as const, enabled: true },
|
||||
{ name: 'disabled-skill', description: 'Disabled', path: '/path/disabled', location: 'project' as const, enabled: false },
|
||||
];
|
||||
|
||||
it('should generate XML config for Claude Code', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'claude-code');
|
||||
expect(config).toContain('<skills_system');
|
||||
expect(config).toContain('<name>skill-one</name>');
|
||||
expect(config).toContain('<name>skill-two</name>');
|
||||
expect(config).not.toContain('disabled-skill');
|
||||
});
|
||||
|
||||
it('should generate MDC config for Cursor', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'cursor');
|
||||
expect(config).toContain('---');
|
||||
expect(config).toContain('description:');
|
||||
expect(config).toContain('globs:');
|
||||
expect(config).toContain('alwaysApply: true');
|
||||
expect(config).toContain('**skill-one**');
|
||||
expect(config).toContain('**skill-two**');
|
||||
});
|
||||
|
||||
it('should generate Markdown table config for Codex', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'codex');
|
||||
expect(config).toContain('| Skill | Description | Command |');
|
||||
expect(config).toContain('| skill-one |');
|
||||
expect(config).toContain('| skill-two |');
|
||||
});
|
||||
|
||||
it('should generate JSON config for Gemini CLI', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'gemini-cli');
|
||||
expect(config).toContain('```json');
|
||||
expect(config).toContain('"name": "skill-one"');
|
||||
expect(config).toContain('"name": "skill-two"');
|
||||
});
|
||||
|
||||
it('should generate Markdown config for Windsurf', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'windsurf');
|
||||
expect(config).toContain('### skill-one');
|
||||
expect(config).toContain('### skill-two');
|
||||
expect(config).toContain('**Invoke:**');
|
||||
});
|
||||
|
||||
it('should return empty string for no enabled skills', () => {
|
||||
const disabledSkills = [
|
||||
{ name: 'disabled', description: 'Disabled', path: '/path', location: 'project' as const, enabled: false },
|
||||
];
|
||||
const config = generateSkillsConfig(disabledSkills, 'claude-code');
|
||||
expect(config).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('utility functions', () => {
|
||||
it('getAgentSkillsDir should return correct path', () => {
|
||||
expect(getAgentSkillsDir('claude-code')).toBe('.claude/skills');
|
||||
expect(getAgentSkillsDir('cursor')).toBe('.cursor/skills');
|
||||
expect(getAgentSkillsDir('windsurf')).toBe('.windsurf/skills');
|
||||
});
|
||||
|
||||
it('getAgentConfigFile should return correct path', () => {
|
||||
expect(getAgentConfigFile('claude-code')).toBe('CLAUDE.md');
|
||||
expect(getAgentConfigFile('cursor')).toBe('.cursor/rules/skills.mdc');
|
||||
expect(getAgentConfigFile('github-copilot')).toBe('.github/copilot-instructions.md');
|
||||
});
|
||||
|
||||
it('supportsAutoDiscovery should return true for all major agents', () => {
|
||||
expect(supportsAutoDiscovery('claude-code')).toBe(true);
|
||||
expect(supportsAutoDiscovery('cursor')).toBe(true);
|
||||
expect(supportsAutoDiscovery('windsurf')).toBe(true);
|
||||
});
|
||||
|
||||
it('getAllSkillsDirs should include alternative directories', () => {
|
||||
const cursorDirs = getAllSkillsDirs('cursor');
|
||||
expect(cursorDirs).toContain('.cursor/skills');
|
||||
expect(cursorDirs).toContain('.cursor/commands');
|
||||
|
||||
const windsurfDirs = getAllSkillsDirs('windsurf');
|
||||
expect(windsurfDirs).toContain('.windsurf/skills');
|
||||
expect(windsurfDirs).toContain('.windsurf/workflows');
|
||||
});
|
||||
|
||||
it('getGlobalSkillsDir should return correct global path', () => {
|
||||
expect(getGlobalSkillsDir('claude-code')).toBe('~/.claude/skills');
|
||||
expect(getGlobalSkillsDir('windsurf')).toBe('~/.codeium/windsurf/skills');
|
||||
expect(getGlobalSkillsDir('opencode')).toBe('~/.config/opencode/skills');
|
||||
expect(getGlobalSkillsDir('roo')).toBe('~/.roo/skills');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Adapter Integration', () => {
|
||||
it('should have matching config formats between AGENT_SKILL_FORMATS and expected values', () => {
|
||||
// Verify that the 2026 updates are consistent
|
||||
expect(AGENT_SKILL_FORMATS.cursor.configFormat).toBe('mdc');
|
||||
expect(AGENT_SKILL_FORMATS.windsurf.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS['github-copilot'].configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS.trae.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS['claude-code'].configFormat).toBe('xml');
|
||||
expect(AGENT_SKILL_FORMATS.codex.configFormat).toBe('markdown-table');
|
||||
expect(AGENT_SKILL_FORMATS['gemini-cli'].configFormat).toBe('json');
|
||||
});
|
||||
|
||||
it('should have valid invoke commands', () => {
|
||||
for (const format of Object.values(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.invokeCommand).toBe('skillkit read');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,269 +0,0 @@
|
||||
/**
|
||||
* Centralized Agent Configuration
|
||||
*
|
||||
* Single source of truth for all AI coding agent configurations.
|
||||
* All modules should import from here instead of defining their own values.
|
||||
*/
|
||||
|
||||
import type { AgentType } from './types.js';
|
||||
|
||||
/**
|
||||
* Agent configuration for skills and config files
|
||||
*/
|
||||
export interface AgentDirectoryConfig {
|
||||
/** Primary skills directory path */
|
||||
skillsDir: string;
|
||||
/** Config file that references skills */
|
||||
configFile: string;
|
||||
/** Alternative skills directories */
|
||||
altSkillsDirs?: string[];
|
||||
/** Global skills directory */
|
||||
globalSkillsDir?: string;
|
||||
/** Config format: xml, markdown, mdc, json, markdown-table */
|
||||
configFormat: 'xml' | 'markdown' | 'mdc' | 'json' | 'markdown-table';
|
||||
/** Whether agent uses YAML frontmatter in SKILL.md */
|
||||
usesFrontmatter: boolean;
|
||||
/** Agent-specific frontmatter fields */
|
||||
frontmatterFields?: string[];
|
||||
/** Whether agent supports skill auto-discovery */
|
||||
supportsAutoDiscovery: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Centralized agent configurations
|
||||
*
|
||||
* This is the ONLY source of truth for agent paths and formats.
|
||||
* Do not define these values elsewhere.
|
||||
*/
|
||||
export const AGENT_CONFIG: Record<AgentType, AgentDirectoryConfig> = {
|
||||
// Claude Code - all Claude products use the same format
|
||||
'claude-code': {
|
||||
skillsDir: '.claude/skills',
|
||||
configFile: 'CLAUDE.md',
|
||||
globalSkillsDir: '~/.claude/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
frontmatterFields: [
|
||||
'name', 'description', 'allowed-tools', 'model', 'context',
|
||||
'agent', 'disable-model-invocation', 'user-invocable', 'argument-hint',
|
||||
],
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Cursor - uses MDC format in .cursor/rules/
|
||||
cursor: {
|
||||
skillsDir: '.cursor/skills',
|
||||
configFile: '.cursor/rules/skills.mdc',
|
||||
altSkillsDirs: ['.cursor/commands'],
|
||||
globalSkillsDir: '~/.cursor/skills',
|
||||
configFormat: 'mdc',
|
||||
usesFrontmatter: true,
|
||||
frontmatterFields: ['description', 'globs', 'alwaysApply'],
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Codex (OpenAI)
|
||||
codex: {
|
||||
skillsDir: '.codex/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
globalSkillsDir: '~/.codex/skills',
|
||||
configFormat: 'markdown-table',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Gemini CLI
|
||||
'gemini-cli': {
|
||||
skillsDir: '.gemini/skills',
|
||||
configFile: 'GEMINI.md',
|
||||
globalSkillsDir: '~/.gemini/skills',
|
||||
configFormat: 'json',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// OpenCode
|
||||
opencode: {
|
||||
skillsDir: '.opencode/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
altSkillsDirs: ['.opencode/agent'],
|
||||
globalSkillsDir: '~/.config/opencode/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Antigravity
|
||||
antigravity: {
|
||||
skillsDir: '.antigravity/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Amp - uses .amp/ directory
|
||||
amp: {
|
||||
skillsDir: '.amp/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Clawdbot
|
||||
clawdbot: {
|
||||
skillsDir: '.clawdbot/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
altSkillsDirs: ['skills'],
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Droid (Factory)
|
||||
droid: {
|
||||
skillsDir: '.factory/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// GitHub Copilot
|
||||
'github-copilot': {
|
||||
skillsDir: '.github/skills',
|
||||
configFile: '.github/copilot-instructions.md',
|
||||
altSkillsDirs: ['.github/instructions'],
|
||||
configFormat: 'markdown',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Goose
|
||||
goose: {
|
||||
skillsDir: '.goose/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
globalSkillsDir: '~/.goose/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Kilo
|
||||
kilo: {
|
||||
skillsDir: '.kilocode/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
altSkillsDirs: ['.kilocode/modes'],
|
||||
globalSkillsDir: '~/.kilocode/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Kiro CLI
|
||||
'kiro-cli': {
|
||||
skillsDir: '.kiro/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
globalSkillsDir: '~/.kiro/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Roo Code
|
||||
roo: {
|
||||
skillsDir: '.roo/skills',
|
||||
configFile: 'AGENTS.md',
|
||||
altSkillsDirs: ['.roo/modes'],
|
||||
globalSkillsDir: '~/.roo/skills',
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Trae
|
||||
trae: {
|
||||
skillsDir: '.trae/skills',
|
||||
configFile: '.trae/rules/project_rules.md',
|
||||
altSkillsDirs: ['.trae/agent'],
|
||||
configFormat: 'markdown',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Windsurf
|
||||
windsurf: {
|
||||
skillsDir: '.windsurf/skills',
|
||||
configFile: '.windsurf/rules/skills.md',
|
||||
altSkillsDirs: ['.windsurf/workflows'],
|
||||
globalSkillsDir: '~/.codeium/windsurf/skills',
|
||||
configFormat: 'markdown',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
|
||||
// Universal - works with any agent
|
||||
universal: {
|
||||
skillsDir: 'skills',
|
||||
configFile: 'AGENTS.md',
|
||||
altSkillsDirs: ['.agent/skills', '.agents/skills'],
|
||||
configFormat: 'xml',
|
||||
usesFrontmatter: true,
|
||||
supportsAutoDiscovery: true,
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Get agent configuration
|
||||
*/
|
||||
export function getAgentDirectoryConfig(agent: AgentType): AgentDirectoryConfig {
|
||||
return AGENT_CONFIG[agent];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get skills directory for an agent
|
||||
*/
|
||||
export function getSkillsDir(agent: AgentType): string {
|
||||
return AGENT_CONFIG[agent].skillsDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config file for an agent
|
||||
*/
|
||||
export function getConfigFile(agent: AgentType): string {
|
||||
return AGENT_CONFIG[agent].configFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all skills directories for an agent (including alternatives)
|
||||
*/
|
||||
export function getAllSkillsDirs(agent: AgentType): string[] {
|
||||
const config = AGENT_CONFIG[agent];
|
||||
const dirs = [config.skillsDir];
|
||||
if (config.altSkillsDirs) {
|
||||
dirs.push(...config.altSkillsDirs);
|
||||
}
|
||||
return dirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get global skills directory for an agent
|
||||
*/
|
||||
export function getGlobalSkillsDir(agent: AgentType): string | undefined {
|
||||
return AGENT_CONFIG[agent].globalSkillsDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if agent supports auto-discovery
|
||||
*/
|
||||
export function supportsAutoDiscovery(agent: AgentType): boolean {
|
||||
return AGENT_CONFIG[agent].supportsAutoDiscovery;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config format for an agent
|
||||
*/
|
||||
export function getConfigFormat(agent: AgentType): AgentDirectoryConfig['configFormat'] {
|
||||
return AGENT_CONFIG[agent].configFormat;
|
||||
}
|
||||
@@ -1,556 +0,0 @@
|
||||
/**
|
||||
* Agent Discovery Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import {
|
||||
discoverAgents,
|
||||
discoverAgentsForAgent,
|
||||
discoverAgentsRecursive,
|
||||
discoverAgentsFromPath,
|
||||
findAllAgents,
|
||||
findAgent,
|
||||
getAgentsDirectory,
|
||||
agentExists,
|
||||
getAgentStats,
|
||||
} from '../discovery.js';
|
||||
|
||||
describe('Agent Discovery', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a temporary test directory
|
||||
testDir = join(tmpdir(), `agent-test-${Date.now()}`);
|
||||
mkdirSync(testDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up
|
||||
if (existsSync(testDir)) {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('discoverAgents', () => {
|
||||
it('should discover agents in .claude/agents directory', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'test-agent.md'),
|
||||
`---
|
||||
name: test-agent
|
||||
description: A test agent
|
||||
---
|
||||
|
||||
Agent content here.`
|
||||
);
|
||||
|
||||
const agents = discoverAgents(testDir);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('test-agent');
|
||||
expect(agents[0].description).toBe('A test agent');
|
||||
expect(agents[0].location).toBe('project');
|
||||
});
|
||||
|
||||
it('should discover multiple agents', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'agent-one.md'),
|
||||
`---
|
||||
name: agent-one
|
||||
description: First agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'agent-two.md'),
|
||||
`---
|
||||
name: agent-two
|
||||
description: Second agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgents(testDir);
|
||||
|
||||
expect(agents).toHaveLength(2);
|
||||
const names = agents.map((a) => a.name);
|
||||
expect(names).toContain('agent-one');
|
||||
expect(names).toContain('agent-two');
|
||||
});
|
||||
|
||||
it('should return empty array when no agents directory exists', () => {
|
||||
const agents = discoverAgents(testDir);
|
||||
expect(agents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should discover agents in alternative directories', () => {
|
||||
const agentsDir = join(testDir, 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'my-agent.md'),
|
||||
`---
|
||||
name: my-agent
|
||||
description: An agent in universal location
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgents(testDir);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('my-agent');
|
||||
});
|
||||
});
|
||||
|
||||
describe('discoverAgentsForAgent', () => {
|
||||
it('should discover agents for specific AI agent type', () => {
|
||||
const claudeAgentsDir = join(testDir, '.claude', 'agents');
|
||||
const cursorAgentsDir = join(testDir, '.cursor', 'agents');
|
||||
mkdirSync(claudeAgentsDir, { recursive: true });
|
||||
mkdirSync(cursorAgentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(claudeAgentsDir, 'claude-agent.md'),
|
||||
`---
|
||||
name: claude-agent
|
||||
description: Claude specific
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(cursorAgentsDir, 'cursor-agent.md'),
|
||||
`---
|
||||
name: cursor-agent
|
||||
description: Cursor specific
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const claudeAgents = discoverAgentsForAgent(testDir, 'claude-code');
|
||||
expect(claudeAgents).toHaveLength(1);
|
||||
expect(claudeAgents[0].name).toBe('claude-agent');
|
||||
|
||||
const cursorAgents = discoverAgentsForAgent(testDir, 'cursor');
|
||||
expect(cursorAgents).toHaveLength(1);
|
||||
expect(cursorAgents[0].name).toBe('cursor-agent');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAllAgents', () => {
|
||||
it('should find agents in multiple search directories', () => {
|
||||
const dir1 = join(testDir, 'project1');
|
||||
const dir2 = join(testDir, 'project2');
|
||||
mkdirSync(join(dir1, '.claude', 'agents'), { recursive: true });
|
||||
mkdirSync(join(dir2, '.claude', 'agents'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(dir1, '.claude', 'agents', 'agent-a.md'),
|
||||
`---
|
||||
name: agent-a
|
||||
description: Agent A
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(dir2, '.claude', 'agents', 'agent-b.md'),
|
||||
`---
|
||||
name: agent-b
|
||||
description: Agent B
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = findAllAgents([dir1, dir2]);
|
||||
|
||||
expect(agents).toHaveLength(2);
|
||||
const names = agents.map((a) => a.name);
|
||||
expect(names).toContain('agent-a');
|
||||
expect(names).toContain('agent-b');
|
||||
});
|
||||
|
||||
it('should deduplicate agents by name', () => {
|
||||
const dir1 = join(testDir, 'project1');
|
||||
const dir2 = join(testDir, 'project2');
|
||||
mkdirSync(join(dir1, '.claude', 'agents'), { recursive: true });
|
||||
mkdirSync(join(dir2, '.claude', 'agents'), { recursive: true });
|
||||
|
||||
// Same agent name in both directories
|
||||
writeFileSync(
|
||||
join(dir1, '.claude', 'agents', 'shared-agent.md'),
|
||||
`---
|
||||
name: shared-agent
|
||||
description: Shared agent (dir1)
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(dir2, '.claude', 'agents', 'shared-agent.md'),
|
||||
`---
|
||||
name: shared-agent
|
||||
description: Shared agent (dir2)
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = findAllAgents([dir1, dir2]);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('shared-agent');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAgent', () => {
|
||||
it('should find a specific agent by name', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'target-agent.md'),
|
||||
`---
|
||||
name: target-agent
|
||||
description: The target agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'other-agent.md'),
|
||||
`---
|
||||
name: other-agent
|
||||
description: Another agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agent = findAgent('target-agent', [testDir]);
|
||||
|
||||
expect(agent).not.toBeNull();
|
||||
expect(agent?.name).toBe('target-agent');
|
||||
expect(agent?.description).toBe('The target agent');
|
||||
});
|
||||
|
||||
it('should return null when agent not found', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
const agent = findAgent('non-existent', [testDir]);
|
||||
|
||||
expect(agent).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentsDirectory', () => {
|
||||
it('should return correct directory for different agent types', () => {
|
||||
expect(getAgentsDirectory(testDir, 'claude-code')).toBe(join(testDir, '.claude', 'agents'));
|
||||
expect(getAgentsDirectory(testDir, 'cursor')).toBe(join(testDir, '.cursor', 'agents'));
|
||||
expect(getAgentsDirectory(testDir, 'universal')).toBe(join(testDir, 'agents'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentExists', () => {
|
||||
it('should return true when agent exists', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'existing-agent.md'),
|
||||
`---
|
||||
name: existing-agent
|
||||
description: Exists
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
expect(agentExists('existing-agent', [testDir])).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when agent does not exist', () => {
|
||||
expect(agentExists('non-existent', [testDir])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentStats', () => {
|
||||
it('should return correct stats', () => {
|
||||
const agentsDir = join(testDir, '.claude', 'agents');
|
||||
mkdirSync(agentsDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'agent-one.md'),
|
||||
`---
|
||||
name: agent-one
|
||||
description: First
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(agentsDir, 'agent-two.md'),
|
||||
`---
|
||||
name: agent-two
|
||||
description: Second
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const stats = getAgentStats([testDir]);
|
||||
|
||||
expect(stats.total).toBe(2);
|
||||
expect(stats.project).toBe(2);
|
||||
expect(stats.global).toBe(0);
|
||||
expect(stats.enabled).toBe(2);
|
||||
expect(stats.disabled).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discoverAgentsRecursive', () => {
|
||||
it('should discover agents in nested directories', () => {
|
||||
// Create nested structure like kubernetes-skills/claude-code/k8s-autoscaling
|
||||
const rootDir = join(testDir, 'skills');
|
||||
mkdirSync(join(rootDir, 'k8s-autoscaling'), { recursive: true });
|
||||
mkdirSync(join(rootDir, 'k8s-security'), { recursive: true });
|
||||
mkdirSync(join(rootDir, 'k8s-deploy'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'k8s-autoscaling', 'AGENT.md'),
|
||||
`---
|
||||
name: k8s-autoscaling
|
||||
description: Kubernetes autoscaling agent
|
||||
---
|
||||
Autoscaling content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'k8s-security', 'AGENT.md'),
|
||||
`---
|
||||
name: k8s-security
|
||||
description: Kubernetes security agent
|
||||
---
|
||||
Security content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'k8s-deploy', 'AGENT.md'),
|
||||
`---
|
||||
name: k8s-deploy
|
||||
description: Kubernetes deployment agent
|
||||
---
|
||||
Deploy content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsRecursive(rootDir);
|
||||
|
||||
expect(agents).toHaveLength(3);
|
||||
const names = agents.map((a) => a.name);
|
||||
expect(names).toContain('k8s-autoscaling');
|
||||
expect(names).toContain('k8s-security');
|
||||
expect(names).toContain('k8s-deploy');
|
||||
});
|
||||
|
||||
it('should discover deeply nested agents', () => {
|
||||
const rootDir = join(testDir, 'deep-skills');
|
||||
mkdirSync(join(rootDir, 'category1', 'subcategory', 'agent-deep'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'category1', 'subcategory', 'agent-deep', 'AGENT.md'),
|
||||
`---
|
||||
name: agent-deep
|
||||
description: Deeply nested agent
|
||||
---
|
||||
Deep content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsRecursive(rootDir);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('agent-deep');
|
||||
});
|
||||
|
||||
it('should discover agents as markdown files', () => {
|
||||
const rootDir = join(testDir, 'md-skills');
|
||||
mkdirSync(join(rootDir, 'subdir'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'top-level-agent.md'),
|
||||
`---
|
||||
name: top-level-agent
|
||||
description: Top level agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'subdir', 'nested-agent.md'),
|
||||
`---
|
||||
name: nested-agent
|
||||
description: Nested agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsRecursive(rootDir);
|
||||
|
||||
expect(agents).toHaveLength(2);
|
||||
const names = agents.map((a) => a.name);
|
||||
expect(names).toContain('top-level-agent');
|
||||
expect(names).toContain('nested-agent');
|
||||
});
|
||||
|
||||
it('should skip hidden directories except standard agent paths', () => {
|
||||
const rootDir = join(testDir, 'hidden-test');
|
||||
mkdirSync(join(rootDir, '.hidden', 'agents'), { recursive: true });
|
||||
mkdirSync(join(rootDir, '.claude', 'agents'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, '.hidden', 'agents', 'hidden-agent.md'),
|
||||
`---
|
||||
name: hidden-agent
|
||||
description: Should be skipped
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, '.claude', 'agents', 'claude-agent.md'),
|
||||
`---
|
||||
name: claude-agent
|
||||
description: Should be found
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsRecursive(rootDir);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('claude-agent');
|
||||
});
|
||||
|
||||
it('should return empty array for non-existent directory', () => {
|
||||
const agents = discoverAgentsRecursive(join(testDir, 'non-existent'));
|
||||
expect(agents).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discoverAgentsFromPath', () => {
|
||||
it('should discover agent from single file', () => {
|
||||
mkdirSync(testDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(testDir, 'single-agent.md'),
|
||||
`---
|
||||
name: single-agent
|
||||
description: A single agent file
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsFromPath(join(testDir, 'single-agent.md'));
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('single-agent');
|
||||
});
|
||||
|
||||
it('should discover agents from directory without recursive flag', () => {
|
||||
const rootDir = join(testDir, 'flat-dir');
|
||||
mkdirSync(rootDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'agent-a.md'),
|
||||
`---
|
||||
name: agent-a
|
||||
description: Agent A
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'agent-b.md'),
|
||||
`---
|
||||
name: agent-b
|
||||
description: Agent B
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsFromPath(rootDir, false);
|
||||
|
||||
expect(agents).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should discover agents from directory with recursive flag', () => {
|
||||
const rootDir = join(testDir, 'nested-dir');
|
||||
mkdirSync(join(rootDir, 'subdir'), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'agent-top.md'),
|
||||
`---
|
||||
name: agent-top
|
||||
description: Top agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(rootDir, 'subdir', 'agent-nested.md'),
|
||||
`---
|
||||
name: agent-nested
|
||||
description: Nested agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agentsNonRecursive = discoverAgentsFromPath(rootDir, false);
|
||||
expect(agentsNonRecursive).toHaveLength(1);
|
||||
expect(agentsNonRecursive[0].name).toBe('agent-top');
|
||||
|
||||
const agentsRecursive = discoverAgentsFromPath(rootDir, true);
|
||||
expect(agentsRecursive).toHaveLength(2);
|
||||
const names = agentsRecursive.map((a) => a.name);
|
||||
expect(names).toContain('agent-top');
|
||||
expect(names).toContain('agent-nested');
|
||||
});
|
||||
|
||||
it('should handle agent directory with AGENT.md', () => {
|
||||
const agentDir = join(testDir, 'agent-dir');
|
||||
mkdirSync(agentDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(agentDir, 'AGENT.md'),
|
||||
`---
|
||||
name: agent-dir
|
||||
description: Directory-based agent
|
||||
---
|
||||
Content.`
|
||||
);
|
||||
|
||||
const agents = discoverAgentsFromPath(agentDir);
|
||||
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0].name).toBe('agent-dir');
|
||||
});
|
||||
|
||||
it('should return empty array for non-existent path', () => {
|
||||
const agents = discoverAgentsFromPath(join(testDir, 'non-existent'));
|
||||
expect(agents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty array for non-markdown file', () => {
|
||||
writeFileSync(join(testDir, 'not-agent.txt'), 'Not an agent');
|
||||
|
||||
const agents = discoverAgentsFromPath(join(testDir, 'not-agent.txt'));
|
||||
expect(agents).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,201 +0,0 @@
|
||||
/**
|
||||
* Agent Parser Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
extractAgentFrontmatter,
|
||||
extractAgentContent,
|
||||
toCanonicalAgent,
|
||||
fromCanonicalAgent,
|
||||
validateAgent,
|
||||
} from '../parser.js';
|
||||
import type { CustomAgent, CanonicalAgent, AgentFrontmatter } from '../types.js';
|
||||
|
||||
describe('Agent Parser', () => {
|
||||
describe('extractAgentFrontmatter', () => {
|
||||
it('should extract valid YAML frontmatter', () => {
|
||||
const content = `---
|
||||
name: test-agent
|
||||
description: A test agent
|
||||
model: opus
|
||||
---
|
||||
|
||||
Agent content here.`;
|
||||
|
||||
const frontmatter = extractAgentFrontmatter(content);
|
||||
expect(frontmatter).not.toBeNull();
|
||||
expect(frontmatter?.name).toBe('test-agent');
|
||||
expect(frontmatter?.description).toBe('A test agent');
|
||||
expect(frontmatter?.model).toBe('opus');
|
||||
});
|
||||
|
||||
it('should return null for content without frontmatter', () => {
|
||||
const content = 'Just some content without frontmatter.';
|
||||
const frontmatter = extractAgentFrontmatter(content);
|
||||
expect(frontmatter).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for invalid YAML', () => {
|
||||
const content = `---
|
||||
name: test-agent
|
||||
invalid: yaml: structure: [broken
|
||||
---
|
||||
|
||||
Content here.`;
|
||||
|
||||
const frontmatter = extractAgentFrontmatter(content);
|
||||
expect(frontmatter).toBeNull();
|
||||
});
|
||||
|
||||
it('should extract complex frontmatter with arrays', () => {
|
||||
const content = `---
|
||||
name: security-reviewer
|
||||
description: Reviews code for security issues
|
||||
disallowedTools:
|
||||
- Bash
|
||||
- Write
|
||||
skills:
|
||||
- code-review
|
||||
- security
|
||||
---
|
||||
|
||||
Content here.`;
|
||||
|
||||
const frontmatter = extractAgentFrontmatter(content);
|
||||
expect(frontmatter?.name).toBe('security-reviewer');
|
||||
expect(frontmatter?.disallowedTools).toEqual(['Bash', 'Write']);
|
||||
expect(frontmatter?.skills).toEqual(['code-review', 'security']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractAgentContent', () => {
|
||||
it('should extract content after frontmatter', () => {
|
||||
const content = `---
|
||||
name: test-agent
|
||||
description: A test agent
|
||||
---
|
||||
|
||||
# Agent Instructions
|
||||
|
||||
This is the main content.`;
|
||||
|
||||
const extracted = extractAgentContent(content);
|
||||
expect(extracted).toBe('# Agent Instructions\n\nThis is the main content.');
|
||||
});
|
||||
|
||||
it('should return full content if no frontmatter', () => {
|
||||
const content = 'Just content without frontmatter.';
|
||||
const extracted = extractAgentContent(content);
|
||||
expect(extracted).toBe('Just content without frontmatter.');
|
||||
});
|
||||
|
||||
it('should handle empty content after frontmatter', () => {
|
||||
const content = `---
|
||||
name: test-agent
|
||||
description: Empty agent
|
||||
---`;
|
||||
|
||||
const extracted = extractAgentContent(content);
|
||||
expect(extracted).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toCanonicalAgent', () => {
|
||||
it('should convert CustomAgent to CanonicalAgent', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'A test agent',
|
||||
path: '/path/to/agent.md',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'test-agent',
|
||||
description: 'A test agent',
|
||||
model: 'opus',
|
||||
permissionMode: 'default',
|
||||
disallowedTools: ['Bash'],
|
||||
skills: ['testing'],
|
||||
} as AgentFrontmatter,
|
||||
content: 'Agent instructions here.',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const canonical = toCanonicalAgent(agent);
|
||||
|
||||
expect(canonical.name).toBe('test-agent');
|
||||
expect(canonical.description).toBe('A test agent');
|
||||
expect(canonical.model).toBe('opus');
|
||||
expect(canonical.permissionMode).toBe('default');
|
||||
expect(canonical.disallowedTools).toEqual(['Bash']);
|
||||
expect(canonical.skills).toEqual(['testing']);
|
||||
expect(canonical.content).toBe('Agent instructions here.');
|
||||
expect(canonical.sourceFormat).toBe('claude-agent');
|
||||
});
|
||||
|
||||
it('should handle string allowedTools', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'Test',
|
||||
path: '/path',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'test-agent',
|
||||
description: 'Test',
|
||||
allowedTools: 'Read, Glob, Grep',
|
||||
} as unknown as AgentFrontmatter,
|
||||
content: 'Content',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const canonical = toCanonicalAgent(agent);
|
||||
expect(canonical.allowedTools).toEqual(['Read', 'Glob', 'Grep']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromCanonicalAgent', () => {
|
||||
it('should generate markdown from CanonicalAgent', () => {
|
||||
const canonical: CanonicalAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'A test agent',
|
||||
model: 'opus',
|
||||
content: '# Test Agent\n\nInstructions here.',
|
||||
sourceFormat: 'claude-agent',
|
||||
};
|
||||
|
||||
const markdown = fromCanonicalAgent(canonical);
|
||||
|
||||
expect(markdown).toContain('---');
|
||||
expect(markdown).toContain('name: test-agent');
|
||||
expect(markdown).toContain('description: A test agent');
|
||||
expect(markdown).toContain('model: opus');
|
||||
expect(markdown).toContain('# Test Agent');
|
||||
});
|
||||
|
||||
it('should include optional fields when present', () => {
|
||||
const canonical: CanonicalAgent = {
|
||||
name: 'security-agent',
|
||||
description: 'Security reviewer',
|
||||
permissionMode: 'plan',
|
||||
disallowedTools: ['Bash', 'Write'],
|
||||
allowedTools: ['Read', 'Glob'],
|
||||
skills: ['security', 'review'],
|
||||
tags: ['security', 'code-review'],
|
||||
version: '1.0.0',
|
||||
author: 'test',
|
||||
content: 'Content here.',
|
||||
sourceFormat: 'claude-agent',
|
||||
};
|
||||
|
||||
const markdown = fromCanonicalAgent(canonical);
|
||||
|
||||
expect(markdown).toContain('permissionMode: plan');
|
||||
expect(markdown).toContain('disallowedTools:');
|
||||
expect(markdown).toContain(' - Bash');
|
||||
expect(markdown).toContain('allowed-tools:');
|
||||
expect(markdown).toContain('skills:');
|
||||
expect(markdown).toContain('tags: [security, code-review]');
|
||||
expect(markdown).toContain('version: "1.0.0"');
|
||||
expect(markdown).toContain('author: test');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,192 +0,0 @@
|
||||
/**
|
||||
* Agent Translator Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
translateAgent,
|
||||
translateCanonicalAgent,
|
||||
getAgentFilename,
|
||||
getAgentTargetDirectory,
|
||||
isAgentCompatible,
|
||||
} from '../translator.js';
|
||||
import type { CustomAgent, CanonicalAgent, AgentFrontmatter } from '../types.js';
|
||||
|
||||
describe('Agent Translator', () => {
|
||||
describe('translateAgent', () => {
|
||||
it('should translate agent to claude-code format', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'A test agent',
|
||||
path: '/path/to/agent.md',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'test-agent',
|
||||
description: 'A test agent',
|
||||
model: 'opus',
|
||||
} as AgentFrontmatter,
|
||||
content: 'Agent instructions here.',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = translateAgent(agent, 'claude-code');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.targetAgent).toBe('claude-code');
|
||||
expect(result.targetFormat).toBe('claude-agent');
|
||||
expect(result.content).toContain('name: test-agent');
|
||||
expect(result.content).toContain('model: opus');
|
||||
});
|
||||
|
||||
it('should translate agent to cursor format', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'reviewer',
|
||||
description: 'Code reviewer',
|
||||
path: '/path/to/agent.md',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'reviewer',
|
||||
description: 'Code reviewer',
|
||||
} as AgentFrontmatter,
|
||||
content: 'Review code carefully.',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = translateAgent(agent, 'cursor');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.targetAgent).toBe('cursor');
|
||||
expect(result.targetFormat).toBe('cursor-agent');
|
||||
expect(result.filename).toBe('reviewer.md');
|
||||
});
|
||||
|
||||
it('should add warnings for hooks in cursor format', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'hooked-agent',
|
||||
description: 'Agent with hooks',
|
||||
path: '/path/to/agent.md',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'hooked-agent',
|
||||
description: 'Agent with hooks',
|
||||
hooks: [
|
||||
{ type: 'PreToolUse', command: 'echo test' },
|
||||
],
|
||||
} as AgentFrontmatter,
|
||||
content: 'Content here.',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = translateAgent(agent, 'cursor');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.warnings).toContain('Hooks may require manual adjustment for Cursor');
|
||||
});
|
||||
|
||||
it('should add incompatible features for universal format', () => {
|
||||
const agent: CustomAgent = {
|
||||
name: 'complex-agent',
|
||||
description: 'Complex agent',
|
||||
path: '/path/to/agent.md',
|
||||
location: 'project',
|
||||
frontmatter: {
|
||||
name: 'complex-agent',
|
||||
description: 'Complex agent',
|
||||
permissionMode: 'plan',
|
||||
hooks: [
|
||||
{ type: 'SessionStart', command: 'echo start' },
|
||||
],
|
||||
} as AgentFrontmatter,
|
||||
content: 'Content here.',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = translateAgent(agent, 'universal');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.incompatible).toContain('hooks (not supported in universal format)');
|
||||
expect(result.incompatible).toContain('permissionMode (not supported in universal format)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateCanonicalAgent', () => {
|
||||
it('should translate canonical agent to different formats', () => {
|
||||
const canonical: CanonicalAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'Test agent',
|
||||
model: 'sonnet',
|
||||
content: 'Agent content.',
|
||||
sourceFormat: 'claude-agent',
|
||||
};
|
||||
|
||||
const claudeResult = translateCanonicalAgent(canonical, 'claude-code');
|
||||
expect(claudeResult.success).toBe(true);
|
||||
expect(claudeResult.content).toContain('name: test-agent');
|
||||
|
||||
const cursorResult = translateCanonicalAgent(canonical, 'cursor');
|
||||
expect(cursorResult.success).toBe(true);
|
||||
expect(cursorResult.content).toContain('name: test-agent');
|
||||
|
||||
const universalResult = translateCanonicalAgent(canonical, 'universal');
|
||||
expect(universalResult.success).toBe(true);
|
||||
expect(universalResult.content).toContain('name: test-agent');
|
||||
});
|
||||
|
||||
it('should include metadata when option is set', () => {
|
||||
const canonical: CanonicalAgent = {
|
||||
name: 'test-agent',
|
||||
description: 'Test agent',
|
||||
content: 'Content.',
|
||||
sourceFormat: 'claude-agent',
|
||||
sourceAgent: 'cursor',
|
||||
};
|
||||
|
||||
const result = translateCanonicalAgent(canonical, 'claude-code', { addMetadata: true });
|
||||
|
||||
expect(result.content).toContain('# Translated by SkillKit from cursor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentFilename', () => {
|
||||
it('should return correct filename for different agents', () => {
|
||||
expect(getAgentFilename('test-agent', 'claude-code')).toBe('test-agent.md');
|
||||
expect(getAgentFilename('reviewer', 'cursor')).toBe('reviewer.md');
|
||||
expect(getAgentFilename('my-agent', 'universal')).toBe('my-agent.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentTargetDirectory', () => {
|
||||
it('should return correct target directory', () => {
|
||||
const rootDir = '/home/user/project';
|
||||
|
||||
expect(getAgentTargetDirectory(rootDir, 'claude-code')).toBe('/home/user/project/.claude/agents');
|
||||
expect(getAgentTargetDirectory(rootDir, 'cursor')).toBe('/home/user/project/.cursor/agents');
|
||||
expect(getAgentTargetDirectory(rootDir, 'universal')).toBe('/home/user/project/agents');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAgentCompatible', () => {
|
||||
it('should return compatible for same format', () => {
|
||||
const result = isAgentCompatible('claude-agent', 'claude-agent');
|
||||
expect(result.compatible).toBe(true);
|
||||
expect(result.warnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return compatible for claude-agent target', () => {
|
||||
const result = isAgentCompatible('cursor-agent', 'claude-agent');
|
||||
expect(result.compatible).toBe(true);
|
||||
});
|
||||
|
||||
it('should add warnings for universal target from claude-agent', () => {
|
||||
const result = isAgentCompatible('claude-agent', 'universal');
|
||||
expect(result.compatible).toBe(true);
|
||||
expect(result.warnings.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should add warnings for cursor target from claude-agent', () => {
|
||||
const result = isAgentCompatible('claude-agent', 'cursor-agent');
|
||||
expect(result.compatible).toBe(true);
|
||||
expect(result.warnings.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,383 +0,0 @@
|
||||
/**
|
||||
* Agent Discovery
|
||||
*
|
||||
* Discovers custom agent definitions across all supported locations.
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join, extname } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import {
|
||||
ALL_AGENT_DISCOVERY_PATHS,
|
||||
AGENT_DISCOVERY_PATHS,
|
||||
type CustomAgent,
|
||||
type AgentLocation,
|
||||
} from './types.js';
|
||||
import { parseAgentFile, parseAgentDir } from './parser.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Discover agents in a specific directory
|
||||
*/
|
||||
function discoverAgentsInDir(
|
||||
dir: string,
|
||||
location: AgentLocation
|
||||
): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
|
||||
if (!existsSync(dir)) {
|
||||
return agents;
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = readdirSync(dir, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = join(dir, entry.name);
|
||||
|
||||
if (entry.isFile() && extname(entry.name) === '.md') {
|
||||
// Parse markdown file directly
|
||||
const agent = parseAgentFile(entryPath, location);
|
||||
if (agent) {
|
||||
agents.push(agent);
|
||||
}
|
||||
} else if (entry.isDirectory()) {
|
||||
// Parse directory with AGENT.md inside
|
||||
const agent = parseAgentDir(entryPath, location);
|
||||
if (agent) {
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors (permission denied, etc.)
|
||||
}
|
||||
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover all agents in a project directory
|
||||
*/
|
||||
export function discoverAgents(rootDir: string): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Search all standard paths
|
||||
for (const searchPath of ALL_AGENT_DISCOVERY_PATHS) {
|
||||
const fullPath = join(rootDir, searchPath);
|
||||
if (existsSync(fullPath)) {
|
||||
for (const agent of discoverAgentsInDir(fullPath, 'project')) {
|
||||
if (!seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover agents for a specific AI coding agent
|
||||
*/
|
||||
export function discoverAgentsForAgent(
|
||||
rootDir: string,
|
||||
agentType: AgentType
|
||||
): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
const seen = new Set<string>();
|
||||
const paths = AGENT_DISCOVERY_PATHS[agentType] || [];
|
||||
|
||||
for (const searchPath of paths) {
|
||||
const fullPath = join(rootDir, searchPath);
|
||||
if (existsSync(fullPath)) {
|
||||
for (const agent of discoverAgentsInDir(fullPath, 'project')) {
|
||||
if (!seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover global agents (in ~/.claude/agents, etc.)
|
||||
*/
|
||||
export function discoverGlobalAgents(): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
const seen = new Set<string>();
|
||||
const home = homedir();
|
||||
|
||||
// Global agent paths
|
||||
const globalPaths = [
|
||||
join(home, '.claude', 'agents'),
|
||||
join(home, '.skillkit', 'agents'),
|
||||
join(home, '.config', 'skillkit', 'agents'),
|
||||
];
|
||||
|
||||
for (const searchPath of globalPaths) {
|
||||
if (existsSync(searchPath)) {
|
||||
for (const agent of discoverAgentsInDir(searchPath, 'global')) {
|
||||
if (!seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all agents (project + global)
|
||||
*/
|
||||
export function findAllAgents(searchDirs: string[]): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Search provided directories
|
||||
for (const dir of searchDirs) {
|
||||
if (!existsSync(dir)) continue;
|
||||
|
||||
const discovered = discoverAgents(dir);
|
||||
for (const agent of discovered) {
|
||||
if (!seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add global agents
|
||||
for (const agent of discoverGlobalAgents()) {
|
||||
if (!seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
}
|
||||
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a specific agent by name
|
||||
*/
|
||||
export function findAgent(
|
||||
name: string,
|
||||
searchDirs: string[]
|
||||
): CustomAgent | null {
|
||||
// Search in provided directories first
|
||||
for (const dir of searchDirs) {
|
||||
if (!existsSync(dir)) continue;
|
||||
|
||||
// Check all discovery paths
|
||||
for (const searchPath of ALL_AGENT_DISCOVERY_PATHS) {
|
||||
const agentsDir = join(dir, searchPath);
|
||||
if (!existsSync(agentsDir)) continue;
|
||||
|
||||
// Try as file
|
||||
const agentFile = join(agentsDir, `${name}.md`);
|
||||
if (existsSync(agentFile)) {
|
||||
return parseAgentFile(agentFile, 'project');
|
||||
}
|
||||
|
||||
// Try as directory
|
||||
const agentDir = join(agentsDir, name);
|
||||
if (existsSync(agentDir) && statSync(agentDir).isDirectory()) {
|
||||
return parseAgentDir(agentDir, 'project');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check global agents
|
||||
const home = homedir();
|
||||
const globalPaths = [
|
||||
join(home, '.claude', 'agents'),
|
||||
join(home, '.skillkit', 'agents'),
|
||||
];
|
||||
|
||||
for (const agentsDir of globalPaths) {
|
||||
if (!existsSync(agentsDir)) continue;
|
||||
|
||||
const agentFile = join(agentsDir, `${name}.md`);
|
||||
if (existsSync(agentFile)) {
|
||||
return parseAgentFile(agentFile, 'global');
|
||||
}
|
||||
|
||||
const agentDir = join(agentsDir, name);
|
||||
if (existsSync(agentDir) && statSync(agentDir).isDirectory()) {
|
||||
return parseAgentDir(agentDir, 'global');
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the agents directory for a specific AI coding agent
|
||||
*/
|
||||
export function getAgentsDirectory(
|
||||
rootDir: string,
|
||||
agentType: AgentType
|
||||
): string {
|
||||
const paths = AGENT_DISCOVERY_PATHS[agentType];
|
||||
if (paths && paths.length > 0) {
|
||||
return join(rootDir, paths[0]);
|
||||
}
|
||||
return join(rootDir, 'agents');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an agent exists
|
||||
*/
|
||||
export function agentExists(
|
||||
name: string,
|
||||
searchDirs: string[]
|
||||
): boolean {
|
||||
return findAgent(name, searchDirs) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent count statistics
|
||||
*/
|
||||
export function getAgentStats(searchDirs: string[]): {
|
||||
total: number;
|
||||
project: number;
|
||||
global: number;
|
||||
enabled: number;
|
||||
disabled: number;
|
||||
} {
|
||||
const allAgents = findAllAgents(searchDirs);
|
||||
|
||||
return {
|
||||
total: allAgents.length,
|
||||
project: allAgents.filter(a => a.location === 'project').length,
|
||||
global: allAgents.filter(a => a.location === 'global').length,
|
||||
enabled: allAgents.filter(a => a.enabled).length,
|
||||
disabled: allAgents.filter(a => !a.enabled).length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively discover all agents in a directory tree
|
||||
* This finds agents at any depth, useful for batch translation
|
||||
*/
|
||||
export function discoverAgentsRecursive(
|
||||
rootDir: string,
|
||||
location: AgentLocation = 'project'
|
||||
): CustomAgent[] {
|
||||
const agents: CustomAgent[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
if (!existsSync(rootDir)) {
|
||||
return agents;
|
||||
}
|
||||
|
||||
function scanDirectory(dir: string): void {
|
||||
try {
|
||||
const entries = readdirSync(dir, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = join(dir, entry.name);
|
||||
|
||||
if (entry.isFile() && extname(entry.name) === '.md') {
|
||||
// Parse markdown file directly
|
||||
const agent = parseAgentFile(entryPath, location);
|
||||
if (agent && !seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
}
|
||||
} else if (entry.isDirectory()) {
|
||||
// Skip hidden directories except standard agent paths
|
||||
if (entry.name.startsWith('.') && !entry.name.startsWith('.claude') &&
|
||||
!entry.name.startsWith('.cursor') && !entry.name.startsWith('.codex')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to parse as agent directory first
|
||||
const agent = parseAgentDir(entryPath, location);
|
||||
if (agent && !seen.has(agent.name)) {
|
||||
seen.add(agent.name);
|
||||
agents.push(agent);
|
||||
} else {
|
||||
// If not an agent directory, recurse into it
|
||||
scanDirectory(entryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors (permission denied, etc.)
|
||||
}
|
||||
}
|
||||
|
||||
scanDirectory(rootDir);
|
||||
return agents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover agents from a custom source path
|
||||
* Handles both file paths and directories
|
||||
*/
|
||||
export function discoverAgentsFromPath(
|
||||
sourcePath: string,
|
||||
recursive: boolean = false,
|
||||
location: AgentLocation = 'project'
|
||||
): CustomAgent[] {
|
||||
if (!existsSync(sourcePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stats = statSync(sourcePath);
|
||||
|
||||
// Single file
|
||||
if (stats.isFile()) {
|
||||
if (extname(sourcePath) === '.md') {
|
||||
const agent = parseAgentFile(sourcePath, location);
|
||||
return agent ? [agent] : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// Directory
|
||||
if (stats.isDirectory()) {
|
||||
if (recursive) {
|
||||
return discoverAgentsRecursive(sourcePath, location);
|
||||
}
|
||||
|
||||
// Non-recursive: only check immediate directory
|
||||
// First try as agent directory
|
||||
const agent = parseAgentDir(sourcePath, location);
|
||||
if (agent) {
|
||||
return [agent];
|
||||
}
|
||||
|
||||
// Otherwise scan directory contents (one level)
|
||||
const agents: CustomAgent[] = [];
|
||||
try {
|
||||
const entries = readdirSync(sourcePath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = join(sourcePath, entry.name);
|
||||
|
||||
if (entry.isFile() && extname(entry.name) === '.md') {
|
||||
const a = parseAgentFile(entryPath, location);
|
||||
if (a) agents.push(a);
|
||||
} else if (entry.isDirectory()) {
|
||||
const a = parseAgentDir(entryPath, location);
|
||||
if (a) agents.push(a);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors
|
||||
}
|
||||
return agents;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/**
|
||||
* Agent Module
|
||||
*
|
||||
* Custom AI sub-agent management for SkillKit.
|
||||
* Supports discovery, parsing, and translation of agents
|
||||
* between different AI coding agent formats.
|
||||
*/
|
||||
|
||||
// Types
|
||||
export {
|
||||
AgentPermissionMode,
|
||||
AgentHook,
|
||||
AgentFrontmatter,
|
||||
AgentLocation,
|
||||
AgentMetadata,
|
||||
AGENT_DISCOVERY_PATHS,
|
||||
ALL_AGENT_DISCOVERY_PATHS,
|
||||
CUSTOM_AGENT_FORMAT_MAP,
|
||||
type CustomAgent,
|
||||
type CanonicalAgent,
|
||||
type AgentFormatCategory,
|
||||
type AgentTranslationResult,
|
||||
type AgentTranslationOptions,
|
||||
} from './types.js';
|
||||
|
||||
// Parser
|
||||
export {
|
||||
extractAgentFrontmatter,
|
||||
extractAgentContent,
|
||||
parseAgentFile,
|
||||
parseAgentDir,
|
||||
loadAgentMetadata,
|
||||
toCanonicalAgent,
|
||||
fromCanonicalAgent,
|
||||
readAgentContent,
|
||||
validateAgent,
|
||||
} from './parser.js';
|
||||
|
||||
// Discovery
|
||||
export {
|
||||
discoverAgents,
|
||||
discoverAgentsForAgent,
|
||||
discoverGlobalAgents,
|
||||
discoverAgentsRecursive,
|
||||
discoverAgentsFromPath,
|
||||
findAllAgents,
|
||||
findAgent,
|
||||
getAgentsDirectory,
|
||||
agentExists,
|
||||
getAgentStats,
|
||||
} from './discovery.js';
|
||||
|
||||
// Translator
|
||||
export {
|
||||
translateAgent,
|
||||
translateCanonicalAgent,
|
||||
translateAgentContent,
|
||||
translateAgents,
|
||||
getAgentFilename,
|
||||
getAgentTargetDirectory,
|
||||
isAgentCompatible,
|
||||
} from './translator.js';
|
||||
@@ -1,418 +0,0 @@
|
||||
/**
|
||||
* Agent Parser
|
||||
*
|
||||
* Parses agent definition files (e.g., .claude/agents/*.md)
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, basename, extname } from 'node:path';
|
||||
import { parse as parseYaml } from 'yaml';
|
||||
import {
|
||||
AgentFrontmatter,
|
||||
AgentMetadata,
|
||||
type CustomAgent,
|
||||
type AgentLocation,
|
||||
type CanonicalAgent,
|
||||
type AgentFormatCategory,
|
||||
} from './types.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Extract YAML frontmatter from markdown content
|
||||
*/
|
||||
export function extractAgentFrontmatter(content: string): Record<string, unknown> | null {
|
||||
const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
|
||||
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return parseYaml(match[1]) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract content after frontmatter
|
||||
*/
|
||||
export function extractAgentContent(content: string): string {
|
||||
const withoutFrontmatter = content.replace(/^---\s*\n[\s\S]*?\n---\s*\n?/, '');
|
||||
return withoutFrontmatter.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an agent file (.md)
|
||||
*/
|
||||
export function parseAgentFile(
|
||||
filePath: string,
|
||||
location: AgentLocation = 'project'
|
||||
): CustomAgent | null {
|
||||
if (!existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only parse .md files
|
||||
if (extname(filePath) !== '.md') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
const rawFrontmatter = extractAgentFrontmatter(content);
|
||||
const agentContent = extractAgentContent(content);
|
||||
|
||||
// If no frontmatter, use filename as name
|
||||
if (!rawFrontmatter) {
|
||||
const name = basename(filePath, '.md');
|
||||
return {
|
||||
name,
|
||||
description: 'No description available',
|
||||
path: filePath,
|
||||
location,
|
||||
frontmatter: {
|
||||
name,
|
||||
description: 'No description available',
|
||||
},
|
||||
content: agentContent,
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Parse frontmatter with validation
|
||||
const parsed = AgentFrontmatter.safeParse(rawFrontmatter);
|
||||
|
||||
if (!parsed.success) {
|
||||
// Fallback to basic parsing
|
||||
const name = (rawFrontmatter.name as string) || basename(filePath, '.md');
|
||||
return {
|
||||
name,
|
||||
description: (rawFrontmatter.description as string) || 'No description available',
|
||||
path: filePath,
|
||||
location,
|
||||
frontmatter: {
|
||||
name,
|
||||
description: (rawFrontmatter.description as string) || 'No description available',
|
||||
...rawFrontmatter,
|
||||
} as AgentFrontmatter,
|
||||
content: agentContent,
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Load metadata if exists
|
||||
const metadataPath = filePath.replace(/\.md$/, '.skillkit-agent.json');
|
||||
const metadata = loadAgentMetadata(metadataPath);
|
||||
|
||||
return {
|
||||
name: parsed.data.name,
|
||||
description: parsed.data.description,
|
||||
path: filePath,
|
||||
location,
|
||||
frontmatter: parsed.data,
|
||||
content: agentContent,
|
||||
metadata: metadata ?? undefined,
|
||||
enabled: metadata?.enabled ?? true,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an agent from a directory (containing AGENT.md)
|
||||
*/
|
||||
export function parseAgentDir(
|
||||
dirPath: string,
|
||||
location: AgentLocation = 'project'
|
||||
): CustomAgent | null {
|
||||
const agentMdPath = join(dirPath, 'AGENT.md');
|
||||
|
||||
if (existsSync(agentMdPath)) {
|
||||
const agent = parseAgentFile(agentMdPath, location);
|
||||
if (agent) {
|
||||
// Update path to directory
|
||||
agent.path = dirPath;
|
||||
}
|
||||
return agent;
|
||||
}
|
||||
|
||||
// Try index.md
|
||||
const indexMdPath = join(dirPath, 'index.md');
|
||||
if (existsSync(indexMdPath)) {
|
||||
const agent = parseAgentFile(indexMdPath, location);
|
||||
if (agent) {
|
||||
agent.path = dirPath;
|
||||
}
|
||||
return agent;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load agent metadata from JSON file
|
||||
*/
|
||||
export function loadAgentMetadata(metadataPath: string): AgentMetadata | null {
|
||||
if (!existsSync(metadataPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(metadataPath, 'utf-8');
|
||||
const data = JSON.parse(content);
|
||||
const parsed = AgentMetadata.safeParse(data);
|
||||
|
||||
return parsed.success ? parsed.data : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert parsed agent to canonical format for translation
|
||||
*/
|
||||
export function toCanonicalAgent(
|
||||
agent: CustomAgent,
|
||||
sourceAgent?: AgentType
|
||||
): CanonicalAgent {
|
||||
const fm = agent.frontmatter;
|
||||
|
||||
// Handle allowed-tools (can be string or array)
|
||||
let allowedTools: string[] | undefined;
|
||||
if (fm.allowedTools) {
|
||||
if (typeof fm.allowedTools === 'string') {
|
||||
// Parse YAML-style list
|
||||
allowedTools = fm.allowedTools.split(/[,\n]/).map(t => t.trim()).filter(Boolean);
|
||||
} else {
|
||||
allowedTools = fm.allowedTools;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: agent.name,
|
||||
description: agent.description,
|
||||
model: fm.model,
|
||||
permissionMode: fm.permissionMode,
|
||||
disallowedTools: fm.disallowedTools,
|
||||
allowedTools,
|
||||
hooks: fm.hooks,
|
||||
skills: fm.skills,
|
||||
context: fm.context,
|
||||
version: fm.version,
|
||||
author: fm.author,
|
||||
tags: fm.tags,
|
||||
userInvocable: fm['user-invocable'],
|
||||
argumentHint: fm['argument-hint'],
|
||||
content: agent.content,
|
||||
sourceFormat: 'claude-agent',
|
||||
sourceAgent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate agent markdown from canonical format
|
||||
*/
|
||||
export function fromCanonicalAgent(
|
||||
canonical: CanonicalAgent,
|
||||
_targetFormat: AgentFormatCategory = 'claude-agent'
|
||||
): string {
|
||||
// Note: _targetFormat reserved for format-specific output in future
|
||||
const lines: string[] = [];
|
||||
|
||||
// Generate frontmatter
|
||||
lines.push('---');
|
||||
lines.push(`name: ${canonical.name}`);
|
||||
lines.push(`description: ${canonical.description}`);
|
||||
|
||||
if (canonical.model) {
|
||||
lines.push(`model: ${canonical.model}`);
|
||||
}
|
||||
|
||||
if (canonical.permissionMode) {
|
||||
lines.push(`permissionMode: ${canonical.permissionMode}`);
|
||||
}
|
||||
|
||||
if (canonical.disallowedTools && canonical.disallowedTools.length > 0) {
|
||||
lines.push('disallowedTools:');
|
||||
for (const tool of canonical.disallowedTools) {
|
||||
lines.push(` - ${tool}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
|
||||
lines.push('allowed-tools:');
|
||||
for (const tool of canonical.allowedTools) {
|
||||
lines.push(` - ${tool}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.hooks && canonical.hooks.length > 0) {
|
||||
lines.push('hooks:');
|
||||
for (const hook of canonical.hooks) {
|
||||
lines.push(` - type: ${hook.type}`);
|
||||
lines.push(` command: ${hook.command}`);
|
||||
if (hook.timeout) lines.push(` timeout: ${hook.timeout}`);
|
||||
if (hook.once) lines.push(` once: ${hook.once}`);
|
||||
if (hook.matcher) lines.push(` matcher: ${hook.matcher}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.skills && canonical.skills.length > 0) {
|
||||
lines.push('skills:');
|
||||
for (const skill of canonical.skills) {
|
||||
lines.push(` - ${skill}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.context) {
|
||||
lines.push(`context: ${canonical.context}`);
|
||||
}
|
||||
|
||||
if (canonical.version) {
|
||||
lines.push(`version: "${canonical.version}"`);
|
||||
}
|
||||
|
||||
if (canonical.author) {
|
||||
lines.push(`author: ${canonical.author}`);
|
||||
}
|
||||
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
lines.push(`tags: [${canonical.tags.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (canonical.userInvocable !== undefined) {
|
||||
lines.push(`user-invocable: ${canonical.userInvocable}`);
|
||||
}
|
||||
|
||||
if (canonical.argumentHint) {
|
||||
lines.push(`argument-hint: "${canonical.argumentHint}"`);
|
||||
}
|
||||
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Add content
|
||||
lines.push(canonical.content);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Read raw agent content
|
||||
*/
|
||||
export function readAgentContent(agentPath: string): string | null {
|
||||
// If it's a file
|
||||
if (existsSync(agentPath) && extname(agentPath) === '.md') {
|
||||
try {
|
||||
return readFileSync(agentPath, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a directory
|
||||
const agentMdPath = join(agentPath, 'AGENT.md');
|
||||
if (existsSync(agentMdPath)) {
|
||||
try {
|
||||
return readFileSync(agentMdPath, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Try index.md
|
||||
const indexMdPath = join(agentPath, 'index.md');
|
||||
if (existsSync(indexMdPath)) {
|
||||
try {
|
||||
return readFileSync(indexMdPath, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an agent file
|
||||
*/
|
||||
export function validateAgent(
|
||||
agentPath: string
|
||||
): { valid: boolean; errors: string[]; warnings: string[] } {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
// Check file exists
|
||||
let filePath = agentPath;
|
||||
if (!existsSync(agentPath)) {
|
||||
errors.push(`Agent file not found: ${agentPath}`);
|
||||
return { valid: false, errors, warnings };
|
||||
}
|
||||
|
||||
// If directory, look for AGENT.md
|
||||
const stats = statSync(agentPath);
|
||||
if (stats.isDirectory()) {
|
||||
const agentMd = join(agentPath, 'AGENT.md');
|
||||
const indexMd = join(agentPath, 'index.md');
|
||||
if (existsSync(agentMd)) {
|
||||
filePath = agentMd;
|
||||
} else if (existsSync(indexMd)) {
|
||||
filePath = indexMd;
|
||||
} else {
|
||||
errors.push('Directory must contain AGENT.md or index.md');
|
||||
return { valid: false, errors, warnings };
|
||||
}
|
||||
}
|
||||
|
||||
// Read content
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(filePath, 'utf-8');
|
||||
} catch {
|
||||
errors.push(`Cannot read file: ${filePath}`);
|
||||
return { valid: false, errors, warnings };
|
||||
}
|
||||
|
||||
// Check frontmatter
|
||||
const frontmatter = extractAgentFrontmatter(content);
|
||||
if (!frontmatter) {
|
||||
errors.push('Missing YAML frontmatter');
|
||||
return { valid: false, errors, warnings };
|
||||
}
|
||||
|
||||
// Validate frontmatter
|
||||
const parsed = AgentFrontmatter.safeParse(frontmatter);
|
||||
if (!parsed.success) {
|
||||
for (const issue of parsed.error.issues) {
|
||||
errors.push(`${issue.path.join('.') || 'frontmatter'}: ${issue.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Warnings
|
||||
if (parsed.success) {
|
||||
const data = parsed.data;
|
||||
const fileName = basename(filePath, '.md');
|
||||
|
||||
if (data.name !== fileName && fileName !== 'AGENT' && fileName !== 'index') {
|
||||
warnings.push(`name "${data.name}" does not match filename "${fileName}"`);
|
||||
}
|
||||
|
||||
if (data.description && data.description.length < 20) {
|
||||
warnings.push('description is short; consider adding more detail');
|
||||
}
|
||||
|
||||
if (data.permissionMode === 'full-auto' || data.permissionMode === 'bypassPermissions') {
|
||||
warnings.push(`permissionMode "${data.permissionMode}" is potentially dangerous`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check content
|
||||
const agentContent = extractAgentContent(content);
|
||||
if (agentContent.length < 50) {
|
||||
warnings.push('Agent system prompt is very short');
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors, warnings };
|
||||
}
|
||||
@@ -1,431 +0,0 @@
|
||||
/**
|
||||
* Agent Translator
|
||||
*
|
||||
* Translates agent definitions between different AI coding agent formats.
|
||||
*/
|
||||
|
||||
import {
|
||||
type CanonicalAgent,
|
||||
type AgentFormatCategory,
|
||||
type AgentTranslationResult,
|
||||
type AgentTranslationOptions,
|
||||
type CustomAgent,
|
||||
CUSTOM_AGENT_FORMAT_MAP,
|
||||
AGENT_DISCOVERY_PATHS,
|
||||
AgentFrontmatter,
|
||||
} from './types.js';
|
||||
import {
|
||||
toCanonicalAgent,
|
||||
fromCanonicalAgent,
|
||||
extractAgentFrontmatter,
|
||||
extractAgentContent,
|
||||
} from './parser.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
import { join } from 'node:path';
|
||||
|
||||
/**
|
||||
* Translate an agent to a target AI coding agent format
|
||||
*/
|
||||
export function translateAgent(
|
||||
agent: CustomAgent,
|
||||
targetAgent: AgentType,
|
||||
options?: AgentTranslationOptions
|
||||
): AgentTranslationResult {
|
||||
const canonical = toCanonicalAgent(agent);
|
||||
return translateCanonicalAgent(canonical, targetAgent, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a canonical agent to a target format
|
||||
*/
|
||||
export function translateCanonicalAgent(
|
||||
canonical: CanonicalAgent,
|
||||
targetAgent: AgentType,
|
||||
options?: AgentTranslationOptions
|
||||
): AgentTranslationResult {
|
||||
const targetFormat = CUSTOM_AGENT_FORMAT_MAP[targetAgent];
|
||||
const warnings: string[] = [];
|
||||
const incompatible: string[] = [];
|
||||
|
||||
// Track incompatible features
|
||||
if (targetFormat === 'universal') {
|
||||
// Universal format has limited support
|
||||
if (canonical.hooks && canonical.hooks.length > 0) {
|
||||
incompatible.push('hooks (not supported in universal format)');
|
||||
}
|
||||
if (canonical.permissionMode) {
|
||||
incompatible.push('permissionMode (not supported in universal format)');
|
||||
}
|
||||
}
|
||||
|
||||
if (targetFormat === 'cursor-agent') {
|
||||
// Cursor may have different hook syntax
|
||||
if (canonical.hooks && canonical.hooks.length > 0) {
|
||||
warnings.push('Hooks may require manual adjustment for Cursor');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate content based on target format
|
||||
let content: string;
|
||||
|
||||
switch (targetFormat) {
|
||||
case 'claude-agent':
|
||||
content = generateClaudeAgent(canonical, options);
|
||||
break;
|
||||
case 'cursor-agent':
|
||||
content = generateCursorAgent(canonical, options);
|
||||
break;
|
||||
case 'universal':
|
||||
content = generateUniversalAgent(canonical, options);
|
||||
break;
|
||||
default:
|
||||
content = fromCanonicalAgent(canonical, targetFormat);
|
||||
}
|
||||
|
||||
// Determine filename
|
||||
const filename = options?.outputFilename || getAgentFilename(canonical.name, targetAgent);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
content,
|
||||
filename,
|
||||
warnings,
|
||||
incompatible,
|
||||
targetFormat,
|
||||
targetAgent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate agent content directly
|
||||
*/
|
||||
export function translateAgentContent(
|
||||
content: string,
|
||||
_sourceAgent: AgentType,
|
||||
targetAgent: AgentType,
|
||||
options?: AgentTranslationOptions
|
||||
): AgentTranslationResult {
|
||||
// Note: _sourceAgent reserved for future format-specific parsing
|
||||
const agent = parseAgentFromContent(content);
|
||||
|
||||
if (!agent) {
|
||||
return {
|
||||
success: false,
|
||||
content: '',
|
||||
filename: '',
|
||||
warnings: ['Failed to parse agent content'],
|
||||
incompatible: [],
|
||||
targetFormat: CUSTOM_AGENT_FORMAT_MAP[targetAgent],
|
||||
targetAgent,
|
||||
};
|
||||
}
|
||||
|
||||
return translateAgent(agent, targetAgent, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse agent from raw content
|
||||
*/
|
||||
function parseAgentFromContent(content: string): CustomAgent | null {
|
||||
const rawFrontmatter = extractAgentFrontmatter(content);
|
||||
const agentContent = extractAgentContent(content);
|
||||
|
||||
if (!rawFrontmatter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = AgentFrontmatter.safeParse(rawFrontmatter);
|
||||
const frontmatter = parsed.success ? parsed.data : {
|
||||
name: (rawFrontmatter.name as string) || 'unnamed-agent',
|
||||
description: (rawFrontmatter.description as string) || 'No description',
|
||||
...rawFrontmatter,
|
||||
};
|
||||
|
||||
return {
|
||||
name: frontmatter.name,
|
||||
description: frontmatter.description,
|
||||
path: '',
|
||||
location: 'project',
|
||||
frontmatter,
|
||||
content: agentContent,
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Claude Code agent format
|
||||
*/
|
||||
function generateClaudeAgent(
|
||||
canonical: CanonicalAgent,
|
||||
options?: AgentTranslationOptions
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Frontmatter
|
||||
lines.push('---');
|
||||
lines.push(`name: ${canonical.name}`);
|
||||
lines.push(`description: ${escapeYamlString(canonical.description)}`);
|
||||
|
||||
if (canonical.model) {
|
||||
lines.push(`model: ${canonical.model}`);
|
||||
}
|
||||
|
||||
if (canonical.permissionMode) {
|
||||
lines.push(`permissionMode: ${canonical.permissionMode}`);
|
||||
}
|
||||
|
||||
if (canonical.disallowedTools && canonical.disallowedTools.length > 0) {
|
||||
lines.push('disallowedTools:');
|
||||
for (const tool of canonical.disallowedTools) {
|
||||
lines.push(` - ${tool}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
|
||||
lines.push('allowed-tools:');
|
||||
for (const tool of canonical.allowedTools) {
|
||||
lines.push(` - ${tool}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.hooks && canonical.hooks.length > 0) {
|
||||
lines.push('hooks:');
|
||||
for (const hook of canonical.hooks) {
|
||||
lines.push(` - type: ${hook.type}`);
|
||||
lines.push(` command: "${escapeYamlString(hook.command)}"`);
|
||||
if (hook.timeout) lines.push(` timeout: ${hook.timeout}`);
|
||||
if (hook.once) lines.push(` once: true`);
|
||||
if (hook.matcher) lines.push(` matcher: "${hook.matcher}"`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.skills && canonical.skills.length > 0) {
|
||||
lines.push('skills:');
|
||||
for (const skill of canonical.skills) {
|
||||
lines.push(` - ${skill}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (canonical.context) {
|
||||
lines.push(`context: ${canonical.context}`);
|
||||
}
|
||||
|
||||
if (canonical.version) {
|
||||
lines.push(`version: "${canonical.version}"`);
|
||||
}
|
||||
|
||||
if (canonical.author) {
|
||||
lines.push(`author: ${canonical.author}`);
|
||||
}
|
||||
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
lines.push(`tags: [${canonical.tags.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (canonical.userInvocable !== undefined) {
|
||||
lines.push(`user-invocable: ${canonical.userInvocable}`);
|
||||
}
|
||||
|
||||
if (canonical.argumentHint) {
|
||||
lines.push(`argument-hint: "${escapeYamlString(canonical.argumentHint)}"`);
|
||||
}
|
||||
|
||||
if (options?.addMetadata) {
|
||||
lines.push(`# Translated by SkillKit from ${canonical.sourceAgent || 'unknown'}`);
|
||||
}
|
||||
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Content
|
||||
lines.push(canonical.content);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Cursor agent format
|
||||
*/
|
||||
function generateCursorAgent(
|
||||
canonical: CanonicalAgent,
|
||||
options?: AgentTranslationOptions
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Cursor uses .mdc format for rules, but agents might be markdown
|
||||
lines.push('---');
|
||||
lines.push(`name: ${canonical.name}`);
|
||||
lines.push(`description: ${escapeYamlString(canonical.description)}`);
|
||||
|
||||
if (canonical.model) {
|
||||
lines.push(`model: ${canonical.model}`);
|
||||
}
|
||||
|
||||
// Cursor-specific: may use different permission syntax
|
||||
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
|
||||
lines.push(`tools: [${canonical.allowedTools.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (canonical.version) {
|
||||
lines.push(`version: "${canonical.version}"`);
|
||||
}
|
||||
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
lines.push(`tags: [${canonical.tags.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (options?.addMetadata) {
|
||||
lines.push(`# Translated by SkillKit from ${canonical.sourceAgent || 'unknown'}`);
|
||||
}
|
||||
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Content
|
||||
lines.push(canonical.content);
|
||||
|
||||
// Add note about incompatible features
|
||||
if (canonical.hooks && canonical.hooks.length > 0) {
|
||||
lines.push('');
|
||||
lines.push('<!-- Note: Hooks from original agent may need manual configuration -->');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate universal agent format
|
||||
*/
|
||||
function generateUniversalAgent(
|
||||
canonical: CanonicalAgent,
|
||||
options?: AgentTranslationOptions
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Universal format: simplified, portable
|
||||
lines.push('---');
|
||||
lines.push(`name: ${canonical.name}`);
|
||||
lines.push(`description: ${escapeYamlString(canonical.description)}`);
|
||||
|
||||
if (canonical.model) {
|
||||
lines.push(`model: ${canonical.model}`);
|
||||
}
|
||||
|
||||
if (canonical.version) {
|
||||
lines.push(`version: "${canonical.version}"`);
|
||||
}
|
||||
|
||||
if (canonical.author) {
|
||||
lines.push(`author: ${canonical.author}`);
|
||||
}
|
||||
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
lines.push(`tags: [${canonical.tags.join(', ')}]`);
|
||||
}
|
||||
|
||||
if (options?.addMetadata) {
|
||||
lines.push(`# Translated by SkillKit`);
|
||||
if (canonical.sourceAgent) {
|
||||
lines.push(`# Original format: ${canonical.sourceAgent}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Content
|
||||
lines.push(`# ${canonical.name}`);
|
||||
lines.push('');
|
||||
lines.push(canonical.content);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the expected filename for an agent
|
||||
*/
|
||||
export function getAgentFilename(
|
||||
agentName: string,
|
||||
targetAgent: AgentType
|
||||
): string {
|
||||
const format = CUSTOM_AGENT_FORMAT_MAP[targetAgent];
|
||||
|
||||
switch (format) {
|
||||
case 'cursor-agent':
|
||||
return `${agentName}.md`; // Or .mdc if Cursor uses that for agents
|
||||
default:
|
||||
return `${agentName}.md`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target directory for an agent
|
||||
*/
|
||||
export function getAgentTargetDirectory(
|
||||
rootDir: string,
|
||||
targetAgent: AgentType
|
||||
): string {
|
||||
const paths = AGENT_DISCOVERY_PATHS[targetAgent];
|
||||
if (paths && paths.length > 0) {
|
||||
return join(rootDir, paths[0]);
|
||||
}
|
||||
return join(rootDir, 'agents');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in YAML strings
|
||||
*/
|
||||
function escapeYamlString(str: string): string {
|
||||
if (/[:\{\}\[\],&*#?|\-<>=!%@`]/.test(str) || str.includes('\n')) {
|
||||
return `"${str.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate multiple agents
|
||||
*/
|
||||
export function translateAgents(
|
||||
agents: CustomAgent[],
|
||||
targetAgent: AgentType,
|
||||
options?: AgentTranslationOptions
|
||||
): AgentTranslationResult[] {
|
||||
return agents.map(agent => translateAgent(agent, targetAgent, options));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if agent format is compatible with target
|
||||
*/
|
||||
export function isAgentCompatible(
|
||||
sourceFormat: AgentFormatCategory,
|
||||
targetFormat: AgentFormatCategory
|
||||
): { compatible: boolean; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
|
||||
if (sourceFormat === targetFormat) {
|
||||
return { compatible: true, warnings };
|
||||
}
|
||||
|
||||
// All formats can translate to claude-agent (most feature-rich)
|
||||
if (targetFormat === 'claude-agent') {
|
||||
return { compatible: true, warnings };
|
||||
}
|
||||
|
||||
// Universal format loses some features
|
||||
if (targetFormat === 'universal') {
|
||||
if (sourceFormat === 'claude-agent') {
|
||||
warnings.push('Hooks, permissionMode, and disallowedTools will be lost');
|
||||
}
|
||||
return { compatible: true, warnings };
|
||||
}
|
||||
|
||||
// Cursor format has partial support
|
||||
if (targetFormat === 'cursor-agent') {
|
||||
if (sourceFormat === 'claude-agent') {
|
||||
warnings.push('Some Claude-specific features may not translate perfectly');
|
||||
}
|
||||
return { compatible: true, warnings };
|
||||
}
|
||||
|
||||
return { compatible: true, warnings };
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
/**
|
||||
* Agent Types
|
||||
*
|
||||
* Types for custom AI sub-agents (e.g., .claude/agents/*.md)
|
||||
* Based on Claude Code's agent specification.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Agent permission modes
|
||||
*/
|
||||
export const AgentPermissionMode = z.enum([
|
||||
'default', // Normal permission prompts
|
||||
'plan', // Plan mode - ask before executing
|
||||
'auto-edit', // Auto-accept edits
|
||||
'full-auto', // Auto-accept everything (dangerous)
|
||||
'bypassPermissions', // Skip all permission checks
|
||||
]);
|
||||
export type AgentPermissionMode = z.infer<typeof AgentPermissionMode>;
|
||||
|
||||
/**
|
||||
* Agent hook definition
|
||||
*/
|
||||
export const AgentHook = z.object({
|
||||
/** Hook event type */
|
||||
type: z.enum([
|
||||
'PreToolUse',
|
||||
'PostToolUse',
|
||||
'Stop',
|
||||
'SubagentStop',
|
||||
'SessionStart',
|
||||
'SessionEnd',
|
||||
]),
|
||||
/** Command to run */
|
||||
command: z.string(),
|
||||
/** Timeout in milliseconds */
|
||||
timeout: z.number().optional(),
|
||||
/** Run only once */
|
||||
once: z.boolean().optional(),
|
||||
/** Tool matcher (for PreToolUse/PostToolUse) */
|
||||
matcher: z.string().optional(),
|
||||
});
|
||||
export type AgentHook = z.infer<typeof AgentHook>;
|
||||
|
||||
/**
|
||||
* Agent frontmatter schema
|
||||
*/
|
||||
export const AgentFrontmatter = z.object({
|
||||
/** Agent name (kebab-case) */
|
||||
name: z.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Agent name must be lowercase alphanumeric with hyphens'),
|
||||
/** Description of what this agent does */
|
||||
description: z.string().min(1).max(1024),
|
||||
/** Model to use (e.g., 'opus', 'sonnet', 'haiku') */
|
||||
model: z.string().optional(),
|
||||
/** Permission mode for this agent */
|
||||
permissionMode: AgentPermissionMode.optional(),
|
||||
/** Tools this agent cannot use */
|
||||
disallowedTools: z.array(z.string()).optional(),
|
||||
/** Allowed tools for this agent */
|
||||
allowedTools: z.union([
|
||||
z.array(z.string()),
|
||||
z.string(), // YAML-style list in frontmatter
|
||||
]).optional(),
|
||||
/** Agent-scoped hooks */
|
||||
hooks: z.array(AgentHook).optional(),
|
||||
/** Skills to auto-load for this agent */
|
||||
skills: z.array(z.string()).optional(),
|
||||
/** Run in forked sub-agent context */
|
||||
context: z.enum(['fork', 'inline']).optional(),
|
||||
/** Version */
|
||||
version: z.string().optional(),
|
||||
/** Author */
|
||||
author: z.string().optional(),
|
||||
/** Tags for categorization */
|
||||
tags: z.array(z.string()).optional(),
|
||||
/** Whether agent is user-invocable via @mention */
|
||||
'user-invocable': z.boolean().optional(),
|
||||
/** Argument hint for agent invocation */
|
||||
'argument-hint': z.string().optional(),
|
||||
});
|
||||
export type AgentFrontmatter = z.infer<typeof AgentFrontmatter>;
|
||||
|
||||
/**
|
||||
* Agent location (project or global)
|
||||
*/
|
||||
export const AgentLocation = z.enum(['project', 'global']);
|
||||
export type AgentLocation = z.infer<typeof AgentLocation>;
|
||||
|
||||
/**
|
||||
* Agent metadata (stored in .skillkit-agent.json)
|
||||
*/
|
||||
export const AgentMetadata = z.object({
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
source: z.string(),
|
||||
sourceType: z.enum(['github', 'gitlab', 'bitbucket', 'local']),
|
||||
subpath: z.string().optional(),
|
||||
installedAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime().optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
version: z.string().optional(),
|
||||
checksum: z.string().optional(),
|
||||
});
|
||||
export type AgentMetadata = z.infer<typeof AgentMetadata>;
|
||||
|
||||
/**
|
||||
* Parsed agent definition
|
||||
*/
|
||||
export interface CustomAgent {
|
||||
/** Agent name */
|
||||
name: string;
|
||||
/** Description */
|
||||
description: string;
|
||||
/** Path to agent directory or file */
|
||||
path: string;
|
||||
/** Project or global location */
|
||||
location: AgentLocation;
|
||||
/** Full frontmatter */
|
||||
frontmatter: AgentFrontmatter;
|
||||
/** Agent content (system prompt) */
|
||||
content: string;
|
||||
/** Metadata if installed via skillkit */
|
||||
metadata?: AgentMetadata;
|
||||
/** Whether agent is enabled */
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical agent for translation
|
||||
*/
|
||||
export interface CanonicalAgent {
|
||||
/** Agent name */
|
||||
name: string;
|
||||
/** Description */
|
||||
description: string;
|
||||
/** Model to use */
|
||||
model?: string;
|
||||
/** Permission mode */
|
||||
permissionMode?: AgentPermissionMode;
|
||||
/** Disallowed tools */
|
||||
disallowedTools?: string[];
|
||||
/** Allowed tools */
|
||||
allowedTools?: string[];
|
||||
/** Agent-scoped hooks */
|
||||
hooks?: AgentHook[];
|
||||
/** Skills to load */
|
||||
skills?: string[];
|
||||
/** Execution context */
|
||||
context?: 'fork' | 'inline';
|
||||
/** Version */
|
||||
version?: string;
|
||||
/** Author */
|
||||
author?: string;
|
||||
/** Tags */
|
||||
tags?: string[];
|
||||
/** User invocable */
|
||||
userInvocable?: boolean;
|
||||
/** Argument hint */
|
||||
argumentHint?: string;
|
||||
/** Main content (system prompt) */
|
||||
content: string;
|
||||
/** Source format */
|
||||
sourceFormat: AgentFormatCategory;
|
||||
/** Source agent type */
|
||||
sourceAgent?: AgentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent format categories
|
||||
*/
|
||||
export type AgentFormatCategory =
|
||||
| 'claude-agent' // Claude Code .claude/agents/*.md
|
||||
| 'cursor-agent' // Cursor agent format (if different)
|
||||
| 'universal'; // Universal agent format
|
||||
|
||||
/**
|
||||
* Agent translation result
|
||||
*/
|
||||
export interface AgentTranslationResult {
|
||||
/** Whether translation succeeded */
|
||||
success: boolean;
|
||||
/** Translated content */
|
||||
content: string;
|
||||
/** Output filename */
|
||||
filename: string;
|
||||
/** Warnings during translation */
|
||||
warnings: string[];
|
||||
/** Features that couldn't be translated */
|
||||
incompatible: string[];
|
||||
/** Target format */
|
||||
targetFormat: AgentFormatCategory;
|
||||
/** Target agent type */
|
||||
targetAgent: AgentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent translation options
|
||||
*/
|
||||
export interface AgentTranslationOptions {
|
||||
/** Preserve original comments */
|
||||
preserveComments?: boolean;
|
||||
/** Add translation metadata */
|
||||
addMetadata?: boolean;
|
||||
/** Custom output filename */
|
||||
outputFilename?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent discovery paths per AI coding agent (2026 updated)
|
||||
*/
|
||||
export const AGENT_DISCOVERY_PATHS: Record<AgentType, string[]> = {
|
||||
'claude-code': ['.claude/agents'],
|
||||
'cursor': ['.cursor/agents', '.cursor/commands'],
|
||||
'codex': ['.codex/agents'],
|
||||
'gemini-cli': ['.gemini/agents'],
|
||||
'opencode': ['.opencode/agents', '.opencode/agent'],
|
||||
'antigravity': ['.antigravity/agents'],
|
||||
'amp': ['.amp/agents'],
|
||||
'clawdbot': ['.clawdbot/agents', 'agents'],
|
||||
'droid': ['.factory/agents'],
|
||||
'github-copilot': ['.github/agents', '.github/instructions', '.github/custom-agents'],
|
||||
'goose': ['.goose/agents'],
|
||||
'kilo': ['.kilocode/agents', '.kilocode/modes'],
|
||||
'kiro-cli': ['.kiro/agents'],
|
||||
'roo': ['.roo/agents', '.roo/modes'],
|
||||
'trae': ['.trae/agents', '.trae/agent'],
|
||||
'windsurf': ['.windsurf/agents', '.windsurf/workflows'],
|
||||
'universal': ['agents', '.agents'],
|
||||
};
|
||||
|
||||
/**
|
||||
* All agent discovery paths (union of all agent paths) - 2026 updated
|
||||
*/
|
||||
export const ALL_AGENT_DISCOVERY_PATHS = [
|
||||
'agents',
|
||||
'.agents',
|
||||
'.claude/agents',
|
||||
'.cursor/agents',
|
||||
'.cursor/commands',
|
||||
'.codex/agents',
|
||||
'.gemini/agents',
|
||||
'.opencode/agents',
|
||||
'.opencode/agent',
|
||||
'.antigravity/agents',
|
||||
'.amp/agents',
|
||||
'.clawdbot/agents',
|
||||
'.factory/agents',
|
||||
'.github/agents',
|
||||
'.github/instructions',
|
||||
'.github/custom-agents',
|
||||
'.goose/agents',
|
||||
'.kilocode/agents',
|
||||
'.kilocode/modes',
|
||||
'.kiro/agents',
|
||||
'.roo/agents',
|
||||
'.roo/modes',
|
||||
'.trae/agents',
|
||||
'.trae/agent',
|
||||
'.windsurf/agents',
|
||||
'.windsurf/workflows',
|
||||
];
|
||||
|
||||
/**
|
||||
* Agent format mapping (which agents use which format)
|
||||
*/
|
||||
export const CUSTOM_AGENT_FORMAT_MAP: Record<AgentType, AgentFormatCategory> = {
|
||||
'claude-code': 'claude-agent',
|
||||
'cursor': 'cursor-agent',
|
||||
'codex': 'claude-agent',
|
||||
'gemini-cli': 'claude-agent',
|
||||
'opencode': 'claude-agent',
|
||||
'antigravity': 'claude-agent',
|
||||
'amp': 'claude-agent',
|
||||
'clawdbot': 'claude-agent',
|
||||
'droid': 'claude-agent',
|
||||
'github-copilot': 'universal',
|
||||
'goose': 'claude-agent',
|
||||
'kilo': 'claude-agent',
|
||||
'kiro-cli': 'claude-agent',
|
||||
'roo': 'claude-agent',
|
||||
'trae': 'claude-agent',
|
||||
'windsurf': 'universal',
|
||||
'universal': 'universal',
|
||||
};
|
||||
@@ -5,7 +5,6 @@ import type { ContextSyncOptions } from './types.js';
|
||||
import { ContextManager } from './manager.js';
|
||||
import { translateSkillFile } from '../translator/index.js';
|
||||
import { findAllSkills } from '../skills.js';
|
||||
import { AGENT_CONFIG } from '../agent-config.js';
|
||||
|
||||
/**
|
||||
* Result of a sync operation
|
||||
@@ -30,6 +29,29 @@ export interface SyncReport {
|
||||
results: SyncResult[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent directory configuration
|
||||
*/
|
||||
const AGENT_DIRS: Record<AgentType, { skillsDir: string; configFile: string }> = {
|
||||
'claude-code': { skillsDir: '.claude/skills', configFile: 'AGENTS.md' },
|
||||
'cursor': { skillsDir: '.cursor/skills', configFile: '.cursorrules' },
|
||||
'codex': { skillsDir: '.codex/skills', configFile: 'AGENTS.md' },
|
||||
'gemini-cli': { skillsDir: '.gemini/skills', configFile: 'GEMINI.md' },
|
||||
'opencode': { skillsDir: '.opencode/skills', configFile: 'AGENTS.md' },
|
||||
'antigravity': { skillsDir: '.antigravity/skills', configFile: 'AGENTS.md' },
|
||||
'amp': { skillsDir: '.agents/skills', configFile: 'AGENTS.md' },
|
||||
'clawdbot': { skillsDir: 'skills', configFile: 'AGENTS.md' },
|
||||
'droid': { skillsDir: '.factory/skills', configFile: 'AGENTS.md' },
|
||||
'github-copilot': { skillsDir: '.github/skills', configFile: 'AGENTS.md' },
|
||||
'goose': { skillsDir: '.goose/skills', configFile: 'AGENTS.md' },
|
||||
'kilo': { skillsDir: '.kilocode/skills', configFile: 'AGENTS.md' },
|
||||
'kiro-cli': { skillsDir: '.kiro/skills', configFile: 'AGENTS.md' },
|
||||
'roo': { skillsDir: '.roo/skills', configFile: 'AGENTS.md' },
|
||||
'trae': { skillsDir: '.trae/skills', configFile: 'AGENTS.md' },
|
||||
'windsurf': { skillsDir: '.windsurf/skills', configFile: 'AGENTS.md' },
|
||||
'universal': { skillsDir: '.agent/skills', configFile: 'AGENTS.md' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Context Sync
|
||||
*
|
||||
@@ -51,7 +73,7 @@ export class ContextSync {
|
||||
detectAgents(): AgentType[] {
|
||||
const detected: AgentType[] = [];
|
||||
|
||||
for (const [agent, config] of Object.entries(AGENT_CONFIG)) {
|
||||
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
|
||||
const skillsPath = join(this.projectPath, config.skillsDir);
|
||||
const configPath = join(this.projectPath, config.configFile);
|
||||
|
||||
@@ -149,7 +171,7 @@ export class ContextSync {
|
||||
const sourceSkills = skills || this.getSourceSkills();
|
||||
|
||||
// Get target directory
|
||||
const agentConfig = AGENT_CONFIG[agent];
|
||||
const agentConfig = AGENT_DIRS[agent];
|
||||
if (!agentConfig) {
|
||||
result.success = false;
|
||||
result.errors.push(`Unknown agent: ${agent}`);
|
||||
@@ -275,8 +297,8 @@ export class ContextSync {
|
||||
// Search directories based on primary agent or common locations
|
||||
const searchDirs: string[] = [];
|
||||
|
||||
if (primaryAgent && AGENT_CONFIG[primaryAgent]) {
|
||||
searchDirs.push(join(this.projectPath, AGENT_CONFIG[primaryAgent].skillsDir));
|
||||
if (primaryAgent && AGENT_DIRS[primaryAgent]) {
|
||||
searchDirs.push(join(this.projectPath, AGENT_DIRS[primaryAgent].skillsDir));
|
||||
}
|
||||
|
||||
// Add common skill locations
|
||||
@@ -305,7 +327,7 @@ export class ContextSync {
|
||||
checkStatus(): Record<AgentType, { hasSkills: boolean; skillCount: number; skills: string[] }> {
|
||||
const status: Record<string, { hasSkills: boolean; skillCount: number; skills: string[] }> = {};
|
||||
|
||||
for (const [agent, config] of Object.entries(AGENT_CONFIG)) {
|
||||
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
|
||||
const skillsPath = join(this.projectPath, config.skillsDir);
|
||||
const skills: string[] = [];
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// Types
|
||||
export * from './types.js';
|
||||
|
||||
// Centralized Agent Configuration (single source of truth)
|
||||
export * from './agent-config.js';
|
||||
|
||||
// Skills discovery and parsing
|
||||
export * from './skills.js';
|
||||
|
||||
@@ -69,9 +66,3 @@ export * from './ai/index.js';
|
||||
|
||||
// Audit Logging (Phase 18)
|
||||
export * from './audit/index.js';
|
||||
|
||||
// Custom Agents Support (Phase 19)
|
||||
export * from './agents/index.js';
|
||||
|
||||
// Skill Translator (Phase 20 - Cross-Agent Skill Translation)
|
||||
export * from './skill-translator.js';
|
||||
|
||||
@@ -128,8 +128,8 @@ export async function buildSkillIndex(
|
||||
onProgress?.('No skills fetched, using sample index...');
|
||||
allSkills.push(...getSampleSkills());
|
||||
sources.push({
|
||||
name: 'built-in',
|
||||
url: 'https://github.com/rohitg00/skillkit',
|
||||
name: 'skillkit-samples',
|
||||
url: 'https://github.com/skillkit/samples',
|
||||
lastFetched: new Date().toISOString(),
|
||||
skillCount: allSkills.length,
|
||||
});
|
||||
@@ -198,7 +198,7 @@ function getSampleSkills(): SkillSummary[] {
|
||||
{
|
||||
name: 'react-best-practices',
|
||||
description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization',
|
||||
source: 'built-in',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['react', 'frontend', 'typescript', 'nextjs', 'performance'],
|
||||
compatibility: {
|
||||
frameworks: ['react', 'nextjs'],
|
||||
@@ -213,7 +213,7 @@ function getSampleSkills(): SkillSummary[] {
|
||||
{
|
||||
name: 'tailwind-patterns',
|
||||
description: 'Tailwind CSS utility patterns, responsive design, and component styling best practices',
|
||||
source: 'built-in',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
@@ -228,7 +228,7 @@ function getSampleSkills(): SkillSummary[] {
|
||||
{
|
||||
name: 'typescript-strict-patterns',
|
||||
description: 'TypeScript strict mode patterns, type safety, and advanced type utilities',
|
||||
source: 'built-in',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['typescript', 'types', 'safety', 'patterns'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
@@ -243,7 +243,7 @@ function getSampleSkills(): SkillSummary[] {
|
||||
{
|
||||
name: 'security-best-practices',
|
||||
description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers',
|
||||
source: 'built-in',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['security', 'xss', 'csrf', 'headers', 'owasp'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
@@ -258,7 +258,7 @@ function getSampleSkills(): SkillSummary[] {
|
||||
{
|
||||
name: 'testing-patterns',
|
||||
description: 'Testing patterns with Vitest/Jest including mocking, assertions, and test organization',
|
||||
source: 'built-in',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['vitest', 'jest', 'testing', 'typescript', 'mocking', 'tdd'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
|
||||
@@ -1,692 +0,0 @@
|
||||
/**
|
||||
* Skill Translator
|
||||
*
|
||||
* Translates SKILL.md files between different AI coding agent formats.
|
||||
* This is the core functionality for SkillKit's cross-agent skill ecosystem.
|
||||
*/
|
||||
|
||||
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join, basename, dirname, resolve, relative, isAbsolute } from 'node:path';
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
import type { AgentType, Skill } from './types.js';
|
||||
import {
|
||||
AGENT_CONFIG,
|
||||
type AgentDirectoryConfig,
|
||||
getSkillsDir,
|
||||
getConfigFile,
|
||||
getAllSkillsDirs as getAgentAllSkillsDirs,
|
||||
getGlobalSkillsDir as getAgentGlobalSkillsDir,
|
||||
supportsAutoDiscovery as agentSupportsAutoDiscovery,
|
||||
} from './agent-config.js';
|
||||
|
||||
/**
|
||||
* Extended skill format for translation (includes invokeCommand)
|
||||
*/
|
||||
export interface AgentSkillFormat extends AgentDirectoryConfig {
|
||||
invokeCommand: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent-specific skill format configurations
|
||||
* Extends AGENT_CONFIG with invokeCommand for all agents
|
||||
*/
|
||||
export const AGENT_SKILL_FORMATS: Record<AgentType, AgentSkillFormat> = Object.fromEntries(
|
||||
Object.entries(AGENT_CONFIG).map(([agent, config]) => [
|
||||
agent,
|
||||
{ ...config, invokeCommand: 'skillkit read' },
|
||||
])
|
||||
) as Record<AgentType, AgentSkillFormat>;
|
||||
|
||||
/**
|
||||
* Canonical skill representation for cross-agent translation
|
||||
*/
|
||||
export interface CrossAgentSkill {
|
||||
name: string;
|
||||
description: string;
|
||||
content: string;
|
||||
frontmatter: Record<string, unknown>;
|
||||
sourcePath: string;
|
||||
sourceAgent?: AgentType;
|
||||
version?: string;
|
||||
author?: string;
|
||||
tags?: string[];
|
||||
allowedTools?: string[];
|
||||
/** Agent-specific fields preserved during translation */
|
||||
agentFields?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill translation result
|
||||
*/
|
||||
export interface SkillTranslationResult {
|
||||
success: boolean;
|
||||
content: string;
|
||||
filename: string;
|
||||
targetDir: string;
|
||||
warnings: string[];
|
||||
incompatible: string[];
|
||||
targetAgent: AgentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill translation options
|
||||
*/
|
||||
export interface SkillTranslationOptions {
|
||||
/** Preserve original comments and formatting */
|
||||
preserveComments?: boolean;
|
||||
/** Add translation metadata comment */
|
||||
addMetadata?: boolean;
|
||||
/** Custom output filename */
|
||||
outputFilename?: string;
|
||||
/** Overwrite existing files */
|
||||
overwrite?: boolean;
|
||||
/** Write to disk */
|
||||
write?: boolean;
|
||||
/** Output directory override */
|
||||
outputDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a SKILL.md file into canonical format
|
||||
*/
|
||||
export function parseSkillToCanonical(
|
||||
skillPath: string,
|
||||
sourceAgent?: AgentType
|
||||
): CrossAgentSkill | null {
|
||||
const skillMdPath = skillPath.endsWith('SKILL.md')
|
||||
? skillPath
|
||||
: join(skillPath, 'SKILL.md');
|
||||
|
||||
if (!existsSync(skillMdPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
return parseSkillContentToCanonical(content, skillPath, sourceAgent);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse skill content string into canonical format
|
||||
*/
|
||||
export function parseSkillContentToCanonical(
|
||||
content: string,
|
||||
sourcePath: string,
|
||||
sourceAgent?: AgentType
|
||||
): CrossAgentSkill | null {
|
||||
const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
|
||||
|
||||
let frontmatter: Record<string, unknown> = {};
|
||||
let bodyContent = content;
|
||||
|
||||
if (frontmatterMatch) {
|
||||
try {
|
||||
frontmatter = parseYaml(frontmatterMatch[1]) as Record<string, unknown>;
|
||||
bodyContent = content.slice(frontmatterMatch[0].length).trim();
|
||||
} catch {
|
||||
// Continue without frontmatter
|
||||
}
|
||||
}
|
||||
|
||||
// If sourcePath is a directory (skill folder), use its basename
|
||||
// If sourcePath is a file (SKILL.md), use the parent directory's basename
|
||||
const name = (frontmatter.name as string) || basename(sourcePath.endsWith('.md') ? dirname(sourcePath) : sourcePath);
|
||||
const description = (frontmatter.description as string) || extractDescriptionFromContent(bodyContent);
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
content: bodyContent,
|
||||
frontmatter,
|
||||
sourcePath,
|
||||
sourceAgent,
|
||||
version: frontmatter.version as string | undefined,
|
||||
author: frontmatter.author as string | undefined,
|
||||
tags: frontmatter.tags as string[] | undefined,
|
||||
allowedTools: parseAllowedTools(frontmatter['allowed-tools']),
|
||||
agentFields: extractAgentSpecificFields(frontmatter, sourceAgent),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract description from markdown content if not in frontmatter
|
||||
*/
|
||||
function extractDescriptionFromContent(content: string): string {
|
||||
// Try to find first paragraph or first heading
|
||||
const lines = content.split('\n').filter(line => line.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
// Skip headings
|
||||
if (trimmed.startsWith('#')) continue;
|
||||
// Skip code blocks
|
||||
if (trimmed.startsWith('```')) continue;
|
||||
// Return first substantive line
|
||||
if (trimmed.length > 10) {
|
||||
return trimmed.slice(0, 200) + (trimmed.length > 200 ? '...' : '');
|
||||
}
|
||||
}
|
||||
|
||||
return 'No description available';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse allowed-tools field (can be string or array)
|
||||
*/
|
||||
function parseAllowedTools(value: unknown): string[] | undefined {
|
||||
if (!value) return undefined;
|
||||
if (Array.isArray(value)) return value;
|
||||
if (typeof value === 'string') {
|
||||
return value.split(',').map(t => t.trim()).filter(Boolean);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract agent-specific fields from frontmatter
|
||||
*/
|
||||
function extractAgentSpecificFields(
|
||||
frontmatter: Record<string, unknown>,
|
||||
_sourceAgent?: AgentType
|
||||
): Record<string, unknown> {
|
||||
const agentFields: Record<string, unknown> = {};
|
||||
|
||||
// Preserve special fields that might be agent-specific
|
||||
const specialFields = [
|
||||
'disable-model-invocation',
|
||||
'user-invocable',
|
||||
'argument-hint',
|
||||
'model',
|
||||
'context',
|
||||
'agent',
|
||||
'globs',
|
||||
'alwaysApply',
|
||||
'applyTo',
|
||||
'mode',
|
||||
'hooks',
|
||||
'permissionMode',
|
||||
];
|
||||
|
||||
for (const field of specialFields) {
|
||||
if (field in frontmatter) {
|
||||
agentFields[field] = frontmatter[field];
|
||||
}
|
||||
}
|
||||
|
||||
return agentFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a cross-agent skill to target agent format
|
||||
*/
|
||||
export function translateSkillToAgent(
|
||||
canonical: CrossAgentSkill,
|
||||
targetAgent: AgentType,
|
||||
options?: SkillTranslationOptions
|
||||
): SkillTranslationResult {
|
||||
const format = AGENT_SKILL_FORMATS[targetAgent];
|
||||
const warnings: string[] = [];
|
||||
const incompatible: string[] = [];
|
||||
|
||||
// Check for incompatible features
|
||||
if (canonical.agentFields?.['hooks'] && targetAgent !== 'claude-code') {
|
||||
incompatible.push('hooks (only supported in Claude Code)');
|
||||
}
|
||||
|
||||
if (canonical.agentFields?.['permissionMode'] && !['claude-code', 'roo'].includes(targetAgent)) {
|
||||
warnings.push('permissionMode may not be fully supported');
|
||||
}
|
||||
|
||||
// Generate SKILL.md content for target agent
|
||||
const content = generateSkillContent(canonical, targetAgent, format, options);
|
||||
|
||||
// Determine output filename and directory
|
||||
const filename = options?.outputFilename || 'SKILL.md';
|
||||
const targetDir = options?.outputDir || join(format.skillsDir, canonical.name);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
content,
|
||||
filename,
|
||||
targetDir,
|
||||
warnings,
|
||||
incompatible,
|
||||
targetAgent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate SKILL.md content for target agent
|
||||
*/
|
||||
function generateSkillContent(
|
||||
canonical: CrossAgentSkill,
|
||||
targetAgent: AgentType,
|
||||
format: AgentSkillFormat,
|
||||
options?: SkillTranslationOptions
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Build frontmatter
|
||||
const frontmatter: Record<string, unknown> = {
|
||||
name: canonical.name,
|
||||
description: canonical.description,
|
||||
};
|
||||
|
||||
// Add version and author if present
|
||||
if (canonical.version) {
|
||||
frontmatter.version = canonical.version;
|
||||
}
|
||||
if (canonical.author) {
|
||||
frontmatter.author = canonical.author;
|
||||
}
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
frontmatter.tags = canonical.tags;
|
||||
}
|
||||
|
||||
// Add allowed-tools if present
|
||||
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
|
||||
frontmatter['allowed-tools'] = canonical.allowedTools.join(', ');
|
||||
}
|
||||
|
||||
// Add agent-specific fields based on target
|
||||
addAgentSpecificFields(frontmatter, canonical, targetAgent, format);
|
||||
|
||||
// Add translation metadata if requested
|
||||
if (options?.addMetadata && canonical.sourceAgent) {
|
||||
frontmatter['_translated-from'] = canonical.sourceAgent;
|
||||
frontmatter['_translated-at'] = new Date().toISOString();
|
||||
}
|
||||
|
||||
// Generate YAML frontmatter
|
||||
lines.push('---');
|
||||
lines.push(stringifyYaml(frontmatter).trim());
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Add content
|
||||
lines.push(canonical.content);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add agent-specific fields to frontmatter
|
||||
*/
|
||||
function addAgentSpecificFields(
|
||||
frontmatter: Record<string, unknown>,
|
||||
canonical: CrossAgentSkill,
|
||||
targetAgent: AgentType,
|
||||
_format: AgentSkillFormat
|
||||
): void {
|
||||
// Claude Code specific
|
||||
if (targetAgent === 'claude-code') {
|
||||
if ('model' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.model = canonical.agentFields!['model'];
|
||||
}
|
||||
if ('context' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.context = canonical.agentFields!['context'];
|
||||
}
|
||||
if ('agent' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.agent = canonical.agentFields!['agent'];
|
||||
}
|
||||
if ('disable-model-invocation' in (canonical.agentFields ?? {})) {
|
||||
frontmatter['disable-model-invocation'] = canonical.agentFields!['disable-model-invocation'];
|
||||
}
|
||||
if ('user-invocable' in (canonical.agentFields ?? {})) {
|
||||
frontmatter['user-invocable'] = canonical.agentFields!['user-invocable'];
|
||||
}
|
||||
if ('argument-hint' in (canonical.agentFields ?? {})) {
|
||||
frontmatter['argument-hint'] = canonical.agentFields!['argument-hint'];
|
||||
}
|
||||
if ('hooks' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.hooks = canonical.agentFields!['hooks'];
|
||||
}
|
||||
if ('permissionMode' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.permissionMode = canonical.agentFields!['permissionMode'];
|
||||
}
|
||||
}
|
||||
|
||||
// Cursor/Trae/Windsurf specific (MDC-style)
|
||||
if (['cursor', 'trae', 'windsurf'].includes(targetAgent)) {
|
||||
if ('globs' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.globs = canonical.agentFields!['globs'];
|
||||
}
|
||||
if ('alwaysApply' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.alwaysApply = canonical.agentFields!['alwaysApply'];
|
||||
}
|
||||
if (targetAgent === 'windsurf' && 'mode' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.mode = canonical.agentFields!['mode'];
|
||||
}
|
||||
}
|
||||
|
||||
// GitHub Copilot specific
|
||||
if (targetAgent === 'github-copilot') {
|
||||
if ('applyTo' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.applyTo = canonical.agentFields!['applyTo'];
|
||||
}
|
||||
}
|
||||
|
||||
// Roo specific
|
||||
if (targetAgent === 'roo') {
|
||||
if ('disable-model-invocation' in (canonical.agentFields ?? {})) {
|
||||
frontmatter['disable-model-invocation'] = canonical.agentFields!['disable-model-invocation'];
|
||||
}
|
||||
if ('user-invocable' in (canonical.agentFields ?? {})) {
|
||||
frontmatter['user-invocable'] = canonical.agentFields!['user-invocable'];
|
||||
}
|
||||
if ('permissionMode' in (canonical.agentFields ?? {})) {
|
||||
frontmatter.permissionMode = canonical.agentFields!['permissionMode'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a skill file to multiple target agents
|
||||
*/
|
||||
export function translateSkillToAll(
|
||||
skillPath: string,
|
||||
sourceAgent?: AgentType,
|
||||
options?: SkillTranslationOptions
|
||||
): Map<AgentType, SkillTranslationResult> {
|
||||
const canonical = parseSkillToCanonical(skillPath, sourceAgent);
|
||||
if (!canonical) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const results = new Map<AgentType, SkillTranslationResult>();
|
||||
const agents: AgentType[] = [
|
||||
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
|
||||
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
|
||||
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
|
||||
];
|
||||
|
||||
for (const agent of agents) {
|
||||
if (agent !== sourceAgent) {
|
||||
results.set(agent, translateSkillToAgent(canonical, agent, options));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write translated skill to disk
|
||||
*/
|
||||
export function writeTranslatedSkill(
|
||||
result: SkillTranslationResult,
|
||||
rootDir: string,
|
||||
options?: { overwrite?: boolean }
|
||||
): { success: boolean; path: string; error?: string; skipped?: boolean } {
|
||||
// Don't write if translation failed
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
path: '',
|
||||
error: 'Translation failed',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rootPath = resolve(rootDir);
|
||||
const filePath = resolve(rootDir, result.targetDir, result.filename);
|
||||
const targetPath = dirname(filePath);
|
||||
|
||||
// Guard against path traversal
|
||||
const relPath = relative(rootPath, filePath);
|
||||
if (relPath.startsWith('..') || isAbsolute(relPath)) {
|
||||
return {
|
||||
success: false,
|
||||
path: filePath,
|
||||
error: 'Resolved output path escapes rootDir',
|
||||
};
|
||||
}
|
||||
|
||||
// Check if file exists and overwrite is disabled
|
||||
if (existsSync(filePath) && options?.overwrite === false) {
|
||||
return {
|
||||
success: false,
|
||||
path: filePath,
|
||||
error: 'File exists and overwrite=false',
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Create directory if needed
|
||||
if (!existsSync(targetPath)) {
|
||||
mkdirSync(targetPath, { recursive: true });
|
||||
}
|
||||
|
||||
writeFileSync(filePath, result.content, 'utf-8');
|
||||
|
||||
return { success: true, path: filePath };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
path: '',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate config file content that references skills
|
||||
* This generates the agent-specific config format (AGENTS.md, .cursorrules, etc.)
|
||||
*/
|
||||
export function generateSkillsConfig(
|
||||
skills: Skill[],
|
||||
targetAgent: AgentType
|
||||
): string {
|
||||
const format = AGENT_SKILL_FORMATS[targetAgent];
|
||||
const enabledSkills = skills.filter(s => s.enabled);
|
||||
|
||||
if (enabledSkills.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
switch (format.configFormat) {
|
||||
case 'xml':
|
||||
return generateXmlConfig(enabledSkills, format);
|
||||
case 'mdc':
|
||||
return generateMdcConfig(enabledSkills, format);
|
||||
case 'markdown-table':
|
||||
return generateMarkdownTableConfig(enabledSkills, format);
|
||||
case 'json':
|
||||
return generateJsonConfig(enabledSkills, format);
|
||||
case 'markdown':
|
||||
return generateMarkdownConfig(enabledSkills, format);
|
||||
default:
|
||||
return generateMarkdownConfig(enabledSkills, format);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate XML-style config (Claude Code, OpenCode, etc.)
|
||||
*/
|
||||
function generateXmlConfig(skills: Skill[], format: AgentSkillFormat): string {
|
||||
const skillsXml = skills.map(s => `<skill>
|
||||
<name>${escapeXml(s.name)}</name>
|
||||
<description>${escapeXml(s.description)}</description>
|
||||
<location>${escapeXml(s.path)}</location>
|
||||
</skill>`).join('\n\n');
|
||||
|
||||
return `<skills_system priority="1">
|
||||
|
||||
## Available Skills
|
||||
|
||||
<!-- SKILLS_TABLE_START -->
|
||||
<usage>
|
||||
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
||||
|
||||
How to use skills:
|
||||
- Invoke: \`${format.invokeCommand} <skill-name>\` or \`npx ${format.invokeCommand} <skill-name>\`
|
||||
- The skill content will load with detailed instructions on how to complete the task
|
||||
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
|
||||
|
||||
Usage notes:
|
||||
- Only use skills listed in <available_skills> below
|
||||
- Do not invoke a skill that is already loaded in your context
|
||||
- Each skill invocation is stateless
|
||||
</usage>
|
||||
|
||||
<available_skills>
|
||||
|
||||
${skillsXml}
|
||||
|
||||
</available_skills>
|
||||
<!-- SKILLS_TABLE_END -->
|
||||
|
||||
</skills_system>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MDC-style config (Cursor)
|
||||
*/
|
||||
function generateMdcConfig(skills: Skill[], format: AgentSkillFormat): string {
|
||||
const skillsList = skills
|
||||
.map(s => `- **${s.name}**: ${s.description}`)
|
||||
.join('\n');
|
||||
|
||||
const skillsXml = skills.map(s => `<skill>
|
||||
<name>${escapeXml(s.name)}</name>
|
||||
<description>${escapeXml(s.description)}</description>
|
||||
<location>${escapeXml(s.path)}</location>
|
||||
</skill>`).join('\n\n');
|
||||
|
||||
return `---
|
||||
description: SkillKit skills integration - provides specialized capabilities and domain knowledge
|
||||
globs: "**/*"
|
||||
alwaysApply: true
|
||||
---
|
||||
# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed.
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skillsList}
|
||||
|
||||
## How to Use Skills
|
||||
|
||||
When a task matches a skill's description, load it with:
|
||||
\`\`\`bash
|
||||
${format.invokeCommand} <skill-name>
|
||||
\`\`\`
|
||||
|
||||
The skill will provide detailed instructions for completing the task.
|
||||
|
||||
<!-- SKILLS_DATA_START -->
|
||||
${skillsXml}
|
||||
<!-- SKILLS_DATA_END -->
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Markdown table config (Codex)
|
||||
*/
|
||||
function generateMarkdownTableConfig(skills: Skill[], format: AgentSkillFormat): string {
|
||||
const skillsList = skills
|
||||
.map(s => `| ${s.name} | ${s.description} | \`${format.invokeCommand} ${s.name}\` |`)
|
||||
.join('\n');
|
||||
|
||||
return `# Skills
|
||||
|
||||
You have access to specialized skills for completing complex tasks.
|
||||
|
||||
| Skill | Description | Command |
|
||||
|-------|-------------|---------|
|
||||
${skillsList}
|
||||
|
||||
## Usage
|
||||
|
||||
When a task matches a skill's capability, run the command to load detailed instructions:
|
||||
|
||||
\`\`\`bash
|
||||
${format.invokeCommand} <skill-name>
|
||||
\`\`\`
|
||||
|
||||
Skills are loaded on-demand to keep context clean. Only load skills when relevant to the current task.
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate JSON config (Gemini CLI)
|
||||
*/
|
||||
function generateJsonConfig(skills: Skill[], format: AgentSkillFormat): string {
|
||||
const skillsJson = skills.map(s => ({
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
invoke: `${format.invokeCommand} ${s.name}`,
|
||||
location: s.path,
|
||||
}));
|
||||
|
||||
return `# Skills Configuration
|
||||
|
||||
You have access to specialized skills that extend your capabilities.
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skills.map(s => `### ${s.name}\n${s.description}\n\nInvoke: \`${format.invokeCommand} ${s.name}\``).join('\n\n')}
|
||||
|
||||
## Skills Data
|
||||
|
||||
\`\`\`json
|
||||
${JSON.stringify(skillsJson, null, 2)}
|
||||
\`\`\`
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
1. When a task matches a skill's description, load it using the invoke command
|
||||
2. Skills provide step-by-step instructions for complex tasks
|
||||
3. Each skill is self-contained with its own resources
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Markdown config (Windsurf, Trae, GitHub Copilot)
|
||||
*/
|
||||
function generateMarkdownConfig(skills: Skill[], format: AgentSkillFormat): string {
|
||||
const skillsList = skills
|
||||
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`${format.invokeCommand} ${s.name}\``)
|
||||
.join('\n\n');
|
||||
|
||||
return `# Skills System
|
||||
|
||||
You have access to specialized skills that can help complete tasks.
|
||||
|
||||
## Available Skills
|
||||
|
||||
${skillsList}
|
||||
|
||||
## How to Use Skills
|
||||
|
||||
When a task matches a skill's description, load it:
|
||||
|
||||
\`\`\`bash
|
||||
${format.invokeCommand} <skill-name>
|
||||
\`\`\`
|
||||
|
||||
Skills provide detailed instructions for completing complex tasks.
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape XML special characters
|
||||
*/
|
||||
function escapeXml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Re-export utility functions from centralized config with legacy names for backwards compatibility
|
||||
export const getAgentSkillsDir = getSkillsDir;
|
||||
export const getAgentConfigFile = getConfigFile;
|
||||
export { agentSupportsAutoDiscovery as supportsAutoDiscovery };
|
||||
export { getAgentAllSkillsDirs as getAllSkillsDirs };
|
||||
export { getAgentGlobalSkillsDir as getGlobalSkillsDir };
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/tui",
|
||||
"version": "1.6.4",
|
||||
"version": "1.5.0",
|
||||
"description": "Terminal UI for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
Reference in New Issue
Block a user