mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-20 12:23:29 +00:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fc62f4e42 | ||
|
|
b3ba8eb59e | ||
|
|
44ed5c2485 | ||
|
|
3d0195f180 | ||
|
|
e74f7d6b57 | ||
|
|
9688959361 | ||
|
|
7805a5fd4b | ||
|
|
b34177ca85 | ||
|
|
2fa62e6863 | ||
|
|
64b802a1e6 | ||
|
|
d3ffb79512 | ||
|
|
b008a46b8d | ||
|
|
ed90080786 | ||
|
|
b701bb5f47 | ||
|
|
1c4c9a794f | ||
|
|
cb37ebeca7 | ||
|
|
7053d1a2b2 | ||
|
|
1ea5ddd4c7 | ||
|
|
720532c020 | ||
|
|
bc12775e0e |
@@ -5,463 +5,333 @@
|
||||
[](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**The universal skills platform for AI coding agents.** Install, manage, translate, and sync skills across 17+ AI tools with smart recommendations.
|
||||
## One CLI. 17 AI Agents. Zero Lock-in.
|
||||
|
||||
**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 && skillkit
|
||||
npm install -g skillkit
|
||||
```
|
||||
|
||||
## Why SkillKit?
|
||||
## What's New in v1.5.0
|
||||
|
||||
| Problem | SkillKit Solution |
|
||||
|---------|------------------|
|
||||
| Skills only work with one agent | **Cross-agent translation** - use any skill with any agent |
|
||||
| Don't know which skills to install | **Smart recommendations** - project-aware suggestions |
|
||||
| Config fragmented across agents | **One config, all agents** - sync everywhere |
|
||||
| Manual skill discovery | **Task-based search** - find skills by what you need |
|
||||
- **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
|
||||
|
||||
## 30-Second Quick Start
|
||||
## The Problem
|
||||
|
||||
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 globally
|
||||
# Install a skill for ALL your agents at once
|
||||
skillkit install anthropics/skills --agent claude-code,cursor,windsurf
|
||||
|
||||
# Or translate existing skills between any agents
|
||||
skillkit translate my-skill --from claude --to cursor,codex,copilot
|
||||
|
||||
# Get smart recommendations based on your project
|
||||
skillkit recommend
|
||||
# > 92% match: vercel-react-best-practices
|
||||
# > 87% match: tailwind-v4-patterns
|
||||
# > 85% match: nextjs-app-router
|
||||
```
|
||||
|
||||

|
||||
|
||||
## What Makes SkillKit Different
|
||||
|
||||
| Feature | Without SkillKit | With SkillKit |
|
||||
|---------|-----------------|---------------|
|
||||
| **Multi-Agent Support** | Manual rewrite for each agent | One command, all agents |
|
||||
| **Team Collaboration** | Email skills back and forth | Git-based bundles, remote sync |
|
||||
| **Skill Discovery** | Search GitHub manually | Smart recommendations for your stack |
|
||||
| **Format Translation** | Learn each agent's format | Automatic conversion (17 formats) |
|
||||
| **Context Sync** | Configure each agent separately | One config, synced everywhere |
|
||||
| **Session Memory** | Knowledge dies with each session | Persistent learning across agents |
|
||||
| **Skill Testing** | Hope it works | Test framework with assertions |
|
||||
|
||||
## 5-Minute Quick Start
|
||||
|
||||
```bash
|
||||
# 1. Install SkillKit globally
|
||||
npm install -g skillkit
|
||||
|
||||
# Get personalized skill recommendations for your project
|
||||
# 2. Launch the interactive TUI (easiest way to start)
|
||||
skillkit
|
||||
|
||||
# Or use CLI commands directly:
|
||||
|
||||
# 3. Get personalized skill recommendations
|
||||
skillkit recommend
|
||||
|
||||
# Install top-rated skills
|
||||
# 4. Install skills from the marketplace
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit
|
||||
# 5. Sync to your AI agent
|
||||
skillkit sync
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### Smart Recommendations
|
||||
Analyzes your project and suggests the best skills:
|
||||
|
||||
```bash
|
||||
skillkit recommend
|
||||
# Project: my-app (Next.js + TypeScript + Tailwind)
|
||||
#
|
||||
# Recommended Skills:
|
||||
# 92% ██████████ vercel-react-best-practices
|
||||
# 87% █████████░ tailwind-v4-patterns
|
||||
# 85% █████████░ nextjs-app-router
|
||||
```
|
||||
## Core Features
|
||||
|
||||
### Cross-Agent Translation
|
||||
Use any skill with any agent - automatic format conversion:
|
||||
|
||||
Use any skill with any agent. SkillKit automatically converts between formats:
|
||||
|
||||
```bash
|
||||
# Translate a Claude skill to Cursor format
|
||||
skillkit translate react-patterns --to cursor
|
||||
|
||||
# Translate all skills for a new agent
|
||||
skillkit translate --all --to antigravity
|
||||
# Translate all your skills to a new agent
|
||||
skillkit translate --all --to windsurf
|
||||
|
||||
# Preview translation without writing
|
||||
skillkit translate my-skill --to codex --dry-run
|
||||
```
|
||||
|
||||
### Project Context Sync
|
||||
Configure once, sync to all your agents:
|
||||
**Supported Agents:** Claude Code, Cursor, Codex, Gemini CLI, OpenCode, Antigravity, Amp, Clawdbot, Droid, GitHub Copilot, Goose, Kilo, Kiro, Roo, Trae, Windsurf, Universal
|
||||
|
||||
### Smart Recommendations
|
||||
|
||||
SkillKit analyzes your project and suggests the perfect skills:
|
||||
|
||||
```bash
|
||||
# Analyze project and create context
|
||||
skillkit context init
|
||||
skillkit recommend
|
||||
|
||||
# Sync your config to all detected agents
|
||||
skillkit context sync --all
|
||||
# Project: my-app (Next.js + TypeScript + Tailwind)
|
||||
#
|
||||
# Recommended Skills:
|
||||
# 92% vercel-react-best-practices
|
||||
# 87% tailwind-v4-patterns
|
||||
# 85% nextjs-app-router
|
||||
# 78% typescript-strict-mode
|
||||
```
|
||||
|
||||
## Interactive TUI
|
||||
Filter by task, category, or minimum score:
|
||||
|
||||
Launch the beautiful terminal interface:
|
||||
```bash
|
||||
skillkit recommend --search "auth" # Task-based search
|
||||
skillkit recommend --category security # Category filter
|
||||
skillkit recommend --min-score 80 # Quality threshold
|
||||
```
|
||||
|
||||
### Session Memory System
|
||||
|
||||
Your AI agents learn, but that knowledge dies with the session. SkillKit captures learnings and makes them persistent:
|
||||
|
||||
```bash
|
||||
# Compress session observations into reusable learnings
|
||||
skillkit memory compress
|
||||
|
||||
# Search past learnings
|
||||
skillkit memory search "authentication patterns"
|
||||
|
||||
# Export a learning as a shareable skill
|
||||
skillkit memory export auth-insight --output auth-patterns.md
|
||||
|
||||
# Share memory across projects
|
||||
skillkit memory --global
|
||||
```
|
||||
|
||||
### Skill Marketplace
|
||||
|
||||
Browse and install from curated skill repositories:
|
||||
|
||||
```bash
|
||||
# Browse all available skills
|
||||
skillkit marketplace
|
||||
|
||||
# Search for specific skills
|
||||
skillkit marketplace search "react hooks"
|
||||
|
||||
# Filter by tags
|
||||
skillkit marketplace --tags typescript,testing
|
||||
|
||||
# Refresh the skill index
|
||||
skillkit marketplace refresh
|
||||
```
|
||||
|
||||
### Interactive TUI
|
||||
|
||||
Beautiful terminal interface for visual skill management:
|
||||
|
||||
```bash
|
||||
skillkit ui
|
||||
# or simply
|
||||
# or just
|
||||
skillkit
|
||||
```
|
||||
|
||||

|
||||
**Navigation:** `h` Home | `b` Browse | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
|
||||
|
||||
**Features:**
|
||||
- Browse 33+ skill repositories
|
||||
- Smart skill recommendations based on your project
|
||||
- Install skills with one keystroke
|
||||
- Multi-agent installation support
|
||||
- Cross-agent skill translation
|
||||
- Responsive design for all terminal sizes
|
||||
### Skill Testing Framework
|
||||
|
||||
**Navigation:**
|
||||
- `h` Home | `b` Browse | `r` Recommend | `l` List | `s` Sync | `,` Config
|
||||
- `↑↓` Navigate | `Enter` Select | `Esc` Back | `q` Quit
|
||||
- `m` Multi-agent selection | `/` Search
|
||||
|
||||
### Compatible With
|
||||
|
||||
| Agent | Status |
|
||||
|-------|--------|
|
||||
| Claude Code | ✅ Native |
|
||||
| OpenAI Codex | ✅ Native |
|
||||
| Cursor | ✅ Native |
|
||||
| Gemini CLI | ✅ Native |
|
||||
| OpenCode | ✅ Native |
|
||||
| Antigravity | ✅ Native |
|
||||
| Amp | ✅ Native |
|
||||
| Clawdbot | ✅ Native |
|
||||
| Droid (Factory) | ✅ Native |
|
||||
| GitHub Copilot | ✅ Native |
|
||||
| Goose | ✅ Native |
|
||||
| Kilo Code | ✅ Native |
|
||||
| Kiro CLI | ✅ Native |
|
||||
| Roo Code | ✅ Native |
|
||||
| Trae | ✅ Native |
|
||||
| Windsurf | ✅ Native |
|
||||
| *Any markdown-config agent* | ✅ Universal |
|
||||
|
||||
## Features
|
||||
|
||||
- **Smart Recommendations**: AI-powered skill suggestions based on your project stack
|
||||
- **Cross-Agent Translation**: Convert skills between any of 17+ agent formats
|
||||
- **Project Context Sync**: One config that syncs to all your agents
|
||||
- **Interactive TUI**: Beautiful terminal interface for managing skills
|
||||
- **Multi-Agent Support**: Works with Claude Code, Cursor, Codex, Windsurf, and 13+ more
|
||||
- **Multi-Platform Git**: GitHub, GitLab, Bitbucket, and local paths
|
||||
- **CI/CD Friendly**: Non-interactive flags for automation (`--skills`, `--all`, `--yes`)
|
||||
- **Zero Config**: Auto-detects your agent and configures appropriately
|
||||
|
||||
## Installation
|
||||
Test your skills with built-in assertions:
|
||||
|
||||
```bash
|
||||
# Global install (recommended)
|
||||
npm install -g skillkit
|
||||
# Run all skill tests
|
||||
skillkit test
|
||||
|
||||
# Or use without installing
|
||||
npx skillkit <command>
|
||||
# Test specific skills
|
||||
skillkit test ./my-skill
|
||||
|
||||
# Or with other package managers
|
||||
pnpm add -g skillkit
|
||||
yarn global add skillkit
|
||||
bun add -g skillkit
|
||||
# Run tests with specific tags
|
||||
skillkit test --tags unit,integration
|
||||
|
||||
# JSON output for CI
|
||||
skillkit test --json
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
### Workflow Orchestration
|
||||
|
||||
Compose skills into multi-step workflows:
|
||||
|
||||
```bash
|
||||
# 1. Get recommendations for your project
|
||||
skillkit recommend
|
||||
# List available workflows
|
||||
skillkit workflow list
|
||||
|
||||
# 2. Install recommended skills
|
||||
skillkit install anthropics/skills
|
||||
# Run a workflow
|
||||
skillkit workflow run feature-development
|
||||
|
||||
# 3. Sync to your agent
|
||||
skillkit sync
|
||||
|
||||
# Or just launch the TUI and do it all interactively
|
||||
skillkit
|
||||
# Create new workflow
|
||||
skillkit workflow create my-workflow
|
||||
```
|
||||
|
||||
## Popular Skill Repositories
|
||||
### CI/CD Integration
|
||||
|
||||
Install skills from these community repositories:
|
||||
Generate CI/CD templates for automated skill management:
|
||||
|
||||
```bash
|
||||
# Anthropic's official skill marketplace
|
||||
skillkit install anthropics/skills
|
||||
# GitHub Actions
|
||||
skillkit cicd github-action
|
||||
|
||||
# Vercel's React & Next.js best practices
|
||||
skillkit install vercel-labs/agent-skills/skills
|
||||
# GitLab CI
|
||||
skillkit cicd gitlab-ci
|
||||
|
||||
# Pre-commit hooks
|
||||
skillkit cicd pre-commit
|
||||
```
|
||||
|
||||

|
||||
## Supported Agents (17)
|
||||
|
||||
| Repository | Skills | Description |
|
||||
|------------|--------|-------------|
|
||||
| [anthropics/skills](https://github.com/anthropics/skills) | `pdf`, `xlsx`, `docx`, etc. | Official Claude Code skill marketplace |
|
||||
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | `vercel-react-best-practices`, `web-design-guidelines` | React/Next.js optimization & UI review |
|
||||
| Agent | Format | Skills Directory |
|
||||
|-------|--------|------------------|
|
||||
| Claude Code | SKILL.md | `.claude/skills/` |
|
||||
| Cursor | MDC (.mdc) | `.cursor/skills/` |
|
||||
| Codex | SKILL.md | `.codex/skills/` |
|
||||
| Gemini CLI | SKILL.md | `.gemini/skills/` |
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.amp/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` |
|
||||
| Kilo Code | SKILL.md | `.kilocode/skills/` |
|
||||
| Kiro CLI | SKILL.md | `.kiro/skills/` |
|
||||
| Roo Code | SKILL.md | `.roo/skills/` |
|
||||
| Trae | SKILL.md | `.trae/skills/` |
|
||||
| Windsurf | Markdown | `.windsurf/skills/` |
|
||||
| Universal | SKILL.md | `skills/` |
|
||||
|
||||
## All Commands
|
||||
|
||||
## Commands
|
||||
|
||||
### `skillkit ui` / `skillkit`
|
||||
|
||||
Launch the interactive Terminal User Interface (TUI) for managing skills.
|
||||
### Skill Management
|
||||
|
||||
```bash
|
||||
skillkit ui # Explicit TUI launch
|
||||
skillkit # Launch TUI if no arguments provided
|
||||
skillkit install <source> # Install skills from GitHub/GitLab/Bitbucket/local
|
||||
skillkit remove <skills> # Remove installed skills
|
||||
skillkit update [skills] # Update skills from source
|
||||
skillkit list # List installed skills
|
||||
skillkit enable <skills> # Enable specific skills
|
||||
skillkit disable <skills> # Disable specific skills
|
||||
skillkit sync # Sync skills to agent config
|
||||
skillkit read <skills> # Read skill content for AI
|
||||
```
|
||||
|
||||
**TUI Features:**
|
||||
- **Browse**: Discover skills from 33+ repositories
|
||||
- **Recommend**: Get smart skill suggestions for your project
|
||||
- **List**: View all installed skills
|
||||
- **Sync**: Sync skills across multiple agents
|
||||
- **Settings**: Configure SkillKit preferences
|
||||
|
||||
**Keyboard Shortcuts:**
|
||||
- `h` - Home screen
|
||||
- `b` - Browse skills marketplace
|
||||
- `r` - Smart recommendations
|
||||
- `l` - List installed skills
|
||||
- `s` - Sync skills across agents
|
||||
- `,` - Settings
|
||||
- `↑↓` - Navigate lists
|
||||
- `Enter` - Select / Install
|
||||
- `m` - Multi-agent selection (when viewing skills)
|
||||
- `/` - Search skills
|
||||
- `Esc` - Return to home
|
||||
- `q` - Quit
|
||||
|
||||
### `skillkit install <source>`
|
||||
|
||||
Install skills from various sources.
|
||||
### Discovery & Recommendations
|
||||
|
||||
```bash
|
||||
# GitHub (default)
|
||||
skillkit install owner/repo
|
||||
skillkit install https://github.com/owner/repo
|
||||
|
||||
# Install from a subdirectory
|
||||
skillkit install owner/repo/skills
|
||||
|
||||
# GitLab
|
||||
skillkit install gitlab:owner/repo
|
||||
skillkit install https://gitlab.com/owner/repo
|
||||
|
||||
# Bitbucket
|
||||
skillkit install bitbucket:owner/repo
|
||||
|
||||
# Local path
|
||||
skillkit install ./my-skills
|
||||
skillkit install ~/dev/skills
|
||||
|
||||
# Options
|
||||
--list # List available skills without installing
|
||||
--skills=pdf,xlsx # Install specific skills only (CI/CD)
|
||||
--all # Install all discovered skills
|
||||
--yes # Skip confirmation prompts
|
||||
--global # Install to global directory
|
||||
--force # Overwrite existing skills
|
||||
--provider=gitlab # Force specific provider
|
||||
--agent=cursor # Install to specific agent (can specify multiple)
|
||||
skillkit recommend # Get smart recommendations
|
||||
skillkit marketplace # Browse skill marketplace
|
||||
skillkit marketplace search # Search marketplace
|
||||
```
|
||||
|
||||
### `skillkit sync`
|
||||
|
||||
Sync installed skills to your agent's config file.
|
||||
### Translation & Context
|
||||
|
||||
```bash
|
||||
skillkit sync
|
||||
skillkit sync --agent cursor
|
||||
skillkit sync --output AGENTS.md
|
||||
skillkit sync --enabled-only
|
||||
skillkit translate # Translate between formats
|
||||
skillkit context init # Initialize project context
|
||||
skillkit context sync # Sync context to agents
|
||||
```
|
||||
|
||||
### `skillkit recommend`
|
||||
|
||||
Get smart skill recommendations based on your project's tech stack.
|
||||
### Memory System
|
||||
|
||||
```bash
|
||||
skillkit recommend # Analyze current directory
|
||||
skillkit recommend --path ./my-app # Analyze specific project
|
||||
skillkit recommend --verbose # Show detailed match reasons
|
||||
skillkit recommend --limit 5 # Limit results
|
||||
skillkit recommend --min-score 50 # Only show high matches
|
||||
skillkit recommend --category security # Filter by category
|
||||
skillkit recommend --search "auth" # Search skills by task
|
||||
skillkit recommend --update # Update skill index
|
||||
skillkit recommend --json # Output as JSON
|
||||
skillkit memory status # View memory status
|
||||
skillkit memory search # Search learnings
|
||||
skillkit memory compress # Compress observations
|
||||
skillkit memory export # Export as skill
|
||||
```
|
||||
|
||||
### `skillkit translate`
|
||||
|
||||
Translate skills between different agent formats.
|
||||
### Testing & Workflows
|
||||
|
||||
```bash
|
||||
skillkit translate react-skill --to cursor # Translate to Cursor format
|
||||
skillkit translate ./skill --from claude --to windsurf # Explicit source/target
|
||||
skillkit translate --all --to cursor # Translate all installed skills
|
||||
skillkit translate react-skill --to cursor --dry-run # Preview without writing
|
||||
skillkit test # Run skill tests
|
||||
skillkit workflow run # Execute workflow
|
||||
skillkit cicd # Generate CI/CD templates
|
||||
```
|
||||
|
||||
**Supported translations:** All 17 agents can translate to/from each other.
|
||||
|
||||
### `skillkit context`
|
||||
|
||||
Manage project context for cross-agent synchronization.
|
||||
### Utilities
|
||||
|
||||
```bash
|
||||
skillkit context init # Analyze project and create context
|
||||
skillkit context show # Display current context
|
||||
skillkit context export # Export context to file
|
||||
skillkit context import ./context.yaml # Import context from file
|
||||
skillkit context sync --agent cursor # Sync context to specific agent
|
||||
skillkit context sync --all # Sync to all detected agents
|
||||
skillkit init # Initialize in project
|
||||
skillkit validate # Validate skill format
|
||||
skillkit create # Create new skill
|
||||
```
|
||||
|
||||
### `skillkit read <skills>`
|
||||
|
||||
Read skill content for AI agent consumption.
|
||||
|
||||
```bash
|
||||
skillkit read pdf
|
||||
skillkit read pdf,xlsx,docx # Multiple skills
|
||||
```
|
||||
|
||||
### `skillkit list`
|
||||
|
||||
List all installed skills.
|
||||
|
||||
```bash
|
||||
skillkit list
|
||||
skillkit list --enabled
|
||||
skillkit list --json
|
||||
```
|
||||
|
||||
### `skillkit enable/disable <skills>`
|
||||
|
||||
Toggle skills on/off without removing them.
|
||||
|
||||
```bash
|
||||
skillkit enable pdf xlsx
|
||||
skillkit disable docx
|
||||
```
|
||||
|
||||
### `skillkit update [skills]`
|
||||
|
||||
Update skills from their original sources.
|
||||
|
||||
```bash
|
||||
skillkit update # Update all
|
||||
skillkit update pdf xlsx # Update specific
|
||||
```
|
||||
|
||||
### `skillkit remove <skills>`
|
||||
|
||||
Remove installed skills.
|
||||
|
||||
```bash
|
||||
skillkit remove pdf xlsx
|
||||
```
|
||||
|
||||
### `skillkit init`
|
||||
|
||||
Initialize skillkit in a project.
|
||||
|
||||
```bash
|
||||
skillkit init
|
||||
skillkit init --agent cursor
|
||||
skillkit init --list # List supported agents
|
||||
```
|
||||
|
||||
### `skillkit validate <path>`
|
||||
|
||||
Validate skills against the [Agent Skills specification](https://agentskills.io/specification).
|
||||
|
||||
```bash
|
||||
skillkit validate ./my-skill # Validate single skill
|
||||
skillkit validate ./skills --all # Validate all skills in directory
|
||||
```
|
||||
|
||||
### `skillkit create <skill-name>`
|
||||
|
||||
Create a new skill with proper structure and template.
|
||||
|
||||
```bash
|
||||
skillkit create my-skill # Basic skill
|
||||
skillkit create my-skill --full # Include all directories (references, scripts, assets)
|
||||
skillkit create my-skill --scripts # Include scripts directory
|
||||
skillkit create my-skill --references # Include references directory
|
||||
skillkit create my-skill --assets # Include assets directory
|
||||
skillkit create my-skill --dir ./skills # Create in specific directory
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
| Agent | Config File | Project Path | Global Path |
|
||||
|-------|-------------|--------------|-------------|
|
||||
| Claude Code | `AGENTS.md` | `.claude/skills/` | `~/.claude/skills/` |
|
||||
| Cursor | `.cursorrules` | `.cursor/skills/` | `~/.cursor/skills/` |
|
||||
| Codex | `AGENTS.md` | `.codex/skills/` | `~/.codex/skills/` |
|
||||
| Gemini CLI | `GEMINI.md` | `.gemini/skills/` | `~/.gemini/skills/` |
|
||||
| OpenCode | `AGENTS.md` | `.opencode/skills/` | `~/.config/opencode/skills/` |
|
||||
| Antigravity | `AGENTS.md` | `.antigravity/skills/` | `~/.gemini/antigravity/skills/` |
|
||||
| Amp | `AGENTS.md` | `.agents/skills/` | `~/.config/agents/skills/` |
|
||||
| Clawdbot | `AGENTS.md` | `skills/` | `~/.clawdbot/skills/` |
|
||||
| Droid (Factory) | `AGENTS.md` | `.factory/skills/` | `~/.factory/skills/` |
|
||||
| GitHub Copilot | `AGENTS.md` | `.github/skills/` | `~/.copilot/skills/` |
|
||||
| Goose | `AGENTS.md` | `.goose/skills/` | `~/.config/goose/skills/` |
|
||||
| Kilo Code | `AGENTS.md` | `.kilocode/skills/` | `~/.kilocode/skills/` |
|
||||
| Kiro CLI | `AGENTS.md` | `.kiro/skills/` | `~/.kiro/skills/` |
|
||||
| Roo Code | `AGENTS.md` | `.roo/skills/` | `~/.roo/skills/` |
|
||||
| Trae | `AGENTS.md` | `.trae/skills/` | `~/.trae/skills/` |
|
||||
| Windsurf | `AGENTS.md` | `.windsurf/skills/` | `~/.codeium/windsurf/skills/` |
|
||||
| Universal | `AGENTS.md` | `.agent/skills/` | `~/.agent/skills/` |
|
||||
|
||||
## Creating Skills
|
||||
|
||||
Use `skillkit create <name>` to scaffold a new skill, or create manually:
|
||||
### Quick Start
|
||||
|
||||
A skill is a directory with a `SKILL.md` file:
|
||||
|
||||
```
|
||||
my-skill/
|
||||
├── SKILL.md # Required: Instructions for the AI
|
||||
├── references/ # Optional: Documentation
|
||||
├── scripts/ # Optional: Helper scripts
|
||||
└── assets/ # Optional: Templates, configs
|
||||
```bash
|
||||
skillkit create my-skill
|
||||
```
|
||||
|
||||
### SKILL.md Format
|
||||
### Manual Creation
|
||||
|
||||
Follows the [Agent Skills specification](https://agentskills.io/specification):
|
||||
Create a `SKILL.md` file following the [Agent Skills specification](https://agentskills.io/specification):
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: my-skill
|
||||
description: What this skill does and when to use it. Include trigger keywords.
|
||||
description: What this skill does and when to use it
|
||||
license: MIT
|
||||
compatibility: Requires Node.js 18+
|
||||
metadata:
|
||||
author: your-org
|
||||
author: your-name
|
||||
version: "1.0"
|
||||
---
|
||||
|
||||
# My Skill
|
||||
|
||||
Instructions for the AI agent on how to use this skill.
|
||||
Instructions for the AI agent.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Scenario 1
|
||||
- Scenario 2
|
||||
|
||||
## Steps
|
||||
|
||||
1. First step
|
||||
2. Second step
|
||||
```
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `name` | Yes | Lowercase alphanumeric with hyphens (max 64 chars) |
|
||||
| `description` | Yes | What it does and when to use it (max 1024 chars) |
|
||||
| `license` | No | License name or reference |
|
||||
| `compatibility` | No | Environment requirements |
|
||||
| `metadata` | No | Arbitrary key-value pairs |
|
||||
|
||||
## CI/CD Usage
|
||||
|
||||
```yaml
|
||||
# GitHub Actions example
|
||||
- name: Setup skills
|
||||
run: |
|
||||
npx skillkit install owner/skills --skills=lint,test,deploy --yes
|
||||
npx skillkit sync --yes
|
||||
```
|
||||
|
||||
## Programmatic API
|
||||
|
||||
```typescript
|
||||
@@ -471,41 +341,68 @@ import {
|
||||
discoverSkills,
|
||||
detectAgent,
|
||||
getAdapter,
|
||||
// Recommendations
|
||||
RecommendationEngine,
|
||||
analyzeProject,
|
||||
|
||||
// Translation
|
||||
translateSkill,
|
||||
translateSkillFile,
|
||||
|
||||
// Recommendations
|
||||
RecommendationEngine,
|
||||
analyzeProject,
|
||||
|
||||
// Context
|
||||
ContextManager,
|
||||
initContext,
|
||||
syncToAllAgents,
|
||||
|
||||
// Memory
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
LearningStore,
|
||||
|
||||
// Marketplace
|
||||
createMarketplaceAggregator,
|
||||
|
||||
// Testing
|
||||
SkillTestRunner,
|
||||
|
||||
// Workflows
|
||||
WorkflowOrchestrator,
|
||||
} from 'skillkit';
|
||||
|
||||
// Find all installed skills
|
||||
const skills = findAllSkills(searchDirs);
|
||||
// Example: Translate and install
|
||||
const skill = await translateSkill(skillContent, 'cursor');
|
||||
console.log(skill.content);
|
||||
|
||||
// Detect current agent
|
||||
const agent = await detectAgent();
|
||||
|
||||
// Generate config
|
||||
const adapter = getAdapter(agent);
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
// Get smart recommendations
|
||||
// Example: Get recommendations
|
||||
const engine = new RecommendationEngine();
|
||||
const profile = await analyzeProject('./my-project');
|
||||
const recommendations = engine.recommend(profile, skills);
|
||||
const recs = engine.recommend(profile);
|
||||
```
|
||||
|
||||
// Translate skills between agents
|
||||
const result = translateSkill(skillContent, 'cursor');
|
||||
console.log(result.content); // Cursor MDC format
|
||||
## Popular Skill Repositories
|
||||
|
||||
// Manage project context
|
||||
const ctx = new ContextManager('./my-project');
|
||||
await ctx.init();
|
||||
await syncToAllAgents(ctx.getContext());
|
||||
| Repository | Description |
|
||||
|------------|-------------|
|
||||
| [anthropics/skills](https://github.com/anthropics/skills) | Official Claude Code marketplace - PDF, XLSX, DOCX processing |
|
||||
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | React/Next.js best practices, web design guidelines |
|
||||
|
||||
## Installation Options
|
||||
|
||||
```bash
|
||||
# npm (recommended)
|
||||
npm install -g skillkit
|
||||
|
||||
# pnpm
|
||||
pnpm add -g skillkit
|
||||
|
||||
# yarn
|
||||
yarn global add skillkit
|
||||
|
||||
# bun
|
||||
bun add -g skillkit
|
||||
|
||||
# npx (no install)
|
||||
npx skillkit <command>
|
||||
```
|
||||
|
||||
## Configuration
|
||||
@@ -523,14 +420,26 @@ 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.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request.
|
||||
Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md).
|
||||
|
||||
## Acknowledgments
|
||||
## Links
|
||||
|
||||
Implements the [Agent Skills](https://agentskills.io) open format, originally developed by Anthropic and adopted by leading AI development tools.
|
||||
- [Agent Skills Specification](https://agentskills.io/specification)
|
||||
- [GitHub Repository](https://github.com/rohitg00/skillkit)
|
||||
- [NPM Package](https://www.npmjs.com/package/skillkit)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# SkillKit
|
||||
|
||||
Universal skills manager for AI coding agents. Install, manage, and sync skills across 17+ AI agents including Claude Code, Cursor, Codex, Gemini CLI, and more.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install -g skillkit
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Initialize skillkit in your project
|
||||
skillkit init
|
||||
|
||||
# Install skills from GitHub
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Get recommendations for your stack
|
||||
skillkit recommend
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## Core Features
|
||||
|
||||
### Cross-Agent Translation
|
||||
|
||||
```bash
|
||||
# Translate a Claude skill to Cursor format
|
||||
skillkit translate react-patterns --to cursor
|
||||
|
||||
# Translate all skills to multiple agents
|
||||
skillkit translate --all --to windsurf,codex
|
||||
|
||||
# Preview translation
|
||||
skillkit translate my-skill --to copilot --dry-run
|
||||
```
|
||||
|
||||
### Smart Recommendations
|
||||
|
||||
```bash
|
||||
# Get project-aware suggestions
|
||||
skillkit recommend
|
||||
|
||||
# Filter by task
|
||||
skillkit recommend --search "authentication"
|
||||
|
||||
# Quality threshold
|
||||
skillkit recommend --min-score 85
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```bash
|
||||
# Initialize team
|
||||
skillkit team init --name "Engineering Team"
|
||||
|
||||
# Create skill bundle
|
||||
skillkit team bundle-create
|
||||
|
||||
# Share with team
|
||||
skillkit team share onboarding-bundle
|
||||
|
||||
# Sync with remote registry
|
||||
skillkit team sync
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```bash
|
||||
# List installed plugins
|
||||
skillkit plugin list
|
||||
|
||||
# Install custom plugin
|
||||
skillkit plugin install @company/custom-translator
|
||||
|
||||
# View plugin info
|
||||
skillkit plugin info my-plugin
|
||||
```
|
||||
|
||||
### Development Methodologies
|
||||
|
||||
```bash
|
||||
# List available methodologies
|
||||
skillkit methodology list
|
||||
|
||||
# Load TDD methodology
|
||||
skillkit methodology load tdd
|
||||
|
||||
# Apply to project
|
||||
skillkit methodology apply agile
|
||||
```
|
||||
|
||||
### Plan System
|
||||
|
||||
```bash
|
||||
# Parse and validate plan
|
||||
skillkit plan parse ./implementation-plan.md
|
||||
skillkit plan validate ./plan.md
|
||||
|
||||
# Execute plan
|
||||
skillkit plan execute ./feature-plan.md
|
||||
|
||||
# Check status
|
||||
skillkit plan status
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```bash
|
||||
# List hooks
|
||||
skillkit hook list
|
||||
|
||||
# Register pre-commit hook
|
||||
skillkit hook register pre-commit
|
||||
|
||||
# Trigger manually
|
||||
skillkit hook trigger pre-commit
|
||||
```
|
||||
|
||||
### Workflow Orchestration
|
||||
|
||||
```bash
|
||||
# List workflows
|
||||
skillkit workflow list
|
||||
|
||||
# Run workflow
|
||||
skillkit workflow run feature-development
|
||||
|
||||
# Create new workflow
|
||||
skillkit workflow create deployment-flow
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```bash
|
||||
# View learnings
|
||||
skillkit memory list
|
||||
|
||||
# Search past sessions
|
||||
skillkit memory search "error handling"
|
||||
|
||||
# Compress observations
|
||||
skillkit memory compress
|
||||
|
||||
# Export learning as skill
|
||||
skillkit memory export auth-insight --output auth-skill.md
|
||||
```
|
||||
|
||||
## Supported Agents (17)
|
||||
|
||||
Claude Code, Cursor, Codex, Gemini CLI, Windsurf, GitHub Copilot, OpenCode, Antigravity, Amp, Clawdbot, Droid, Goose, Kilo, Kiro, Roo, Trae, Universal
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Install and Sync
|
||||
|
||||
```bash
|
||||
# Install to multiple agents
|
||||
skillkit install anthropics/skills --agent claude-code,cursor
|
||||
|
||||
# Sync all skills to detected agents
|
||||
skillkit sync --all
|
||||
```
|
||||
|
||||
### Context Management
|
||||
|
||||
```bash
|
||||
# Initialize project context
|
||||
skillkit context init
|
||||
|
||||
# View detected stack
|
||||
skillkit context show
|
||||
|
||||
# Sync to all agents
|
||||
skillkit context sync --all
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Run all skill tests
|
||||
skillkit test
|
||||
|
||||
# Test specific skills
|
||||
skillkit test ./my-skill --tags unit
|
||||
|
||||
# CI/CD integration
|
||||
skillkit cicd init
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.3.0",
|
||||
"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": {
|
||||
|
||||
@@ -19,6 +19,26 @@ import {
|
||||
TranslateCommand,
|
||||
ContextCommand,
|
||||
RecommendCommand,
|
||||
StatusCommand,
|
||||
PauseCommand,
|
||||
ResumeCommand,
|
||||
WorkflowRunCommand,
|
||||
WorkflowListCommand,
|
||||
WorkflowCreateCommand,
|
||||
RunCommand,
|
||||
TestCommand,
|
||||
MarketplaceCommand,
|
||||
MemoryCommand,
|
||||
SettingsCommand,
|
||||
CICDCommand,
|
||||
TeamCommand,
|
||||
PluginCommand,
|
||||
MethodologyCommand,
|
||||
HookCommand,
|
||||
PlanCommand,
|
||||
CommandCmd,
|
||||
AICommand,
|
||||
AuditCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
@@ -51,5 +71,25 @@ cli.register(UICommand);
|
||||
cli.register(TranslateCommand);
|
||||
cli.register(ContextCommand);
|
||||
cli.register(RecommendCommand);
|
||||
cli.register(StatusCommand);
|
||||
cli.register(PauseCommand);
|
||||
cli.register(ResumeCommand);
|
||||
cli.register(WorkflowRunCommand);
|
||||
cli.register(WorkflowListCommand);
|
||||
cli.register(WorkflowCreateCommand);
|
||||
cli.register(RunCommand);
|
||||
cli.register(TestCommand);
|
||||
cli.register(MarketplaceCommand);
|
||||
cli.register(MemoryCommand);
|
||||
cli.register(SettingsCommand);
|
||||
cli.register(CICDCommand);
|
||||
cli.register(TeamCommand);
|
||||
cli.register(PluginCommand);
|
||||
cli.register(MethodologyCommand);
|
||||
cli.register(HookCommand);
|
||||
cli.register(PlanCommand);
|
||||
cli.register(CommandCmd);
|
||||
cli.register(AICommand);
|
||||
cli.register(AuditCommand);
|
||||
|
||||
cli.runExit(process.argv.slice(2));
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.2.0",
|
||||
"version": "1.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "skillkit",
|
||||
"version": "1.2.0",
|
||||
"version": "1.5.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chalk": "^5.3.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "skillkit-monorepo",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"description": "Universal skills loader for AI coding agents - Monorepo",
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# @skillkit/agents
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/agents)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Agent adapters for SkillKit** - configuration and detection for 17 AI coding agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/agents
|
||||
```
|
||||
|
||||
## Supported Agents (17)
|
||||
|
||||
| Agent | Config Format | Project Skills | Global Skills |
|
||||
|-------|--------------|----------------|---------------|
|
||||
| Claude Code | SKILL.md | `.claude/skills/` | `~/.claude/skills/` |
|
||||
| Cursor | MDC (.mdc) | `.cursor/skills/` | `~/.cursor/skills/` |
|
||||
| Codex | SKILL.md | `.codex/skills/` | `~/.codex/skills/` |
|
||||
| Gemini CLI | SKILL.md | `.gemini/skills/` | `~/.gemini/skills/` |
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` | `~/.config/opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` | `~/.gemini/antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.agents/skills/` | `~/.config/agents/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` | `~/.clawdbot/skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` | `~/.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` | `~/.copilot/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` | `~/.config/goose/skills/` |
|
||||
| Kilo Code | SKILL.md | `.kilocode/skills/` | `~/.kilocode/skills/` |
|
||||
| Kiro CLI | SKILL.md | `.kiro/skills/` | `~/.kiro/skills/` |
|
||||
| Roo Code | SKILL.md | `.roo/skills/` | `~/.roo/skills/` |
|
||||
| Trae | SKILL.md | `.trae/skills/` | `~/.trae/skills/` |
|
||||
| Windsurf | Markdown | `.windsurf/skills/` | `~/.codeium/windsurf/skills/` |
|
||||
| Universal | SKILL.md | `skills/` | `~/.agent/skills/` |
|
||||
|
||||
## Usage
|
||||
|
||||
### Get Agent Adapter
|
||||
|
||||
```typescript
|
||||
import { getAdapter, AgentType } from '@skillkit/agents';
|
||||
|
||||
// Get adapter for specific agent
|
||||
const adapter = getAdapter('claude-code');
|
||||
|
||||
console.log(adapter.name); // 'claude-code'
|
||||
console.log(adapter.skillsDir); // '.claude/skills/'
|
||||
console.log(adapter.globalSkillsDir); // '~/.claude/skills/'
|
||||
console.log(adapter.configFile); // 'AGENTS.md'
|
||||
console.log(adapter.format); // 'skill-md'
|
||||
```
|
||||
|
||||
### Detect Installed Agents
|
||||
|
||||
```typescript
|
||||
import { detectAgent, detectAllAgents } from '@skillkit/agents';
|
||||
|
||||
// Detect primary agent in current directory
|
||||
const primary = await detectAgent();
|
||||
console.log(primary); // 'claude-code'
|
||||
|
||||
// Detect all installed agents
|
||||
const all = await detectAllAgents();
|
||||
console.log(all); // ['claude-code', 'cursor', 'windsurf']
|
||||
|
||||
// Detect in specific directory
|
||||
const agents = await detectAllAgents('./my-project');
|
||||
```
|
||||
|
||||
### List All Adapters
|
||||
|
||||
```typescript
|
||||
import { listAdapters, getAdapterNames } from '@skillkit/agents';
|
||||
|
||||
// Get all adapter configurations
|
||||
const adapters = listAdapters();
|
||||
adapters.forEach(adapter => {
|
||||
console.log(`${adapter.name}: ${adapter.skillsDir}`);
|
||||
});
|
||||
|
||||
// Get just the names
|
||||
const names = getAdapterNames();
|
||||
console.log(names); // ['claude-code', 'cursor', 'codex', ...]
|
||||
```
|
||||
|
||||
### Generate Agent Config
|
||||
|
||||
```typescript
|
||||
import { getAdapter } from '@skillkit/agents';
|
||||
import { findAllSkills } from '@skillkit/core';
|
||||
|
||||
const adapter = getAdapter('cursor');
|
||||
const skills = findAllSkills([adapter.skillsDir]);
|
||||
|
||||
// Generate config file content
|
||||
const config = adapter.generateConfig(skills);
|
||||
console.log(config);
|
||||
```
|
||||
|
||||
### Get Skills Directory
|
||||
|
||||
```typescript
|
||||
import { getAdapter } from '@skillkit/agents';
|
||||
import { homedir } from 'os';
|
||||
|
||||
const adapter = getAdapter('claude-code');
|
||||
|
||||
// Project-local skills directory
|
||||
const projectDir = adapter.skillsDir; // '.claude/skills/'
|
||||
|
||||
// Global skills directory
|
||||
const globalDir = adapter.globalSkillsDir.replace('~', homedir());
|
||||
// '/Users/you/.claude/skills/'
|
||||
```
|
||||
|
||||
## Adapter Interface
|
||||
|
||||
```typescript
|
||||
interface AgentAdapter {
|
||||
// Agent identifier
|
||||
name: AgentType;
|
||||
|
||||
// Display name
|
||||
displayName: string;
|
||||
|
||||
// Skill file format
|
||||
format: 'skill-md' | 'mdc' | 'markdown';
|
||||
|
||||
// Project skills directory (relative)
|
||||
skillsDir: string;
|
||||
|
||||
// Global skills directory (with ~)
|
||||
globalSkillsDir: string;
|
||||
|
||||
// Config file name
|
||||
configFile: string;
|
||||
|
||||
// Generate config from skills
|
||||
generateConfig(skills: Skill[]): string;
|
||||
|
||||
// Parse existing config
|
||||
parseConfig(content: string): Skill[];
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Types
|
||||
|
||||
```typescript
|
||||
type AgentType =
|
||||
| 'claude-code'
|
||||
| 'cursor'
|
||||
| 'codex'
|
||||
| 'gemini-cli'
|
||||
| 'opencode'
|
||||
| 'antigravity'
|
||||
| 'amp'
|
||||
| 'clawdbot'
|
||||
| 'droid'
|
||||
| 'github-copilot'
|
||||
| 'goose'
|
||||
| 'kilo'
|
||||
| 'kiro-cli'
|
||||
| 'roo'
|
||||
| 'trae'
|
||||
| 'windsurf'
|
||||
| 'universal';
|
||||
```
|
||||
|
||||
## Format Details
|
||||
|
||||
### SKILL.md Format
|
||||
Used by most agents. YAML frontmatter + Markdown content:
|
||||
```markdown
|
||||
---
|
||||
name: my-skill
|
||||
description: What this skill does
|
||||
---
|
||||
# My Skill
|
||||
Instructions...
|
||||
```
|
||||
|
||||
### MDC Format (Cursor)
|
||||
Cursor-specific format with globs and alwaysApply:
|
||||
```
|
||||
---
|
||||
description: What this skill does
|
||||
globs: ["**/*.tsx"]
|
||||
alwaysApply: false
|
||||
---
|
||||
Instructions...
|
||||
```
|
||||
|
||||
### Markdown Format
|
||||
Plain markdown used by Windsurf and Copilot:
|
||||
```markdown
|
||||
# Skill Name
|
||||
Instructions for the agent...
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/agents",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.0",
|
||||
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -11,7 +11,9 @@
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
@@ -19,7 +21,8 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@skillkit/core": "workspace:*"
|
||||
"@skillkit/core": "workspace:*",
|
||||
"minimatch": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* Agent Features Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import {
|
||||
PermissionManager,
|
||||
createPermissionManager,
|
||||
isAllowed,
|
||||
isDenied,
|
||||
needsConfirmation,
|
||||
} from '../permissions.js';
|
||||
import {
|
||||
GlobMatcher,
|
||||
createGlobMatcher,
|
||||
matchPattern,
|
||||
parseGlobsFromMDC,
|
||||
fromCommonPatterns,
|
||||
COMMON_PATTERNS,
|
||||
} from '../globs.js';
|
||||
import {
|
||||
BootstrapManager,
|
||||
createBootstrapManager,
|
||||
createBootstrapSet,
|
||||
} from '../bootstrap.js';
|
||||
import {
|
||||
ModeManager,
|
||||
createModeManager,
|
||||
createDefaultModeManager,
|
||||
ALL_MODES,
|
||||
} from '../modes.js';
|
||||
import type { PermissionConfig, GlobConfig, ModeConfig } from '../types.js';
|
||||
|
||||
describe('PermissionManager', () => {
|
||||
let manager: PermissionManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createPermissionManager();
|
||||
});
|
||||
|
||||
describe('checkFileAccess', () => {
|
||||
it('should return default permission for unmatched files', () => {
|
||||
manager.setConfig({ default: 'ask' });
|
||||
expect(manager.checkFileAccess('some/file.ts')).toBe('ask');
|
||||
});
|
||||
|
||||
it('should match file patterns', () => {
|
||||
manager.setConfig({
|
||||
files: [
|
||||
{ pattern: '*.ts', level: 'allow' },
|
||||
{ pattern: 'secret/*', level: 'deny' },
|
||||
],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
expect(manager.checkFileAccess('app.ts')).toBe('allow');
|
||||
expect(manager.checkFileAccess('secret/keys.json')).toBe('deny');
|
||||
expect(manager.checkFileAccess('random.json')).toBe('ask');
|
||||
});
|
||||
|
||||
it('should use first matching pattern', () => {
|
||||
manager.setConfig({
|
||||
files: [
|
||||
{ pattern: '*.ts', level: 'deny' },
|
||||
{ pattern: 'src/*.ts', level: 'allow' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(manager.checkFileAccess('app.ts')).toBe('deny');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkCommandAccess', () => {
|
||||
it('should check command patterns', () => {
|
||||
manager.setConfig({
|
||||
commands: [
|
||||
{ pattern: 'npm *', level: 'allow' },
|
||||
{ pattern: 'rm *', level: 'deny' },
|
||||
],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
expect(manager.checkCommandAccess('npm install')).toBe('allow');
|
||||
expect(manager.checkCommandAccess('rm -rf /')).toBe('deny');
|
||||
expect(manager.checkCommandAccess('git status')).toBe('ask');
|
||||
});
|
||||
});
|
||||
|
||||
describe('addFilePattern', () => {
|
||||
it('should add file pattern', () => {
|
||||
manager.addFilePattern({ pattern: '*.js', level: 'allow' });
|
||||
|
||||
expect(manager.checkFileAccess('app.js')).toBe('allow');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateOpenCodeConfig', () => {
|
||||
it('should generate OpenCode-compatible config', () => {
|
||||
manager.setConfig({
|
||||
files: [{ pattern: 'src/*', level: 'allow' }],
|
||||
commands: [{ pattern: 'npm *', level: 'allow' }],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
const config = manager.generateOpenCodeConfig();
|
||||
|
||||
expect(config).toContain('File Access');
|
||||
expect(config).toContain('allow: `src/*`');
|
||||
expect(config).toContain('Command Execution');
|
||||
expect(config).toContain('Default: ask');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkillMetadata', () => {
|
||||
it('should generate skill metadata', () => {
|
||||
manager.setConfig({
|
||||
files: [{ pattern: '*.ts', level: 'allow' }],
|
||||
default: 'deny',
|
||||
});
|
||||
|
||||
const metadata = manager.generateSkillMetadata();
|
||||
|
||||
expect(metadata.filePermissions).toHaveLength(1);
|
||||
expect(metadata.defaultPermission).toBe('deny');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromMetadata', () => {
|
||||
it('should parse permissions from metadata', () => {
|
||||
const metadata = {
|
||||
filePermissions: [{ pattern: '*.ts', level: 'allow' }],
|
||||
defaultPermission: 'ask',
|
||||
};
|
||||
|
||||
const config = PermissionManager.fromMetadata(metadata);
|
||||
|
||||
expect(config.files).toHaveLength(1);
|
||||
expect(config.default).toBe('ask');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Permission helpers', () => {
|
||||
it('isAllowed should work correctly', () => {
|
||||
expect(isAllowed('allow')).toBe(true);
|
||||
expect(isAllowed('deny')).toBe(false);
|
||||
expect(isAllowed('ask')).toBe(false);
|
||||
});
|
||||
|
||||
it('isDenied should work correctly', () => {
|
||||
expect(isDenied('deny')).toBe(true);
|
||||
expect(isDenied('allow')).toBe(false);
|
||||
});
|
||||
|
||||
it('needsConfirmation should work correctly', () => {
|
||||
expect(needsConfirmation('ask')).toBe(true);
|
||||
expect(needsConfirmation('allow')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobMatcher', () => {
|
||||
let matcher: GlobMatcher;
|
||||
|
||||
describe('matches', () => {
|
||||
it('should match simple patterns', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
expect(matcher.matches('app.js')).toBe(false);
|
||||
});
|
||||
|
||||
it('should match wildcard patterns', () => {
|
||||
matcher = createGlobMatcher({ include: ['src/**/*.ts'] });
|
||||
|
||||
expect(matcher.matches('src/app.ts')).toBe(true);
|
||||
expect(matcher.matches('src/components/Button.ts')).toBe(true);
|
||||
expect(matcher.matches('lib/app.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should respect exclude patterns', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['**/*.ts'],
|
||||
exclude: ['**/*.test.ts'],
|
||||
});
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
expect(matcher.matches('app.test.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should skip hidden files by default', () => {
|
||||
matcher = createGlobMatcher({ include: ['**/*'] });
|
||||
|
||||
expect(matcher.matches('.hidden/file.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should match hidden files when enabled', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['**/*'],
|
||||
matchHidden: true,
|
||||
});
|
||||
|
||||
expect(matcher.matches('.hidden/file.ts')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filter', () => {
|
||||
it('should filter file list', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
|
||||
const files = ['app.ts', 'app.js', 'index.ts'];
|
||||
const result = matcher.filter(files);
|
||||
|
||||
expect(result).toEqual(['app.ts', 'index.ts']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addInclude', () => {
|
||||
it('should add include pattern', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
matcher.addInclude('*.js');
|
||||
|
||||
expect(matcher.matches('app.js')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateCursorGlobs', () => {
|
||||
it('should generate Cursor-compatible globs', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['src/**/*.ts'],
|
||||
exclude: ['**/*.test.ts'],
|
||||
});
|
||||
|
||||
const globs = matcher.generateCursorGlobs();
|
||||
|
||||
expect(globs).toContain('src/**/*.ts');
|
||||
expect(globs).toContain('!**/*.test.ts');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchPattern', () => {
|
||||
it('should create matcher from single pattern', () => {
|
||||
const matcher = matchPattern('*.ts');
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseGlobsFromMDC', () => {
|
||||
it('should parse globs from MDC content', () => {
|
||||
const content = `---
|
||||
globs: ["**/*.ts", "!**/*.test.ts"]
|
||||
---
|
||||
Content here`;
|
||||
|
||||
const config = parseGlobsFromMDC(content);
|
||||
|
||||
expect(config?.include).toContain('**/*.ts');
|
||||
expect(config?.exclude).toContain('**/*.test.ts');
|
||||
});
|
||||
|
||||
it('should return null for invalid content', () => {
|
||||
const result = parseGlobsFromMDC('no globs here');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromCommonPatterns', () => {
|
||||
it('should create config from common patterns', () => {
|
||||
const config = fromCommonPatterns(['typescript', 'source'], ['nodeModules']);
|
||||
|
||||
expect(config.include).toContain('**/*.ts');
|
||||
expect(config.include).toContain('src/**/*');
|
||||
expect(config.exclude).toContain('**/node_modules/**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('COMMON_PATTERNS', () => {
|
||||
it('should have expected patterns', () => {
|
||||
expect(COMMON_PATTERNS.typescript).toContain('**/*.ts');
|
||||
expect(COMMON_PATTERNS.tests).toContain('**/*.test.*');
|
||||
expect(COMMON_PATTERNS.nodeModules).toContain('**/node_modules/**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BootstrapManager', () => {
|
||||
let manager: BootstrapManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createBootstrapManager();
|
||||
});
|
||||
|
||||
describe('addFile/getFile', () => {
|
||||
it('should add and get files', () => {
|
||||
manager.addFile({
|
||||
type: 'agents',
|
||||
name: 'AGENTS.md',
|
||||
content: '# Agents',
|
||||
priority: 100,
|
||||
});
|
||||
|
||||
const file = manager.getFile('agents');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.name).toBe('AGENTS.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFilesByPriority', () => {
|
||||
it('should return files sorted by priority', () => {
|
||||
manager.addFile({ type: 'tools', name: 'TOOLS.md', content: '', priority: 10 });
|
||||
manager.addFile({ type: 'agents', name: 'AGENTS.md', content: '', priority: 100 });
|
||||
manager.addFile({ type: 'soul', name: 'SOUL.md', content: '', priority: 50 });
|
||||
|
||||
const files = manager.getFilesByPriority();
|
||||
|
||||
expect(files[0].type).toBe('agents');
|
||||
expect(files[1].type).toBe('soul');
|
||||
expect(files[2].type).toBe('tools');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAgentsFile', () => {
|
||||
it('should create AGENTS.md', () => {
|
||||
manager.createAgentsFile([
|
||||
{
|
||||
name: 'Coder',
|
||||
description: 'A coding agent',
|
||||
capabilities: ['Write code', 'Debug'],
|
||||
},
|
||||
]);
|
||||
|
||||
const file = manager.getFile('agents');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('# Agents');
|
||||
expect(file?.content).toContain('## Coder');
|
||||
expect(file?.content).toContain('Write code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createSoulFile', () => {
|
||||
it('should create SOUL.md', () => {
|
||||
manager.createSoulFile({
|
||||
personality: 'Helpful and precise',
|
||||
values: ['Accuracy', 'Efficiency'],
|
||||
});
|
||||
|
||||
const file = manager.getFile('soul');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('Helpful and precise');
|
||||
expect(file?.content).toContain('Accuracy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createToolsFile', () => {
|
||||
it('should create TOOLS.md', () => {
|
||||
manager.createToolsFile([
|
||||
{
|
||||
name: 'read_file',
|
||||
description: 'Read a file',
|
||||
usage: 'read_file(path)',
|
||||
},
|
||||
]);
|
||||
|
||||
const file = manager.getFile('tools');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('## read_file');
|
||||
expect(file?.content).toContain('read_file(path)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateCombinedContent', () => {
|
||||
it('should generate combined content', () => {
|
||||
manager.addFile({ type: 'agents', name: 'AGENTS.md', content: '# Agents', priority: 100 });
|
||||
manager.addFile({ type: 'soul', name: 'SOUL.md', content: '# Soul', priority: 50 });
|
||||
|
||||
const combined = manager.generateCombinedContent();
|
||||
|
||||
expect(combined).toContain('<!-- AGENTS.md -->');
|
||||
expect(combined).toContain('# Agents');
|
||||
expect(combined).toContain('<!-- SOUL.md -->');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBootstrapSet', () => {
|
||||
it('should create complete bootstrap set', () => {
|
||||
const manager = createBootstrapSet({
|
||||
agents: [{ name: 'Test Agent' }],
|
||||
soul: { personality: 'Friendly' },
|
||||
tools: [{ name: 'tool1' }],
|
||||
});
|
||||
|
||||
expect(manager.hasFile('agents')).toBe(true);
|
||||
expect(manager.hasFile('soul')).toBe(true);
|
||||
expect(manager.hasFile('tools')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ModeManager', () => {
|
||||
let manager: ModeManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createModeManager([
|
||||
{ mode: 'code', description: 'Coding mode', skills: ['tdd', 'debugging'] },
|
||||
{ mode: 'architect', description: 'Architecture mode', skills: ['planning'] },
|
||||
]);
|
||||
});
|
||||
|
||||
describe('addMode/getMode', () => {
|
||||
it('should add and get modes', () => {
|
||||
const mode = manager.getMode('code');
|
||||
|
||||
expect(mode).toBeDefined();
|
||||
expect(mode?.description).toBe('Coding mode');
|
||||
expect(mode?.skills).toContain('tdd');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableModes', () => {
|
||||
it('should return available modes', () => {
|
||||
const modes = manager.getAvailableModes();
|
||||
|
||||
expect(modes).toContain('code');
|
||||
expect(modes).toContain('architect');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setMode/getCurrentMode', () => {
|
||||
it('should set and get current mode', () => {
|
||||
manager.setMode('architect');
|
||||
|
||||
expect(manager.getCurrentMode()).toBe('architect');
|
||||
});
|
||||
|
||||
it('should throw for unconfigured mode', () => {
|
||||
expect(() => manager.setMode('debug')).toThrow('Mode not configured');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentSkills', () => {
|
||||
it('should return skills for current mode', () => {
|
||||
manager.setMode('code');
|
||||
|
||||
const skills = manager.getCurrentSkills();
|
||||
|
||||
expect(skills).toContain('tdd');
|
||||
expect(skills).toContain('debugging');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSkillAvailable', () => {
|
||||
it('should check if skill is available', () => {
|
||||
manager.setMode('code');
|
||||
|
||||
expect(manager.isSkillAvailable('tdd')).toBe(true);
|
||||
expect(manager.isSkillAvailable('planning')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFileAllowed', () => {
|
||||
it('should return true when no patterns defined', () => {
|
||||
expect(manager.isFileAllowed('any/file.ts')).toBe(true);
|
||||
});
|
||||
|
||||
it('should check file patterns when defined', () => {
|
||||
manager.addMode({
|
||||
mode: 'restricted',
|
||||
description: 'Restricted mode',
|
||||
skills: [],
|
||||
allowedFiles: ['src/**/*'],
|
||||
});
|
||||
manager.setMode('restricted');
|
||||
|
||||
expect(manager.isFileAllowed('src/app.ts')).toBe(true);
|
||||
expect(manager.isFileAllowed('lib/util.ts')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addModeListener', () => {
|
||||
it('should notify listeners on mode change', () => {
|
||||
let notified = false;
|
||||
let newModeValue = '';
|
||||
|
||||
manager.addModeListener((newMode) => {
|
||||
notified = true;
|
||||
newModeValue = newMode;
|
||||
});
|
||||
|
||||
manager.setMode('architect');
|
||||
|
||||
expect(notified).toBe(true);
|
||||
expect(newModeValue).toBe('architect');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateRooConfig', () => {
|
||||
it('should generate Roo-compatible config', () => {
|
||||
const config = manager.generateRooConfig();
|
||||
|
||||
expect(config.defaultMode).toBe('code');
|
||||
expect(config.modes).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateModeDocumentation', () => {
|
||||
it('should generate mode documentation', () => {
|
||||
const docs = manager.generateModeDocumentation();
|
||||
|
||||
expect(docs).toContain('# Available Modes');
|
||||
expect(docs).toContain('## code');
|
||||
expect(docs).toContain('## architect');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createDefaultModeManager', () => {
|
||||
it('should create manager with default modes', () => {
|
||||
const manager = createDefaultModeManager({
|
||||
code: ['tdd'],
|
||||
debug: ['debugging'],
|
||||
});
|
||||
|
||||
const modes = manager.getAvailableModes();
|
||||
|
||||
expect(modes.length).toBe(7); // All default modes
|
||||
expect(manager.getMode('code')?.skills).toContain('tdd');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ALL_MODES', () => {
|
||||
it('should contain all mode types', () => {
|
||||
expect(ALL_MODES).toContain('code');
|
||||
expect(ALL_MODES).toContain('architect');
|
||||
expect(ALL_MODES).toContain('debug');
|
||||
expect(ALL_MODES).toContain('test');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* Bootstrap Files System
|
||||
*
|
||||
* Implements bootstrap file generation for agents that support them.
|
||||
*/
|
||||
|
||||
import type {
|
||||
BootstrapFile,
|
||||
BootstrapFileType,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Default bootstrap file names for each type
|
||||
*/
|
||||
const DEFAULT_FILE_NAMES: Record<BootstrapFileType, string> = {
|
||||
agents: 'AGENTS.md',
|
||||
soul: 'SOUL.md',
|
||||
tools: 'TOOLS.md',
|
||||
identity: 'IDENTITY.md',
|
||||
context: 'CONTEXT.md',
|
||||
brief: 'BRIEF.md',
|
||||
history: 'HISTORY.md',
|
||||
};
|
||||
|
||||
/**
|
||||
* BootstrapManager - Manage bootstrap files for agents
|
||||
*/
|
||||
export class BootstrapManager {
|
||||
private files: Map<BootstrapFileType, BootstrapFile> = new Map();
|
||||
|
||||
/**
|
||||
* Add a bootstrap file
|
||||
*/
|
||||
addFile(file: BootstrapFile): void {
|
||||
this.files.set(file.type, file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a bootstrap file by type
|
||||
*/
|
||||
getFile(type: BootstrapFileType): BootstrapFile | undefined {
|
||||
return this.files.get(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all bootstrap files
|
||||
*/
|
||||
getAllFiles(): BootstrapFile[] {
|
||||
return Array.from(this.files.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get files sorted by priority
|
||||
*/
|
||||
getFilesByPriority(): BootstrapFile[] {
|
||||
return this.getAllFiles().sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a bootstrap file
|
||||
*/
|
||||
removeFile(type: BootstrapFileType): boolean {
|
||||
return this.files.delete(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file type exists
|
||||
*/
|
||||
hasFile(type: BootstrapFileType): boolean {
|
||||
return this.files.has(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create AGENTS.md file
|
||||
*/
|
||||
createAgentsFile(agents: AgentDefinition[]): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Agents');
|
||||
lines.push('');
|
||||
lines.push('This file defines the available agents and their capabilities.');
|
||||
lines.push('');
|
||||
|
||||
for (const agent of agents) {
|
||||
lines.push(`## ${agent.name}`);
|
||||
lines.push('');
|
||||
if (agent.description) {
|
||||
lines.push(agent.description);
|
||||
lines.push('');
|
||||
}
|
||||
if (agent.capabilities && agent.capabilities.length > 0) {
|
||||
lines.push('### Capabilities');
|
||||
lines.push('');
|
||||
for (const cap of agent.capabilities) {
|
||||
lines.push(`- ${cap}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
if (agent.constraints && agent.constraints.length > 0) {
|
||||
lines.push('### Constraints');
|
||||
lines.push('');
|
||||
for (const constraint of agent.constraints) {
|
||||
lines.push(`- ${constraint}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'agents',
|
||||
name: 'AGENTS.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 100,
|
||||
required: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create SOUL.md file
|
||||
*/
|
||||
createSoulFile(soul: SoulDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Soul');
|
||||
lines.push('');
|
||||
lines.push('This file defines the personality and behavior of the agent.');
|
||||
lines.push('');
|
||||
|
||||
if (soul.personality) {
|
||||
lines.push('## Personality');
|
||||
lines.push('');
|
||||
lines.push(soul.personality);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.values && soul.values.length > 0) {
|
||||
lines.push('## Values');
|
||||
lines.push('');
|
||||
for (const value of soul.values) {
|
||||
lines.push(`- ${value}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.communication) {
|
||||
lines.push('## Communication Style');
|
||||
lines.push('');
|
||||
lines.push(soul.communication);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.rules && soul.rules.length > 0) {
|
||||
lines.push('## Rules');
|
||||
lines.push('');
|
||||
for (const rule of soul.rules) {
|
||||
lines.push(`- ${rule}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'soul',
|
||||
name: 'SOUL.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 90,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create TOOLS.md file
|
||||
*/
|
||||
createToolsFile(tools: ToolDefinition[]): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Tools');
|
||||
lines.push('');
|
||||
lines.push('This file defines the available tools and their usage.');
|
||||
lines.push('');
|
||||
|
||||
for (const tool of tools) {
|
||||
lines.push(`## ${tool.name}`);
|
||||
lines.push('');
|
||||
if (tool.description) {
|
||||
lines.push(tool.description);
|
||||
lines.push('');
|
||||
}
|
||||
if (tool.usage) {
|
||||
lines.push('### Usage');
|
||||
lines.push('');
|
||||
lines.push('```');
|
||||
lines.push(tool.usage);
|
||||
lines.push('```');
|
||||
lines.push('');
|
||||
}
|
||||
if (tool.examples && tool.examples.length > 0) {
|
||||
lines.push('### Examples');
|
||||
lines.push('');
|
||||
for (const example of tool.examples) {
|
||||
lines.push(`- ${example}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'tools',
|
||||
name: 'TOOLS.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 80,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create IDENTITY.md file
|
||||
*/
|
||||
createIdentityFile(identity: IdentityDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Identity');
|
||||
lines.push('');
|
||||
|
||||
if (identity.name) {
|
||||
lines.push(`**Name:** ${identity.name}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.role) {
|
||||
lines.push(`**Role:** ${identity.role}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.description) {
|
||||
lines.push('## Description');
|
||||
lines.push('');
|
||||
lines.push(identity.description);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.expertise && identity.expertise.length > 0) {
|
||||
lines.push('## Expertise');
|
||||
lines.push('');
|
||||
for (const exp of identity.expertise) {
|
||||
lines.push(`- ${exp}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'identity',
|
||||
name: 'IDENTITY.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 95,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CONTEXT.md file
|
||||
*/
|
||||
createContextFile(context: ContextDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Context');
|
||||
lines.push('');
|
||||
|
||||
if (context.project) {
|
||||
lines.push('## Project');
|
||||
lines.push('');
|
||||
lines.push(context.project);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.techStack && context.techStack.length > 0) {
|
||||
lines.push('## Tech Stack');
|
||||
lines.push('');
|
||||
for (const tech of context.techStack) {
|
||||
lines.push(`- ${tech}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.conventions && context.conventions.length > 0) {
|
||||
lines.push('## Conventions');
|
||||
lines.push('');
|
||||
for (const conv of context.conventions) {
|
||||
lines.push(`- ${conv}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.currentTask) {
|
||||
lines.push('## Current Task');
|
||||
lines.push('');
|
||||
lines.push(context.currentTask);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'context',
|
||||
name: 'CONTEXT.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 70,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate all files as a map
|
||||
*/
|
||||
generateFiles(): Map<string, string> {
|
||||
const files = new Map<string, string>();
|
||||
|
||||
for (const file of this.getFilesByPriority()) {
|
||||
files.set(file.name, file.content);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate combined content for agents without file support
|
||||
*/
|
||||
generateCombinedContent(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const file of this.getFilesByPriority()) {
|
||||
lines.push(`<!-- ${file.name} -->`);
|
||||
lines.push('');
|
||||
lines.push(file.content);
|
||||
lines.push('');
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default file name for a type
|
||||
*/
|
||||
static getDefaultFileName(type: BootstrapFileType): string {
|
||||
return DEFAULT_FILE_NAMES[type];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent definition for AGENTS.md
|
||||
*/
|
||||
export interface AgentDefinition {
|
||||
name: string;
|
||||
description?: string;
|
||||
capabilities?: string[];
|
||||
constraints?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Soul definition for SOUL.md
|
||||
*/
|
||||
export interface SoulDefinition {
|
||||
personality?: string;
|
||||
values?: string[];
|
||||
communication?: string;
|
||||
rules?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool definition for TOOLS.md
|
||||
*/
|
||||
export interface ToolDefinition {
|
||||
name: string;
|
||||
description?: string;
|
||||
usage?: string;
|
||||
examples?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity definition for IDENTITY.md
|
||||
*/
|
||||
export interface IdentityDefinition {
|
||||
name?: string;
|
||||
role?: string;
|
||||
description?: string;
|
||||
expertise?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Context definition for CONTEXT.md
|
||||
*/
|
||||
export interface ContextDefinition {
|
||||
project?: string;
|
||||
techStack?: string[];
|
||||
conventions?: string[];
|
||||
currentTask?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BootstrapManager instance
|
||||
*/
|
||||
export function createBootstrapManager(): BootstrapManager {
|
||||
return new BootstrapManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a complete bootstrap set from definitions
|
||||
*/
|
||||
export function createBootstrapSet(options: {
|
||||
agents?: AgentDefinition[];
|
||||
soul?: SoulDefinition;
|
||||
tools?: ToolDefinition[];
|
||||
identity?: IdentityDefinition;
|
||||
context?: ContextDefinition;
|
||||
}): BootstrapManager {
|
||||
const manager = new BootstrapManager();
|
||||
|
||||
if (options.agents) {
|
||||
manager.createAgentsFile(options.agents);
|
||||
}
|
||||
|
||||
if (options.soul) {
|
||||
manager.createSoulFile(options.soul);
|
||||
}
|
||||
|
||||
if (options.tools) {
|
||||
manager.createToolsFile(options.tools);
|
||||
}
|
||||
|
||||
if (options.identity) {
|
||||
manager.createIdentityFile(options.identity);
|
||||
}
|
||||
|
||||
if (options.context) {
|
||||
manager.createContextFile(options.context);
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Glob Pattern System
|
||||
*
|
||||
* Implements file pattern matching for file-scoped skills.
|
||||
*/
|
||||
|
||||
import { minimatch } from 'minimatch';
|
||||
import type { GlobConfig } from './types.js';
|
||||
|
||||
/**
|
||||
* GlobMatcher - Match files against glob patterns
|
||||
*/
|
||||
export class GlobMatcher {
|
||||
private config: GlobConfig;
|
||||
private includePatterns: RegExp[];
|
||||
private excludePatterns: RegExp[];
|
||||
|
||||
constructor(config: GlobConfig) {
|
||||
this.config = config;
|
||||
this.includePatterns = config.include.map((p) => this.patternToRegex(p));
|
||||
this.excludePatterns = (config.exclude || []).map((p) => this.patternToRegex(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file matches the glob patterns
|
||||
*/
|
||||
matches(filePath: string): boolean {
|
||||
// Normalize path separators
|
||||
const normalizedPath = filePath.replace(/\\/g, '/');
|
||||
|
||||
// Check if hidden file and skip if not matching hidden
|
||||
if (!this.config.matchHidden && this.isHiddenFile(normalizedPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check exclude patterns first
|
||||
for (const pattern of this.excludePatterns) {
|
||||
if (pattern.test(normalizedPath)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check include patterns
|
||||
for (const pattern of this.includePatterns) {
|
||||
if (pattern.test(normalizedPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter a list of files
|
||||
*/
|
||||
filter(filePaths: string[]): string[] {
|
||||
return filePaths.filter((p) => this.matches(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all include patterns
|
||||
*/
|
||||
getIncludePatterns(): string[] {
|
||||
return [...this.config.include];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all exclude patterns
|
||||
*/
|
||||
getExcludePatterns(): string[] {
|
||||
return [...(this.config.exclude || [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an include pattern
|
||||
*/
|
||||
addInclude(pattern: string): void {
|
||||
this.config.include.push(pattern);
|
||||
this.includePatterns.push(this.patternToRegex(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an exclude pattern
|
||||
*/
|
||||
addExclude(pattern: string): void {
|
||||
if (!this.config.exclude) {
|
||||
this.config.exclude = [];
|
||||
}
|
||||
this.config.exclude.push(pattern);
|
||||
this.excludePatterns.push(this.patternToRegex(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert glob pattern to regex using minimatch
|
||||
*
|
||||
* Uses the battle-tested minimatch library to avoid ReDoS vulnerabilities
|
||||
* and ensure consistent glob matching behavior.
|
||||
*/
|
||||
private patternToRegex(pattern: string): RegExp {
|
||||
// Handle negation
|
||||
const isNegated = pattern.startsWith('!');
|
||||
const cleanPattern = isNegated ? pattern.slice(1) : pattern;
|
||||
|
||||
// Adjust pattern for directory matching
|
||||
let adjustedPattern = cleanPattern;
|
||||
if (this.config.matchDirectories && !cleanPattern.endsWith('/**')) {
|
||||
// Append /** to match directories and their contents
|
||||
adjustedPattern = cleanPattern.endsWith('/')
|
||||
? `${cleanPattern}**`
|
||||
: `${cleanPattern}/**`;
|
||||
}
|
||||
|
||||
// Use minimatch to create a safe regex
|
||||
// minimatch returns null if pattern is invalid, fallback to match-nothing regex
|
||||
const regex = minimatch.makeRe(adjustedPattern, { dot: this.config.matchHidden });
|
||||
|
||||
return regex || /(?!)/; // /(?!)/ is a regex that never matches anything
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is hidden (starts with .)
|
||||
*/
|
||||
private isHiddenFile(path: string): boolean {
|
||||
const parts = path.split('/');
|
||||
return parts.some((part) => part.startsWith('.') && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Cursor-compatible globs field
|
||||
*/
|
||||
generateCursorGlobs(): string[] {
|
||||
const globs: string[] = [...this.config.include];
|
||||
|
||||
// Add negated exclude patterns
|
||||
if (this.config.exclude) {
|
||||
for (const pattern of this.config.exclude) {
|
||||
globs.push(`!${pattern}`);
|
||||
}
|
||||
}
|
||||
|
||||
return globs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MDC frontmatter
|
||||
*/
|
||||
generateMDCFrontmatter(): string {
|
||||
const globs = this.generateCursorGlobs();
|
||||
return `globs: ${JSON.stringify(globs)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GlobMatcher instance
|
||||
*/
|
||||
export function createGlobMatcher(config: GlobConfig): GlobMatcher {
|
||||
return new GlobMatcher(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GlobMatcher from a single pattern
|
||||
*/
|
||||
export function matchPattern(pattern: string): GlobMatcher {
|
||||
return new GlobMatcher({ include: [pattern] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse glob patterns from Cursor MDC format
|
||||
*/
|
||||
export function parseGlobsFromMDC(content: string): GlobConfig | null {
|
||||
const match = content.match(/globs:\s*(\[.*?\])/s);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const patterns = JSON.parse(match[1]) as string[];
|
||||
const include: string[] = [];
|
||||
const exclude: string[] = [];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
if (pattern.startsWith('!')) {
|
||||
exclude.push(pattern.slice(1));
|
||||
} else {
|
||||
include.push(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
return { include, exclude };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common glob patterns for different file types
|
||||
*/
|
||||
export const COMMON_PATTERNS = {
|
||||
/** All TypeScript files */
|
||||
typescript: ['**/*.ts', '**/*.tsx'],
|
||||
/** All JavaScript files */
|
||||
javascript: ['**/*.js', '**/*.jsx', '**/*.mjs', '**/*.cjs'],
|
||||
/** All test files */
|
||||
tests: ['**/*.test.*', '**/*.spec.*', '**/__tests__/**'],
|
||||
/** All config files */
|
||||
configs: ['*.config.*', '*rc', '*rc.*', '*.json', '*.yaml', '*.yml'],
|
||||
/** All source files */
|
||||
source: ['src/**/*'],
|
||||
/** All documentation */
|
||||
docs: ['**/*.md', 'docs/**/*', 'README*'],
|
||||
/** Node modules (usually excluded) */
|
||||
nodeModules: ['**/node_modules/**'],
|
||||
/** Build outputs (usually excluded) */
|
||||
buildOutputs: ['**/dist/**', '**/build/**', '**/.next/**'],
|
||||
/** All files */
|
||||
all: ['**/*'],
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Create glob config from common pattern names
|
||||
*/
|
||||
export function fromCommonPatterns(
|
||||
includeNames: (keyof typeof COMMON_PATTERNS)[],
|
||||
excludeNames?: (keyof typeof COMMON_PATTERNS)[]
|
||||
): GlobConfig {
|
||||
const include: string[] = [];
|
||||
const exclude: string[] = [];
|
||||
|
||||
for (const name of includeNames) {
|
||||
include.push(...COMMON_PATTERNS[name]);
|
||||
}
|
||||
|
||||
if (excludeNames) {
|
||||
for (const name of excludeNames) {
|
||||
exclude.push(...COMMON_PATTERNS[name]);
|
||||
}
|
||||
}
|
||||
|
||||
return { include, exclude };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Agent Features Module
|
||||
*
|
||||
* Enhanced agent-specific features including:
|
||||
* - Permissions system (OpenCode-style)
|
||||
* - Glob pattern matching (Cursor-style)
|
||||
* - Bootstrap files (Amp-style)
|
||||
* - Multi-mode support (Roo/Kilo-style)
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './permissions.js';
|
||||
export * from './globs.js';
|
||||
export * from './bootstrap.js';
|
||||
export * from './modes.js';
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Multi-Mode System
|
||||
*
|
||||
* Implements multi-mode support for agents that support different operating modes.
|
||||
*/
|
||||
|
||||
import type { AgentMode, ModeConfig } from './types.js';
|
||||
import { GlobMatcher } from './globs.js';
|
||||
|
||||
/**
|
||||
* Default mode configurations
|
||||
*/
|
||||
const DEFAULT_MODES: Record<AgentMode, Omit<ModeConfig, 'skills'>> = {
|
||||
code: {
|
||||
mode: 'code',
|
||||
description: 'Code editing and implementation mode',
|
||||
promptPrefix: 'You are in code mode. Focus on writing and editing code.',
|
||||
},
|
||||
architect: {
|
||||
mode: 'architect',
|
||||
description: 'Architecture and planning mode',
|
||||
promptPrefix: 'You are in architect mode. Focus on system design and planning.',
|
||||
},
|
||||
ask: {
|
||||
mode: 'ask',
|
||||
description: 'Question and answer mode',
|
||||
promptPrefix: 'You are in ask mode. Focus on answering questions clearly.',
|
||||
},
|
||||
debug: {
|
||||
mode: 'debug',
|
||||
description: 'Debugging and troubleshooting mode',
|
||||
promptPrefix: 'You are in debug mode. Focus on finding and fixing issues.',
|
||||
},
|
||||
review: {
|
||||
mode: 'review',
|
||||
description: 'Code review mode',
|
||||
promptPrefix: 'You are in review mode. Focus on reviewing code quality.',
|
||||
},
|
||||
test: {
|
||||
mode: 'test',
|
||||
description: 'Testing mode',
|
||||
promptPrefix: 'You are in test mode. Focus on writing and running tests.',
|
||||
},
|
||||
docs: {
|
||||
mode: 'docs',
|
||||
description: 'Documentation mode',
|
||||
promptPrefix: 'You are in docs mode. Focus on writing documentation.',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* ModeManager - Manage agent operating modes
|
||||
*/
|
||||
export class ModeManager {
|
||||
private modes: Map<AgentMode, ModeConfig> = new Map();
|
||||
private currentMode: AgentMode = 'code';
|
||||
private modeListeners: Set<ModeChangeListener> = new Set();
|
||||
|
||||
constructor(modes?: ModeConfig[]) {
|
||||
if (modes) {
|
||||
for (const mode of modes) {
|
||||
this.addMode(mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a mode configuration
|
||||
*/
|
||||
addMode(config: ModeConfig): void {
|
||||
this.modes.set(config.mode, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a mode configuration
|
||||
*/
|
||||
getMode(mode: AgentMode): ModeConfig | undefined {
|
||||
return this.modes.get(mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all mode configurations
|
||||
*/
|
||||
getAllModes(): ModeConfig[] {
|
||||
return Array.from(this.modes.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available mode names
|
||||
*/
|
||||
getAvailableModes(): AgentMode[] {
|
||||
return Array.from(this.modes.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current mode
|
||||
*/
|
||||
setMode(mode: AgentMode): void {
|
||||
const config = this.modes.get(mode);
|
||||
if (!config) {
|
||||
throw new Error(`Mode not configured: ${mode}`);
|
||||
}
|
||||
|
||||
const previousMode = this.currentMode;
|
||||
this.currentMode = mode;
|
||||
|
||||
// Notify listeners
|
||||
for (const listener of this.modeListeners) {
|
||||
listener(mode, previousMode, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current mode
|
||||
*/
|
||||
getCurrentMode(): AgentMode {
|
||||
return this.currentMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current mode configuration
|
||||
*/
|
||||
getCurrentModeConfig(): ModeConfig | undefined {
|
||||
return this.modes.get(this.currentMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get skills for current mode
|
||||
*/
|
||||
getCurrentSkills(): string[] {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.skills || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tools for current mode
|
||||
*/
|
||||
getCurrentTools(): string[] {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.tools || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a skill is available in current mode
|
||||
*/
|
||||
isSkillAvailable(skillName: string): boolean {
|
||||
const skills = this.getCurrentSkills();
|
||||
return skills.length === 0 || skills.includes(skillName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is allowed in current mode
|
||||
*/
|
||||
isFileAllowed(filePath: string): boolean {
|
||||
const config = this.getCurrentModeConfig();
|
||||
if (!config?.allowedFiles || config.allowedFiles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const matcher = new GlobMatcher({ include: config.allowedFiles });
|
||||
return matcher.matches(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add mode change listener
|
||||
*/
|
||||
addModeListener(listener: ModeChangeListener): void {
|
||||
this.modeListeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove mode change listener
|
||||
*/
|
||||
removeModeListener(listener: ModeChangeListener): void {
|
||||
this.modeListeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mode from default configuration
|
||||
*/
|
||||
addDefaultMode(mode: AgentMode, skills: string[]): void {
|
||||
const defaultConfig = DEFAULT_MODES[mode];
|
||||
this.addMode({
|
||||
...defaultConfig,
|
||||
skills,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mode-specific prompt prefix
|
||||
*/
|
||||
getPromptPrefix(): string {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.promptPrefix || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Roo-compatible mode configuration
|
||||
*/
|
||||
generateRooConfig(): Record<string, unknown> {
|
||||
const modes: Record<string, unknown> = {};
|
||||
|
||||
for (const config of this.modes.values()) {
|
||||
modes[config.mode] = {
|
||||
description: config.description,
|
||||
skills: config.skills,
|
||||
tools: config.tools,
|
||||
promptPrefix: config.promptPrefix,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
defaultMode: this.currentMode,
|
||||
modes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mode documentation
|
||||
*/
|
||||
generateModeDocumentation(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Available Modes');
|
||||
lines.push('');
|
||||
|
||||
for (const config of this.modes.values()) {
|
||||
lines.push(`## ${config.mode}`);
|
||||
lines.push('');
|
||||
lines.push(config.description);
|
||||
lines.push('');
|
||||
|
||||
if (config.skills.length > 0) {
|
||||
lines.push('### Skills');
|
||||
lines.push('');
|
||||
for (const skill of config.skills) {
|
||||
lines.push(`- ${skill}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (config.tools && config.tools.length > 0) {
|
||||
lines.push('### Tools');
|
||||
lines.push('');
|
||||
for (const tool of config.tools) {
|
||||
lines.push(`- ${tool}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode change listener type
|
||||
*/
|
||||
export type ModeChangeListener = (
|
||||
newMode: AgentMode,
|
||||
previousMode: AgentMode,
|
||||
config: ModeConfig
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Create a ModeManager instance
|
||||
*/
|
||||
export function createModeManager(modes?: ModeConfig[]): ModeManager {
|
||||
return new ModeManager(modes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModeManager with all default modes
|
||||
*/
|
||||
export function createDefaultModeManager(
|
||||
skillsPerMode: Partial<Record<AgentMode, string[]>>
|
||||
): ModeManager {
|
||||
const manager = new ModeManager();
|
||||
|
||||
for (const [mode, config] of Object.entries(DEFAULT_MODES)) {
|
||||
const skills = skillsPerMode[mode as AgentMode] || [];
|
||||
manager.addMode({
|
||||
...config,
|
||||
skills,
|
||||
});
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default configuration for a mode
|
||||
*/
|
||||
export function getDefaultModeConfig(mode: AgentMode): Omit<ModeConfig, 'skills'> {
|
||||
return DEFAULT_MODES[mode];
|
||||
}
|
||||
|
||||
/**
|
||||
* All available agent modes
|
||||
*/
|
||||
export const ALL_MODES: AgentMode[] = ['code', 'architect', 'ask', 'debug', 'review', 'test', 'docs'];
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Permissions System
|
||||
*
|
||||
* Implements permission patterns for agent skill access control.
|
||||
*/
|
||||
|
||||
import { minimatch } from 'minimatch';
|
||||
import type {
|
||||
PermissionConfig,
|
||||
PermissionPattern,
|
||||
PermissionLevel,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* PermissionManager - Manage skill permissions
|
||||
*/
|
||||
export class PermissionManager {
|
||||
private config: PermissionConfig;
|
||||
|
||||
constructor(config?: PermissionConfig) {
|
||||
this.config = config || { default: 'ask' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set permission configuration
|
||||
*/
|
||||
setConfig(config: PermissionConfig): void {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get permission configuration
|
||||
*/
|
||||
getConfig(): PermissionConfig {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check file access permission
|
||||
*/
|
||||
checkFileAccess(path: string): PermissionLevel {
|
||||
return this.checkPattern(path, this.config.files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check command execution permission
|
||||
*/
|
||||
checkCommandAccess(command: string): PermissionLevel {
|
||||
return this.checkPattern(command, this.config.commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check network access permission
|
||||
*/
|
||||
checkNetworkAccess(url: string): PermissionLevel {
|
||||
return this.checkPattern(url, this.config.network);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check environment variable access
|
||||
*/
|
||||
checkEnvAccess(varName: string): PermissionLevel {
|
||||
return this.checkPattern(varName, this.config.env);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add file permission pattern
|
||||
*/
|
||||
addFilePattern(pattern: PermissionPattern): void {
|
||||
if (!this.config.files) {
|
||||
this.config.files = [];
|
||||
}
|
||||
this.config.files.push(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add command permission pattern
|
||||
*/
|
||||
addCommandPattern(pattern: PermissionPattern): void {
|
||||
if (!this.config.commands) {
|
||||
this.config.commands = [];
|
||||
}
|
||||
this.config.commands.push(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check pattern against permission list
|
||||
*/
|
||||
private checkPattern(
|
||||
value: string,
|
||||
patterns?: PermissionPattern[]
|
||||
): PermissionLevel {
|
||||
if (!patterns || patterns.length === 0) {
|
||||
return this.config.default || 'ask';
|
||||
}
|
||||
|
||||
// Check patterns in order (first match wins)
|
||||
for (const pattern of patterns) {
|
||||
if (this.matchPattern(value, pattern.pattern)) {
|
||||
return pattern.level;
|
||||
}
|
||||
}
|
||||
|
||||
return this.config.default || 'ask';
|
||||
}
|
||||
|
||||
/**
|
||||
* Match value against pattern (glob-style)
|
||||
*
|
||||
* Uses minimatch for safe glob matching, avoiding ReDoS vulnerabilities.
|
||||
*/
|
||||
private matchPattern(value: string, pattern: string): boolean {
|
||||
// Use minimatch for safe, battle-tested glob matching
|
||||
// nocase option ensures case-insensitive matching
|
||||
return minimatch(value, pattern, { nocase: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate OpenCode-compatible permission config
|
||||
*/
|
||||
generateOpenCodeConfig(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Permission Configuration');
|
||||
lines.push('');
|
||||
|
||||
if (this.config.files && this.config.files.length > 0) {
|
||||
lines.push('## File Access');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.files) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (this.config.commands && this.config.commands.length > 0) {
|
||||
lines.push('## Command Execution');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.commands) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (this.config.network && this.config.network.length > 0) {
|
||||
lines.push('## Network Access');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.network) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`Default: ${this.config.default || 'ask'}`);
|
||||
lines.push('');
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate SKILL.md metadata for permissions
|
||||
*/
|
||||
generateSkillMetadata(): Record<string, unknown> {
|
||||
const metadata: Record<string, unknown> = {};
|
||||
|
||||
if (this.config.files) {
|
||||
metadata.filePermissions = this.config.files.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.commands) {
|
||||
metadata.commandPermissions = this.config.commands.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.network) {
|
||||
metadata.networkPermissions = this.config.network.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.default) {
|
||||
metadata.defaultPermission = this.config.default;
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse permissions from SKILL.md metadata
|
||||
*/
|
||||
static fromMetadata(metadata: Record<string, unknown>): PermissionConfig {
|
||||
const config: PermissionConfig = {};
|
||||
|
||||
if (metadata.filePermissions && Array.isArray(metadata.filePermissions)) {
|
||||
config.files = metadata.filePermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.commandPermissions && Array.isArray(metadata.commandPermissions)) {
|
||||
config.commands = metadata.commandPermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.networkPermissions && Array.isArray(metadata.networkPermissions)) {
|
||||
config.network = metadata.networkPermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.defaultPermission) {
|
||||
config.default = metadata.defaultPermission as PermissionLevel;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two permission configs
|
||||
*/
|
||||
static merge(base: PermissionConfig, override: PermissionConfig): PermissionConfig {
|
||||
return {
|
||||
files: [...(base.files || []), ...(override.files || [])],
|
||||
commands: [...(base.commands || []), ...(override.commands || [])],
|
||||
network: [...(base.network || []), ...(override.network || [])],
|
||||
env: [...(base.env || []), ...(override.env || [])],
|
||||
default: override.default || base.default,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a PermissionManager instance
|
||||
*/
|
||||
export function createPermissionManager(config?: PermissionConfig): PermissionManager {
|
||||
return new PermissionManager(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick permission check helpers
|
||||
*/
|
||||
export function isAllowed(level: PermissionLevel): boolean {
|
||||
return level === 'allow';
|
||||
}
|
||||
|
||||
export function isDenied(level: PermissionLevel): boolean {
|
||||
return level === 'deny';
|
||||
}
|
||||
|
||||
export function needsConfirmation(level: PermissionLevel): boolean {
|
||||
return level === 'ask';
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Agent Features Types
|
||||
*
|
||||
* Type definitions for enhanced agent-specific features.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Permission level for agent actions
|
||||
*/
|
||||
export type PermissionLevel = 'allow' | 'deny' | 'ask';
|
||||
|
||||
/**
|
||||
* Permission pattern for file/resource access
|
||||
*/
|
||||
export interface PermissionPattern {
|
||||
/** Pattern to match (glob or regex) */
|
||||
pattern: string;
|
||||
/** Permission level */
|
||||
level: PermissionLevel;
|
||||
/** Description of why this permission is needed */
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission configuration for skills
|
||||
*/
|
||||
export interface PermissionConfig {
|
||||
/** File access permissions */
|
||||
files?: PermissionPattern[];
|
||||
/** Command execution permissions */
|
||||
commands?: PermissionPattern[];
|
||||
/** Network access permissions */
|
||||
network?: PermissionPattern[];
|
||||
/** Environment variable access */
|
||||
env?: PermissionPattern[];
|
||||
/** Default permission level */
|
||||
default?: PermissionLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Glob pattern configuration for file-scoped skills
|
||||
*/
|
||||
export interface GlobConfig {
|
||||
/** Patterns to include */
|
||||
include: string[];
|
||||
/** Patterns to exclude */
|
||||
exclude?: string[];
|
||||
/** Whether to match directories */
|
||||
matchDirectories?: boolean;
|
||||
/** Whether to match hidden files */
|
||||
matchHidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap file types
|
||||
*/
|
||||
export type BootstrapFileType =
|
||||
| 'agents' // AGENTS.md - Agent definitions
|
||||
| 'soul' // SOUL.md - Personality and behavior
|
||||
| 'tools' // TOOLS.md - Available tools
|
||||
| 'identity' // IDENTITY.md - Agent identity
|
||||
| 'context' // CONTEXT.md - Context information
|
||||
| 'brief' // BRIEF.md - Project brief
|
||||
| 'history'; // HISTORY.md - Conversation history
|
||||
|
||||
/**
|
||||
* Bootstrap file configuration
|
||||
*/
|
||||
export interface BootstrapFile {
|
||||
/** File type */
|
||||
type: BootstrapFileType;
|
||||
/** File name */
|
||||
name: string;
|
||||
/** File content */
|
||||
content: string;
|
||||
/** Priority (higher = loaded first) */
|
||||
priority?: number;
|
||||
/** Whether file is required */
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent mode types
|
||||
*/
|
||||
export type AgentMode =
|
||||
| 'code' // Code editing mode
|
||||
| 'architect' // Architecture/planning mode
|
||||
| 'ask' // Question/answer mode
|
||||
| 'debug' // Debugging mode
|
||||
| 'review' // Code review mode
|
||||
| 'test' // Testing mode
|
||||
| 'docs'; // Documentation mode
|
||||
|
||||
/**
|
||||
* Mode configuration
|
||||
*/
|
||||
export interface ModeConfig {
|
||||
/** Mode name */
|
||||
mode: AgentMode;
|
||||
/** Mode description */
|
||||
description: string;
|
||||
/** Skills available in this mode */
|
||||
skills: string[];
|
||||
/** Tools available in this mode */
|
||||
tools?: string[];
|
||||
/** Default prompt prefix for this mode */
|
||||
promptPrefix?: string;
|
||||
/** Allowed file patterns in this mode */
|
||||
allowedFiles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool whitelist configuration
|
||||
*/
|
||||
export interface ToolWhitelistConfig {
|
||||
/** Allowed tools */
|
||||
allowed: string[];
|
||||
/** Denied tools */
|
||||
denied?: string[];
|
||||
/** Mode for handling unlisted tools */
|
||||
unlisted?: 'allow' | 'deny' | 'ask';
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill package configuration (for .skill bundles)
|
||||
*/
|
||||
export interface SkillPackageConfig {
|
||||
/** Package name */
|
||||
name: string;
|
||||
/** Package version */
|
||||
version: string;
|
||||
/** Package description */
|
||||
description?: string;
|
||||
/** Entry point skill */
|
||||
entryPoint: string;
|
||||
/** Included skill files */
|
||||
files: string[];
|
||||
/** Dependencies */
|
||||
dependencies?: string[];
|
||||
/** Metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent feature capabilities
|
||||
*/
|
||||
export interface AgentCapabilities {
|
||||
/** Supports permission system */
|
||||
permissions: boolean;
|
||||
/** Supports glob patterns */
|
||||
globs: boolean;
|
||||
/** Supports bootstrap files */
|
||||
bootstrapFiles: boolean;
|
||||
/** Supports multi-mode */
|
||||
multiMode: boolean;
|
||||
/** Supports tool whitelisting */
|
||||
toolWhitelist: boolean;
|
||||
/** Supports .skill packages */
|
||||
skillPackages: boolean;
|
||||
/** Supports hooks */
|
||||
hooks: boolean;
|
||||
/** Supports subagents */
|
||||
subagents: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent feature set
|
||||
*/
|
||||
export interface AgentFeatures {
|
||||
/** Agent type */
|
||||
agent: AgentType;
|
||||
/** Agent capabilities */
|
||||
capabilities: AgentCapabilities;
|
||||
/** Permission configuration */
|
||||
permissions?: PermissionConfig;
|
||||
/** Glob configuration */
|
||||
globs?: GlobConfig;
|
||||
/** Bootstrap files */
|
||||
bootstrapFiles?: BootstrapFile[];
|
||||
/** Mode configurations */
|
||||
modes?: ModeConfig[];
|
||||
/** Tool whitelist */
|
||||
toolWhitelist?: ToolWhitelistConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature generation options
|
||||
*/
|
||||
export interface FeatureGenerationOptions {
|
||||
/** Target agent */
|
||||
agent: AgentType;
|
||||
/** Output directory */
|
||||
outputDir?: string;
|
||||
/** Include optional files */
|
||||
includeOptional?: boolean;
|
||||
/** Dry run (don't write files) */
|
||||
dryRun?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature validation result
|
||||
*/
|
||||
export interface FeatureValidationResult {
|
||||
/** Whether features are valid */
|
||||
valid: boolean;
|
||||
/** Validation errors */
|
||||
errors: string[];
|
||||
/** Validation warnings */
|
||||
warnings: string[];
|
||||
/** Agent capabilities used */
|
||||
usedCapabilities: (keyof AgentCapabilities)[];
|
||||
}
|
||||
@@ -37,6 +37,9 @@ export * from './trae.js';
|
||||
export * from './windsurf.js';
|
||||
export * from './universal.js';
|
||||
|
||||
// Agent features
|
||||
export * from './features/index.js';
|
||||
|
||||
const adapters: Record<AgentType, AgentAdapter> = {
|
||||
'claude-code': new ClaudeCodeAdapter(),
|
||||
cursor: new CursorAdapter(),
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
# @skillkit/cli
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/cli)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Command-line interface for SkillKit** - install, manage, translate, and sync skills across 17 AI coding agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install -g @skillkit/cli
|
||||
# or
|
||||
npm install -g skillkit # includes CLI
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Get skill recommendations for your project
|
||||
skillkit recommend
|
||||
|
||||
# Install skills from GitHub
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Translate skills between agents
|
||||
skillkit translate my-skill --to cursor
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## All Commands
|
||||
|
||||
### Skill Management
|
||||
|
||||
```bash
|
||||
skillkit install <source> # Install from GitHub/GitLab/Bitbucket/local
|
||||
skillkit remove <skills> # Remove installed skills
|
||||
skillkit update [skills] # Update skills from source
|
||||
skillkit list # List installed skills
|
||||
skillkit enable <skills> # Enable specific skills
|
||||
skillkit disable <skills> # Disable specific skills
|
||||
skillkit sync # Sync to agent config
|
||||
skillkit read <skills> # Read skill content
|
||||
```
|
||||
|
||||
### Discovery & Recommendations
|
||||
|
||||
```bash
|
||||
skillkit recommend # Project-based recommendations
|
||||
skillkit recommend --search "auth" # Task-based search
|
||||
skillkit recommend --category security # Filter by category
|
||||
skillkit recommend --min-score 80 # Quality threshold
|
||||
|
||||
skillkit marketplace # Browse skills
|
||||
skillkit marketplace search "react" # Search marketplace
|
||||
skillkit marketplace --tags typescript # Filter by tags
|
||||
skillkit marketplace refresh # Refresh index
|
||||
```
|
||||
|
||||
### Translation
|
||||
|
||||
```bash
|
||||
skillkit translate <skill> --to <agent> # Translate single skill
|
||||
skillkit translate --all --to cursor # Translate all skills
|
||||
skillkit translate skill --dry-run # Preview without writing
|
||||
```
|
||||
|
||||
### Context Management
|
||||
|
||||
```bash
|
||||
skillkit context init # Analyze project, create context
|
||||
skillkit context show # Display current context
|
||||
skillkit context sync --all # Sync to all detected agents
|
||||
skillkit context export # Export context file
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```bash
|
||||
skillkit memory status # View memory status
|
||||
skillkit memory search "auth" # Search learnings
|
||||
skillkit memory list # List all learnings
|
||||
skillkit memory compress # Compress observations
|
||||
skillkit memory export <id> # Export as skill
|
||||
skillkit memory add # Add manual learning
|
||||
skillkit memory --global # Use global scope
|
||||
```
|
||||
|
||||
### Testing & Workflows
|
||||
|
||||
```bash
|
||||
skillkit test # Run all skill tests
|
||||
skillkit test ./my-skill # Test specific skill
|
||||
skillkit test --tags unit # Run tagged tests
|
||||
|
||||
skillkit workflow list # List workflows
|
||||
skillkit workflow run <name> # Execute workflow
|
||||
skillkit workflow create # Create new workflow
|
||||
|
||||
skillkit cicd github-action # Generate GitHub Actions
|
||||
skillkit cicd gitlab-ci # Generate GitLab CI
|
||||
skillkit cicd pre-commit # Generate pre-commit hook
|
||||
skillkit cicd init # Initialize CI/CD templates
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```bash
|
||||
skillkit team init --name "Team" # Initialize team
|
||||
skillkit team share <bundle> # Share skill bundle
|
||||
skillkit team import <path> # Import bundle
|
||||
skillkit team list # List team bundles
|
||||
skillkit team sync # Sync with remote
|
||||
skillkit team remove <bundle> # Remove bundle
|
||||
skillkit team bundle-create # Create new bundle
|
||||
skillkit team bundle-export <id> # Export bundle
|
||||
skillkit team bundle-list # List all bundles
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```bash
|
||||
skillkit plugin list # List installed plugins
|
||||
skillkit plugin install <name> # Install plugin
|
||||
skillkit plugin uninstall <name> # Uninstall plugin
|
||||
skillkit plugin enable <name> # Enable plugin
|
||||
skillkit plugin disable <name> # Disable plugin
|
||||
skillkit plugin info <name> # Plugin details
|
||||
```
|
||||
|
||||
### Methodologies & Plans
|
||||
|
||||
```bash
|
||||
skillkit methodology list # List methodologies
|
||||
skillkit methodology load <name> # Load methodology
|
||||
skillkit methodology apply <name> # Apply to project
|
||||
|
||||
skillkit plan parse <file> # Parse plan file
|
||||
skillkit plan validate <file> # Validate plan
|
||||
skillkit plan execute <file> # Execute plan
|
||||
skillkit plan status # Plan execution status
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```bash
|
||||
skillkit hook list # List registered hooks
|
||||
skillkit hook register <event> # Register new hook
|
||||
skillkit hook trigger <event> # Trigger hook manually
|
||||
skillkit hook enable <id> # Enable hook
|
||||
skillkit hook disable <id> # Disable hook
|
||||
```
|
||||
|
||||
### Agent Commands
|
||||
|
||||
```bash
|
||||
skillkit command generate <agent> # Generate agent-native commands
|
||||
skillkit command list <agent> # List available commands
|
||||
```
|
||||
|
||||
### Utilities
|
||||
|
||||
```bash
|
||||
skillkit init # Initialize in project
|
||||
skillkit init --agent cursor # Initialize for specific agent
|
||||
skillkit validate ./skill # Validate skill format
|
||||
skillkit create my-skill # Create new skill
|
||||
skillkit settings # View all settings
|
||||
skillkit settings --set key=value # Update setting
|
||||
```
|
||||
|
||||
## Install Options
|
||||
|
||||
```bash
|
||||
skillkit install owner/repo # GitHub repository
|
||||
skillkit install gitlab:owner/repo # GitLab repository
|
||||
skillkit install ./local/path # Local directory
|
||||
|
||||
# Options
|
||||
--list # List available skills without installing
|
||||
--skills=pdf,xlsx # Install specific skills
|
||||
--all # Install all discovered skills
|
||||
--yes # Skip confirmation prompts
|
||||
--global # Install globally
|
||||
--force # Overwrite existing
|
||||
--agent=cursor,windsurf # Install to specific agents
|
||||
```
|
||||
|
||||
## Programmatic Usage
|
||||
|
||||
```typescript
|
||||
import {
|
||||
installCommand,
|
||||
listCommand,
|
||||
syncCommand,
|
||||
translateCommand,
|
||||
recommendCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
// Install skills programmatically
|
||||
await installCommand('anthropics/skills', {
|
||||
agent: ['claude-code', 'cursor'],
|
||||
yes: true,
|
||||
});
|
||||
|
||||
// List installed skills
|
||||
const skills = await listCommand({ json: true });
|
||||
|
||||
// Sync to agent
|
||||
await syncCommand({ all: true });
|
||||
|
||||
// Translate skill
|
||||
await translateCommand('my-skill', {
|
||||
to: 'cursor',
|
||||
dryRun: false,
|
||||
});
|
||||
|
||||
// Get recommendations
|
||||
const recs = await recommendCommand({
|
||||
path: './my-project',
|
||||
minScore: 70,
|
||||
});
|
||||
```
|
||||
|
||||
## CI/CD Usage
|
||||
|
||||
```yaml
|
||||
# GitHub Actions example
|
||||
- name: Setup skills
|
||||
run: |
|
||||
npx skillkit install owner/skills --skills=lint,test --yes
|
||||
npx skillkit sync --yes
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
| Agent | Format |
|
||||
|-------|--------|
|
||||
| Claude Code | SKILL.md |
|
||||
| Cursor | MDC (.mdc) |
|
||||
| Codex | SKILL.md |
|
||||
| Gemini CLI | SKILL.md |
|
||||
| Windsurf | Markdown |
|
||||
| GitHub Copilot | Markdown |
|
||||
| + 11 more | SKILL.md |
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/cli",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.0",
|
||||
"description": "CLI commands for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -11,7 +11,9 @@
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
@@ -26,7 +28,8 @@
|
||||
"clipanion": "^4.0.0-rc.4",
|
||||
"got": "^14.4.1",
|
||||
"isomorphic-git": "^1.27.1",
|
||||
"ora": "^8.1.0"
|
||||
"ora": "^8.1.0",
|
||||
"yaml": "^2.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import { promises as fs } from 'fs';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
type SearchableSkill,
|
||||
type SkillExample,
|
||||
AIManager,
|
||||
loadIndex as loadIndexFromCache,
|
||||
} from '@skillkit/core';
|
||||
|
||||
export class AICommand extends Command {
|
||||
static override paths = [['ai']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'AI-powered skill search and generation',
|
||||
details: `
|
||||
The ai command provides AI-powered features for skills:
|
||||
|
||||
- Natural language search: Find skills using conversational queries
|
||||
- Skill generation: Automatically generate skills from examples
|
||||
- Similar skills: Find skills similar to a given skill
|
||||
|
||||
Note: Without an API key, the command uses a basic mock AI provider.
|
||||
Set ANTHROPIC_API_KEY or OPENAI_API_KEY to use real AI features.
|
||||
`,
|
||||
examples: [
|
||||
['Search skills naturally', '$0 ai search "help me write better tests"'],
|
||||
['Generate skill from description', '$0 ai generate --description "skill for code review"'],
|
||||
['Generate from code example', '$0 ai generate --from-code example.ts --description "..."'],
|
||||
['Find similar skills', '$0 ai similar my-skill-name'],
|
||||
],
|
||||
});
|
||||
|
||||
// Subcommand
|
||||
subcommand = Option.String({ required: true });
|
||||
|
||||
// Search options
|
||||
query = Option.String('--query,-q', {
|
||||
description: 'Search query for natural language search',
|
||||
});
|
||||
|
||||
// Generation options
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Description of the skill to generate',
|
||||
});
|
||||
|
||||
fromCode = Option.String('--from-code', {
|
||||
description: 'Generate skill from code example file',
|
||||
});
|
||||
|
||||
additionalContext = Option.String('--context', {
|
||||
description: 'Additional context for generation',
|
||||
});
|
||||
|
||||
targetAgent = Option.String('--agent,-a', {
|
||||
description: 'Target agent for generated skill',
|
||||
});
|
||||
|
||||
// Similar skills option
|
||||
skillName = Option.String({ required: false });
|
||||
|
||||
// Common options
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Maximum number of results',
|
||||
});
|
||||
|
||||
minRelevance = Option.String('--min-relevance', {
|
||||
description: 'Minimum relevance score (0-1)',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file for generated skill',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const aiConfig = this.getAIConfig();
|
||||
const manager = new AIManager(aiConfig);
|
||||
|
||||
if (!this.json) {
|
||||
const providerName = manager.getProviderName();
|
||||
if (providerName === 'mock') {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ Using mock AI provider (limited functionality)\n' +
|
||||
' Set ANTHROPIC_API_KEY or OPENAI_API_KEY for real AI features\n'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
switch (this.subcommand) {
|
||||
case 'search':
|
||||
return await this.handleSearch(manager);
|
||||
case 'generate':
|
||||
case 'gen':
|
||||
return await this.handleGenerate(manager);
|
||||
case 'similar':
|
||||
return await this.handleSimilar(manager);
|
||||
default:
|
||||
console.error(
|
||||
chalk.red(`Unknown subcommand: ${this.subcommand}\n`)
|
||||
);
|
||||
console.log('Valid subcommands: search, generate, similar');
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSearch(manager: AIManager): Promise<number> {
|
||||
const query = this.query || this.skillName;
|
||||
if (!query) {
|
||||
console.error(chalk.red('Search query required (--query or positional argument)'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await this.loadSkills();
|
||||
if (skills.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow('No skills found. Run "skillkit recommend --update" first.')
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const spinner = ora('Searching with AI...').start();
|
||||
|
||||
try {
|
||||
const results = await manager.searchSkills(query, skills, {
|
||||
limit: this.limit ? parseInt(this.limit, 10) : 10,
|
||||
minRelevance: this.minRelevance
|
||||
? parseFloat(this.minRelevance)
|
||||
: 0.5,
|
||||
includeReasoning: !this.json,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.log(chalk.yellow(`No skills found matching "${query}"`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`\nAI Search Results (${results.length} found):\n`));
|
||||
|
||||
for (const result of results) {
|
||||
const score = Math.round(result.relevance * 100);
|
||||
const scoreColor =
|
||||
score >= 70 ? chalk.green : score >= 50 ? chalk.yellow : chalk.dim;
|
||||
|
||||
console.log(
|
||||
` ${scoreColor(`${score}%`)} ${chalk.bold(result.skill.name)}`
|
||||
);
|
||||
|
||||
if (result.skill.description) {
|
||||
console.log(` ${chalk.dim(result.skill.description)}`);
|
||||
}
|
||||
|
||||
if (result.reasoning) {
|
||||
console.log(` ${chalk.dim('→ ' + result.reasoning)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleGenerate(manager: AIManager): Promise<number> {
|
||||
const description = this.description;
|
||||
if (!description) {
|
||||
console.error(chalk.red('Description required (--description)'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
let codeExamples: string[] = [];
|
||||
if (this.fromCode) {
|
||||
const codePath = resolve(this.fromCode);
|
||||
try {
|
||||
const code = await fs.readFile(codePath, 'utf-8');
|
||||
codeExamples = [code];
|
||||
} catch {
|
||||
console.error(chalk.red(`Failed to read code file: ${codePath}`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
const example: SkillExample = {
|
||||
description,
|
||||
context: this.additionalContext,
|
||||
codeExamples,
|
||||
targetAgent: this.targetAgent,
|
||||
};
|
||||
|
||||
const spinner = ora('Generating skill with AI...').start();
|
||||
|
||||
try {
|
||||
const generated = await manager.generateSkill(example, {
|
||||
targetAgent: this.targetAgent,
|
||||
includeTests: true,
|
||||
includeDocumentation: true,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
const validation = manager.validateGenerated(generated);
|
||||
if (!validation.valid) {
|
||||
console.log(chalk.yellow('\n⚠ Generated skill has validation warnings:'));
|
||||
for (const error of validation.errors) {
|
||||
console.log(chalk.dim(` • ${error}`));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(generated, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.green('\n✓ Generated skill successfully\n'));
|
||||
console.log(chalk.cyan('Name:') + ` ${generated.name}`);
|
||||
console.log(chalk.cyan('Description:') + ` ${generated.description}`);
|
||||
console.log(
|
||||
chalk.cyan('Tags:') + ` ${generated.tags.join(', ')}`
|
||||
);
|
||||
console.log(
|
||||
chalk.cyan('Confidence:') +
|
||||
` ${Math.round(generated.confidence * 100)}%`
|
||||
);
|
||||
|
||||
if (generated.reasoning) {
|
||||
console.log(chalk.cyan('Reasoning:') + ` ${generated.reasoning}`);
|
||||
}
|
||||
|
||||
console.log('\n' + chalk.dim('Content:'));
|
||||
console.log(chalk.dim('─'.repeat(60)));
|
||||
console.log(generated.content);
|
||||
console.log(chalk.dim('─'.repeat(60)));
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await fs.writeFile(outputPath, generated.content, 'utf-8');
|
||||
console.log(chalk.green(`\n✓ Saved to: ${outputPath}`));
|
||||
} else {
|
||||
console.log(
|
||||
chalk.dim('\nSave with: --output <filename>')
|
||||
);
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Generation failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSimilar(manager: AIManager): Promise<number> {
|
||||
const skillName = this.skillName;
|
||||
if (!skillName) {
|
||||
console.error(chalk.red('Skill name required'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await this.loadSkills();
|
||||
if (skills.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow('No skills found. Run "skillkit recommend --update" first.')
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const targetSkill = skills.find(
|
||||
(s) => s.name.toLowerCase() === skillName.toLowerCase()
|
||||
);
|
||||
|
||||
if (!targetSkill) {
|
||||
console.error(chalk.red(`Skill not found: ${skillName}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const spinner = ora('Finding similar skills...').start();
|
||||
|
||||
try {
|
||||
const results = await manager.findSimilar(targetSkill, skills, {
|
||||
limit: this.limit ? parseInt(this.limit, 10) : 10,
|
||||
minRelevance: this.minRelevance
|
||||
? parseFloat(this.minRelevance)
|
||||
: 0.5,
|
||||
includeReasoning: !this.json,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow(`No similar skills found for "${skillName}"`)
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(
|
||||
chalk.cyan(`\nSkills similar to "${skillName}" (${results.length} found):\n`)
|
||||
);
|
||||
|
||||
for (const result of results) {
|
||||
const score = Math.round(result.relevance * 100);
|
||||
const scoreColor =
|
||||
score >= 70 ? chalk.green : score >= 50 ? chalk.yellow : chalk.dim;
|
||||
|
||||
console.log(
|
||||
` ${scoreColor(`${score}%`)} ${chalk.bold(result.skill.name)}`
|
||||
);
|
||||
|
||||
if (result.skill.description) {
|
||||
console.log(` ${chalk.dim(result.skill.description)}`);
|
||||
}
|
||||
|
||||
if (result.reasoning) {
|
||||
console.log(` ${chalk.dim('→ ' + result.reasoning)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadSkills(): Promise<SearchableSkill[]> {
|
||||
const index = loadIndexFromCache();
|
||||
if (!index) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return index.skills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
content: '',
|
||||
tags: s.tags,
|
||||
source: s.source,
|
||||
}));
|
||||
}
|
||||
|
||||
private getAIConfig() {
|
||||
const apiKey =
|
||||
process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY;
|
||||
|
||||
return {
|
||||
provider:
|
||||
process.env.ANTHROPIC_API_KEY
|
||||
? ('anthropic' as const)
|
||||
: process.env.OPENAI_API_KEY
|
||||
? ('openai' as const)
|
||||
: ('none' as const),
|
||||
apiKey,
|
||||
model: process.env.ANTHROPIC_API_KEY ? 'claude-3-sonnet-20240229' : undefined,
|
||||
maxTokens: 4096,
|
||||
temperature: 0.7,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import chalk from 'chalk';
|
||||
import { AuditLogger, type AuditQuery, type AuditEventType } from '@skillkit/core';
|
||||
|
||||
export class AuditCommand extends Command {
|
||||
static override paths = [['audit']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'View and manage audit logs',
|
||||
details: `
|
||||
The audit command provides access to the audit log system.
|
||||
All skill operations, team activities, and plugin actions are logged.
|
||||
|
||||
Subcommands:
|
||||
log View recent audit log entries
|
||||
export Export audit logs to file
|
||||
stats Show audit statistics
|
||||
clear Clear old audit entries
|
||||
`,
|
||||
examples: [
|
||||
['View recent logs', '$0 audit log'],
|
||||
['View logs with filters', '$0 audit log --type skill.install --limit 20'],
|
||||
['Export logs to JSON', '$0 audit export --format json --output audit.json'],
|
||||
['Show statistics', '$0 audit stats'],
|
||||
['Clear logs older than 30 days', '$0 audit clear --days 30'],
|
||||
],
|
||||
});
|
||||
|
||||
subcommand = Option.String({ required: true });
|
||||
|
||||
// Query options
|
||||
type = Option.Array('--type,-t', {
|
||||
description: 'Filter by event type',
|
||||
});
|
||||
|
||||
user = Option.String('--user,-u', {
|
||||
description: 'Filter by user',
|
||||
});
|
||||
|
||||
resource = Option.String('--resource,-r', {
|
||||
description: 'Filter by resource',
|
||||
});
|
||||
|
||||
success = Option.Boolean('--success', {
|
||||
description: 'Show only successful operations',
|
||||
});
|
||||
|
||||
failed = Option.Boolean('--failed', {
|
||||
description: 'Show only failed operations',
|
||||
});
|
||||
|
||||
since = Option.String('--since', {
|
||||
description: 'Show events since date (ISO 8601)',
|
||||
});
|
||||
|
||||
until = Option.String('--until', {
|
||||
description: 'Show events until date (ISO 8601)',
|
||||
});
|
||||
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Maximum number of entries',
|
||||
});
|
||||
|
||||
// Export options
|
||||
format = Option.String('--format,-f', {
|
||||
description: 'Export format (json, csv, text)',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file path',
|
||||
});
|
||||
|
||||
// Clear options
|
||||
days = Option.String('--days', {
|
||||
description: 'Clear entries older than N days',
|
||||
});
|
||||
|
||||
// Common options
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
const logDir = path.join(targetPath, '.skillkit');
|
||||
const logger = new AuditLogger(logDir);
|
||||
|
||||
try {
|
||||
switch (this.subcommand) {
|
||||
case 'log':
|
||||
case 'list':
|
||||
return await this.handleLog(logger);
|
||||
case 'export':
|
||||
return await this.handleExport(logger);
|
||||
case 'stats':
|
||||
return await this.handleStats(logger);
|
||||
case 'clear':
|
||||
return await this.handleClear(logger);
|
||||
default:
|
||||
console.error(chalk.red(`Unknown subcommand: ${this.subcommand}\n`));
|
||||
console.log('Valid subcommands: log, export, stats, clear');
|
||||
return 1;
|
||||
}
|
||||
} finally {
|
||||
await logger.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
private async handleLog(logger: AuditLogger): Promise<number> {
|
||||
const query = this.buildQuery();
|
||||
const events = await logger.query(query);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(events, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (events.length === 0) {
|
||||
console.log(chalk.yellow('No audit events found'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`\nAudit Log (${events.length} entries):\n`));
|
||||
|
||||
for (const event of events) {
|
||||
const statusIcon = event.success ? chalk.green('✓') : chalk.red('✗');
|
||||
const timestamp = event.timestamp.toLocaleString();
|
||||
|
||||
console.log(
|
||||
`${statusIcon} ${chalk.dim(timestamp)} ${chalk.bold(event.type)}`
|
||||
);
|
||||
console.log(
|
||||
` ${event.action} on ${chalk.cyan(event.resource)}`
|
||||
);
|
||||
|
||||
if (event.user) {
|
||||
console.log(` ${chalk.dim('User:')} ${event.user}`);
|
||||
}
|
||||
|
||||
if (event.duration) {
|
||||
console.log(` ${chalk.dim('Duration:')} ${event.duration}ms`);
|
||||
}
|
||||
|
||||
if (event.error) {
|
||||
console.log(` ${chalk.red('Error:')} ${event.error}`);
|
||||
}
|
||||
|
||||
if (event.details && Object.keys(event.details).length > 0) {
|
||||
console.log(` ${chalk.dim('Details:')} ${JSON.stringify(event.details)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleExport(logger: AuditLogger): Promise<number> {
|
||||
const format = (this.format as 'json' | 'csv' | 'text') || 'json';
|
||||
const query = this.buildQuery();
|
||||
|
||||
const content = await logger.export({ format, query });
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await fs.writeFile(outputPath, content, 'utf-8');
|
||||
console.log(chalk.green(`✓ Exported audit log to: ${outputPath}`));
|
||||
} else {
|
||||
console.log(content);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleStats(logger: AuditLogger): Promise<number> {
|
||||
const stats = await logger.stats();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(stats, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan('\nAudit Statistics:\n'));
|
||||
console.log(`Total Events: ${chalk.bold(stats.totalEvents.toString())}`);
|
||||
console.log(
|
||||
`Success Rate: ${chalk.bold(`${(stats.successRate * 100).toFixed(1)}%`)}`
|
||||
);
|
||||
|
||||
if (Object.keys(stats.eventsByType).length > 0) {
|
||||
console.log(chalk.cyan('\nEvents by Type:'));
|
||||
const sorted = Object.entries(stats.eventsByType).sort(
|
||||
([, a], [, b]) => b - a
|
||||
);
|
||||
for (const [type, count] of sorted) {
|
||||
console.log(` ${type.padEnd(30)} ${count}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.topResources.length > 0) {
|
||||
console.log(chalk.cyan('\nTop Resources:'));
|
||||
for (const { resource, count } of stats.topResources) {
|
||||
console.log(` ${resource.padEnd(40)} ${count}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.recentErrors.length > 0) {
|
||||
console.log(chalk.cyan(`\nRecent Errors (${stats.recentErrors.length}):`));
|
||||
for (const error of stats.recentErrors.slice(0, 5)) {
|
||||
const timestamp = error.timestamp.toLocaleString();
|
||||
console.log(
|
||||
` ${chalk.red('✗')} ${chalk.dim(timestamp)} ${error.type}`
|
||||
);
|
||||
if (error.error) {
|
||||
console.log(` ${chalk.dim(error.error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleClear(logger: AuditLogger): Promise<number> {
|
||||
if (!this.days) {
|
||||
console.error(chalk.red('--days option required'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const daysAgo = parseInt(this.days, 10);
|
||||
const cutoffDate = new Date();
|
||||
cutoffDate.setDate(cutoffDate.getDate() - daysAgo);
|
||||
|
||||
const cleared = await logger.clear(cutoffDate);
|
||||
|
||||
console.log(
|
||||
chalk.green(
|
||||
`✓ Cleared ${cleared} audit entries older than ${daysAgo} days`
|
||||
)
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private buildQuery(): AuditQuery {
|
||||
const query: AuditQuery = {};
|
||||
|
||||
if (this.type && this.type.length > 0) {
|
||||
query.types = this.type as AuditEventType[];
|
||||
}
|
||||
|
||||
if (this.user) {
|
||||
query.user = this.user;
|
||||
}
|
||||
|
||||
if (this.resource) {
|
||||
query.resource = this.resource;
|
||||
}
|
||||
|
||||
if (this.success) {
|
||||
query.success = true;
|
||||
} else if (this.failed) {
|
||||
query.success = false;
|
||||
}
|
||||
|
||||
if (this.since) {
|
||||
query.startDate = new Date(this.since);
|
||||
}
|
||||
|
||||
if (this.until) {
|
||||
query.endDate = new Date(this.until);
|
||||
}
|
||||
|
||||
if (this.limit) {
|
||||
query.limit = parseInt(this.limit, 10);
|
||||
} else {
|
||||
query.limit = 50;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
type CICDProvider = 'github' | 'gitlab' | 'circleci';
|
||||
|
||||
const GITHUB_ACTIONS_WORKFLOW = `name: SkillKit CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
paths:
|
||||
- '.skillkit/**'
|
||||
- 'skills/**'
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
paths:
|
||||
- '.skillkit/**'
|
||||
- 'skills/**'
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate Skills
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Validate Skills
|
||||
run: skillkit validate --all
|
||||
|
||||
- name: List Skills
|
||||
run: skillkit list
|
||||
|
||||
test:
|
||||
name: Test Skills
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Run Skill Tests
|
||||
run: skillkit test --all
|
||||
continue-on-error: true
|
||||
|
||||
sync:
|
||||
name: Sync Skills
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Sync Skills to All Agents
|
||||
run: skillkit sync --yes
|
||||
`;
|
||||
|
||||
const GITLAB_CI = `stages:
|
||||
- validate
|
||||
- test
|
||||
- sync
|
||||
|
||||
variables:
|
||||
NODE_VERSION: "20"
|
||||
|
||||
.skillkit-base:
|
||||
image: node:\${NODE_VERSION}
|
||||
before_script:
|
||||
- npm install -g skillkit
|
||||
rules:
|
||||
- changes:
|
||||
- .skillkit/**/*
|
||||
- skills/**/*
|
||||
- .claude/skills/**/*
|
||||
- .cursor/skills/**/*
|
||||
|
||||
validate:
|
||||
extends: .skillkit-base
|
||||
stage: validate
|
||||
script:
|
||||
- skillkit validate --all
|
||||
- skillkit list
|
||||
|
||||
test:
|
||||
extends: .skillkit-base
|
||||
stage: test
|
||||
script:
|
||||
- skillkit test --all
|
||||
allow_failure: true
|
||||
needs:
|
||||
- validate
|
||||
|
||||
sync:
|
||||
extends: .skillkit-base
|
||||
stage: sync
|
||||
script:
|
||||
- skillkit sync --yes
|
||||
needs:
|
||||
- validate
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
changes:
|
||||
- .skillkit/**/*
|
||||
- skills/**/*
|
||||
- .claude/skills/**/*
|
||||
- .cursor/skills/**/*
|
||||
`;
|
||||
|
||||
const CIRCLECI_CONFIG = `version: 2.1
|
||||
|
||||
executors:
|
||||
node:
|
||||
docker:
|
||||
- image: cimg/node:20.0
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Validate Skills
|
||||
command: skillkit validate --all
|
||||
- run:
|
||||
name: List Skills
|
||||
command: skillkit list
|
||||
|
||||
test:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Run Skill Tests
|
||||
command: skillkit test --all || true
|
||||
|
||||
sync:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Sync Skills
|
||||
command: skillkit sync --yes
|
||||
|
||||
workflows:
|
||||
skillkit:
|
||||
jobs:
|
||||
- validate:
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- main
|
||||
- master
|
||||
- test:
|
||||
requires:
|
||||
- validate
|
||||
- sync:
|
||||
requires:
|
||||
- validate
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- main
|
||||
- master
|
||||
`;
|
||||
|
||||
/**
|
||||
* CICD command - initialize CI/CD workflows for skill validation and testing
|
||||
*/
|
||||
export class CICDCommand extends Command {
|
||||
static override paths = [['cicd', 'init']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Initialize CI/CD workflows for skill validation',
|
||||
details: `
|
||||
The cicd command sets up continuous integration workflows to automatically
|
||||
validate and test skills on every push or pull request.
|
||||
|
||||
Supported providers: github, gitlab, circleci
|
||||
`,
|
||||
examples: [
|
||||
['Initialize GitHub Actions workflow', '$0 cicd init'],
|
||||
['Initialize GitLab CI', '$0 cicd init --provider gitlab'],
|
||||
['Initialize CircleCI', '$0 cicd init --provider circleci'],
|
||||
['Initialize all providers', '$0 cicd init --all'],
|
||||
['Force overwrite existing files', '$0 cicd init --force'],
|
||||
],
|
||||
});
|
||||
|
||||
// Provider selection
|
||||
provider = Option.String('--provider,-p', 'github', {
|
||||
description: 'CI/CD provider (github, gitlab, circleci)',
|
||||
});
|
||||
|
||||
// Generate for all providers
|
||||
all = Option.Boolean('--all,-a', false, {
|
||||
description: 'Generate workflows for all supported providers',
|
||||
});
|
||||
|
||||
// Force overwrite
|
||||
force = Option.Boolean('--force,-f', false, {
|
||||
description: 'Overwrite existing workflow files',
|
||||
});
|
||||
|
||||
// Project path
|
||||
targetPath = Option.String('--path', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = this.targetPath || process.cwd();
|
||||
|
||||
const providers: CICDProvider[] = this.all
|
||||
? ['github', 'gitlab', 'circleci']
|
||||
: [this.provider as CICDProvider];
|
||||
|
||||
console.log(chalk.cyan('Initializing CI/CD workflows...'));
|
||||
console.log();
|
||||
|
||||
let success = true;
|
||||
let created = false;
|
||||
|
||||
for (const provider of providers) {
|
||||
const result = this.createWorkflow(projectPath, provider);
|
||||
if (result.skipped) {
|
||||
console.log(chalk.yellow(` ${result.message}`));
|
||||
continue;
|
||||
}
|
||||
if (!result.success) {
|
||||
success = false;
|
||||
console.error(chalk.red(` ${result.message}`));
|
||||
continue;
|
||||
}
|
||||
created = true;
|
||||
console.log(chalk.green(` ✓ ${result.message}`));
|
||||
}
|
||||
|
||||
if (success) {
|
||||
console.log();
|
||||
console.log(
|
||||
created
|
||||
? chalk.green('CI/CD workflows initialized successfully!')
|
||||
: chalk.yellow('CI/CD workflows already exist; nothing to do.')
|
||||
);
|
||||
console.log();
|
||||
if (created) {
|
||||
console.log(chalk.dim('The workflows will run on push/PR to validate your skills.'));
|
||||
console.log(chalk.dim('Commit the generated files to enable CI/CD.'));
|
||||
}
|
||||
}
|
||||
|
||||
return success ? 0 : 1;
|
||||
}
|
||||
|
||||
private createWorkflow(
|
||||
projectPath: string,
|
||||
provider: CICDProvider
|
||||
): { success: boolean; message: string; skipped?: boolean } {
|
||||
switch (provider) {
|
||||
case 'github':
|
||||
return this.createGitHubActions(projectPath);
|
||||
case 'gitlab':
|
||||
return this.createGitLabCI(projectPath);
|
||||
case 'circleci':
|
||||
return this.createCircleCI(projectPath);
|
||||
default:
|
||||
return { success: false, message: `Unknown provider: ${provider}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createGitHubActions(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const workflowDir = join(projectPath, '.github', 'workflows');
|
||||
const workflowFile = join(workflowDir, 'skillkit.yml');
|
||||
|
||||
if (existsSync(workflowFile) && !this.force) {
|
||||
return {
|
||||
success: true,
|
||||
message: `GitHub Actions workflow already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(workflowDir, { recursive: true });
|
||||
writeFileSync(workflowFile, GITHUB_ACTIONS_WORKFLOW);
|
||||
return { success: true, message: `Created ${workflowFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create GitHub workflow: ${error}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createGitLabCI(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const ciFile = join(projectPath, '.gitlab-ci.yml');
|
||||
|
||||
if (existsSync(ciFile) && !this.force) {
|
||||
// Check if skillkit jobs already exist for better messaging
|
||||
try {
|
||||
const content = readFileSync(ciFile, 'utf-8');
|
||||
if (content.includes('skillkit')) {
|
||||
return {
|
||||
success: true,
|
||||
message: `.gitlab-ci.yml already contains SkillKit config (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
message: `.gitlab-ci.yml already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to read .gitlab-ci.yml: ${error}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
writeFileSync(ciFile, GITLAB_CI);
|
||||
return { success: true, message: `Created ${ciFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create GitLab CI config: ${error}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createCircleCI(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const circleDir = join(projectPath, '.circleci');
|
||||
const configFile = join(circleDir, 'config.yml');
|
||||
|
||||
if (existsSync(configFile) && !this.force) {
|
||||
return {
|
||||
success: true,
|
||||
message: `CircleCI config already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(circleDir, { recursive: true });
|
||||
writeFileSync(configFile, CIRCLECI_CONFIG);
|
||||
return { success: true, message: `Created ${configFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create CircleCI config: ${error}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* Command CLI
|
||||
*
|
||||
* Manage slash commands and agent integration.
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
||||
import { resolve, join, dirname, extname } from 'node:path';
|
||||
import * as path from 'node:path';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import {
|
||||
createCommandRegistry,
|
||||
createCommandGenerator,
|
||||
getAgentFormat,
|
||||
supportsSlashCommands,
|
||||
} from '@skillkit/core';
|
||||
import type { SlashCommand, AgentType } from '@skillkit/core';
|
||||
|
||||
export class CommandCmd extends Command {
|
||||
static paths = [['command']];
|
||||
|
||||
static usage = Command.Usage({
|
||||
category: 'Commands',
|
||||
description: 'Manage slash commands and agent integration',
|
||||
details: `
|
||||
This command provides tools for working with slash commands.
|
||||
|
||||
Actions:
|
||||
- list: List registered commands
|
||||
- create: Create a new command from a skill
|
||||
- generate: Generate agent-specific command files
|
||||
- validate: Validate command definitions
|
||||
- export: Export commands to a bundle
|
||||
- import: Import commands from a bundle
|
||||
|
||||
Examples:
|
||||
$ skillkit command list
|
||||
$ skillkit command create my-skill --name my-command
|
||||
$ skillkit command generate --agent claude-code
|
||||
$ skillkit command validate ./commands.json
|
||||
`,
|
||||
examples: [
|
||||
['List all commands', '$0 command list'],
|
||||
['Create command from skill', '$0 command create tdd --name run-tdd'],
|
||||
['Generate for Claude Code', '$0 command generate --agent claude-code'],
|
||||
['Export commands', '$0 command export --output commands.json'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
|
||||
skill = Option.String('--skill,-s', {
|
||||
description: 'Skill to create command from',
|
||||
});
|
||||
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Command name',
|
||||
});
|
||||
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Command description',
|
||||
});
|
||||
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Target agent for generation',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file or directory',
|
||||
});
|
||||
|
||||
input = Option.String('--input,-i', {
|
||||
description: 'Input file',
|
||||
});
|
||||
|
||||
category = Option.String('--category,-c', {
|
||||
description: 'Command category',
|
||||
});
|
||||
|
||||
all = Option.Boolean('--all', false, {
|
||||
description: 'Include all commands (hidden and disabled)',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Show what would be generated without writing files',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listCommands();
|
||||
case 'create':
|
||||
return await this.createCommand();
|
||||
case 'generate':
|
||||
return await this.generateCommands();
|
||||
case 'validate':
|
||||
return await this.validateCommands();
|
||||
case 'export':
|
||||
return await this.exportCommands();
|
||||
case 'import':
|
||||
return await this.importCommands();
|
||||
case 'info':
|
||||
return await this.showInfo();
|
||||
default:
|
||||
this.context.stderr.write(
|
||||
`Unknown action: ${this.action}\n` +
|
||||
`Available actions: list, create, generate, validate, export, import, info\n`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.stderr.write(`Error: ${(error as Error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listCommands(): Promise<number> {
|
||||
const registry = createCommandRegistry();
|
||||
|
||||
// Load commands from local config
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const commands = registry.search({
|
||||
category: this.category,
|
||||
includeHidden: this.all,
|
||||
includeDisabled: this.all,
|
||||
});
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(commands, null, 2) + '\n');
|
||||
} else {
|
||||
if (commands.length === 0) {
|
||||
this.context.stdout.write('No commands registered.\n');
|
||||
this.context.stdout.write('Use "skillkit command create" to create commands from skills.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Registered Commands (${commands.length}):\n\n`);
|
||||
|
||||
// Group by category
|
||||
const categories = new Map<string, typeof commands>();
|
||||
for (const cmd of commands) {
|
||||
const cat = cmd.category || 'uncategorized';
|
||||
if (!categories.has(cat)) {
|
||||
categories.set(cat, []);
|
||||
}
|
||||
categories.get(cat)!.push(cmd);
|
||||
}
|
||||
|
||||
for (const [category, cmds] of categories) {
|
||||
this.context.stdout.write(` ${category.toUpperCase()}\n`);
|
||||
for (const cmd of cmds) {
|
||||
const status = cmd.enabled ? '' : ' (disabled)';
|
||||
const hidden = cmd.hidden ? ' (hidden)' : '';
|
||||
this.context.stdout.write(` /${cmd.name}${status}${hidden}\n`);
|
||||
this.context.stdout.write(` ${cmd.description}\n`);
|
||||
if (cmd.aliases && cmd.aliases.length > 0) {
|
||||
this.context.stdout.write(` Aliases: ${cmd.aliases.join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createCommand(): Promise<number> {
|
||||
if (!this.skill) {
|
||||
this.context.stderr.write('Error: --skill is required for create action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const commandName = this.name || this.skill.toLowerCase().replace(/[^a-z0-9]+/g, '-');
|
||||
|
||||
const command: SlashCommand = {
|
||||
name: commandName,
|
||||
description: this.description || `Execute ${this.skill} skill`,
|
||||
skill: this.skill,
|
||||
category: this.category,
|
||||
examples: [`/${commandName}`],
|
||||
};
|
||||
|
||||
// Save to commands config
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
let commands: SlashCommand[] = [];
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const content = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
commands = config.commands || [];
|
||||
}
|
||||
|
||||
// Check if command already exists
|
||||
const existing = commands.findIndex((c) => c.name === commandName);
|
||||
if (existing >= 0) {
|
||||
// Merge new properties with existing command to preserve metadata
|
||||
const previous = commands[existing];
|
||||
commands[existing] = {
|
||||
...previous,
|
||||
name: commandName,
|
||||
skill: this.skill,
|
||||
description: this.description ?? previous.description ?? command.description,
|
||||
category: this.category ?? previous.category,
|
||||
examples: command.examples?.length ? command.examples : previous.examples,
|
||||
// Preserve existing metadata if not provided
|
||||
aliases: previous.aliases,
|
||||
args: previous.args,
|
||||
tags: previous.tags,
|
||||
hidden: previous.hidden,
|
||||
metadata: previous.metadata,
|
||||
};
|
||||
this.context.stdout.write(`Updated command: /${commandName}\n`);
|
||||
} else {
|
||||
commands.push(command);
|
||||
this.context.stdout.write(`Created command: /${commandName}\n`);
|
||||
}
|
||||
|
||||
// Ensure directory exists
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
|
||||
// Save config
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: '1.0.0', commands }, null, 2)
|
||||
);
|
||||
|
||||
this.context.stdout.write(`Saved to: ${configPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async generateCommands(): Promise<number> {
|
||||
const agent = (this.agent || 'claude-code') as AgentType;
|
||||
|
||||
if (!supportsSlashCommands(agent)) {
|
||||
this.context.stdout.write(`Note: ${agent} has limited slash command support.\n`);
|
||||
}
|
||||
|
||||
const registry = createCommandRegistry();
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const commands = registry.getAll(this.all);
|
||||
|
||||
if (commands.length === 0) {
|
||||
this.context.stderr.write('No commands to generate. Create commands first.\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createCommandGenerator({
|
||||
includeHidden: this.all,
|
||||
includeDisabled: this.all,
|
||||
});
|
||||
|
||||
const format = getAgentFormat(agent);
|
||||
const outputTarget = this.output
|
||||
? resolve(this.output)
|
||||
: resolve(process.cwd(), format.directory);
|
||||
const outputDir = extname(outputTarget) ? dirname(outputTarget) : outputTarget;
|
||||
|
||||
const result = generator.generate(commands, agent);
|
||||
|
||||
if (typeof result === 'string') {
|
||||
// Single file output (e.g., Cursor rules)
|
||||
const extension = format.extension
|
||||
? format.extension.startsWith('.') ? format.extension : `.${format.extension}`
|
||||
: '.mdc';
|
||||
const filePath = extname(outputTarget)
|
||||
? outputTarget
|
||||
: join(outputTarget, `commands${extension}`);
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('Would write to: ' + filePath + '\n\n');
|
||||
this.context.stdout.write(result);
|
||||
} else {
|
||||
await mkdir(dirname(filePath), { recursive: true });
|
||||
await writeFile(filePath, result);
|
||||
this.context.stdout.write(`Generated: ${filePath}\n`);
|
||||
}
|
||||
} else {
|
||||
// Multiple file output
|
||||
if (extname(outputTarget)) {
|
||||
this.context.stderr.write(
|
||||
'Error: --output must be a directory for multi-file formats\n'
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('Would write to: ' + outputDir + '\n\n');
|
||||
for (const [filename, content] of result) {
|
||||
this.context.stdout.write(`--- ${filename} ---\n`);
|
||||
this.context.stdout.write(content.substring(0, 500));
|
||||
if (content.length > 500) {
|
||||
this.context.stdout.write('\n... (truncated)\n');
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
} else {
|
||||
await mkdir(outputDir, { recursive: true });
|
||||
for (const [filename, content] of result) {
|
||||
const filePath = join(outputDir, filename);
|
||||
await writeFile(filePath, content);
|
||||
this.context.stdout.write(`Generated: ${filePath}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate manifest
|
||||
const manifestPath = join(outputDir, 'manifest.json');
|
||||
const manifest = generator.generateManifest(commands);
|
||||
|
||||
if (!this.dryRun) {
|
||||
await writeFile(manifestPath, manifest);
|
||||
this.context.stdout.write(`Generated: ${manifestPath}\n`);
|
||||
}
|
||||
|
||||
this.context.stdout.write(`\nGenerated ${commands.length} commands for ${agent}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async validateCommands(): Promise<number> {
|
||||
const inputPath = this.input || resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
|
||||
if (!existsSync(inputPath)) {
|
||||
this.context.stderr.write(`File not found: ${inputPath}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const content = await readFile(inputPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
const commands: SlashCommand[] = config.commands || [];
|
||||
|
||||
const registry = createCommandRegistry({ validateOnRegister: false });
|
||||
let valid = 0;
|
||||
let invalid = 0;
|
||||
|
||||
this.context.stdout.write(`Validating ${commands.length} commands...\n\n`);
|
||||
|
||||
for (const command of commands) {
|
||||
const result = registry.validate(command);
|
||||
|
||||
if (result.valid) {
|
||||
valid++;
|
||||
if (!this.json) {
|
||||
this.context.stdout.write(`\u2713 /${command.name}\n`);
|
||||
}
|
||||
} else {
|
||||
invalid++;
|
||||
if (!this.json) {
|
||||
this.context.stdout.write(`\u2717 /${command.name}\n`);
|
||||
for (const error of result.errors) {
|
||||
this.context.stdout.write(` Error: ${error}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.json && result.warnings.length > 0) {
|
||||
for (const warning of result.warnings) {
|
||||
this.context.stdout.write(` Warning: ${warning}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(
|
||||
JSON.stringify({
|
||||
total: commands.length,
|
||||
valid,
|
||||
invalid,
|
||||
}) + '\n'
|
||||
);
|
||||
} else {
|
||||
this.context.stdout.write(`\nValidation complete: ${valid} valid, ${invalid} invalid\n`);
|
||||
}
|
||||
|
||||
return invalid > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
private async exportCommands(): Promise<number> {
|
||||
const registry = createCommandRegistry();
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const bundle = registry.export(this.all);
|
||||
|
||||
if (this.output) {
|
||||
let outputPath = resolve(this.output);
|
||||
|
||||
// Check if output is a directory or ends with path separator
|
||||
const stat = await fs.stat(outputPath).catch(() => null);
|
||||
if ((stat && stat.isDirectory()) || this.output.endsWith(path.sep)) {
|
||||
outputPath = path.join(outputPath, 'commands.json');
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
||||
await writeFile(outputPath, JSON.stringify(bundle, null, 2));
|
||||
this.context.stdout.write(`Exported ${bundle.commands.length} commands to: ${outputPath}\n`);
|
||||
} else {
|
||||
this.context.stdout.write(JSON.stringify(bundle, null, 2) + '\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importCommands(): Promise<number> {
|
||||
if (!this.input) {
|
||||
this.context.stderr.write('Error: --input is required for import action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const inputPath = resolve(this.input);
|
||||
if (!existsSync(inputPath)) {
|
||||
this.context.stderr.write(`File not found: ${inputPath}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const content = await readFile(inputPath, 'utf-8');
|
||||
const bundle = JSON.parse(content);
|
||||
|
||||
// Load existing commands
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
let existingCommands: SlashCommand[] = [];
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const existingContent = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(existingContent);
|
||||
existingCommands = config.commands || [];
|
||||
}
|
||||
|
||||
// Merge commands
|
||||
const commandMap = new Map<string, SlashCommand>();
|
||||
for (const cmd of existingCommands) {
|
||||
commandMap.set(cmd.name, cmd);
|
||||
}
|
||||
for (const cmd of bundle.commands) {
|
||||
commandMap.set(cmd.name, cmd);
|
||||
}
|
||||
|
||||
const mergedCommands = Array.from(commandMap.values());
|
||||
|
||||
// Save
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: '1.0.0', commands: mergedCommands }, null, 2)
|
||||
);
|
||||
|
||||
const imported = bundle.commands.length;
|
||||
this.context.stdout.write(`Imported ${imported} commands\n`);
|
||||
this.context.stdout.write(`Total commands: ${mergedCommands.length}\n`);
|
||||
this.context.stdout.write(`Saved to: ${configPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showInfo(): Promise<number> {
|
||||
const agent = (this.agent || 'claude-code') as AgentType;
|
||||
const format = getAgentFormat(agent);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(format, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Agent: ${agent}\n`);
|
||||
this.context.stdout.write(`Directory: ${format.directory}\n`);
|
||||
this.context.stdout.write(`Extension: ${format.extension}\n`);
|
||||
this.context.stdout.write(`Supports Slash Commands: ${format.supportsSlashCommands}\n`);
|
||||
this.context.stdout.write(`Supports Command Files: ${format.supportsCommandFiles}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async loadCommandsFromConfig(
|
||||
registry: ReturnType<typeof createCommandRegistry>
|
||||
): Promise<void> {
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const content = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
const commands: SlashCommand[] = config.commands || [];
|
||||
|
||||
for (const command of commands) {
|
||||
try {
|
||||
registry.register(command);
|
||||
} catch {
|
||||
// Skip invalid commands
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Hook Command
|
||||
*
|
||||
* Manage skill hooks for automatic triggering
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createHookManager, type HookEvent, type InjectionMode } from '@skillkit/core';
|
||||
|
||||
export class HookCommand extends Command {
|
||||
static override paths = [['hook']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage skill hooks for automatic triggering',
|
||||
examples: [
|
||||
['List all hooks', '$0 hook list'],
|
||||
['Add a session start hook', '$0 hook add session:start tdd-workflow'],
|
||||
['Add a file save hook with pattern', '$0 hook add file:save code-review --pattern "*.ts"'],
|
||||
['Remove a hook', '$0 hook remove <hook-id>'],
|
||||
['Enable a hook', '$0 hook enable <hook-id>'],
|
||||
['Disable a hook', '$0 hook disable <hook-id>'],
|
||||
['Generate agent hooks', '$0 hook generate --agent claude-code'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
target = Option.String({ required: false });
|
||||
skill = Option.String({ required: false });
|
||||
pattern = Option.String('--pattern,-p', { description: 'File pattern matcher' });
|
||||
agent = Option.String('--agent,-a', { description: 'Target agent for generation' });
|
||||
inject = Option.String('--inject,-i', { description: 'Injection mode: content, reference, prompt' });
|
||||
priority = Option.String('--priority', { description: 'Hook priority (higher = earlier)' });
|
||||
verbose = Option.Boolean('--verbose,-v', { description: 'Show detailed output' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listHooks(projectPath);
|
||||
case 'add':
|
||||
return await this.addHook(projectPath);
|
||||
case 'remove':
|
||||
return await this.removeHook(projectPath);
|
||||
case 'enable':
|
||||
return await this.enableHook(projectPath);
|
||||
case 'disable':
|
||||
return await this.disableHook(projectPath);
|
||||
case 'generate':
|
||||
return await this.generateHooks(projectPath);
|
||||
case 'info':
|
||||
return await this.showHookInfo(projectPath);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, add, remove, enable, disable, generate, info\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listHooks(projectPath: string): Promise<number> {
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
if (hooks.length === 0) {
|
||||
this.context.stdout.write('No hooks configured.\n');
|
||||
this.context.stdout.write(chalk.gray('Run `skillkit hook add <event> <skill>` to add a hook.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan('Configured Hooks:\n\n'));
|
||||
|
||||
// Group by event
|
||||
const eventGroups = new Map<string, typeof hooks>();
|
||||
for (const hook of hooks) {
|
||||
const group = eventGroups.get(hook.event) || [];
|
||||
group.push(hook);
|
||||
eventGroups.set(hook.event, group);
|
||||
}
|
||||
|
||||
for (const [event, eventHooks] of eventGroups) {
|
||||
this.context.stdout.write(chalk.yellow(`${event}:\n`));
|
||||
for (const hook of eventHooks) {
|
||||
const status = hook.enabled ? chalk.green('●') : chalk.gray('○');
|
||||
this.context.stdout.write(` ${status} ${chalk.white(hook.id.slice(0, 8))} → ${hook.skills.join(', ')}\n`);
|
||||
if (hook.matcher) {
|
||||
this.context.stdout.write(chalk.gray(` Pattern: ${hook.matcher}\n`));
|
||||
}
|
||||
if (this.verbose) {
|
||||
this.context.stdout.write(chalk.gray(` Inject: ${hook.inject}, Priority: ${hook.priority || 0}\n`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(`\nTotal: ${hooks.length} hooks\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async addHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Event type required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook add <event> <skill>\n');
|
||||
this.context.stderr.write('Events: session:start, session:end, file:save, file:open, task:start, commit:pre, commit:post, error:occur, test:fail, build:fail\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.skill) {
|
||||
this.context.stderr.write(chalk.red('Skill name required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook add <event> <skill>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const event = this.target as HookEvent;
|
||||
const validEvents: HookEvent[] = [
|
||||
'session:start', 'session:resume', 'session:end',
|
||||
'file:open', 'file:save', 'file:create', 'file:delete',
|
||||
'task:start', 'task:complete',
|
||||
'commit:pre', 'commit:post',
|
||||
'error:occur', 'test:fail', 'test:pass',
|
||||
'build:start', 'build:fail', 'build:success',
|
||||
];
|
||||
|
||||
if (!validEvents.includes(event)) {
|
||||
this.context.stderr.write(chalk.red(`Invalid event: ${this.target}\n`));
|
||||
this.context.stderr.write(`Valid events: ${validEvents.join(', ')}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
|
||||
const hook = manager.registerHook({
|
||||
event,
|
||||
skills: [this.skill],
|
||||
inject: (this.inject as InjectionMode) || 'reference',
|
||||
matcher: this.pattern,
|
||||
priority: this.priority ? parseInt(this.priority, 10) : 0,
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook added: ${hook.id.slice(0, 8)}\n`));
|
||||
this.context.stdout.write(` Event: ${event}\n`);
|
||||
this.context.stdout.write(` Skill: ${this.skill}\n`);
|
||||
if (this.pattern) {
|
||||
this.context.stdout.write(` Pattern: ${this.pattern}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async removeHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook remove <hook-id>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
// Find hook by ID prefix
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.unregisterHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook removed: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async enableHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.enableHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook enabled: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async disableHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.disableHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.yellow(`○ Hook disabled: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async generateHooks(projectPath: string): Promise<number> {
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
if (hooks.length === 0) {
|
||||
this.context.stdout.write('No hooks configured to generate.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const agent = this.agent || 'claude-code';
|
||||
const generated = manager.generateAgentHooks(agent as any);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Generated hooks for ${agent}:\n\n`));
|
||||
|
||||
if (typeof generated === 'string') {
|
||||
this.context.stdout.write(generated);
|
||||
} else {
|
||||
this.context.stdout.write(JSON.stringify(generated, null, 2));
|
||||
}
|
||||
|
||||
this.context.stdout.write('\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showHookInfo(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nHook: ${hook.id}\n`));
|
||||
this.context.stdout.write(`Event: ${hook.event}\n`);
|
||||
this.context.stdout.write(`Skills: ${hook.skills.join(', ')}\n`);
|
||||
this.context.stdout.write(`Enabled: ${hook.enabled ? 'Yes' : 'No'}\n`);
|
||||
this.context.stdout.write(`Inject: ${hook.inject}\n`);
|
||||
this.context.stdout.write(`Priority: ${hook.priority || 0}\n`);
|
||||
if (hook.matcher) {
|
||||
this.context.stdout.write(`Pattern: ${hook.matcher}\n`);
|
||||
}
|
||||
if (hook.condition) {
|
||||
this.context.stdout.write(`Condition: ${hook.condition}\n`);
|
||||
}
|
||||
if (hook.agentOverrides) {
|
||||
this.context.stdout.write(`Agent Overrides: ${Object.keys(hook.agentOverrides).join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -13,3 +13,21 @@ export { UICommand } from './ui.js';
|
||||
export { TranslateCommand } from './translate.js';
|
||||
export { ContextCommand } from './context.js';
|
||||
export { RecommendCommand } from './recommend.js';
|
||||
export { StatusCommand } from './status.js';
|
||||
export { PauseCommand } from './pause.js';
|
||||
export { ResumeCommand } from './resume.js';
|
||||
export { WorkflowRunCommand, WorkflowListCommand, WorkflowCreateCommand } from './workflow/index.js';
|
||||
export { RunCommand } from './run.js';
|
||||
export { TestCommand } from './test.js';
|
||||
export { MarketplaceCommand } from './marketplace.js';
|
||||
export { MemoryCommand } from './memory.js';
|
||||
export { SettingsCommand } from './settings.js';
|
||||
export { CICDCommand } from './cicd.js';
|
||||
export { TeamCommand } from './team.js';
|
||||
export { PluginCommand } from './plugin.js';
|
||||
export { MethodologyCommand } from './methodology.js';
|
||||
export { HookCommand } from './hook.js';
|
||||
export { PlanCommand } from './plan.js';
|
||||
export { CommandCmd } from './command.js';
|
||||
export { AICommand } from './ai.js';
|
||||
export { AuditCommand } from './audit.js';
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
createMarketplaceAggregator,
|
||||
type MarketplaceSearchOptions,
|
||||
} from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Marketplace command - browse and install skills from the marketplace
|
||||
*/
|
||||
export class MarketplaceCommand extends Command {
|
||||
static override paths = [['marketplace'], ['market'], ['mp']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Browse and install skills from the marketplace',
|
||||
details: `
|
||||
The marketplace command lets you discover and install skills
|
||||
from curated repositories.
|
||||
|
||||
Skills are aggregated from multiple sources including:
|
||||
- composioHQ/awesome-claude-code-skills
|
||||
- anthropics/courses
|
||||
- User-added custom sources
|
||||
`,
|
||||
examples: [
|
||||
['Browse marketplace', '$0 marketplace'],
|
||||
['Search for skills', '$0 marketplace search typescript'],
|
||||
['Refresh marketplace index', '$0 marketplace refresh'],
|
||||
['Show popular tags', '$0 marketplace tags'],
|
||||
['List sources', '$0 marketplace sources'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: false });
|
||||
query = Option.String({ required: false });
|
||||
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Limit results',
|
||||
});
|
||||
|
||||
tags = Option.String('--tags,-t', {
|
||||
description: 'Filter by tags (comma-separated)',
|
||||
});
|
||||
|
||||
source = Option.String('--source,-s', {
|
||||
description: 'Filter by source',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const marketplace = createMarketplaceAggregator();
|
||||
|
||||
switch (this.action) {
|
||||
case 'search':
|
||||
return this.searchSkills(marketplace);
|
||||
case 'refresh':
|
||||
return this.refreshIndex(marketplace);
|
||||
case 'tags':
|
||||
return this.showTags(marketplace);
|
||||
case 'sources':
|
||||
return this.showSources(marketplace);
|
||||
default:
|
||||
// Default: browse/search
|
||||
if (this.query || this.action) {
|
||||
return this.searchSkills(marketplace);
|
||||
}
|
||||
return this.browseMarketplace(marketplace);
|
||||
}
|
||||
}
|
||||
|
||||
private async browseMarketplace(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Loading marketplace...').start();
|
||||
|
||||
try {
|
||||
const index = await marketplace.getIndex();
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify({
|
||||
totalSkills: index.totalCount,
|
||||
sources: index.sources.length,
|
||||
updatedAt: index.updatedAt,
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Skill Marketplace\n'));
|
||||
console.log(`Total skills: ${chalk.cyan(index.totalCount)}`);
|
||||
console.log(`Sources: ${chalk.cyan(index.sources.length)}`);
|
||||
console.log(`Last updated: ${chalk.dim(new Date(index.updatedAt).toLocaleString())}\n`);
|
||||
|
||||
// Show sample skills
|
||||
console.log(chalk.bold('Featured Skills:\n'));
|
||||
const featured = index.skills.slice(0, 10);
|
||||
|
||||
for (const skill of featured) {
|
||||
console.log(` ${chalk.cyan(skill.name)}`);
|
||||
if (skill.description) {
|
||||
console.log(` ${chalk.dim(skill.description.slice(0, 60))}${skill.description.length > 60 ? '...' : ''}`);
|
||||
}
|
||||
console.log(` ${chalk.dim(`Source: ${skill.source.name}`)}`);
|
||||
console.log();
|
||||
}
|
||||
|
||||
console.log(chalk.dim('Use "skillkit marketplace search <query>" to search for skills.'));
|
||||
console.log(chalk.dim('Use "skillkit marketplace tags" to see popular tags.'));
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to load marketplace');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async searchSkills(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const query = this.query || this.action;
|
||||
|
||||
// Validate and parse limit
|
||||
let limit = 20;
|
||||
if (this.limit) {
|
||||
const parsed = parseInt(this.limit, 10);
|
||||
if (isNaN(parsed) || parsed <= 0) {
|
||||
console.error(chalk.red('Invalid --limit value. Must be a positive number.'));
|
||||
return 1;
|
||||
}
|
||||
limit = parsed;
|
||||
}
|
||||
|
||||
// Sanitize tags - filter out empty strings
|
||||
const tags = this.tags
|
||||
?.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
|
||||
const spinner = ora(`Searching for "${query}"...`).start();
|
||||
|
||||
try {
|
||||
const options: MarketplaceSearchOptions = {
|
||||
query: query || undefined,
|
||||
limit,
|
||||
tags: tags && tags.length > 0 ? tags : undefined,
|
||||
source: this.source,
|
||||
};
|
||||
|
||||
const result = await marketplace.search(options);
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(result));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (result.skills.length === 0) {
|
||||
console.log(chalk.yellow(`No skills found${query ? ` matching "${query}"` : ''}.`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold(`Found ${result.total} skill(s):\n`));
|
||||
|
||||
for (const skill of result.skills) {
|
||||
console.log(`${chalk.cyan(skill.name)} ${chalk.dim(`(${skill.source.name})`)}`);
|
||||
if (skill.description) {
|
||||
console.log(` ${skill.description}`);
|
||||
}
|
||||
if (skill.tags.length > 0) {
|
||||
console.log(` Tags: ${chalk.dim(skill.tags.join(', '))}`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (result.total > result.skills.length) {
|
||||
console.log(chalk.dim(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshIndex(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Refreshing marketplace index...').start();
|
||||
|
||||
try {
|
||||
const index = await marketplace.refresh();
|
||||
spinner.succeed(`Marketplace refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Refresh failed');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async showTags(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Loading tags...').start();
|
||||
|
||||
try {
|
||||
const tags = await marketplace.getPopularTags(30);
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(tags));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Popular Tags:\n'));
|
||||
|
||||
for (const { tag, count } of tags) {
|
||||
const bar = '█'.repeat(Math.min(count, 20));
|
||||
console.log(` ${tag.padEnd(15)} ${chalk.cyan(bar)} ${count}`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to load tags');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async showSources(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const sources = marketplace.getSources();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(sources));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Skill Sources:\n'));
|
||||
|
||||
for (const source of sources) {
|
||||
console.log(`${chalk.cyan(source.name)} ${source.official ? chalk.green('(official)') : ''}`);
|
||||
console.log(` ${chalk.dim(`${source.owner}/${source.repo}`)}`);
|
||||
if (source.description) {
|
||||
console.log(` ${source.description}`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,872 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import {
|
||||
ObservationStore,
|
||||
LearningStore,
|
||||
getMemoryPaths,
|
||||
initializeMemoryDirectory,
|
||||
getMemoryStatus,
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
type Learning,
|
||||
} from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Memory command - manage session memory across AI agents
|
||||
*/
|
||||
export class MemoryCommand extends Command {
|
||||
static override paths = [['memory'], ['mem']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage session memory across AI coding agents',
|
||||
details: `
|
||||
The memory command helps you view, search, and manage learnings
|
||||
captured from coding sessions across all AI agents.
|
||||
|
||||
Subcommands:
|
||||
- status: Show current memory status
|
||||
- search: Search memories by query
|
||||
- list: List all learnings
|
||||
- show: Show a specific learning
|
||||
- compress: Compress observations into learnings
|
||||
- export: Export a learning as a skill
|
||||
- import: Import memories from another project
|
||||
- clear: Clear session observations
|
||||
- add: Manually add a learning
|
||||
- rate: Rate a learning's effectiveness
|
||||
- config: Configure memory settings
|
||||
`,
|
||||
examples: [
|
||||
['Show memory status', '$0 memory status'],
|
||||
['Search memories', '$0 memory search "authentication"'],
|
||||
['Search global memories', '$0 memory search --global "react hooks"'],
|
||||
['List project learnings', '$0 memory list'],
|
||||
['List global learnings', '$0 memory list --global'],
|
||||
['Show a learning', '$0 memory show <id>'],
|
||||
['Compress observations', '$0 memory compress'],
|
||||
['Export as skill', '$0 memory export <id> --name my-skill'],
|
||||
['Clear session', '$0 memory clear'],
|
||||
['Add manual learning', '$0 memory add --title "..." --content "..."'],
|
||||
['Rate effectiveness', '$0 memory rate <id> 85'],
|
||||
],
|
||||
});
|
||||
|
||||
// Subcommand (status, search, list, show, compress, export, import, clear, add, rate, config)
|
||||
action = Option.String({ required: false });
|
||||
|
||||
// Second argument (query for search, id for show/export/rate)
|
||||
arg = Option.String({ required: false });
|
||||
|
||||
// Third argument (rating value for rate command)
|
||||
ratingArg = Option.String({ required: false });
|
||||
|
||||
// Global scope
|
||||
global = Option.Boolean('--global,-g', false, {
|
||||
description: 'Use global memories instead of project',
|
||||
});
|
||||
|
||||
// Tags filter
|
||||
tags = Option.String('--tags,-t', {
|
||||
description: 'Filter by tags (comma-separated)',
|
||||
});
|
||||
|
||||
// Limit results
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Maximum number of results',
|
||||
});
|
||||
|
||||
// Title for add
|
||||
title = Option.String('--title', {
|
||||
description: 'Title for new learning',
|
||||
});
|
||||
|
||||
// Content for add
|
||||
content = Option.String('--content,-c', {
|
||||
description: 'Content for new learning',
|
||||
});
|
||||
|
||||
// Name for export
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Name for exported skill',
|
||||
});
|
||||
|
||||
// Output file
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file path',
|
||||
});
|
||||
|
||||
// Input file
|
||||
input = Option.String('--input,-i', {
|
||||
description: 'Input file path',
|
||||
});
|
||||
|
||||
// Keep learnings when clearing
|
||||
keepLearnings = Option.Boolean('--keep-learnings', false, {
|
||||
description: 'Keep learnings when clearing',
|
||||
});
|
||||
|
||||
// Dry run
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Preview without making changes',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
// Verbose output
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Show detailed output',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const action = this.action || 'status';
|
||||
|
||||
switch (action) {
|
||||
case 'status':
|
||||
return this.showStatus();
|
||||
case 'search':
|
||||
return this.searchMemories();
|
||||
case 'list':
|
||||
return this.listLearnings();
|
||||
case 'show':
|
||||
return this.showLearning();
|
||||
case 'compress':
|
||||
return this.compressObservations();
|
||||
case 'export':
|
||||
return this.exportLearning();
|
||||
case 'import':
|
||||
return this.importMemories();
|
||||
case 'clear':
|
||||
return this.clearMemory();
|
||||
case 'add':
|
||||
return this.addLearning();
|
||||
case 'rate':
|
||||
return this.rateLearning();
|
||||
case 'config':
|
||||
return this.showConfig();
|
||||
default:
|
||||
console.error(chalk.red(`Unknown action: ${action}`));
|
||||
console.log(chalk.gray('Available actions: status, search, list, show, compress, export, import, clear, add, rate, config'));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show memory status
|
||||
*/
|
||||
private async showStatus(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
const status = getMemoryStatus(projectPath);
|
||||
const paths = getMemoryPaths(projectPath);
|
||||
|
||||
// Get counts from stores
|
||||
const observationStore = new ObservationStore(projectPath);
|
||||
const projectLearningStore = new LearningStore('project', projectPath);
|
||||
const globalLearningStore = new LearningStore('global');
|
||||
|
||||
const sessionObservations = status.hasObservations ? observationStore.count() : 0;
|
||||
const projectLearnings = status.hasLearnings ? projectLearningStore.count() : 0;
|
||||
const globalLearnings = status.hasGlobalLearnings ? globalLearningStore.count() : 0;
|
||||
const sessionId = status.hasObservations ? observationStore.getSessionId() : null;
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify({
|
||||
...status,
|
||||
sessionObservations,
|
||||
projectLearnings,
|
||||
globalLearnings,
|
||||
sessionId,
|
||||
paths,
|
||||
}, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('\nMemory Status\n'));
|
||||
|
||||
// Session observations
|
||||
console.log(chalk.cyan('Session:'));
|
||||
console.log(` Observations: ${sessionObservations}`);
|
||||
if (sessionId) {
|
||||
console.log(` Session ID: ${chalk.gray(sessionId.slice(0, 8))}`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
// Project learnings
|
||||
console.log(chalk.cyan('Project:'));
|
||||
console.log(` Learnings: ${projectLearnings}`);
|
||||
console.log(` Path: ${chalk.gray(status.projectMemoryExists ? paths.projectMemoryDir : 'Not initialized')}`);
|
||||
console.log();
|
||||
|
||||
// Global learnings
|
||||
console.log(chalk.cyan('Global:'));
|
||||
console.log(` Learnings: ${globalLearnings}`);
|
||||
console.log(` Path: ${chalk.gray(status.globalMemoryExists ? paths.globalMemoryDir : 'Not initialized')}`);
|
||||
console.log();
|
||||
|
||||
// Recommendations
|
||||
if (sessionObservations >= 50) {
|
||||
console.log(chalk.yellow('💡 You have many uncompressed observations. Consider running:'));
|
||||
console.log(chalk.gray(' skillkit memory compress'));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search memories
|
||||
*/
|
||||
private async searchMemories(): Promise<number> {
|
||||
const query = this.arg;
|
||||
if (!query) {
|
||||
console.error(chalk.red('Error: Search query is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory search "your query"'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const injector = createMemoryInjector(projectPath);
|
||||
|
||||
// Validate and parse limit
|
||||
let maxLearnings = 10;
|
||||
if (this.limit) {
|
||||
const parsed = parseInt(this.limit, 10);
|
||||
if (isNaN(parsed) || parsed <= 0) {
|
||||
console.log(chalk.red('Invalid --limit value. Must be a positive number.'));
|
||||
return 1;
|
||||
}
|
||||
maxLearnings = parsed;
|
||||
}
|
||||
|
||||
// Sanitize tags - filter out empty strings
|
||||
const tags = this.tags
|
||||
?.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
|
||||
const results = injector.search(query, {
|
||||
includeGlobal: this.global,
|
||||
tags: tags && tags.length > 0 ? tags : undefined,
|
||||
maxLearnings,
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.log(chalk.yellow(`No memories found for: "${query}"`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold(`\nFound ${results.length} memories:\n`));
|
||||
|
||||
for (const { learning, relevanceScore, matchedBy } of results) {
|
||||
console.log(`${chalk.cyan('●')} ${chalk.bold(learning.title)}`);
|
||||
console.log(` ID: ${chalk.gray(learning.id.slice(0, 8))}`);
|
||||
console.log(` Relevance: ${this.formatScore(relevanceScore)}%`);
|
||||
console.log(` Tags: ${learning.tags.join(', ')}`);
|
||||
console.log(` Scope: ${learning.scope}`);
|
||||
|
||||
if (this.verbose) {
|
||||
console.log(` Matched: ${this.formatMatchedBy(matchedBy)}`);
|
||||
console.log(` Created: ${new Date(learning.createdAt).toLocaleDateString()}`);
|
||||
console.log(` Uses: ${learning.useCount}`);
|
||||
}
|
||||
|
||||
// Show excerpt
|
||||
const excerpt = learning.content.slice(0, 100);
|
||||
console.log(` ${chalk.gray(excerpt)}${learning.content.length > 100 ? '...' : ''}`);
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all learnings
|
||||
*/
|
||||
private async listLearnings(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
const store = new LearningStore(
|
||||
this.global ? 'global' : 'project',
|
||||
this.global ? undefined : projectPath
|
||||
);
|
||||
|
||||
let learnings = store.getAll();
|
||||
|
||||
// Filter by tags if specified
|
||||
if (this.tags) {
|
||||
const tagList = this.tags.split(',').map((t) => t.trim().toLowerCase());
|
||||
learnings = learnings.filter((l) =>
|
||||
l.tags.some((t) => tagList.includes(t.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
// Limit results
|
||||
const limit = this.limit ? parseInt(this.limit, 10) : learnings.length;
|
||||
learnings = learnings.slice(0, limit);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(learnings, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const scope = this.global ? 'Global' : 'Project';
|
||||
console.log(chalk.bold(`\n${scope} Learnings (${learnings.length}):\n`));
|
||||
|
||||
if (learnings.length === 0) {
|
||||
console.log(chalk.gray('No learnings found.'));
|
||||
console.log(chalk.gray('\nCapture learnings by running skills or add manually:'));
|
||||
console.log(chalk.gray(' skillkit memory add --title "..." --content "..."'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const learning of learnings) {
|
||||
const effectiveness = learning.effectiveness !== undefined
|
||||
? ` [${this.formatScore(learning.effectiveness)}%]`
|
||||
: '';
|
||||
|
||||
console.log(`${chalk.cyan('●')} ${learning.title}${chalk.green(effectiveness)}`);
|
||||
console.log(` ${chalk.gray(learning.id.slice(0, 8))} | ${learning.tags.join(', ')} | ${learning.useCount} uses`);
|
||||
|
||||
if (this.verbose) {
|
||||
const excerpt = learning.content.slice(0, 80);
|
||||
console.log(` ${chalk.gray(excerpt)}${learning.content.length > 80 ? '...' : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a specific learning
|
||||
*/
|
||||
private async showLearning(): Promise<number> {
|
||||
const id = this.arg;
|
||||
if (!id) {
|
||||
console.error(chalk.red('Error: Learning ID is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory show <id>'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
// Try project store first
|
||||
let learning = new LearningStore('project', projectPath).getById(id);
|
||||
|
||||
// Try global store
|
||||
if (!learning) {
|
||||
learning = new LearningStore('global').getById(id);
|
||||
}
|
||||
|
||||
// Try matching by prefix
|
||||
if (!learning) {
|
||||
const projectLearnings = new LearningStore('project', projectPath).getAll();
|
||||
const globalLearnings = new LearningStore('global').getAll();
|
||||
const all = [...projectLearnings, ...globalLearnings];
|
||||
|
||||
learning = all.find((l) => l.id.startsWith(id));
|
||||
}
|
||||
|
||||
if (!learning) {
|
||||
console.error(chalk.red(`Learning not found: ${id}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(learning, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold(`\n${learning.title}\n`));
|
||||
console.log(chalk.gray(`ID: ${learning.id}`));
|
||||
console.log(chalk.gray(`Scope: ${learning.scope}`));
|
||||
console.log(chalk.gray(`Source: ${learning.source}`));
|
||||
console.log(chalk.gray(`Tags: ${learning.tags.join(', ')}`));
|
||||
|
||||
if (learning.frameworks?.length) {
|
||||
console.log(chalk.gray(`Frameworks: ${learning.frameworks.join(', ')}`));
|
||||
}
|
||||
|
||||
if (learning.patterns?.length) {
|
||||
console.log(chalk.gray(`Patterns: ${learning.patterns.join(', ')}`));
|
||||
}
|
||||
|
||||
console.log(chalk.gray(`Created: ${new Date(learning.createdAt).toLocaleString()}`));
|
||||
console.log(chalk.gray(`Updated: ${new Date(learning.updatedAt).toLocaleString()}`));
|
||||
console.log(chalk.gray(`Uses: ${learning.useCount}`));
|
||||
|
||||
if (learning.effectiveness !== undefined) {
|
||||
console.log(chalk.gray(`Effectiveness: ${this.formatScore(learning.effectiveness)}%`));
|
||||
}
|
||||
|
||||
console.log(chalk.bold('\nContent:\n'));
|
||||
console.log(learning.content);
|
||||
console.log();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress observations into learnings
|
||||
*/
|
||||
private async compressObservations(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
// Initialize memory directory if needed
|
||||
initializeMemoryDirectory(projectPath);
|
||||
|
||||
const observationStore = new ObservationStore(projectPath);
|
||||
const observations = observationStore.getAll();
|
||||
|
||||
if (observations.length === 0) {
|
||||
console.log(chalk.yellow('No observations to compress.'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Found ${observations.length} observations to compress...\n`));
|
||||
|
||||
const compressor = createMemoryCompressor(projectPath);
|
||||
const compressionOptions = {
|
||||
minObservations: 2,
|
||||
additionalTags: this.tags?.split(',').map((t) => t.trim()),
|
||||
};
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.gray('(Dry run - no changes will be made)\n'));
|
||||
|
||||
// For dry-run, only compress without storing
|
||||
const result = await compressor.compress(observations, compressionOptions);
|
||||
|
||||
console.log(chalk.green(`✓ Would compress ${result.stats.inputCount} observations into ${result.stats.outputCount} learnings\n`));
|
||||
|
||||
if (result.learnings.length > 0) {
|
||||
console.log(chalk.bold('Learnings that would be created:'));
|
||||
for (const learning of result.learnings) {
|
||||
console.log(` ${chalk.cyan('●')} ${learning.title}`);
|
||||
console.log(` Tags: ${learning.tags.join(', ')}`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Actual compression with storage
|
||||
const { learnings, result } = await compressor.compressAndStore(observations, compressionOptions);
|
||||
|
||||
console.log(chalk.green(`✓ Compressed ${result.stats.inputCount} observations into ${result.stats.outputCount} learnings\n`));
|
||||
|
||||
if (learnings.length > 0) {
|
||||
console.log(chalk.bold('New Learnings:'));
|
||||
for (const learning of learnings) {
|
||||
console.log(` ${chalk.cyan('●')} ${learning.title}`);
|
||||
console.log(` Tags: ${learning.tags.join(', ')}`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (result.processedObservationIds.length > 0) {
|
||||
// Remove processed observations
|
||||
const deleted = observationStore.deleteMany(result.processedObservationIds);
|
||||
console.log(chalk.gray(`Cleared ${deleted} processed observations.`));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a learning as a skill
|
||||
*/
|
||||
private async exportLearning(): Promise<number> {
|
||||
const id = this.arg;
|
||||
if (!id) {
|
||||
console.error(chalk.red('Error: Learning ID is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory export <id> --name my-skill'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
// Find the learning
|
||||
let learning = new LearningStore('project', projectPath).getById(id);
|
||||
if (!learning) {
|
||||
learning = new LearningStore('global').getById(id);
|
||||
}
|
||||
|
||||
// Try matching by prefix
|
||||
if (!learning) {
|
||||
const projectLearnings = new LearningStore('project', projectPath).getAll();
|
||||
const globalLearnings = new LearningStore('global').getAll();
|
||||
const all = [...projectLearnings, ...globalLearnings];
|
||||
learning = all.find((l) => l.id.startsWith(id));
|
||||
}
|
||||
|
||||
if (!learning) {
|
||||
console.error(chalk.red(`Learning not found: ${id}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Generate skill name
|
||||
const skillName = this.name || this.slugify(learning.title);
|
||||
|
||||
// Generate skill content
|
||||
const skillContent = this.generateSkillContent(learning, skillName);
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.gray('(Dry run preview)\n'));
|
||||
console.log(skillContent);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Determine output path
|
||||
const outputPath = this.output || `.skillkit/exports/${skillName}/SKILL.md`;
|
||||
const { dirname } = await import('node:path');
|
||||
const { existsSync, mkdirSync, writeFileSync } = await import('node:fs');
|
||||
|
||||
const outputDir = dirname(outputPath);
|
||||
if (!existsSync(outputDir)) {
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
writeFileSync(outputPath, skillContent, 'utf-8');
|
||||
|
||||
console.log(chalk.green(`✓ Exported learning as skill: ${skillName}`));
|
||||
console.log(chalk.gray(` Path: ${outputPath}`));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Import memories from another project
|
||||
*/
|
||||
private async importMemories(): Promise<number> {
|
||||
const inputPath = this.input || this.arg;
|
||||
if (!inputPath) {
|
||||
console.error(chalk.red('Error: Input path is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory import --input <path>'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { existsSync, readFileSync } = await import('node:fs');
|
||||
const { resolve } = await import('node:path');
|
||||
|
||||
const fullPath = resolve(inputPath);
|
||||
if (!existsSync(fullPath)) {
|
||||
console.error(chalk.red(`File not found: ${fullPath}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const store = new LearningStore(
|
||||
this.global ? 'global' : 'project',
|
||||
this.global ? undefined : projectPath
|
||||
);
|
||||
|
||||
try {
|
||||
const content = readFileSync(fullPath, 'utf-8');
|
||||
const { parse: parseYaml } = await import('yaml');
|
||||
const data = parseYaml(content) as { learnings?: Learning[] };
|
||||
|
||||
if (!data.learnings || !Array.isArray(data.learnings)) {
|
||||
console.error(chalk.red('Invalid memory file format'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
let imported = 0;
|
||||
for (const learning of data.learnings) {
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.gray(`Would import: ${learning.title}`));
|
||||
} else {
|
||||
store.add({
|
||||
source: 'imported',
|
||||
title: learning.title,
|
||||
content: learning.content,
|
||||
// Default to empty arrays if not present in imported YAML
|
||||
tags: Array.isArray(learning.tags) ? learning.tags : [],
|
||||
frameworks: Array.isArray(learning.frameworks) ? learning.frameworks : [],
|
||||
patterns: Array.isArray(learning.patterns) ? learning.patterns : [],
|
||||
});
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.gray(`\n(Dry run - ${data.learnings.length} learnings would be imported)`));
|
||||
} else {
|
||||
console.log(chalk.green(`✓ Imported ${imported} learnings`));
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Import failed: ${error}`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear session observations
|
||||
*/
|
||||
private async clearMemory(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
if (this.dryRun) {
|
||||
const observationStore = new ObservationStore(projectPath);
|
||||
const learningStore = new LearningStore('project', projectPath);
|
||||
|
||||
console.log(chalk.gray('(Dry run preview)\n'));
|
||||
console.log(`Would clear ${observationStore.count()} observations`);
|
||||
if (!this.keepLearnings) {
|
||||
console.log(`Would clear ${learningStore.count()} learnings`);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const observationStore = new ObservationStore(projectPath);
|
||||
observationStore.clear();
|
||||
console.log(chalk.green('✓ Cleared session observations'));
|
||||
|
||||
if (!this.keepLearnings) {
|
||||
const learningStore = new LearningStore('project', projectPath);
|
||||
learningStore.clear();
|
||||
console.log(chalk.green('✓ Cleared project learnings'));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a manual learning
|
||||
*/
|
||||
private async addLearning(): Promise<number> {
|
||||
if (!this.title) {
|
||||
console.error(chalk.red('Error: --title is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.content) {
|
||||
console.error(chalk.red('Error: --content is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const store = new LearningStore(
|
||||
this.global ? 'global' : 'project',
|
||||
this.global ? undefined : projectPath
|
||||
);
|
||||
|
||||
const tags = this.tags?.split(',').map((t) => t.trim()) || [];
|
||||
|
||||
const learning = store.add({
|
||||
source: 'manual',
|
||||
title: this.title,
|
||||
content: this.content,
|
||||
tags,
|
||||
});
|
||||
|
||||
console.log(chalk.green(`✓ Added learning: ${learning.title}`));
|
||||
console.log(chalk.gray(` ID: ${learning.id}`));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rate a learning's effectiveness
|
||||
*/
|
||||
private async rateLearning(): Promise<number> {
|
||||
const id = this.arg;
|
||||
if (!id) {
|
||||
console.error(chalk.red('Error: Learning ID is required'));
|
||||
console.log(chalk.gray('Usage: skillkit memory rate <id> <rating>'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const rating = parseInt(this.ratingArg || '0', 10);
|
||||
if (isNaN(rating) || rating < 0 || rating > 100) {
|
||||
console.error(chalk.red('Error: Rating must be 0-100'));
|
||||
console.log(chalk.gray('Usage: skillkit memory rate <id> <rating>'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
// Try project store first
|
||||
const projectStore = new LearningStore('project', projectPath);
|
||||
let learning = projectStore.getById(id);
|
||||
let store = projectStore;
|
||||
|
||||
if (!learning) {
|
||||
const globalStore = new LearningStore('global');
|
||||
learning = globalStore.getById(id);
|
||||
store = globalStore;
|
||||
}
|
||||
|
||||
// Try prefix match
|
||||
if (!learning) {
|
||||
const projectLearnings = projectStore.getAll();
|
||||
const globalStore = new LearningStore('global');
|
||||
const globalLearnings = globalStore.getAll();
|
||||
|
||||
learning = projectLearnings.find((l) => l.id.startsWith(id));
|
||||
if (learning) {
|
||||
store = projectStore;
|
||||
} else {
|
||||
learning = globalLearnings.find((l) => l.id.startsWith(id));
|
||||
if (learning) {
|
||||
store = globalStore;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!learning) {
|
||||
console.error(chalk.red(`Learning not found: ${id}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
store.setEffectiveness(learning.id, rating);
|
||||
console.log(chalk.green(`✓ Rated "${learning.title}" as ${rating}% effective`));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show memory configuration
|
||||
*/
|
||||
private async showConfig(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
const paths = getMemoryPaths(projectPath);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(paths, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('\nMemory Configuration\n'));
|
||||
|
||||
console.log(chalk.cyan('Paths:'));
|
||||
console.log(` Project observations: ${chalk.gray(paths.observationsFile)}`);
|
||||
console.log(` Project learnings: ${chalk.gray(paths.learningsFile)}`);
|
||||
console.log(` Project index: ${chalk.gray(paths.indexFile)}`);
|
||||
console.log(` Global learnings: ${chalk.gray(paths.globalLearningsFile)}`);
|
||||
console.log(` Global index: ${chalk.gray(paths.globalIndexFile)}`);
|
||||
console.log();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format relevance/effectiveness score with color
|
||||
*/
|
||||
private formatScore(score: number): string {
|
||||
if (score >= 80) return chalk.green(score.toString());
|
||||
if (score >= 50) return chalk.yellow(score.toString());
|
||||
return chalk.red(score.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Format matched by info
|
||||
*/
|
||||
private formatMatchedBy(matchedBy: {
|
||||
frameworks: string[];
|
||||
tags: string[];
|
||||
keywords: string[];
|
||||
patterns: string[];
|
||||
}): string {
|
||||
const parts: string[] = [];
|
||||
if (matchedBy.frameworks.length > 0) {
|
||||
parts.push(`frameworks: ${matchedBy.frameworks.join(', ')}`);
|
||||
}
|
||||
if (matchedBy.tags.length > 0) {
|
||||
parts.push(`tags: ${matchedBy.tags.join(', ')}`);
|
||||
}
|
||||
if (matchedBy.keywords.length > 0) {
|
||||
parts.push(`keywords: ${matchedBy.keywords.slice(0, 3).join(', ')}`);
|
||||
}
|
||||
if (matchedBy.patterns.length > 0) {
|
||||
parts.push(`patterns: ${matchedBy.patterns.join(', ')}`);
|
||||
}
|
||||
return parts.join(' | ') || 'general';
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert title to slug
|
||||
*/
|
||||
private slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape a YAML scalar value if it contains special characters
|
||||
*/
|
||||
private escapeYamlValue(value: string): string {
|
||||
// Check if value needs quoting (contains special YAML characters)
|
||||
if (/[:#\[\]{}|>&*!?,'"\\@`]/.test(value) || value.includes('\n')) {
|
||||
// Use double quotes and escape internal quotes/backslashes
|
||||
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate skill content from learning
|
||||
*/
|
||||
private generateSkillContent(learning: Learning, skillName: string): string {
|
||||
// Escape values that might contain special YAML characters
|
||||
const escapedName = this.escapeYamlValue(skillName);
|
||||
const escapedDesc = this.escapeYamlValue(learning.title);
|
||||
const escapedTags = learning.tags.map((t) => this.escapeYamlValue(t));
|
||||
|
||||
const lines: string[] = [
|
||||
'---',
|
||||
`name: ${escapedName}`,
|
||||
`description: ${escapedDesc}`,
|
||||
`version: 1.0.0`,
|
||||
`tags: [${escapedTags.join(', ')}]`,
|
||||
`source: skillkit-memory`,
|
||||
`sourceType: local`,
|
||||
];
|
||||
|
||||
if (learning.frameworks?.length) {
|
||||
const escapedFrameworks = learning.frameworks.map((f) => this.escapeYamlValue(f));
|
||||
lines.push(`compatibility:`);
|
||||
lines.push(` frameworks: [${escapedFrameworks.join(', ')}]`);
|
||||
}
|
||||
|
||||
lines.push('---', '', `# ${learning.title}`, '');
|
||||
|
||||
if (learning.patterns?.length) {
|
||||
lines.push(`## Patterns`, '');
|
||||
for (const pattern of learning.patterns) {
|
||||
lines.push(`- ${pattern}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`## Content`, '', learning.content, '');
|
||||
|
||||
lines.push(
|
||||
'---',
|
||||
'',
|
||||
'*Exported from SkillKit session memory*',
|
||||
`*Created: ${new Date(learning.createdAt).toLocaleDateString()}*`,
|
||||
`*Uses: ${learning.useCount}*`
|
||||
);
|
||||
|
||||
if (learning.effectiveness !== undefined) {
|
||||
lines.push(`*Effectiveness: ${learning.effectiveness}%*`);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* Methodology Command
|
||||
*
|
||||
* Manage methodology packs for AI coding agents
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createMethodologyManager, createMethodologyLoader } from '@skillkit/core';
|
||||
|
||||
export class MethodologyCommand extends Command {
|
||||
static override paths = [['methodology']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage methodology packs for AI coding agents',
|
||||
examples: [
|
||||
['List available packs', '$0 methodology list'],
|
||||
['Install all methodology packs', '$0 methodology install'],
|
||||
['Install specific pack', '$0 methodology install testing'],
|
||||
['Install specific skill', '$0 methodology install testing/red-green-refactor'],
|
||||
['Sync methodology skills to agents', '$0 methodology sync'],
|
||||
['Search methodology skills', '$0 methodology search tdd'],
|
||||
['Show pack details', '$0 methodology info testing'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
target = Option.String({ required: false });
|
||||
agent = Option.String('--agent,-a', { description: 'Target agent for sync' });
|
||||
dryRun = Option.Boolean('--dry-run', { description: 'Preview without making changes' });
|
||||
verbose = Option.Boolean('--verbose,-v', { description: 'Show detailed output' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listPacks();
|
||||
case 'install':
|
||||
return await this.installPacks(projectPath);
|
||||
case 'uninstall':
|
||||
return await this.uninstallPack(projectPath);
|
||||
case 'sync':
|
||||
return await this.syncSkills(projectPath);
|
||||
case 'search':
|
||||
return await this.searchSkills();
|
||||
case 'info':
|
||||
return await this.showPackInfo();
|
||||
case 'installed':
|
||||
return await this.listInstalled(projectPath);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, install, uninstall, sync, search, info, installed\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listPacks(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
const packs = await loader.loadAllPacks();
|
||||
|
||||
if (packs.length === 0) {
|
||||
this.context.stdout.write('No methodology packs available.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan('Available Methodology Packs:\n\n'));
|
||||
|
||||
for (const pack of packs) {
|
||||
this.context.stdout.write(chalk.green(` ${pack.name}`) + ` v${pack.version}\n`);
|
||||
this.context.stdout.write(chalk.gray(` ${pack.description}\n`));
|
||||
this.context.stdout.write(` Skills: ${pack.skills.join(', ')}\n`);
|
||||
this.context.stdout.write(` Tags: ${pack.tags.join(', ')}\n`);
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Total: ${packs.length} packs\n`);
|
||||
this.context.stdout.write(chalk.gray('\nRun `skillkit methodology install` to install all packs.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async installPacks(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
const loader = manager.getLoader();
|
||||
|
||||
if (this.target) {
|
||||
// Check if it's a skill ID (pack/skill) or pack name
|
||||
if (this.target.includes('/')) {
|
||||
// Install single skill
|
||||
this.context.stdout.write(`Installing skill: ${chalk.cyan(this.target)}...\n`);
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.yellow('[dry-run] Would install skill.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installSkill(this.target);
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green(`✓ Skill installed: ${this.target}\n`));
|
||||
} else {
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
// Install single pack
|
||||
this.context.stdout.write(`Installing pack: ${chalk.cyan(this.target)}...\n`);
|
||||
|
||||
if (this.dryRun) {
|
||||
const pack = await loader.loadPack(this.target);
|
||||
if (pack) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would install ${pack.skills.length} skills.\n`));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installPack(this.target);
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green(`✓ Pack "${this.target}" installed!\n`));
|
||||
this.context.stdout.write(` Installed: ${result.installed.length} skills\n`);
|
||||
if (result.skipped.length > 0) {
|
||||
this.context.stdout.write(` Skipped (already installed): ${result.skipped.length}\n`);
|
||||
}
|
||||
} else {
|
||||
this.context.stderr.write(chalk.red(`✗ Failed to install pack\n`));
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` - ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Install all packs
|
||||
this.context.stdout.write('Installing all methodology packs...\n\n');
|
||||
|
||||
if (this.dryRun) {
|
||||
const packs = await loader.loadAllPacks();
|
||||
let totalSkills = 0;
|
||||
for (const pack of packs) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would install ${pack.name} (${pack.skills.length} skills)\n`));
|
||||
totalSkills += pack.skills.length;
|
||||
}
|
||||
this.context.stdout.write(chalk.yellow(`\n[dry-run] Would install ${totalSkills} skills total.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installAllPacks();
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green('\n✓ All methodology packs installed!\n'));
|
||||
this.context.stdout.write(` Installed: ${result.installed.length} skills\n`);
|
||||
if (result.skipped.length > 0) {
|
||||
this.context.stdout.write(` Skipped (already installed): ${result.skipped.length}\n`);
|
||||
}
|
||||
} else {
|
||||
this.context.stdout.write(chalk.yellow('\n⚠ Some skills failed to install:\n'));
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` - ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
this.context.stdout.write(`\n Installed: ${result.installed.length} skills\n`);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray('\nRun `skillkit methodology sync` to sync to detected agents.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async uninstallPack(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Pack name required for uninstall.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology uninstall <pack-name>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would uninstall pack: ${this.target}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
await manager.uninstallPack(this.target);
|
||||
this.context.stdout.write(chalk.green(`✓ Pack "${this.target}" uninstalled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async syncSkills(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath, autoSync: false });
|
||||
|
||||
this.context.stdout.write('Syncing methodology skills to detected agents...\n\n');
|
||||
|
||||
if (this.dryRun) {
|
||||
const installed = manager.listInstalledSkills();
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would sync ${installed.length} skills.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.syncAll();
|
||||
|
||||
if (result.synced.length > 0) {
|
||||
this.context.stdout.write(chalk.green('✓ Sync complete!\n'));
|
||||
for (const sync of result.synced) {
|
||||
this.context.stdout.write(` ${sync.skill} → ${sync.agents.join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
if (result.failed.length > 0) {
|
||||
this.context.stdout.write(chalk.yellow('\n⚠ Some syncs failed:\n'));
|
||||
for (const fail of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` ${fail.skill} (${fail.agent}): ${fail.error}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
if (result.synced.length === 0 && result.failed.length === 0) {
|
||||
this.context.stdout.write('No installed skills to sync. Run `skillkit methodology install` first.\n');
|
||||
}
|
||||
|
||||
return result.success ? 0 : 1;
|
||||
}
|
||||
|
||||
private async searchSkills(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Search query required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology search <query>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await loader.searchSkills(this.target);
|
||||
|
||||
if (skills.length === 0) {
|
||||
this.context.stdout.write(`No skills found matching "${this.target}".\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Found ${skills.length} skills matching "${this.target}":\n\n`));
|
||||
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.green(` ${skill.id}`) + ` v${skill.version}\n`);
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description || 'No description'}\n`));
|
||||
if (skill.tags.length > 0) {
|
||||
this.context.stdout.write(` Tags: ${skill.tags.join(', ')}\n`);
|
||||
}
|
||||
if (this.verbose && skill.metadata.triggers) {
|
||||
this.context.stdout.write(` Triggers: ${skill.metadata.triggers.join(', ')}\n`);
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showPackInfo(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Pack name required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology info <pack-name>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const pack = await loader.loadPack(this.target);
|
||||
|
||||
if (!pack) {
|
||||
this.context.stderr.write(chalk.red(`Pack not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nPack: ${pack.name}\n`));
|
||||
this.context.stdout.write(`Version: ${pack.version}\n`);
|
||||
this.context.stdout.write(`Description: ${pack.description}\n`);
|
||||
this.context.stdout.write(`Tags: ${pack.tags.join(', ')}\n`);
|
||||
this.context.stdout.write(`Author: ${pack.author || 'Unknown'}\n`);
|
||||
this.context.stdout.write(`License: ${pack.license || 'Unknown'}\n`);
|
||||
this.context.stdout.write(`Compatibility: ${pack.compatibility.join(', ')}\n`);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nSkills (${pack.skills.length}):\n`));
|
||||
|
||||
const skills = await loader.loadPackSkills(this.target);
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.green(` ${skill.id.split('/')[1]}\n`));
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description || 'No description'}\n`));
|
||||
if (this.verbose) {
|
||||
if (skill.metadata.triggers) {
|
||||
this.context.stdout.write(` Triggers: ${skill.metadata.triggers.join(', ')}\n`);
|
||||
}
|
||||
if (skill.metadata.difficulty) {
|
||||
this.context.stdout.write(` Difficulty: ${skill.metadata.difficulty}\n`);
|
||||
}
|
||||
if (skill.metadata.estimatedTime) {
|
||||
this.context.stdout.write(` Est. Time: ${skill.metadata.estimatedTime} min\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray(`\nRun \`skillkit methodology install ${this.target}\` to install this pack.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listInstalled(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
|
||||
const installedPacks = manager.listInstalledPacks();
|
||||
const installedSkills = manager.listInstalledSkills();
|
||||
|
||||
if (installedPacks.length === 0 && installedSkills.length === 0) {
|
||||
this.context.stdout.write('No methodology skills installed.\n');
|
||||
this.context.stdout.write(chalk.gray('Run `skillkit methodology install` to install methodology packs.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (installedPacks.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('Installed Packs:\n'));
|
||||
for (const pack of installedPacks) {
|
||||
this.context.stdout.write(chalk.green(` ${pack.name}`) + ` v${pack.version}\n`);
|
||||
this.context.stdout.write(` Skills: ${pack.skills.length}\n`);
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
if (installedSkills.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('Installed Skills:\n'));
|
||||
for (const skill of installedSkills) {
|
||||
const syncStatus = skill.syncedAgents.length > 0
|
||||
? chalk.green(`synced to ${skill.syncedAgents.length} agents`)
|
||||
: chalk.yellow('not synced');
|
||||
this.context.stdout.write(` ${chalk.green(skill.id)} v${skill.version} [${syncStatus}]\n`);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray(`\nTotal: ${installedSkills.length} skills installed.\n`));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { SessionManager } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Pause command - pause current skill execution
|
||||
*/
|
||||
export class PauseCommand extends Command {
|
||||
static override paths = [['pause']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Pause current skill execution for later resumption',
|
||||
details: `
|
||||
The pause command saves the current execution state so you can
|
||||
continue later with "skillkit resume".
|
||||
|
||||
This is useful when you need to:
|
||||
- Take a break from a long skill execution
|
||||
- Handle an interruption
|
||||
- Review progress before continuing
|
||||
`,
|
||||
examples: [
|
||||
['Pause current execution', '$0 pause'],
|
||||
],
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
const manager = new SessionManager(targetPath);
|
||||
const state = manager.get();
|
||||
|
||||
if (!state) {
|
||||
console.log(chalk.yellow('No active session found.'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!state.currentExecution) {
|
||||
console.log(chalk.yellow('No skill execution in progress.'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (state.currentExecution.status === 'paused') {
|
||||
console.log(chalk.yellow('Execution is already paused.'));
|
||||
console.log(chalk.dim('Resume with: skillkit resume'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const success = manager.pause();
|
||||
|
||||
if (success) {
|
||||
const exec = state.currentExecution;
|
||||
console.log(chalk.green('✓ Execution paused'));
|
||||
console.log();
|
||||
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
|
||||
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks completed`);
|
||||
console.log();
|
||||
console.log(chalk.dim('Resume with: skillkit resume'));
|
||||
console.log(chalk.dim('View status: skillkit status'));
|
||||
return 0;
|
||||
} else {
|
||||
console.log(chalk.red('Failed to pause execution.'));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* Plan Command
|
||||
*
|
||||
* Manage structured development plans.
|
||||
* Parse, validate, execute, and generate plans.
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
createPlanParser,
|
||||
createPlanValidator,
|
||||
createPlanGenerator,
|
||||
createPlanExecutor,
|
||||
dryRunExecutor,
|
||||
shellExecutor,
|
||||
TASK_TEMPLATES,
|
||||
} from '@skillkit/core';
|
||||
|
||||
export class PlanCommand extends Command {
|
||||
static paths = [['plan']];
|
||||
|
||||
static usage = Command.Usage({
|
||||
category: 'Development',
|
||||
description: 'Manage structured development plans',
|
||||
details: `
|
||||
This command provides tools for working with structured development plans.
|
||||
|
||||
Actions:
|
||||
- parse: Parse a markdown plan to structured format
|
||||
- validate: Validate a plan for completeness
|
||||
- execute: Execute a plan (with optional dry-run)
|
||||
- generate: Generate a plan from task list
|
||||
- templates: List available task templates
|
||||
- create: Create a new empty plan
|
||||
|
||||
Examples:
|
||||
$ skillkit plan parse ./plan.md
|
||||
$ skillkit plan validate ./plan.md
|
||||
$ skillkit plan execute ./plan.md --dry-run
|
||||
$ skillkit plan generate "Add auth" --tasks "Setup,Login,Logout"
|
||||
$ skillkit plan templates
|
||||
`,
|
||||
examples: [
|
||||
['Parse a markdown plan', '$0 plan parse ./development-plan.md'],
|
||||
['Validate a plan', '$0 plan validate ./plan.md --strict'],
|
||||
['Dry-run execute a plan', '$0 plan execute ./plan.md --dry-run'],
|
||||
['List task templates', '$0 plan templates'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
|
||||
file = Option.String('--file,-f', {
|
||||
description: 'Plan file path',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file path',
|
||||
});
|
||||
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Plan name',
|
||||
});
|
||||
|
||||
goal = Option.String('--goal,-g', {
|
||||
description: 'Plan goal',
|
||||
});
|
||||
|
||||
tasks = Option.String('--tasks,-t', {
|
||||
description: 'Comma-separated list of task names',
|
||||
});
|
||||
|
||||
template = Option.String('--template', {
|
||||
description: 'Task template to use',
|
||||
});
|
||||
|
||||
techStack = Option.String('--tech-stack', {
|
||||
description: 'Comma-separated tech stack',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Dry run execution (no actual changes)',
|
||||
});
|
||||
|
||||
strict = Option.Boolean('--strict', false, {
|
||||
description: 'Strict validation (treat warnings as errors)',
|
||||
});
|
||||
|
||||
stopOnError = Option.Boolean('--stop-on-error', true, {
|
||||
description: 'Stop execution on first error',
|
||||
});
|
||||
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Verbose output',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'parse':
|
||||
return await this.parsePlan();
|
||||
case 'validate':
|
||||
return await this.validatePlan();
|
||||
case 'execute':
|
||||
return await this.executePlan();
|
||||
case 'generate':
|
||||
return await this.generatePlan();
|
||||
case 'templates':
|
||||
return await this.listTemplates();
|
||||
case 'create':
|
||||
return await this.createPlan();
|
||||
default:
|
||||
this.context.stderr.write(
|
||||
`Unknown action: ${this.action}\n` +
|
||||
`Available actions: parse, validate, execute, generate, templates, create\n`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.stderr.write(`Error: ${(error as Error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async parsePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for parse action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(plan, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Plan: ${plan.name}\n`);
|
||||
this.context.stdout.write(`Goal: ${plan.goal}\n`);
|
||||
this.context.stdout.write(`Status: ${plan.status}\n`);
|
||||
this.context.stdout.write(`Tasks: ${plan.tasks.length}\n\n`);
|
||||
|
||||
for (const task of plan.tasks) {
|
||||
this.context.stdout.write(` Task ${task.id}: ${task.name}\n`);
|
||||
this.context.stdout.write(` Steps: ${task.steps.length}\n`);
|
||||
if (task.estimatedMinutes) {
|
||||
this.context.stdout.write(` Estimated: ${task.estimatedMinutes} min\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await writeFile(outputPath, JSON.stringify(plan, null, 2));
|
||||
this.context.stdout.write(`\nSaved to: ${outputPath}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async validatePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for validate action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
const validator = createPlanValidator({ strict: this.strict });
|
||||
const result = validator.validate(plan);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Validation: ${result.valid ? 'PASSED' : 'FAILED'}\n\n`);
|
||||
|
||||
this.context.stdout.write(`Statistics:\n`);
|
||||
this.context.stdout.write(` Total tasks: ${result.stats.totalTasks}\n`);
|
||||
this.context.stdout.write(` Total steps: ${result.stats.totalSteps}\n`);
|
||||
this.context.stdout.write(` Estimated time: ${result.stats.estimatedMinutes} minutes\n`);
|
||||
this.context.stdout.write(` Tasks with tests: ${result.stats.tasksWithTests}\n`);
|
||||
this.context.stdout.write(` Avg steps/task: ${result.stats.avgStepsPerTask}\n\n`);
|
||||
|
||||
if (result.issues.length > 0) {
|
||||
this.context.stdout.write(`Issues:\n`);
|
||||
for (const issue of result.issues) {
|
||||
const icon =
|
||||
issue.type === 'error' ? '\u274C' : issue.type === 'warning' ? '\u26A0\uFE0F' : '\u2139\uFE0F';
|
||||
const location = issue.taskId ? `Task ${issue.taskId}` : 'Plan';
|
||||
this.context.stdout.write(` ${icon} [${location}] ${issue.message}\n`);
|
||||
if (issue.suggestion && this.verbose) {
|
||||
this.context.stdout.write(` Suggestion: ${issue.suggestion}\n`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.context.stdout.write('No issues found.\n');
|
||||
}
|
||||
}
|
||||
|
||||
return result.valid ? 0 : 1;
|
||||
}
|
||||
|
||||
private async executePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for execute action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
// Validate first
|
||||
const validator = createPlanValidator({ strict: this.strict });
|
||||
const validation = validator.validate(plan);
|
||||
|
||||
if (!validation.valid) {
|
||||
this.context.stderr.write('Plan validation failed. Fix errors before executing.\n');
|
||||
for (const issue of validation.issues.filter((i) => i.type === 'error')) {
|
||||
this.context.stderr.write(` \u274C ${issue.message}\n`);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create executor
|
||||
const executor = createPlanExecutor({
|
||||
stepExecutor: this.dryRun ? dryRunExecutor : shellExecutor,
|
||||
});
|
||||
|
||||
// Add progress listener
|
||||
executor.addListener((event, _plan, task) => {
|
||||
if (this.verbose) {
|
||||
if (event === 'plan:task_started' && task) {
|
||||
this.context.stdout.write(`Starting task ${task.id}: ${task.name}\n`);
|
||||
} else if (event === 'plan:task_completed' && task) {
|
||||
this.context.stdout.write(`Completed task ${task.id}: ${task.name}\n`);
|
||||
} else if (event === 'plan:task_failed' && task) {
|
||||
this.context.stderr.write(`Failed task ${task.id}: ${task.name}\n`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.context.stdout.write(`Executing plan: ${plan.name}\n`);
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('(Dry run mode - no actual changes)\n');
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
|
||||
const result = await executor.execute(plan, {
|
||||
dryRun: this.dryRun,
|
||||
stopOnError: this.stopOnError,
|
||||
onProgress: (taskId, step, status) => {
|
||||
if (this.verbose) {
|
||||
this.context.stdout.write(` Task ${taskId}, Step ${step}: ${status}\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
this.context.stdout.write('\n');
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(
|
||||
JSON.stringify(
|
||||
{
|
||||
...result,
|
||||
taskResults: Object.fromEntries(result.taskResults),
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + '\n'
|
||||
);
|
||||
} else {
|
||||
this.context.stdout.write(`Execution: ${result.success ? 'SUCCESS' : 'FAILED'}\n`);
|
||||
this.context.stdout.write(`Duration: ${result.durationMs}ms\n`);
|
||||
this.context.stdout.write(`Completed: ${result.completedTasks.length} tasks\n`);
|
||||
this.context.stdout.write(`Failed: ${result.failedTasks.length} tasks\n`);
|
||||
this.context.stdout.write(`Skipped: ${result.skippedTasks.length} tasks\n`);
|
||||
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
this.context.stdout.write('\nErrors:\n');
|
||||
for (const error of result.errors) {
|
||||
this.context.stderr.write(` - ${error}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.success ? 0 : 1;
|
||||
}
|
||||
|
||||
private async generatePlan(): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write('Error: --name is required for generate action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createPlanGenerator({
|
||||
includeTests: true,
|
||||
includeCommits: true,
|
||||
techStack: this.techStack?.split(',').map((s) => s.trim()).filter((s) => s !== ''),
|
||||
});
|
||||
|
||||
let plan;
|
||||
|
||||
if (this.tasks) {
|
||||
const taskNames = this.tasks.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
plan = generator.fromTaskList(this.name, this.goal || 'Complete the tasks', taskNames, {
|
||||
template: this.template as keyof typeof TASK_TEMPLATES,
|
||||
techStack: this.techStack?.split(',').map((s) => s.trim()).filter((s) => s !== ''),
|
||||
});
|
||||
} else {
|
||||
plan = generator.createPlan(this.name, this.goal || 'Complete the project');
|
||||
if (this.techStack) {
|
||||
plan.techStack = this.techStack.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
}
|
||||
}
|
||||
|
||||
const markdown = generator.toMarkdown(plan);
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await writeFile(outputPath, markdown);
|
||||
this.context.stdout.write(`Plan saved to: ${outputPath}\n`);
|
||||
} else if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(plan, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(markdown);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listTemplates(): Promise<number> {
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(TASK_TEMPLATES, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write('Available Task Templates:\n\n');
|
||||
|
||||
for (const [name, template] of Object.entries(TASK_TEMPLATES)) {
|
||||
this.context.stdout.write(` ${name}\n`);
|
||||
this.context.stdout.write(` ${template.description}\n`);
|
||||
this.context.stdout.write(` Steps: ${template.steps.length}\n`);
|
||||
this.context.stdout.write(` Estimated: ${template.estimatedMinutes} min\n\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createPlan(): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write('Error: --name is required for create action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createPlanGenerator({
|
||||
includeTests: true,
|
||||
includeCommits: true,
|
||||
});
|
||||
|
||||
const plan = generator.createPlan(this.name, this.goal || 'Complete the project');
|
||||
|
||||
if (this.techStack) {
|
||||
plan.techStack = this.techStack.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
}
|
||||
|
||||
const markdown = generator.toMarkdown(plan);
|
||||
|
||||
const outputPath = this.output || resolve(`${this.name.toLowerCase().replace(/\s+/g, '-')}-plan.md`);
|
||||
await writeFile(outputPath, markdown);
|
||||
this.context.stdout.write(`Plan created: ${outputPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Plugin Command
|
||||
*
|
||||
* Manage SkillKit plugins
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { join, isAbsolute, resolve, sep } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { existsSync, mkdirSync, copyFileSync, cpSync, rmSync } from 'node:fs';
|
||||
import chalk from 'chalk';
|
||||
import { createPluginManager, loadPlugin, loadPluginsFromDirectory } from '@skillkit/core';
|
||||
|
||||
export class PluginCommand extends Command {
|
||||
static override paths = [['plugin']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage SkillKit plugins',
|
||||
examples: [
|
||||
['List installed plugins', '$0 plugin list'],
|
||||
['Install a plugin', '$0 plugin install --source ./my-plugin'],
|
||||
['Install from npm', '$0 plugin install --source skillkit-plugin-gitlab'],
|
||||
['Uninstall a plugin', '$0 plugin uninstall --name my-plugin'],
|
||||
['Enable a plugin', '$0 plugin enable --name my-plugin'],
|
||||
['Disable a plugin', '$0 plugin disable --name my-plugin'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
source = Option.String('--source,-s', { description: 'Plugin source (file path or npm package)' });
|
||||
name = Option.String('--name,-n', { description: 'Plugin name' });
|
||||
global = Option.Boolean('--global,-g', { description: 'Use global plugin directory' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginManager = createPluginManager(projectPath);
|
||||
|
||||
// Auto-load plugins from directory
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
try {
|
||||
const plugins = await loadPluginsFromDirectory(pluginsDir);
|
||||
for (const plugin of plugins) {
|
||||
if (pluginManager.isPluginEnabled(plugin.metadata.name)) {
|
||||
await pluginManager.register(plugin);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Plugins directory may not exist
|
||||
}
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return this.listPlugins(pluginManager);
|
||||
case 'install':
|
||||
return await this.installPlugin(pluginManager);
|
||||
case 'uninstall':
|
||||
return await this.uninstallPlugin(pluginManager);
|
||||
case 'enable':
|
||||
return this.enablePlugin(pluginManager);
|
||||
case 'disable':
|
||||
return this.disablePlugin(pluginManager);
|
||||
case 'info':
|
||||
return this.pluginInfo(pluginManager);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, install, uninstall, enable, disable, info\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private listPlugins(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
const plugins = pluginManager.listPlugins();
|
||||
|
||||
if (plugins.length === 0) {
|
||||
this.context.stdout.write('No plugins installed.\n');
|
||||
this.context.stdout.write('Use `skillkit plugin install --source <source>` to install a plugin.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Installed Plugins (${plugins.length}):\n\n`));
|
||||
|
||||
for (const plugin of plugins) {
|
||||
const enabled = pluginManager.isPluginEnabled(plugin.name);
|
||||
const status = enabled
|
||||
? chalk.green('enabled')
|
||||
: chalk.gray('disabled');
|
||||
|
||||
this.context.stdout.write(chalk.cyan(` ${plugin.name}`) + ` v${plugin.version} [${status}]\n`);
|
||||
if (plugin.description) {
|
||||
this.context.stdout.write(chalk.gray(` ${plugin.description}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
// Show registered extensions
|
||||
const translators = pluginManager.getAllTranslators();
|
||||
const providers = pluginManager.getAllProviders();
|
||||
const commands = pluginManager.getAllCommands();
|
||||
|
||||
if (translators.size > 0 || providers.size > 0 || commands.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('\nRegistered Extensions:\n'));
|
||||
if (translators.size > 0) {
|
||||
this.context.stdout.write(` Translators: ${Array.from(translators.keys()).join(', ')}\n`);
|
||||
}
|
||||
if (providers.size > 0) {
|
||||
this.context.stdout.write(` Providers: ${Array.from(providers.keys()).join(', ')}\n`);
|
||||
}
|
||||
if (commands.length > 0) {
|
||||
this.context.stdout.write(` Commands: ${commands.map((c) => c.name).join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate plugin name to prevent path traversal attacks
|
||||
* Allows scoped npm names like @scope/name (mirrors loader.ts validation)
|
||||
*/
|
||||
private isValidPluginName(name: string): boolean {
|
||||
if (!name) return false;
|
||||
|
||||
// Reject backslashes, path traversal sequences, and names starting with '.'
|
||||
if (name.includes('\\') || name.includes('..') || name === '.' || name.startsWith('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Allow scoped npm names (@scope/name) or simple names (no slashes)
|
||||
// Use the same regex pattern as loader.ts validatePlugin
|
||||
return /^(?:@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(name);
|
||||
}
|
||||
|
||||
private async installPlugin(pluginManager: ReturnType<typeof createPluginManager>): Promise<number> {
|
||||
if (!this.source) {
|
||||
this.context.stderr.write(chalk.red('--source is required for install\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Expand tilde to home directory for all operations
|
||||
const resolvedSource = this.source.startsWith('~')
|
||||
? join(homedir(), this.source.slice(1))
|
||||
: this.source;
|
||||
|
||||
this.context.stdout.write(`Installing plugin from ${this.source}...\n`);
|
||||
|
||||
const plugin = await loadPlugin(resolvedSource);
|
||||
|
||||
// Validate plugin name from metadata
|
||||
const pluginName = plugin.metadata.name;
|
||||
if (!this.isValidPluginName(pluginName)) {
|
||||
this.context.stderr.write(chalk.red(`Invalid plugin name: ${pluginName}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Determine plugins directory
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
|
||||
// Persist plugin files to disk if source is a local file/directory
|
||||
const isLocalPath =
|
||||
this.source.startsWith('./') ||
|
||||
this.source.startsWith('../') ||
|
||||
this.source.startsWith('/') ||
|
||||
this.source.startsWith('~') ||
|
||||
this.source.includes('\\') ||
|
||||
isAbsolute(this.source);
|
||||
|
||||
if (isLocalPath && existsSync(resolvedSource)) {
|
||||
const targetDir = join(pluginsDir, pluginName);
|
||||
|
||||
// Verify targetDir is within pluginsDir (defense in depth)
|
||||
const resolvedTarget = resolve(targetDir);
|
||||
const resolvedPluginsDir = resolve(pluginsDir);
|
||||
if (!resolvedTarget.startsWith(resolvedPluginsDir + sep)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create plugins directory if needed
|
||||
if (!existsSync(pluginsDir)) {
|
||||
mkdirSync(pluginsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy plugin to plugins directory
|
||||
const { statSync } = await import('node:fs');
|
||||
const sourceStat = statSync(resolvedSource);
|
||||
|
||||
if (sourceStat.isDirectory()) {
|
||||
// Copy entire directory
|
||||
cpSync(resolvedSource, targetDir, { recursive: true });
|
||||
} else {
|
||||
// Copy single file with a loader-recognized name
|
||||
if (!existsSync(targetDir)) {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
// Preserve .mjs for ESM plugins, use .js for others
|
||||
let destFileName: string;
|
||||
if (resolvedSource.endsWith('.json')) {
|
||||
destFileName = 'plugin.json';
|
||||
} else if (resolvedSource.endsWith('.mjs')) {
|
||||
destFileName = 'index.mjs';
|
||||
} else {
|
||||
destFileName = 'index.js';
|
||||
}
|
||||
copyFileSync(resolvedSource, join(targetDir, destFileName));
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.dim(` Copied to ${targetDir}\n`));
|
||||
}
|
||||
|
||||
await pluginManager.register(plugin);
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${plugin.metadata.name}" installed!\n`));
|
||||
this.context.stdout.write(` Version: ${plugin.metadata.version}\n`);
|
||||
if (plugin.metadata.description) {
|
||||
this.context.stdout.write(` ${plugin.metadata.description}\n`);
|
||||
}
|
||||
|
||||
// Show what was registered
|
||||
if (plugin.translators?.length) {
|
||||
this.context.stdout.write(` Translators: ${plugin.translators.map((t) => t.agentType).join(', ')}\n`);
|
||||
}
|
||||
if (plugin.providers?.length) {
|
||||
this.context.stdout.write(` Providers: ${plugin.providers.map((p) => p.providerName).join(', ')}\n`);
|
||||
}
|
||||
if (plugin.commands?.length) {
|
||||
this.context.stdout.write(` Commands: ${plugin.commands.map((c) => c.name).join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async uninstallPlugin(pluginManager: ReturnType<typeof createPluginManager>): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for uninstall\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Validate plugin name to prevent path traversal attacks
|
||||
if (!this.isValidPluginName(this.name)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
await pluginManager.unregister(this.name);
|
||||
|
||||
// Remove plugin files from disk
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
const pluginDir = join(pluginsDir, this.name);
|
||||
|
||||
// Verify pluginDir is within pluginsDir (defense in depth)
|
||||
const resolvedPluginDir = resolve(pluginDir);
|
||||
const resolvedPluginsDir = resolve(pluginsDir);
|
||||
if (!resolvedPluginDir.startsWith(resolvedPluginsDir + sep)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (existsSync(pluginDir)) {
|
||||
rmSync(pluginDir, { recursive: true, force: true });
|
||||
this.context.stdout.write(chalk.dim(` Removed ${pluginDir}\n`));
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" uninstalled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private enablePlugin(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for enable\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
pluginManager.enablePlugin(this.name);
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" enabled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private disablePlugin(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for disable\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
pluginManager.disablePlugin(this.name);
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" disabled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private pluginInfo(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for info\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const plugin = pluginManager.getPlugin(this.name);
|
||||
if (!plugin) {
|
||||
this.context.stderr.write(chalk.red(`Plugin "${this.name}" not found.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { metadata } = plugin;
|
||||
const enabled = pluginManager.isPluginEnabled(this.name);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`${metadata.name}`) + ` v${metadata.version}\n`);
|
||||
this.context.stdout.write(`Status: ${enabled ? 'enabled' : 'disabled'}\n`);
|
||||
if (metadata.description) {
|
||||
this.context.stdout.write(`Description: ${metadata.description}\n`);
|
||||
}
|
||||
if (metadata.author) {
|
||||
this.context.stdout.write(`Author: ${metadata.author}\n`);
|
||||
}
|
||||
if (metadata.homepage) {
|
||||
this.context.stdout.write(`Homepage: ${metadata.homepage}\n`);
|
||||
}
|
||||
if (metadata.keywords?.length) {
|
||||
this.context.stdout.write(`Keywords: ${metadata.keywords.join(', ')}\n`);
|
||||
}
|
||||
if (metadata.dependencies?.length) {
|
||||
this.context.stdout.write(`Dependencies: ${metadata.dependencies.join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,20 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
type ProjectProfile,
|
||||
type SkillSummary,
|
||||
type SkillIndex,
|
||||
type ScoredSkill,
|
||||
ContextManager,
|
||||
RecommendationEngine,
|
||||
buildSkillIndex,
|
||||
saveIndex,
|
||||
loadIndex as loadIndexFromCache,
|
||||
isIndexStale,
|
||||
INDEX_PATH,
|
||||
KNOWN_SKILL_REPOS,
|
||||
} from '@skillkit/core';
|
||||
|
||||
const INDEX_PATH = join(process.env.HOME || '~', '.skillkit', 'index.json');
|
||||
const INDEX_CACHE_HOURS = 24;
|
||||
|
||||
/**
|
||||
* Recommend command - get smart skill recommendations based on project analysis
|
||||
*/
|
||||
@@ -41,7 +42,8 @@ export class RecommendCommand extends Command {
|
||||
['Filter by category', '$0 recommend --category security'],
|
||||
['Show detailed reasons', '$0 recommend --verbose'],
|
||||
['Update skill index', '$0 recommend --update'],
|
||||
['Search for skills by task', '$0 recommend --search "authentication"'],
|
||||
['Search for skills by task', '$0 recommend --task "authentication"'],
|
||||
['Search for skills (alias)', '$0 recommend --search "testing"'],
|
||||
],
|
||||
});
|
||||
|
||||
@@ -70,11 +72,16 @@ export class RecommendCommand extends Command {
|
||||
description: 'Update skill index from sources',
|
||||
});
|
||||
|
||||
// Search mode
|
||||
// Search mode (--search or --task)
|
||||
search = Option.String('--search,-s', {
|
||||
description: 'Search skills by task/query',
|
||||
});
|
||||
|
||||
// Task alias for search (GSD-style)
|
||||
task = Option.String('--task,-t', {
|
||||
description: 'Search skills by task (alias for --search)',
|
||||
});
|
||||
|
||||
// Include installed skills
|
||||
includeInstalled = Option.Boolean('--include-installed', false, {
|
||||
description: 'Include already installed skills',
|
||||
@@ -95,7 +102,7 @@ export class RecommendCommand extends Command {
|
||||
|
||||
// Handle index update
|
||||
if (this.update) {
|
||||
return this.updateIndex();
|
||||
return await this.updateIndex();
|
||||
}
|
||||
|
||||
// Load or create project profile
|
||||
@@ -121,9 +128,10 @@ export class RecommendCommand extends Command {
|
||||
const engine = new RecommendationEngine();
|
||||
engine.loadIndex(index);
|
||||
|
||||
// Handle search mode
|
||||
if (this.search) {
|
||||
return this.handleSearch(engine, this.search);
|
||||
// Handle search mode (--search or --task)
|
||||
const searchQuery = this.search || this.task;
|
||||
if (searchQuery) {
|
||||
return this.handleSearch(engine, searchQuery);
|
||||
}
|
||||
|
||||
// Get recommendations
|
||||
@@ -308,72 +316,65 @@ export class RecommendCommand extends Command {
|
||||
/**
|
||||
* Load skill index from cache
|
||||
*/
|
||||
private loadIndex(): SkillIndex | null {
|
||||
if (!existsSync(INDEX_PATH)) {
|
||||
private loadIndex() {
|
||||
const index = loadIndexFromCache();
|
||||
|
||||
if (!index) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(INDEX_PATH, 'utf-8');
|
||||
const index = JSON.parse(content) as SkillIndex;
|
||||
|
||||
// Check if index is stale
|
||||
// Check if index is stale
|
||||
if (isIndexStale(index) && !this.json) {
|
||||
const lastUpdated = new Date(index.lastUpdated);
|
||||
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
|
||||
|
||||
if (hoursSinceUpdate > INDEX_CACHE_HOURS && !this.json) {
|
||||
console.log(
|
||||
chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
|
||||
);
|
||||
}
|
||||
|
||||
return index;
|
||||
} catch {
|
||||
return null;
|
||||
console.log(
|
||||
chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
|
||||
);
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update skill index from sources
|
||||
*/
|
||||
private updateIndex(): number {
|
||||
console.log(chalk.cyan('Updating skill index...\n'));
|
||||
private async updateIndex(): Promise<number> {
|
||||
console.log(chalk.cyan('Updating skill index from GitHub repositories...\n'));
|
||||
console.log(chalk.dim(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
|
||||
|
||||
// For now, create a sample index with well-known skill repositories
|
||||
// In the future, this would fetch from a registry or known skill sources
|
||||
const sampleIndex: SkillIndex = {
|
||||
version: 1,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
skills: getSampleSkills(),
|
||||
sources: [
|
||||
{
|
||||
name: 'vercel-labs',
|
||||
url: 'https://github.com/vercel-labs/agent-skills',
|
||||
lastFetched: new Date().toISOString(),
|
||||
skillCount: 5,
|
||||
},
|
||||
{
|
||||
name: 'anthropics',
|
||||
url: 'https://github.com/anthropics/skills',
|
||||
lastFetched: new Date().toISOString(),
|
||||
skillCount: 3,
|
||||
},
|
||||
],
|
||||
};
|
||||
const spinner = ora('Fetching skills...').start();
|
||||
|
||||
// Save index
|
||||
const indexDir = join(process.env.HOME || '~', '.skillkit');
|
||||
if (!existsSync(indexDir)) {
|
||||
mkdirSync(indexDir, { recursive: true });
|
||||
try {
|
||||
const { index, errors } = await buildSkillIndex(KNOWN_SKILL_REPOS, (message) => {
|
||||
spinner.text = message;
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
// Report any errors
|
||||
if (errors.length > 0) {
|
||||
console.log(chalk.yellow('\nWarnings:'));
|
||||
for (const error of errors) {
|
||||
console.log(chalk.dim(` • ${error}`));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Save the index
|
||||
saveIndex(index);
|
||||
|
||||
console.log(chalk.green(`✓ Updated index with ${index.skills.length} skills`));
|
||||
if (index.sources.length > 0) {
|
||||
console.log(chalk.dim(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
|
||||
}
|
||||
console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`));
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to update index');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
writeFileSync(INDEX_PATH, JSON.stringify(sampleIndex, null, 2));
|
||||
|
||||
console.log(chalk.green(`✓ Updated index with ${sampleIndex.skills.length} skills`));
|
||||
console.log(chalk.dim(` Sources: ${sampleIndex.sources.map((s) => s.name).join(', ')}`));
|
||||
console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,161 +385,3 @@ function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen - 3) + '...';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample skills for the index (in a real implementation, this would fetch from sources)
|
||||
*/
|
||||
function getSampleSkills(): SkillSummary[] {
|
||||
return [
|
||||
{
|
||||
name: 'vercel-react-best-practices',
|
||||
description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization',
|
||||
source: 'vercel-labs/agent-skills',
|
||||
tags: ['react', 'frontend', 'typescript', 'nextjs', 'performance'],
|
||||
compatibility: {
|
||||
frameworks: ['react', 'nextjs'],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 1500,
|
||||
quality: 95,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'tailwind-v4-patterns',
|
||||
description: 'Tailwind CSS v4 utility patterns, responsive design, and component styling best practices',
|
||||
source: 'vercel-labs/agent-skills',
|
||||
tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['tailwindcss'],
|
||||
},
|
||||
popularity: 1200,
|
||||
quality: 92,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'nextjs-app-router',
|
||||
description: 'Next.js App Router patterns including layouts, server actions, and data fetching',
|
||||
source: 'vercel-labs/agent-skills',
|
||||
tags: ['nextjs', 'react', 'routing', 'server-actions', 'frontend'],
|
||||
compatibility: {
|
||||
frameworks: ['nextjs'],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 1100,
|
||||
quality: 94,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'typescript-strict-patterns',
|
||||
description: 'TypeScript strict mode patterns, type safety, and advanced type utilities',
|
||||
source: 'anthropics/skills',
|
||||
tags: ['typescript', 'types', 'safety', 'patterns'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 900,
|
||||
quality: 90,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'supabase-best-practices',
|
||||
description: 'Supabase integration patterns including auth, database queries, and real-time subscriptions',
|
||||
source: 'anthropics/skills',
|
||||
tags: ['supabase', 'database', 'auth', 'backend', 'postgresql'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['@supabase/supabase-js'],
|
||||
},
|
||||
popularity: 800,
|
||||
quality: 88,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'vitest-testing-patterns',
|
||||
description: 'Testing patterns with Vitest including mocking, assertions, and test organization',
|
||||
source: 'anthropics/skills',
|
||||
tags: ['vitest', 'testing', 'typescript', 'mocking', 'tdd'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['vitest'],
|
||||
},
|
||||
popularity: 700,
|
||||
quality: 86,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: false,
|
||||
},
|
||||
{
|
||||
name: 'prisma-database-patterns',
|
||||
description: 'Prisma ORM patterns for schema design, migrations, and efficient queries',
|
||||
source: 'vercel-labs/agent-skills',
|
||||
tags: ['prisma', 'database', 'orm', 'postgresql', 'backend'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript'],
|
||||
libraries: ['@prisma/client'],
|
||||
},
|
||||
popularity: 850,
|
||||
quality: 89,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'security-best-practices',
|
||||
description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers',
|
||||
source: 'trailofbits/skills',
|
||||
tags: ['security', 'xss', 'csrf', 'headers', 'owasp'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript', 'python'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 600,
|
||||
quality: 95,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'python-fastapi-patterns',
|
||||
description: 'FastAPI best practices for building high-performance Python APIs',
|
||||
source: 'python-skills/fastapi',
|
||||
tags: ['python', 'fastapi', 'backend', 'api', 'async'],
|
||||
compatibility: {
|
||||
frameworks: ['fastapi'],
|
||||
languages: ['python'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 550,
|
||||
quality: 85,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: false,
|
||||
},
|
||||
{
|
||||
name: 'zustand-state-management',
|
||||
description: 'Zustand state management patterns for React applications',
|
||||
source: 'react-skills/state',
|
||||
tags: ['zustand', 'react', 'state-management', 'frontend'],
|
||||
compatibility: {
|
||||
frameworks: ['react'],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['zustand'],
|
||||
},
|
||||
popularity: 650,
|
||||
quality: 84,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { SessionManager } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Resume command - resume paused skill execution
|
||||
*/
|
||||
export class ResumeCommand extends Command {
|
||||
static override paths = [['resume']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Resume a paused skill execution',
|
||||
details: `
|
||||
The resume command continues a previously paused skill execution
|
||||
from where it left off.
|
||||
|
||||
The execution state is preserved, including:
|
||||
- Completed tasks
|
||||
- User decisions
|
||||
- Modified files
|
||||
`,
|
||||
examples: [
|
||||
['Resume paused execution', '$0 resume'],
|
||||
],
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
const manager = new SessionManager(targetPath);
|
||||
const state = manager.get();
|
||||
|
||||
if (!state) {
|
||||
console.log(chalk.yellow('No active session found.'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!state.currentExecution) {
|
||||
console.log(chalk.yellow('No skill execution to resume.'));
|
||||
console.log(chalk.dim('Start a new execution with: skillkit run <skill>'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (state.currentExecution.status !== 'paused') {
|
||||
if (state.currentExecution.status === 'running') {
|
||||
console.log(chalk.yellow('Execution is already running.'));
|
||||
} else {
|
||||
console.log(chalk.yellow(`Execution is ${state.currentExecution.status}.`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
const success = manager.resume();
|
||||
|
||||
if (success) {
|
||||
const exec = state.currentExecution;
|
||||
console.log(chalk.green('✓ Execution resumed'));
|
||||
console.log();
|
||||
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
|
||||
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks`);
|
||||
console.log();
|
||||
|
||||
// Show next task
|
||||
const nextTask = exec.tasks.find((t) => t.status === 'pending' || t.status === 'in_progress');
|
||||
if (nextTask) {
|
||||
console.log(` Next task: ${chalk.cyan(nextTask.name)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('The execution will continue from where it left off.'));
|
||||
console.log(chalk.dim('View status: skillkit status'));
|
||||
return 0;
|
||||
} else {
|
||||
console.log(chalk.red('Failed to resume execution.'));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
createExecutionEngine,
|
||||
discoverSkills,
|
||||
extractFrontmatter,
|
||||
type ExecutableSkill,
|
||||
type ExecutableTask,
|
||||
type AgentType,
|
||||
} from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Run command - execute a skill
|
||||
*/
|
||||
export class RunCommand extends Command {
|
||||
static override paths = [['run']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Execute a skill with task-based orchestration',
|
||||
details: `
|
||||
The run command executes a skill, optionally breaking it down into
|
||||
tasks with verification checkpoints.
|
||||
|
||||
Skills can be:
|
||||
- Installed skills (by name)
|
||||
- Local skill files (by path)
|
||||
- Remote skills (owner/repo/path)
|
||||
`,
|
||||
examples: [
|
||||
['Run an installed skill', '$0 run typescript-strict-mode'],
|
||||
['Run a local skill file', '$0 run ./my-skill/SKILL.md'],
|
||||
['Dry run (show what would happen)', '$0 run typescript-strict-mode --dry-run'],
|
||||
['Run with verification', '$0 run setup-testing --verify'],
|
||||
],
|
||||
});
|
||||
|
||||
// Skill name or path
|
||||
skillRef = Option.String({ required: true });
|
||||
|
||||
// Target agent
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Target agent (claude-code, cursor, etc.)',
|
||||
});
|
||||
|
||||
// Dry run
|
||||
dryRun = Option.Boolean('--dry-run,-n', false, {
|
||||
description: 'Show what would be executed without running',
|
||||
});
|
||||
|
||||
// Enable verification
|
||||
verify = Option.Boolean('--verify', false, {
|
||||
description: 'Run verification checks after each task',
|
||||
});
|
||||
|
||||
// Auto-commit
|
||||
autoCommit = Option.Boolean('--auto-commit', false, {
|
||||
description: 'Create git commits after each task',
|
||||
});
|
||||
|
||||
// Continue on error
|
||||
continueOnError = Option.Boolean('--continue-on-error', false, {
|
||||
description: 'Continue execution even if a task fails',
|
||||
});
|
||||
|
||||
// Verbose output
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Show detailed execution progress',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
// Load the skill
|
||||
const skill = await this.loadSkill(targetPath);
|
||||
if (!skill) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Show skill info
|
||||
if (!this.json) {
|
||||
console.log(chalk.cyan(`Executing skill: ${chalk.bold(skill.name)}`));
|
||||
if (skill.description) {
|
||||
console.log(chalk.dim(skill.description));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Dry run mode
|
||||
if (this.dryRun) {
|
||||
this.showDryRun(skill);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const spinner = ora();
|
||||
let currentTask = '';
|
||||
|
||||
// Create execution engine
|
||||
const engine = createExecutionEngine(targetPath, {
|
||||
onProgress: (event) => {
|
||||
if (this.json) return;
|
||||
|
||||
switch (event.type) {
|
||||
case 'task_start':
|
||||
currentTask = event.taskName || '';
|
||||
spinner.start(`Task ${(event.taskIndex || 0) + 1}/${event.totalTasks}: ${currentTask}`);
|
||||
break;
|
||||
|
||||
case 'task_complete':
|
||||
const icon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
|
||||
spinner.stopAndPersist({
|
||||
symbol: icon,
|
||||
text: `Task ${(event.taskIndex || 0) + 1}/${event.totalTasks}: ${currentTask}`,
|
||||
});
|
||||
if (event.error && this.verbose) {
|
||||
console.log(chalk.red(` Error: ${event.error}`));
|
||||
}
|
||||
break;
|
||||
|
||||
case 'checkpoint':
|
||||
spinner.info(`Checkpoint: ${event.message}`);
|
||||
break;
|
||||
|
||||
case 'verification':
|
||||
if (this.verbose) {
|
||||
console.log(chalk.dim(` ${event.message}`));
|
||||
}
|
||||
break;
|
||||
|
||||
case 'complete':
|
||||
console.log();
|
||||
if (event.status === 'completed') {
|
||||
console.log(chalk.green('✓ Skill execution completed'));
|
||||
} else {
|
||||
console.log(chalk.red(`✗ Skill execution ${event.status}`));
|
||||
if (event.error) {
|
||||
console.log(chalk.red(` Error: ${event.error}`));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
},
|
||||
checkpointHandler: async (task, _context) => {
|
||||
// For CLI, we auto-continue but could add interactive prompts
|
||||
if (task.type === 'checkpoint:decision' && task.options) {
|
||||
// Use first option by default
|
||||
return {
|
||||
continue: true,
|
||||
selectedOption: task.options[0],
|
||||
};
|
||||
}
|
||||
return { continue: true };
|
||||
},
|
||||
});
|
||||
|
||||
// Execute the skill
|
||||
const result = await engine.execute(skill, {
|
||||
agent: this.agent as AgentType | undefined,
|
||||
autoCommit: this.autoCommit,
|
||||
verify: this.verify,
|
||||
continueOnError: this.continueOnError,
|
||||
});
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
// Show summary
|
||||
console.log();
|
||||
console.log(chalk.cyan('Summary:'));
|
||||
console.log(` Duration: ${chalk.dim(this.formatDuration(result.durationMs || 0))}`);
|
||||
console.log(` Tasks: ${chalk.dim(`${result.tasks.filter(t => t.status === 'completed').length}/${result.tasks.length} completed`)}`);
|
||||
|
||||
if (result.filesModified.length > 0) {
|
||||
console.log(` Files modified: ${chalk.dim(result.filesModified.length.toString())}`);
|
||||
}
|
||||
|
||||
if (result.commits.length > 0) {
|
||||
console.log(` Commits: ${chalk.dim(result.commits.join(', '))}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.status === 'completed' ? 0 : 1;
|
||||
}
|
||||
|
||||
private async loadSkill(projectPath: string): Promise<ExecutableSkill | null> {
|
||||
// Check if it's a file path (must be a file, not directory)
|
||||
if (this.skillRef.endsWith('.md') || (existsSync(this.skillRef) && statSync(this.skillRef).isFile())) {
|
||||
return this.loadSkillFromFile(resolve(this.skillRef));
|
||||
}
|
||||
|
||||
// Check installed skills
|
||||
const skill = this.findInstalledSkill(projectPath, this.skillRef);
|
||||
if (skill) {
|
||||
return skill;
|
||||
}
|
||||
|
||||
console.error(chalk.red(`Skill "${this.skillRef}" not found`));
|
||||
console.log(chalk.dim('Install skills with: skillkit install <source>'));
|
||||
return null;
|
||||
}
|
||||
|
||||
private loadSkillFromFile(filePath: string): ExecutableSkill | null {
|
||||
if (!existsSync(filePath)) {
|
||||
console.error(chalk.red(`File not found: ${filePath}`));
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
const frontmatter = extractFrontmatter(content);
|
||||
|
||||
// Parse tasks from frontmatter if present
|
||||
const tasks = this.parseTasksFromFrontmatter(frontmatter);
|
||||
|
||||
return {
|
||||
name: (frontmatter?.name as string) || this.skillRef,
|
||||
description: frontmatter?.description as string,
|
||||
version: frontmatter?.version as string,
|
||||
source: filePath,
|
||||
content,
|
||||
tasks,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Failed to load skill: ${error}`));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private findInstalledSkill(projectPath: string, skillName: string): ExecutableSkill | null {
|
||||
// Search in common skill directories
|
||||
const skillDirs = [
|
||||
join(projectPath, '.claude', 'skills'),
|
||||
join(projectPath, '.cursor', 'skills'),
|
||||
join(projectPath, 'skills'),
|
||||
join(projectPath, '.skillkit', 'skills'),
|
||||
];
|
||||
|
||||
for (const dir of skillDirs) {
|
||||
if (!existsSync(dir)) continue;
|
||||
|
||||
const skills = discoverSkills(dir);
|
||||
const skill = skills.find((s) => s.name === skillName);
|
||||
|
||||
if (skill) {
|
||||
const skillMdPath = join(skill.path, 'SKILL.md');
|
||||
if (existsSync(skillMdPath)) {
|
||||
return this.loadSkillFromFile(skillMdPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseTasksFromFrontmatter(frontmatter: Record<string, unknown> | null): ExecutableTask[] | undefined {
|
||||
if (!frontmatter?.tasks || !Array.isArray(frontmatter.tasks)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return frontmatter.tasks.map((task: Record<string, unknown>, index: number) => ({
|
||||
id: (task.id as string) || `task-${index}`,
|
||||
name: (task.name as string) || `Task ${index + 1}`,
|
||||
type: (task.type as ExecutableTask['type']) || 'auto',
|
||||
action: (task.action as string) || '',
|
||||
files: task.files as string[] | undefined,
|
||||
options: task.options as string[] | undefined,
|
||||
verify: task.verify as ExecutableTask['verify'],
|
||||
}));
|
||||
}
|
||||
|
||||
private showDryRun(skill: ExecutableSkill): void {
|
||||
console.log(chalk.cyan('Dry Run - Execution Plan'));
|
||||
console.log();
|
||||
console.log(`Skill: ${chalk.bold(skill.name)}`);
|
||||
if (skill.description) {
|
||||
console.log(`Description: ${chalk.dim(skill.description)}`);
|
||||
}
|
||||
console.log(`Source: ${chalk.dim(skill.source)}`);
|
||||
console.log();
|
||||
|
||||
if (skill.tasks && skill.tasks.length > 0) {
|
||||
console.log(chalk.cyan('Tasks:'));
|
||||
for (let i = 0; i < skill.tasks.length; i++) {
|
||||
const task = skill.tasks[i];
|
||||
const typeLabel = this.getTaskTypeLabel(task.type);
|
||||
console.log(` ${i + 1}. ${task.name} ${typeLabel}`);
|
||||
if (task.action) {
|
||||
console.log(` ${chalk.dim(task.action)}`);
|
||||
}
|
||||
if (task.files && task.files.length > 0) {
|
||||
console.log(` Files: ${chalk.dim(task.files.join(', '))}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log(chalk.dim('No structured tasks defined. Skill will be executed as a single unit.'));
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('This is a dry run. Remove --dry-run to execute.'));
|
||||
}
|
||||
|
||||
private getTaskTypeLabel(type: string): string {
|
||||
switch (type) {
|
||||
case 'auto':
|
||||
return chalk.green('[auto]');
|
||||
case 'checkpoint:human-verify':
|
||||
return chalk.yellow('[verify]');
|
||||
case 'checkpoint:decision':
|
||||
return chalk.blue('[decision]');
|
||||
case 'checkpoint:human-action':
|
||||
return chalk.magenta('[manual]');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private formatDuration(ms: number): string {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const seconds = Math.floor((ms % 60000) / 1000);
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { loadConfig, saveConfig, type SkillkitConfig, type AgentType } from '@skillkit/core';
|
||||
|
||||
const VALID_AGENTS: AgentType[] = [
|
||||
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
|
||||
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
|
||||
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
|
||||
];
|
||||
|
||||
/**
|
||||
* Settings command - view and modify SkillKit configuration
|
||||
*/
|
||||
export class SettingsCommand extends Command {
|
||||
static override paths = [['settings'], ['config']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'View and modify SkillKit settings',
|
||||
details: `
|
||||
View or modify SkillKit configuration. Settings are stored in skillkit.yaml.
|
||||
|
||||
Without arguments, shows all current settings.
|
||||
With --set, modifies a specific setting.
|
||||
`,
|
||||
examples: [
|
||||
['Show all settings', '$0 settings'],
|
||||
['Set default agent', '$0 settings --set agent=claude-code'],
|
||||
['Enable auto-sync', '$0 settings --set autoSync=true'],
|
||||
['Set cache directory', '$0 settings --set cacheDir=~/.cache/skillkit'],
|
||||
['Show settings as JSON', '$0 settings --json'],
|
||||
['Save to global config', '$0 settings --set agent=cursor --global'],
|
||||
],
|
||||
});
|
||||
|
||||
// Set a setting
|
||||
set = Option.String('--set,-s', {
|
||||
description: 'Set a config value (key=value)',
|
||||
});
|
||||
|
||||
// Get a specific setting
|
||||
get = Option.String('--get,-g', {
|
||||
description: 'Get a specific setting value',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
// Global config
|
||||
global = Option.Boolean('--global', false, {
|
||||
description: 'Use global config (~/.config/skillkit/)',
|
||||
});
|
||||
|
||||
// Reset to defaults
|
||||
reset = Option.Boolean('--reset', false, {
|
||||
description: 'Reset all settings to defaults',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
// Load current config (respect --global flag)
|
||||
const config = loadConfig(this.global);
|
||||
|
||||
// Reset to defaults
|
||||
if (this.reset) {
|
||||
const defaultConfig: SkillkitConfig = {
|
||||
version: 1,
|
||||
agent: 'universal',
|
||||
autoSync: true,
|
||||
};
|
||||
saveConfig(defaultConfig, this.global);
|
||||
console.log(chalk.green('Settings reset to defaults'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Get a specific setting
|
||||
if (this.get) {
|
||||
// Check if the key is a known setting (not just if value is undefined)
|
||||
const knownKeys = [
|
||||
'agent', 'autoSync', 'cacheDir', 'skillsDir',
|
||||
'enabledSkills', 'disabledSkills', 'marketplaceSources', 'defaultTimeout'
|
||||
];
|
||||
if (!knownKeys.includes(this.get)) {
|
||||
console.error(chalk.red(`Unknown setting: ${this.get}`));
|
||||
return 1;
|
||||
}
|
||||
const value = this.getConfigValue(config, this.get);
|
||||
if (this.json) {
|
||||
// Use null instead of undefined so the key is preserved in JSON output
|
||||
console.log(JSON.stringify({ [this.get]: value ?? null }));
|
||||
} else {
|
||||
console.log(value ?? '(not set)');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Set a setting
|
||||
if (this.set) {
|
||||
const [key, ...valueParts] = this.set.split('=');
|
||||
const value = valueParts.join('=');
|
||||
|
||||
if (!key || !this.set.includes('=')) {
|
||||
console.error(chalk.red('Invalid format. Use: --set key=value'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const result = this.setConfigValue(config, key, value);
|
||||
if (!result.success) {
|
||||
console.error(chalk.red(result.error));
|
||||
return 1;
|
||||
}
|
||||
|
||||
saveConfig(config, this.global);
|
||||
console.log(chalk.green(`${key} = ${value}`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Show all settings
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(config, null, 2));
|
||||
} else {
|
||||
console.log(chalk.cyan('SkillKit Settings'));
|
||||
console.log(chalk.dim('─'.repeat(40)));
|
||||
console.log();
|
||||
|
||||
const settings = [
|
||||
{ key: 'agent', label: 'Default Agent', value: config.agent },
|
||||
{ key: 'autoSync', label: 'Auto Sync', value: config.autoSync ? 'enabled' : 'disabled' },
|
||||
{ key: 'cacheDir', label: 'Cache Dir', value: config.cacheDir || '~/.skillkit/cache' },
|
||||
{ key: 'skillsDir', label: 'Skills Dir', value: config.skillsDir || '(default)' },
|
||||
{ key: 'defaultTimeout', label: 'Timeout', value: config.defaultTimeout ? `${config.defaultTimeout}ms` : '(default)' },
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
console.log(` ${chalk.white(setting.label.padEnd(14))} ${chalk.dim(setting.value)}`);
|
||||
}
|
||||
|
||||
if (config.enabledSkills?.length) {
|
||||
console.log();
|
||||
console.log(` ${chalk.white('Enabled Skills'.padEnd(14))} ${chalk.dim(config.enabledSkills.join(', '))}`);
|
||||
}
|
||||
|
||||
if (config.disabledSkills?.length) {
|
||||
console.log(` ${chalk.white('Disabled Skills'.padEnd(14))} ${chalk.dim(config.disabledSkills.join(', '))}`);
|
||||
}
|
||||
|
||||
if (config.marketplaceSources?.length) {
|
||||
console.log(` ${chalk.white('Marketplaces'.padEnd(14))} ${chalk.dim(config.marketplaceSources.join(', '))}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('Use --set key=value to modify settings'));
|
||||
console.log(chalk.dim('Available keys: agent, autoSync, cacheDir, skillsDir, defaultTimeout'));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private getConfigValue(config: SkillkitConfig, key: string): unknown {
|
||||
switch (key) {
|
||||
case 'agent':
|
||||
return config.agent;
|
||||
case 'autoSync':
|
||||
return config.autoSync;
|
||||
case 'cacheDir':
|
||||
return config.cacheDir;
|
||||
case 'skillsDir':
|
||||
return config.skillsDir;
|
||||
case 'enabledSkills':
|
||||
return config.enabledSkills;
|
||||
case 'disabledSkills':
|
||||
return config.disabledSkills;
|
||||
case 'marketplaceSources':
|
||||
return config.marketplaceSources;
|
||||
case 'defaultTimeout':
|
||||
return config.defaultTimeout;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private setConfigValue(
|
||||
config: SkillkitConfig,
|
||||
key: string,
|
||||
value: string
|
||||
): { success: boolean; error?: string } {
|
||||
switch (key) {
|
||||
case 'agent':
|
||||
if (!VALID_AGENTS.includes(value as AgentType)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Invalid agent. Valid options: ${VALID_AGENTS.join(', ')}`,
|
||||
};
|
||||
}
|
||||
config.agent = value as AgentType;
|
||||
break;
|
||||
|
||||
case 'autoSync':
|
||||
if (!['true', 'false', 'enabled', 'disabled'].includes(value.toLowerCase())) {
|
||||
return { success: false, error: 'autoSync must be true/false or enabled/disabled' };
|
||||
}
|
||||
config.autoSync = value.toLowerCase() === 'true' || value.toLowerCase() === 'enabled';
|
||||
break;
|
||||
|
||||
case 'cacheDir':
|
||||
config.cacheDir = value || undefined;
|
||||
break;
|
||||
|
||||
case 'skillsDir':
|
||||
config.skillsDir = value || undefined;
|
||||
break;
|
||||
|
||||
case 'defaultTimeout': {
|
||||
const timeout = parseInt(value, 10);
|
||||
if (isNaN(timeout) || timeout <= 0) {
|
||||
return { success: false, error: 'defaultTimeout must be a positive number (milliseconds)' };
|
||||
}
|
||||
config.defaultTimeout = timeout;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
return { success: false, error: `Unknown setting: ${key}` };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { SessionManager } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Status command - show current session state
|
||||
*/
|
||||
export class StatusCommand extends Command {
|
||||
static override paths = [['status'], ['st']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Show current session state and execution progress',
|
||||
details: `
|
||||
The status command shows the current state of skill execution sessions,
|
||||
including any paused executions and recent history.
|
||||
`,
|
||||
examples: [
|
||||
['Show session status', '$0 status'],
|
||||
['Show with history', '$0 status --history'],
|
||||
['Show JSON output', '$0 status --json'],
|
||||
],
|
||||
});
|
||||
|
||||
// Show history
|
||||
history = Option.Boolean('--history,-h', false, {
|
||||
description: 'Show execution history',
|
||||
});
|
||||
|
||||
// History limit
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Limit history entries (default: 10)',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
const manager = new SessionManager(targetPath);
|
||||
const state = manager.get();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(state || { message: 'No session found' }, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!state) {
|
||||
console.log(chalk.dim('No active session found.'));
|
||||
console.log(chalk.dim('Run a skill with "skillkit run <skill>" to start a session.'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Show current execution
|
||||
if (state.currentExecution) {
|
||||
const exec = state.currentExecution;
|
||||
const statusColor = exec.status === 'paused' ? chalk.yellow : chalk.green;
|
||||
|
||||
console.log(chalk.cyan('Current Execution:\n'));
|
||||
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
|
||||
console.log(` Source: ${chalk.dim(exec.skillSource)}`);
|
||||
console.log(` Status: ${statusColor(exec.status)}`);
|
||||
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks`);
|
||||
console.log(` Started: ${chalk.dim(new Date(exec.startedAt).toLocaleString())}`);
|
||||
|
||||
if (exec.pausedAt) {
|
||||
console.log(` Paused: ${chalk.dim(new Date(exec.pausedAt).toLocaleString())}`);
|
||||
}
|
||||
|
||||
console.log(chalk.cyan('\n Tasks:'));
|
||||
for (const task of exec.tasks) {
|
||||
const statusIcon = this.getStatusIcon(task.status);
|
||||
const statusText = this.getStatusColor(task.status)(task.status);
|
||||
console.log(` ${statusIcon} ${task.name} - ${statusText}`);
|
||||
if (task.error) {
|
||||
console.log(` ${chalk.red('Error:')} ${task.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (exec.status === 'paused') {
|
||||
console.log(chalk.yellow('\n Resume with: skillkit resume'));
|
||||
}
|
||||
} else {
|
||||
console.log(chalk.dim('No active execution.'));
|
||||
}
|
||||
|
||||
// Show history
|
||||
if (this.history || (!state.currentExecution && state.history.length > 0)) {
|
||||
const limit = this.limit ? parseInt(this.limit, 10) : 10;
|
||||
const history = manager.getHistory(limit);
|
||||
|
||||
if (history.length > 0) {
|
||||
console.log(chalk.cyan('\nExecution History:\n'));
|
||||
|
||||
for (const entry of history) {
|
||||
const statusColor = entry.status === 'completed' ? chalk.green : chalk.red;
|
||||
const duration = this.formatDuration(entry.durationMs);
|
||||
|
||||
console.log(` ${statusColor('●')} ${chalk.bold(entry.skillName)}`);
|
||||
console.log(` ${chalk.dim(entry.skillSource)} • ${duration}`);
|
||||
console.log(` ${chalk.dim(new Date(entry.completedAt).toLocaleString())}`);
|
||||
|
||||
if (entry.commits.length > 0) {
|
||||
console.log(` Commits: ${chalk.dim(entry.commits.join(', '))}`);
|
||||
}
|
||||
|
||||
if (entry.error) {
|
||||
console.log(` ${chalk.red('Error:')} ${entry.error}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show decisions
|
||||
if (state.decisions.length > 0) {
|
||||
console.log(chalk.cyan('Saved Decisions:\n'));
|
||||
for (const decision of state.decisions.slice(0, 5)) {
|
||||
console.log(` ${chalk.dim(decision.key)}: ${decision.value}`);
|
||||
}
|
||||
if (state.decisions.length > 5) {
|
||||
console.log(chalk.dim(` ... and ${state.decisions.length - 5} more`));
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private getStatusIcon(status: string): string {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return chalk.green('✓');
|
||||
case 'failed':
|
||||
return chalk.red('✗');
|
||||
case 'in_progress':
|
||||
return chalk.blue('●');
|
||||
case 'paused':
|
||||
return chalk.yellow('⏸');
|
||||
default:
|
||||
return chalk.dim('○');
|
||||
}
|
||||
}
|
||||
|
||||
private getStatusColor(status: string): (text: string) => string {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return chalk.green;
|
||||
case 'failed':
|
||||
return chalk.red;
|
||||
case 'in_progress':
|
||||
return chalk.blue;
|
||||
case 'paused':
|
||||
return chalk.yellow;
|
||||
default:
|
||||
return chalk.dim;
|
||||
}
|
||||
}
|
||||
|
||||
private formatDuration(ms: number): string {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const seconds = Math.floor((ms % 60000) / 1000);
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* Team Command
|
||||
*
|
||||
* Manage team skill sharing and collaboration
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createTeamManager, createSkillBundle, exportBundle, importBundle } from '@skillkit/core';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export class TeamCommand extends Command {
|
||||
static override paths = [['team']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage team skill sharing and collaboration',
|
||||
examples: [
|
||||
['Initialize team', '$0 team init --name "My Team" --registry https://github.com/myteam/skills'],
|
||||
['Share a skill', '$0 team share --name my-skill'],
|
||||
['Import a skill', '$0 team import --name shared-skill'],
|
||||
['List shared skills', '$0 team list'],
|
||||
['Sync with remote', '$0 team sync'],
|
||||
['Create a bundle', '$0 team bundle-create --name my-bundle --skills skill1,skill2'],
|
||||
['Export a bundle', '$0 team bundle-export --name my-bundle --output ./bundle.json'],
|
||||
['Import a bundle', '$0 team bundle-import --source ./bundle.json'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
name = Option.String('--name', { description: 'Team name (for init), skill name, or bundle name' });
|
||||
registry = Option.String('--registry', { description: 'Registry URL (for init)' });
|
||||
description = Option.String('--description,-d', { description: 'Description (for share/bundle)' });
|
||||
tags = Option.String('--tags,-t', { description: 'Comma-separated tags (for share)' });
|
||||
skills = Option.String('--skills', { description: 'Comma-separated skill names (for bundle)' });
|
||||
output = Option.String('--output,-o', { description: 'Output path (for bundle-export)' });
|
||||
source = Option.String('--source,-s', { description: 'Source path (for bundle-import)' });
|
||||
overwrite = Option.Boolean('--overwrite', { description: 'Overwrite existing (for import)' });
|
||||
dryRun = Option.Boolean('--dry-run', { description: 'Preview without changes' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
const teamManager = createTeamManager(projectPath);
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'init':
|
||||
return await this.initTeam(teamManager);
|
||||
case 'share':
|
||||
return await this.shareSkill(teamManager);
|
||||
case 'import':
|
||||
return await this.importSkill(teamManager);
|
||||
case 'list':
|
||||
return await this.listSkills(teamManager);
|
||||
case 'sync':
|
||||
return await this.syncTeam(teamManager);
|
||||
case 'remove':
|
||||
return await this.removeSkill(teamManager);
|
||||
case 'bundle-create':
|
||||
return await this.createBundle(teamManager);
|
||||
case 'bundle-export':
|
||||
return await this.exportSkillBundle(teamManager);
|
||||
case 'bundle-import':
|
||||
return await this.importSkillBundle();
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: init, share, import, list, sync, remove, bundle-create, bundle-export, bundle-import\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async initTeam(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for init\n'));
|
||||
return 1;
|
||||
}
|
||||
if (!this.registry) {
|
||||
this.context.stderr.write(chalk.red('--registry is required for init\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const config = await teamManager.init({
|
||||
teamName: this.name,
|
||||
registryUrl: this.registry,
|
||||
});
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Team initialized!\n'));
|
||||
this.context.stdout.write(` Team ID: ${config.teamId}\n`);
|
||||
this.context.stdout.write(` Registry: ${config.registryUrl}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async shareSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for share\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const shared = await teamManager.shareSkill({
|
||||
skillName: this.name,
|
||||
description: this.description,
|
||||
tags: this.tags?.split(',').map((t) => t.trim()),
|
||||
});
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Skill shared!\n'));
|
||||
this.context.stdout.write(` Name: ${shared.name}\n`);
|
||||
this.context.stdout.write(` Version: ${shared.version}\n`);
|
||||
this.context.stdout.write(` Source: ${shared.source}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for import\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const result = await teamManager.importSkill(this.name, {
|
||||
overwrite: this.overwrite,
|
||||
dryRun: this.dryRun,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${result.error}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.cyan(`[dry-run] Would import to: ${result.path}\n`));
|
||||
} else {
|
||||
this.context.stdout.write(chalk.green(`✓ Skill imported to: ${result.path}\n`));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listSkills(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = teamManager.listSharedSkills();
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Team: ${config.teamName}\n`));
|
||||
this.context.stdout.write(chalk.gray(`Registry: ${config.registryUrl}\n\n`));
|
||||
|
||||
if (skills.length === 0) {
|
||||
this.context.stdout.write('No shared skills yet. Use `skillkit team share` to share a skill.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Shared Skills (${skills.length}):\n`);
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.cyan(` ${skill.name}`) + ` v${skill.version}\n`);
|
||||
if (skill.description) {
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description}\n`));
|
||||
}
|
||||
this.context.stdout.write(` by ${skill.author} | ${skill.downloads || 0} downloads\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async syncTeam(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Syncing with ${config.registryUrl}...\n`);
|
||||
|
||||
const result = await teamManager.sync();
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Sync complete!\n'));
|
||||
if (result.added.length > 0) {
|
||||
this.context.stdout.write(` Added: ${result.added.join(', ')}\n`);
|
||||
}
|
||||
if (result.updated.length > 0) {
|
||||
this.context.stdout.write(` Updated: ${result.updated.join(', ')}\n`);
|
||||
}
|
||||
if (result.added.length === 0 && result.updated.length === 0) {
|
||||
this.context.stdout.write(' Already up to date.\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async removeSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for remove\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const removed = teamManager.removeSkill(this.name);
|
||||
if (!removed) {
|
||||
this.context.stderr.write(chalk.red(`Skill "${this.name}" not found in team registry.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Skill "${this.name}" removed from team registry.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createBundle(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <bundle-name> is required for bundle-create\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.skills) {
|
||||
this.context.stderr.write(chalk.red('--skills <skill1,skill2,...> is required for bundle-create\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skillNames = this.skills.split(',').map((s) => s.trim());
|
||||
const projectPath = process.cwd();
|
||||
const skillsDir = join(projectPath, 'skills');
|
||||
|
||||
// Create the bundle
|
||||
const bundle = createSkillBundle(this.name, config.teamName, this.description);
|
||||
|
||||
let addedCount = 0;
|
||||
for (const skillName of skillNames) {
|
||||
const skillPath = join(skillsDir, skillName);
|
||||
try {
|
||||
bundle.addSkill(skillPath);
|
||||
addedCount++;
|
||||
this.context.stdout.write(chalk.gray(` + ${skillName}\n`));
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.yellow(` ⚠ Skipping ${skillName}: ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
if (addedCount === 0) {
|
||||
this.context.stderr.write(chalk.red('No skills were added to the bundle.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Export to default location
|
||||
const outputPath = this.output || join(projectPath, '.skillkit', 'bundles', `${this.name}.json`);
|
||||
const result = exportBundle(bundle, outputPath);
|
||||
|
||||
if (!result.success) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${result.error}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`\n✓ Bundle "${this.name}" created with ${addedCount} skills!\n`));
|
||||
this.context.stdout.write(` Checksum: ${bundle.getChecksum()}\n`);
|
||||
this.context.stdout.write(` Output: ${result.path}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async exportSkillBundle(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <bundle-name> is required for bundle-export\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.output) {
|
||||
this.context.stderr.write(chalk.red('--output <path> is required for bundle-export\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const bundlePath = join(projectPath, '.skillkit', 'bundles', `${this.name}.json`);
|
||||
|
||||
// Check if bundle exists
|
||||
const { existsSync, readFileSync, writeFileSync } = await import('node:fs');
|
||||
if (!existsSync(bundlePath)) {
|
||||
this.context.stderr.write(chalk.red(`Bundle "${this.name}" not found. Create it first with bundle-create.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Copy bundle to output
|
||||
const content = readFileSync(bundlePath, 'utf-8');
|
||||
writeFileSync(this.output, content, 'utf-8');
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Bundle exported to: ${this.output}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importSkillBundle(): Promise<number> {
|
||||
if (!this.source) {
|
||||
this.context.stderr.write(chalk.red('--source <path> is required for bundle-import\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { existsSync } = await import('node:fs');
|
||||
if (!existsSync(this.source)) {
|
||||
this.context.stderr.write(chalk.red(`Bundle file not found: ${this.source}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const skillsDir = join(projectPath, 'skills');
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.cyan('[dry-run] Would import bundle to: ' + skillsDir + '\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = importBundle(this.source, skillsDir, { overwrite: this.overwrite });
|
||||
|
||||
if (!result.success && result.imported.length === 0) {
|
||||
this.context.stderr.write(chalk.red('✗ Failed to import bundle:\n'));
|
||||
for (const error of result.errors) {
|
||||
this.context.stderr.write(chalk.red(` - ${error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Imported ${result.imported.length} skills from bundle!\n`));
|
||||
for (const name of result.imported) {
|
||||
this.context.stdout.write(chalk.gray(` + ${name}\n`));
|
||||
}
|
||||
if (result.errors.length > 0) {
|
||||
this.context.stdout.write(chalk.yellow('\nWarnings:\n'));
|
||||
for (const error of result.errors) {
|
||||
this.context.stdout.write(chalk.yellow(` - ${error}\n`));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import chalk from 'chalk';
|
||||
import {
|
||||
runTestSuite,
|
||||
createTestSuiteFromFrontmatter,
|
||||
type SkillTestSuite,
|
||||
type TestSuiteResult,
|
||||
} from '@skillkit/core';
|
||||
import { parse as parseYaml } from 'yaml';
|
||||
|
||||
/**
|
||||
* Test command - run skill tests
|
||||
*/
|
||||
export class TestCommand extends Command {
|
||||
static override paths = [['test']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Run skill tests',
|
||||
details: `
|
||||
The test command runs test cases defined in skill frontmatter.
|
||||
|
||||
Tests are defined in the skill's YAML frontmatter using the 'tests' key.
|
||||
|
||||
Example skill with tests:
|
||||
\`\`\`yaml
|
||||
---
|
||||
name: my-skill
|
||||
tests:
|
||||
- name: "Creates config file"
|
||||
assertions:
|
||||
- type: file_exists
|
||||
target: config.json
|
||||
- name: "Types check"
|
||||
assertions:
|
||||
- type: type_check
|
||||
---
|
||||
\`\`\`
|
||||
`,
|
||||
examples: [
|
||||
['Run all skill tests', '$0 test'],
|
||||
['Run tests for a specific skill', '$0 test my-skill'],
|
||||
['Run with verbose output', '$0 test --verbose'],
|
||||
['Stop on first failure', '$0 test --bail'],
|
||||
['Run tests with specific tags', '$0 test --tags unit,integration'],
|
||||
],
|
||||
});
|
||||
|
||||
skill = Option.String({ required: false });
|
||||
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Verbose output',
|
||||
});
|
||||
|
||||
bail = Option.Boolean('--bail,-b', false, {
|
||||
description: 'Stop on first failure',
|
||||
});
|
||||
|
||||
tags = Option.String('--tags,-t', {
|
||||
description: 'Only run tests with these tags (comma-separated)',
|
||||
});
|
||||
|
||||
skipTags = Option.String('--skip-tags', {
|
||||
description: 'Skip tests with these tags (comma-separated)',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output results as JSON',
|
||||
});
|
||||
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path',
|
||||
});
|
||||
|
||||
timeout = Option.String('--timeout', {
|
||||
description: 'Test timeout in milliseconds',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
// Find skills to test
|
||||
const skillFiles = this.findSkillFiles(targetPath);
|
||||
|
||||
if (skillFiles.length === 0) {
|
||||
if (!this.json) {
|
||||
console.log(chalk.yellow('No skills found with tests.'));
|
||||
console.log(chalk.dim('Add tests to your skills using YAML frontmatter.'));
|
||||
} else {
|
||||
console.log(JSON.stringify({ results: [], passed: true, total: 0 }));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Filter by skill name if provided
|
||||
const filesToTest = this.skill
|
||||
? skillFiles.filter((f) => f.name.includes(this.skill!))
|
||||
: skillFiles;
|
||||
|
||||
if (filesToTest.length === 0) {
|
||||
if (!this.json) {
|
||||
console.log(chalk.yellow(`No skills found matching "${this.skill}"`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.json) {
|
||||
console.log(chalk.bold('Running skill tests...\n'));
|
||||
}
|
||||
|
||||
// Parse tags
|
||||
const tags = this.tags?.split(',').map((t) => t.trim());
|
||||
const skipTags = this.skipTags?.split(',').map((t) => t.trim());
|
||||
const timeout = this.timeout ? parseInt(this.timeout, 10) : undefined;
|
||||
|
||||
// Run tests for each skill
|
||||
const results: TestSuiteResult[] = [];
|
||||
let allPassed = true;
|
||||
|
||||
for (const file of filesToTest) {
|
||||
const suite = this.parseSkillTests(file.path, file.name);
|
||||
|
||||
if (!suite || suite.tests.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!this.json) {
|
||||
console.log(chalk.blue(`Testing: ${suite.skillName}`));
|
||||
}
|
||||
|
||||
const result = await runTestSuite(suite, {
|
||||
cwd: targetPath,
|
||||
verbose: this.verbose,
|
||||
bail: this.bail,
|
||||
tags,
|
||||
skipTags,
|
||||
timeout,
|
||||
onProgress: (event) => {
|
||||
if (this.json || !this.verbose) return;
|
||||
|
||||
switch (event.type) {
|
||||
case 'test_start':
|
||||
console.log(chalk.dim(` Running: ${event.testName}`));
|
||||
break;
|
||||
case 'test_end':
|
||||
if (event.passed) {
|
||||
console.log(chalk.green(` ✓ ${event.testName}`));
|
||||
} else {
|
||||
console.log(chalk.red(` ✗ ${event.testName}`));
|
||||
if (event.error) {
|
||||
console.log(chalk.red(` ${event.error}`));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'assertion_end':
|
||||
if (this.verbose && !event.passed) {
|
||||
console.log(chalk.red(` - ${event.assertionType}: ${event.error}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
results.push(result);
|
||||
|
||||
if (!result.passed) {
|
||||
allPassed = false;
|
||||
}
|
||||
|
||||
if (!this.json) {
|
||||
const icon = result.passed ? chalk.green('✓') : chalk.red('✗');
|
||||
const status = result.passed ? 'PASSED' : 'FAILED';
|
||||
console.log(
|
||||
`${icon} ${suite.skillName}: ${result.passedCount}/${result.tests.length} tests ${status} (${result.duration}ms)\n`
|
||||
);
|
||||
}
|
||||
|
||||
if (this.bail && !result.passed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Summary
|
||||
if (this.json) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
results: results.map((r) => ({
|
||||
skill: r.skillName,
|
||||
passed: r.passed,
|
||||
tests: r.passedCount,
|
||||
failed: r.failedCount,
|
||||
skipped: r.skippedCount,
|
||||
duration: r.duration,
|
||||
})),
|
||||
passed: allPassed,
|
||||
total: results.length,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
const totalTests = results.reduce((acc, r) => acc + r.tests.length, 0);
|
||||
const passedTests = results.reduce((acc, r) => acc + r.passedCount, 0);
|
||||
const failedTests = results.reduce((acc, r) => acc + r.failedCount, 0);
|
||||
const skippedTests = results.reduce((acc, r) => acc + r.skippedCount, 0);
|
||||
|
||||
console.log(chalk.bold('Summary:'));
|
||||
console.log(` Skills tested: ${results.length}`);
|
||||
console.log(` Total tests: ${totalTests}`);
|
||||
console.log(chalk.green(` Passed: ${passedTests}`));
|
||||
if (failedTests > 0) {
|
||||
console.log(chalk.red(` Failed: ${failedTests}`));
|
||||
}
|
||||
if (skippedTests > 0) {
|
||||
console.log(chalk.yellow(` Skipped: ${skippedTests}`));
|
||||
}
|
||||
|
||||
if (allPassed) {
|
||||
console.log(chalk.green('\n✓ All tests passed!'));
|
||||
} else {
|
||||
console.log(chalk.red('\n✗ Some tests failed.'));
|
||||
}
|
||||
}
|
||||
|
||||
return allPassed ? 0 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find skill files with tests
|
||||
*/
|
||||
private findSkillFiles(projectPath: string): { name: string; path: string }[] {
|
||||
const files: { name: string; path: string }[] = [];
|
||||
|
||||
// Check common skill directories
|
||||
const skillDirs = [
|
||||
'.claude/skills',
|
||||
'.cursor/skills',
|
||||
'.skillkit/skills',
|
||||
'skills',
|
||||
];
|
||||
|
||||
for (const dir of skillDirs) {
|
||||
const fullDir = join(projectPath, dir);
|
||||
if (!existsSync(fullDir)) continue;
|
||||
|
||||
try {
|
||||
const entries = readdirSync(fullDir, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.mdc'))) {
|
||||
files.push({
|
||||
name: entry.name.replace(/\.(md|mdc)$/, ''),
|
||||
path: join(fullDir, entry.name),
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Directory not readable
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse skill file for tests
|
||||
*/
|
||||
private parseSkillTests(filePath: string, skillName: string): SkillTestSuite | null {
|
||||
try {
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
|
||||
// Extract frontmatter
|
||||
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (!frontmatterMatch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const frontmatter = parseYaml(frontmatterMatch[1]) as Record<string, unknown>;
|
||||
|
||||
if (!frontmatter.tests) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createTestSuiteFromFrontmatter(skillName, frontmatter);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { createWorkflowTemplate, saveWorkflow, serializeWorkflow } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Workflow Create command - create a new workflow
|
||||
*/
|
||||
export class WorkflowCreateCommand extends Command {
|
||||
static override paths = [['workflow', 'create'], ['wf', 'create'], ['workflow', 'new'], ['wf', 'new']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Create a new workflow',
|
||||
details: `
|
||||
The workflow create command creates a new workflow template
|
||||
that you can customize with your skill composition.
|
||||
`,
|
||||
examples: [
|
||||
['Create a new workflow', '$0 workflow create my-workflow'],
|
||||
['Create with description', '$0 workflow create setup-project --description "Project setup workflow"'],
|
||||
['Print to stdout', '$0 workflow create my-workflow --stdout'],
|
||||
],
|
||||
});
|
||||
|
||||
// Workflow name
|
||||
workflowName = Option.String({ required: true });
|
||||
|
||||
// Description
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Workflow description',
|
||||
});
|
||||
|
||||
// Print to stdout instead of saving
|
||||
stdout = Option.Boolean('--stdout', false, {
|
||||
description: 'Print workflow YAML to stdout instead of saving',
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
const workflow = createWorkflowTemplate(this.workflowName, this.description);
|
||||
|
||||
if (this.stdout) {
|
||||
console.log(serializeWorkflow(workflow));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const filePath = saveWorkflow(targetPath, workflow);
|
||||
|
||||
console.log(chalk.green(`✓ Created workflow: ${chalk.bold(this.workflowName)}`));
|
||||
console.log(chalk.dim(` File: ${filePath}`));
|
||||
console.log();
|
||||
console.log(chalk.dim('Edit the workflow file to add skills and configure waves.'));
|
||||
console.log(chalk.dim('Run with: skillkit workflow run ' + this.workflowName));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Workflow command exports
|
||||
export { WorkflowRunCommand } from './run.js';
|
||||
export { WorkflowListCommand } from './list.js';
|
||||
export { WorkflowCreateCommand } from './create.js';
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { listWorkflows } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Workflow List command - list available workflows
|
||||
*/
|
||||
export class WorkflowListCommand extends Command {
|
||||
static override paths = [['workflow', 'list'], ['wf', 'list'], ['workflow', 'ls'], ['wf', 'ls']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'List available workflows',
|
||||
details: `
|
||||
The workflow list command shows all available workflows
|
||||
defined in .skillkit/workflows/
|
||||
`,
|
||||
examples: [
|
||||
['List all workflows', '$0 workflow list'],
|
||||
['List with details', '$0 workflow list --verbose'],
|
||||
],
|
||||
});
|
||||
|
||||
// Verbose output
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Show detailed workflow information',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
let workflows: ReturnType<typeof listWorkflows>;
|
||||
try {
|
||||
workflows = listWorkflows(targetPath);
|
||||
} catch (err) {
|
||||
console.log(chalk.red('Failed to list workflows.'));
|
||||
console.log(chalk.dim(String(err)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(workflows, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (workflows.length === 0) {
|
||||
console.log(chalk.yellow('No workflows found.'));
|
||||
console.log(chalk.dim('Create a workflow with: skillkit workflow create'));
|
||||
console.log(chalk.dim('Or add YAML files to .skillkit/workflows/'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Available Workflows (${workflows.length}):\n`));
|
||||
|
||||
for (const workflow of workflows) {
|
||||
console.log(` ${chalk.bold(workflow.name)}`);
|
||||
|
||||
if (workflow.description) {
|
||||
console.log(` ${chalk.dim(workflow.description)}`);
|
||||
}
|
||||
|
||||
if (this.verbose) {
|
||||
console.log(` Version: ${chalk.dim(workflow.version || 'N/A')}`);
|
||||
console.log(` Waves: ${chalk.dim(workflow.waves.length.toString())}`);
|
||||
|
||||
const totalSkills = workflow.waves.reduce(
|
||||
(sum, wave) => sum + wave.skills.length,
|
||||
0
|
||||
);
|
||||
console.log(` Total Skills: ${chalk.dim(totalSkills.toString())}`);
|
||||
|
||||
if (workflow.tags && workflow.tags.length > 0) {
|
||||
console.log(` Tags: ${chalk.dim(workflow.tags.join(', '))}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
console.log(chalk.dim('Run a workflow with: skillkit workflow run <name>'));
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
loadWorkflowByName,
|
||||
loadWorkflow,
|
||||
validateWorkflow,
|
||||
createWorkflowOrchestrator,
|
||||
createSkillExecutor,
|
||||
createSimulatedSkillExecutor,
|
||||
type AgentType,
|
||||
} from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Workflow Run command - execute a workflow
|
||||
*/
|
||||
export class WorkflowRunCommand extends Command {
|
||||
static override paths = [['workflow', 'run'], ['wf', 'run']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Execute a skill workflow',
|
||||
details: `
|
||||
The workflow run command executes a workflow definition,
|
||||
running skills in waves with parallel or sequential execution.
|
||||
|
||||
Workflows are defined in YAML files in .skillkit/workflows/
|
||||
`,
|
||||
examples: [
|
||||
['Run a workflow by name', '$0 workflow run setup-project'],
|
||||
['Run a workflow from file', '$0 workflow run --file my-workflow.yaml'],
|
||||
['Dry run (no execution)', '$0 workflow run setup-project --dry-run'],
|
||||
],
|
||||
});
|
||||
|
||||
// Workflow name
|
||||
workflowName = Option.String({ required: false });
|
||||
|
||||
// Workflow file path
|
||||
file = Option.String('--file,-f', {
|
||||
description: 'Path to workflow YAML file',
|
||||
});
|
||||
|
||||
// Dry run
|
||||
dryRun = Option.Boolean('--dry-run,-n', false, {
|
||||
description: 'Show what would be executed without running',
|
||||
});
|
||||
|
||||
// Verbose output
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Show detailed execution progress',
|
||||
});
|
||||
|
||||
// Continue on error
|
||||
continueOnError = Option.Boolean('--continue-on-error', false, {
|
||||
description: 'Continue execution even if a skill fails',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
// Project path
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
// Agent to use for execution
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Agent to use for skill execution (e.g., claude-code, codex)',
|
||||
});
|
||||
|
||||
// Simulate execution (for testing)
|
||||
simulate = Option.Boolean('--simulate', false, {
|
||||
description: 'Simulate execution without running skills (for testing)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
// Load workflow
|
||||
let workflow;
|
||||
try {
|
||||
if (this.file) {
|
||||
workflow = loadWorkflow(resolve(this.file));
|
||||
} else if (this.workflowName) {
|
||||
workflow = loadWorkflowByName(targetPath, this.workflowName);
|
||||
if (!workflow) {
|
||||
console.error(chalk.red(`Workflow "${this.workflowName}" not found`));
|
||||
console.log(chalk.dim('List available workflows: skillkit workflow list'));
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
console.error(chalk.red('Please specify a workflow name or --file'));
|
||||
return 1;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Failed to load workflow: ${error}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Validate workflow
|
||||
const validation = validateWorkflow(workflow);
|
||||
if (!validation.valid) {
|
||||
console.error(chalk.red('Invalid workflow:'));
|
||||
for (const error of validation.errors) {
|
||||
console.error(chalk.red(` • ${error}`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Dry run mode
|
||||
if (this.dryRun) {
|
||||
this.showDryRun(workflow);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Execute workflow
|
||||
console.log(chalk.cyan(`Executing workflow: ${chalk.bold(workflow.name)}`));
|
||||
if (workflow.description) {
|
||||
console.log(chalk.dim(workflow.description));
|
||||
}
|
||||
console.log();
|
||||
|
||||
const spinner = ora();
|
||||
let currentWave = -1;
|
||||
|
||||
// Create the skill executor (real or simulated)
|
||||
const skillExecutor = this.simulate
|
||||
? createSimulatedSkillExecutor({
|
||||
delay: 500,
|
||||
onExecute: (skillName) => {
|
||||
if (this.verbose && !this.json) {
|
||||
console.log(chalk.dim(` [Simulated] ${skillName}`));
|
||||
}
|
||||
},
|
||||
})
|
||||
: createSkillExecutor({
|
||||
projectPath: targetPath,
|
||||
preferredAgent: this.agent as AgentType | undefined,
|
||||
fallbackToAvailable: true,
|
||||
onExecutionEvent: (event) => {
|
||||
if (this.verbose && !this.json) {
|
||||
switch (event.type) {
|
||||
case 'skill_found':
|
||||
console.log(chalk.dim(` Found: ${event.message}`));
|
||||
break;
|
||||
case 'skill_not_found':
|
||||
console.log(chalk.red(` Not found: ${event.skillName}`));
|
||||
break;
|
||||
case 'agent_selected':
|
||||
console.log(chalk.dim(` Agent: ${event.agent}`));
|
||||
break;
|
||||
case 'execution_complete':
|
||||
if (!event.success) {
|
||||
console.log(chalk.red(` Error: ${event.error}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Create orchestrator with real skill executor
|
||||
const orchestrator = createWorkflowOrchestrator(
|
||||
skillExecutor,
|
||||
(event) => {
|
||||
if (this.json) return;
|
||||
|
||||
switch (event.type) {
|
||||
case 'wave_start':
|
||||
currentWave = event.waveIndex || 0;
|
||||
spinner.start(`Wave ${currentWave + 1}: ${event.waveName || 'Executing...'}`);
|
||||
break;
|
||||
|
||||
case 'skill_start':
|
||||
if (this.verbose) {
|
||||
spinner.text = `Wave ${currentWave + 1}: Running ${event.skillName}...`;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'skill_complete':
|
||||
if (this.verbose) {
|
||||
const icon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
|
||||
console.log(` ${icon} ${event.skillName}`);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'wave_complete':
|
||||
const waveIcon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
|
||||
spinner.stopAndPersist({
|
||||
symbol: waveIcon,
|
||||
text: `Wave ${(event.waveIndex || 0) + 1}: ${event.waveName || 'Complete'}`,
|
||||
});
|
||||
break;
|
||||
|
||||
case 'workflow_complete':
|
||||
console.log();
|
||||
if (event.status === 'completed') {
|
||||
console.log(chalk.green('✓ Workflow completed successfully'));
|
||||
} else {
|
||||
console.log(chalk.red(`✗ Workflow ${event.status}`));
|
||||
if (event.error) {
|
||||
console.log(chalk.red(` Error: ${event.error}`));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const execution = await orchestrator.execute(workflow);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(execution, null, 2));
|
||||
}
|
||||
|
||||
return execution.status === 'completed' ? 0 : 1;
|
||||
}
|
||||
|
||||
private showDryRun(workflow: { name: string; description?: string; waves: Array<{ name?: string; parallel: boolean; skills: Array<string | { skill: string }> }> }): void {
|
||||
console.log(chalk.cyan('Dry Run - Workflow Execution Plan'));
|
||||
console.log();
|
||||
console.log(`Workflow: ${chalk.bold(workflow.name)}`);
|
||||
if (workflow.description) {
|
||||
console.log(`Description: ${chalk.dim(workflow.description)}`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
for (let i = 0; i < workflow.waves.length; i++) {
|
||||
const wave = workflow.waves[i];
|
||||
const modeLabel = wave.parallel ? chalk.blue('[parallel]') : chalk.yellow('[sequential]');
|
||||
|
||||
console.log(`${chalk.cyan(`Wave ${i + 1}`)}: ${wave.name || 'Unnamed'} ${modeLabel}`);
|
||||
|
||||
for (const skill of wave.skills) {
|
||||
const skillName = typeof skill === 'string' ? skill : skill.skill;
|
||||
console.log(` • ${skillName}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
console.log(chalk.dim('This is a dry run. No skills were executed.'));
|
||||
console.log(chalk.dim('Remove --dry-run to execute the workflow.'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
# @skillkit/core
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/core)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Core engine for SkillKit** - skill discovery, cross-agent translation, recommendations, session memory, testing, and workflow orchestration.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/core
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Skill Discovery**: Find and parse SKILL.md files from any source
|
||||
- **Cross-Agent Translation**: Convert skills between 17 agent formats (Claude Code, Cursor, Windsurf, etc.)
|
||||
- **Project Context Detection**: Analyze project stack, dependencies, and configurations
|
||||
- **Smart Recommendations**: AI-powered skill suggestions based on project profile
|
||||
- **Session Memory**: Capture and persist learnings across AI coding sessions
|
||||
- **Skill Testing**: Test framework with assertions for skill validation
|
||||
- **Workflow Orchestration**: Compose skills into multi-step workflows
|
||||
- **Marketplace Aggregation**: Browse and search curated skill repositories
|
||||
- **Team Collaboration**: Share skill bundles with Git-based remote sync
|
||||
- **Plugin System**: Extend with custom translators, providers, and commands
|
||||
- **Methodologies**: 5 development frameworks (Agile, TDD, DevOps, Design Thinking, Feature Flags)
|
||||
- **Multi-Agent Orchestration**: Coordinate teams of AI agents with task assignment
|
||||
- **Plan System**: Parse, validate, and execute structured development plans
|
||||
- **Hooks & Automation**: Auto-trigger skills on file changes, git events
|
||||
|
||||
## Usage
|
||||
|
||||
### Skill Discovery
|
||||
|
||||
```typescript
|
||||
import { findAllSkills, discoverSkills, parseSkill } from '@skillkit/core';
|
||||
|
||||
// Find all installed skills
|
||||
const skills = findAllSkills(['.claude/skills', '.cursor/skills']);
|
||||
|
||||
// Discover skills from a repository
|
||||
const repoSkills = await discoverSkills('anthropics/skills');
|
||||
|
||||
// Parse a single skill file
|
||||
const skill = parseSkill('./my-skill/SKILL.md');
|
||||
```
|
||||
|
||||
### Cross-Agent Translation
|
||||
|
||||
```typescript
|
||||
import { translateSkill, translateSkillFile, TranslatorRegistry } from '@skillkit/core';
|
||||
|
||||
// Translate skill content to Cursor format
|
||||
const result = translateSkill(skillContent, 'cursor');
|
||||
console.log(result.content); // MDC format for Cursor
|
||||
|
||||
// Translate a skill file
|
||||
const translated = await translateSkillFile('./skill.md', 'windsurf');
|
||||
|
||||
// Get available translators
|
||||
const registry = new TranslatorRegistry();
|
||||
const formats = registry.getSupportedFormats();
|
||||
```
|
||||
|
||||
### Project Context & Recommendations
|
||||
|
||||
```typescript
|
||||
import { ProjectDetector, RecommendationEngine, ContextManager } from '@skillkit/core';
|
||||
|
||||
// Detect project context
|
||||
const detector = new ProjectDetector();
|
||||
const profile = await detector.analyze('./my-project');
|
||||
// profile.stack includes: languages, frameworks, libraries, testing tools, etc.
|
||||
|
||||
// Get skill recommendations
|
||||
const engine = new RecommendationEngine();
|
||||
const recommendations = engine.recommend(profile, availableSkills);
|
||||
// Returns skills sorted by match score
|
||||
|
||||
// Manage project context
|
||||
const ctx = new ContextManager('./my-project');
|
||||
await ctx.init();
|
||||
const context = ctx.getContext();
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
LearningStore,
|
||||
ObservationStore,
|
||||
} from '@skillkit/core';
|
||||
|
||||
// Compress observations into learnings
|
||||
const compressor = createMemoryCompressor('./my-project');
|
||||
const learnings = compressor.compress();
|
||||
|
||||
// Inject relevant memories into prompts
|
||||
const injector = createMemoryInjector('./my-project');
|
||||
const memories = injector.search('authentication patterns');
|
||||
|
||||
// Manage learnings directly
|
||||
const store = new LearningStore('./my-project');
|
||||
const learning = store.add({
|
||||
title: 'React hooks best practices',
|
||||
content: 'Always cleanup effects...',
|
||||
tags: ['react', 'hooks'],
|
||||
});
|
||||
```
|
||||
|
||||
### Skill Testing
|
||||
|
||||
```typescript
|
||||
import { SkillTestRunner, parseTestCases } from '@skillkit/core';
|
||||
|
||||
// Run skill tests
|
||||
const runner = new SkillTestRunner('./my-project');
|
||||
const results = await runner.runAll();
|
||||
|
||||
// Run specific tests
|
||||
const result = await runner.run('./my-skill', {
|
||||
tags: ['unit'],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Parse test cases from skill
|
||||
const testCases = parseTestCases(skillContent);
|
||||
```
|
||||
|
||||
### Workflow Orchestration
|
||||
|
||||
```typescript
|
||||
import { WorkflowOrchestrator, parseWorkflow, WorkflowStore } from '@skillkit/core';
|
||||
|
||||
// Parse and run a workflow
|
||||
const workflow = parseWorkflow('./workflow.yaml');
|
||||
const orchestrator = new WorkflowOrchestrator(workflow);
|
||||
await orchestrator.execute();
|
||||
|
||||
// Manage workflows
|
||||
const store = new WorkflowStore('./my-project');
|
||||
const workflows = store.list();
|
||||
```
|
||||
|
||||
### Marketplace
|
||||
|
||||
```typescript
|
||||
import { createMarketplaceAggregator, MarketplaceSource } from '@skillkit/core';
|
||||
|
||||
// Browse skill marketplace
|
||||
const marketplace = createMarketplaceAggregator();
|
||||
const results = await marketplace.search({ query: 'react' });
|
||||
|
||||
// Filter by tags
|
||||
const filtered = await marketplace.search({
|
||||
query: 'authentication',
|
||||
tags: ['security', 'auth'],
|
||||
limit: 10,
|
||||
});
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```typescript
|
||||
import { TeamManager, SkillBundle } from '@skillkit/core';
|
||||
|
||||
// Initialize team
|
||||
const teamManager = new TeamManager('./my-project');
|
||||
await teamManager.init('Engineering Team');
|
||||
|
||||
// Create skill bundle
|
||||
const bundle = await teamManager.createBundle('onboarding', {
|
||||
skills: ['git-workflow', 'code-review'],
|
||||
description: 'New developer onboarding',
|
||||
});
|
||||
|
||||
// Share bundle
|
||||
await teamManager.shareBundle(bundle);
|
||||
|
||||
// Sync with remote registry
|
||||
await teamManager.syncWithRemote('https://github.com/myorg/skills');
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```typescript
|
||||
import { PluginManager, TranslatorPlugin } from '@skillkit/core';
|
||||
|
||||
// Load plugins
|
||||
const pluginManager = new PluginManager('./my-project');
|
||||
await pluginManager.loadAll();
|
||||
|
||||
// Install plugin
|
||||
await pluginManager.install('custom-translator');
|
||||
|
||||
// Create custom plugin
|
||||
const myPlugin: TranslatorPlugin = {
|
||||
name: 'my-agent',
|
||||
parse: async (content) => ({ /* canonical skill */ }),
|
||||
generate: async (skill) => '/* custom format */',
|
||||
};
|
||||
```
|
||||
|
||||
### Methodologies
|
||||
|
||||
```typescript
|
||||
import { MethodologyManager } from '@skillkit/core';
|
||||
|
||||
// List available methodologies
|
||||
const methodologies = await MethodologyManager.list();
|
||||
|
||||
// Load methodology
|
||||
const tdd = await MethodologyManager.load('tdd');
|
||||
// Returns: { name: 'TDD', skills: ['red-green-refactor', 'test-first'], ... }
|
||||
```
|
||||
|
||||
### Multi-Agent Orchestration
|
||||
|
||||
```typescript
|
||||
import { TeamOrchestrator, TaskManager } from '@skillkit/core';
|
||||
|
||||
// Create agent team
|
||||
const orchestrator = new TeamOrchestrator();
|
||||
const team = await orchestrator.createTeam({
|
||||
name: 'feature-dev',
|
||||
leader: { id: 'architect', name: 'System Architect' },
|
||||
teammates: [
|
||||
{ id: 'frontend', name: 'Frontend Dev', capabilities: ['react'] },
|
||||
{ id: 'backend', name: 'Backend Dev', capabilities: ['api'] },
|
||||
],
|
||||
});
|
||||
|
||||
// Manage tasks
|
||||
const taskManager = new TaskManager();
|
||||
const task = taskManager.createTask('Build login', 'Create login endpoint', spec);
|
||||
await taskManager.assignTask(task.id, 'backend');
|
||||
|
||||
// Get stats
|
||||
const stats = taskManager.getStats();
|
||||
```
|
||||
|
||||
### Plan System
|
||||
|
||||
```typescript
|
||||
import { PlanParser, PlanValidator, PlanExecutor } from '@skillkit/core';
|
||||
|
||||
// Parse plan from markdown
|
||||
const parser = new PlanParser();
|
||||
const plan = await parser.parseFile('./plan.md');
|
||||
|
||||
// Validate plan
|
||||
const validator = new PlanValidator();
|
||||
const validation = validator.validate(plan);
|
||||
|
||||
// Execute plan
|
||||
const executor = new PlanExecutor();
|
||||
const result = await executor.execute(plan, { dryRun: false });
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```typescript
|
||||
import { HookRegistry } from '@skillkit/core';
|
||||
|
||||
// Register hooks
|
||||
const hooks = new HookRegistry('./my-project');
|
||||
await hooks.register('pre-commit', {
|
||||
event: 'pre-commit',
|
||||
skill: 'code-review',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
// Trigger hook
|
||||
await hooks.trigger('pre-commit', { files: ['src/index.ts'] });
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
The translator supports all 17 SkillKit-compatible agents:
|
||||
|
||||
| Agent | Format |
|
||||
|-------|--------|
|
||||
| Claude Code | SKILL.md |
|
||||
| Cursor | MDC (.mdc) |
|
||||
| Codex | SKILL.md |
|
||||
| Gemini CLI | SKILL.md |
|
||||
| Windsurf | Markdown |
|
||||
| GitHub Copilot | Markdown |
|
||||
| OpenCode, Antigravity, Amp, Goose, Kilo, Kiro, Roo, Trae | SKILL.md |
|
||||
| Universal | SKILL.md |
|
||||
|
||||
## API Reference
|
||||
|
||||
### Skill Types
|
||||
|
||||
```typescript
|
||||
interface CanonicalSkill {
|
||||
name: string;
|
||||
description?: string;
|
||||
version?: string;
|
||||
author?: string;
|
||||
tags?: string[];
|
||||
globs?: string[];
|
||||
alwaysApply?: boolean;
|
||||
content: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface TranslationResult {
|
||||
content: string;
|
||||
format: string;
|
||||
warnings?: string[];
|
||||
}
|
||||
```
|
||||
|
||||
### Context Types
|
||||
|
||||
```typescript
|
||||
interface ProjectProfile {
|
||||
name: string;
|
||||
type: 'web-app' | 'api' | 'cli' | 'library' | 'unknown';
|
||||
stack: {
|
||||
languages: Detection[];
|
||||
frameworks: Detection[];
|
||||
libraries: Detection[];
|
||||
testing: Detection[];
|
||||
databases: Detection[];
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/core",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.0",
|
||||
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -35,7 +35,9 @@
|
||||
"types": "./dist/recommend/index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
@@ -43,6 +45,8 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/minimatch": "^6.0.0",
|
||||
"minimatch": "^10.1.1",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { AIManager } from '../manager.js';
|
||||
import type { SearchableSkill, SkillExample } from '../types.js';
|
||||
|
||||
describe('AIManager', () => {
|
||||
let manager: AIManager;
|
||||
let testSkills: SearchableSkill[];
|
||||
|
||||
beforeEach(() => {
|
||||
manager = new AIManager({
|
||||
provider: 'mock',
|
||||
});
|
||||
|
||||
testSkills = [
|
||||
{
|
||||
name: 'test-driven-development',
|
||||
description: 'Write tests before code using TDD methodology',
|
||||
content: 'TDD skill content',
|
||||
tags: ['testing', 'tdd', 'quality'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
{
|
||||
name: 'code-review',
|
||||
description: 'Perform thorough code reviews',
|
||||
content: 'Code review skill content',
|
||||
tags: ['review', 'quality', 'collaboration'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
{
|
||||
name: 'debugging-guide',
|
||||
description: 'Systematic approach to debugging issues',
|
||||
content: 'Debugging skill content',
|
||||
tags: ['debugging', 'troubleshooting'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
describe('searchSkills', () => {
|
||||
it('should search skills by query', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results[0].skill.name).toBe('test-driven-development');
|
||||
expect(results[0].relevance).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should respect limit option', async () => {
|
||||
const results = await manager.searchSkills('code', testSkills, {
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
expect(results.length).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should filter by min relevance', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
minRelevance: 0.8,
|
||||
});
|
||||
|
||||
for (const result of results) {
|
||||
expect(result.relevance).toBeGreaterThanOrEqual(0.8);
|
||||
}
|
||||
});
|
||||
|
||||
it('should include reasoning when requested', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
includeReasoning: true,
|
||||
});
|
||||
|
||||
if (results.length > 0) {
|
||||
expect(results[0].reasoning).toBeDefined();
|
||||
expect(results[0].reasoning.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchByIntent', () => {
|
||||
it('should search by user intent', async () => {
|
||||
const results = await manager.searchByIntent(
|
||||
'I want to improve my testing workflow',
|
||||
testSkills,
|
||||
{ minRelevance: 0 }
|
||||
);
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
const names = results.map((r) => r.skill.name);
|
||||
expect(names).toContain('test-driven-development');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findSimilar', () => {
|
||||
it('should find similar skills', async () => {
|
||||
const targetSkill = testSkills[0];
|
||||
const results = await manager.findSimilar(targetSkill, testSkills, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
results.forEach((r) => {
|
||||
expect(r.skill.name).not.toBe(targetSkill.name);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkill', () => {
|
||||
it('should generate skill from example', async () => {
|
||||
const example: SkillExample = {
|
||||
description: 'Help with API testing',
|
||||
context: 'REST APIs using Jest',
|
||||
};
|
||||
|
||||
const generated = await manager.generateSkill(example);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.name.length).toBeGreaterThan(0);
|
||||
expect(generated.description).toBe(example.description);
|
||||
expect(generated.content).toBeDefined();
|
||||
expect(generated.tags).toBeDefined();
|
||||
expect(generated.confidence).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should include target agent metadata', async () => {
|
||||
const example: SkillExample = {
|
||||
description: 'Test skill',
|
||||
};
|
||||
|
||||
const generated = await manager.generateSkill(example, {
|
||||
targetAgent: 'claude-code',
|
||||
});
|
||||
|
||||
expect(generated.content).toContain('agent: claude-code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateFromCode', () => {
|
||||
it('should generate skill from code example', async () => {
|
||||
const code = `
|
||||
function add(a: number, b: number): number {
|
||||
return a + b;
|
||||
}
|
||||
`;
|
||||
const description = 'Simple addition function';
|
||||
|
||||
const generated = await manager.generateFromCode(code, description);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.description).toBe(description);
|
||||
expect(generated.content).toContain('Example');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateFromTemplate', () => {
|
||||
it('should generate skill from template', async () => {
|
||||
const generated = await manager.generateFromTemplate(
|
||||
'api-testing',
|
||||
{ framework: 'Jest', type: 'REST' }
|
||||
);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.content).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateGenerated', () => {
|
||||
it('should validate valid generated skill', () => {
|
||||
const skill = {
|
||||
name: 'valid-skill-name',
|
||||
description: 'This is a valid description with enough length',
|
||||
content: 'This is valid content with enough length to pass validation checks',
|
||||
tags: ['test', 'valid'],
|
||||
confidence: 0.8,
|
||||
reasoning: 'Valid reasoning',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should reject skill with short name', () => {
|
||||
const skill = {
|
||||
name: 'ab',
|
||||
description: 'Valid description',
|
||||
content: 'Valid content with enough length',
|
||||
tags: [],
|
||||
confidence: 0.8,
|
||||
reasoning: '',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain(
|
||||
'Skill name must be at least 3 characters'
|
||||
);
|
||||
});
|
||||
|
||||
it('should reject skill with low confidence', () => {
|
||||
const skill = {
|
||||
name: 'valid-name',
|
||||
description: 'Valid description',
|
||||
content: 'Valid content with enough length',
|
||||
tags: [],
|
||||
confidence: 0.4,
|
||||
reasoning: '',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain(
|
||||
'Skill confidence is too low (< 0.6)'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProviderName', () => {
|
||||
it('should return provider name', () => {
|
||||
const name = manager.getProviderName();
|
||||
expect(name).toBe('mock');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateConfig', () => {
|
||||
it('should update configuration', () => {
|
||||
manager.updateConfig({
|
||||
temperature: 0.5,
|
||||
});
|
||||
|
||||
// Provider should be recreated
|
||||
expect(manager.getProviderName()).toBe('mock');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type {
|
||||
AIProvider,
|
||||
AIGenerateOptions,
|
||||
GeneratedSkill,
|
||||
SkillExample,
|
||||
} from './types.js';
|
||||
|
||||
export class AISkillGenerator {
|
||||
constructor(private provider: AIProvider) {}
|
||||
|
||||
async generate(
|
||||
example: SkillExample,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
const skill = await this.provider.generateSkill(example);
|
||||
|
||||
if (options.targetAgent && skill.content) {
|
||||
skill.content = this.addAgentMetadata(skill.content, options.targetAgent);
|
||||
}
|
||||
|
||||
return skill;
|
||||
}
|
||||
|
||||
async generateFromCode(
|
||||
code: string,
|
||||
description: string,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generate(
|
||||
{
|
||||
description,
|
||||
codeExamples: [code],
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
async generateFromTemplate(
|
||||
templateName: string,
|
||||
variables: Record<string, string>,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generate(
|
||||
{
|
||||
description: `Create a skill based on the ${templateName} template with the following customization: ${JSON.stringify(variables)}`,
|
||||
context: `Template: ${templateName}`,
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private addAgentMetadata(content: string, agent: string): string {
|
||||
const metadata = `---
|
||||
agent: ${agent}
|
||||
generated: ${new Date().toISOString()}
|
||||
---
|
||||
|
||||
${content}`;
|
||||
return metadata;
|
||||
}
|
||||
|
||||
validateGenerated(skill: GeneratedSkill): {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
} {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (!skill.name || skill.name.length < 3) {
|
||||
errors.push('Skill name must be at least 3 characters');
|
||||
}
|
||||
|
||||
if (!skill.description || skill.description.length < 10) {
|
||||
errors.push('Skill description must be at least 10 characters');
|
||||
}
|
||||
|
||||
if (!skill.content || skill.content.length < 50) {
|
||||
errors.push('Skill content must be at least 50 characters');
|
||||
}
|
||||
|
||||
if (skill.confidence < 0.6) {
|
||||
errors.push('Skill confidence is too low (< 0.6)');
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './types.js';
|
||||
export * from './search.js';
|
||||
export * from './generator.js';
|
||||
export * from './manager.js';
|
||||
export * from './providers/index.js';
|
||||
@@ -0,0 +1,104 @@
|
||||
import type {
|
||||
AIConfig,
|
||||
AIProvider,
|
||||
AISearchOptions,
|
||||
AISearchResult,
|
||||
AIGenerateOptions,
|
||||
GeneratedSkill,
|
||||
SearchableSkill,
|
||||
SkillExample,
|
||||
} from './types.js';
|
||||
import { AISearch } from './search.js';
|
||||
import { AISkillGenerator } from './generator.js';
|
||||
import { MockAIProvider } from './providers/mock.js';
|
||||
|
||||
export class AIManager {
|
||||
private provider: AIProvider;
|
||||
private search: AISearch;
|
||||
private generator: AISkillGenerator;
|
||||
|
||||
constructor(private config: AIConfig) {
|
||||
this.provider = this.createProvider();
|
||||
this.search = new AISearch(this.provider);
|
||||
this.generator = new AISkillGenerator(this.provider);
|
||||
}
|
||||
|
||||
async searchSkills(
|
||||
query: string,
|
||||
skills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.search(query, skills, options);
|
||||
}
|
||||
|
||||
async searchByIntent(
|
||||
intent: string,
|
||||
skills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.searchByIntent(intent, skills, options);
|
||||
}
|
||||
|
||||
async findSimilar(
|
||||
skill: SearchableSkill,
|
||||
allSkills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.findSimilar(skill, allSkills, options);
|
||||
}
|
||||
|
||||
async generateSkill(
|
||||
example: SkillExample,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generate(example, options);
|
||||
}
|
||||
|
||||
async generateFromCode(
|
||||
code: string,
|
||||
description: string,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generateFromCode(code, description, options);
|
||||
}
|
||||
|
||||
async generateFromTemplate(
|
||||
templateName: string,
|
||||
variables: Record<string, string>,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generateFromTemplate(templateName, variables, options);
|
||||
}
|
||||
|
||||
validateGenerated(skill: GeneratedSkill): {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
} {
|
||||
return this.generator.validateGenerated(skill);
|
||||
}
|
||||
|
||||
private createProvider(): AIProvider {
|
||||
if (this.config.provider === 'none' || !this.config.apiKey) {
|
||||
return new MockAIProvider();
|
||||
}
|
||||
|
||||
switch (this.config.provider) {
|
||||
case 'anthropic':
|
||||
case 'openai':
|
||||
return new MockAIProvider();
|
||||
default:
|
||||
return new MockAIProvider();
|
||||
}
|
||||
}
|
||||
|
||||
getProviderName(): string {
|
||||
return this.provider.name;
|
||||
}
|
||||
|
||||
updateConfig(config: Partial<AIConfig>): void {
|
||||
this.config = { ...this.config, ...config };
|
||||
this.provider = this.createProvider();
|
||||
this.search = new AISearch(this.provider);
|
||||
this.generator = new AISkillGenerator(this.provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
AIProvider,
|
||||
AISearchResult,
|
||||
GeneratedSkill,
|
||||
SearchableSkill,
|
||||
SkillExample,
|
||||
} from '../types.js';
|
||||
|
||||
export abstract class BaseAIProvider implements AIProvider {
|
||||
abstract name: string;
|
||||
|
||||
abstract search(
|
||||
query: string,
|
||||
skills: SearchableSkill[]
|
||||
): Promise<AISearchResult[]>;
|
||||
|
||||
abstract generateSkill(example: SkillExample): Promise<GeneratedSkill>;
|
||||
|
||||
protected buildSearchPrompt(query: string, skills: SearchableSkill[]): string {
|
||||
const skillsList = skills
|
||||
.map(
|
||||
(s, i) =>
|
||||
`${i + 1}. ${s.name}${s.description ? ` - ${s.description}` : ''}${s.tags ? ` [${s.tags.join(', ')}]` : ''}`
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
return `You are a skill search assistant. Given a user query and a list of available skills, identify the most relevant skills.
|
||||
|
||||
User Query: "${query}"
|
||||
|
||||
Available Skills:
|
||||
${skillsList}
|
||||
|
||||
For each relevant skill (up to 10), provide:
|
||||
1. Skill index number
|
||||
2. Relevance score (0-1)
|
||||
3. Brief reasoning
|
||||
|
||||
Format your response as JSON:
|
||||
[
|
||||
{
|
||||
"index": <number>,
|
||||
"relevance": <0-1>,
|
||||
"reasoning": "<explanation>"
|
||||
}
|
||||
]`;
|
||||
}
|
||||
|
||||
protected buildGeneratePrompt(example: SkillExample): string {
|
||||
let prompt = `You are a skill generation assistant. Generate a complete skill based on the following specification:
|
||||
|
||||
Description: ${example.description}`;
|
||||
|
||||
if (example.context) {
|
||||
prompt += `\n\nContext: ${example.context}`;
|
||||
}
|
||||
|
||||
if (example.codeExamples && example.codeExamples.length > 0) {
|
||||
prompt += `\n\nCode Examples:\n${example.codeExamples.map((code, i) => `Example ${i + 1}:\n\`\`\`\n${code}\n\`\`\``).join('\n\n')}`;
|
||||
}
|
||||
|
||||
if (example.expectedBehavior) {
|
||||
prompt += `\n\nExpected Behavior: ${example.expectedBehavior}`;
|
||||
}
|
||||
|
||||
prompt += `
|
||||
|
||||
Generate a skill in SKILL.md format with:
|
||||
1. Clear name (kebab-case)
|
||||
2. Comprehensive description
|
||||
3. Detailed instructions
|
||||
4. Relevant tags
|
||||
5. Usage examples if applicable
|
||||
|
||||
Format your response as JSON:
|
||||
{
|
||||
"name": "<skill-name>",
|
||||
"description": "<description>",
|
||||
"content": "<full SKILL.md content>",
|
||||
"tags": ["<tag1>", "<tag2>"],
|
||||
"confidence": <0-1>,
|
||||
"reasoning": "<why this skill design>"
|
||||
}`;
|
||||
|
||||
return prompt;
|
||||
}
|
||||
|
||||
protected parseSearchResponse(
|
||||
response: string,
|
||||
skills: SearchableSkill[]
|
||||
): AISearchResult[] {
|
||||
try {
|
||||
const parsed = JSON.parse(response);
|
||||
return parsed.map((item: any) => ({
|
||||
skill: skills[item.index - 1],
|
||||
relevance: item.relevance,
|
||||
reasoning: item.reasoning,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
protected parseGenerateResponse(response: string): GeneratedSkill {
|
||||
try {
|
||||
const parsed = JSON.parse(response);
|
||||
return {
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
content: parsed.content,
|
||||
tags: parsed.tags || [],
|
||||
confidence: parsed.confidence || 0.7,
|
||||
reasoning: parsed.reasoning || '',
|
||||
};
|
||||
} catch {
|
||||
throw new Error('Failed to parse skill generation response');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { BaseAIProvider } from './base.js';
|
||||
export { MockAIProvider } from './mock.js';
|
||||
@@ -0,0 +1,144 @@
|
||||
import { BaseAIProvider } from './base.js';
|
||||
import type {
|
||||
AISearchResult,
|
||||
GeneratedSkill,
|
||||
SearchableSkill,
|
||||
SkillExample,
|
||||
} from '../types.js';
|
||||
|
||||
export class MockAIProvider extends BaseAIProvider {
|
||||
name = 'mock';
|
||||
|
||||
async search(
|
||||
query: string,
|
||||
skills: SearchableSkill[]
|
||||
): Promise<AISearchResult[]> {
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const queryTerms = lowerQuery.split(/\s+/).filter((t) => t.length > 2);
|
||||
|
||||
return skills
|
||||
.map((skill) => {
|
||||
let relevance = 0;
|
||||
|
||||
const nameMatch = skill.name.toLowerCase().includes(lowerQuery);
|
||||
const descMatch = skill.description?.toLowerCase().includes(lowerQuery);
|
||||
const tagMatch = skill.tags?.some((t) =>
|
||||
t.toLowerCase().includes(lowerQuery)
|
||||
);
|
||||
const contentMatch = skill.content.toLowerCase().includes(lowerQuery);
|
||||
|
||||
// Also check individual terms
|
||||
const nameTermMatch = queryTerms.some((term) =>
|
||||
skill.name.toLowerCase().includes(term)
|
||||
);
|
||||
const descTermMatch = queryTerms.some(
|
||||
(term) => skill.description?.toLowerCase().includes(term)
|
||||
);
|
||||
const tagTermMatch = queryTerms.some((term) =>
|
||||
skill.tags?.some((t) => t.toLowerCase().includes(term))
|
||||
);
|
||||
|
||||
if (nameMatch) relevance += 0.5;
|
||||
if (descMatch) relevance += 0.3;
|
||||
if (tagMatch) relevance += 0.2;
|
||||
if (contentMatch) relevance += 0.1;
|
||||
|
||||
// Partial term matches
|
||||
if (!nameMatch && nameTermMatch) relevance += 0.3;
|
||||
if (!descMatch && descTermMatch) relevance += 0.2;
|
||||
if (!tagMatch && tagTermMatch) relevance += 0.15;
|
||||
|
||||
relevance = Math.min(1, relevance);
|
||||
|
||||
return {
|
||||
skill,
|
||||
relevance,
|
||||
reasoning: this.buildReasoning(
|
||||
nameMatch || nameTermMatch,
|
||||
descMatch || descTermMatch,
|
||||
tagMatch || tagTermMatch,
|
||||
contentMatch
|
||||
),
|
||||
};
|
||||
})
|
||||
.filter((r) => r.relevance > 0)
|
||||
.sort((a, b) => b.relevance - a.relevance)
|
||||
.slice(0, 10);
|
||||
}
|
||||
|
||||
async generateSkill(example: SkillExample): Promise<GeneratedSkill> {
|
||||
const name = this.generateName(example.description);
|
||||
const tags = this.generateTags(example.description);
|
||||
|
||||
return {
|
||||
name,
|
||||
description: example.description,
|
||||
content: this.generateContent(name, example),
|
||||
tags,
|
||||
confidence: 0.75,
|
||||
reasoning: 'Mock generated skill based on description and examples',
|
||||
};
|
||||
}
|
||||
|
||||
private buildReasoning(
|
||||
nameMatch: boolean,
|
||||
descMatch: boolean | undefined,
|
||||
tagMatch: boolean | undefined,
|
||||
contentMatch: boolean
|
||||
): string {
|
||||
const matches: string[] = [];
|
||||
if (nameMatch) matches.push('name');
|
||||
if (descMatch === true) matches.push('description');
|
||||
if (tagMatch === true) matches.push('tags');
|
||||
if (contentMatch) matches.push('content');
|
||||
|
||||
return matches.length > 0
|
||||
? `Matched in: ${matches.join(', ')}`
|
||||
: 'No significant matches';
|
||||
}
|
||||
|
||||
private generateName(description: string): string {
|
||||
return description
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s]/g, '')
|
||||
.split(/\s+/)
|
||||
.slice(0, 3)
|
||||
.join('-');
|
||||
}
|
||||
|
||||
private generateTags(description: string): string[] {
|
||||
const commonTags = ['productivity', 'automation', 'development'];
|
||||
if (description.toLowerCase().includes('test')) commonTags.push('testing');
|
||||
if (description.toLowerCase().includes('debug'))
|
||||
commonTags.push('debugging');
|
||||
if (description.toLowerCase().includes('code')) commonTags.push('coding');
|
||||
return commonTags.slice(0, 5);
|
||||
}
|
||||
|
||||
private generateContent(name: string, example: SkillExample): string {
|
||||
let content = `# ${name}\n\n${example.description}\n\n`;
|
||||
|
||||
if (example.context) {
|
||||
content += `## Context\n\n${example.context}\n\n`;
|
||||
}
|
||||
|
||||
content += `## Instructions\n\n`;
|
||||
content += `1. Review the task requirements\n`;
|
||||
content += `2. Implement the solution\n`;
|
||||
content += `3. Test the implementation\n`;
|
||||
content += `4. Document the changes\n\n`;
|
||||
|
||||
if (example.codeExamples && example.codeExamples.length > 0) {
|
||||
content += `## Examples\n\n`;
|
||||
example.codeExamples.forEach((code, i) => {
|
||||
content += `### Example ${i + 1}\n\n\`\`\`\n${code}\n\`\`\`\n\n`;
|
||||
});
|
||||
}
|
||||
|
||||
if (example.expectedBehavior) {
|
||||
content += `## Expected Behavior\n\n${example.expectedBehavior}\n`;
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type {
|
||||
AIProvider,
|
||||
AISearchOptions,
|
||||
AISearchResult,
|
||||
SearchableSkill,
|
||||
} from './types.js';
|
||||
|
||||
export class AISearch {
|
||||
constructor(private provider: AIProvider) {}
|
||||
|
||||
async search(
|
||||
query: string,
|
||||
skills: SearchableSkill[],
|
||||
options: AISearchOptions = {}
|
||||
): Promise<AISearchResult[]> {
|
||||
const {
|
||||
limit = 10,
|
||||
minRelevance = 0.5,
|
||||
includeReasoning = true,
|
||||
} = options;
|
||||
|
||||
const results = await this.provider.search(query, skills);
|
||||
|
||||
const filtered = results
|
||||
.filter((r) => r.relevance >= minRelevance)
|
||||
.slice(0, limit);
|
||||
|
||||
if (!includeReasoning) {
|
||||
filtered.forEach((r) => {
|
||||
r.reasoning = '';
|
||||
});
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
async searchByIntent(
|
||||
intent: string,
|
||||
skills: SearchableSkill[],
|
||||
options: AISearchOptions = {}
|
||||
): Promise<AISearchResult[]> {
|
||||
const enhancedQuery = `Find skills that help with: ${intent}. Consider the skill's purpose, capabilities, and use cases.`;
|
||||
return this.search(enhancedQuery, skills, options);
|
||||
}
|
||||
|
||||
async findSimilar(
|
||||
skill: SearchableSkill,
|
||||
allSkills: SearchableSkill[],
|
||||
options: AISearchOptions = {}
|
||||
): Promise<AISearchResult[]> {
|
||||
const query = `Find skills similar to "${skill.name}". ${skill.description ? `This skill: ${skill.description}` : ''}`;
|
||||
const filtered = allSkills.filter((s) => s.name !== skill.name);
|
||||
return this.search(query, filtered, options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
export interface AIProvider {
|
||||
name: string;
|
||||
search(query: string, skills: SearchableSkill[]): Promise<AISearchResult[]>;
|
||||
generateSkill(example: SkillExample): Promise<GeneratedSkill>;
|
||||
}
|
||||
|
||||
export interface SearchableSkill {
|
||||
name: string;
|
||||
description?: string;
|
||||
content: string;
|
||||
tags?: string[];
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface AISearchResult {
|
||||
skill: SearchableSkill;
|
||||
relevance: number;
|
||||
reasoning: string;
|
||||
}
|
||||
|
||||
export interface SkillExample {
|
||||
description: string;
|
||||
context?: string;
|
||||
codeExamples?: string[];
|
||||
expectedBehavior?: string;
|
||||
targetAgent?: string;
|
||||
}
|
||||
|
||||
export interface GeneratedSkill {
|
||||
name: string;
|
||||
description: string;
|
||||
content: string;
|
||||
tags: string[];
|
||||
confidence: number;
|
||||
reasoning: string;
|
||||
}
|
||||
|
||||
export interface AIConfig {
|
||||
provider: 'anthropic' | 'openai' | 'none';
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
maxTokens?: number;
|
||||
temperature?: number;
|
||||
}
|
||||
|
||||
export interface AISearchOptions {
|
||||
limit?: number;
|
||||
minRelevance?: number;
|
||||
includeReasoning?: boolean;
|
||||
}
|
||||
|
||||
export interface AIGenerateOptions {
|
||||
targetAgent?: string;
|
||||
includeTests?: boolean;
|
||||
includeDocumentation?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fs } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { AuditLogger } from '../logger.js';
|
||||
|
||||
describe('AuditLogger', () => {
|
||||
let logger: AuditLogger;
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = join(tmpdir(), `skillkit-audit-test-${Date.now()}`);
|
||||
await fs.mkdir(tempDir, { recursive: true });
|
||||
logger = new AuditLogger(tempDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await logger.destroy();
|
||||
try {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
});
|
||||
|
||||
describe('log', () => {
|
||||
it('should log an event', async () => {
|
||||
await logger.log(
|
||||
'skill.install',
|
||||
'install',
|
||||
'test-skill',
|
||||
{ source: 'github' },
|
||||
true
|
||||
);
|
||||
|
||||
await logger.flush();
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events.length).toBe(1);
|
||||
expect(events[0].type).toBe('skill.install');
|
||||
expect(events[0].action).toBe('install');
|
||||
expect(events[0].resource).toBe('test-skill');
|
||||
expect(events[0].success).toBe(true);
|
||||
});
|
||||
|
||||
it('should log failure event', async () => {
|
||||
await logger.log(
|
||||
'skill.install',
|
||||
'install',
|
||||
'test-skill',
|
||||
{},
|
||||
false,
|
||||
'Network error'
|
||||
);
|
||||
|
||||
await logger.flush();
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events[0].success).toBe(false);
|
||||
expect(events[0].error).toBe('Network error');
|
||||
});
|
||||
|
||||
it('should log event with duration', async () => {
|
||||
await logger.log(
|
||||
'skill.execute',
|
||||
'execute',
|
||||
'test-skill',
|
||||
{},
|
||||
true,
|
||||
undefined,
|
||||
1234
|
||||
);
|
||||
|
||||
await logger.flush();
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events[0].duration).toBe(1234);
|
||||
});
|
||||
|
||||
it('should auto-flush when buffer reaches limit', async () => {
|
||||
for (let i = 0; i < 15; i++) {
|
||||
await logger.log(
|
||||
'skill.sync',
|
||||
'sync',
|
||||
`skill-${i}`,
|
||||
{},
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('query', () => {
|
||||
beforeEach(async () => {
|
||||
await logger.log('skill.install', 'install', 'skill-1', {}, true);
|
||||
await logger.log('skill.uninstall', 'uninstall', 'skill-2', {}, true);
|
||||
await logger.log('team.create', 'create', 'team-1', {}, true);
|
||||
await logger.log('skill.install', 'install', 'skill-3', {}, false, 'Error');
|
||||
await logger.flush();
|
||||
});
|
||||
|
||||
it('should query all events', async () => {
|
||||
const events = await logger.query();
|
||||
expect(events.length).toBe(4);
|
||||
});
|
||||
|
||||
it('should filter by type', async () => {
|
||||
const events = await logger.query({
|
||||
types: ['skill.install'],
|
||||
});
|
||||
|
||||
expect(events.length).toBe(2);
|
||||
events.forEach((e) => {
|
||||
expect(e.type).toBe('skill.install');
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter by success', async () => {
|
||||
const events = await logger.query({
|
||||
success: true,
|
||||
});
|
||||
|
||||
expect(events.length).toBe(3);
|
||||
events.forEach((e) => {
|
||||
expect(e.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter by resource', async () => {
|
||||
const events = await logger.query({
|
||||
resource: 'skill-1',
|
||||
});
|
||||
|
||||
expect(events.length).toBe(1);
|
||||
expect(events[0].resource).toBe('skill-1');
|
||||
});
|
||||
|
||||
it('should filter by date range', async () => {
|
||||
const startDate = new Date(Date.now() - 1000);
|
||||
const endDate = new Date(Date.now() + 1000);
|
||||
|
||||
const events = await logger.query({
|
||||
startDate,
|
||||
endDate,
|
||||
});
|
||||
|
||||
expect(events.length).toBe(4);
|
||||
});
|
||||
|
||||
it('should respect limit', async () => {
|
||||
const events = await logger.query({
|
||||
limit: 2,
|
||||
});
|
||||
|
||||
expect(events.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should respect offset', async () => {
|
||||
const events = await logger.query({
|
||||
offset: 2,
|
||||
});
|
||||
|
||||
expect(events.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stats', () => {
|
||||
beforeEach(async () => {
|
||||
await logger.log('skill.install', 'install', 'skill-1', {}, true);
|
||||
await logger.log('skill.install', 'install', 'skill-2', {}, true);
|
||||
await logger.log('skill.install', 'install', 'skill-3', {}, false, 'Error');
|
||||
await logger.log('team.create', 'create', 'team-1', {}, true);
|
||||
await logger.flush();
|
||||
});
|
||||
|
||||
it('should calculate stats', async () => {
|
||||
const stats = await logger.stats();
|
||||
|
||||
expect(stats.totalEvents).toBe(4);
|
||||
expect(stats.successRate).toBe(0.75); // 3 out of 4
|
||||
expect(stats.eventsByType['skill.install']).toBe(3);
|
||||
expect(stats.eventsByType['team.create']).toBe(1);
|
||||
});
|
||||
|
||||
it('should include recent errors', async () => {
|
||||
const stats = await logger.stats();
|
||||
|
||||
expect(stats.recentErrors.length).toBe(1);
|
||||
expect(stats.recentErrors[0].error).toBe('Error');
|
||||
});
|
||||
|
||||
it('should include top resources', async () => {
|
||||
const stats = await logger.stats();
|
||||
|
||||
expect(stats.topResources.length).toBeGreaterThan(0);
|
||||
expect(stats.topResources[0].count).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('export', () => {
|
||||
beforeEach(async () => {
|
||||
await logger.log('skill.install', 'install', 'skill-1', {}, true);
|
||||
await logger.log('team.create', 'create', 'team-1', {}, true);
|
||||
await logger.flush();
|
||||
});
|
||||
|
||||
it('should export to JSON', async () => {
|
||||
const content = await logger.export({ format: 'json' });
|
||||
|
||||
const parsed = JSON.parse(content);
|
||||
expect(Array.isArray(parsed)).toBe(true);
|
||||
expect(parsed.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should export to CSV', async () => {
|
||||
const content = await logger.export({ format: 'csv' });
|
||||
|
||||
expect(content).toContain('ID,Timestamp,Type');
|
||||
expect(content).toContain('skill.install');
|
||||
expect(content).toContain('team.create');
|
||||
});
|
||||
|
||||
it('should export to text', async () => {
|
||||
const content = await logger.export({ format: 'text' });
|
||||
|
||||
expect(content).toContain('skill.install');
|
||||
expect(content).toContain('SUCCESS');
|
||||
});
|
||||
|
||||
it('should export with query filter', async () => {
|
||||
const content = await logger.export({
|
||||
format: 'json',
|
||||
query: { types: ['skill.install'] },
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.length).toBe(1);
|
||||
expect(parsed[0].type).toBe('skill.install');
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
beforeEach(async () => {
|
||||
const oldDate = new Date(Date.now() - 1000 * 60 * 60 * 24 * 40);
|
||||
const recentDate = new Date();
|
||||
|
||||
await logger.log('skill.install', 'install', 'old-skill', {}, true);
|
||||
await logger.flush();
|
||||
|
||||
const events = await logger.query();
|
||||
events[0].timestamp = oldDate;
|
||||
|
||||
const logFile = join(tempDir, 'audit.log');
|
||||
const content = events.map((e) => JSON.stringify(e)).join('\n');
|
||||
await fs.writeFile(logFile, content, 'utf-8');
|
||||
|
||||
await logger.log('skill.install', 'install', 'new-skill', {}, true);
|
||||
await logger.flush();
|
||||
});
|
||||
|
||||
it('should clear old entries', async () => {
|
||||
const cutoffDate = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30);
|
||||
const cleared = await logger.clear(cutoffDate);
|
||||
|
||||
expect(cleared).toBeGreaterThan(0);
|
||||
|
||||
const events = await logger.query();
|
||||
events.forEach((e) => {
|
||||
expect(e.timestamp.getTime()).toBeGreaterThanOrEqual(
|
||||
cutoffDate.getTime()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear all entries when no date provided', async () => {
|
||||
const cleared = await logger.clear();
|
||||
|
||||
expect(cleared).toBeGreaterThan(0);
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flush', () => {
|
||||
it('should persist buffered events', async () => {
|
||||
await logger.log('skill.install', 'install', 'skill-1', {}, true);
|
||||
|
||||
// Don't auto-flush
|
||||
let events = await logger.query();
|
||||
expect(events.length).toBe(0);
|
||||
|
||||
await logger.flush();
|
||||
|
||||
events = await logger.query();
|
||||
expect(events.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle empty buffer', async () => {
|
||||
await logger.flush();
|
||||
|
||||
const events = await logger.query();
|
||||
expect(events.length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './types.js';
|
||||
export * from './logger.js';
|
||||
@@ -0,0 +1,293 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import type {
|
||||
AuditEvent,
|
||||
AuditEventType,
|
||||
AuditQuery,
|
||||
AuditStats,
|
||||
AuditExportOptions,
|
||||
} from './types.js';
|
||||
|
||||
export class AuditLogger {
|
||||
private logFile: string;
|
||||
private buffer: AuditEvent[] = [];
|
||||
private flushInterval: NodeJS.Timeout | null = null;
|
||||
private flushing: Promise<void> | null = null;
|
||||
|
||||
constructor(logDir: string) {
|
||||
this.logFile = path.join(logDir, 'audit.log');
|
||||
this.startAutoFlush();
|
||||
}
|
||||
|
||||
async log(
|
||||
type: AuditEventType,
|
||||
action: string,
|
||||
resource: string,
|
||||
details?: Record<string, unknown>,
|
||||
success: boolean = true,
|
||||
error?: string,
|
||||
duration?: number
|
||||
): Promise<void> {
|
||||
const event: AuditEvent = {
|
||||
id: this.generateId(),
|
||||
timestamp: new Date(),
|
||||
type,
|
||||
user: process.env.USER || 'unknown',
|
||||
action,
|
||||
resource,
|
||||
details,
|
||||
success,
|
||||
error,
|
||||
duration,
|
||||
};
|
||||
|
||||
this.buffer.push(event);
|
||||
|
||||
if (this.buffer.length >= 10) {
|
||||
await this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
async query(query: AuditQuery = {}): Promise<AuditEvent[]> {
|
||||
const events = await this.loadEvents();
|
||||
return this.filterEvents(events, query);
|
||||
}
|
||||
|
||||
async stats(): Promise<AuditStats> {
|
||||
const events = await this.loadEvents();
|
||||
|
||||
const totalEvents = events.length;
|
||||
const successEvents = events.filter((e) => e.success).length;
|
||||
const successRate = totalEvents > 0 ? successEvents / totalEvents : 0;
|
||||
|
||||
const eventsByType: Record<AuditEventType, number> = {} as any;
|
||||
events.forEach((e) => {
|
||||
eventsByType[e.type] = (eventsByType[e.type] || 0) + 1;
|
||||
});
|
||||
|
||||
const recentErrors = events
|
||||
.filter((e) => !e.success)
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
|
||||
.slice(0, 10);
|
||||
|
||||
const resourceCounts = new Map<string, number>();
|
||||
events.forEach((e) => {
|
||||
resourceCounts.set(e.resource, (resourceCounts.get(e.resource) || 0) + 1);
|
||||
});
|
||||
|
||||
const topResources = Array.from(resourceCounts.entries())
|
||||
.map(([resource, count]) => ({ resource, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 10);
|
||||
|
||||
return {
|
||||
totalEvents,
|
||||
successRate,
|
||||
eventsByType,
|
||||
recentErrors,
|
||||
topResources,
|
||||
};
|
||||
}
|
||||
|
||||
async export(options: AuditExportOptions): Promise<string> {
|
||||
const events = await this.query(options.query);
|
||||
|
||||
switch (options.format) {
|
||||
case 'json':
|
||||
return JSON.stringify(events, null, 2);
|
||||
case 'csv':
|
||||
return this.toCsv(events);
|
||||
case 'text':
|
||||
return this.toText(events);
|
||||
default:
|
||||
return JSON.stringify(events, null, 2);
|
||||
}
|
||||
}
|
||||
|
||||
async clear(olderThan?: Date): Promise<number> {
|
||||
const events = await this.loadEvents();
|
||||
|
||||
const filtered = olderThan
|
||||
? events.filter((e) => e.timestamp >= olderThan)
|
||||
: [];
|
||||
|
||||
await this.saveEvents(filtered);
|
||||
|
||||
return events.length - filtered.length;
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
// If already flushing, wait for it to complete
|
||||
if (this.flushing) {
|
||||
return this.flushing;
|
||||
}
|
||||
|
||||
if (this.buffer.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Start flush with mutex
|
||||
this.flushing = this.doFlush();
|
||||
try {
|
||||
await this.flushing;
|
||||
} finally {
|
||||
this.flushing = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async doFlush(): Promise<void> {
|
||||
// Snapshot buffer and clear it before async operations
|
||||
const toFlush = this.buffer;
|
||||
this.buffer = [];
|
||||
|
||||
try {
|
||||
const events = await this.loadEvents();
|
||||
events.push(...toFlush);
|
||||
await this.saveEvents(events);
|
||||
} catch (error) {
|
||||
// Restore events on failure
|
||||
this.buffer = [...toFlush, ...this.buffer];
|
||||
console.error('Failed to flush audit log:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
if (this.flushInterval) {
|
||||
clearInterval(this.flushInterval);
|
||||
this.flushInterval = null;
|
||||
}
|
||||
await this.flush();
|
||||
}
|
||||
|
||||
private startAutoFlush(): void {
|
||||
this.flushInterval = setInterval(
|
||||
() => {
|
||||
this.flush().catch(console.error);
|
||||
},
|
||||
30000
|
||||
);
|
||||
}
|
||||
|
||||
private async loadEvents(): Promise<AuditEvent[]> {
|
||||
try {
|
||||
const content = await fs.readFile(this.logFile, 'utf-8');
|
||||
const events: AuditEvent[] = [];
|
||||
|
||||
for (const line of content.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
|
||||
try {
|
||||
const event = JSON.parse(line);
|
||||
event.timestamp = new Date(event.timestamp);
|
||||
events.push(event);
|
||||
} catch (error) {
|
||||
// Skip malformed lines silently to prevent data loss
|
||||
// Malformed lines are ignored, valid events are preserved
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
} catch (error) {
|
||||
// Only propagate genuine filesystem errors
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw error;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private async saveEvents(events: AuditEvent[]): Promise<void> {
|
||||
const dir = path.dirname(this.logFile);
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
const content = events.map((e) => JSON.stringify(e)).join('\n');
|
||||
await fs.writeFile(this.logFile, content, 'utf-8');
|
||||
}
|
||||
|
||||
private filterEvents(events: AuditEvent[], query: AuditQuery): AuditEvent[] {
|
||||
let filtered = events;
|
||||
|
||||
if (query.types && query.types.length > 0) {
|
||||
filtered = filtered.filter((e) => query.types!.includes(e.type));
|
||||
}
|
||||
|
||||
if (query.user) {
|
||||
filtered = filtered.filter((e) => e.user === query.user);
|
||||
}
|
||||
|
||||
if (query.resource) {
|
||||
filtered = filtered.filter((e) =>
|
||||
e.resource.toLowerCase().includes(query.resource!.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
if (query.startDate) {
|
||||
filtered = filtered.filter((e) => e.timestamp >= query.startDate!);
|
||||
}
|
||||
|
||||
if (query.endDate) {
|
||||
filtered = filtered.filter((e) => e.timestamp <= query.endDate!);
|
||||
}
|
||||
|
||||
if (query.success !== undefined) {
|
||||
filtered = filtered.filter((e) => e.success === query.success);
|
||||
}
|
||||
|
||||
filtered.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
|
||||
|
||||
if (query.offset !== undefined && query.offset !== null) {
|
||||
filtered = filtered.slice(query.offset);
|
||||
}
|
||||
|
||||
if (query.limit !== undefined && query.limit !== null) {
|
||||
filtered = filtered.slice(0, query.limit);
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
private generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
||||
}
|
||||
|
||||
private toCsv(events: AuditEvent[]): string {
|
||||
const headers = [
|
||||
'ID',
|
||||
'Timestamp',
|
||||
'Type',
|
||||
'User',
|
||||
'Action',
|
||||
'Resource',
|
||||
'Success',
|
||||
'Error',
|
||||
'Duration',
|
||||
];
|
||||
|
||||
const rows = events.map((e) => [
|
||||
e.id,
|
||||
e.timestamp.toISOString(),
|
||||
e.type,
|
||||
e.user || '',
|
||||
e.action,
|
||||
e.resource,
|
||||
e.success ? 'true' : 'false',
|
||||
e.error || '',
|
||||
e.duration?.toString() || '',
|
||||
]);
|
||||
|
||||
return [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
|
||||
}
|
||||
|
||||
private toText(events: AuditEvent[]): string {
|
||||
return events
|
||||
.map((e) => {
|
||||
let text = `[${e.timestamp.toISOString()}] ${e.type} - ${e.action} on ${e.resource}`;
|
||||
if (e.user) text += ` by ${e.user}`;
|
||||
text += ` (${e.success ? 'SUCCESS' : 'FAILED'})`;
|
||||
if (e.error) text += `\n Error: ${e.error}`;
|
||||
if (e.duration) text += `\n Duration: ${e.duration}ms`;
|
||||
return text;
|
||||
})
|
||||
.join('\n\n');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
export type AuditEventType =
|
||||
| 'skill.install'
|
||||
| 'skill.uninstall'
|
||||
| 'skill.sync'
|
||||
| 'skill.translate'
|
||||
| 'skill.execute'
|
||||
| 'team.create'
|
||||
| 'team.share'
|
||||
| 'team.import'
|
||||
| 'team.sync'
|
||||
| 'bundle.create'
|
||||
| 'bundle.export'
|
||||
| 'bundle.import'
|
||||
| 'plugin.install'
|
||||
| 'plugin.uninstall'
|
||||
| 'plugin.enable'
|
||||
| 'plugin.disable'
|
||||
| 'workflow.execute'
|
||||
| 'ai.search'
|
||||
| 'ai.generate';
|
||||
|
||||
export interface AuditEvent {
|
||||
id: string;
|
||||
timestamp: Date;
|
||||
type: AuditEventType;
|
||||
user?: string;
|
||||
action: string;
|
||||
resource: string;
|
||||
details?: Record<string, unknown>;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export interface AuditQuery {
|
||||
types?: AuditEventType[];
|
||||
user?: string;
|
||||
resource?: string;
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
success?: boolean;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export interface AuditStats {
|
||||
totalEvents: number;
|
||||
successRate: number;
|
||||
eventsByType: Record<AuditEventType, number>;
|
||||
recentErrors: AuditEvent[];
|
||||
topResources: Array<{ resource: string; count: number }>;
|
||||
}
|
||||
|
||||
export interface AuditExportOptions {
|
||||
format: 'json' | 'csv' | 'text';
|
||||
query?: AuditQuery;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* CI/CD Integration Module
|
||||
*
|
||||
* Provides templates and utilities for integrating skill validation
|
||||
* into CI/CD pipelines.
|
||||
*/
|
||||
|
||||
export * from './templates.js';
|
||||
|
||||
export {
|
||||
GITHUB_ACTION_TEMPLATE,
|
||||
PRE_COMMIT_HOOK_TEMPLATE,
|
||||
PRE_COMMIT_CONFIG_TEMPLATE,
|
||||
GITLAB_CI_TEMPLATE,
|
||||
CIRCLECI_CONFIG_TEMPLATE,
|
||||
getCICDTemplate,
|
||||
listCICDTemplates,
|
||||
} from './templates.js';
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* CI/CD Templates
|
||||
*
|
||||
* Provides templates for GitHub Actions, pre-commit hooks, and other CI/CD integrations.
|
||||
*/
|
||||
|
||||
/**
|
||||
* GitHub Action workflow for skill validation
|
||||
*/
|
||||
export const GITHUB_ACTION_TEMPLATE = `# Skill Validation Workflow
|
||||
# This workflow validates skills in your repository
|
||||
|
||||
name: Validate Skills
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
- 'skills/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
- 'skills/**'
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Validate Skills
|
||||
run: skillkit validate
|
||||
|
||||
- name: Run Skill Tests
|
||||
run: skillkit test --json > test-results.json
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Test Results
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: skill-test-results
|
||||
path: test-results.json
|
||||
retention-days: 30
|
||||
|
||||
- name: Check Test Results
|
||||
run: |
|
||||
if [ -f test-results.json ]; then
|
||||
passed=$(cat test-results.json | jq -r '.passed')
|
||||
if [ "$passed" = "false" ]; then
|
||||
echo "Some skill tests failed"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
`;
|
||||
|
||||
/**
|
||||
* Pre-commit hook script for skill validation
|
||||
*/
|
||||
export const PRE_COMMIT_HOOK_TEMPLATE = `#!/bin/bash
|
||||
# SkillKit Pre-commit Hook
|
||||
# Validates skills before commit
|
||||
|
||||
# Colors for output
|
||||
RED='\\033[0;31m'
|
||||
GREEN='\\033[0;32m'
|
||||
YELLOW='\\033[0;33m'
|
||||
NC='\\033[0m' # No Color
|
||||
|
||||
echo -e "\${YELLOW}Running SkillKit validation...\${NC}"
|
||||
|
||||
# Check if skillkit is installed
|
||||
if ! command -v skillkit &> /dev/null; then
|
||||
echo -e "\${RED}SkillKit not found. Install with: npm install -g skillkit\${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get list of staged skill files
|
||||
SKILL_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\.(md|mdc)$' | grep -E '(skills|.claude|.cursor)')
|
||||
|
||||
if [ -z "$SKILL_FILES" ]; then
|
||||
echo -e "\${GREEN}No skill files staged, skipping validation.\${NC}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Validating skill files:"
|
||||
echo "$SKILL_FILES"
|
||||
|
||||
# Run validation
|
||||
if ! skillkit validate; then
|
||||
echo -e "\${RED}Skill validation failed. Please fix the errors and try again.\${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run tests if any
|
||||
if skillkit test --json 2>/dev/null | jq -e '.passed == false' > /dev/null 2>&1; then
|
||||
echo -e "\${RED}Skill tests failed. Please fix the failing tests.\${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "\${GREEN}All skills validated successfully!\${NC}"
|
||||
exit 0
|
||||
`;
|
||||
|
||||
/**
|
||||
* Pre-commit config for .pre-commit-config.yaml
|
||||
*/
|
||||
export const PRE_COMMIT_CONFIG_TEMPLATE = `# SkillKit Pre-commit Configuration
|
||||
# Add this to your .pre-commit-config.yaml
|
||||
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: skillkit-validate
|
||||
name: SkillKit Validate
|
||||
entry: skillkit validate
|
||||
language: system
|
||||
files: \\.(md|mdc)$
|
||||
pass_filenames: false
|
||||
|
||||
- id: skillkit-test
|
||||
name: SkillKit Test
|
||||
entry: skillkit test
|
||||
language: system
|
||||
files: \\.(md|mdc)$
|
||||
pass_filenames: false
|
||||
`;
|
||||
|
||||
/**
|
||||
* GitLab CI template
|
||||
*/
|
||||
export const GITLAB_CI_TEMPLATE = `# SkillKit GitLab CI Configuration
|
||||
# Add this to your .gitlab-ci.yml
|
||||
|
||||
skill-validation:
|
||||
image: node:20
|
||||
stage: test
|
||||
before_script:
|
||||
- npm install -g skillkit
|
||||
script:
|
||||
- skillkit validate
|
||||
- skillkit test --json > test-results.json
|
||||
artifacts:
|
||||
# Note: test-results.json is JSON format, not JUnit XML
|
||||
paths:
|
||||
- test-results.json
|
||||
expire_in: 30 days
|
||||
rules:
|
||||
- changes:
|
||||
- ".claude/skills/**"
|
||||
- ".cursor/skills/**"
|
||||
- "skills/**"
|
||||
`;
|
||||
|
||||
/**
|
||||
* CircleCI config template
|
||||
*/
|
||||
export const CIRCLECI_CONFIG_TEMPLATE = `# SkillKit CircleCI Configuration
|
||||
# Add this to your .circleci/config.yml
|
||||
|
||||
version: 2.1
|
||||
|
||||
jobs:
|
||||
validate-skills:
|
||||
docker:
|
||||
- image: cimg/node:20.0
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Validate Skills
|
||||
command: skillkit validate
|
||||
- run:
|
||||
name: Run Skill Tests
|
||||
command: skillkit test --json > test-results.json
|
||||
- store_artifacts:
|
||||
path: test-results.json
|
||||
destination: skill-tests
|
||||
|
||||
workflows:
|
||||
skill-validation:
|
||||
jobs:
|
||||
- validate-skills:
|
||||
filters:
|
||||
branches:
|
||||
only: /.*/
|
||||
`;
|
||||
|
||||
/**
|
||||
* Get a CI/CD template by name
|
||||
*/
|
||||
export function getCICDTemplate(name: string): string | null {
|
||||
switch (name.toLowerCase()) {
|
||||
case 'github':
|
||||
case 'github-action':
|
||||
case 'github-actions':
|
||||
return GITHUB_ACTION_TEMPLATE;
|
||||
case 'pre-commit':
|
||||
case 'pre-commit-hook':
|
||||
return PRE_COMMIT_HOOK_TEMPLATE;
|
||||
case 'pre-commit-config':
|
||||
return PRE_COMMIT_CONFIG_TEMPLATE;
|
||||
case 'gitlab':
|
||||
case 'gitlab-ci':
|
||||
return GITLAB_CI_TEMPLATE;
|
||||
case 'circleci':
|
||||
case 'circle-ci':
|
||||
return CIRCLECI_CONFIG_TEMPLATE;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List available CI/CD templates
|
||||
*/
|
||||
export function listCICDTemplates(): { name: string; description: string }[] {
|
||||
return [
|
||||
{ name: 'github-action', description: 'GitHub Actions workflow for skill validation' },
|
||||
{ name: 'pre-commit-hook', description: 'Git pre-commit hook script' },
|
||||
{ name: 'pre-commit-config', description: 'pre-commit framework configuration' },
|
||||
{ name: 'gitlab-ci', description: 'GitLab CI configuration' },
|
||||
{ name: 'circleci', description: 'CircleCI configuration' },
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
/**
|
||||
* Commands Module Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import {
|
||||
CommandRegistry,
|
||||
createCommandRegistry,
|
||||
CommandGenerator,
|
||||
createCommandGenerator,
|
||||
getAgentFormat,
|
||||
supportsSlashCommands,
|
||||
} from '../index.js';
|
||||
import type { SlashCommand, CommandContext, AgentType } from '../types.js';
|
||||
|
||||
describe('CommandRegistry', () => {
|
||||
let registry: CommandRegistry;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = createCommandRegistry({ allowOverrides: true });
|
||||
});
|
||||
|
||||
describe('register', () => {
|
||||
it('should register a valid command', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
registry.register(command);
|
||||
|
||||
expect(registry.has('test-cmd')).toBe(true);
|
||||
expect(registry.size).toBe(1);
|
||||
});
|
||||
|
||||
it('should register command with aliases', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
aliases: ['tc', 'test'],
|
||||
};
|
||||
|
||||
registry.register(command);
|
||||
|
||||
expect(registry.has('test-cmd')).toBe(true);
|
||||
expect(registry.has('tc')).toBe(true);
|
||||
expect(registry.has('test')).toBe(true);
|
||||
});
|
||||
|
||||
it('should throw on duplicate command without override', () => {
|
||||
const strictRegistry = createCommandRegistry({ allowOverrides: false });
|
||||
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
strictRegistry.register(command);
|
||||
|
||||
expect(() => strictRegistry.register(command)).toThrow('Command already registered');
|
||||
});
|
||||
|
||||
it('should allow override when enabled', () => {
|
||||
const command1: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'First version',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
const command2: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Second version',
|
||||
skill: 'test-skill-2',
|
||||
};
|
||||
|
||||
registry.register(command1);
|
||||
registry.register(command2);
|
||||
|
||||
expect(registry.get('test-cmd')?.description).toBe('Second version');
|
||||
});
|
||||
|
||||
it('should validate command on register', () => {
|
||||
const invalidCommand: SlashCommand = {
|
||||
name: '', // Invalid: empty name
|
||||
description: 'Test',
|
||||
skill: 'test',
|
||||
};
|
||||
|
||||
expect(() => registry.register(invalidCommand)).toThrow('Invalid command');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unregister', () => {
|
||||
it('should unregister a command', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
aliases: ['tc'],
|
||||
};
|
||||
|
||||
registry.register(command);
|
||||
expect(registry.has('test-cmd')).toBe(true);
|
||||
|
||||
const result = registry.unregister('test-cmd');
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(registry.has('test-cmd')).toBe(false);
|
||||
expect(registry.has('tc')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for non-existent command', () => {
|
||||
const result = registry.unregister('non-existent');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('get', () => {
|
||||
it('should get command by name', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
registry.register(command);
|
||||
|
||||
const result = registry.get('test-cmd');
|
||||
expect(result?.name).toBe('test-cmd');
|
||||
});
|
||||
|
||||
it('should get command by alias', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
aliases: ['tc'],
|
||||
};
|
||||
|
||||
registry.register(command);
|
||||
|
||||
const result = registry.get('tc');
|
||||
expect(result?.name).toBe('test-cmd');
|
||||
});
|
||||
|
||||
it('should return undefined for non-existent command', () => {
|
||||
const result = registry.get('non-existent');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
beforeEach(() => {
|
||||
registry.register({
|
||||
name: 'test-one',
|
||||
description: 'First test command',
|
||||
skill: 'skill-one',
|
||||
category: 'testing',
|
||||
tags: ['test', 'one'],
|
||||
});
|
||||
registry.register({
|
||||
name: 'test-two',
|
||||
description: 'Second test command',
|
||||
skill: 'skill-two',
|
||||
category: 'testing',
|
||||
tags: ['test', 'two'],
|
||||
});
|
||||
registry.register({
|
||||
name: 'deploy',
|
||||
description: 'Deploy command',
|
||||
skill: 'deploy-skill',
|
||||
category: 'deployment',
|
||||
tags: ['deploy'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should search by query', () => {
|
||||
const results = registry.search({ query: 'test' });
|
||||
expect(results).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should search by category', () => {
|
||||
const results = registry.search({ category: 'testing' });
|
||||
expect(results).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should search by tags', () => {
|
||||
const results = registry.search({ tags: ['deploy'] });
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].name).toBe('deploy');
|
||||
});
|
||||
|
||||
it('should limit results', () => {
|
||||
const results = registry.search({ limit: 1 });
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enable/disable', () => {
|
||||
it('should disable a command', () => {
|
||||
registry.register({
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
});
|
||||
|
||||
registry.disable('test-cmd');
|
||||
|
||||
const cmd = registry.get('test-cmd');
|
||||
expect(cmd?.enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('should enable a command', () => {
|
||||
registry.register({
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
});
|
||||
|
||||
registry.disable('test-cmd');
|
||||
registry.enable('test-cmd');
|
||||
|
||||
const cmd = registry.get('test-cmd');
|
||||
expect(cmd?.enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should execute command with handler', async () => {
|
||||
registry.register(
|
||||
{
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
},
|
||||
async () => ({
|
||||
success: true,
|
||||
output: 'Executed',
|
||||
})
|
||||
);
|
||||
|
||||
const context: Omit<CommandContext, 'command'> = {
|
||||
args: {},
|
||||
agent: 'claude-code' as AgentType,
|
||||
cwd: '/test',
|
||||
};
|
||||
|
||||
const result = await registry.execute('test-cmd', context);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.output).toBe('Executed');
|
||||
});
|
||||
|
||||
it('should return error for non-existent command', async () => {
|
||||
const result = await registry.execute('non-existent', {
|
||||
args: {},
|
||||
agent: 'claude-code' as AgentType,
|
||||
cwd: '/test',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('not found');
|
||||
});
|
||||
|
||||
it('should return error for disabled command', async () => {
|
||||
registry.register({
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
});
|
||||
registry.disable('test-cmd');
|
||||
|
||||
const result = await registry.execute('test-cmd', {
|
||||
args: {},
|
||||
agent: 'claude-code' as AgentType,
|
||||
cwd: '/test',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('disabled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validate', () => {
|
||||
it('should validate valid command', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
examples: ['/test-cmd'],
|
||||
};
|
||||
|
||||
const result = registry.validate(command);
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should reject command without name', () => {
|
||||
const command: SlashCommand = {
|
||||
name: '',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
const result = registry.validate(command);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain('Command must have a name');
|
||||
});
|
||||
|
||||
it('should reject command with invalid name format', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'INVALID_NAME',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
const result = registry.validate(command);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
});
|
||||
|
||||
it('should warn about missing examples', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
};
|
||||
|
||||
const result = registry.validate(command);
|
||||
|
||||
expect(result.warnings).toContain('Command has no usage examples');
|
||||
});
|
||||
});
|
||||
|
||||
describe('export/import', () => {
|
||||
it('should export commands to bundle', () => {
|
||||
registry.register({
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
});
|
||||
|
||||
const bundle = registry.export();
|
||||
|
||||
expect(bundle.version).toBe('1.0.0');
|
||||
expect(bundle.commands).toHaveLength(1);
|
||||
expect(bundle.commands[0].name).toBe('test-cmd');
|
||||
});
|
||||
|
||||
it('should import commands from bundle', () => {
|
||||
const bundle = {
|
||||
version: '1.0.0',
|
||||
commands: [
|
||||
{
|
||||
name: 'imported-cmd',
|
||||
description: 'Imported command',
|
||||
skill: 'imported-skill',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const imported = registry.import(bundle);
|
||||
|
||||
expect(imported).toBe(1);
|
||||
expect(registry.has('imported-cmd')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCategories', () => {
|
||||
it('should return unique categories', () => {
|
||||
registry.register({
|
||||
name: 'cmd-one',
|
||||
description: 'Command one',
|
||||
skill: 'skill',
|
||||
category: 'testing',
|
||||
});
|
||||
registry.register({
|
||||
name: 'cmd-two',
|
||||
description: 'Command two',
|
||||
skill: 'skill',
|
||||
category: 'debugging',
|
||||
});
|
||||
registry.register({
|
||||
name: 'cmd-three',
|
||||
description: 'Command three',
|
||||
skill: 'skill',
|
||||
category: 'testing',
|
||||
});
|
||||
|
||||
const categories = registry.getCategories();
|
||||
|
||||
expect(categories).toHaveLength(2);
|
||||
expect(categories).toContain('testing');
|
||||
expect(categories).toContain('debugging');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('CommandGenerator', () => {
|
||||
let generator: CommandGenerator;
|
||||
|
||||
beforeEach(() => {
|
||||
generator = createCommandGenerator();
|
||||
});
|
||||
|
||||
describe('fromSkill', () => {
|
||||
it('should generate command from skill', () => {
|
||||
const skill = {
|
||||
name: 'Test Skill',
|
||||
description: 'A test skill',
|
||||
content: 'Test content',
|
||||
tags: ['test'],
|
||||
};
|
||||
|
||||
const command = generator.fromSkill(skill);
|
||||
|
||||
expect(command.name).toBe('test-skill');
|
||||
expect(command.description).toBe('A test skill');
|
||||
expect(command.skill).toBe('Test Skill');
|
||||
});
|
||||
|
||||
it('should use custom command name', () => {
|
||||
const skill = {
|
||||
name: 'Test Skill',
|
||||
description: 'A test skill',
|
||||
content: 'Test content',
|
||||
};
|
||||
|
||||
const command = generator.fromSkill(skill, 'custom-name');
|
||||
|
||||
expect(command.name).toBe('custom-name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateClaudeCommand', () => {
|
||||
it('should generate Claude Code command file', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
aliases: ['tc'],
|
||||
examples: ['/test-cmd'],
|
||||
};
|
||||
|
||||
const content = generator.generateClaudeCommand(command);
|
||||
|
||||
expect(content).toContain('name: test-cmd');
|
||||
expect(content).toContain('description: Test command');
|
||||
expect(content).toContain('aliases: [tc]');
|
||||
expect(content).toContain('# /test-cmd');
|
||||
});
|
||||
|
||||
it('should include args in frontmatter', () => {
|
||||
const command: SlashCommand = {
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
args: [
|
||||
{
|
||||
name: 'file',
|
||||
description: 'File path',
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const content = generator.generateClaudeCommand(command);
|
||||
|
||||
expect(content).toContain('args:');
|
||||
expect(content).toContain('name: file');
|
||||
expect(content).toContain('required: true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateCursorRules', () => {
|
||||
it('should generate Cursor rules with @-mentions', () => {
|
||||
const commands: SlashCommand[] = [
|
||||
{
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
},
|
||||
];
|
||||
|
||||
const content = generator.generateCursorRules(commands);
|
||||
|
||||
expect(content).toContain('## @test-cmd');
|
||||
expect(content).toContain('Test command');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generate', () => {
|
||||
const commands: SlashCommand[] = [
|
||||
{
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
},
|
||||
];
|
||||
|
||||
it('should generate for claude-code', () => {
|
||||
const result = generator.generate(commands, 'claude-code');
|
||||
|
||||
expect(result instanceof Map).toBe(true);
|
||||
expect((result as Map<string, string>).has('test-cmd.md')).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate for cursor', () => {
|
||||
const result = generator.generate(commands, 'cursor');
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
expect((result as string)).toContain('@test-cmd');
|
||||
});
|
||||
|
||||
it('should generate for opencode', () => {
|
||||
const result = generator.generate(commands, 'opencode');
|
||||
|
||||
expect(result instanceof Map).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate for github-copilot', () => {
|
||||
const result = generator.generate(commands, 'github-copilot');
|
||||
|
||||
expect(result instanceof Map).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateManifest', () => {
|
||||
it('should generate JSON manifest', () => {
|
||||
const commands: SlashCommand[] = [
|
||||
{
|
||||
name: 'test-cmd',
|
||||
description: 'Test command',
|
||||
skill: 'test-skill',
|
||||
},
|
||||
];
|
||||
|
||||
const manifest = generator.generateManifest(commands);
|
||||
const parsed = JSON.parse(manifest);
|
||||
|
||||
expect(parsed.version).toBe('1.0.0');
|
||||
expect(parsed.commands).toHaveLength(1);
|
||||
expect(parsed.generatedAt).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentFormat', () => {
|
||||
it('should return format for claude-code', () => {
|
||||
const format = getAgentFormat('claude-code');
|
||||
|
||||
expect(format.agent).toBe('claude-code');
|
||||
expect(format.directory).toBe('.claude/commands');
|
||||
expect(format.extension).toBe('.md');
|
||||
expect(format.supportsSlashCommands).toBe(true);
|
||||
});
|
||||
|
||||
it('should return format for cursor', () => {
|
||||
const format = getAgentFormat('cursor');
|
||||
|
||||
expect(format.agent).toBe('cursor');
|
||||
expect(format.supportsSlashCommands).toBe(false);
|
||||
});
|
||||
|
||||
it('should return universal format for unknown agent', () => {
|
||||
const format = getAgentFormat('unknown' as AgentType);
|
||||
|
||||
expect(format.agent).toBe('universal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('supportsSlashCommands', () => {
|
||||
it('should return true for claude-code', () => {
|
||||
expect(supportsSlashCommands('claude-code')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for cursor', () => {
|
||||
expect(supportsSlashCommands('cursor')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for windsurf', () => {
|
||||
expect(supportsSlashCommands('windsurf')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* Command Generator
|
||||
*
|
||||
* Generates agent-specific slash commands from skills.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
import type { CanonicalSkill } from '../translator/types.js';
|
||||
import type {
|
||||
SlashCommand,
|
||||
CommandGeneratorOptions,
|
||||
AgentCommandFormat,
|
||||
RegisteredCommand,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Agent command formats
|
||||
*/
|
||||
const AGENT_FORMATS: Record<AgentType, AgentCommandFormat> = {
|
||||
'claude-code': {
|
||||
agent: 'claude-code',
|
||||
extension: '.md',
|
||||
directory: '.claude/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
cursor: {
|
||||
agent: 'cursor',
|
||||
extension: '.mdc',
|
||||
directory: '.cursor/rules',
|
||||
supportsSlashCommands: false,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
codex: {
|
||||
agent: 'codex',
|
||||
extension: '.md',
|
||||
directory: '.codex/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
'gemini-cli': {
|
||||
agent: 'gemini-cli',
|
||||
extension: '.md',
|
||||
directory: '.gemini/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
opencode: {
|
||||
agent: 'opencode',
|
||||
extension: '.md',
|
||||
directory: '.opencode/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
antigravity: {
|
||||
agent: 'antigravity',
|
||||
extension: '.md',
|
||||
directory: '.antigravity/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
amp: {
|
||||
agent: 'amp',
|
||||
extension: '.md',
|
||||
directory: '.amp/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
clawdbot: {
|
||||
agent: 'clawdbot',
|
||||
extension: '.md',
|
||||
directory: '.clawdbot/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
droid: {
|
||||
agent: 'droid',
|
||||
extension: '.md',
|
||||
directory: '.factory/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
'github-copilot': {
|
||||
agent: 'github-copilot',
|
||||
extension: '.md',
|
||||
directory: '.github/copilot/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
goose: {
|
||||
agent: 'goose',
|
||||
extension: '.md',
|
||||
directory: '.goose/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
kilo: {
|
||||
agent: 'kilo',
|
||||
extension: '.md',
|
||||
directory: '.kilocode/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
'kiro-cli': {
|
||||
agent: 'kiro-cli',
|
||||
extension: '.md',
|
||||
directory: '.kiro/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
roo: {
|
||||
agent: 'roo',
|
||||
extension: '.md',
|
||||
directory: '.roo/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
trae: {
|
||||
agent: 'trae',
|
||||
extension: '.md',
|
||||
directory: '.trae/commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
windsurf: {
|
||||
agent: 'windsurf',
|
||||
extension: '.md',
|
||||
directory: '.windsurf/commands',
|
||||
supportsSlashCommands: false,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
universal: {
|
||||
agent: 'universal',
|
||||
extension: '.md',
|
||||
directory: 'commands',
|
||||
supportsSlashCommands: true,
|
||||
supportsCommandFiles: true,
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* CommandGenerator - Generate agent-specific commands
|
||||
*/
|
||||
export class CommandGenerator {
|
||||
private options: Partial<CommandGeneratorOptions>;
|
||||
|
||||
constructor(options?: Partial<CommandGeneratorOptions>) {
|
||||
this.options = options || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent command format
|
||||
*/
|
||||
getAgentFormat(agent: AgentType): AgentCommandFormat {
|
||||
return AGENT_FORMATS[agent] || AGENT_FORMATS.universal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate command from skill
|
||||
*/
|
||||
fromSkill(skill: CanonicalSkill, commandName?: string): SlashCommand {
|
||||
return {
|
||||
name: commandName || this.slugify(skill.name),
|
||||
description: skill.description || `Execute ${skill.name} skill`,
|
||||
skill: skill.name,
|
||||
tags: skill.tags,
|
||||
category: this.inferCategory(skill),
|
||||
examples: this.generateExamples(skill, commandName || this.slugify(skill.name)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate commands from multiple skills
|
||||
*/
|
||||
fromSkills(skills: CanonicalSkill[]): SlashCommand[] {
|
||||
return skills.map((skill) => this.fromSkill(skill));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Claude Code command file
|
||||
*/
|
||||
generateClaudeCommand(command: SlashCommand | RegisteredCommand): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Frontmatter
|
||||
lines.push('---');
|
||||
lines.push(`name: ${command.name}`);
|
||||
lines.push(`description: ${command.description}`);
|
||||
if (command.aliases && command.aliases.length > 0) {
|
||||
lines.push(`aliases: [${command.aliases.join(', ')}]`);
|
||||
}
|
||||
if (command.disableModelInvocation) {
|
||||
lines.push('disableModelInvocation: true');
|
||||
}
|
||||
if (command.args && command.args.length > 0) {
|
||||
lines.push('args:');
|
||||
for (const arg of command.args) {
|
||||
lines.push(` - name: ${arg.name}`);
|
||||
lines.push(` description: ${arg.description}`);
|
||||
if (arg.required) lines.push(` required: true`);
|
||||
if (arg.default) lines.push(` default: "${arg.default}"`);
|
||||
}
|
||||
}
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
|
||||
// Command content
|
||||
lines.push(`# /${command.name}`);
|
||||
lines.push('');
|
||||
lines.push(command.description);
|
||||
lines.push('');
|
||||
|
||||
// Usage examples
|
||||
if (command.examples && command.examples.length > 0) {
|
||||
lines.push('## Usage');
|
||||
lines.push('');
|
||||
for (const example of command.examples) {
|
||||
lines.push(`- ${example}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
// Skill reference
|
||||
lines.push('## Skill');
|
||||
lines.push('');
|
||||
lines.push(`This command invokes the \`${command.skill}\` skill.`);
|
||||
lines.push('');
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Claude Code commands
|
||||
*/
|
||||
generateClaudeCommands(commands: (SlashCommand | RegisteredCommand)[]): Map<string, string> {
|
||||
const files = new Map<string, string>();
|
||||
for (const command of commands) {
|
||||
if (this.shouldInclude(command)) {
|
||||
const filename = `${command.name}.md`;
|
||||
files.set(filename, this.generateClaudeCommand(command));
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Cursor rules with @-mention syntax
|
||||
*/
|
||||
generateCursorRules(commands: (SlashCommand | RegisteredCommand)[]): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('---');
|
||||
lines.push('description: Available commands');
|
||||
lines.push('globs: ["**/*"]');
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
lines.push('# Available Commands');
|
||||
lines.push('');
|
||||
lines.push('You can invoke the following commands using @-mentions:');
|
||||
lines.push('');
|
||||
|
||||
for (const command of commands) {
|
||||
if (this.shouldInclude(command)) {
|
||||
lines.push(`## @${command.name}`);
|
||||
lines.push('');
|
||||
lines.push(command.description);
|
||||
lines.push('');
|
||||
if (command.examples && command.examples.length > 0) {
|
||||
lines.push('**Usage:**');
|
||||
for (const example of command.examples) {
|
||||
lines.push(`- ${example}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate OpenCode commands
|
||||
*/
|
||||
generateOpenCodeCommands(commands: (SlashCommand | RegisteredCommand)[]): Map<string, string> {
|
||||
const files = new Map<string, string>();
|
||||
|
||||
for (const command of commands) {
|
||||
if (this.shouldInclude(command)) {
|
||||
const lines: string[] = [];
|
||||
|
||||
// SKILL.md format with command metadata
|
||||
lines.push('---');
|
||||
lines.push(`name: ${command.name}`);
|
||||
lines.push(`description: ${command.description}`);
|
||||
lines.push('type: command');
|
||||
if (command.aliases && command.aliases.length > 0) {
|
||||
lines.push(`aliases: [${command.aliases.join(', ')}]`);
|
||||
}
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
lines.push(`# ${command.name}`);
|
||||
lines.push('');
|
||||
lines.push(command.description);
|
||||
lines.push('');
|
||||
|
||||
if (command.args && command.args.length > 0) {
|
||||
lines.push('## Arguments');
|
||||
lines.push('');
|
||||
for (const arg of command.args) {
|
||||
const required = arg.required ? '(required)' : '(optional)';
|
||||
lines.push(`- \`${arg.name}\` ${required}: ${arg.description}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (command.examples && command.examples.length > 0) {
|
||||
lines.push('## Examples');
|
||||
lines.push('');
|
||||
for (const example of command.examples) {
|
||||
lines.push(`- ${example}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push('## Skill Reference');
|
||||
lines.push('');
|
||||
lines.push(`Invokes: \`${command.skill}\``);
|
||||
lines.push('');
|
||||
|
||||
const filename = `${command.name}.md`;
|
||||
files.set(filename, lines.join('\n'));
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Copilot commands (agent skills format)
|
||||
*/
|
||||
generateCopilotCommands(commands: (SlashCommand | RegisteredCommand)[]): Map<string, string> {
|
||||
const files = new Map<string, string>();
|
||||
|
||||
for (const command of commands) {
|
||||
if (this.shouldInclude(command)) {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`# ${command.name}`);
|
||||
lines.push('');
|
||||
lines.push(`> ${command.description}`);
|
||||
lines.push('');
|
||||
|
||||
if (command.args && command.args.length > 0) {
|
||||
lines.push('## Parameters');
|
||||
lines.push('');
|
||||
lines.push('| Name | Required | Description |');
|
||||
lines.push('|------|----------|-------------|');
|
||||
for (const arg of command.args) {
|
||||
lines.push(`| ${arg.name} | ${arg.required ? 'Yes' : 'No'} | ${arg.description} |`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (command.examples && command.examples.length > 0) {
|
||||
lines.push('## Examples');
|
||||
lines.push('');
|
||||
for (const example of command.examples) {
|
||||
lines.push(`\`\`\`\n${example}\n\`\`\``);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push('## Implementation');
|
||||
lines.push('');
|
||||
lines.push(`This command is powered by the \`${command.skill}\` skill.`);
|
||||
lines.push('');
|
||||
|
||||
const filename = `${command.name}.md`;
|
||||
files.set(filename, lines.join('\n'));
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate commands for any agent
|
||||
*/
|
||||
generate(
|
||||
commands: (SlashCommand | RegisteredCommand)[],
|
||||
agent: AgentType
|
||||
): Map<string, string> | string {
|
||||
switch (agent) {
|
||||
case 'claude-code':
|
||||
case 'codex':
|
||||
case 'gemini-cli':
|
||||
case 'amp':
|
||||
case 'roo':
|
||||
case 'kiro-cli':
|
||||
return this.generateClaudeCommands(commands);
|
||||
|
||||
case 'cursor':
|
||||
return this.generateCursorRules(commands);
|
||||
|
||||
case 'opencode':
|
||||
return this.generateOpenCodeCommands(commands);
|
||||
|
||||
case 'github-copilot':
|
||||
return this.generateCopilotCommands(commands);
|
||||
|
||||
default:
|
||||
// Use Claude Code format as default
|
||||
return this.generateClaudeCommands(commands);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate JSON manifest of commands
|
||||
*/
|
||||
generateManifest(commands: (SlashCommand | RegisteredCommand)[]): string {
|
||||
const manifest = {
|
||||
version: '1.0.0',
|
||||
commands: commands.filter((c) => this.shouldInclude(c)).map((c) => ({
|
||||
name: c.name,
|
||||
description: c.description,
|
||||
skill: c.skill,
|
||||
aliases: c.aliases,
|
||||
args: c.args,
|
||||
category: c.category,
|
||||
tags: c.tags,
|
||||
})),
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return JSON.stringify(manifest, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if command should be included
|
||||
*/
|
||||
private shouldInclude(command: SlashCommand | RegisteredCommand): boolean {
|
||||
// Check hidden
|
||||
if (command.hidden && !this.options.includeHidden) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check enabled (for RegisteredCommand)
|
||||
if ('enabled' in command && !command.enabled && !this.options.includeDisabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slugify a string for command name
|
||||
*/
|
||||
private slugify(str: string): string {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer category from skill
|
||||
*/
|
||||
private inferCategory(skill: CanonicalSkill): string | undefined {
|
||||
const tags = skill.tags || [];
|
||||
const name = skill.name.toLowerCase();
|
||||
|
||||
if (tags.includes('testing') || name.includes('test')) {
|
||||
return 'testing';
|
||||
}
|
||||
if (tags.includes('debugging') || name.includes('debug')) {
|
||||
return 'debugging';
|
||||
}
|
||||
if (tags.includes('planning') || name.includes('plan')) {
|
||||
return 'planning';
|
||||
}
|
||||
if (tags.includes('collaboration') || name.includes('review')) {
|
||||
return 'collaboration';
|
||||
}
|
||||
if (tags.includes('git') || name.includes('commit') || name.includes('branch')) {
|
||||
return 'git';
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate usage examples
|
||||
*/
|
||||
private generateExamples(skill: CanonicalSkill, commandName: string): string[] {
|
||||
const examples: string[] = [];
|
||||
|
||||
examples.push(`/${commandName}`);
|
||||
|
||||
// Add examples based on skill content
|
||||
if (skill.content.toLowerCase().includes('file')) {
|
||||
examples.push(`/${commandName} path/to/file.ts`);
|
||||
}
|
||||
|
||||
if (skill.content.toLowerCase().includes('test')) {
|
||||
examples.push(`/${commandName} --run-tests`);
|
||||
}
|
||||
|
||||
return examples;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a CommandGenerator instance
|
||||
*/
|
||||
export function createCommandGenerator(options?: Partial<CommandGeneratorOptions>): CommandGenerator {
|
||||
return new CommandGenerator(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent format info
|
||||
*/
|
||||
export function getAgentFormat(agent: AgentType): AgentCommandFormat {
|
||||
return AGENT_FORMATS[agent] || AGENT_FORMATS.universal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if agent supports slash commands
|
||||
*/
|
||||
export function supportsSlashCommands(agent: AgentType): boolean {
|
||||
const format = AGENT_FORMATS[agent];
|
||||
return format?.supportsSlashCommands ?? true;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Commands Module
|
||||
*
|
||||
* Slash commands and agent integration.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './registry.js';
|
||||
export * from './generator.js';
|
||||
@@ -0,0 +1,428 @@
|
||||
/**
|
||||
* Command Registry
|
||||
*
|
||||
* Central registry for managing slash commands.
|
||||
*/
|
||||
|
||||
import type {
|
||||
SlashCommand,
|
||||
RegisteredCommand,
|
||||
CommandRegistryOptions,
|
||||
CommandSearchOptions,
|
||||
CommandValidationResult,
|
||||
CommandHandler,
|
||||
CommandEvent,
|
||||
CommandEventListener,
|
||||
CommandContext,
|
||||
SlashCommandResult,
|
||||
CommandBundle,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* CommandRegistry - Central registry for slash commands
|
||||
*/
|
||||
export class CommandRegistry {
|
||||
private commands: Map<string, RegisteredCommand> = new Map();
|
||||
private aliases: Map<string, string> = new Map();
|
||||
private listeners: Set<CommandEventListener> = new Set();
|
||||
private options: CommandRegistryOptions;
|
||||
|
||||
constructor(options?: CommandRegistryOptions) {
|
||||
this.options = {
|
||||
allowOverrides: false,
|
||||
validateOnRegister: true,
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a command
|
||||
*/
|
||||
register(command: SlashCommand, handler?: CommandHandler, source?: string): void {
|
||||
// Validate if enabled
|
||||
if (this.options.validateOnRegister) {
|
||||
const validation = this.validate(command);
|
||||
if (!validation.valid) {
|
||||
throw new Error(`Invalid command: ${validation.errors.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for existing command
|
||||
if (this.commands.has(command.name) && !this.options.allowOverrides) {
|
||||
throw new Error(`Command already registered: ${command.name}`);
|
||||
}
|
||||
|
||||
// Create registered command
|
||||
const registered: RegisteredCommand = {
|
||||
...command,
|
||||
handler: handler || this.options.defaultHandler,
|
||||
enabled: true,
|
||||
source,
|
||||
};
|
||||
|
||||
// Register command
|
||||
this.commands.set(command.name, registered);
|
||||
|
||||
// Register aliases
|
||||
if (command.aliases) {
|
||||
for (const alias of command.aliases) {
|
||||
this.aliases.set(alias, command.name);
|
||||
}
|
||||
}
|
||||
|
||||
this.emit('command:registered', registered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register multiple commands
|
||||
*/
|
||||
registerAll(commands: SlashCommand[], handler?: CommandHandler, source?: string): void {
|
||||
for (const command of commands) {
|
||||
this.register(command, handler, source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a command
|
||||
*/
|
||||
unregister(name: string): boolean {
|
||||
const command = this.commands.get(name);
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove aliases
|
||||
if (command.aliases) {
|
||||
for (const alias of command.aliases) {
|
||||
this.aliases.delete(alias);
|
||||
}
|
||||
}
|
||||
|
||||
this.commands.delete(name);
|
||||
this.emit('command:unregistered', command);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a command by name or alias
|
||||
*/
|
||||
get(name: string): RegisteredCommand | undefined {
|
||||
// Check direct name
|
||||
const command = this.commands.get(name);
|
||||
if (command) {
|
||||
return command;
|
||||
}
|
||||
|
||||
// Check aliases
|
||||
const aliasTarget = this.aliases.get(name);
|
||||
if (aliasTarget) {
|
||||
return this.commands.get(aliasTarget);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a command exists
|
||||
*/
|
||||
has(name: string): boolean {
|
||||
return this.commands.has(name) || this.aliases.has(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered commands
|
||||
*/
|
||||
getAll(includeDisabled = false): RegisteredCommand[] {
|
||||
const commands = Array.from(this.commands.values());
|
||||
return includeDisabled ? commands : commands.filter((c) => c.enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search commands
|
||||
*/
|
||||
search(options?: CommandSearchOptions): RegisteredCommand[] {
|
||||
let commands = this.getAll(options?.includeDisabled);
|
||||
|
||||
// Filter hidden
|
||||
if (!options?.includeHidden) {
|
||||
commands = commands.filter((c) => !c.hidden);
|
||||
}
|
||||
|
||||
// Filter by category
|
||||
if (options?.category) {
|
||||
commands = commands.filter((c) => c.category === options.category);
|
||||
}
|
||||
|
||||
// Filter by tags
|
||||
if (options?.tags && options.tags.length > 0) {
|
||||
commands = commands.filter((c) => c.tags && options.tags!.some((t) => c.tags!.includes(t)));
|
||||
}
|
||||
|
||||
// Search by query
|
||||
if (options?.query) {
|
||||
const query = options.query.toLowerCase();
|
||||
commands = commands.filter(
|
||||
(c) =>
|
||||
c.name.toLowerCase().includes(query) ||
|
||||
c.description.toLowerCase().includes(query) ||
|
||||
c.aliases?.some((a) => a.toLowerCase().includes(query))
|
||||
);
|
||||
}
|
||||
|
||||
// Sort by priority
|
||||
commands.sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
|
||||
// Limit results
|
||||
if (options?.limit) {
|
||||
commands = commands.slice(0, options.limit);
|
||||
}
|
||||
|
||||
return commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable a command
|
||||
*/
|
||||
enable(name: string): boolean {
|
||||
const command = this.commands.get(name);
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
command.enabled = true;
|
||||
this.emit('command:enabled', command);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable a command
|
||||
*/
|
||||
disable(name: string): boolean {
|
||||
const command = this.commands.get(name);
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
command.enabled = false;
|
||||
this.emit('command:disabled', command);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
*/
|
||||
async execute(name: string, context: Omit<CommandContext, 'command'>): Promise<SlashCommandResult> {
|
||||
const command = this.get(name);
|
||||
if (!command) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Command not found: ${name}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!command.enabled) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Command is disabled: ${name}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!command.handler) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Command has no handler: ${name}`,
|
||||
};
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
const result = await command.handler({
|
||||
...context,
|
||||
command,
|
||||
});
|
||||
|
||||
result.durationMs = Date.now() - startTime;
|
||||
this.emit('command:executed', command, result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const result: SlashCommandResult = {
|
||||
success: false,
|
||||
error: (error as Error).message,
|
||||
durationMs: Date.now() - startTime,
|
||||
};
|
||||
this.emit('command:failed', command, result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a command
|
||||
*/
|
||||
validate(command: SlashCommand): CommandValidationResult {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
// Name is required
|
||||
if (!command.name || !command.name.trim()) {
|
||||
errors.push('Command must have a name');
|
||||
} else {
|
||||
// Name format validation
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(command.name)) {
|
||||
errors.push('Command name must start with a letter and contain only lowercase letters, numbers, and hyphens');
|
||||
}
|
||||
}
|
||||
|
||||
// Description is required
|
||||
if (!command.description || !command.description.trim()) {
|
||||
errors.push('Command must have a description');
|
||||
}
|
||||
|
||||
// Skill is required
|
||||
if (!command.skill || !command.skill.trim()) {
|
||||
errors.push('Command must reference a skill');
|
||||
}
|
||||
|
||||
// Validate aliases
|
||||
if (command.aliases) {
|
||||
for (const alias of command.aliases) {
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(alias)) {
|
||||
errors.push(`Invalid alias format: ${alias}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate args
|
||||
if (command.args) {
|
||||
const argNames = new Set<string>();
|
||||
for (const arg of command.args) {
|
||||
if (!arg.name || !arg.name.trim()) {
|
||||
errors.push('Argument must have a name');
|
||||
} else if (argNames.has(arg.name)) {
|
||||
errors.push(`Duplicate argument name: ${arg.name}`);
|
||||
} else {
|
||||
argNames.add(arg.name);
|
||||
}
|
||||
|
||||
if (!arg.description || !arg.description.trim()) {
|
||||
warnings.push(`Argument ${arg.name} has no description`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate examples
|
||||
if (!command.examples || command.examples.length === 0) {
|
||||
warnings.push('Command has no usage examples');
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get categories
|
||||
*/
|
||||
getCategories(): string[] {
|
||||
const categories = new Set<string>();
|
||||
for (const command of this.commands.values()) {
|
||||
if (command.category) {
|
||||
categories.add(command.category);
|
||||
}
|
||||
}
|
||||
return Array.from(categories).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commands by category
|
||||
*/
|
||||
getByCategory(category: string): RegisteredCommand[] {
|
||||
return this.getAll().filter((c) => c.category === category);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export commands to bundle
|
||||
*/
|
||||
export(includeDisabled = false): CommandBundle {
|
||||
const commands = this.getAll(includeDisabled).map((c) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { handler, enabled, source, ...command } = c;
|
||||
return command;
|
||||
});
|
||||
|
||||
return {
|
||||
version: '1.0.0',
|
||||
commands,
|
||||
metadata: {
|
||||
createdAt: new Date(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Import commands from bundle
|
||||
*/
|
||||
import(bundle: CommandBundle, handler?: CommandHandler, source?: string): number {
|
||||
let imported = 0;
|
||||
for (const command of bundle.commands) {
|
||||
try {
|
||||
this.register(command, handler, source);
|
||||
imported++;
|
||||
} catch {
|
||||
// Skip commands that fail to register
|
||||
}
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all commands
|
||||
*/
|
||||
clear(): void {
|
||||
this.commands.clear();
|
||||
this.aliases.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get command count
|
||||
*/
|
||||
get size(): number {
|
||||
return this.commands.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
*/
|
||||
addListener(listener: CommandEventListener): void {
|
||||
this.listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event listener
|
||||
*/
|
||||
removeListener(listener: CommandEventListener): void {
|
||||
this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event
|
||||
*/
|
||||
private emit(event: CommandEvent, command: RegisteredCommand, result?: SlashCommandResult): void {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
listener(event, command, result);
|
||||
} catch {
|
||||
// Ignore listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a CommandRegistry instance
|
||||
*/
|
||||
export function createCommandRegistry(options?: CommandRegistryOptions): CommandRegistry {
|
||||
return new CommandRegistry(options);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Command Types
|
||||
*
|
||||
* Type definitions for slash commands and agent integration.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Command argument definition
|
||||
*/
|
||||
export interface CommandArg {
|
||||
/** Argument name */
|
||||
name: string;
|
||||
/** Argument description */
|
||||
description: string;
|
||||
/** Whether the argument is required */
|
||||
required?: boolean;
|
||||
/** Default value */
|
||||
default?: string;
|
||||
/** Argument type */
|
||||
type?: 'string' | 'number' | 'boolean' | 'file' | 'choice';
|
||||
/** Valid choices (for type: 'choice') */
|
||||
choices?: string[];
|
||||
/** Validation pattern (regex) */
|
||||
pattern?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slash command definition
|
||||
*/
|
||||
export interface SlashCommand {
|
||||
/** Command name (without slash) */
|
||||
name: string;
|
||||
/** Command description */
|
||||
description: string;
|
||||
/** Skill to invoke when command is executed */
|
||||
skill: string;
|
||||
/** Alternative names for the command */
|
||||
aliases?: string[];
|
||||
/** Whether to disable model invocation (user-only) */
|
||||
disableModelInvocation?: boolean;
|
||||
/** Command arguments */
|
||||
args?: CommandArg[];
|
||||
/** Category for grouping */
|
||||
category?: string;
|
||||
/** Usage examples */
|
||||
examples?: string[];
|
||||
/** Tags for filtering */
|
||||
tags?: string[];
|
||||
/** Priority for ordering */
|
||||
priority?: number;
|
||||
/** Whether the command is hidden from help */
|
||||
hidden?: boolean;
|
||||
/** Metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command execution context
|
||||
*/
|
||||
export interface CommandContext {
|
||||
/** The command being executed */
|
||||
command: SlashCommand;
|
||||
/** Parsed arguments */
|
||||
args: Record<string, unknown>;
|
||||
/** Agent executing the command */
|
||||
agent: AgentType;
|
||||
/** Working directory */
|
||||
cwd: string;
|
||||
/** Environment variables */
|
||||
env?: Record<string, string>;
|
||||
/** Additional context */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command execution result
|
||||
*/
|
||||
export interface SlashCommandResult {
|
||||
/** Whether execution succeeded */
|
||||
success: boolean;
|
||||
/** Output message */
|
||||
output?: string;
|
||||
/** Error message if failed */
|
||||
error?: string;
|
||||
/** Data returned by the command */
|
||||
data?: unknown;
|
||||
/** Duration in milliseconds */
|
||||
durationMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command handler function
|
||||
*/
|
||||
export type CommandHandler = (context: CommandContext) => Promise<SlashCommandResult>;
|
||||
|
||||
/**
|
||||
* Registered command with handler
|
||||
*/
|
||||
export interface RegisteredCommand extends SlashCommand {
|
||||
/** Command handler function */
|
||||
handler?: CommandHandler;
|
||||
/** Whether the command is enabled */
|
||||
enabled: boolean;
|
||||
/** Source of the command (plugin, skill, etc.) */
|
||||
source?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command registry options
|
||||
*/
|
||||
export interface CommandRegistryOptions {
|
||||
/** Allow command overrides */
|
||||
allowOverrides?: boolean;
|
||||
/** Validate commands on registration */
|
||||
validateOnRegister?: boolean;
|
||||
/** Default handler for commands without one */
|
||||
defaultHandler?: CommandHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command generator options
|
||||
*/
|
||||
export interface CommandGeneratorOptions {
|
||||
/** Target agent */
|
||||
agent: AgentType;
|
||||
/** Include hidden commands */
|
||||
includeHidden?: boolean;
|
||||
/** Include disabled commands */
|
||||
includeDisabled?: boolean;
|
||||
/** Output format */
|
||||
format?: 'markdown' | 'json' | 'native';
|
||||
/** Custom template */
|
||||
template?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command search options
|
||||
*/
|
||||
export interface CommandSearchOptions {
|
||||
/** Search query */
|
||||
query?: string;
|
||||
/** Filter by category */
|
||||
category?: string;
|
||||
/** Filter by tags */
|
||||
tags?: string[];
|
||||
/** Include hidden commands */
|
||||
includeHidden?: boolean;
|
||||
/** Include disabled commands */
|
||||
includeDisabled?: boolean;
|
||||
/** Maximum results */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command validation result
|
||||
*/
|
||||
export interface CommandValidationResult {
|
||||
/** Whether the command is valid */
|
||||
valid: boolean;
|
||||
/** Validation errors */
|
||||
errors: string[];
|
||||
/** Validation warnings */
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent command format
|
||||
*/
|
||||
export interface AgentCommandFormat {
|
||||
/** Agent type */
|
||||
agent: AgentType;
|
||||
/** File extension */
|
||||
extension: string;
|
||||
/** Directory for commands */
|
||||
directory: string;
|
||||
/** Whether agent supports slash commands */
|
||||
supportsSlashCommands: boolean;
|
||||
/** Whether agent supports command files */
|
||||
supportsCommandFiles: boolean;
|
||||
/** Template for generating commands */
|
||||
template?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command event types
|
||||
*/
|
||||
export type CommandEvent =
|
||||
| 'command:registered'
|
||||
| 'command:unregistered'
|
||||
| 'command:enabled'
|
||||
| 'command:disabled'
|
||||
| 'command:executed'
|
||||
| 'command:failed';
|
||||
|
||||
/**
|
||||
* Command event listener
|
||||
*/
|
||||
export type CommandEventListener = (
|
||||
event: CommandEvent,
|
||||
command: RegisteredCommand,
|
||||
result?: SlashCommandResult
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Command import/export format
|
||||
*/
|
||||
export interface CommandBundle {
|
||||
/** Bundle version */
|
||||
version: string;
|
||||
/** Commands in the bundle */
|
||||
commands: SlashCommand[];
|
||||
/** Bundle metadata */
|
||||
metadata?: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
author?: string;
|
||||
createdAt?: Date;
|
||||
};
|
||||
}
|
||||
@@ -15,10 +15,32 @@ export function getGlobalConfigPath(): string {
|
||||
return join(homedir(), '.config', 'skillkit', CONFIG_FILE);
|
||||
}
|
||||
|
||||
export function loadConfig(): SkillkitConfig {
|
||||
export function loadConfig(global = false): SkillkitConfig {
|
||||
const projectPath = getProjectConfigPath();
|
||||
const globalPath = getGlobalConfigPath();
|
||||
|
||||
// If global is explicitly requested, only load from global path
|
||||
if (global) {
|
||||
if (existsSync(globalPath)) {
|
||||
try {
|
||||
const content = readFileSync(globalPath, 'utf-8');
|
||||
const data = parseYaml(content);
|
||||
const parsed = SkillkitConfig.safeParse(data);
|
||||
if (parsed.success) {
|
||||
return parsed.data;
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
agent: 'universal',
|
||||
autoSync: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Default behavior: project config takes precedence over global
|
||||
if (existsSync(projectPath)) {
|
||||
try {
|
||||
const content = readFileSync(projectPath, 'utf-8');
|
||||
|
||||
@@ -40,3 +40,14 @@ export {
|
||||
type SyncResult,
|
||||
type SyncReport,
|
||||
} from './sync.js';
|
||||
|
||||
// Loader (Smart Context Loading)
|
||||
export {
|
||||
ContextLoader,
|
||||
createContextLoader,
|
||||
estimateTokens,
|
||||
DEFAULT_CONTEXT_CATEGORIES,
|
||||
type ContextCategory,
|
||||
type ContextLoadOptions,
|
||||
type LoadedContext,
|
||||
} from './loader.js';
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* Context Loader
|
||||
*
|
||||
* Smart context loading with token budgets and category-based loading.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
/**
|
||||
* Context category with size limits
|
||||
*/
|
||||
export interface ContextCategory {
|
||||
/** Category name */
|
||||
name: string;
|
||||
/** Maximum tokens for this category */
|
||||
maxTokens: number;
|
||||
/** Whether to always load this category */
|
||||
alwaysLoad: boolean;
|
||||
/** File path (relative to project) */
|
||||
file?: string;
|
||||
/** Inline content */
|
||||
content?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context loading options
|
||||
*/
|
||||
export interface ContextLoadOptions {
|
||||
/** Total token budget */
|
||||
totalBudget?: number;
|
||||
/** Categories to load (load all if not specified) */
|
||||
categories?: string[];
|
||||
/** Whether to warn when approaching budget limits */
|
||||
warnOnBudgetLimit?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loaded context result
|
||||
*/
|
||||
export interface LoadedContext {
|
||||
/** All loaded content combined */
|
||||
content: string;
|
||||
/** Total tokens used */
|
||||
totalTokens: number;
|
||||
/** Budget remaining */
|
||||
budgetRemaining: number;
|
||||
/** Categories loaded */
|
||||
categoriesLoaded: string[];
|
||||
/** Categories skipped (due to budget or not found) */
|
||||
categoriesSkipped: string[];
|
||||
/** Warnings generated */
|
||||
warnings: string[];
|
||||
/** Whether budget is near limit (>50% used) */
|
||||
nearBudgetLimit: boolean;
|
||||
/** Whether context is degraded (>70% used) */
|
||||
contextDegraded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default context categories
|
||||
*/
|
||||
export const DEFAULT_CONTEXT_CATEGORIES: ContextCategory[] = [
|
||||
{
|
||||
name: 'project',
|
||||
maxTokens: 2000,
|
||||
alwaysLoad: true,
|
||||
file: '.skillkit/context.yaml',
|
||||
},
|
||||
{
|
||||
name: 'requirements',
|
||||
maxTokens: 5000,
|
||||
alwaysLoad: false,
|
||||
file: 'REQUIREMENTS.md',
|
||||
},
|
||||
{
|
||||
name: 'decisions',
|
||||
maxTokens: 1000,
|
||||
alwaysLoad: false,
|
||||
file: '.skillkit/decisions.yaml',
|
||||
},
|
||||
{
|
||||
name: 'readme',
|
||||
maxTokens: 3000,
|
||||
alwaysLoad: false,
|
||||
file: 'README.md',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Rough estimate of tokens from text
|
||||
* (approximation: ~4 characters per token for English text)
|
||||
*/
|
||||
export function estimateTokens(text: string): number {
|
||||
return Math.ceil(text.length / 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Context Loader class
|
||||
*/
|
||||
export class ContextLoader {
|
||||
private projectPath: string;
|
||||
private categories: ContextCategory[];
|
||||
private defaultBudget: number;
|
||||
|
||||
constructor(projectPath: string, options?: { categories?: ContextCategory[]; defaultBudget?: number }) {
|
||||
this.projectPath = projectPath;
|
||||
this.categories = options?.categories || DEFAULT_CONTEXT_CATEGORIES;
|
||||
this.defaultBudget = options?.defaultBudget || 32000; // Default ~32k tokens
|
||||
}
|
||||
|
||||
/**
|
||||
* Load context based on options
|
||||
*/
|
||||
load(options: ContextLoadOptions = {}): LoadedContext {
|
||||
const totalBudget = options.totalBudget || this.defaultBudget;
|
||||
const requestedCategories = options.categories;
|
||||
|
||||
const result: LoadedContext = {
|
||||
content: '',
|
||||
totalTokens: 0,
|
||||
budgetRemaining: totalBudget,
|
||||
categoriesLoaded: [],
|
||||
categoriesSkipped: [],
|
||||
warnings: [],
|
||||
nearBudgetLimit: false,
|
||||
contextDegraded: false,
|
||||
};
|
||||
|
||||
const contentParts: string[] = [];
|
||||
|
||||
// First pass: load alwaysLoad categories
|
||||
for (const category of this.categories) {
|
||||
if (!category.alwaysLoad) continue;
|
||||
if (requestedCategories && !requestedCategories.includes(category.name)) continue;
|
||||
|
||||
this.loadCategory(category, result, contentParts, totalBudget);
|
||||
}
|
||||
|
||||
// Second pass: load requested categories
|
||||
for (const category of this.categories) {
|
||||
if (category.alwaysLoad) continue; // Already loaded
|
||||
if (requestedCategories && !requestedCategories.includes(category.name)) continue;
|
||||
|
||||
this.loadCategory(category, result, contentParts, totalBudget);
|
||||
}
|
||||
|
||||
// Combine content
|
||||
result.content = contentParts.join('\n\n---\n\n');
|
||||
|
||||
// Check budget status
|
||||
const usagePercent = (result.totalTokens / totalBudget) * 100;
|
||||
result.nearBudgetLimit = usagePercent >= 50;
|
||||
result.contextDegraded = usagePercent >= 70;
|
||||
|
||||
// Add warnings for budget limits
|
||||
if (result.contextDegraded && options.warnOnBudgetLimit !== false) {
|
||||
result.warnings.push(
|
||||
`Context usage at ${Math.round(usagePercent)}% - quality may degrade. Consider spawning a fresh agent.`
|
||||
);
|
||||
} else if (result.nearBudgetLimit && options.warnOnBudgetLimit !== false) {
|
||||
result.warnings.push(`Context usage at ${Math.round(usagePercent)}% - approaching limit.`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a single category
|
||||
*/
|
||||
private loadCategory(
|
||||
category: ContextCategory,
|
||||
result: LoadedContext,
|
||||
contentParts: string[],
|
||||
totalBudget: number
|
||||
): void {
|
||||
let content: string | null = null;
|
||||
|
||||
// Load from file
|
||||
if (category.file) {
|
||||
const filePath = join(this.projectPath, category.file);
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
content = readFileSync(filePath, 'utf-8');
|
||||
} catch {
|
||||
result.categoriesSkipped.push(category.name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use inline content if no file
|
||||
if (!content && category.content) {
|
||||
content = category.content;
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
result.categoriesSkipped.push(category.name);
|
||||
return;
|
||||
}
|
||||
|
||||
// Estimate tokens
|
||||
const tokens = estimateTokens(content);
|
||||
|
||||
// Check category limit
|
||||
if (tokens > category.maxTokens) {
|
||||
// Truncate to category limit
|
||||
const truncateChars = category.maxTokens * 4;
|
||||
content = content.slice(0, truncateChars) + '\n\n[... content truncated ...]';
|
||||
result.warnings.push(
|
||||
`Category "${category.name}" truncated to ${category.maxTokens} tokens`
|
||||
);
|
||||
}
|
||||
|
||||
// Check total budget
|
||||
const truncatedTokens = estimateTokens(content);
|
||||
if (result.totalTokens + truncatedTokens > totalBudget) {
|
||||
// Skip if would exceed budget
|
||||
result.categoriesSkipped.push(category.name);
|
||||
result.warnings.push(
|
||||
`Category "${category.name}" skipped - would exceed budget`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add to result
|
||||
contentParts.push(`# ${category.name.toUpperCase()}\n\n${content}`);
|
||||
result.totalTokens += truncatedTokens;
|
||||
result.budgetRemaining = totalBudget - result.totalTokens;
|
||||
result.categoriesLoaded.push(category.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get category by name
|
||||
*/
|
||||
getCategory(name: string): ContextCategory | undefined {
|
||||
return this.categories.find((c) => c.name === name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a custom category
|
||||
*/
|
||||
addCategory(category: ContextCategory): void {
|
||||
const existing = this.categories.findIndex((c) => c.name === category.name);
|
||||
if (existing >= 0) {
|
||||
this.categories[existing] = category;
|
||||
} else {
|
||||
this.categories.push(category);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a category
|
||||
*/
|
||||
removeCategory(name: string): void {
|
||||
this.categories = this.categories.filter((c) => c.name !== name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get estimated context size for categories
|
||||
*/
|
||||
estimateSize(categoryNames?: string[]): { category: string; tokens: number; available: boolean }[] {
|
||||
const estimates: { category: string; tokens: number; available: boolean }[] = [];
|
||||
|
||||
for (const category of this.categories) {
|
||||
if (categoryNames && !categoryNames.includes(category.name)) continue;
|
||||
|
||||
let tokens = 0;
|
||||
let available = false;
|
||||
|
||||
if (category.file) {
|
||||
const filePath = join(this.projectPath, category.file);
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
tokens = Math.ceil(stat.size / 4); // Rough estimate
|
||||
available = true;
|
||||
} catch {
|
||||
// File not accessible
|
||||
}
|
||||
}
|
||||
} else if (category.content) {
|
||||
tokens = estimateTokens(category.content);
|
||||
available = true;
|
||||
}
|
||||
|
||||
estimates.push({
|
||||
category: category.name,
|
||||
tokens: Math.min(tokens, category.maxTokens),
|
||||
available,
|
||||
});
|
||||
}
|
||||
|
||||
return estimates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if context would exceed budget threshold
|
||||
*/
|
||||
wouldExceedThreshold(additionalTokens: number, threshold: number = 0.7): boolean {
|
||||
const currentTokens = this.load().totalTokens;
|
||||
const newTotal = currentTokens + additionalTokens;
|
||||
return newTotal / this.defaultBudget > threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest spawning fresh agent if context is degraded
|
||||
*/
|
||||
shouldSpawnFreshAgent(): { should: boolean; reason?: string } {
|
||||
const context = this.load();
|
||||
|
||||
if (context.contextDegraded) {
|
||||
return {
|
||||
should: true,
|
||||
reason: `Context at ${Math.round((context.totalTokens / this.defaultBudget) * 100)}% capacity`,
|
||||
};
|
||||
}
|
||||
|
||||
return { should: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a context loader
|
||||
*/
|
||||
export function createContextLoader(
|
||||
projectPath: string,
|
||||
options?: { categories?: ContextCategory[]; defaultBudget?: number }
|
||||
): ContextLoader {
|
||||
return new ContextLoader(projectPath, options);
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* Agent Execution Module
|
||||
*
|
||||
* Handles real execution of skills through various AI agent CLIs.
|
||||
*/
|
||||
|
||||
import { spawn, type SpawnOptions } from 'node:child_process';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Agent CLI configuration
|
||||
*/
|
||||
export interface AgentCLIConfig {
|
||||
/** Agent type */
|
||||
type: AgentType;
|
||||
/** CLI command name */
|
||||
command: string;
|
||||
/** Whether the agent supports CLI execution */
|
||||
supportsCLI: boolean;
|
||||
/** Arguments to pass the prompt/skill content */
|
||||
promptArgs?: string[];
|
||||
/** Arguments for non-interactive mode */
|
||||
nonInteractiveArgs?: string[];
|
||||
/** Environment variables needed */
|
||||
envVars?: Record<string, string>;
|
||||
/** How to check if agent is installed */
|
||||
checkCommand?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution result from an agent
|
||||
*/
|
||||
export interface AgentExecutionResult {
|
||||
success: boolean;
|
||||
output: string;
|
||||
error?: string;
|
||||
exitCode: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent CLI configurations
|
||||
*/
|
||||
export const AGENT_CLI_CONFIGS: AgentCLIConfig[] = [
|
||||
{
|
||||
type: 'claude-code',
|
||||
command: 'claude',
|
||||
supportsCLI: true,
|
||||
promptArgs: ['--print', '-p'],
|
||||
nonInteractiveArgs: ['--no-input'],
|
||||
checkCommand: 'claude --version',
|
||||
},
|
||||
{
|
||||
type: 'codex',
|
||||
command: 'codex',
|
||||
supportsCLI: true,
|
||||
promptArgs: ['-p'],
|
||||
checkCommand: 'codex --version',
|
||||
},
|
||||
{
|
||||
type: 'gemini-cli',
|
||||
command: 'gemini',
|
||||
supportsCLI: true,
|
||||
promptArgs: [],
|
||||
checkCommand: 'gemini --version',
|
||||
},
|
||||
{
|
||||
type: 'opencode',
|
||||
command: 'opencode',
|
||||
supportsCLI: true,
|
||||
promptArgs: ['--prompt'],
|
||||
checkCommand: 'opencode --version',
|
||||
},
|
||||
{
|
||||
type: 'goose',
|
||||
command: 'goose',
|
||||
supportsCLI: true,
|
||||
promptArgs: ['run'],
|
||||
checkCommand: 'goose --version',
|
||||
},
|
||||
// IDE-based agents (no CLI execution)
|
||||
{
|
||||
type: 'cursor',
|
||||
command: 'cursor',
|
||||
supportsCLI: false,
|
||||
},
|
||||
{
|
||||
type: 'windsurf',
|
||||
command: 'windsurf',
|
||||
supportsCLI: false,
|
||||
},
|
||||
{
|
||||
type: 'github-copilot',
|
||||
command: 'gh copilot',
|
||||
supportsCLI: false,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get CLI config for an agent
|
||||
*/
|
||||
export function getAgentCLIConfig(agentType: AgentType): AgentCLIConfig | undefined {
|
||||
return AGENT_CLI_CONFIGS.find((c) => c.type === agentType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an agent CLI is available
|
||||
*/
|
||||
export async function isAgentCLIAvailable(agentType: AgentType): Promise<boolean> {
|
||||
const config = getAgentCLIConfig(agentType);
|
||||
if (!config || !config.supportsCLI) return false;
|
||||
|
||||
try {
|
||||
// Check if command exists
|
||||
const checkCmd = config.checkCommand || `which ${config.command}`;
|
||||
const result = await executeCommand(checkCmd.split(' ')[0], checkCmd.split(' ').slice(1), {
|
||||
timeout: 5000,
|
||||
});
|
||||
return result.exitCode === 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all available CLI agents
|
||||
*/
|
||||
export async function getAvailableCLIAgents(): Promise<AgentType[]> {
|
||||
const available: AgentType[] = [];
|
||||
|
||||
for (const config of AGENT_CLI_CONFIGS) {
|
||||
if (config.supportsCLI && (await isAgentCLIAvailable(config.type))) {
|
||||
available.push(config.type);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a skill using an agent CLI
|
||||
*/
|
||||
export async function executeWithAgent(
|
||||
agentType: AgentType,
|
||||
prompt: string,
|
||||
options: {
|
||||
cwd?: string;
|
||||
timeout?: number;
|
||||
env?: Record<string, string>;
|
||||
} = {}
|
||||
): Promise<AgentExecutionResult> {
|
||||
const config = getAgentCLIConfig(agentType);
|
||||
|
||||
if (!config) {
|
||||
return {
|
||||
success: false,
|
||||
output: '',
|
||||
error: `Unknown agent type: ${agentType}`,
|
||||
exitCode: 1,
|
||||
duration: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (!config.supportsCLI) {
|
||||
return {
|
||||
success: false,
|
||||
output: '',
|
||||
error: `Agent ${agentType} does not support CLI execution. Please use IDE integration.`,
|
||||
exitCode: 1,
|
||||
duration: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const isAvailable = await isAgentCLIAvailable(agentType);
|
||||
if (!isAvailable) {
|
||||
return {
|
||||
success: false,
|
||||
output: '',
|
||||
error: `Agent CLI '${config.command}' is not installed or not in PATH`,
|
||||
exitCode: 1,
|
||||
duration: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Build command arguments
|
||||
const args: string[] = [...(config.promptArgs || [])];
|
||||
|
||||
// For Claude Code, use --print mode with the prompt
|
||||
if (agentType === 'claude-code') {
|
||||
args.push(prompt);
|
||||
} else {
|
||||
// For other agents, pass prompt as argument
|
||||
args.push(prompt);
|
||||
}
|
||||
|
||||
// Add non-interactive flags if available
|
||||
if (config.nonInteractiveArgs) {
|
||||
args.push(...config.nonInteractiveArgs);
|
||||
}
|
||||
|
||||
return executeCommand(config.command, args, {
|
||||
cwd: options.cwd || process.cwd(),
|
||||
timeout: options.timeout || 300000, // 5 minutes default
|
||||
env: {
|
||||
...process.env,
|
||||
...config.envVars,
|
||||
...options.env,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command and capture output
|
||||
*/
|
||||
async function executeCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: {
|
||||
cwd?: string;
|
||||
timeout?: number;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
} = {}
|
||||
): Promise<AgentExecutionResult> {
|
||||
return new Promise((resolve) => {
|
||||
const startTime = Date.now();
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let timedOut = false;
|
||||
|
||||
const spawnOptions: SpawnOptions = {
|
||||
cwd: options.cwd,
|
||||
env: options.env as NodeJS.ProcessEnv,
|
||||
// shell: false (default) - prevents shell injection when passing untrusted input
|
||||
};
|
||||
|
||||
const child = spawn(command, args, spawnOptions);
|
||||
|
||||
// Set up timeout
|
||||
const timeoutId = options.timeout
|
||||
? setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill('SIGTERM');
|
||||
}, options.timeout)
|
||||
: null;
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
resolve({
|
||||
success: false,
|
||||
output: stdout,
|
||||
error: error.message,
|
||||
exitCode: 1,
|
||||
duration: Date.now() - startTime,
|
||||
});
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
resolve({
|
||||
success: code === 0 && !timedOut,
|
||||
output: stdout,
|
||||
error: timedOut ? 'Execution timed out' : stderr || undefined,
|
||||
exitCode: code ?? 1,
|
||||
duration: Date.now() - startTime,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Format skill content as a prompt for an agent
|
||||
*/
|
||||
export function formatSkillAsPrompt(
|
||||
skillName: string,
|
||||
skillContent: string,
|
||||
taskDescription?: string
|
||||
): string {
|
||||
let prompt = `Execute the following skill: ${skillName}\n\n`;
|
||||
|
||||
if (taskDescription) {
|
||||
prompt += `Task: ${taskDescription}\n\n`;
|
||||
}
|
||||
|
||||
prompt += `Skill Content:\n${skillContent}`;
|
||||
|
||||
return prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent execution strategy
|
||||
*/
|
||||
export type ExecutionStrategy = 'cli' | 'ide' | 'api' | 'manual';
|
||||
|
||||
/**
|
||||
* Get recommended execution strategy for an agent
|
||||
*/
|
||||
export function getExecutionStrategy(agentType: AgentType): ExecutionStrategy {
|
||||
const config = getAgentCLIConfig(agentType);
|
||||
|
||||
if (config?.supportsCLI) {
|
||||
return 'cli';
|
||||
}
|
||||
|
||||
// IDE-based agents
|
||||
if (['cursor', 'windsurf', 'github-copilot', 'kilo'].includes(agentType)) {
|
||||
return 'ide';
|
||||
}
|
||||
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get instructions for manual/IDE execution
|
||||
*/
|
||||
export function getManualExecutionInstructions(
|
||||
agentType: AgentType,
|
||||
skillPath: string
|
||||
): string {
|
||||
const strategy = getExecutionStrategy(agentType);
|
||||
|
||||
if (strategy === 'ide') {
|
||||
return `
|
||||
To execute this skill with ${agentType}:
|
||||
1. Open your project in ${agentType}
|
||||
2. The skill has been synced to the agent's skills directory
|
||||
3. Open the AI assistant/chat
|
||||
4. Reference the skill or ask the assistant to follow the instructions
|
||||
|
||||
Skill location: ${skillPath}
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
To execute this skill manually:
|
||||
1. Open the skill file: ${skillPath}
|
||||
2. Copy the skill content
|
||||
3. Paste it into your AI coding assistant
|
||||
4. Follow the instructions in the skill
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
/**
|
||||
* Skill Execution Engine
|
||||
*
|
||||
* Executes skills with task-based orchestration, verification, and state management.
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type {
|
||||
ExecutableSkill,
|
||||
ExecutableTask,
|
||||
ExecutionOptions,
|
||||
TaskExecutionResult,
|
||||
SkillExecutionResult,
|
||||
CheckpointHandler,
|
||||
CheckpointResponse,
|
||||
ExecutionTaskStatus,
|
||||
} from './types.js';
|
||||
import { SessionManager } from '../session/manager.js';
|
||||
import type { SessionTask } from '../session/types.js';
|
||||
|
||||
/**
|
||||
* Progress event for execution
|
||||
*/
|
||||
export interface ExecutionProgressEvent {
|
||||
type: 'task_start' | 'task_complete' | 'checkpoint' | 'verification' | 'complete';
|
||||
taskId?: string;
|
||||
taskName?: string;
|
||||
taskIndex?: number;
|
||||
totalTasks?: number;
|
||||
status?: ExecutionTaskStatus | 'paused' | 'cancelled';
|
||||
message?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Progress callback type
|
||||
*/
|
||||
export type ExecutionProgressCallback = (event: ExecutionProgressEvent) => void;
|
||||
|
||||
/**
|
||||
* Skill Execution Engine
|
||||
*/
|
||||
export class SkillExecutionEngine {
|
||||
private projectPath: string;
|
||||
private sessionManager: SessionManager;
|
||||
private checkpointHandler?: CheckpointHandler;
|
||||
private onProgress?: ExecutionProgressCallback;
|
||||
|
||||
constructor(
|
||||
projectPath: string,
|
||||
options?: {
|
||||
checkpointHandler?: CheckpointHandler;
|
||||
onProgress?: ExecutionProgressCallback;
|
||||
}
|
||||
) {
|
||||
this.projectPath = projectPath;
|
||||
this.sessionManager = new SessionManager(projectPath);
|
||||
this.checkpointHandler = options?.checkpointHandler;
|
||||
this.onProgress = options?.onProgress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a skill
|
||||
*/
|
||||
async execute(
|
||||
skill: ExecutableSkill,
|
||||
options: ExecutionOptions = {}
|
||||
): Promise<SkillExecutionResult> {
|
||||
const startTime = new Date();
|
||||
const tasks = skill.tasks || [];
|
||||
|
||||
// Handle dry run
|
||||
if (options.dryRun) {
|
||||
return this.createDryRunResult(skill);
|
||||
}
|
||||
|
||||
// Check if there's an existing paused execution for this skill
|
||||
const existingState = this.sessionManager.get();
|
||||
if (existingState?.currentExecution?.skillName === skill.name) {
|
||||
if (existingState.currentExecution.status === 'paused') {
|
||||
// Resume from paused state
|
||||
return this.resumeExecution(skill, options);
|
||||
}
|
||||
}
|
||||
|
||||
// Start new execution
|
||||
const sessionTasks: Omit<SessionTask, 'status'>[] = tasks.map((task, index) => ({
|
||||
id: task.id || `task-${index}`,
|
||||
name: task.name,
|
||||
type: task.type === 'auto' ? 'auto' : task.type,
|
||||
}));
|
||||
|
||||
this.sessionManager.startExecution(skill.name, skill.source, sessionTasks);
|
||||
|
||||
const taskResults: TaskExecutionResult[] = [];
|
||||
let overallStatus: 'completed' | 'failed' | 'cancelled' | 'paused' = 'completed';
|
||||
let overallError: string | undefined;
|
||||
|
||||
// Execute tasks
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
const task = tasks[i];
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'task_start',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
});
|
||||
|
||||
// Handle checkpoints
|
||||
if (task.type !== 'auto') {
|
||||
const checkpointResult = await this.handleCheckpoint(task, {
|
||||
skillName: skill.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
});
|
||||
|
||||
if (!checkpointResult.continue) {
|
||||
overallStatus = 'paused';
|
||||
this.sessionManager.pause();
|
||||
break;
|
||||
}
|
||||
|
||||
// For decision checkpoints, record the decision
|
||||
if (task.type === 'checkpoint:decision' && checkpointResult.selectedOption) {
|
||||
this.sessionManager.recordDecision(
|
||||
`${skill.name}:${task.id}`,
|
||||
checkpointResult.selectedOption,
|
||||
skill.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the task
|
||||
const taskResult = await this.executeTask(task, skill, options);
|
||||
taskResults.push(taskResult);
|
||||
|
||||
this.sessionManager.updateTask(task.id || `task-${i}`, {
|
||||
status: taskResult.status === 'completed' ? 'completed' : 'failed',
|
||||
output: taskResult.output,
|
||||
error: taskResult.error,
|
||||
filesModified: taskResult.filesModified,
|
||||
commitSha: taskResult.commitSha,
|
||||
});
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'task_complete',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
status: taskResult.status,
|
||||
error: taskResult.error,
|
||||
});
|
||||
|
||||
// Handle task failure
|
||||
if (taskResult.status === 'failed') {
|
||||
if (!options.continueOnError) {
|
||||
overallStatus = 'failed';
|
||||
overallError = taskResult.error;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Run verification if enabled
|
||||
if (options.verify && task.verify) {
|
||||
const verificationPassed = await this.runVerification(task, taskResult);
|
||||
if (!verificationPassed && !options.continueOnError) {
|
||||
overallStatus = 'failed';
|
||||
overallError = 'Verification failed';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const endTime = new Date();
|
||||
|
||||
// Complete the execution
|
||||
if (overallStatus !== 'paused') {
|
||||
this.sessionManager.completeExecution(overallStatus, overallError);
|
||||
}
|
||||
|
||||
const result: SkillExecutionResult = {
|
||||
skillName: skill.name,
|
||||
skillSource: skill.source,
|
||||
status: overallStatus,
|
||||
startedAt: startTime.toISOString(),
|
||||
completedAt: endTime.toISOString(),
|
||||
durationMs: endTime.getTime() - startTime.getTime(),
|
||||
tasks: taskResults,
|
||||
filesModified: Array.from(new Set(taskResults.flatMap((t) => t.filesModified || []))),
|
||||
commits: taskResults.map((t) => t.commitSha).filter((sha): sha is string => !!sha),
|
||||
error: overallError,
|
||||
};
|
||||
|
||||
const statusMessages: Record<'completed' | 'failed' | 'cancelled' | 'paused', string> = {
|
||||
completed: 'Skill execution completed',
|
||||
paused: 'Skill execution paused',
|
||||
failed: overallError || 'Skill execution failed',
|
||||
cancelled: 'Skill execution cancelled',
|
||||
};
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'complete',
|
||||
status: overallStatus,
|
||||
message: statusMessages[overallStatus],
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a paused execution
|
||||
*/
|
||||
private async resumeExecution(
|
||||
skill: ExecutableSkill,
|
||||
options: ExecutionOptions
|
||||
): Promise<SkillExecutionResult> {
|
||||
const state = this.sessionManager.get();
|
||||
if (!state?.currentExecution) {
|
||||
throw new Error('No execution to resume');
|
||||
}
|
||||
|
||||
this.sessionManager.resume();
|
||||
const execution = state.currentExecution;
|
||||
const tasks = skill.tasks || [];
|
||||
|
||||
const taskResults: TaskExecutionResult[] = [];
|
||||
let overallStatus: 'completed' | 'failed' | 'cancelled' | 'paused' = 'completed';
|
||||
let overallError: string | undefined;
|
||||
|
||||
// Find where to resume from
|
||||
const startIndex = execution.currentStep;
|
||||
|
||||
for (let i = startIndex; i < tasks.length; i++) {
|
||||
const task = tasks[i];
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'task_start',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
});
|
||||
|
||||
// Handle checkpoints (same as in execute)
|
||||
if (task.type !== 'auto') {
|
||||
const checkpointResult = await this.handleCheckpoint(task, {
|
||||
skillName: skill.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
});
|
||||
|
||||
if (!checkpointResult.continue) {
|
||||
overallStatus = 'paused';
|
||||
this.sessionManager.pause();
|
||||
break;
|
||||
}
|
||||
|
||||
// For decision checkpoints, record the decision
|
||||
if (task.type === 'checkpoint:decision' && checkpointResult.selectedOption) {
|
||||
this.sessionManager.recordDecision(
|
||||
`${skill.name}:${task.id}`,
|
||||
checkpointResult.selectedOption,
|
||||
skill.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const taskResult = await this.executeTask(task, skill, options);
|
||||
taskResults.push(taskResult);
|
||||
|
||||
this.sessionManager.updateTask(task.id || `task-${i}`, {
|
||||
status: taskResult.status === 'completed' ? 'completed' : 'failed',
|
||||
output: taskResult.output,
|
||||
error: taskResult.error,
|
||||
filesModified: taskResult.filesModified,
|
||||
commitSha: taskResult.commitSha,
|
||||
});
|
||||
|
||||
// Emit task_complete progress event (matching execute behavior)
|
||||
this.onProgress?.({
|
||||
type: 'task_complete',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
taskIndex: i,
|
||||
totalTasks: tasks.length,
|
||||
status: taskResult.status,
|
||||
error: taskResult.error,
|
||||
});
|
||||
|
||||
// Handle task failure
|
||||
if (taskResult.status === 'failed') {
|
||||
if (!options.continueOnError) {
|
||||
overallStatus = 'failed';
|
||||
overallError = taskResult.error;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Run verification if enabled (matching execute behavior)
|
||||
if (options.verify && task.verify) {
|
||||
const verificationPassed = await this.runVerification(task, taskResult);
|
||||
if (!verificationPassed && !options.continueOnError) {
|
||||
overallStatus = 'failed';
|
||||
overallError = 'Verification failed';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only complete execution if not paused
|
||||
if (overallStatus !== 'paused') {
|
||||
this.sessionManager.completeExecution(overallStatus, overallError);
|
||||
}
|
||||
|
||||
return {
|
||||
skillName: skill.name,
|
||||
skillSource: skill.source,
|
||||
status: overallStatus,
|
||||
startedAt: execution.startedAt,
|
||||
completedAt: new Date().toISOString(),
|
||||
durationMs: Date.now() - new Date(execution.startedAt).getTime(),
|
||||
tasks: taskResults,
|
||||
filesModified: Array.from(new Set(taskResults.flatMap((t) => t.filesModified || []))),
|
||||
commits: taskResults.map((t) => t.commitSha).filter((sha): sha is string => !!sha),
|
||||
error: overallError,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a single task
|
||||
*/
|
||||
private async executeTask(
|
||||
task: ExecutableTask,
|
||||
_skill: ExecutableSkill,
|
||||
_options: ExecutionOptions
|
||||
): Promise<TaskExecutionResult> {
|
||||
const startTime = new Date();
|
||||
const taskId = task.id || randomUUID();
|
||||
|
||||
try {
|
||||
// For now, we simulate task execution
|
||||
// In a real implementation, this would integrate with the AI agent
|
||||
// to execute the task action based on the skill content
|
||||
|
||||
// Simulate some work
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const endTime = new Date();
|
||||
|
||||
return {
|
||||
taskId,
|
||||
taskName: task.name,
|
||||
status: 'completed',
|
||||
startedAt: startTime.toISOString(),
|
||||
completedAt: endTime.toISOString(),
|
||||
durationMs: endTime.getTime() - startTime.getTime(),
|
||||
output: `Task "${task.name}" completed successfully`,
|
||||
filesModified: task.files,
|
||||
};
|
||||
} catch (error) {
|
||||
const endTime = new Date();
|
||||
|
||||
return {
|
||||
taskId,
|
||||
taskName: task.name,
|
||||
status: 'failed',
|
||||
startedAt: startTime.toISOString(),
|
||||
completedAt: endTime.toISOString(),
|
||||
durationMs: endTime.getTime() - startTime.getTime(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a checkpoint
|
||||
*/
|
||||
private async handleCheckpoint(
|
||||
task: ExecutableTask,
|
||||
context: { skillName: string; taskIndex: number; totalTasks: number }
|
||||
): Promise<CheckpointResponse> {
|
||||
this.onProgress?.({
|
||||
type: 'checkpoint',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
taskIndex: context.taskIndex,
|
||||
totalTasks: context.totalTasks,
|
||||
message: `Checkpoint: ${task.type}`,
|
||||
});
|
||||
|
||||
if (this.checkpointHandler) {
|
||||
return this.checkpointHandler(task, context);
|
||||
}
|
||||
|
||||
// Default: auto-continue for non-decision checkpoints
|
||||
if (task.type === 'checkpoint:decision') {
|
||||
// Use first option if no handler
|
||||
return {
|
||||
continue: true,
|
||||
selectedOption: task.options?.[0],
|
||||
};
|
||||
}
|
||||
|
||||
return { continue: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a regex pattern is potentially dangerous (ReDoS-vulnerable)
|
||||
* Rejects patterns with nested quantifiers and other known problematic constructs
|
||||
*/
|
||||
private isUnsafeRegexPattern(pattern: string): boolean {
|
||||
// Detect nested quantifiers like (a+)+, (a*)+, (a+)*, (a*)*
|
||||
// These are the primary cause of catastrophic backtracking
|
||||
const nestedQuantifierPattern = /\([^)]*[+*][^)]*\)[+*?]/;
|
||||
if (nestedQuantifierPattern.test(pattern)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detect overlapping alternations with quantifiers like (a|a)+
|
||||
const overlappingAlternation = /\([^|)]*\|[^|)]*\)[+*]/;
|
||||
if (overlappingAlternation.test(pattern)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detect excessive quantifiers (more than 3 quantifiers in a row-ish)
|
||||
const quantifierCount = (pattern.match(/[+*?]|\{\d+/g) || []).length;
|
||||
if (quantifierCount > 10) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detect very long character classes which can be slow
|
||||
const longCharClass = /\[[^\]]{50,}\]/;
|
||||
if (longCharClass.test(pattern)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely test a regex pattern with ReDoS prevention
|
||||
*
|
||||
* This method validates patterns before execution to prevent catastrophic backtracking.
|
||||
* Note: This cannot guarantee protection against all ReDoS patterns, but catches common ones.
|
||||
*/
|
||||
private safeRegexTest(pattern: string, input: string, _timeoutMs = 1000): boolean {
|
||||
// Strict length limits to prevent excessive processing
|
||||
if (pattern.length > 200 || input.length > 50000) {
|
||||
console.warn(`Regex test skipped: pattern or input too long`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reject patterns known to cause ReDoS
|
||||
if (this.isUnsafeRegexPattern(pattern)) {
|
||||
console.warn(`Regex pattern rejected as potentially unsafe: ${pattern.slice(0, 50)}...`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const regex = new RegExp(pattern);
|
||||
return regex.test(input);
|
||||
} catch {
|
||||
// Invalid regex pattern
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run verification for a task
|
||||
*
|
||||
* SECURITY NOTE: Verification commands are executed from skill configuration.
|
||||
* Only run skills from trusted sources. Commands run with the same privileges
|
||||
* as the skillkit process.
|
||||
*/
|
||||
private async runVerification(
|
||||
task: ExecutableTask,
|
||||
result: TaskExecutionResult
|
||||
): Promise<boolean> {
|
||||
if (!task.verify) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const verificationResults = {
|
||||
automated: [] as { rule: string; passed: boolean; output?: string }[],
|
||||
human: [] as { description: string; passed: boolean }[],
|
||||
};
|
||||
|
||||
// Run automated verification
|
||||
if (task.verify.automated) {
|
||||
for (const rule of task.verify.automated) {
|
||||
if (rule.command) {
|
||||
try {
|
||||
// SECURITY: Commands are from skill config - only run trusted skills
|
||||
const output = execSync(rule.command, {
|
||||
cwd: this.projectPath,
|
||||
encoding: 'utf-8',
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
let passed = true;
|
||||
if (rule.expect) {
|
||||
if (rule.expect === 'success') {
|
||||
passed = true;
|
||||
} else if (rule.expect.startsWith('contains:')) {
|
||||
const expected = rule.expect.slice(9);
|
||||
passed = output.includes(expected);
|
||||
} else if (rule.expect.startsWith('matches:')) {
|
||||
const pattern = rule.expect.slice(8);
|
||||
// Use safe regex test to prevent ReDoS
|
||||
passed = this.safeRegexTest(pattern, output);
|
||||
}
|
||||
}
|
||||
|
||||
verificationResults.automated.push({
|
||||
rule: rule.command,
|
||||
passed,
|
||||
output,
|
||||
});
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'verification',
|
||||
taskId: task.id,
|
||||
taskName: task.name,
|
||||
message: `Verification ${passed ? 'passed' : 'failed'}: ${rule.command}`,
|
||||
});
|
||||
|
||||
if (!passed) {
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
verificationResults.automated.push({
|
||||
rule: rule.command,
|
||||
passed: false,
|
||||
output: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Human verification would be handled by checkpoint handler
|
||||
result.verificationResults = verificationResults;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a dry run result
|
||||
*/
|
||||
private createDryRunResult(skill: ExecutableSkill): SkillExecutionResult {
|
||||
const tasks = skill.tasks || [];
|
||||
|
||||
return {
|
||||
skillName: skill.name,
|
||||
skillSource: skill.source,
|
||||
status: 'completed',
|
||||
startedAt: new Date().toISOString(),
|
||||
completedAt: new Date().toISOString(),
|
||||
durationMs: 0,
|
||||
tasks: tasks.map((task) => ({
|
||||
taskId: task.id || randomUUID(),
|
||||
taskName: task.name,
|
||||
status: 'skipped' as ExecutionTaskStatus,
|
||||
startedAt: new Date().toISOString(),
|
||||
completedAt: new Date().toISOString(),
|
||||
durationMs: 0,
|
||||
output: '[Dry run - not executed]',
|
||||
})),
|
||||
filesModified: [],
|
||||
commits: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause current execution
|
||||
*/
|
||||
pause(): boolean {
|
||||
return this.sessionManager.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if execution is paused
|
||||
*/
|
||||
isPaused(): boolean {
|
||||
return this.sessionManager.isPaused();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session manager
|
||||
*/
|
||||
getSessionManager(): SessionManager {
|
||||
return this.sessionManager;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new skill execution engine
|
||||
*/
|
||||
export function createExecutionEngine(
|
||||
projectPath: string,
|
||||
options?: {
|
||||
checkpointHandler?: CheckpointHandler;
|
||||
onProgress?: ExecutionProgressCallback;
|
||||
}
|
||||
): SkillExecutionEngine {
|
||||
return new SkillExecutionEngine(projectPath, options);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Skill Execution Engine Module
|
||||
*
|
||||
* Provides skill execution with task-based orchestration,
|
||||
* verification, and session state management.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './engine.js';
|
||||
export { SkillExecutionEngine, createExecutionEngine } from './engine.js';
|
||||
|
||||
// Agent Execution (Real CLI integration)
|
||||
export * from './agents.js';
|
||||
export {
|
||||
executeWithAgent,
|
||||
isAgentCLIAvailable,
|
||||
getAvailableCLIAgents,
|
||||
getAgentCLIConfig,
|
||||
formatSkillAsPrompt,
|
||||
getExecutionStrategy,
|
||||
getManualExecutionInstructions,
|
||||
AGENT_CLI_CONFIGS,
|
||||
type AgentCLIConfig,
|
||||
type AgentExecutionResult,
|
||||
type ExecutionStrategy,
|
||||
} from './agents.js';
|
||||
|
||||
// Skill Executor for Workflows
|
||||
export {
|
||||
createSkillExecutor,
|
||||
createSimulatedSkillExecutor,
|
||||
type SkillExecutorOptions,
|
||||
type SkillExecutionEvent,
|
||||
} from './skill-executor.js';
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Skill Executor for Workflows
|
||||
*
|
||||
* Provides a real skill executor that finds skills by name
|
||||
* and executes them using available agent CLIs.
|
||||
*/
|
||||
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { findSkill, readSkillContent, SKILL_DISCOVERY_PATHS } from '../skills.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
import {
|
||||
executeWithAgent,
|
||||
getAvailableCLIAgents,
|
||||
formatSkillAsPrompt,
|
||||
getExecutionStrategy,
|
||||
getManualExecutionInstructions,
|
||||
} from './agents.js';
|
||||
import type { SkillExecutor } from '../workflow/orchestrator.js';
|
||||
|
||||
/**
|
||||
* Options for creating a skill executor
|
||||
*/
|
||||
export interface SkillExecutorOptions {
|
||||
/** Project path to search for skills */
|
||||
projectPath?: string;
|
||||
/** Preferred agent to use for execution */
|
||||
preferredAgent?: AgentType;
|
||||
/** Timeout for skill execution (ms) */
|
||||
timeout?: number;
|
||||
/** Whether to fall back to other agents if preferred is unavailable */
|
||||
fallbackToAvailable?: boolean;
|
||||
/** Callback for execution events */
|
||||
onExecutionEvent?: (event: SkillExecutionEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill execution event
|
||||
*/
|
||||
export interface SkillExecutionEvent {
|
||||
type: 'skill_found' | 'skill_not_found' | 'agent_selected' | 'execution_start' | 'execution_complete';
|
||||
skillName: string;
|
||||
agent?: AgentType;
|
||||
message?: string;
|
||||
success?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get search directories for skills
|
||||
*/
|
||||
function getSearchDirs(projectPath: string): string[] {
|
||||
const dirs: string[] = [];
|
||||
|
||||
// Project-local paths
|
||||
for (const searchPath of SKILL_DISCOVERY_PATHS) {
|
||||
const fullPath = join(projectPath, searchPath);
|
||||
if (existsSync(fullPath)) {
|
||||
dirs.push(fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Global paths
|
||||
const home = homedir();
|
||||
const globalPaths = [
|
||||
join(home, '.claude', 'skills'),
|
||||
join(home, '.cursor', 'skills'),
|
||||
join(home, '.codex', 'skills'),
|
||||
join(home, '.skillkit', 'skills'),
|
||||
];
|
||||
|
||||
for (const globalPath of globalPaths) {
|
||||
if (existsSync(globalPath)) {
|
||||
dirs.push(globalPath);
|
||||
}
|
||||
}
|
||||
|
||||
return dirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a skill executor for workflow orchestration
|
||||
*
|
||||
* This returns a function compatible with the WorkflowOrchestrator's SkillExecutor type.
|
||||
*/
|
||||
export function createSkillExecutor(options: SkillExecutorOptions = {}): SkillExecutor {
|
||||
const {
|
||||
projectPath = process.cwd(),
|
||||
preferredAgent,
|
||||
timeout = 300000, // 5 minutes
|
||||
fallbackToAvailable = true,
|
||||
onExecutionEvent,
|
||||
} = options;
|
||||
|
||||
return async (skillName: string, config?: Record<string, unknown>): Promise<{ success: boolean; error?: string }> => {
|
||||
// Find the skill
|
||||
const searchDirs = getSearchDirs(projectPath);
|
||||
const skill = findSkill(skillName, searchDirs);
|
||||
|
||||
if (!skill) {
|
||||
onExecutionEvent?.({
|
||||
type: 'skill_not_found',
|
||||
skillName,
|
||||
message: `Skill "${skillName}" not found in any search directory`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: `Skill "${skillName}" not found. Search paths: ${searchDirs.join(', ')}`,
|
||||
};
|
||||
}
|
||||
|
||||
onExecutionEvent?.({
|
||||
type: 'skill_found',
|
||||
skillName,
|
||||
message: `Found skill at: ${skill.path}`,
|
||||
});
|
||||
|
||||
// Read skill content
|
||||
const content = readSkillContent(skill.path);
|
||||
if (!content) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Could not read skill content from: ${skill.path}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Determine which agent to use
|
||||
let agentToUse: AgentType | undefined = preferredAgent;
|
||||
|
||||
if (!agentToUse || fallbackToAvailable) {
|
||||
const availableAgents = await getAvailableCLIAgents();
|
||||
|
||||
if (preferredAgent && availableAgents.includes(preferredAgent)) {
|
||||
agentToUse = preferredAgent;
|
||||
} else if (availableAgents.length > 0) {
|
||||
// Prefer claude-code if available, otherwise use first available
|
||||
agentToUse = availableAgents.includes('claude-code') ? 'claude-code' : availableAgents[0];
|
||||
}
|
||||
}
|
||||
|
||||
// If no CLI agent available, provide manual instructions or error
|
||||
if (!agentToUse) {
|
||||
const strategy = getExecutionStrategy(preferredAgent || 'universal');
|
||||
const instructions = getManualExecutionInstructions(preferredAgent || 'universal', skill.path);
|
||||
|
||||
if (strategy === 'ide' || strategy === 'manual') {
|
||||
onExecutionEvent?.({
|
||||
type: 'execution_complete',
|
||||
skillName,
|
||||
success: false,
|
||||
message: 'No CLI agent available',
|
||||
error: `No CLI agent available for execution.\n${instructions}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: `No CLI agent available for automated execution. ${instructions}`,
|
||||
};
|
||||
}
|
||||
|
||||
// strategy is 'cli' but the preferred agent's CLI is not installed
|
||||
const errorMsg = preferredAgent
|
||||
? `The preferred agent "${preferredAgent}" supports CLI execution but its CLI is not installed.`
|
||||
: 'No CLI agent is available for execution.';
|
||||
|
||||
onExecutionEvent?.({
|
||||
type: 'execution_complete',
|
||||
skillName,
|
||||
success: false,
|
||||
message: 'CLI not installed',
|
||||
error: `${errorMsg}\n${instructions}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: `${errorMsg} ${instructions}`,
|
||||
};
|
||||
}
|
||||
|
||||
onExecutionEvent?.({
|
||||
type: 'agent_selected',
|
||||
skillName,
|
||||
agent: agentToUse,
|
||||
message: `Using agent: ${agentToUse}`,
|
||||
});
|
||||
|
||||
// Format the prompt with skill content and any config
|
||||
let taskDescription: string | undefined;
|
||||
if (config?.task) {
|
||||
taskDescription = String(config.task);
|
||||
}
|
||||
|
||||
const prompt = formatSkillAsPrompt(skillName, content, taskDescription);
|
||||
|
||||
onExecutionEvent?.({
|
||||
type: 'execution_start',
|
||||
skillName,
|
||||
agent: agentToUse,
|
||||
message: `Starting execution with ${agentToUse}`,
|
||||
});
|
||||
|
||||
// Execute with the agent
|
||||
const result = await executeWithAgent(agentToUse!, prompt, {
|
||||
cwd: projectPath,
|
||||
timeout,
|
||||
});
|
||||
|
||||
onExecutionEvent?.({
|
||||
type: 'execution_complete',
|
||||
skillName,
|
||||
agent: agentToUse,
|
||||
success: result.success,
|
||||
error: result.error,
|
||||
message: result.success ? 'Execution completed successfully' : `Execution failed: ${result.error}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: result.success,
|
||||
error: result.error,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a simulated skill executor for testing/dry-run
|
||||
*
|
||||
* This executor doesn't actually run skills but simulates execution.
|
||||
*/
|
||||
export function createSimulatedSkillExecutor(options: {
|
||||
delay?: number;
|
||||
shouldFail?: (skillName: string) => boolean;
|
||||
onExecute?: (skillName: string) => void;
|
||||
} = {}): SkillExecutor {
|
||||
const { delay = 100, shouldFail, onExecute } = options;
|
||||
|
||||
return async (skillName: string, _config?: Record<string, unknown>): Promise<{ success: boolean; error?: string }> => {
|
||||
onExecute?.(skillName);
|
||||
|
||||
// Simulate execution time
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
|
||||
const failed = shouldFail?.(skillName) ?? false;
|
||||
|
||||
return {
|
||||
success: !failed,
|
||||
error: failed ? `Simulated failure for skill: ${skillName}` : undefined,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Executor Types
|
||||
*
|
||||
* Types for skill execution engine.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Task type within a skill
|
||||
*/
|
||||
export type ExecutableTaskType =
|
||||
| 'auto'
|
||||
| 'checkpoint:human-verify'
|
||||
| 'checkpoint:decision'
|
||||
| 'checkpoint:human-action';
|
||||
|
||||
/**
|
||||
* Task status
|
||||
*/
|
||||
export type ExecutionTaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
|
||||
|
||||
/**
|
||||
* Verification rule for a task
|
||||
*/
|
||||
export interface VerificationRule {
|
||||
/** Command to run for verification */
|
||||
command?: string;
|
||||
/** Expected result (success, contains:<text>, matches:<regex>) */
|
||||
expect?: string;
|
||||
/** Human verification prompt */
|
||||
description?: string;
|
||||
/** URL to show for verification */
|
||||
url?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* An executable task within a skill
|
||||
*/
|
||||
export interface ExecutableTask {
|
||||
/** Task identifier */
|
||||
id: string;
|
||||
/** Task name/description */
|
||||
name: string;
|
||||
/** Task type */
|
||||
type: ExecutableTaskType;
|
||||
/** Action description for AI agent */
|
||||
action: string;
|
||||
/** Files expected to be modified */
|
||||
files?: string[];
|
||||
/** Verification rules */
|
||||
verify?: {
|
||||
automated?: VerificationRule[];
|
||||
human?: VerificationRule[];
|
||||
};
|
||||
/** Options for checkpoint:decision type */
|
||||
options?: string[];
|
||||
/** Dependencies (task IDs that must complete first) */
|
||||
dependsOn?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended skill with execution metadata
|
||||
*/
|
||||
export interface ExecutableSkill {
|
||||
/** Skill name */
|
||||
name: string;
|
||||
/** Skill description */
|
||||
description?: string;
|
||||
/** Skill version */
|
||||
version?: string;
|
||||
/** Skill source (repo or path) */
|
||||
source: string;
|
||||
/** Skill content (instructions) */
|
||||
content: string;
|
||||
/** Executable tasks */
|
||||
tasks?: ExecutableTask[];
|
||||
/** Environment requirements */
|
||||
requirements?: {
|
||||
frameworks?: string[];
|
||||
languages?: string[];
|
||||
libraries?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Task execution result
|
||||
*/
|
||||
export interface TaskExecutionResult {
|
||||
/** Task ID */
|
||||
taskId: string;
|
||||
/** Task name */
|
||||
taskName: string;
|
||||
/** Final status */
|
||||
status: ExecutionTaskStatus;
|
||||
/** Start time */
|
||||
startedAt: string;
|
||||
/** End time (only present for completed/failed/skipped tasks) */
|
||||
completedAt?: string;
|
||||
/** Duration in milliseconds (only present for completed/failed/skipped tasks) */
|
||||
durationMs?: number;
|
||||
/** Output/result */
|
||||
output?: string;
|
||||
/** Error message if failed */
|
||||
error?: string;
|
||||
/** Files modified */
|
||||
filesModified?: string[];
|
||||
/** Git commit SHA if committed */
|
||||
commitSha?: string;
|
||||
/** Verification results */
|
||||
verificationResults?: {
|
||||
automated: { rule: string; passed: boolean; output?: string }[];
|
||||
human: { description: string; passed: boolean }[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill execution result
|
||||
*/
|
||||
export interface SkillExecutionResult {
|
||||
/** Skill name */
|
||||
skillName: string;
|
||||
/** Skill source */
|
||||
skillSource: string;
|
||||
/** Overall status */
|
||||
status: 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
/** Start time */
|
||||
startedAt: string;
|
||||
/** End time */
|
||||
completedAt?: string;
|
||||
/** Total duration in milliseconds */
|
||||
durationMs?: number;
|
||||
/** Task results */
|
||||
tasks: TaskExecutionResult[];
|
||||
/** All files modified */
|
||||
filesModified: string[];
|
||||
/** All commits created */
|
||||
commits: string[];
|
||||
/** Error if failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution options
|
||||
*/
|
||||
export interface ExecutionOptions {
|
||||
/** Target agent to use */
|
||||
agent?: AgentType;
|
||||
/** Whether to create commits per task */
|
||||
autoCommit?: boolean;
|
||||
/** Whether to run verification checks */
|
||||
verify?: boolean;
|
||||
/** Dry run (show what would be done) */
|
||||
dryRun?: boolean;
|
||||
/** Continue on task failure */
|
||||
continueOnError?: boolean;
|
||||
/** Environment variables to set */
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkpoint response from user
|
||||
*/
|
||||
export interface CheckpointResponse {
|
||||
/** Whether to continue */
|
||||
continue: boolean;
|
||||
/** Selected option (for decision checkpoints) */
|
||||
selectedOption?: string;
|
||||
/** User notes */
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkpoint handler function type
|
||||
*/
|
||||
export type CheckpointHandler = (
|
||||
task: ExecutableTask,
|
||||
context: { skillName: string; taskIndex: number; totalTasks: number }
|
||||
) => Promise<CheckpointResponse>;
|
||||
@@ -0,0 +1,610 @@
|
||||
/**
|
||||
* Hooks System Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { HookManager, createHookManager } from '../manager.js';
|
||||
import { SkillTriggerEngine, createTriggerEngine } from '../triggers.js';
|
||||
import type { SkillHook, HookEvent, HookContext } from '../types.js';
|
||||
|
||||
describe('HookManager', () => {
|
||||
let tempDir: string;
|
||||
let manager: HookManager;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), 'skillkit-hooks-test-'));
|
||||
manager = createHookManager({ projectPath: tempDir, autoLoad: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('registerHook', () => {
|
||||
it('should register a hook with generated ID', () => {
|
||||
const hook = manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['tdd-workflow'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(hook.id).toBeDefined();
|
||||
expect(hook.event).toBe('session:start');
|
||||
expect(hook.skills).toEqual(['tdd-workflow']);
|
||||
expect(hook.inject).toBe('reference');
|
||||
expect(hook.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should register a hook with custom ID', () => {
|
||||
const hook = manager.registerHook({
|
||||
id: 'my-hook',
|
||||
event: 'file:save',
|
||||
skills: ['code-review'],
|
||||
inject: 'content',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(hook.id).toBe('my-hook');
|
||||
});
|
||||
|
||||
it('should set default values', () => {
|
||||
const hook = manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(hook.priority).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unregisterHook', () => {
|
||||
it('should remove a registered hook', () => {
|
||||
const hook = manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(manager.getHook(hook.id)).toBeDefined();
|
||||
expect(manager.unregisterHook(hook.id)).toBe(true);
|
||||
expect(manager.getHook(hook.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return false for non-existent hook', () => {
|
||||
expect(manager.unregisterHook('non-existent')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getHooksForEvent', () => {
|
||||
it('should return hooks for a specific event', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill1'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill2'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'file:save',
|
||||
skills: ['skill3'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const sessionHooks = manager.getHooksForEvent('session:start');
|
||||
expect(sessionHooks).toHaveLength(2);
|
||||
expect(sessionHooks.every((h) => h.event === 'session:start')).toBe(true);
|
||||
});
|
||||
|
||||
it('should only return enabled hooks', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill1'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill2'],
|
||||
inject: 'reference',
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
const hooks = manager.getHooksForEvent('session:start');
|
||||
expect(hooks).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should sort by priority (higher first)', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['low'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
priority: 1,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['high'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
priority: 10,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['medium'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
priority: 5,
|
||||
});
|
||||
|
||||
const hooks = manager.getHooksForEvent('session:start');
|
||||
expect(hooks[0].skills).toEqual(['high']);
|
||||
expect(hooks[1].skills).toEqual(['medium']);
|
||||
expect(hooks[2].skills).toEqual(['low']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableHook/disableHook', () => {
|
||||
it('should enable a disabled hook', () => {
|
||||
const hook = manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
expect(manager.enableHook(hook.id)).toBe(true);
|
||||
expect(manager.getHook(hook.id)?.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should disable an enabled hook', () => {
|
||||
const hook = manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(manager.disableHook(hook.id)).toBe(true);
|
||||
expect(manager.getHook(hook.id)?.enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should trigger hooks for an event', async () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill1', 'skill2'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const context: HookContext = {
|
||||
event: 'session:start',
|
||||
trigger: 'test',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const result = await manager.trigger('session:start', context);
|
||||
|
||||
expect(result.event).toBe('session:start');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills).toHaveLength(2);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should filter by matcher pattern', async () => {
|
||||
manager.registerHook({
|
||||
event: 'file:save',
|
||||
skills: ['test-skill'],
|
||||
inject: 'reference',
|
||||
matcher: '*.test.ts',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const matchContext: HookContext = {
|
||||
event: 'file:save',
|
||||
trigger: 'foo.test.ts',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const noMatchContext: HookContext = {
|
||||
event: 'file:save',
|
||||
trigger: 'foo.ts',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const matchResult = await manager.trigger('file:save', matchContext);
|
||||
expect(matchResult.matchedHooks).toHaveLength(1);
|
||||
|
||||
const noMatchResult = await manager.trigger('file:save', noMatchContext);
|
||||
expect(noMatchResult.matchedHooks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle injection modes', async () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['ref-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['content-skill'],
|
||||
inject: 'content',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['prompt-skill'],
|
||||
inject: 'prompt',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const context: HookContext = {
|
||||
event: 'session:start',
|
||||
trigger: 'test',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const result = await manager.trigger('session:start', context);
|
||||
|
||||
const refSkill = result.activatedSkills.find((s) => s.skillId === 'ref-skill');
|
||||
expect(refSkill?.reference).toBe('@ref-skill');
|
||||
|
||||
const contentSkill = result.activatedSkills.find((s) => s.skillId === 'content-skill');
|
||||
expect(contentSkill?.content).toBeDefined();
|
||||
|
||||
const promptSkill = result.activatedSkills.find((s) => s.skillId === 'prompt-skill');
|
||||
expect(promptSkill?.content).toContain('prompt-skill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('save/load', () => {
|
||||
it('should save and load hooks', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['skill1'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'file:save',
|
||||
skills: ['skill2'],
|
||||
inject: 'content',
|
||||
enabled: false,
|
||||
matcher: '*.ts',
|
||||
});
|
||||
|
||||
manager.save();
|
||||
|
||||
// Create new manager to load
|
||||
const newManager = createHookManager({ projectPath: tempDir, autoLoad: true });
|
||||
const hooks = newManager.getAllHooks();
|
||||
|
||||
expect(hooks).toHaveLength(2);
|
||||
expect(hooks.find((h) => h.skills[0] === 'skill1')).toBeDefined();
|
||||
expect(hooks.find((h) => h.skills[0] === 'skill2')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateAgentHooks', () => {
|
||||
it('should generate Claude Code hooks format', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['tdd'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const hooks = manager.generateAgentHooks('claude-code');
|
||||
expect(hooks).toHaveProperty('hooks');
|
||||
expect((hooks as any).hooks).toBeInstanceOf(Array);
|
||||
});
|
||||
|
||||
it('should generate Cursor rules format', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['tdd'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const rules = manager.generateAgentHooks('cursor');
|
||||
expect(typeof rules).toBe('string');
|
||||
expect(rules).toContain('session start');
|
||||
});
|
||||
|
||||
it('should generate generic format for other agents', () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['tdd'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const content = manager.generateAgentHooks('gemini-cli');
|
||||
expect(typeof content).toBe('string');
|
||||
expect(content).toContain('Skill Activation Triggers');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listeners', () => {
|
||||
it('should notify listeners on trigger', async () => {
|
||||
let notified = false;
|
||||
manager.addListener((event, context, result) => {
|
||||
notified = true;
|
||||
expect(event).toBe('session:start');
|
||||
});
|
||||
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
await manager.trigger('session:start', {
|
||||
event: 'session:start',
|
||||
trigger: 'test',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
expect(notified).toBe(true);
|
||||
});
|
||||
|
||||
it('should remove listeners', async () => {
|
||||
let callCount = 0;
|
||||
const listener = () => {
|
||||
callCount++;
|
||||
};
|
||||
|
||||
manager.addListener(listener);
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const context: HookContext = {
|
||||
event: 'session:start',
|
||||
trigger: 'test',
|
||||
projectPath: tempDir,
|
||||
agent: 'claude-code',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
await manager.trigger('session:start', context);
|
||||
expect(callCount).toBe(1);
|
||||
|
||||
manager.removeListener(listener);
|
||||
await manager.trigger('session:start', context);
|
||||
expect(callCount).toBe(1); // Should not increase
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SkillTriggerEngine', () => {
|
||||
let tempDir: string;
|
||||
let manager: HookManager;
|
||||
let engine: SkillTriggerEngine;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), 'skillkit-trigger-test-'));
|
||||
manager = createHookManager({ projectPath: tempDir, autoLoad: false });
|
||||
engine = createTriggerEngine(manager, { projectPath: tempDir, watchFiles: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
engine.stop();
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('lifecycle', () => {
|
||||
it('should start and stop', async () => {
|
||||
let sessionStartTriggered = false;
|
||||
let sessionEndTriggered = false;
|
||||
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['start-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'session:end',
|
||||
skills: ['end-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
manager.addListener((event) => {
|
||||
if (event === 'session:start') sessionStartTriggered = true;
|
||||
if (event === 'session:end') sessionEndTriggered = true;
|
||||
});
|
||||
|
||||
engine.start('claude-code');
|
||||
// Give it a moment to process
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(sessionStartTriggered).toBe(true);
|
||||
expect(engine.isActive()).toBe(true);
|
||||
|
||||
engine.stop();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(sessionEndTriggered).toBe(true);
|
||||
expect(engine.isActive()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('event triggering', () => {
|
||||
beforeEach(() => {
|
||||
manager.registerHook({
|
||||
event: 'file:save',
|
||||
skills: ['save-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'task:start',
|
||||
skills: ['task-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'commit:pre',
|
||||
skills: ['commit-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'error:occur',
|
||||
skills: ['error-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'test:fail',
|
||||
skills: ['test-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
manager.registerHook({
|
||||
event: 'build:fail',
|
||||
skills: ['build-skill'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should trigger file save event', async () => {
|
||||
const result = await engine.triggerFileSave('src/index.ts');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('save-skill');
|
||||
});
|
||||
|
||||
it('should trigger task start event', async () => {
|
||||
const result = await engine.triggerTaskStart('implement-feature', 'task-123');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('task-skill');
|
||||
});
|
||||
|
||||
it('should trigger pre-commit event', async () => {
|
||||
const result = await engine.triggerPreCommit('feat: add new feature');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('commit-skill');
|
||||
});
|
||||
|
||||
it('should trigger error event', async () => {
|
||||
const result = await engine.triggerError(new Error('Something went wrong'), 'test-context');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('error-skill');
|
||||
});
|
||||
|
||||
it('should trigger test fail event', async () => {
|
||||
const result = await engine.triggerTestFail('should add numbers', 'Expected 4 but got 5');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('test-skill');
|
||||
});
|
||||
|
||||
it('should trigger build fail event', async () => {
|
||||
const result = await engine.triggerBuildFail('TypeScript error');
|
||||
expect(result.matchedHooks).toHaveLength(1);
|
||||
expect(result.activatedSkills[0].skillId).toBe('build-skill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('agent setting', () => {
|
||||
it('should use the set agent in context', async () => {
|
||||
manager.registerHook({
|
||||
event: 'session:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
let capturedAgent: string | null = null;
|
||||
manager.addListener((event, context) => {
|
||||
capturedAgent = context.agent;
|
||||
});
|
||||
|
||||
engine.setAgent('cursor');
|
||||
await engine.triggerEvent('session:start', 'test');
|
||||
|
||||
expect(capturedAgent).toBe('cursor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listeners', () => {
|
||||
it('should notify engine listeners', async () => {
|
||||
let notified = false;
|
||||
engine.addListener((event) => {
|
||||
notified = true;
|
||||
expect(event).toBe('task:start');
|
||||
});
|
||||
|
||||
manager.registerHook({
|
||||
event: 'task:start',
|
||||
skills: ['test'],
|
||||
inject: 'reference',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
await engine.triggerTaskStart('test-task');
|
||||
expect(notified).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hook Event Types', () => {
|
||||
it('should support all documented events', () => {
|
||||
const events: HookEvent[] = [
|
||||
'session:start',
|
||||
'session:resume',
|
||||
'session:end',
|
||||
'file:open',
|
||||
'file:save',
|
||||
'file:create',
|
||||
'file:delete',
|
||||
'task:start',
|
||||
'task:complete',
|
||||
'commit:pre',
|
||||
'commit:post',
|
||||
'error:occur',
|
||||
'test:fail',
|
||||
'test:pass',
|
||||
'build:start',
|
||||
'build:fail',
|
||||
'build:success',
|
||||
];
|
||||
|
||||
// Just verify all events are valid strings
|
||||
expect(events).toHaveLength(17);
|
||||
events.forEach((event) => {
|
||||
expect(typeof event).toBe('string');
|
||||
expect(event).toContain(':');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Hooks & Automatic Triggering System
|
||||
*
|
||||
* Provides event-driven skill activation across all supported agents.
|
||||
*
|
||||
* Key features:
|
||||
* - 17+ hook events (session, file, task, commit, error, test, build)
|
||||
* - Pattern matching with glob support
|
||||
* - Agent-specific hook generation
|
||||
* - File watching for automatic triggers
|
||||
* - Condition expressions for complex logic
|
||||
*/
|
||||
|
||||
// Manager
|
||||
export { HookManager, createHookManager } from './manager.js';
|
||||
|
||||
// Trigger Engine
|
||||
export { SkillTriggerEngine, createTriggerEngine } from './triggers.js';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
HookEvent,
|
||||
InjectionMode,
|
||||
SkillHook,
|
||||
HookContext,
|
||||
ActivatedSkill,
|
||||
HookTriggerResult,
|
||||
HookError,
|
||||
HookConfig,
|
||||
AgentHookFormat,
|
||||
HookManagerOptions,
|
||||
TriggerEngineOptions,
|
||||
HookEventListener,
|
||||
MatcherFunction,
|
||||
} from './types.js';
|
||||
@@ -0,0 +1,539 @@
|
||||
/**
|
||||
* Hook Manager
|
||||
*
|
||||
* Manages skill hooks for automatic triggering across all supported agents.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { minimatch } from 'minimatch';
|
||||
import type { AgentType } from '../types.js';
|
||||
import type {
|
||||
SkillHook,
|
||||
HookEvent,
|
||||
HookContext,
|
||||
HookConfig,
|
||||
HookManagerOptions,
|
||||
ActivatedSkill,
|
||||
HookTriggerResult,
|
||||
HookError,
|
||||
HookEventListener,
|
||||
} from './types.js';
|
||||
|
||||
const DEFAULT_CONFIG_PATH = '.skillkit/hooks.json';
|
||||
|
||||
/**
|
||||
* HookManager - Manages skill hooks for automatic triggering
|
||||
*/
|
||||
export class HookManager {
|
||||
private hooks: Map<string, SkillHook> = new Map();
|
||||
private listeners: Set<HookEventListener> = new Set();
|
||||
private options: Required<HookManagerOptions>;
|
||||
|
||||
constructor(options: HookManagerOptions) {
|
||||
this.options = {
|
||||
projectPath: options.projectPath,
|
||||
configPath: options.configPath || join(options.projectPath, DEFAULT_CONFIG_PATH),
|
||||
autoLoad: options.autoLoad ?? true,
|
||||
defaultInjectionMode: options.defaultInjectionMode || 'reference',
|
||||
};
|
||||
|
||||
if (this.options.autoLoad) {
|
||||
this.load();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new hook
|
||||
*/
|
||||
registerHook(hook: Omit<SkillHook, 'id'> & { id?: string }): SkillHook {
|
||||
const fullHook: SkillHook = {
|
||||
...hook,
|
||||
id: hook.id || randomUUID(),
|
||||
inject: hook.inject || this.options.defaultInjectionMode,
|
||||
enabled: hook.enabled ?? true,
|
||||
priority: hook.priority ?? 0,
|
||||
};
|
||||
|
||||
this.hooks.set(fullHook.id, fullHook);
|
||||
return fullHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a hook by ID
|
||||
*/
|
||||
unregisterHook(id: string): boolean {
|
||||
return this.hooks.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a hook by ID
|
||||
*/
|
||||
getHook(id: string): SkillHook | undefined {
|
||||
return this.hooks.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all hooks
|
||||
*/
|
||||
getAllHooks(): SkillHook[] {
|
||||
return Array.from(this.hooks.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get hooks for a specific event
|
||||
*/
|
||||
getHooksForEvent(event: HookEvent): SkillHook[] {
|
||||
return this.getAllHooks()
|
||||
.filter((hook) => hook.event === event && hook.enabled)
|
||||
.sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a hook
|
||||
*/
|
||||
updateHook(id: string, updates: Partial<SkillHook>): SkillHook | undefined {
|
||||
const existing = this.hooks.get(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const updated = { ...existing, ...updates, id };
|
||||
this.hooks.set(id, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable a hook
|
||||
*/
|
||||
enableHook(id: string): boolean {
|
||||
const hook = this.hooks.get(id);
|
||||
if (!hook) return false;
|
||||
hook.enabled = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable a hook
|
||||
*/
|
||||
disableHook(id: string): boolean {
|
||||
const hook = this.hooks.get(id);
|
||||
if (!hook) return false;
|
||||
hook.enabled = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger hooks for an event
|
||||
*/
|
||||
async trigger(event: HookEvent, context: HookContext): Promise<HookTriggerResult> {
|
||||
const startTime = Date.now();
|
||||
const matchedHooks: SkillHook[] = [];
|
||||
const activatedSkills: ActivatedSkill[] = [];
|
||||
const errors: HookError[] = [];
|
||||
|
||||
const hooks = this.getHooksForEvent(event);
|
||||
|
||||
for (const hook of hooks) {
|
||||
try {
|
||||
// Check if matcher matches
|
||||
if (hook.matcher && !this.matchesTrigger(hook.matcher, context.trigger)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check condition if present
|
||||
if (hook.condition && !this.evaluateCondition(hook.condition, context)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedHooks.push(hook);
|
||||
|
||||
// Apply agent-specific overrides
|
||||
const effectiveHook = this.applyAgentOverrides(hook, context.agent);
|
||||
|
||||
// Activate each skill
|
||||
for (const skillId of effectiveHook.skills) {
|
||||
try {
|
||||
const activated = await this.activateSkill(skillId, effectiveHook, context);
|
||||
activatedSkills.push(activated);
|
||||
} catch (err) {
|
||||
errors.push({
|
||||
hookId: hook.id,
|
||||
skillId,
|
||||
message: err instanceof Error ? err.message : 'Unknown error',
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
errors.push({
|
||||
hookId: hook.id,
|
||||
message: err instanceof Error ? err.message : 'Unknown error',
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result: HookTriggerResult = {
|
||||
event,
|
||||
matchedHooks,
|
||||
activatedSkills,
|
||||
errors,
|
||||
executionTimeMs: Date.now() - startTime,
|
||||
};
|
||||
|
||||
// Notify listeners
|
||||
await this.notifyListeners(event, context, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
*/
|
||||
addListener(listener: HookEventListener): void {
|
||||
this.listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event listener
|
||||
*/
|
||||
removeListener(listener: HookEventListener): void {
|
||||
this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load hooks from config file
|
||||
*/
|
||||
load(): void {
|
||||
if (!existsSync(this.options.configPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(this.options.configPath, 'utf-8');
|
||||
const config: HookConfig = JSON.parse(content);
|
||||
|
||||
this.hooks.clear();
|
||||
for (const hook of config.hooks) {
|
||||
this.hooks.set(hook.id, {
|
||||
...hook,
|
||||
inject: hook.inject || config.defaults?.inject || this.options.defaultInjectionMode,
|
||||
priority: hook.priority ?? config.defaults?.priority ?? 0,
|
||||
enabled: hook.enabled ?? config.defaults?.enabled ?? true,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors, start with empty hooks
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save hooks to config file
|
||||
*/
|
||||
save(): void {
|
||||
const config: HookConfig = {
|
||||
version: 1,
|
||||
hooks: this.getAllHooks(),
|
||||
defaults: {
|
||||
inject: this.options.defaultInjectionMode,
|
||||
priority: 0,
|
||||
enabled: true,
|
||||
},
|
||||
};
|
||||
|
||||
const dir = dirname(this.options.configPath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
writeFileSync(this.options.configPath, JSON.stringify(config, null, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate agent-specific hook configuration
|
||||
*/
|
||||
generateAgentHooks(agent: AgentType): string | Record<string, unknown> {
|
||||
const hooks = this.getAllHooks().filter((h) => h.enabled);
|
||||
|
||||
switch (agent) {
|
||||
case 'claude-code':
|
||||
return this.generateClaudeCodeHooks(hooks);
|
||||
case 'cursor':
|
||||
return this.generateCursorHooks(hooks);
|
||||
case 'opencode':
|
||||
return this.generateOpenCodeHooks(hooks);
|
||||
default:
|
||||
return this.generateGenericHooks(hooks);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Claude Code hooks.json format
|
||||
*/
|
||||
private generateClaudeCodeHooks(hooks: SkillHook[]): Record<string, unknown> {
|
||||
const hookEntries: Record<string, unknown>[] = [];
|
||||
|
||||
for (const hook of hooks) {
|
||||
// Map our events to Claude Code hook events
|
||||
const claudeEvent = this.mapToClaudeCodeEvent(hook.event);
|
||||
if (!claudeEvent) continue;
|
||||
|
||||
hookEntries.push({
|
||||
event: claudeEvent,
|
||||
command: this.generateClaudeCommand(hook),
|
||||
matcher: hook.matcher ? String(hook.matcher) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return { hooks: hookEntries };
|
||||
}
|
||||
|
||||
/**
|
||||
* Map SkillKit events to Claude Code events
|
||||
*/
|
||||
private mapToClaudeCodeEvent(event: HookEvent): string | null {
|
||||
const mapping: Record<HookEvent, string | null> = {
|
||||
'session:start': 'SessionStart',
|
||||
'session:resume': 'SessionResume',
|
||||
'session:end': 'SessionEnd',
|
||||
'file:open': null,
|
||||
'file:save': 'PreToolUse',
|
||||
'file:create': 'PostToolUse',
|
||||
'file:delete': 'PostToolUse',
|
||||
'task:start': null,
|
||||
'task:complete': null,
|
||||
'commit:pre': 'PreToolUse',
|
||||
'commit:post': 'PostToolUse',
|
||||
'error:occur': null,
|
||||
'test:fail': 'PostToolUse',
|
||||
'test:pass': 'PostToolUse',
|
||||
'build:start': 'PreToolUse',
|
||||
'build:fail': 'PostToolUse',
|
||||
'build:success': 'PostToolUse',
|
||||
};
|
||||
return mapping[event];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Claude Code command for a hook
|
||||
*/
|
||||
private generateClaudeCommand(hook: SkillHook): string {
|
||||
const skillRefs = hook.skills.map((s) => `@${s}`).join(' ');
|
||||
return `echo "Activating skills: ${skillRefs}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Cursor rules with hooks
|
||||
*/
|
||||
private generateCursorHooks(hooks: SkillHook[]): string {
|
||||
const lines: string[] = ['# Auto-generated skill activation rules', ''];
|
||||
|
||||
for (const hook of hooks) {
|
||||
lines.push(`## ${hook.event} Hook`);
|
||||
lines.push(`When ${hook.event.replace(':', ' ')} occurs:`);
|
||||
for (const skill of hook.skills) {
|
||||
lines.push(`- Apply skill: ${skill}`);
|
||||
}
|
||||
if (hook.matcher) {
|
||||
lines.push(`- Pattern: ${hook.matcher}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate OpenCode hooks
|
||||
*/
|
||||
private generateOpenCodeHooks(hooks: SkillHook[]): Record<string, unknown> {
|
||||
return {
|
||||
triggers: hooks.map((hook) => ({
|
||||
event: hook.event,
|
||||
skills: hook.skills,
|
||||
matcher: hook.matcher ? String(hook.matcher) : undefined,
|
||||
enabled: hook.enabled,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate generic AGENTS.md injection for unsupported agents
|
||||
*/
|
||||
private generateGenericHooks(hooks: SkillHook[]): string {
|
||||
const lines: string[] = [
|
||||
'# Skill Activation Triggers',
|
||||
'',
|
||||
'The following skills should be activated based on events:',
|
||||
'',
|
||||
];
|
||||
|
||||
const eventGroups = new Map<HookEvent, SkillHook[]>();
|
||||
for (const hook of hooks) {
|
||||
const group = eventGroups.get(hook.event) || [];
|
||||
group.push(hook);
|
||||
eventGroups.set(hook.event, group);
|
||||
}
|
||||
|
||||
for (const [event, eventHooks] of eventGroups) {
|
||||
lines.push(`## On ${event.replace(':', ' ').replace(/\b\w/g, (c) => c.toUpperCase())}`);
|
||||
for (const hook of eventHooks) {
|
||||
lines.push(`- Activate: ${hook.skills.join(', ')}`);
|
||||
if (hook.matcher) {
|
||||
lines.push(` - When matching: ${hook.matcher}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if trigger matches the pattern
|
||||
*/
|
||||
private matchesTrigger(matcher: string | RegExp, trigger: string): boolean {
|
||||
if (matcher instanceof RegExp) {
|
||||
return matcher.test(trigger);
|
||||
}
|
||||
// Use minimatch for glob patterns
|
||||
return minimatch(trigger, matcher);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate condition expression
|
||||
*/
|
||||
private evaluateCondition(condition: string, context: HookContext): boolean {
|
||||
// Simple condition evaluation
|
||||
// Supports: event == 'x', trigger.includes('y'), metadata.key == 'value'
|
||||
try {
|
||||
const safeContext = {
|
||||
event: context.event,
|
||||
trigger: context.trigger,
|
||||
agent: context.agent,
|
||||
metadata: context.metadata || {},
|
||||
};
|
||||
|
||||
// Very basic expression evaluation
|
||||
if (condition.includes('==')) {
|
||||
const [left, right] = condition.split('==').map((s) => s.trim());
|
||||
const leftVal = this.resolveValue(left, safeContext);
|
||||
const rightVal = right.replace(/['"]/g, '');
|
||||
return leftVal === rightVal;
|
||||
}
|
||||
|
||||
if (condition.includes('.includes(')) {
|
||||
const match = condition.match(/(\w+)\.includes\(['"](.+)['"]\)/);
|
||||
if (match) {
|
||||
const [, prop, search] = match;
|
||||
const val = this.resolveValue(prop, safeContext);
|
||||
return typeof val === 'string' && val.includes(search);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a value from context
|
||||
*/
|
||||
private resolveValue(path: string, context: Record<string, unknown>): unknown {
|
||||
const parts = path.split('.');
|
||||
let current: unknown = context;
|
||||
|
||||
for (const part of parts) {
|
||||
if (current && typeof current === 'object' && part in current) {
|
||||
current = (current as Record<string, unknown>)[part];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply agent-specific overrides to a hook
|
||||
*/
|
||||
private applyAgentOverrides(hook: SkillHook, agent: AgentType): SkillHook {
|
||||
if (!hook.agentOverrides || !hook.agentOverrides[agent]) {
|
||||
return hook;
|
||||
}
|
||||
|
||||
return {
|
||||
...hook,
|
||||
...hook.agentOverrides[agent],
|
||||
id: hook.id,
|
||||
event: hook.event,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate a skill from a hook
|
||||
*/
|
||||
private async activateSkill(
|
||||
skillId: string,
|
||||
hook: SkillHook,
|
||||
context: HookContext
|
||||
): Promise<ActivatedSkill> {
|
||||
const activated: ActivatedSkill = {
|
||||
skillId,
|
||||
hookId: hook.id,
|
||||
injectionMode: hook.inject,
|
||||
activatedAt: new Date(),
|
||||
};
|
||||
|
||||
switch (hook.inject) {
|
||||
case 'content':
|
||||
// Load skill content
|
||||
activated.content = await this.loadSkillContent(skillId, context);
|
||||
break;
|
||||
case 'reference':
|
||||
// Create reference
|
||||
activated.reference = `@${skillId}`;
|
||||
break;
|
||||
case 'prompt':
|
||||
// Create prompt injection
|
||||
activated.content = `Please apply the "${skillId}" skill to this task.`;
|
||||
break;
|
||||
}
|
||||
|
||||
return activated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load skill content (placeholder - integrates with skill loader)
|
||||
*/
|
||||
private async loadSkillContent(skillId: string, _context: HookContext): Promise<string> {
|
||||
// This would integrate with the methodology loader or skill manager
|
||||
// For now, return a placeholder
|
||||
return `# Skill: ${skillId}\n\nThis skill was auto-activated by a hook.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all listeners of a trigger event
|
||||
*/
|
||||
private async notifyListeners(
|
||||
event: HookEvent,
|
||||
context: HookContext,
|
||||
result: HookTriggerResult
|
||||
): Promise<void> {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
await listener(event, context, result);
|
||||
} catch {
|
||||
// Ignore listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a HookManager instance
|
||||
*/
|
||||
export function createHookManager(options: HookManagerOptions): HookManager {
|
||||
return new HookManager(options);
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Skill Trigger Engine
|
||||
*
|
||||
* Monitors events and triggers skill activation based on configured hooks.
|
||||
*/
|
||||
|
||||
import { watch, type FSWatcher } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import type { AgentType } from '../types.js';
|
||||
import type {
|
||||
HookEvent,
|
||||
HookContext,
|
||||
HookTriggerResult,
|
||||
TriggerEngineOptions,
|
||||
HookEventListener,
|
||||
} from './types.js';
|
||||
import { HookManager } from './manager.js';
|
||||
|
||||
/**
|
||||
* Debounce helper
|
||||
*/
|
||||
function debounce<T extends (...args: string[]) => void>(
|
||||
fn: T,
|
||||
delay: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
return (...args: Parameters<T>) => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => fn(...args), delay);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* SkillTriggerEngine - Monitors events and triggers skill activation
|
||||
*/
|
||||
export class SkillTriggerEngine {
|
||||
private hookManager: HookManager;
|
||||
private options: Required<TriggerEngineOptions>;
|
||||
private watchers: Map<string, FSWatcher> = new Map();
|
||||
private listeners: Set<HookEventListener> = new Set();
|
||||
private isRunning = false;
|
||||
private currentAgent: AgentType = 'universal';
|
||||
|
||||
constructor(hookManager: HookManager, options: TriggerEngineOptions) {
|
||||
this.hookManager = hookManager;
|
||||
this.options = {
|
||||
projectPath: options.projectPath,
|
||||
watchFiles: options.watchFiles ?? false,
|
||||
debounceMs: options.debounceMs ?? 100,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the trigger engine
|
||||
*/
|
||||
start(agent?: AgentType): void {
|
||||
if (this.isRunning) return;
|
||||
|
||||
this.isRunning = true;
|
||||
this.currentAgent = agent || 'universal';
|
||||
|
||||
if (this.options.watchFiles) {
|
||||
this.startFileWatcher();
|
||||
}
|
||||
|
||||
// Trigger session:start
|
||||
this.triggerEvent('session:start', 'engine_start');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the trigger engine
|
||||
*/
|
||||
stop(): void {
|
||||
if (!this.isRunning) return;
|
||||
|
||||
// Trigger session:end
|
||||
this.triggerEvent('session:end', 'engine_stop');
|
||||
|
||||
this.stopFileWatcher();
|
||||
this.isRunning = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current agent
|
||||
*/
|
||||
setAgent(agent: AgentType): void {
|
||||
this.currentAgent = agent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually trigger an event
|
||||
*/
|
||||
async triggerEvent(
|
||||
event: HookEvent,
|
||||
trigger: string,
|
||||
metadata?: Record<string, unknown>
|
||||
): Promise<HookTriggerResult> {
|
||||
const context: HookContext = {
|
||||
event,
|
||||
trigger,
|
||||
projectPath: this.options.projectPath,
|
||||
agent: this.currentAgent,
|
||||
metadata,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const result = await this.hookManager.trigger(event, context);
|
||||
|
||||
// Notify local listeners
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
await listener(event, context, result);
|
||||
} catch {
|
||||
// Ignore listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger file:open event
|
||||
*/
|
||||
async triggerFileOpen(filePath: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('file:open', filePath, { filePath });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger file:save event
|
||||
*/
|
||||
async triggerFileSave(filePath: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('file:save', filePath, { filePath });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger file:create event
|
||||
*/
|
||||
async triggerFileCreate(filePath: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('file:create', filePath, { filePath });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger file:delete event
|
||||
*/
|
||||
async triggerFileDelete(filePath: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('file:delete', filePath, { filePath });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger task:start event
|
||||
*/
|
||||
async triggerTaskStart(taskName: string, taskId?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('task:start', taskName, { taskName, taskId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger task:complete event
|
||||
*/
|
||||
async triggerTaskComplete(
|
||||
taskName: string,
|
||||
taskId?: string,
|
||||
success?: boolean
|
||||
): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('task:complete', taskName, { taskName, taskId, success });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger commit:pre event
|
||||
*/
|
||||
async triggerPreCommit(message?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('commit:pre', 'git_commit', { message });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger commit:post event
|
||||
*/
|
||||
async triggerPostCommit(commitHash?: string, message?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('commit:post', 'git_commit', { commitHash, message });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger error:occur event
|
||||
*/
|
||||
async triggerError(error: Error | string, context?: string): Promise<HookTriggerResult> {
|
||||
const errorMessage = error instanceof Error ? error.message : error;
|
||||
const errorStack = error instanceof Error ? error.stack : undefined;
|
||||
return this.triggerEvent('error:occur', errorMessage, { error: errorMessage, stack: errorStack, context });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger test:fail event
|
||||
*/
|
||||
async triggerTestFail(testName: string, error?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('test:fail', testName, { testName, error });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger test:pass event
|
||||
*/
|
||||
async triggerTestPass(testName: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('test:pass', testName, { testName });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger build:start event
|
||||
*/
|
||||
async triggerBuildStart(command?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('build:start', 'build', { command });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger build:fail event
|
||||
*/
|
||||
async triggerBuildFail(error?: string): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('build:fail', 'build', { error });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger build:success event
|
||||
*/
|
||||
async triggerBuildSuccess(): Promise<HookTriggerResult> {
|
||||
return this.triggerEvent('build:success', 'build', {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
*/
|
||||
addListener(listener: HookEventListener): void {
|
||||
this.listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event listener
|
||||
*/
|
||||
removeListener(listener: HookEventListener): void {
|
||||
this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if engine is running
|
||||
*/
|
||||
isActive(): boolean {
|
||||
return this.isRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start file watcher
|
||||
*/
|
||||
private startFileWatcher(): void {
|
||||
try {
|
||||
const watcher = watch(
|
||||
this.options.projectPath,
|
||||
{ recursive: true },
|
||||
debounce((eventType: string, filename: string | null) => {
|
||||
if (!filename) return;
|
||||
|
||||
const relativePath = relative(this.options.projectPath, join(this.options.projectPath, filename));
|
||||
|
||||
// Skip node_modules, .git, etc.
|
||||
if (this.shouldIgnore(relativePath)) return;
|
||||
|
||||
if (eventType === 'rename') {
|
||||
// Could be create or delete
|
||||
this.triggerFileCreate(relativePath);
|
||||
} else if (eventType === 'change') {
|
||||
this.triggerFileSave(relativePath);
|
||||
}
|
||||
}, this.options.debounceMs)
|
||||
);
|
||||
|
||||
this.watchers.set('main', watcher);
|
||||
} catch {
|
||||
// File watching not available
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop file watcher
|
||||
*/
|
||||
private stopFileWatcher(): void {
|
||||
for (const watcher of this.watchers.values()) {
|
||||
watcher.close();
|
||||
}
|
||||
this.watchers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path should be ignored
|
||||
*/
|
||||
private shouldIgnore(filePath: string): boolean {
|
||||
const ignorePaths = [
|
||||
'node_modules',
|
||||
'.git',
|
||||
'.skillkit',
|
||||
'dist',
|
||||
'build',
|
||||
'coverage',
|
||||
'.next',
|
||||
'.nuxt',
|
||||
];
|
||||
|
||||
return ignorePaths.some((ignore) => filePath.includes(ignore));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a SkillTriggerEngine instance
|
||||
*/
|
||||
export function createTriggerEngine(
|
||||
hookManager: HookManager,
|
||||
options: TriggerEngineOptions
|
||||
): SkillTriggerEngine {
|
||||
return new SkillTriggerEngine(hookManager, options);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Hooks & Automatic Triggering System Types
|
||||
*
|
||||
* Provides event-driven skill activation across all supported agents.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
/**
|
||||
* Hook events that can trigger skill activation
|
||||
*/
|
||||
export type HookEvent =
|
||||
| 'session:start'
|
||||
| 'session:resume'
|
||||
| 'session:end'
|
||||
| 'file:open'
|
||||
| 'file:save'
|
||||
| 'file:create'
|
||||
| 'file:delete'
|
||||
| 'task:start'
|
||||
| 'task:complete'
|
||||
| 'commit:pre'
|
||||
| 'commit:post'
|
||||
| 'error:occur'
|
||||
| 'test:fail'
|
||||
| 'test:pass'
|
||||
| 'build:start'
|
||||
| 'build:fail'
|
||||
| 'build:success';
|
||||
|
||||
/**
|
||||
* How to inject the skill when triggered
|
||||
*/
|
||||
export type InjectionMode = 'content' | 'reference' | 'prompt';
|
||||
|
||||
/**
|
||||
* Skill hook configuration
|
||||
*/
|
||||
export interface SkillHook {
|
||||
/** Unique identifier for this hook */
|
||||
id: string;
|
||||
/** Event that triggers this hook */
|
||||
event: HookEvent;
|
||||
/** Pattern to match (e.g., "*.test.ts", "src/**\/*.tsx") */
|
||||
matcher?: string | RegExp;
|
||||
/** Skills to activate when triggered */
|
||||
skills: string[];
|
||||
/** How to inject the skill */
|
||||
inject: InjectionMode;
|
||||
/** Priority (higher = earlier execution) */
|
||||
priority?: number;
|
||||
/** Condition expression (optional) */
|
||||
condition?: string;
|
||||
/** Whether hook is enabled */
|
||||
enabled: boolean;
|
||||
/** Agent-specific overrides */
|
||||
agentOverrides?: Partial<Record<AgentType, Partial<SkillHook>>>;
|
||||
/** Metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context provided when a hook is triggered
|
||||
*/
|
||||
export interface HookContext {
|
||||
/** The event that was triggered */
|
||||
event: HookEvent;
|
||||
/** What triggered the event (filename, command, etc.) */
|
||||
trigger: string;
|
||||
/** Project path */
|
||||
projectPath: string;
|
||||
/** Target agent */
|
||||
agent: AgentType;
|
||||
/** Additional metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
/** Timestamp */
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of activating a skill via hook
|
||||
*/
|
||||
export interface ActivatedSkill {
|
||||
/** Skill ID */
|
||||
skillId: string;
|
||||
/** Hook that activated it */
|
||||
hookId: string;
|
||||
/** Injection mode used */
|
||||
injectionMode: InjectionMode;
|
||||
/** The skill content (if injection mode is 'content') */
|
||||
content?: string;
|
||||
/** The skill reference (if injection mode is 'reference') */
|
||||
reference?: string;
|
||||
/** Activation timestamp */
|
||||
activatedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook trigger result
|
||||
*/
|
||||
export interface HookTriggerResult {
|
||||
/** Event that was triggered */
|
||||
event: HookEvent;
|
||||
/** Hooks that matched */
|
||||
matchedHooks: SkillHook[];
|
||||
/** Skills that were activated */
|
||||
activatedSkills: ActivatedSkill[];
|
||||
/** Any errors that occurred */
|
||||
errors: HookError[];
|
||||
/** Total execution time in ms */
|
||||
executionTimeMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook error
|
||||
*/
|
||||
export interface HookError {
|
||||
hookId: string;
|
||||
skillId?: string;
|
||||
message: string;
|
||||
stack?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook configuration file format
|
||||
*/
|
||||
export interface HookConfig {
|
||||
version: number;
|
||||
hooks: SkillHook[];
|
||||
defaults?: {
|
||||
inject?: InjectionMode;
|
||||
priority?: number;
|
||||
enabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent-specific hook format generator
|
||||
*/
|
||||
export interface AgentHookFormat {
|
||||
/** Agent type */
|
||||
agent: AgentType;
|
||||
/** Generate hook configuration for this agent */
|
||||
generate(hooks: SkillHook[]): string | Record<string, unknown>;
|
||||
/** Parse agent-specific hook format */
|
||||
parse(content: string | Record<string, unknown>): SkillHook[];
|
||||
/** File path for hook configuration */
|
||||
configPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook manager options
|
||||
*/
|
||||
export interface HookManagerOptions {
|
||||
/** Project path */
|
||||
projectPath: string;
|
||||
/** Path to hooks configuration file */
|
||||
configPath?: string;
|
||||
/** Whether to auto-load hooks on init */
|
||||
autoLoad?: boolean;
|
||||
/** Default injection mode */
|
||||
defaultInjectionMode?: InjectionMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger engine options
|
||||
*/
|
||||
export interface TriggerEngineOptions {
|
||||
/** Project path */
|
||||
projectPath: string;
|
||||
/** Whether to enable file watching */
|
||||
watchFiles?: boolean;
|
||||
/** Debounce time for file events (ms) */
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook event listener
|
||||
*/
|
||||
export type HookEventListener = (
|
||||
event: HookEvent,
|
||||
context: HookContext,
|
||||
result: HookTriggerResult
|
||||
) => void | Promise<void>;
|
||||
|
||||
/**
|
||||
* Matcher function type
|
||||
*/
|
||||
export type MatcherFunction = (trigger: string, context: HookContext) => boolean;
|
||||
@@ -18,3 +18,51 @@ export * from './context/index.js';
|
||||
|
||||
// Recommendation Engine (Smart Recommendations)
|
||||
export * from './recommend/index.js';
|
||||
|
||||
// Session Management (Pause/Resume Support)
|
||||
export * from './session/index.js';
|
||||
|
||||
// Workflow Orchestration (Skill Composition)
|
||||
export * from './workflow/index.js';
|
||||
|
||||
// Skill Execution Engine
|
||||
export * from './executor/index.js';
|
||||
|
||||
// Skill Testing Framework
|
||||
export * from './testing/index.js';
|
||||
|
||||
// Skill Marketplace (Aggregated Index)
|
||||
export * from './marketplace/index.js';
|
||||
|
||||
// CI/CD Integration (Templates & Utilities)
|
||||
export * from './cicd/index.js';
|
||||
|
||||
// Memory System (Cross-Agent Session Memory)
|
||||
export * from './memory/index.js';
|
||||
|
||||
// Team Collaboration (Skill Sharing)
|
||||
export * from './team/index.js';
|
||||
|
||||
// Plugin System (Extensibility)
|
||||
export * from './plugins/index.js';
|
||||
|
||||
// Methodology Framework (Phase 12)
|
||||
export * from './methodology/index.js';
|
||||
|
||||
// Hooks & Automatic Triggering System (Phase 13)
|
||||
export * from './hooks/index.js';
|
||||
|
||||
// Team Orchestration System (Phase 14)
|
||||
export * from './orchestrator/index.js';
|
||||
|
||||
// Structured Plan System (Phase 15)
|
||||
export * from './plan/index.js';
|
||||
|
||||
// Slash Commands & Agent Integration (Phase 16)
|
||||
export * from './commands/index.js';
|
||||
|
||||
// AI-Powered Features (Phase 18)
|
||||
export * from './ai/index.js';
|
||||
|
||||
// Audit Logging (Phase 18)
|
||||
export * from './audit/index.js';
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
/**
|
||||
* Marketplace Aggregator
|
||||
*
|
||||
* Fetches and indexes skills from multiple GitHub repositories.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import type {
|
||||
SkillSource,
|
||||
MarketplaceSkill,
|
||||
MarketplaceIndex,
|
||||
MarketplaceSearchOptions,
|
||||
MarketplaceSearchResult,
|
||||
MarketplaceConfig,
|
||||
} from './types.js';
|
||||
import {
|
||||
DEFAULT_SKILL_SOURCES,
|
||||
MARKETPLACE_CACHE_FILE,
|
||||
DEFAULT_CACHE_TTL,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Marketplace Aggregator
|
||||
*/
|
||||
export class MarketplaceAggregator {
|
||||
private config: MarketplaceConfig;
|
||||
private cacheDir: string;
|
||||
private cachePath: string;
|
||||
private index: MarketplaceIndex | null = null;
|
||||
|
||||
constructor(config: MarketplaceConfig = {}) {
|
||||
this.config = config;
|
||||
this.cacheDir = config.cacheDir || join(homedir(), '.skillkit', 'marketplace');
|
||||
this.cachePath = join(this.cacheDir, MARKETPLACE_CACHE_FILE);
|
||||
|
||||
// Ensure cache directory exists
|
||||
if (!existsSync(this.cacheDir)) {
|
||||
mkdirSync(this.cacheDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all sources (default + custom)
|
||||
*/
|
||||
getSources(): SkillSource[] {
|
||||
return [...DEFAULT_SKILL_SOURCES, ...(this.config.sources || [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cached index
|
||||
*/
|
||||
loadCache(): MarketplaceIndex | null {
|
||||
if (!existsSync(this.cachePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(this.cachePath, 'utf-8');
|
||||
const index = JSON.parse(content) as MarketplaceIndex;
|
||||
|
||||
// Check if cache is expired
|
||||
const cacheAge = Date.now() - new Date(index.updatedAt).getTime();
|
||||
const ttl = this.config.cacheTTL || DEFAULT_CACHE_TTL;
|
||||
|
||||
if (cacheAge > ttl) {
|
||||
return null; // Cache expired
|
||||
}
|
||||
|
||||
this.index = index;
|
||||
return index;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save index to cache
|
||||
*/
|
||||
saveCache(index: MarketplaceIndex): void {
|
||||
writeFileSync(this.cachePath, JSON.stringify(index, null, 2));
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch skills from a single source
|
||||
*/
|
||||
async fetchSource(source: SkillSource): Promise<MarketplaceSkill[]> {
|
||||
const skills: MarketplaceSkill[] = [];
|
||||
const branch = source.branch || 'main';
|
||||
|
||||
try {
|
||||
// Try to fetch skills index file
|
||||
const indexPaths = [
|
||||
source.indexPath,
|
||||
'skills.json',
|
||||
'index.json',
|
||||
'.skillkit/skills.json',
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
for (const indexPath of indexPaths) {
|
||||
try {
|
||||
const url = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${indexPath}`;
|
||||
const response = await fetch(url);
|
||||
|
||||
if (response.ok) {
|
||||
const data = (await response.json()) as unknown;
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
for (const item of data) {
|
||||
skills.push(this.parseSkillEntry(item as Record<string, unknown>, source));
|
||||
}
|
||||
return skills;
|
||||
}
|
||||
|
||||
const dataObj = data as Record<string, unknown>;
|
||||
if (dataObj.skills && Array.isArray(dataObj.skills)) {
|
||||
for (const item of dataObj.skills) {
|
||||
skills.push(this.parseSkillEntry(item as Record<string, unknown>, source));
|
||||
}
|
||||
return skills;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Try next path
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Try to parse README for skill links
|
||||
const readmeUrl = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/README.md`;
|
||||
const readmeResponse = await fetch(readmeUrl);
|
||||
|
||||
if (readmeResponse.ok) {
|
||||
const readme = await readmeResponse.text();
|
||||
const parsedSkills = this.parseReadmeForSkills(readme, source);
|
||||
skills.push(...parsedSkills);
|
||||
}
|
||||
|
||||
// If still no skills, add the repo itself as a skill source
|
||||
if (skills.length === 0) {
|
||||
skills.push({
|
||||
id: `${source.owner}/${source.repo}`,
|
||||
name: source.repo,
|
||||
description: source.description || `Skills from ${source.name}`,
|
||||
source,
|
||||
path: '/',
|
||||
tags: ['repository'],
|
||||
rawUrl: `https://github.com/${source.owner}/${source.repo}`,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch skills from ${source.owner}/${source.repo}:`, error);
|
||||
}
|
||||
|
||||
return skills;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is an absolute URL
|
||||
*/
|
||||
private isAbsoluteUrl(path: string): boolean {
|
||||
return /^https?:\/\//i.test(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a GitHub URL to raw content URL
|
||||
*/
|
||||
private toRawUrl(url: string): string {
|
||||
return url
|
||||
.replace('://github.com/', '://raw.githubusercontent.com/')
|
||||
.replace('/blob/', '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a skill entry from JSON
|
||||
*/
|
||||
private parseSkillEntry(
|
||||
item: Record<string, unknown>,
|
||||
source: SkillSource
|
||||
): MarketplaceSkill {
|
||||
const name = String(item.name || item.title || 'Unknown');
|
||||
const path = String(item.path || item.file || item.url || '/');
|
||||
|
||||
// Handle absolute URLs - use them directly instead of building from source
|
||||
const rawUrl = this.isAbsoluteUrl(path)
|
||||
? this.toRawUrl(path)
|
||||
: this.buildRawUrl(source, path);
|
||||
|
||||
return {
|
||||
id: `${source.owner}/${source.repo}/${path}`,
|
||||
name,
|
||||
description: String(item.description || item.desc || ''),
|
||||
source,
|
||||
path,
|
||||
version: item.version as string | undefined,
|
||||
author: item.author as string | undefined,
|
||||
tags: Array.isArray(item.tags) ? item.tags : [],
|
||||
agents: Array.isArray(item.agents) ? item.agents : undefined,
|
||||
stars: typeof item.stars === 'number' ? item.stars : undefined,
|
||||
updatedAt: item.updatedAt as string | undefined,
|
||||
downloads: typeof item.downloads === 'number' ? item.downloads : undefined,
|
||||
rawUrl,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse README for skill links
|
||||
*/
|
||||
private parseReadmeForSkills(
|
||||
readme: string,
|
||||
source: SkillSource
|
||||
): MarketplaceSkill[] {
|
||||
const skills: MarketplaceSkill[] = [];
|
||||
const branch = source.branch || 'main';
|
||||
|
||||
// Look for markdown links to skill files
|
||||
const linkPattern = /\[([^\]]+)\]\(([^)]+\.md)\)/g;
|
||||
let match;
|
||||
|
||||
while ((match = linkPattern.exec(readme)) !== null) {
|
||||
const name = match[1];
|
||||
const path = match[2];
|
||||
|
||||
// Skip external links and non-skill files
|
||||
if (path.startsWith('http') && !path.includes(source.repo)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract description from surrounding text
|
||||
const contextStart = Math.max(0, match.index - 200);
|
||||
const contextEnd = Math.min(readme.length, match.index + 200);
|
||||
const context = readme.slice(contextStart, contextEnd);
|
||||
|
||||
// Try to find description in list item or paragraph
|
||||
const descMatch = context.match(/[-*]\s*\[.*?\]\(.*?\)\s*[-:]\s*(.+?)(?:\n|$)/);
|
||||
const description = descMatch ? descMatch[1].trim() : '';
|
||||
|
||||
// Handle absolute URLs in README links
|
||||
const isAbsolute = this.isAbsoluteUrl(path);
|
||||
const normalizedPath = isAbsolute ? path : (path.startsWith('/') ? path : `/${path}`);
|
||||
const rawUrl = isAbsolute
|
||||
? this.toRawUrl(path)
|
||||
: `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${path}`;
|
||||
|
||||
skills.push({
|
||||
id: `${source.owner}/${source.repo}/${path}`,
|
||||
name,
|
||||
description,
|
||||
source,
|
||||
path: normalizedPath,
|
||||
tags: this.inferTags(name, description),
|
||||
rawUrl,
|
||||
});
|
||||
}
|
||||
|
||||
return skills;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build raw URL for a skill
|
||||
*/
|
||||
private buildRawUrl(source: SkillSource, path: string): string {
|
||||
const branch = source.branch || 'main';
|
||||
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
||||
return `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${cleanPath}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer tags from name and description
|
||||
*/
|
||||
private inferTags(name: string, description: string): string[] {
|
||||
const tags: string[] = [];
|
||||
const text = `${name} ${description}`.toLowerCase();
|
||||
|
||||
const tagKeywords: Record<string, string[]> = {
|
||||
typescript: ['typescript', 'ts', 'tsc'],
|
||||
javascript: ['javascript', 'js', 'node'],
|
||||
react: ['react', 'jsx', 'tsx'],
|
||||
nextjs: ['next', 'nextjs', 'next.js'],
|
||||
testing: ['test', 'jest', 'vitest', 'mocha'],
|
||||
linting: ['lint', 'eslint', 'prettier'],
|
||||
auth: ['auth', 'authentication', 'login', 'oauth'],
|
||||
database: ['database', 'db', 'postgres', 'mysql', 'mongo'],
|
||||
api: ['api', 'rest', 'graphql'],
|
||||
devops: ['ci', 'cd', 'docker', 'kubernetes'],
|
||||
git: ['git', 'github', 'commit'],
|
||||
};
|
||||
|
||||
for (const [tag, keywords] of Object.entries(tagKeywords)) {
|
||||
if (keywords.some((k) => text.includes(k))) {
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the marketplace index
|
||||
*/
|
||||
async refresh(): Promise<MarketplaceIndex> {
|
||||
const sources = this.getSources();
|
||||
const allSkills: MarketplaceSkill[] = [];
|
||||
|
||||
// Fetch from all sources in parallel
|
||||
const results = await Promise.all(
|
||||
sources.map((source) => this.fetchSource(source))
|
||||
);
|
||||
|
||||
for (const skills of results) {
|
||||
allSkills.push(...skills);
|
||||
}
|
||||
|
||||
// Create index
|
||||
const index: MarketplaceIndex = {
|
||||
version: 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
sources,
|
||||
skills: allSkills,
|
||||
totalCount: allSkills.length,
|
||||
};
|
||||
|
||||
// Save to cache
|
||||
this.saveCache(index);
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the marketplace index (from cache or refresh)
|
||||
*/
|
||||
async getIndex(forceRefresh = false): Promise<MarketplaceIndex> {
|
||||
// Check in-memory cache first
|
||||
if (!forceRefresh && this.index) {
|
||||
return this.index;
|
||||
}
|
||||
|
||||
// Check file cache
|
||||
if (!forceRefresh) {
|
||||
const cached = this.loadCache();
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
return this.refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the marketplace
|
||||
*/
|
||||
async search(options: MarketplaceSearchOptions = {}): Promise<MarketplaceSearchResult> {
|
||||
const index = await this.getIndex();
|
||||
let skills = [...index.skills];
|
||||
|
||||
// Filter by query
|
||||
if (options.query) {
|
||||
const query = options.query.toLowerCase();
|
||||
skills = skills.filter(
|
||||
(s) =>
|
||||
s.name.toLowerCase().includes(query) ||
|
||||
s.description.toLowerCase().includes(query) ||
|
||||
s.tags.some((t) => t.toLowerCase().includes(query))
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by tags
|
||||
if (options.tags && options.tags.length > 0) {
|
||||
skills = skills.filter((s) =>
|
||||
options.tags!.some((t) => s.tags.includes(t))
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by source
|
||||
if (options.source) {
|
||||
skills = skills.filter(
|
||||
(s) =>
|
||||
s.source.name === options.source ||
|
||||
`${s.source.owner}/${s.source.repo}` === options.source
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by agent
|
||||
if (options.agent) {
|
||||
skills = skills.filter(
|
||||
(s) => !s.agents || s.agents.includes(options.agent!)
|
||||
);
|
||||
}
|
||||
|
||||
// Sort
|
||||
const sortBy = options.sortBy || 'name';
|
||||
const sortOrder = options.sortOrder || 'asc';
|
||||
|
||||
skills.sort((a, b) => {
|
||||
let comparison = 0;
|
||||
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
comparison = a.name.localeCompare(b.name);
|
||||
break;
|
||||
case 'stars':
|
||||
comparison = (a.stars || 0) - (b.stars || 0);
|
||||
break;
|
||||
case 'downloads':
|
||||
comparison = (a.downloads || 0) - (b.downloads || 0);
|
||||
break;
|
||||
case 'updatedAt':
|
||||
comparison =
|
||||
new Date(a.updatedAt || 0).getTime() -
|
||||
new Date(b.updatedAt || 0).getTime();
|
||||
break;
|
||||
}
|
||||
|
||||
return sortOrder === 'desc' ? -comparison : comparison;
|
||||
});
|
||||
|
||||
const total = skills.length;
|
||||
|
||||
// Apply pagination
|
||||
if (options.offset) {
|
||||
skills = skills.slice(options.offset);
|
||||
}
|
||||
|
||||
if (options.limit) {
|
||||
skills = skills.slice(0, options.limit);
|
||||
}
|
||||
|
||||
return {
|
||||
skills,
|
||||
total,
|
||||
query: options.query,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a skill by ID
|
||||
*/
|
||||
async getSkill(id: string): Promise<MarketplaceSkill | null> {
|
||||
const index = await this.getIndex();
|
||||
return index.skills.find((s) => s.id === id) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get skill content
|
||||
*/
|
||||
async getSkillContent(skill: MarketplaceSkill): Promise<string | null> {
|
||||
if (!skill.rawUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(skill.rawUrl);
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
} catch {
|
||||
// Fetch failed
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get popular tags
|
||||
*/
|
||||
async getPopularTags(limit = 20): Promise<{ tag: string; count: number }[]> {
|
||||
const index = await this.getIndex();
|
||||
const tagCounts = new Map<string, number>();
|
||||
|
||||
for (const skill of index.skills) {
|
||||
for (const tag of skill.tags) {
|
||||
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const tags = Array.from(tagCounts.entries())
|
||||
.map(([tag, count]) => ({ tag, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, limit);
|
||||
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a custom source
|
||||
*/
|
||||
addSource(source: SkillSource): void {
|
||||
if (!this.config.sources) {
|
||||
this.config.sources = [];
|
||||
}
|
||||
this.config.sources.push(source);
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a custom source
|
||||
*/
|
||||
removeSource(owner: string, repo: string): void {
|
||||
if (this.config.sources) {
|
||||
this.config.sources = this.config.sources.filter(
|
||||
(s) => s.owner !== owner || s.repo !== repo
|
||||
);
|
||||
}
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache
|
||||
*/
|
||||
clearCache(): void {
|
||||
if (existsSync(this.cachePath)) {
|
||||
unlinkSync(this.cachePath);
|
||||
}
|
||||
this.index = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a marketplace aggregator
|
||||
*/
|
||||
export function createMarketplaceAggregator(
|
||||
config?: MarketplaceConfig
|
||||
): MarketplaceAggregator {
|
||||
return new MarketplaceAggregator(config);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Skill Marketplace Module
|
||||
*
|
||||
* Provides aggregated skill discovery from multiple GitHub repositories.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { createMarketplaceAggregator } from '@skillkit/core';
|
||||
*
|
||||
* const marketplace = createMarketplaceAggregator();
|
||||
*
|
||||
* // Search for skills
|
||||
* const results = await marketplace.search({ query: 'typescript' });
|
||||
*
|
||||
* // Get popular tags
|
||||
* const tags = await marketplace.getPopularTags();
|
||||
*
|
||||
* // Refresh index from all sources
|
||||
* await marketplace.refresh();
|
||||
* ```
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './aggregator.js';
|
||||
|
||||
export {
|
||||
MarketplaceAggregator,
|
||||
createMarketplaceAggregator,
|
||||
} from './aggregator.js';
|
||||
|
||||
export {
|
||||
DEFAULT_SKILL_SOURCES,
|
||||
MARKETPLACE_CACHE_FILE,
|
||||
DEFAULT_CACHE_TTL,
|
||||
type SkillSource,
|
||||
type MarketplaceSkill,
|
||||
type MarketplaceIndex,
|
||||
type MarketplaceSearchOptions,
|
||||
type MarketplaceSearchResult,
|
||||
type MarketplaceConfig,
|
||||
} from './types.js';
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Skill Marketplace Types
|
||||
*
|
||||
* Types for the aggregated skill marketplace.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Skill source repository
|
||||
*/
|
||||
export interface SkillSource {
|
||||
/** Repository owner */
|
||||
owner: string;
|
||||
/** Repository name */
|
||||
repo: string;
|
||||
/** Human-readable name */
|
||||
name: string;
|
||||
/** Description */
|
||||
description?: string;
|
||||
/** Whether this is an official source */
|
||||
official?: boolean;
|
||||
/** Branch to fetch from */
|
||||
branch?: string;
|
||||
/** Path to skills index file */
|
||||
indexPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill entry in the marketplace
|
||||
*/
|
||||
export interface MarketplaceSkill {
|
||||
/** Unique identifier (owner/repo/path) */
|
||||
id: string;
|
||||
/** Skill name */
|
||||
name: string;
|
||||
/** Description */
|
||||
description: string;
|
||||
/** Source repository */
|
||||
source: SkillSource;
|
||||
/** Path within the repository */
|
||||
path: string;
|
||||
/** Version if available */
|
||||
version?: string;
|
||||
/** Author */
|
||||
author?: string;
|
||||
/** Tags for categorization */
|
||||
tags: string[];
|
||||
/** Supported agents */
|
||||
agents?: string[];
|
||||
/** GitHub stars (if available) */
|
||||
stars?: number;
|
||||
/** Last updated date */
|
||||
updatedAt?: string;
|
||||
/** Download/install count */
|
||||
downloads?: number;
|
||||
/** Raw content URL */
|
||||
rawUrl?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marketplace index (cached locally)
|
||||
*/
|
||||
export interface MarketplaceIndex {
|
||||
/** Index version */
|
||||
version: number;
|
||||
/** When the index was last updated */
|
||||
updatedAt: string;
|
||||
/** Sources included in this index */
|
||||
sources: SkillSource[];
|
||||
/** All skills in the index */
|
||||
skills: MarketplaceSkill[];
|
||||
/** Total skill count */
|
||||
totalCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search options for the marketplace
|
||||
*/
|
||||
export interface MarketplaceSearchOptions {
|
||||
/** Search query */
|
||||
query?: string;
|
||||
/** Filter by tags */
|
||||
tags?: string[];
|
||||
/** Filter by source */
|
||||
source?: string;
|
||||
/** Filter by agent compatibility */
|
||||
agent?: string;
|
||||
/** Sort by field */
|
||||
sortBy?: 'name' | 'stars' | 'downloads' | 'updatedAt';
|
||||
/** Sort direction */
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
/** Limit results */
|
||||
limit?: number;
|
||||
/** Offset for pagination */
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search result
|
||||
*/
|
||||
export interface MarketplaceSearchResult {
|
||||
/** Matching skills */
|
||||
skills: MarketplaceSkill[];
|
||||
/** Total matches (before limit) */
|
||||
total: number;
|
||||
/** Query that was searched */
|
||||
query?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marketplace configuration
|
||||
*/
|
||||
export interface MarketplaceConfig {
|
||||
/** Custom sources to include */
|
||||
sources?: SkillSource[];
|
||||
/** Cache directory */
|
||||
cacheDir?: string;
|
||||
/** Cache TTL in milliseconds */
|
||||
cacheTTL?: number;
|
||||
/** GitHub token for API access */
|
||||
githubToken?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default skill sources
|
||||
*/
|
||||
export const DEFAULT_SKILL_SOURCES: SkillSource[] = [
|
||||
{
|
||||
owner: 'composioHQ',
|
||||
repo: 'awesome-claude-code-skills',
|
||||
name: 'Composio Curated',
|
||||
description: 'Curated collection of Claude Code skills',
|
||||
official: false,
|
||||
branch: 'main',
|
||||
},
|
||||
{
|
||||
owner: 'anthropics',
|
||||
repo: 'courses',
|
||||
name: 'Anthropic Official',
|
||||
description: 'Official Anthropic courses and skills',
|
||||
official: true,
|
||||
branch: 'master',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Cache file name
|
||||
*/
|
||||
export const MARKETPLACE_CACHE_FILE = 'marketplace-index.json';
|
||||
|
||||
/**
|
||||
* Default cache TTL (1 hour)
|
||||
*/
|
||||
export const DEFAULT_CACHE_TTL = 60 * 60 * 1000;
|
||||
@@ -0,0 +1,500 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import {
|
||||
RuleBasedCompressor,
|
||||
APIBasedCompressor,
|
||||
MemoryCompressor,
|
||||
LearningConsolidator,
|
||||
createRuleBasedCompressor,
|
||||
createAPIBasedCompressor,
|
||||
createMemoryCompressor,
|
||||
} from '../compressor.js';
|
||||
import type { Observation, Learning } from '../types.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
// Helper to create mock observations
|
||||
const createObservation = (overrides: Partial<Observation> = {}): Observation => ({
|
||||
id: `obs-${Math.random().toString(36).slice(2, 9)}`,
|
||||
timestamp: new Date().toISOString(),
|
||||
sessionId: 'test-session',
|
||||
agent: 'claude-code',
|
||||
type: 'tool_use',
|
||||
content: {
|
||||
action: 'Test action',
|
||||
context: 'Test context',
|
||||
},
|
||||
relevance: 60,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Helper to create mock learnings
|
||||
const createLearning = (overrides: Partial<Learning> = {}): Learning => ({
|
||||
id: `learn-${Math.random().toString(36).slice(2, 9)}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
source: 'session',
|
||||
title: 'Test Learning',
|
||||
content: 'Test content for learning',
|
||||
scope: 'project',
|
||||
tags: ['test'],
|
||||
useCount: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('RuleBasedCompressor', () => {
|
||||
let compressor: RuleBasedCompressor;
|
||||
|
||||
beforeEach(() => {
|
||||
compressor = new RuleBasedCompressor();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('getType', () => {
|
||||
it('should return rule-based', () => {
|
||||
expect(compressor.getType()).toBe('rule-based');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compress', () => {
|
||||
it('should return empty result when observations below threshold', async () => {
|
||||
const observations = [createObservation(), createObservation()];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 5 });
|
||||
|
||||
expect(result.learnings).toHaveLength(0);
|
||||
expect(result.skippedObservationIds).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should extract error-solution pairs', async () => {
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: {
|
||||
action: 'Build failed',
|
||||
context: 'Running npm build',
|
||||
error: 'TypeError: Cannot read property of undefined',
|
||||
},
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'solution',
|
||||
content: {
|
||||
action: 'Added null check',
|
||||
context: 'Fixed the TypeError',
|
||||
solution: 'Added optional chaining operator',
|
||||
},
|
||||
relevance: 90,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: {
|
||||
action: 'Some other action',
|
||||
context: 'Context',
|
||||
},
|
||||
relevance: 50,
|
||||
}),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 2 });
|
||||
|
||||
expect(result.learnings.length).toBeGreaterThanOrEqual(1);
|
||||
const errorSolutionLearning = result.learnings.find((l) =>
|
||||
l.title.includes('Error Resolution')
|
||||
);
|
||||
expect(errorSolutionLearning).toBeDefined();
|
||||
});
|
||||
|
||||
it('should extract decision patterns', async () => {
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'decision',
|
||||
content: {
|
||||
action: 'Use TypeScript',
|
||||
context: 'Choosing programming language',
|
||||
},
|
||||
relevance: 75,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'decision',
|
||||
content: {
|
||||
action: 'Use React hooks',
|
||||
context: 'State management approach',
|
||||
},
|
||||
relevance: 75,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: {
|
||||
action: 'Filler',
|
||||
context: 'Context',
|
||||
},
|
||||
relevance: 50,
|
||||
}),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 2 });
|
||||
|
||||
expect(result.learnings.length).toBeGreaterThanOrEqual(1);
|
||||
const decisionLearning = result.learnings.find((l) => l.title.includes('Decision'));
|
||||
expect(decisionLearning).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter by minimum importance', async () => {
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: { action: 'Low importance action', context: 'Context' },
|
||||
relevance: 50,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: { action: 'Another action', context: 'Context' },
|
||||
relevance: 50,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: { action: 'Third action', context: 'Context' },
|
||||
relevance: 50,
|
||||
}),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, {
|
||||
minObservations: 2,
|
||||
minImportance: 9, // Very high threshold
|
||||
});
|
||||
|
||||
// Tool use patterns have low importance, so should be filtered
|
||||
expect(result.learnings.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should limit output to maxLearnings', async () => {
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: { action: 'Error 1', context: 'Context', error: 'Error 1' },
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: { action: 'Error 2', context: 'Context', error: 'Error 2' },
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: { action: 'Error 3', context: 'Context', error: 'Error 3' },
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'solution',
|
||||
content: { action: 'Solution 1', context: 'Context', solution: 'Solution' },
|
||||
relevance: 90,
|
||||
}),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, {
|
||||
minObservations: 2,
|
||||
maxLearnings: 2,
|
||||
});
|
||||
|
||||
expect(result.learnings.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('should add additional tags to learnings', async () => {
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: { action: 'Error', context: 'Context', error: 'Some error' },
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'solution',
|
||||
content: { action: 'Fix', context: 'Context', solution: 'Fixed it' },
|
||||
relevance: 90,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'tool_use',
|
||||
content: { action: 'Action', context: 'Context' },
|
||||
relevance: 50,
|
||||
}),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, {
|
||||
minObservations: 2,
|
||||
additionalTags: ['project-x', 'sprint-1'],
|
||||
});
|
||||
|
||||
if (result.learnings.length > 0) {
|
||||
expect(result.learnings[0].tags).toContain('project-x');
|
||||
expect(result.learnings[0].tags).toContain('sprint-1');
|
||||
}
|
||||
});
|
||||
|
||||
it('should calculate compression stats', async () => {
|
||||
const observations = [
|
||||
createObservation({ type: 'error', relevance: 85 }),
|
||||
createObservation({ type: 'solution', relevance: 90 }),
|
||||
createObservation({ type: 'tool_use', relevance: 50 }),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 2 });
|
||||
|
||||
expect(result.stats.inputCount).toBe(3);
|
||||
expect(result.stats.outputCount).toBe(result.learnings.length);
|
||||
expect(result.stats.compressionRatio).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('APIBasedCompressor', () => {
|
||||
let compressor: APIBasedCompressor;
|
||||
|
||||
beforeEach(() => {
|
||||
compressor = new APIBasedCompressor({
|
||||
provider: 'anthropic',
|
||||
apiKey: 'test-key',
|
||||
model: 'claude-3-haiku-20240307',
|
||||
});
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('getType', () => {
|
||||
it('should return api', () => {
|
||||
expect(compressor.getType()).toBe('api');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compress', () => {
|
||||
it('should return empty result when observations below threshold', async () => {
|
||||
const observations = [createObservation()];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 5 });
|
||||
|
||||
expect(result.learnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should fall back to rule-based on API failure', async () => {
|
||||
// Mock fetch to fail
|
||||
global.fetch = vi.fn().mockRejectedValue(new Error('API error'));
|
||||
|
||||
const observations = [
|
||||
createObservation({ type: 'error', relevance: 85 }),
|
||||
createObservation({ type: 'solution', relevance: 90 }),
|
||||
createObservation({ type: 'tool_use', relevance: 50 }),
|
||||
];
|
||||
|
||||
const result = await compressor.compress(observations, { minObservations: 2 });
|
||||
|
||||
// Should not throw, should return result from fallback
|
||||
expect(result.stats.inputCount).toBe(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('MemoryCompressor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should create with default engine', () => {
|
||||
const compressor = new MemoryCompressor('/test/project');
|
||||
expect(compressor.getEngineType()).toBe('rule-based');
|
||||
});
|
||||
|
||||
it('should accept custom engine', () => {
|
||||
const apiEngine = new APIBasedCompressor({
|
||||
provider: 'openai',
|
||||
apiKey: 'test',
|
||||
});
|
||||
const compressor = new MemoryCompressor('/test/project', { engine: apiEngine });
|
||||
expect(compressor.getEngineType()).toBe('api');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setEngine', () => {
|
||||
it('should allow changing the engine', () => {
|
||||
const compressor = new MemoryCompressor('/test/project');
|
||||
expect(compressor.getEngineType()).toBe('rule-based');
|
||||
|
||||
compressor.setEngine(
|
||||
new APIBasedCompressor({
|
||||
provider: 'anthropic',
|
||||
apiKey: 'test',
|
||||
})
|
||||
);
|
||||
expect(compressor.getEngineType()).toBe('api');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compressAndStore', () => {
|
||||
it('should compress and store learnings', async () => {
|
||||
const compressor = createMemoryCompressor('/test/project', {
|
||||
projectName: 'test-project',
|
||||
});
|
||||
|
||||
const observations = [
|
||||
createObservation({
|
||||
type: 'error',
|
||||
content: { action: 'Error', context: 'Context', error: 'Test error' },
|
||||
relevance: 85,
|
||||
}),
|
||||
createObservation({
|
||||
type: 'solution',
|
||||
content: { action: 'Fix', context: 'Fixed error', solution: 'Applied fix' },
|
||||
relevance: 90,
|
||||
}),
|
||||
createObservation({ type: 'tool_use', relevance: 50 }),
|
||||
];
|
||||
|
||||
const { learnings, result } = await compressor.compressAndStore(observations, {
|
||||
minObservations: 2,
|
||||
});
|
||||
|
||||
expect(result.stats.inputCount).toBe(3);
|
||||
// Learnings should have been created
|
||||
expect(learnings.length).toBe(result.learnings.length);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('LearningConsolidator', () => {
|
||||
let consolidator: LearningConsolidator;
|
||||
|
||||
beforeEach(() => {
|
||||
consolidator = new LearningConsolidator();
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
describe('findSimilar', () => {
|
||||
it('should find similar learnings', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'React hooks best practices',
|
||||
tags: ['react', 'hooks'],
|
||||
patterns: ['best-practices'],
|
||||
content: 'When using React hooks, always follow the rules of hooks.',
|
||||
}),
|
||||
createLearning({
|
||||
id: 'l2',
|
||||
title: 'React hooks patterns',
|
||||
tags: ['react', 'hooks', 'patterns'],
|
||||
patterns: ['best-practices'],
|
||||
content: 'React hooks provide a way to use state in functional components.',
|
||||
}),
|
||||
createLearning({
|
||||
id: 'l3',
|
||||
title: 'TypeScript generics guide',
|
||||
tags: ['typescript', 'generics'],
|
||||
patterns: ['type-safety'],
|
||||
content: 'TypeScript generics allow you to write reusable type-safe code.',
|
||||
}),
|
||||
];
|
||||
|
||||
const pairs = consolidator.findSimilar(learnings, 0.5);
|
||||
|
||||
// The two React hooks learnings should be similar
|
||||
expect(pairs.length).toBeGreaterThanOrEqual(1);
|
||||
const reactPair = pairs.find(
|
||||
([a, b]) =>
|
||||
(a.id === 'l1' && b.id === 'l2') || (a.id === 'l2' && b.id === 'l1')
|
||||
);
|
||||
expect(reactPair).toBeDefined();
|
||||
});
|
||||
|
||||
it('should not find similar for distinct learnings', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
title: 'React tutorial',
|
||||
tags: ['react', 'frontend'],
|
||||
content: 'React is a library for building user interfaces.',
|
||||
}),
|
||||
createLearning({
|
||||
title: 'Python basics',
|
||||
tags: ['python', 'backend'],
|
||||
content: 'Python is a versatile programming language.',
|
||||
}),
|
||||
];
|
||||
|
||||
const pairs = consolidator.findSimilar(learnings, 0.8);
|
||||
|
||||
expect(pairs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('merge', () => {
|
||||
it('should merge two learnings', () => {
|
||||
const l1 = createLearning({
|
||||
title: 'React hooks patterns',
|
||||
content: 'Content 1 about hooks',
|
||||
tags: ['react', 'hooks'],
|
||||
frameworks: ['react'],
|
||||
patterns: ['hooks'],
|
||||
useCount: 5,
|
||||
effectiveness: 80,
|
||||
});
|
||||
|
||||
const l2 = createLearning({
|
||||
title: 'React hooks best practices',
|
||||
content: 'Content 2 about best practices for hooks in React applications',
|
||||
tags: ['react', 'best-practices'],
|
||||
frameworks: ['react', 'nextjs'],
|
||||
patterns: ['hooks', 'state-management'],
|
||||
useCount: 3,
|
||||
effectiveness: 70,
|
||||
});
|
||||
|
||||
const merged = consolidator.merge(l1, l2);
|
||||
|
||||
// Should combine tags
|
||||
expect(merged.tags).toContain('react');
|
||||
expect(merged.tags).toContain('hooks');
|
||||
expect(merged.tags).toContain('best-practices');
|
||||
|
||||
// Should combine frameworks
|
||||
expect(merged.frameworks).toContain('react');
|
||||
expect(merged.frameworks).toContain('nextjs');
|
||||
|
||||
// Should combine patterns
|
||||
expect(merged.patterns).toContain('hooks');
|
||||
expect(merged.patterns).toContain('state-management');
|
||||
|
||||
// Should combine use count
|
||||
expect(merged.useCount).toBe(8);
|
||||
|
||||
// Should keep higher effectiveness
|
||||
expect(merged.effectiveness).toBe(80);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Factory functions', () => {
|
||||
it('createRuleBasedCompressor should create instance', () => {
|
||||
const compressor = createRuleBasedCompressor();
|
||||
expect(compressor).toBeInstanceOf(RuleBasedCompressor);
|
||||
expect(compressor.getType()).toBe('rule-based');
|
||||
});
|
||||
|
||||
it('createAPIBasedCompressor should create instance', () => {
|
||||
const compressor = createAPIBasedCompressor({
|
||||
provider: 'anthropic',
|
||||
apiKey: 'test-key',
|
||||
});
|
||||
expect(compressor).toBeInstanceOf(APIBasedCompressor);
|
||||
expect(compressor.getType()).toBe('api');
|
||||
});
|
||||
|
||||
it('createMemoryCompressor should create instance', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const compressor = createMemoryCompressor('/test/project');
|
||||
expect(compressor).toBeInstanceOf(MemoryCompressor);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,533 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { MemoryInjector, createMemoryInjector } from '../injector.js';
|
||||
import type { Learning } from '../types.js';
|
||||
import type { ProjectContext } from '../../context/types.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
// Helper to create mock learnings
|
||||
const createLearning = (overrides: Partial<Learning> = {}): Learning => ({
|
||||
id: `learn-${Math.random().toString(36).slice(2, 9)}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
source: 'session',
|
||||
title: 'Test Learning',
|
||||
content: 'Test content for learning that provides useful information about best practices.',
|
||||
scope: 'project',
|
||||
tags: ['test'],
|
||||
useCount: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Helper to create mock project context
|
||||
const createProjectContext = (overrides: Partial<ProjectContext> = {}): ProjectContext => ({
|
||||
version: 1,
|
||||
project: {
|
||||
name: 'test-project',
|
||||
description: 'A test project',
|
||||
type: 'web-app',
|
||||
},
|
||||
stack: {
|
||||
languages: [{ name: 'TypeScript', confidence: 100 }],
|
||||
frameworks: [{ name: 'React', confidence: 100 }, { name: 'Next.js', confidence: 90 }],
|
||||
libraries: [],
|
||||
styling: [{ name: 'Tailwind', confidence: 100 }],
|
||||
testing: [{ name: 'Vitest', confidence: 100 }],
|
||||
databases: [],
|
||||
tools: [],
|
||||
runtime: [{ name: 'Node.js', confidence: 100 }],
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Mock YAML content for project learnings
|
||||
const createMockLearningsYaml = (learnings: Learning[]) => ({
|
||||
version: 1,
|
||||
learnings,
|
||||
});
|
||||
|
||||
describe('MemoryInjector', () => {
|
||||
let injector: MemoryInjector;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should create instance without project context', () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
expect(injector).toBeInstanceOf(MemoryInjector);
|
||||
});
|
||||
|
||||
it('should create instance with project context', () => {
|
||||
const context = createProjectContext();
|
||||
injector = new MemoryInjector('/test/project', 'test-project', context);
|
||||
expect(injector).toBeInstanceOf(MemoryInjector);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setProjectContext', () => {
|
||||
it('should set project context', () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
const context = createProjectContext();
|
||||
injector.setProjectContext(context);
|
||||
// No direct way to verify, but it should not throw
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRelevantMemories', () => {
|
||||
it('should return empty array when no learnings exist', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
const memories = await injector.getRelevantMemories();
|
||||
expect(memories).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return learnings with relevance scores', async () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'React hooks best practices',
|
||||
tags: ['react', 'hooks'],
|
||||
frameworks: ['react'],
|
||||
useCount: 5,
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
const context = createProjectContext();
|
||||
injector = new MemoryInjector('/test/project', 'test-project', context);
|
||||
|
||||
const memories = await injector.getRelevantMemories();
|
||||
|
||||
expect(memories.length).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('should filter by minimum relevance', async () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Unrelated learning',
|
||||
tags: ['unrelated'],
|
||||
useCount: 0,
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const memories = await injector.getRelevantMemories({ minRelevance: 90 });
|
||||
|
||||
expect(memories).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should limit results to maxLearnings', async () => {
|
||||
const learnings = Array.from({ length: 20 }, (_, i) =>
|
||||
createLearning({
|
||||
id: `l${i}`,
|
||||
title: `Learning ${i}`,
|
||||
tags: ['common-tag'],
|
||||
useCount: i,
|
||||
})
|
||||
);
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const memories = await injector.getRelevantMemories({
|
||||
maxLearnings: 5,
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(memories.length).toBeLessThanOrEqual(5);
|
||||
});
|
||||
|
||||
it('should match by current task keywords', async () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Authentication patterns',
|
||||
content: 'How to implement JWT authentication in Node.js applications.',
|
||||
tags: ['auth', 'jwt', 'security'],
|
||||
}),
|
||||
createLearning({
|
||||
id: 'l2',
|
||||
title: 'CSS Grid layout',
|
||||
content: 'Guide to using CSS Grid for responsive layouts.',
|
||||
tags: ['css', 'layout'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const memories = await injector.getRelevantMemories({
|
||||
currentTask: 'implement JWT authentication',
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
// Auth learning should rank higher
|
||||
if (memories.length > 0) {
|
||||
const authMemory = memories.find((m) => m.learning.id === 'l1');
|
||||
const cssMemory = memories.find((m) => m.learning.id === 'l2');
|
||||
|
||||
if (authMemory && cssMemory) {
|
||||
expect(authMemory.relevanceScore).toBeGreaterThan(cssMemory.relevanceScore);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('inject', () => {
|
||||
it('should return empty result when no learnings exist', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.inject();
|
||||
|
||||
expect(result.memories).toHaveLength(0);
|
||||
expect(result.formattedContent).toBe('');
|
||||
expect(result.totalTokens).toBe(0);
|
||||
expect(result.stats.injected).toBe(0);
|
||||
});
|
||||
|
||||
it('should respect token budget', async () => {
|
||||
const learnings = Array.from({ length: 10 }, (_, i) =>
|
||||
createLearning({
|
||||
id: `l${i}`,
|
||||
title: `Learning ${i}`,
|
||||
content: 'A'.repeat(500), // Long content
|
||||
tags: ['test'],
|
||||
useCount: 10 - i,
|
||||
})
|
||||
);
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.inject({
|
||||
maxTokens: 100,
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(result.totalTokens).toBeLessThanOrEqual(100);
|
||||
});
|
||||
|
||||
it('should format content as markdown by default', async () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test Learning',
|
||||
content: 'Test content',
|
||||
tags: ['test'],
|
||||
useCount: 5,
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.inject({ minRelevance: 0 });
|
||||
|
||||
if (result.memories.length > 0) {
|
||||
expect(result.formattedContent).toContain('# Relevant Memories');
|
||||
expect(result.formattedContent).toContain('## Test Learning');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectForAgent', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test Learning',
|
||||
content: 'Test content for agent',
|
||||
tags: ['test'],
|
||||
frameworks: ['react'],
|
||||
useCount: 5,
|
||||
}),
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
});
|
||||
|
||||
it('should format for claude-code with XML tags', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.injectForAgent('claude-code', { minRelevance: 0 });
|
||||
|
||||
if (result.memories.length > 0) {
|
||||
expect(result.formattedContent).toContain('<memories>');
|
||||
expect(result.formattedContent).toContain('<memory');
|
||||
expect(result.formattedContent).toContain('</memories>');
|
||||
}
|
||||
});
|
||||
|
||||
it('should format for cursor with MDC format', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.injectForAgent('cursor', { minRelevance: 0 });
|
||||
|
||||
if (result.memories.length > 0) {
|
||||
expect(result.formattedContent).toContain('---');
|
||||
expect(result.formattedContent).toContain('description:');
|
||||
expect(result.formattedContent).toContain('# Session Memories');
|
||||
}
|
||||
});
|
||||
|
||||
it('should format for github-copilot with HTML comments', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.injectForAgent('github-copilot', { minRelevance: 0 });
|
||||
|
||||
if (result.memories.length > 0) {
|
||||
expect(result.formattedContent).toContain('<!-- Session Memories -->');
|
||||
}
|
||||
});
|
||||
|
||||
it('should use default markdown for unknown agents', async () => {
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const result = await injector.injectForAgent('universal', { minRelevance: 0 });
|
||||
|
||||
if (result.memories.length > 0) {
|
||||
expect(result.formattedContent).toContain('# Relevant Memories');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSummaries', () => {
|
||||
it('should return memory summaries', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test Learning',
|
||||
tags: ['test', 'example'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const summaries = injector.getSummaries();
|
||||
|
||||
expect(summaries.length).toBeGreaterThanOrEqual(0);
|
||||
if (summaries.length > 0) {
|
||||
expect(summaries[0]).toHaveProperty('id');
|
||||
expect(summaries[0]).toHaveProperty('title');
|
||||
expect(summaries[0]).toHaveProperty('tags');
|
||||
expect(summaries[0]).toHaveProperty('relevance');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPreviews', () => {
|
||||
it('should return memory previews for given IDs', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test Learning',
|
||||
content: 'Full content that is longer than the excerpt limit would allow.',
|
||||
tags: ['test'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const previews = injector.getPreviews(['l1']);
|
||||
|
||||
if (previews.length > 0) {
|
||||
expect(previews[0]).toHaveProperty('excerpt');
|
||||
expect(previews[0].excerpt.length).toBeLessThanOrEqual(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('should return empty for non-existent IDs', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const previews = injector.getPreviews(['non-existent']);
|
||||
|
||||
expect(previews).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFullMemories', () => {
|
||||
it('should return full memory content', () => {
|
||||
const fullContent = 'This is the full content of the learning that should be returned.';
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test Learning',
|
||||
content: fullContent,
|
||||
tags: ['test'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const fullMemories = injector.getFullMemories(['l1']);
|
||||
|
||||
if (fullMemories.length > 0) {
|
||||
expect(fullMemories[0].content).toBe(fullContent);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
it('should search memories by query', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'React hooks patterns',
|
||||
content: 'How to use useEffect and useState effectively.',
|
||||
tags: ['react', 'hooks'],
|
||||
}),
|
||||
createLearning({
|
||||
id: 'l2',
|
||||
title: 'Python data analysis',
|
||||
content: 'Using pandas for data manipulation.',
|
||||
tags: ['python', 'data'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const results = injector.search('react hooks');
|
||||
|
||||
// React learning should be found
|
||||
const reactResult = results.find((r) => r.learning.id === 'l1');
|
||||
if (results.length > 0 && reactResult) {
|
||||
expect(reactResult.matchedBy.keywords.length).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('should respect minRelevance in search', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Unrelated topic',
|
||||
content: 'Nothing to do with the search.',
|
||||
tags: ['other'],
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const results = injector.search('completely different query', { minRelevance: 80 });
|
||||
|
||||
expect(results).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatForAgent', () => {
|
||||
it('should escape XML special characters for Claude', () => {
|
||||
const learnings = [
|
||||
createLearning({
|
||||
id: 'l1',
|
||||
title: 'Test <script> & "quotes"',
|
||||
content: 'Content with <tags> & special chars',
|
||||
tags: ['test'],
|
||||
useCount: 5,
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(
|
||||
JSON.stringify(createMockLearningsYaml(learnings))
|
||||
);
|
||||
|
||||
injector = new MemoryInjector('/test/project');
|
||||
|
||||
const memories = injector.search('test', { minRelevance: 0 });
|
||||
const formatted = injector.formatForAgent(memories, 'claude-code');
|
||||
|
||||
if (memories.length > 0) {
|
||||
expect(formatted).toContain('<script>');
|
||||
expect(formatted).toContain('&');
|
||||
expect(formatted).toContain('"');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMemoryInjector', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('should create MemoryInjector instance', () => {
|
||||
const injector = createMemoryInjector('/test/project');
|
||||
expect(injector).toBeInstanceOf(MemoryInjector);
|
||||
});
|
||||
|
||||
it('should create with project name', () => {
|
||||
const injector = createMemoryInjector('/test/project', 'my-project');
|
||||
expect(injector).toBeInstanceOf(MemoryInjector);
|
||||
});
|
||||
|
||||
it('should create with project context', () => {
|
||||
const context = createProjectContext();
|
||||
const injector = createMemoryInjector('/test/project', 'my-project', context);
|
||||
expect(injector).toBeInstanceOf(MemoryInjector);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,647 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { LearningStore } from '../learning-store.js';
|
||||
import type { Learning } from '../types.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
// Helper to check if a string is a valid UUID
|
||||
const isValidUUID = (str: string): boolean => {
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
return uuidRegex.test(str);
|
||||
};
|
||||
|
||||
describe('LearningStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should set project file path for project scope', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const store = new LearningStore('project', '/test/project', 'my-project');
|
||||
expect(store.getScope()).toBe('project');
|
||||
});
|
||||
|
||||
it('should set global file path for global scope', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const store = new LearningStore('global');
|
||||
expect(store.getScope()).toBe('global');
|
||||
});
|
||||
});
|
||||
|
||||
describe('add', () => {
|
||||
it('should add a new learning', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new LearningStore('project', '/test/project', 'my-project');
|
||||
const learning = store.add({
|
||||
source: 'session',
|
||||
title: 'React hooks best practices',
|
||||
content: 'When using useEffect, always include cleanup functions...',
|
||||
tags: ['react', 'hooks', 'best-practices'],
|
||||
frameworks: ['react'],
|
||||
});
|
||||
|
||||
expect(isValidUUID(learning.id)).toBe(true);
|
||||
expect(learning).toMatchObject({
|
||||
createdAt: '2024-01-15T10:00:00.000Z',
|
||||
updatedAt: '2024-01-15T10:00:00.000Z',
|
||||
source: 'session',
|
||||
title: 'React hooks best practices',
|
||||
useCount: 0,
|
||||
scope: 'project',
|
||||
project: 'my-project',
|
||||
});
|
||||
|
||||
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should update an existing learning', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Original title
|
||||
content: Original content
|
||||
scope: project
|
||||
tags:
|
||||
- react
|
||||
useCount: 5
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const updated = store.update('learn-1', {
|
||||
title: 'Updated title',
|
||||
content: 'Updated content',
|
||||
});
|
||||
|
||||
expect(updated).not.toBeNull();
|
||||
expect(updated!.title).toBe('Updated title');
|
||||
expect(updated!.content).toBe('Updated content');
|
||||
expect(updated!.updatedAt).toBe('2024-01-15T10:00:00.000Z');
|
||||
expect(updated!.useCount).toBe(5); // Preserved
|
||||
});
|
||||
|
||||
it('should return null when learning not found', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const updated = store.update('non-existent', { title: 'test' });
|
||||
|
||||
expect(updated).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should delete an existing learning', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: To delete
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: To keep
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const result = store.delete('learn-1');
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(store.getAll()).toHaveLength(1);
|
||||
expect(store.getAll()[0].id).toBe('learn-2');
|
||||
});
|
||||
|
||||
it('should return false when learning not found', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const result = store.delete('non-existent');
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByTags', () => {
|
||||
it('should find learnings by tags', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: React patterns
|
||||
content: Content
|
||||
scope: project
|
||||
tags:
|
||||
- react
|
||||
- patterns
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: TypeScript tips
|
||||
content: Content
|
||||
scope: project
|
||||
tags:
|
||||
- typescript
|
||||
- tips
|
||||
useCount: 0
|
||||
- id: learn-3
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: React TypeScript
|
||||
content: Content
|
||||
scope: project
|
||||
tags:
|
||||
- react
|
||||
- typescript
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getByTags(['react']);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.map((l) => l.id)).toContain('learn-1');
|
||||
expect(results.map((l) => l.id)).toContain('learn-3');
|
||||
});
|
||||
|
||||
it('should be case-insensitive', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: React patterns
|
||||
content: Content
|
||||
scope: project
|
||||
tags:
|
||||
- React
|
||||
- PATTERNS
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getByTags(['react', 'patterns']);
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByFrameworks', () => {
|
||||
it('should find learnings by frameworks', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Next.js routing
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
frameworks:
|
||||
- nextjs
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Express middleware
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
frameworks:
|
||||
- express
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getByFrameworks(['nextjs']);
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].title).toBe('Next.js routing');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRecent', () => {
|
||||
it('should return most recently updated learnings', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Oldest
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-12T09:00:00.000Z"
|
||||
updatedAt: "2024-01-14T09:00:00.000Z"
|
||||
source: session
|
||||
title: Middle
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
- id: learn-3
|
||||
createdAt: "2024-01-11T09:00:00.000Z"
|
||||
updatedAt: "2024-01-15T09:00:00.000Z"
|
||||
source: session
|
||||
title: Newest
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getRecent(2);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].title).toBe('Newest');
|
||||
expect(results[1].title).toBe('Middle');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMostUsed', () => {
|
||||
it('should return most used learnings', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Low usage
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 2
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: High usage
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 15
|
||||
- id: learn-3
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Medium usage
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 8
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getMostUsed(2);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].title).toBe('High usage');
|
||||
expect(results[1].title).toBe('Medium usage');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMostEffective', () => {
|
||||
it('should return most effective learnings', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: No rating
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: High effectiveness
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
effectiveness: 90
|
||||
- id: learn-3
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Low effectiveness
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
effectiveness: 40
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.getMostEffective(2);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].title).toBe('High effectiveness');
|
||||
expect(results[1].title).toBe('Low effectiveness');
|
||||
});
|
||||
});
|
||||
|
||||
describe('incrementUseCount', () => {
|
||||
it('should increment use count and set lastUsed', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Test
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 5
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
store.incrementUseCount('learn-1');
|
||||
|
||||
const learning = store.getById('learn-1');
|
||||
expect(learning?.useCount).toBe(6);
|
||||
expect(learning?.lastUsed).toBe('2024-01-15T10:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setEffectiveness', () => {
|
||||
it('should set effectiveness rating', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Test
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
store.setEffectiveness('learn-1', 85);
|
||||
|
||||
const learning = store.getById('learn-1');
|
||||
expect(learning?.effectiveness).toBe(85);
|
||||
});
|
||||
|
||||
it('should clamp effectiveness between 0 and 100', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Test
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
|
||||
store.setEffectiveness('learn-1', 150);
|
||||
expect(store.getById('learn-1')?.effectiveness).toBe(100);
|
||||
|
||||
store.setEffectiveness('learn-1', -20);
|
||||
expect(store.getById('learn-1')?.effectiveness).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
it('should search by title', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: React hooks patterns
|
||||
content: Some content about hooks
|
||||
scope: project
|
||||
tags:
|
||||
- react
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: TypeScript generics
|
||||
content: Generic types explained
|
||||
scope: project
|
||||
tags:
|
||||
- typescript
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.search('React hooks');
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].title).toBe('React hooks patterns');
|
||||
});
|
||||
|
||||
it('should search by content', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Error handling
|
||||
content: Use try-catch blocks for async operations
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.search('async operations');
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should search by tags', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Some title
|
||||
content: Some content
|
||||
scope: project
|
||||
tags:
|
||||
- authentication
|
||||
- security
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
const results = store.search('authentication');
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
it('should clear all learnings', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(`
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Test
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
store.clear();
|
||||
|
||||
expect(store.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('count', () => {
|
||||
it('should return the number of learnings', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
learnings:
|
||||
- id: learn-1
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: First
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
- id: learn-2
|
||||
createdAt: "2024-01-10T09:00:00.000Z"
|
||||
updatedAt: "2024-01-10T09:00:00.000Z"
|
||||
source: session
|
||||
title: Second
|
||||
content: Content
|
||||
scope: project
|
||||
tags: []
|
||||
useCount: 0
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new LearningStore('project', '/test/project');
|
||||
|
||||
expect(store.count()).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,487 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { MemoryIndexStore } from '../memory-index.js';
|
||||
import type { Learning } from '../types.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('MemoryIndexStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
const createMockLearning = (overrides: Partial<Learning> = {}): Learning => ({
|
||||
id: 'learn-1',
|
||||
createdAt: '2024-01-10T09:00:00.000Z',
|
||||
updatedAt: '2024-01-10T09:00:00.000Z',
|
||||
source: 'session',
|
||||
title: 'React hooks best practices',
|
||||
content: 'When using useEffect, always include cleanup functions for subscriptions.',
|
||||
scope: 'project',
|
||||
tags: ['react', 'hooks', 'best-practices'],
|
||||
frameworks: ['react'],
|
||||
useCount: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('indexLearning', () => {
|
||||
it('should index a learning by keywords and tags', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const learning = createMockLearning();
|
||||
|
||||
store.indexLearning(learning);
|
||||
|
||||
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
|
||||
// Should contain keyword entries
|
||||
expect(content).toContain('react');
|
||||
expect(content).toContain('hooks');
|
||||
expect(content).toContain('useeffect');
|
||||
expect(content).toContain('cleanup');
|
||||
});
|
||||
|
||||
it('should add learning ID to existing keywords', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- existing-learn-1
|
||||
tags:
|
||||
react:
|
||||
- existing-learn-1
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const learning = createMockLearning({ id: 'learn-2' });
|
||||
|
||||
store.indexLearning(learning);
|
||||
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
// Should have both IDs under react keyword
|
||||
expect(content).toContain('existing-learn-1');
|
||||
expect(content).toContain('learn-2');
|
||||
});
|
||||
|
||||
it('should index frameworks as tags', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const learning = createMockLearning({
|
||||
frameworks: ['nextjs', 'tailwind'],
|
||||
});
|
||||
|
||||
store.indexLearning(learning);
|
||||
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
expect(content).toContain('nextjs');
|
||||
expect(content).toContain('tailwind');
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeLearning', () => {
|
||||
it('should remove learning from all index entries', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- learn-1
|
||||
- learn-2
|
||||
hooks:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
store.removeLearning('learn-1');
|
||||
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
// learn-1 should be removed
|
||||
expect(content).not.toMatch(/learn-1/);
|
||||
// learn-2 should still exist
|
||||
expect(content).toContain('learn-2');
|
||||
// hooks entry should be completely removed (was only learn-1)
|
||||
expect(content).not.toContain('hooks:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchByKeywords', () => {
|
||||
it('should find learnings by keywords', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- learn-1
|
||||
- learn-3
|
||||
hooks:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
tags: {}
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.searchByKeywords('react hooks');
|
||||
|
||||
// learn-1 matches both 'react' and 'hooks', should be first
|
||||
expect(results[0]).toBe('learn-1');
|
||||
expect(results).toContain('learn-3');
|
||||
});
|
||||
|
||||
it('should return empty array for no matches', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- learn-1
|
||||
tags: {}
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.searchByKeywords('python django');
|
||||
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle partial matches', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
authentication:
|
||||
- learn-1
|
||||
authorization:
|
||||
- learn-2
|
||||
tags: {}
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.searchByKeywords('auth');
|
||||
|
||||
expect(results).toContain('learn-1');
|
||||
expect(results).toContain('learn-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchByTags', () => {
|
||||
it('should find learnings by tags', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries: {}
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
- learn-2
|
||||
nextjs:
|
||||
- learn-1
|
||||
express:
|
||||
- learn-3
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.searchByTags(['react', 'nextjs']);
|
||||
|
||||
// learn-1 matches both tags, should be first
|
||||
expect(results[0]).toBe('learn-1');
|
||||
expect(results).toContain('learn-2');
|
||||
expect(results).not.toContain('learn-3');
|
||||
});
|
||||
|
||||
it('should be case-insensitive', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries: {}
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.searchByTags(['REACT']);
|
||||
|
||||
expect(results).toContain('learn-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
it('should combine keyword and tag search', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
hooks:
|
||||
- learn-1
|
||||
- learn-2
|
||||
state:
|
||||
- learn-3
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
- learn-3
|
||||
vue:
|
||||
- learn-2
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.search('hooks', ['react']);
|
||||
|
||||
// learn-1 matches both keyword and tag
|
||||
expect(results[0]).toBe('learn-1');
|
||||
});
|
||||
|
||||
it('should handle keyword-only search', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
hooks:
|
||||
- learn-1
|
||||
tags: {}
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.search('hooks');
|
||||
|
||||
expect(results).toContain('learn-1');
|
||||
});
|
||||
|
||||
it('should handle tag-only search', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries: {}
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const results = store.search('', ['react']);
|
||||
|
||||
expect(results).toContain('learn-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllTags', () => {
|
||||
it('should return all unique tags sorted', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries: {}
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
nextjs:
|
||||
- learn-1
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const tags = store.getAllTags();
|
||||
|
||||
expect(tags).toEqual(['nextjs', 'react', 'typescript']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTagCounts', () => {
|
||||
it('should return tag usage counts', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries: {}
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
- learn-2
|
||||
- learn-3
|
||||
typescript:
|
||||
- learn-1
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const counts = store.getTagCounts();
|
||||
|
||||
expect(counts).toEqual({
|
||||
react: 3,
|
||||
typescript: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('rebuildIndex', () => {
|
||||
it('should rebuild index from learnings', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const learnings: Learning[] = [
|
||||
{
|
||||
id: 'learn-1',
|
||||
createdAt: '2024-01-10T09:00:00.000Z',
|
||||
updatedAt: '2024-01-10T09:00:00.000Z',
|
||||
source: 'session',
|
||||
title: 'React patterns',
|
||||
content: 'Using React hooks effectively',
|
||||
scope: 'project',
|
||||
tags: ['react'],
|
||||
useCount: 0,
|
||||
},
|
||||
{
|
||||
id: 'learn-2',
|
||||
createdAt: '2024-01-10T09:00:00.000Z',
|
||||
updatedAt: '2024-01-10T09:00:00.000Z',
|
||||
source: 'session',
|
||||
title: 'TypeScript tips',
|
||||
content: 'TypeScript generics explained',
|
||||
scope: 'project',
|
||||
tags: ['typescript'],
|
||||
useCount: 0,
|
||||
},
|
||||
];
|
||||
|
||||
store.rebuildIndex(learnings);
|
||||
|
||||
// Get the last write call (after both learnings are indexed)
|
||||
const calls = vi.mocked(writeFileSync).mock.calls;
|
||||
const [, content] = calls[calls.length - 1];
|
||||
expect(content).toContain('react');
|
||||
expect(content).toContain('typescript');
|
||||
expect(content).toContain('learn-1');
|
||||
expect(content).toContain('learn-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
it('should clear the index', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(`
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- learn-1
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
`);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
store.clear();
|
||||
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
expect(content).toContain('entries: {}');
|
||||
expect(content).toContain('tags: {}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStats', () => {
|
||||
it('should return index statistics', () => {
|
||||
const existingIndex = `
|
||||
version: 1
|
||||
lastUpdated: "2024-01-14T10:00:00.000Z"
|
||||
entries:
|
||||
react:
|
||||
- learn-1
|
||||
hooks:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
tags:
|
||||
react:
|
||||
- learn-1
|
||||
typescript:
|
||||
- learn-2
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingIndex);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
const stats = store.getStats();
|
||||
|
||||
expect(stats.keywords).toBe(3);
|
||||
expect(stats.tags).toBe(2);
|
||||
expect(stats.lastUpdated).toBe('2024-01-14T10:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exists', () => {
|
||||
it('should return true when file exists', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
|
||||
expect(store.exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when file does not exist', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new MemoryIndexStore('/test/project');
|
||||
|
||||
expect(store.exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,444 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { ObservationStore } from '../observation-store.js';
|
||||
import type { ObservationType, ObservationContent } from '../types.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
// Helper to check if a string is a valid UUID
|
||||
const isValidUUID = (str: string): boolean => {
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
return uuidRegex.test(str);
|
||||
};
|
||||
|
||||
describe('ObservationStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should set the correct file path', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const store = new ObservationStore('/test/project');
|
||||
expect(store).toBeDefined();
|
||||
});
|
||||
|
||||
it('should accept a custom session ID', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const store = new ObservationStore('/test/project', 'custom-session-id');
|
||||
expect(store.getSessionId()).toBe('custom-session-id');
|
||||
});
|
||||
|
||||
it('should generate a session ID if not provided', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
const store = new ObservationStore('/test/project');
|
||||
expect(isValidUUID(store.getSessionId())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('add', () => {
|
||||
it('should add a new observation', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const content: ObservationContent = {
|
||||
action: 'Created new file',
|
||||
context: 'User requested new component',
|
||||
result: 'File created successfully',
|
||||
files: ['src/Component.tsx'],
|
||||
tags: ['react', 'typescript'],
|
||||
};
|
||||
|
||||
const observation = store.add('file_change', content, 'claude-code', 75);
|
||||
|
||||
expect(isValidUUID(observation.id)).toBe(true);
|
||||
expect(observation).toMatchObject({
|
||||
timestamp: '2024-01-15T10:00:00.000Z',
|
||||
sessionId: 'session-1',
|
||||
agent: 'claude-code',
|
||||
type: 'file_change',
|
||||
content,
|
||||
relevance: 75,
|
||||
});
|
||||
|
||||
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should use default relevance of 50', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new ObservationStore('/test/project');
|
||||
const observation = store.add(
|
||||
'decision',
|
||||
{ action: 'test', context: 'test' },
|
||||
'cursor'
|
||||
);
|
||||
|
||||
expect(observation.relevance).toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAll', () => {
|
||||
it('should return all observations', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: tool_use
|
||||
content:
|
||||
action: Read file
|
||||
context: Analyzing code
|
||||
relevance: 60
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Use React hooks
|
||||
context: State management
|
||||
relevance: 80
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const observations = store.getAll();
|
||||
|
||||
expect(observations).toHaveLength(2);
|
||||
expect(observations[0].id).toBe('obs-1');
|
||||
expect(observations[1].id).toBe('obs-2');
|
||||
});
|
||||
|
||||
it('should return empty array when no observations exist', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new ObservationStore('/test/project');
|
||||
const observations = store.getAll();
|
||||
|
||||
expect(observations).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByType', () => {
|
||||
it('should filter observations by type', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: error
|
||||
content:
|
||||
action: Build failed
|
||||
context: TypeScript error
|
||||
error: Type mismatch
|
||||
relevance: 90
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: solution
|
||||
content:
|
||||
action: Fixed error
|
||||
context: Added type annotation
|
||||
solution: Added explicit type
|
||||
relevance: 85
|
||||
- id: obs-3
|
||||
timestamp: "2024-01-15T10:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: error
|
||||
content:
|
||||
action: Test failed
|
||||
context: Unit test
|
||||
error: Assertion failed
|
||||
relevance: 70
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const errors = store.getByType('error');
|
||||
|
||||
expect(errors).toHaveLength(2);
|
||||
expect(errors[0].type).toBe('error');
|
||||
expect(errors[1].type).toBe('error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByRelevance', () => {
|
||||
it('should filter observations by minimum relevance', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 30
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 70
|
||||
- id: obs-3
|
||||
timestamp: "2024-01-15T10:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 90
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const highRelevance = store.getByRelevance(60);
|
||||
|
||||
expect(highRelevance).toHaveLength(2);
|
||||
expect(highRelevance[0].relevance).toBe(70);
|
||||
expect(highRelevance[1].relevance).toBe(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRecent', () => {
|
||||
it('should return the most recent observations', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: First
|
||||
context: Test
|
||||
relevance: 50
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Second
|
||||
context: Test
|
||||
relevance: 50
|
||||
- id: obs-3
|
||||
timestamp: "2024-01-15T10:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Third
|
||||
context: Test
|
||||
relevance: 50
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const recent = store.getRecent(2);
|
||||
|
||||
expect(recent).toHaveLength(2);
|
||||
expect(recent[0].content.action).toBe('Second');
|
||||
expect(recent[1].content.action).toBe('Third');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUncompressed', () => {
|
||||
it('should return observations not in the compressed list', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
- id: obs-3
|
||||
timestamp: "2024-01-15T10:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
const uncompressed = store.getUncompressed(['obs-1', 'obs-3']);
|
||||
|
||||
expect(uncompressed).toHaveLength(1);
|
||||
expect(uncompressed[0].id).toBe('obs-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
it('should clear all observations', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(`
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
`);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
store.clear();
|
||||
|
||||
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
|
||||
expect(content).toContain('observations: []');
|
||||
});
|
||||
});
|
||||
|
||||
describe('session management', () => {
|
||||
it('should clear observations when session ID changes', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: old-session
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: old-session
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'new-session');
|
||||
const observations = store.getAll();
|
||||
|
||||
expect(observations).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should allow setting session ID', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'initial-session');
|
||||
store.setSessionId('updated-session');
|
||||
|
||||
expect(store.getSessionId()).toBe('updated-session');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exists', () => {
|
||||
it('should return true when file exists', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
|
||||
const store = new ObservationStore('/test/project');
|
||||
|
||||
expect(store.exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when file does not exist', () => {
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
|
||||
const store = new ObservationStore('/test/project');
|
||||
|
||||
expect(store.exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('count', () => {
|
||||
it('should return the number of observations', () => {
|
||||
const existingData = `
|
||||
version: 1
|
||||
sessionId: session-1
|
||||
observations:
|
||||
- id: obs-1
|
||||
timestamp: "2024-01-15T09:00:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
- id: obs-2
|
||||
timestamp: "2024-01-15T09:30:00.000Z"
|
||||
sessionId: session-1
|
||||
agent: claude-code
|
||||
type: decision
|
||||
content:
|
||||
action: Test
|
||||
context: Test
|
||||
relevance: 50
|
||||
`;
|
||||
|
||||
vi.mocked(existsSync).mockReturnValue(true);
|
||||
vi.mocked(readFileSync).mockReturnValue(existingData);
|
||||
|
||||
const store = new ObservationStore('/test/project', 'session-1');
|
||||
|
||||
expect(store.count()).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,421 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { MemoryObserver, createMemoryObserver, type ObservableEvent } from '../observer.js';
|
||||
import type { ExecutionProgressEvent } from '../../executor/engine.js';
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('MemoryObserver', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should create an observer with default config', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
expect(observer).toBeDefined();
|
||||
expect(observer.getObservationCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('should accept custom session ID', () => {
|
||||
const observer = new MemoryObserver('/test/project', 'custom-session');
|
||||
expect(observer.getSessionId()).toBe('custom-session');
|
||||
});
|
||||
|
||||
it('should accept custom config', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
minRelevance: 50,
|
||||
captureTaskStarts: true,
|
||||
});
|
||||
expect(observer).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setAgent', () => {
|
||||
it('should set the current agent', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
observer.setAgent('cursor');
|
||||
// Agent is used when creating observations
|
||||
expect(observer).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setSkillName', () => {
|
||||
it('should set the current skill name', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
observer.setSkillName('test-skill');
|
||||
expect(observer).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('observe', () => {
|
||||
it('should capture high-relevance events', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'error_encountered',
|
||||
timestamp: new Date().toISOString(),
|
||||
error: 'TypeError: Cannot read property of undefined',
|
||||
context: 'Running test suite',
|
||||
};
|
||||
|
||||
const observation = observer.observe(event);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('error');
|
||||
expect(observation?.relevance).toBeGreaterThanOrEqual(80);
|
||||
});
|
||||
|
||||
it('should filter low-relevance events by default', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
minRelevance: 50,
|
||||
});
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'task_start',
|
||||
timestamp: new Date().toISOString(),
|
||||
taskName: 'Test task',
|
||||
};
|
||||
|
||||
// Task starts have low relevance and are disabled by default
|
||||
const observation = observer.observe(event);
|
||||
expect(observation).toBeNull();
|
||||
});
|
||||
|
||||
it('should capture task starts when enabled', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
captureTaskStarts: true,
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'task_start',
|
||||
timestamp: new Date().toISOString(),
|
||||
taskName: 'Test task',
|
||||
};
|
||||
|
||||
const observation = observer.observe(event);
|
||||
expect(observation).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should capture solutions with high relevance', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'solution_applied',
|
||||
timestamp: new Date().toISOString(),
|
||||
output: 'Added null check before accessing property',
|
||||
context: 'Fixed TypeError',
|
||||
};
|
||||
|
||||
const observation = observer.observe(event);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('solution');
|
||||
expect(observation?.relevance).toBeGreaterThanOrEqual(85);
|
||||
});
|
||||
|
||||
it('should capture decisions', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'checkpoint_decision',
|
||||
timestamp: new Date().toISOString(),
|
||||
decision: 'Use React hooks',
|
||||
context: 'Choosing state management approach',
|
||||
};
|
||||
|
||||
const observation = observer.observe(event);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('decision');
|
||||
});
|
||||
|
||||
it('should capture file modifications', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const event: ObservableEvent = {
|
||||
type: 'file_modified',
|
||||
timestamp: new Date().toISOString(),
|
||||
files: ['src/App.tsx', 'src/index.ts'],
|
||||
context: 'Refactoring components',
|
||||
};
|
||||
|
||||
const observation = observer.observe(event);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('file_change');
|
||||
expect(observation?.content.files).toContain('src/App.tsx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createProgressCallback', () => {
|
||||
it('should create a callback that captures progress events', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
const callback = observer.createProgressCallback();
|
||||
|
||||
const progressEvent: ExecutionProgressEvent = {
|
||||
type: 'task_complete',
|
||||
taskId: 'task-1',
|
||||
taskName: 'Build project',
|
||||
taskIndex: 0,
|
||||
totalTasks: 3,
|
||||
status: 'completed',
|
||||
message: 'Build completed successfully',
|
||||
};
|
||||
|
||||
callback(progressEvent);
|
||||
|
||||
expect(observer.getObservationCount()).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('should capture failed task events', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
const callback = observer.createProgressCallback();
|
||||
|
||||
const progressEvent: ExecutionProgressEvent = {
|
||||
type: 'task_complete',
|
||||
taskId: 'task-1',
|
||||
taskName: 'Run tests',
|
||||
status: 'failed',
|
||||
error: 'Test suite failed: 3 tests failed',
|
||||
};
|
||||
|
||||
callback(progressEvent);
|
||||
|
||||
const observations = observer.getObservations();
|
||||
const errorObs = observations.find((o) => o.type === 'error');
|
||||
expect(errorObs).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordFileModification', () => {
|
||||
it('should record file modifications', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordFileModification(
|
||||
['src/components/Button.tsx'],
|
||||
'Updated button styling'
|
||||
);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('file_change');
|
||||
expect(observation?.content.files).toContain('src/components/Button.tsx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordError', () => {
|
||||
it('should record errors', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordError(
|
||||
'ModuleNotFoundError: Cannot find module react',
|
||||
'Import resolution'
|
||||
);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('error');
|
||||
expect(observation?.content.error).toContain('ModuleNotFoundError');
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordSolution', () => {
|
||||
it('should record solutions', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordSolution(
|
||||
'Installed missing dependency: npm install react',
|
||||
'Fixed import error',
|
||||
'ModuleNotFoundError'
|
||||
);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('solution');
|
||||
});
|
||||
|
||||
it('should boost relevance for solutions matching pending errors', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
// First record an error
|
||||
observer.recordError('TypeError: x is not a function', 'Runtime error');
|
||||
|
||||
// Then record a matching solution
|
||||
const solution = observer.recordSolution(
|
||||
'Changed x to be a function',
|
||||
'Fixed type error',
|
||||
'TypeError: x is not a function'
|
||||
);
|
||||
|
||||
expect(solution).not.toBeNull();
|
||||
expect(solution?.relevance).toBeGreaterThanOrEqual(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordDecision', () => {
|
||||
it('should record decisions with options', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordDecision(
|
||||
'Use TypeScript',
|
||||
['TypeScript', 'JavaScript', 'Flow'],
|
||||
'Language selection'
|
||||
);
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('decision');
|
||||
expect(observation?.content.context).toContain('TypeScript');
|
||||
expect(observation?.content.context).toContain('JavaScript');
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordExecutionStart', () => {
|
||||
it('should record execution start', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
const observation = observer.recordExecutionStart('code-review', 'claude-code');
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.content.action).toContain('code-review');
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordExecutionPause', () => {
|
||||
it('should record execution pause', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordExecutionPause('User requested pause');
|
||||
|
||||
expect(observation).not.toBeNull();
|
||||
expect(observation?.type).toBe('checkpoint');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tag generation', () => {
|
||||
it('should generate typescript tags for .ts files', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordFileModification(
|
||||
['src/utils.ts', 'src/types.ts'],
|
||||
'Updated utilities'
|
||||
);
|
||||
|
||||
expect(observation?.content.tags).toContain('typescript');
|
||||
});
|
||||
|
||||
it('should generate testing tags for test files', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordFileModification(
|
||||
['src/__tests__/utils.test.ts'],
|
||||
'Added tests'
|
||||
);
|
||||
|
||||
expect(observation?.content.tags).toContain('testing');
|
||||
});
|
||||
|
||||
it('should generate error-related tags from error content', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
const observation = observer.recordError(
|
||||
'TypeError: Cannot read property of null',
|
||||
'Runtime error'
|
||||
);
|
||||
|
||||
expect(observation?.content.tags).toContain('null-check');
|
||||
});
|
||||
});
|
||||
|
||||
describe('relevance scoring', () => {
|
||||
it('should score errors higher than task completions', () => {
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
minRelevance: 0,
|
||||
captureTaskStarts: true,
|
||||
});
|
||||
|
||||
const errorObs = observer.observe({
|
||||
type: 'error_encountered',
|
||||
timestamp: new Date().toISOString(),
|
||||
error: 'Test error',
|
||||
context: 'Test',
|
||||
});
|
||||
|
||||
const taskObs = observer.observe({
|
||||
type: 'task_complete',
|
||||
timestamp: new Date().toISOString(),
|
||||
taskName: 'Test task',
|
||||
context: 'Test',
|
||||
});
|
||||
|
||||
expect(errorObs?.relevance).toBeGreaterThan(taskObs?.relevance || 0);
|
||||
});
|
||||
|
||||
it('should use custom relevance scorer when provided', () => {
|
||||
const customScorer = vi.fn().mockReturnValue(75);
|
||||
const observer = new MemoryObserver('/test/project', undefined, {
|
||||
relevanceScorer: customScorer,
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
observer.observe({
|
||||
type: 'task_complete',
|
||||
timestamp: new Date().toISOString(),
|
||||
taskName: 'Test',
|
||||
context: 'Test',
|
||||
});
|
||||
|
||||
expect(customScorer).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
it('should clear all observations', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
observer.recordError('Test error', 'Test context');
|
||||
expect(observer.getObservationCount()).toBeGreaterThan(0);
|
||||
|
||||
observer.clear();
|
||||
expect(observer.getObservationCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getObservations', () => {
|
||||
it('should return all observations', () => {
|
||||
const observer = new MemoryObserver('/test/project');
|
||||
|
||||
observer.recordError('Error 1', 'Context 1');
|
||||
observer.recordError('Error 2', 'Context 2');
|
||||
|
||||
const observations = observer.getObservations();
|
||||
expect(observations.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMemoryObserver', () => {
|
||||
it('should create an observer instance', () => {
|
||||
const observer = createMemoryObserver('/test/project');
|
||||
expect(observer).toBeInstanceOf(MemoryObserver);
|
||||
});
|
||||
|
||||
it('should pass through options', () => {
|
||||
const observer = createMemoryObserver('/test/project', 'session-123', {
|
||||
minRelevance: 60,
|
||||
});
|
||||
expect(observer.getSessionId()).toBe('session-123');
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Memory-Enabled Execution Engine Integration
|
||||
*
|
||||
* Provides utilities to integrate MemoryObserver with SkillExecutionEngine.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
import {
|
||||
SkillExecutionEngine,
|
||||
createExecutionEngine,
|
||||
type ExecutionProgressCallback,
|
||||
type ExecutionProgressEvent,
|
||||
} from '../executor/engine.js';
|
||||
import type { CheckpointHandler, ExecutionOptions, ExecutableSkill } from '../executor/types.js';
|
||||
import { MemoryObserver, type MemoryObserverConfig } from './observer.js';
|
||||
|
||||
/**
|
||||
* Options for creating a memory-enabled execution engine
|
||||
*/
|
||||
export interface MemoryEnabledEngineOptions {
|
||||
/** Checkpoint handler for interactive checkpoints */
|
||||
checkpointHandler?: CheckpointHandler;
|
||||
/** Additional progress callback (called alongside memory observer) */
|
||||
onProgress?: ExecutionProgressCallback;
|
||||
/** Memory observer configuration */
|
||||
memoryConfig?: MemoryObserverConfig;
|
||||
/** Session ID for the memory observer */
|
||||
sessionId?: string;
|
||||
/** Default agent type */
|
||||
defaultAgent?: AgentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory-enabled execution engine wrapper
|
||||
*/
|
||||
export class MemoryEnabledEngine {
|
||||
private engine: SkillExecutionEngine;
|
||||
private observer: MemoryObserver;
|
||||
private userProgressCallback?: ExecutionProgressCallback;
|
||||
|
||||
constructor(projectPath: string, options: MemoryEnabledEngineOptions = {}) {
|
||||
// Create memory observer
|
||||
this.observer = new MemoryObserver(projectPath, options.sessionId, options.memoryConfig);
|
||||
|
||||
// Set default agent if provided
|
||||
if (options.defaultAgent) {
|
||||
this.observer.setAgent(options.defaultAgent);
|
||||
}
|
||||
|
||||
// Store user's progress callback
|
||||
this.userProgressCallback = options.onProgress;
|
||||
|
||||
// Create the combined progress callback
|
||||
const combinedProgressCallback: ExecutionProgressCallback = (event: ExecutionProgressEvent) => {
|
||||
// Forward to memory observer
|
||||
const observerCallback = this.observer.createProgressCallback();
|
||||
observerCallback(event);
|
||||
|
||||
// Forward to user's callback if provided
|
||||
if (this.userProgressCallback) {
|
||||
this.userProgressCallback(event);
|
||||
}
|
||||
};
|
||||
|
||||
// Create the underlying engine with the combined callback
|
||||
this.engine = createExecutionEngine(projectPath, {
|
||||
checkpointHandler: options.checkpointHandler,
|
||||
onProgress: combinedProgressCallback,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a skill with memory observation
|
||||
*/
|
||||
async execute(
|
||||
skill: ExecutableSkill,
|
||||
options: ExecutionOptions = {}
|
||||
): ReturnType<SkillExecutionEngine['execute']> {
|
||||
// Set skill name in observer
|
||||
this.observer.setSkillName(skill.name);
|
||||
|
||||
// Set agent if provided in options
|
||||
if (options.agent) {
|
||||
this.observer.setAgent(options.agent);
|
||||
}
|
||||
|
||||
// Record execution start
|
||||
this.observer.recordExecutionStart(skill.name, options.agent || 'claude-code');
|
||||
|
||||
try {
|
||||
// Execute the skill
|
||||
const result = await this.engine.execute(skill, options);
|
||||
|
||||
// Record file modifications from result
|
||||
if (result.filesModified.length > 0) {
|
||||
this.observer.recordFileModification(
|
||||
result.filesModified,
|
||||
`Files modified during skill "${skill.name}" execution`
|
||||
);
|
||||
}
|
||||
|
||||
// Record any errors
|
||||
if (result.error) {
|
||||
this.observer.recordError(result.error, `Skill "${skill.name}" failed`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// Record unexpected errors
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
this.observer.recordError(errorMessage, `Unexpected error during skill "${skill.name}" execution`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a manual error observation
|
||||
*/
|
||||
recordError(error: string, context: string, taskId?: string): void {
|
||||
this.observer.recordError(error, context, taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a manual solution observation
|
||||
*/
|
||||
recordSolution(solution: string, context: string, relatedError?: string): void {
|
||||
this.observer.recordSolution(solution, context, relatedError);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a file modification observation
|
||||
*/
|
||||
recordFileModification(files: string[], context: string): void {
|
||||
this.observer.recordFileModification(files, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a decision observation
|
||||
*/
|
||||
recordDecision(decision: string, options: string[], context: string): void {
|
||||
this.observer.recordDecision(decision, options, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause execution
|
||||
*/
|
||||
pause(): boolean {
|
||||
const paused = this.engine.pause();
|
||||
if (paused) {
|
||||
this.observer.recordExecutionPause();
|
||||
}
|
||||
return paused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if execution is paused
|
||||
*/
|
||||
isPaused(): boolean {
|
||||
return this.engine.isPaused();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the memory observer
|
||||
*/
|
||||
getObserver(): MemoryObserver {
|
||||
return this.observer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying execution engine
|
||||
*/
|
||||
getEngine(): SkillExecutionEngine {
|
||||
return this.engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the session manager
|
||||
*/
|
||||
getSessionManager(): ReturnType<SkillExecutionEngine['getSessionManager']> {
|
||||
return this.engine.getSessionManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get observation count
|
||||
*/
|
||||
getObservationCount(): number {
|
||||
return this.observer.getObservationCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all observations
|
||||
*/
|
||||
getObservations(): ReturnType<MemoryObserver['getObservations']> {
|
||||
return this.observer.getObservations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear observations
|
||||
*/
|
||||
clearObservations(): void {
|
||||
this.observer.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a memory-enabled execution engine
|
||||
*/
|
||||
export function createMemoryEnabledEngine(
|
||||
projectPath: string,
|
||||
options?: MemoryEnabledEngineOptions
|
||||
): MemoryEnabledEngine {
|
||||
return new MemoryEnabledEngine(projectPath, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an existing progress callback with memory observation
|
||||
*/
|
||||
export function wrapProgressCallbackWithMemory(
|
||||
projectPath: string,
|
||||
existingCallback?: ExecutionProgressCallback,
|
||||
memoryConfig?: MemoryObserverConfig,
|
||||
sessionId?: string
|
||||
): { callback: ExecutionProgressCallback; observer: MemoryObserver } {
|
||||
const observer = new MemoryObserver(projectPath, sessionId, memoryConfig);
|
||||
const observerCallback = observer.createProgressCallback();
|
||||
|
||||
const wrappedCallback: ExecutionProgressCallback = (event: ExecutionProgressEvent) => {
|
||||
observerCallback(event);
|
||||
if (existingCallback) {
|
||||
existingCallback(event);
|
||||
}
|
||||
};
|
||||
|
||||
return { callback: wrappedCallback, observer };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Memory Module - Cross-Agent Session Memory System
|
||||
// Provides persistent memory across all AI coding agents
|
||||
|
||||
export * from './types.js';
|
||||
export { ObservationStore } from './observation-store.js';
|
||||
export { LearningStore } from './learning-store.js';
|
||||
export { MemoryIndexStore } from './memory-index.js';
|
||||
export {
|
||||
getMemoryPaths,
|
||||
initializeMemoryDirectory,
|
||||
memoryDirectoryExists,
|
||||
globalMemoryDirectoryExists,
|
||||
getMemoryStatus,
|
||||
type MemoryPaths,
|
||||
type MemoryStatus,
|
||||
} from './initializer.js';
|
||||
export {
|
||||
MemoryObserver,
|
||||
createMemoryObserver,
|
||||
type ObservableEvent,
|
||||
type ObservableEventType,
|
||||
type MemoryObserverConfig,
|
||||
} from './observer.js';
|
||||
export {
|
||||
MemoryEnabledEngine,
|
||||
createMemoryEnabledEngine,
|
||||
wrapProgressCallbackWithMemory,
|
||||
type MemoryEnabledEngineOptions,
|
||||
} from './engine-integration.js';
|
||||
export {
|
||||
RuleBasedCompressor,
|
||||
APIBasedCompressor,
|
||||
MemoryCompressor,
|
||||
LearningConsolidator,
|
||||
createRuleBasedCompressor,
|
||||
createAPIBasedCompressor,
|
||||
createMemoryCompressor,
|
||||
type CompressionEngine,
|
||||
type CompressedLearning,
|
||||
type CompressionResult,
|
||||
type CompressionOptions,
|
||||
type APICompressionConfig,
|
||||
} from './compressor.js';
|
||||
export {
|
||||
MemoryInjector,
|
||||
createMemoryInjector,
|
||||
type InjectionOptions,
|
||||
type InjectedMemory,
|
||||
type InjectionResult,
|
||||
} from './injector.js';
|
||||
@@ -0,0 +1,78 @@
|
||||
import { existsSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
export interface MemoryPaths {
|
||||
projectMemoryDir: string;
|
||||
globalMemoryDir: string;
|
||||
observationsFile: string;
|
||||
learningsFile: string;
|
||||
indexFile: string;
|
||||
globalLearningsFile: string;
|
||||
globalIndexFile: string;
|
||||
}
|
||||
|
||||
export function getMemoryPaths(projectPath: string): MemoryPaths {
|
||||
const projectMemoryDir = join(projectPath, '.skillkit', 'memory');
|
||||
const globalMemoryDir = join(homedir(), '.skillkit', 'memory');
|
||||
|
||||
return {
|
||||
projectMemoryDir,
|
||||
globalMemoryDir,
|
||||
observationsFile: join(projectMemoryDir, 'observations.yaml'),
|
||||
learningsFile: join(projectMemoryDir, 'learnings.yaml'),
|
||||
indexFile: join(projectMemoryDir, 'index.yaml'),
|
||||
globalLearningsFile: join(globalMemoryDir, 'global.yaml'),
|
||||
globalIndexFile: join(globalMemoryDir, 'index.yaml'),
|
||||
};
|
||||
}
|
||||
|
||||
export function initializeMemoryDirectory(projectPath: string): MemoryPaths {
|
||||
const paths = getMemoryPaths(projectPath);
|
||||
|
||||
// Create project memory directory
|
||||
if (!existsSync(paths.projectMemoryDir)) {
|
||||
mkdirSync(paths.projectMemoryDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Create global memory directory
|
||||
if (!existsSync(paths.globalMemoryDir)) {
|
||||
mkdirSync(paths.globalMemoryDir, { recursive: true });
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
export function memoryDirectoryExists(projectPath: string): boolean {
|
||||
const paths = getMemoryPaths(projectPath);
|
||||
return existsSync(paths.projectMemoryDir);
|
||||
}
|
||||
|
||||
export function globalMemoryDirectoryExists(): boolean {
|
||||
const globalMemoryDir = join(homedir(), '.skillkit', 'memory');
|
||||
return existsSync(globalMemoryDir);
|
||||
}
|
||||
|
||||
export interface MemoryStatus {
|
||||
projectMemoryExists: boolean;
|
||||
globalMemoryExists: boolean;
|
||||
hasObservations: boolean;
|
||||
hasLearnings: boolean;
|
||||
hasGlobalLearnings: boolean;
|
||||
hasIndex: boolean;
|
||||
hasGlobalIndex: boolean;
|
||||
}
|
||||
|
||||
export function getMemoryStatus(projectPath: string): MemoryStatus {
|
||||
const paths = getMemoryPaths(projectPath);
|
||||
|
||||
return {
|
||||
projectMemoryExists: existsSync(paths.projectMemoryDir),
|
||||
globalMemoryExists: existsSync(paths.globalMemoryDir),
|
||||
hasObservations: existsSync(paths.observationsFile),
|
||||
hasLearnings: existsSync(paths.learningsFile),
|
||||
hasGlobalLearnings: existsSync(paths.globalLearningsFile),
|
||||
hasIndex: existsSync(paths.indexFile),
|
||||
hasGlobalIndex: existsSync(paths.globalIndexFile),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,716 @@
|
||||
/**
|
||||
* Memory Injector
|
||||
*
|
||||
* Injects relevant memories into agent context with relevance matching,
|
||||
* agent-specific formatting, and token budgeting.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
import type { ProjectContext } from '../context/types.js';
|
||||
import type { Learning, MemorySummary, MemoryPreview, MemoryFull } from './types.js';
|
||||
import { LearningStore } from './learning-store.js';
|
||||
|
||||
/**
|
||||
* Injection options
|
||||
*/
|
||||
export interface InjectionOptions {
|
||||
/** Maximum tokens to use for injected memories */
|
||||
maxTokens?: number;
|
||||
/** Minimum relevance score to include (0-100) */
|
||||
minRelevance?: number;
|
||||
/** Maximum number of learnings to inject */
|
||||
maxLearnings?: number;
|
||||
/** Include global memories */
|
||||
includeGlobal?: boolean;
|
||||
/** Specific tags to match */
|
||||
tags?: string[];
|
||||
/** Current task description for relevance matching */
|
||||
currentTask?: string;
|
||||
/** Progressive disclosure level */
|
||||
disclosureLevel?: 'summary' | 'preview' | 'full';
|
||||
}
|
||||
|
||||
/**
|
||||
* Injected memory with relevance score
|
||||
*/
|
||||
export interface InjectedMemory {
|
||||
learning: Learning;
|
||||
relevanceScore: number;
|
||||
matchedBy: {
|
||||
frameworks: string[];
|
||||
tags: string[];
|
||||
keywords: string[];
|
||||
patterns: string[];
|
||||
};
|
||||
tokenEstimate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injection result
|
||||
*/
|
||||
export interface InjectionResult {
|
||||
memories: InjectedMemory[];
|
||||
formattedContent: string;
|
||||
totalTokens: number;
|
||||
stats: {
|
||||
considered: number;
|
||||
matched: number;
|
||||
injected: number;
|
||||
truncated: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Default injection options
|
||||
*/
|
||||
const DEFAULT_OPTIONS: Required<Omit<InjectionOptions, 'tags' | 'currentTask'>> = {
|
||||
maxTokens: 2000,
|
||||
minRelevance: 30,
|
||||
maxLearnings: 10,
|
||||
includeGlobal: true,
|
||||
disclosureLevel: 'preview',
|
||||
};
|
||||
|
||||
/**
|
||||
* Approximate tokens per character (conservative estimate)
|
||||
*/
|
||||
const TOKENS_PER_CHAR = 0.25;
|
||||
|
||||
/**
|
||||
* Memory Injector
|
||||
*
|
||||
* Retrieves and formats relevant memories for injection into agent context.
|
||||
*/
|
||||
export class MemoryInjector {
|
||||
private projectStore: LearningStore;
|
||||
private globalStore: LearningStore;
|
||||
private projectContext?: ProjectContext;
|
||||
|
||||
constructor(
|
||||
projectPath: string,
|
||||
projectName?: string,
|
||||
projectContext?: ProjectContext
|
||||
) {
|
||||
this.projectStore = new LearningStore('project', projectPath, projectName);
|
||||
this.globalStore = new LearningStore('global');
|
||||
this.projectContext = projectContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set project context for better relevance matching
|
||||
*/
|
||||
setProjectContext(context: ProjectContext): void {
|
||||
this.projectContext = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get relevant memories for injection
|
||||
*/
|
||||
async getRelevantMemories(options: InjectionOptions = {}): Promise<InjectedMemory[]> {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
|
||||
// Collect all learnings
|
||||
const projectLearnings = this.projectStore.getAll();
|
||||
const globalLearnings = opts.includeGlobal ? this.globalStore.getAll() : [];
|
||||
const allLearnings = [...projectLearnings, ...globalLearnings];
|
||||
|
||||
// Score each learning for relevance
|
||||
const scored = allLearnings.map((learning) => ({
|
||||
learning,
|
||||
...this.scoreLearning(learning, opts),
|
||||
}));
|
||||
|
||||
// Filter by minimum relevance
|
||||
const filtered = scored.filter((s) => s.relevanceScore >= opts.minRelevance);
|
||||
|
||||
// Sort by relevance (descending)
|
||||
filtered.sort((a, b) => b.relevanceScore - a.relevanceScore);
|
||||
|
||||
// Limit to max learnings
|
||||
return filtered.slice(0, opts.maxLearnings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Score a learning for relevance to current context
|
||||
*/
|
||||
private scoreLearning(
|
||||
learning: Learning,
|
||||
options: InjectionOptions
|
||||
): Omit<InjectedMemory, 'learning'> {
|
||||
let score = 0;
|
||||
const matchedBy = {
|
||||
frameworks: [] as string[],
|
||||
tags: [] as string[],
|
||||
keywords: [] as string[],
|
||||
patterns: [] as string[],
|
||||
};
|
||||
|
||||
// Match by frameworks from project context
|
||||
if (this.projectContext?.stack) {
|
||||
const projectFrameworks = this.extractFrameworkNames();
|
||||
const learningFrameworks = learning.frameworks || [];
|
||||
|
||||
for (const fw of learningFrameworks) {
|
||||
if (projectFrameworks.has(fw.toLowerCase())) {
|
||||
score += 15;
|
||||
matchedBy.frameworks.push(fw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Match by explicitly requested tags
|
||||
if (options.tags && options.tags.length > 0) {
|
||||
const requestedTags = new Set(options.tags.map((t) => t.toLowerCase()));
|
||||
for (const tag of learning.tags) {
|
||||
if (requestedTags.has(tag.toLowerCase())) {
|
||||
score += 20;
|
||||
matchedBy.tags.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Match by current task keywords
|
||||
if (options.currentTask) {
|
||||
const taskKeywords = this.extractKeywords(options.currentTask);
|
||||
const learningKeywords = [
|
||||
...this.extractKeywords(learning.title),
|
||||
...this.extractKeywords(learning.content),
|
||||
...learning.tags,
|
||||
];
|
||||
|
||||
const learningKeywordSet = new Set(learningKeywords.map((k) => k.toLowerCase()));
|
||||
for (const kw of taskKeywords) {
|
||||
if (learningKeywordSet.has(kw.toLowerCase())) {
|
||||
score += 10;
|
||||
if (!matchedBy.keywords.includes(kw)) {
|
||||
matchedBy.keywords.push(kw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Match by patterns
|
||||
if (learning.patterns && learning.patterns.length > 0) {
|
||||
// Patterns are valuable - boost score
|
||||
score += learning.patterns.length * 5;
|
||||
matchedBy.patterns.push(...learning.patterns);
|
||||
}
|
||||
|
||||
// Boost by effectiveness if known
|
||||
if (learning.effectiveness !== undefined) {
|
||||
score += (learning.effectiveness / 100) * 20;
|
||||
}
|
||||
|
||||
// Boost by use count (popular learnings are likely valuable)
|
||||
score += Math.min(learning.useCount * 2, 15);
|
||||
|
||||
// Boost recent learnings
|
||||
const daysSinceUpdate = this.daysSince(learning.updatedAt);
|
||||
if (daysSinceUpdate < 7) {
|
||||
score += 10;
|
||||
} else if (daysSinceUpdate < 30) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Cap score at 100
|
||||
score = Math.min(score, 100);
|
||||
|
||||
// Estimate token count
|
||||
const tokenEstimate = this.estimateTokens(learning, options.disclosureLevel || 'preview');
|
||||
|
||||
return {
|
||||
relevanceScore: score,
|
||||
matchedBy,
|
||||
tokenEstimate,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract framework names from project context
|
||||
*/
|
||||
private extractFrameworkNames(): Set<string> {
|
||||
const names = new Set<string>();
|
||||
|
||||
if (!this.projectContext?.stack) return names;
|
||||
|
||||
const stack = this.projectContext.stack;
|
||||
const categories = [
|
||||
stack.languages,
|
||||
stack.frameworks,
|
||||
stack.libraries,
|
||||
stack.styling,
|
||||
stack.testing,
|
||||
stack.databases,
|
||||
stack.tools,
|
||||
stack.runtime,
|
||||
];
|
||||
|
||||
for (const category of categories) {
|
||||
for (const detection of category) {
|
||||
names.add(detection.name.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract keywords from text
|
||||
*/
|
||||
private extractKeywords(text: string): string[] {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.split(/[\s\-_.,;:!?()[\]{}'"]+/)
|
||||
.filter((word) => word.length > 2 && !STOP_WORDS.has(word));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate days since a date
|
||||
*/
|
||||
private daysSince(dateStr: string): number {
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
return Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate tokens for a learning
|
||||
*/
|
||||
private estimateTokens(
|
||||
learning: Learning,
|
||||
level: 'summary' | 'preview' | 'full'
|
||||
): number {
|
||||
switch (level) {
|
||||
case 'summary':
|
||||
return Math.ceil((learning.title.length + learning.tags.join(' ').length) * TOKENS_PER_CHAR);
|
||||
case 'preview':
|
||||
const excerpt = learning.content.slice(0, 200);
|
||||
return Math.ceil(
|
||||
(learning.title.length + excerpt.length + learning.tags.join(' ').length) * TOKENS_PER_CHAR
|
||||
);
|
||||
case 'full':
|
||||
return Math.ceil(
|
||||
(learning.title.length + learning.content.length + learning.tags.join(' ').length) *
|
||||
TOKENS_PER_CHAR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject memories and return formatted content
|
||||
*/
|
||||
async inject(options: InjectionOptions = {}): Promise<InjectionResult> {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
const allMemories = await this.getRelevantMemories(opts);
|
||||
|
||||
// Select memories within token budget
|
||||
const selected: InjectedMemory[] = [];
|
||||
let totalTokens = 0;
|
||||
let truncated = 0;
|
||||
|
||||
for (const memory of allMemories) {
|
||||
if (totalTokens + memory.tokenEstimate <= opts.maxTokens) {
|
||||
selected.push(memory);
|
||||
totalTokens += memory.tokenEstimate;
|
||||
|
||||
// Increment use count
|
||||
if (memory.learning.scope === 'project') {
|
||||
this.projectStore.incrementUseCount(memory.learning.id);
|
||||
} else {
|
||||
this.globalStore.incrementUseCount(memory.learning.id);
|
||||
}
|
||||
} else {
|
||||
truncated++;
|
||||
}
|
||||
}
|
||||
|
||||
// Format the content
|
||||
const formattedContent = this.formatMemories(selected, opts.disclosureLevel || 'preview');
|
||||
|
||||
return {
|
||||
memories: selected,
|
||||
formattedContent,
|
||||
totalTokens,
|
||||
stats: {
|
||||
considered: this.projectStore.count() + (opts.includeGlobal ? this.globalStore.count() : 0),
|
||||
matched: allMemories.length,
|
||||
injected: selected.length,
|
||||
truncated,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject memories formatted for a specific agent
|
||||
*/
|
||||
async injectForAgent(
|
||||
agent: AgentType,
|
||||
options: InjectionOptions = {}
|
||||
): Promise<InjectionResult> {
|
||||
const result = await this.inject(options);
|
||||
|
||||
// Reformat for specific agent
|
||||
result.formattedContent = this.formatForAgent(result.memories, agent, options.disclosureLevel);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format memories for display
|
||||
*/
|
||||
private formatMemories(
|
||||
memories: InjectedMemory[],
|
||||
level: 'summary' | 'preview' | 'full'
|
||||
): string {
|
||||
if (memories.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const lines: string[] = ['# Relevant Memories', ''];
|
||||
|
||||
for (const { learning, relevanceScore, matchedBy } of memories) {
|
||||
lines.push(`## ${learning.title}`);
|
||||
lines.push(`*Relevance: ${relevanceScore}% | Tags: ${learning.tags.join(', ')}*`);
|
||||
|
||||
if (matchedBy.frameworks.length > 0) {
|
||||
lines.push(`*Matched frameworks: ${matchedBy.frameworks.join(', ')}*`);
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
|
||||
switch (level) {
|
||||
case 'summary':
|
||||
// Just title and tags (already shown above)
|
||||
break;
|
||||
case 'preview':
|
||||
lines.push(learning.content.slice(0, 200) + (learning.content.length > 200 ? '...' : ''));
|
||||
break;
|
||||
case 'full':
|
||||
lines.push(learning.content);
|
||||
break;
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format memories for a specific agent
|
||||
*/
|
||||
formatForAgent(
|
||||
memories: InjectedMemory[],
|
||||
agent: AgentType,
|
||||
level: 'summary' | 'preview' | 'full' = 'preview'
|
||||
): string {
|
||||
if (memories.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
switch (agent) {
|
||||
case 'claude-code':
|
||||
return this.formatForClaude(memories, level);
|
||||
case 'cursor':
|
||||
return this.formatForCursor(memories, level);
|
||||
case 'codex':
|
||||
case 'github-copilot':
|
||||
return this.formatForCopilot(memories, level);
|
||||
default:
|
||||
return this.formatMemories(memories, level);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format memories for Claude (XML tags)
|
||||
*/
|
||||
private formatForClaude(
|
||||
memories: InjectedMemory[],
|
||||
level: 'summary' | 'preview' | 'full'
|
||||
): string {
|
||||
const lines: string[] = ['<memories>'];
|
||||
|
||||
for (const { learning, relevanceScore } of memories) {
|
||||
lines.push(` <memory relevance="${relevanceScore}" scope="${learning.scope}">`);
|
||||
lines.push(` <title>${this.escapeXml(learning.title)}</title>`);
|
||||
lines.push(` <tags>${learning.tags.join(', ')}</tags>`);
|
||||
|
||||
if (level !== 'summary') {
|
||||
const content =
|
||||
level === 'preview' ? learning.content.slice(0, 200) : learning.content;
|
||||
lines.push(` <content>${this.escapeXml(content)}</content>`);
|
||||
}
|
||||
|
||||
if (learning.frameworks && learning.frameworks.length > 0) {
|
||||
lines.push(` <frameworks>${learning.frameworks.join(', ')}</frameworks>`);
|
||||
}
|
||||
|
||||
lines.push(' </memory>');
|
||||
}
|
||||
|
||||
lines.push('</memories>');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format memories for Cursor (.mdc format)
|
||||
*/
|
||||
private formatForCursor(
|
||||
memories: InjectedMemory[],
|
||||
level: 'summary' | 'preview' | 'full'
|
||||
): string {
|
||||
const lines: string[] = [
|
||||
'---',
|
||||
'description: Relevant memories from previous sessions',
|
||||
'globs:',
|
||||
' - "**/*"',
|
||||
'---',
|
||||
'',
|
||||
'# Session Memories',
|
||||
'',
|
||||
];
|
||||
|
||||
for (const { learning, relevanceScore } of memories) {
|
||||
lines.push(`## ${learning.title}`);
|
||||
lines.push('');
|
||||
lines.push(`> Relevance: ${relevanceScore}% | Tags: ${learning.tags.join(', ')}`);
|
||||
lines.push('');
|
||||
|
||||
if (level !== 'summary') {
|
||||
const content =
|
||||
level === 'preview'
|
||||
? learning.content.slice(0, 200) + (learning.content.length > 200 ? '...' : '')
|
||||
: learning.content;
|
||||
lines.push(content);
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format memories for Copilot/Codex (concise markdown)
|
||||
*/
|
||||
private formatForCopilot(
|
||||
memories: InjectedMemory[],
|
||||
level: 'summary' | 'preview' | 'full'
|
||||
): string {
|
||||
const lines: string[] = ['<!-- Session Memories -->'];
|
||||
|
||||
for (const { learning } of memories) {
|
||||
lines.push(`### ${learning.title}`);
|
||||
lines.push(`Tags: ${learning.tags.join(', ')}`);
|
||||
|
||||
if (level !== 'summary') {
|
||||
const content =
|
||||
level === 'preview' ? learning.content.slice(0, 150) : learning.content;
|
||||
lines.push(content);
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape XML special characters
|
||||
*/
|
||||
private escapeXml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory summaries (for progressive disclosure)
|
||||
*/
|
||||
getSummaries(options: InjectionOptions = {}): MemorySummary[] {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
|
||||
const projectLearnings = this.projectStore.getAll();
|
||||
const globalLearnings = opts.includeGlobal ? this.globalStore.getAll() : [];
|
||||
const allLearnings = [...projectLearnings, ...globalLearnings];
|
||||
|
||||
return allLearnings.map((learning) => ({
|
||||
id: learning.id,
|
||||
title: learning.title,
|
||||
tags: learning.tags,
|
||||
relevance: this.scoreLearning(learning, opts).relevanceScore,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory previews (for progressive disclosure)
|
||||
*/
|
||||
getPreviews(ids: string[], options: InjectionOptions = {}): MemoryPreview[] {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
const previews: MemoryPreview[] = [];
|
||||
|
||||
for (const id of ids) {
|
||||
let learning = this.projectStore.getById(id);
|
||||
if (!learning && opts.includeGlobal) {
|
||||
learning = this.globalStore.getById(id);
|
||||
}
|
||||
|
||||
if (learning) {
|
||||
previews.push({
|
||||
id: learning.id,
|
||||
title: learning.title,
|
||||
tags: learning.tags,
|
||||
relevance: this.scoreLearning(learning, opts).relevanceScore,
|
||||
excerpt: learning.content.slice(0, 200),
|
||||
lastUsed: learning.lastUsed,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return previews;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full memories (for progressive disclosure)
|
||||
*/
|
||||
getFullMemories(ids: string[], options: InjectionOptions = {}): MemoryFull[] {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
const fullMemories: MemoryFull[] = [];
|
||||
|
||||
for (const id of ids) {
|
||||
let learning = this.projectStore.getById(id);
|
||||
if (!learning && opts.includeGlobal) {
|
||||
learning = this.globalStore.getById(id);
|
||||
}
|
||||
|
||||
if (learning) {
|
||||
fullMemories.push({
|
||||
id: learning.id,
|
||||
title: learning.title,
|
||||
tags: learning.tags,
|
||||
relevance: this.scoreLearning(learning, opts).relevanceScore,
|
||||
excerpt: learning.content.slice(0, 200),
|
||||
lastUsed: learning.lastUsed,
|
||||
content: learning.content,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return fullMemories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search memories by query
|
||||
*/
|
||||
search(query: string, options: InjectionOptions = {}): InjectedMemory[] {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options, currentTask: query };
|
||||
const projectResults = this.projectStore.search(query);
|
||||
const globalResults = opts.includeGlobal ? this.globalStore.search(query) : [];
|
||||
const allResults = [...projectResults, ...globalResults];
|
||||
|
||||
return allResults
|
||||
.map((learning) => ({
|
||||
learning,
|
||||
...this.scoreLearning(learning, opts),
|
||||
}))
|
||||
.filter((m) => m.relevanceScore >= opts.minRelevance)
|
||||
.sort((a, b) => b.relevanceScore - a.relevanceScore)
|
||||
.slice(0, opts.maxLearnings);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common stop words to ignore in keyword extraction
|
||||
*/
|
||||
const STOP_WORDS = new Set([
|
||||
'the',
|
||||
'a',
|
||||
'an',
|
||||
'and',
|
||||
'or',
|
||||
'but',
|
||||
'in',
|
||||
'on',
|
||||
'at',
|
||||
'to',
|
||||
'for',
|
||||
'of',
|
||||
'with',
|
||||
'by',
|
||||
'from',
|
||||
'as',
|
||||
'is',
|
||||
'was',
|
||||
'are',
|
||||
'were',
|
||||
'been',
|
||||
'be',
|
||||
'have',
|
||||
'has',
|
||||
'had',
|
||||
'do',
|
||||
'does',
|
||||
'did',
|
||||
'will',
|
||||
'would',
|
||||
'could',
|
||||
'should',
|
||||
'may',
|
||||
'might',
|
||||
'must',
|
||||
'can',
|
||||
'this',
|
||||
'that',
|
||||
'these',
|
||||
'those',
|
||||
'i',
|
||||
'you',
|
||||
'he',
|
||||
'she',
|
||||
'it',
|
||||
'we',
|
||||
'they',
|
||||
'what',
|
||||
'which',
|
||||
'who',
|
||||
'when',
|
||||
'where',
|
||||
'why',
|
||||
'how',
|
||||
'all',
|
||||
'each',
|
||||
'every',
|
||||
'both',
|
||||
'few',
|
||||
'more',
|
||||
'most',
|
||||
'other',
|
||||
'some',
|
||||
'such',
|
||||
'no',
|
||||
'nor',
|
||||
'not',
|
||||
'only',
|
||||
'own',
|
||||
'same',
|
||||
'so',
|
||||
'than',
|
||||
'too',
|
||||
'very',
|
||||
'just',
|
||||
'also',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Create a MemoryInjector instance
|
||||
*/
|
||||
export function createMemoryInjector(
|
||||
projectPath: string,
|
||||
projectName?: string,
|
||||
projectContext?: ProjectContext
|
||||
): MemoryInjector {
|
||||
return new MemoryInjector(projectPath, projectName, projectContext);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { Learning, LearningStoreData } from './types.js';
|
||||
|
||||
export class LearningStore {
|
||||
private readonly filePath: string;
|
||||
private readonly scope: 'project' | 'global';
|
||||
private readonly projectName?: string;
|
||||
private data: LearningStoreData | null = null;
|
||||
|
||||
constructor(
|
||||
scope: 'project' | 'global',
|
||||
projectPath?: string,
|
||||
projectName?: string
|
||||
) {
|
||||
this.scope = scope;
|
||||
this.projectName = projectName;
|
||||
|
||||
if (scope === 'project' && projectPath) {
|
||||
this.filePath = join(projectPath, '.skillkit', 'memory', 'learnings.yaml');
|
||||
} else {
|
||||
this.filePath = join(homedir(), '.skillkit', 'memory', 'global.yaml');
|
||||
}
|
||||
}
|
||||
|
||||
private ensureDir(): void {
|
||||
const dir = dirname(this.filePath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
private load(): LearningStoreData {
|
||||
if (this.data) return this.data;
|
||||
|
||||
if (existsSync(this.filePath)) {
|
||||
try {
|
||||
const content = readFileSync(this.filePath, 'utf-8');
|
||||
this.data = parseYaml(content) as LearningStoreData;
|
||||
} catch {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
} else {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private createEmpty(): LearningStoreData {
|
||||
return {
|
||||
version: 1,
|
||||
learnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
this.ensureDir();
|
||||
const content = stringifyYaml(this.data, { lineWidth: 0 });
|
||||
writeFileSync(this.filePath, content, 'utf-8');
|
||||
}
|
||||
|
||||
add(learning: Omit<Learning, 'id' | 'createdAt' | 'updatedAt' | 'useCount' | 'scope' | 'project'>): Learning {
|
||||
const data = this.load();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const newLearning: Learning = {
|
||||
...learning,
|
||||
id: randomUUID(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
useCount: 0,
|
||||
scope: this.scope,
|
||||
project: this.projectName,
|
||||
};
|
||||
|
||||
data.learnings.push(newLearning);
|
||||
this.save();
|
||||
|
||||
return newLearning;
|
||||
}
|
||||
|
||||
update(id: string, updates: Partial<Omit<Learning, 'id' | 'createdAt'>>): Learning | null {
|
||||
const data = this.load();
|
||||
const index = data.learnings.findIndex((l) => l.id === id);
|
||||
|
||||
if (index === -1) return null;
|
||||
|
||||
data.learnings[index] = {
|
||||
...data.learnings[index],
|
||||
...updates,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.save();
|
||||
return data.learnings[index];
|
||||
}
|
||||
|
||||
delete(id: string): boolean {
|
||||
const data = this.load();
|
||||
const index = data.learnings.findIndex((l) => l.id === id);
|
||||
|
||||
if (index === -1) return false;
|
||||
|
||||
data.learnings.splice(index, 1);
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
getAll(): Learning[] {
|
||||
return this.load().learnings;
|
||||
}
|
||||
|
||||
getById(id: string): Learning | undefined {
|
||||
return this.load().learnings.find((l) => l.id === id);
|
||||
}
|
||||
|
||||
getByTags(tags: string[]): Learning[] {
|
||||
const tagSet = new Set(tags.map((t) => t.toLowerCase()));
|
||||
return this.load().learnings.filter((l) =>
|
||||
l.tags.some((t) => tagSet.has(t.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
getByFrameworks(frameworks: string[]): Learning[] {
|
||||
const fwSet = new Set(frameworks.map((f) => f.toLowerCase()));
|
||||
return this.load().learnings.filter((l) =>
|
||||
l.frameworks?.some((f) => fwSet.has(f.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
getRecent(count: number): Learning[] {
|
||||
const learnings = this.load().learnings;
|
||||
return [...learnings]
|
||||
.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
|
||||
.slice(0, count);
|
||||
}
|
||||
|
||||
getMostUsed(count: number): Learning[] {
|
||||
const learnings = this.load().learnings;
|
||||
return [...learnings].sort((a, b) => b.useCount - a.useCount).slice(0, count);
|
||||
}
|
||||
|
||||
getMostEffective(count: number): Learning[] {
|
||||
const learnings = this.load().learnings.filter((l) => l.effectiveness !== undefined);
|
||||
return [...learnings]
|
||||
.sort((a, b) => (b.effectiveness || 0) - (a.effectiveness || 0))
|
||||
.slice(0, count);
|
||||
}
|
||||
|
||||
incrementUseCount(id: string): void {
|
||||
const data = this.load();
|
||||
const learning = data.learnings.find((l) => l.id === id);
|
||||
|
||||
if (learning) {
|
||||
learning.useCount += 1;
|
||||
learning.lastUsed = new Date().toISOString();
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
setEffectiveness(id: string, effectiveness: number): void {
|
||||
const data = this.load();
|
||||
const learning = data.learnings.find((l) => l.id === id);
|
||||
|
||||
if (learning) {
|
||||
learning.effectiveness = Math.max(0, Math.min(100, effectiveness));
|
||||
learning.updatedAt = new Date().toISOString();
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
search(query: string): Learning[] {
|
||||
const queryLower = query.toLowerCase();
|
||||
const queryWords = queryLower.split(/\s+/).filter((w) => w.length > 2);
|
||||
|
||||
return this.load().learnings.filter((l) => {
|
||||
const titleMatch = l.title.toLowerCase().includes(queryLower);
|
||||
const contentMatch = l.content.toLowerCase().includes(queryLower);
|
||||
const tagMatch = l.tags.some((t) => t.toLowerCase().includes(queryLower));
|
||||
const wordMatch = queryWords.some(
|
||||
(word) =>
|
||||
l.title.toLowerCase().includes(word) ||
|
||||
l.content.toLowerCase().includes(word)
|
||||
);
|
||||
|
||||
return titleMatch || contentMatch || tagMatch || wordMatch;
|
||||
});
|
||||
}
|
||||
|
||||
count(): number {
|
||||
return this.load().learnings.length;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.data = this.createEmpty();
|
||||
this.save();
|
||||
}
|
||||
|
||||
exists(): boolean {
|
||||
return existsSync(this.filePath);
|
||||
}
|
||||
|
||||
getScope(): 'project' | 'global' {
|
||||
return this.scope;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
import type { Learning, MemoryIndex } from './types.js';
|
||||
|
||||
export class MemoryIndexStore {
|
||||
private readonly filePath: string;
|
||||
private data: MemoryIndex | null = null;
|
||||
|
||||
constructor(basePath: string, _isGlobal = false) {
|
||||
// Both global and project use .skillkit subdirectory
|
||||
// Global: ~/.skillkit/memory/index.yaml (basePath = homedir())
|
||||
// Project: <projectPath>/.skillkit/memory/index.yaml (basePath = projectPath)
|
||||
// Note: _isGlobal kept for API compatibility but basePath determines the actual path
|
||||
this.filePath = join(basePath, '.skillkit', 'memory', 'index.yaml');
|
||||
}
|
||||
|
||||
private ensureDir(): void {
|
||||
const dir = dirname(this.filePath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
private load(): MemoryIndex {
|
||||
if (this.data) return this.data;
|
||||
|
||||
if (existsSync(this.filePath)) {
|
||||
try {
|
||||
const content = readFileSync(this.filePath, 'utf-8');
|
||||
this.data = parseYaml(content) as MemoryIndex;
|
||||
} catch {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
} else {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private createEmpty(): MemoryIndex {
|
||||
return {
|
||||
version: 1,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
entries: {},
|
||||
tags: {},
|
||||
};
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
this.ensureDir();
|
||||
if (this.data) {
|
||||
this.data.lastUpdated = new Date().toISOString();
|
||||
}
|
||||
const content = stringifyYaml(this.data, { lineWidth: 0 });
|
||||
writeFileSync(this.filePath, content, 'utf-8');
|
||||
}
|
||||
|
||||
private extractKeywords(text: string): string[] {
|
||||
// Extract meaningful keywords from text
|
||||
const stopWords = new Set([
|
||||
'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
|
||||
'of', 'with', 'by', 'from', 'is', 'are', 'was', 'were', 'be', 'been',
|
||||
'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
|
||||
'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that',
|
||||
'these', 'those', 'it', 'its', 'i', 'you', 'we', 'they', 'he', 'she',
|
||||
]);
|
||||
|
||||
const words = text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, ' ')
|
||||
.split(/\s+/)
|
||||
.filter((word) => word.length > 2 && !stopWords.has(word));
|
||||
|
||||
return [...new Set(words)];
|
||||
}
|
||||
|
||||
indexLearning(learning: Learning): void {
|
||||
const data = this.load();
|
||||
|
||||
// Extract keywords from title and content
|
||||
const titleKeywords = this.extractKeywords(learning.title);
|
||||
const contentKeywords = this.extractKeywords(learning.content);
|
||||
const allKeywords = [...new Set([...titleKeywords, ...contentKeywords])];
|
||||
|
||||
// Index by keywords
|
||||
for (const keyword of allKeywords) {
|
||||
if (!data.entries[keyword]) {
|
||||
data.entries[keyword] = [];
|
||||
}
|
||||
if (!data.entries[keyword].includes(learning.id)) {
|
||||
data.entries[keyword].push(learning.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Index by tags
|
||||
for (const tag of learning.tags) {
|
||||
const normalizedTag = tag.toLowerCase();
|
||||
if (!data.tags[normalizedTag]) {
|
||||
data.tags[normalizedTag] = [];
|
||||
}
|
||||
if (!data.tags[normalizedTag].includes(learning.id)) {
|
||||
data.tags[normalizedTag].push(learning.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Index by frameworks if present
|
||||
if (learning.frameworks) {
|
||||
for (const framework of learning.frameworks) {
|
||||
const normalizedFw = framework.toLowerCase();
|
||||
if (!data.tags[normalizedFw]) {
|
||||
data.tags[normalizedFw] = [];
|
||||
}
|
||||
if (!data.tags[normalizedFw].includes(learning.id)) {
|
||||
data.tags[normalizedFw].push(learning.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
removeLearning(learningId: string): void {
|
||||
const data = this.load();
|
||||
|
||||
// Remove from keyword entries
|
||||
for (const keyword of Object.keys(data.entries)) {
|
||||
data.entries[keyword] = data.entries[keyword].filter((id) => id !== learningId);
|
||||
if (data.entries[keyword].length === 0) {
|
||||
delete data.entries[keyword];
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from tags
|
||||
for (const tag of Object.keys(data.tags)) {
|
||||
data.tags[tag] = data.tags[tag].filter((id) => id !== learningId);
|
||||
if (data.tags[tag].length === 0) {
|
||||
delete data.tags[tag];
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
searchByKeywords(query: string): string[] {
|
||||
const data = this.load();
|
||||
const keywords = this.extractKeywords(query);
|
||||
|
||||
if (keywords.length === 0) return [];
|
||||
|
||||
// Find IDs that match any keyword
|
||||
const matchCounts = new Map<string, number>();
|
||||
|
||||
for (const keyword of keywords) {
|
||||
// Exact match
|
||||
if (data.entries[keyword]) {
|
||||
for (const id of data.entries[keyword]) {
|
||||
matchCounts.set(id, (matchCounts.get(id) || 0) + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Partial match (keyword is substring of indexed word, but not exact match)
|
||||
for (const [indexed, ids] of Object.entries(data.entries)) {
|
||||
// Skip exact matches - they're already counted above with higher weight
|
||||
if (indexed === keyword) continue;
|
||||
if (indexed.includes(keyword) || keyword.includes(indexed)) {
|
||||
for (const id of ids) {
|
||||
matchCounts.set(id, (matchCounts.get(id) || 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by match count (most matches first)
|
||||
return [...matchCounts.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([id]) => id);
|
||||
}
|
||||
|
||||
searchByTags(tags: string[]): string[] {
|
||||
const data = this.load();
|
||||
const normalizedTags = tags.map((t) => t.toLowerCase());
|
||||
|
||||
const matchCounts = new Map<string, number>();
|
||||
|
||||
for (const tag of normalizedTags) {
|
||||
if (data.tags[tag]) {
|
||||
for (const id of data.tags[tag]) {
|
||||
matchCounts.set(id, (matchCounts.get(id) || 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by match count
|
||||
return [...matchCounts.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([id]) => id);
|
||||
}
|
||||
|
||||
search(query: string, tags?: string[]): string[] {
|
||||
const keywordResults = this.searchByKeywords(query);
|
||||
const tagResults = tags ? this.searchByTags(tags) : [];
|
||||
|
||||
if (!tags || tags.length === 0) {
|
||||
return keywordResults;
|
||||
}
|
||||
|
||||
if (!query || query.trim().length === 0) {
|
||||
return tagResults;
|
||||
}
|
||||
|
||||
// Combine results, prioritizing items that match both
|
||||
const keywordSet = new Set(keywordResults);
|
||||
const tagSet = new Set(tagResults);
|
||||
|
||||
const both: string[] = [];
|
||||
const keywordOnly: string[] = [];
|
||||
const tagOnly: string[] = [];
|
||||
|
||||
for (const id of keywordResults) {
|
||||
if (tagSet.has(id)) {
|
||||
both.push(id);
|
||||
} else {
|
||||
keywordOnly.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const id of tagResults) {
|
||||
if (!keywordSet.has(id)) {
|
||||
tagOnly.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
return [...both, ...keywordOnly, ...tagOnly];
|
||||
}
|
||||
|
||||
getAllTags(): string[] {
|
||||
const data = this.load();
|
||||
return Object.keys(data.tags).sort();
|
||||
}
|
||||
|
||||
getTagCounts(): Record<string, number> {
|
||||
const data = this.load();
|
||||
const counts: Record<string, number> = {};
|
||||
for (const [tag, ids] of Object.entries(data.tags)) {
|
||||
counts[tag] = ids.length;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
rebuildIndex(learnings: Learning[]): void {
|
||||
// Clear existing index
|
||||
this.data = this.createEmpty();
|
||||
|
||||
// Re-index all learnings
|
||||
for (const learning of learnings) {
|
||||
this.indexLearning(learning);
|
||||
}
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.data = this.createEmpty();
|
||||
this.save();
|
||||
}
|
||||
|
||||
exists(): boolean {
|
||||
return existsSync(this.filePath);
|
||||
}
|
||||
|
||||
getStats(): { keywords: number; tags: number; lastUpdated: string } {
|
||||
const data = this.load();
|
||||
return {
|
||||
keywords: Object.keys(data.entries).length,
|
||||
tags: Object.keys(data.tags).length,
|
||||
lastUpdated: data.lastUpdated,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type {
|
||||
Observation,
|
||||
ObservationContent,
|
||||
ObservationStoreData,
|
||||
ObservationType,
|
||||
} from './types.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
export class ObservationStore {
|
||||
private readonly filePath: string;
|
||||
private data: ObservationStoreData | null = null;
|
||||
private sessionId: string;
|
||||
|
||||
constructor(projectPath: string, sessionId?: string) {
|
||||
this.filePath = join(projectPath, '.skillkit', 'memory', 'observations.yaml');
|
||||
this.sessionId = sessionId || randomUUID();
|
||||
}
|
||||
|
||||
private ensureDir(): void {
|
||||
const dir = dirname(this.filePath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
private load(): ObservationStoreData {
|
||||
if (this.data) return this.data;
|
||||
|
||||
if (existsSync(this.filePath)) {
|
||||
try {
|
||||
const content = readFileSync(this.filePath, 'utf-8');
|
||||
this.data = parseYaml(content) as ObservationStoreData;
|
||||
if (this.data.sessionId !== this.sessionId) {
|
||||
this.data.sessionId = this.sessionId;
|
||||
this.data.observations = [];
|
||||
}
|
||||
} catch {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
} else {
|
||||
this.data = this.createEmpty();
|
||||
}
|
||||
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private createEmpty(): ObservationStoreData {
|
||||
return {
|
||||
version: 1,
|
||||
sessionId: this.sessionId,
|
||||
observations: [],
|
||||
};
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
this.ensureDir();
|
||||
const content = stringifyYaml(this.data, { lineWidth: 0 });
|
||||
writeFileSync(this.filePath, content, 'utf-8');
|
||||
}
|
||||
|
||||
add(
|
||||
type: ObservationType,
|
||||
content: ObservationContent,
|
||||
agent: AgentType,
|
||||
relevance = 50
|
||||
): Observation {
|
||||
const data = this.load();
|
||||
|
||||
const observation: Observation = {
|
||||
id: randomUUID(),
|
||||
timestamp: new Date().toISOString(),
|
||||
sessionId: this.sessionId,
|
||||
agent,
|
||||
type,
|
||||
content,
|
||||
relevance,
|
||||
};
|
||||
|
||||
data.observations.push(observation);
|
||||
this.save();
|
||||
|
||||
return observation;
|
||||
}
|
||||
|
||||
getAll(): Observation[] {
|
||||
return this.load().observations;
|
||||
}
|
||||
|
||||
getByType(type: ObservationType): Observation[] {
|
||||
return this.load().observations.filter((o) => o.type === type);
|
||||
}
|
||||
|
||||
getByRelevance(minRelevance: number): Observation[] {
|
||||
return this.load().observations.filter((o) => o.relevance >= minRelevance);
|
||||
}
|
||||
|
||||
getRecent(count: number): Observation[] {
|
||||
const observations = this.load().observations;
|
||||
return observations.slice(-count);
|
||||
}
|
||||
|
||||
getUncompressed(compressedIds: string[]): Observation[] {
|
||||
const compressedSet = new Set(compressedIds);
|
||||
return this.load().observations.filter((o) => !compressedSet.has(o.id));
|
||||
}
|
||||
|
||||
count(): number {
|
||||
return this.load().observations.length;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.data = this.createEmpty();
|
||||
this.save();
|
||||
}
|
||||
|
||||
getById(id: string): Observation | undefined {
|
||||
return this.load().observations.find((o) => o.id === id);
|
||||
}
|
||||
|
||||
getByIds(ids: string[]): Observation[] {
|
||||
const idSet = new Set(ids);
|
||||
return this.load().observations.filter((o) => idSet.has(o.id));
|
||||
}
|
||||
|
||||
getSessionId(): string {
|
||||
return this.sessionId;
|
||||
}
|
||||
|
||||
setSessionId(sessionId: string): void {
|
||||
this.sessionId = sessionId;
|
||||
if (this.data) {
|
||||
this.data.sessionId = sessionId;
|
||||
}
|
||||
}
|
||||
|
||||
exists(): boolean {
|
||||
return existsSync(this.filePath);
|
||||
}
|
||||
|
||||
delete(id: string): boolean {
|
||||
const data = this.load();
|
||||
const index = data.observations.findIndex((o) => o.id === id);
|
||||
|
||||
if (index === -1) return false;
|
||||
|
||||
data.observations.splice(index, 1);
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
deleteMany(ids: string[]): number {
|
||||
const idSet = new Set(ids);
|
||||
const data = this.load();
|
||||
const initialLength = data.observations.length;
|
||||
|
||||
data.observations = data.observations.filter((o) => !idSet.has(o.id));
|
||||
|
||||
if (data.observations.length !== initialLength) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
return initialLength - data.observations.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,636 @@
|
||||
/**
|
||||
* Memory Observer
|
||||
*
|
||||
* Captures observations during skill execution and stores them in the ObservationStore.
|
||||
* Provides intelligent filtering to capture only significant events.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '../types.js';
|
||||
import type { ExecutionProgressEvent } from '../executor/engine.js';
|
||||
import type { ObservationType, ObservationContent, Observation } from './types.js';
|
||||
import { ObservationStore } from './observation-store.js';
|
||||
|
||||
/**
|
||||
* Event types that can be observed
|
||||
*/
|
||||
export type ObservableEventType =
|
||||
| 'task_start'
|
||||
| 'task_complete'
|
||||
| 'task_failed'
|
||||
| 'checkpoint_reached'
|
||||
| 'checkpoint_decision'
|
||||
| 'verification_passed'
|
||||
| 'verification_failed'
|
||||
| 'file_modified'
|
||||
| 'error_encountered'
|
||||
| 'solution_applied'
|
||||
| 'execution_start'
|
||||
| 'execution_complete'
|
||||
| 'execution_paused';
|
||||
|
||||
/**
|
||||
* Observable event structure
|
||||
*/
|
||||
export interface ObservableEvent {
|
||||
type: ObservableEventType;
|
||||
timestamp: string;
|
||||
skillName?: string;
|
||||
taskId?: string;
|
||||
taskName?: string;
|
||||
taskAction?: string;
|
||||
files?: string[];
|
||||
error?: string;
|
||||
output?: string;
|
||||
decision?: string;
|
||||
context?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Observer configuration
|
||||
*/
|
||||
export interface MemoryObserverConfig {
|
||||
/** Minimum relevance score to store (0-100) */
|
||||
minRelevance?: number;
|
||||
/** Whether to capture task starts */
|
||||
captureTaskStarts?: boolean;
|
||||
/** Whether to capture checkpoints */
|
||||
captureCheckpoints?: boolean;
|
||||
/** Whether to capture file modifications */
|
||||
captureFileModifications?: boolean;
|
||||
/** Whether to capture errors */
|
||||
captureErrors?: boolean;
|
||||
/** Whether to capture solutions */
|
||||
captureSolutions?: boolean;
|
||||
/** Custom relevance scorer */
|
||||
relevanceScorer?: (event: ObservableEvent) => number;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG: Required<Omit<MemoryObserverConfig, 'relevanceScorer'>> = {
|
||||
minRelevance: 30,
|
||||
captureTaskStarts: false, // Task starts are usually low-value
|
||||
captureCheckpoints: true,
|
||||
captureFileModifications: true,
|
||||
captureErrors: true,
|
||||
captureSolutions: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Memory Observer
|
||||
*
|
||||
* Captures and filters observations during skill execution.
|
||||
*/
|
||||
export class MemoryObserver {
|
||||
private store: ObservationStore;
|
||||
private config: Required<Omit<MemoryObserverConfig, 'relevanceScorer'>> & {
|
||||
relevanceScorer?: (event: ObservableEvent) => number;
|
||||
};
|
||||
private currentAgent: AgentType = 'claude-code';
|
||||
private currentSkillName?: string;
|
||||
private pendingErrors: Map<string, ObservableEvent> = new Map();
|
||||
|
||||
constructor(projectPath: string, sessionId?: string, config?: MemoryObserverConfig) {
|
||||
this.store = new ObservationStore(projectPath, sessionId);
|
||||
this.config = { ...DEFAULT_CONFIG, ...config };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current agent being used
|
||||
*/
|
||||
setAgent(agent: AgentType): void {
|
||||
this.currentAgent = agent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current skill being executed
|
||||
*/
|
||||
setSkillName(skillName: string): void {
|
||||
this.currentSkillName = skillName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying observation store
|
||||
*/
|
||||
getStore(): ObservationStore {
|
||||
return this.store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe an event and potentially store it
|
||||
*/
|
||||
observe(event: ObservableEvent): Observation | null {
|
||||
// Check if we should capture this event type
|
||||
if (!this.shouldCapture(event)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Classify the event into an observation type
|
||||
const observationType = this.classifyEvent(event);
|
||||
|
||||
// Extract content from the event
|
||||
const content = this.extractContent(event);
|
||||
|
||||
// Score relevance
|
||||
const relevance = this.scoreRelevance(event);
|
||||
|
||||
// Check minimum relevance threshold
|
||||
if (relevance < this.config.minRelevance) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Store the observation
|
||||
return this.store.add(observationType, content, this.currentAgent, relevance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an observation callback for the SkillExecutionEngine
|
||||
*/
|
||||
createProgressCallback(): (event: ExecutionProgressEvent) => void {
|
||||
return (progressEvent: ExecutionProgressEvent) => {
|
||||
const observableEvent = this.convertProgressEvent(progressEvent);
|
||||
if (observableEvent) {
|
||||
this.observe(observableEvent);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ExecutionProgressEvent to ObservableEvent
|
||||
*/
|
||||
private convertProgressEvent(event: ExecutionProgressEvent): ObservableEvent | null {
|
||||
const baseEvent = {
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
taskId: event.taskId,
|
||||
taskName: event.taskName,
|
||||
};
|
||||
|
||||
switch (event.type) {
|
||||
case 'task_start':
|
||||
return {
|
||||
...baseEvent,
|
||||
type: 'task_start',
|
||||
context: `Starting task ${event.taskIndex !== undefined ? event.taskIndex + 1 : ''} of ${event.totalTasks || '?'}`,
|
||||
};
|
||||
|
||||
case 'task_complete':
|
||||
if (event.status === 'failed') {
|
||||
return {
|
||||
...baseEvent,
|
||||
type: 'task_failed',
|
||||
error: event.error,
|
||||
context: event.message,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...baseEvent,
|
||||
type: 'task_complete',
|
||||
output: event.message,
|
||||
context: `Completed task ${event.taskIndex !== undefined ? event.taskIndex + 1 : ''} of ${event.totalTasks || '?'}`,
|
||||
};
|
||||
|
||||
case 'checkpoint':
|
||||
return {
|
||||
...baseEvent,
|
||||
type: 'checkpoint_reached',
|
||||
context: event.message,
|
||||
};
|
||||
|
||||
case 'verification':
|
||||
const passed = event.message?.includes('passed');
|
||||
return {
|
||||
...baseEvent,
|
||||
type: passed ? 'verification_passed' : 'verification_failed',
|
||||
context: event.message,
|
||||
error: passed ? undefined : event.message,
|
||||
};
|
||||
|
||||
case 'complete':
|
||||
return {
|
||||
...baseEvent,
|
||||
type: 'execution_complete',
|
||||
context: event.message,
|
||||
error: event.status === 'failed' ? event.message : undefined,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a file modification event
|
||||
*/
|
||||
recordFileModification(files: string[], context: string): Observation | null {
|
||||
return this.observe({
|
||||
type: 'file_modified',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
files,
|
||||
context,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record an error event
|
||||
*/
|
||||
recordError(error: string, context: string, taskId?: string): Observation | null {
|
||||
const event: ObservableEvent = {
|
||||
type: 'error_encountered',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
taskId,
|
||||
error,
|
||||
context,
|
||||
};
|
||||
|
||||
// Store pending error for potential solution matching
|
||||
const errorKey = this.generateErrorKey(error);
|
||||
this.pendingErrors.set(errorKey, event);
|
||||
|
||||
return this.observe(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a solution event (potentially matching a previous error)
|
||||
*/
|
||||
recordSolution(solution: string, context: string, relatedError?: string): Observation | null {
|
||||
const event: ObservableEvent = {
|
||||
type: 'solution_applied',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
output: solution,
|
||||
context,
|
||||
error: relatedError,
|
||||
};
|
||||
|
||||
// If we can match this to a pending error, increase relevance
|
||||
if (relatedError) {
|
||||
const errorKey = this.generateErrorKey(relatedError);
|
||||
this.pendingErrors.delete(errorKey);
|
||||
}
|
||||
|
||||
return this.observe(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a decision event
|
||||
*/
|
||||
recordDecision(decision: string, options: string[], context: string): Observation | null {
|
||||
return this.observe({
|
||||
type: 'checkpoint_decision',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
decision,
|
||||
context: `Decision: ${decision} (options: ${options.join(', ')}). Context: ${context}`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record execution start
|
||||
*/
|
||||
recordExecutionStart(skillName: string, agent: AgentType): Observation | null {
|
||||
this.currentSkillName = skillName;
|
||||
this.currentAgent = agent;
|
||||
|
||||
return this.observe({
|
||||
type: 'execution_start',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName,
|
||||
context: `Started execution of skill "${skillName}" with agent "${agent}"`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record execution pause
|
||||
*/
|
||||
recordExecutionPause(reason?: string): Observation | null {
|
||||
return this.observe({
|
||||
type: 'execution_paused',
|
||||
timestamp: new Date().toISOString(),
|
||||
skillName: this.currentSkillName,
|
||||
context: reason || 'Execution paused',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should capture this event type
|
||||
*/
|
||||
private shouldCapture(event: ObservableEvent): boolean {
|
||||
switch (event.type) {
|
||||
case 'task_start':
|
||||
return this.config.captureTaskStarts;
|
||||
case 'checkpoint_reached':
|
||||
case 'checkpoint_decision':
|
||||
return this.config.captureCheckpoints;
|
||||
case 'file_modified':
|
||||
return this.config.captureFileModifications;
|
||||
case 'error_encountered':
|
||||
case 'task_failed':
|
||||
case 'verification_failed':
|
||||
return this.config.captureErrors;
|
||||
case 'solution_applied':
|
||||
return this.config.captureSolutions;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify event into observation type
|
||||
*/
|
||||
private classifyEvent(event: ObservableEvent): ObservationType {
|
||||
switch (event.type) {
|
||||
case 'error_encountered':
|
||||
case 'task_failed':
|
||||
case 'verification_failed':
|
||||
return 'error';
|
||||
|
||||
case 'solution_applied':
|
||||
return 'solution';
|
||||
|
||||
case 'checkpoint_decision':
|
||||
return 'decision';
|
||||
|
||||
case 'file_modified':
|
||||
return 'file_change';
|
||||
|
||||
case 'execution_paused':
|
||||
case 'checkpoint_reached':
|
||||
return 'checkpoint';
|
||||
|
||||
case 'task_start':
|
||||
case 'task_complete':
|
||||
case 'verification_passed':
|
||||
case 'execution_start':
|
||||
case 'execution_complete':
|
||||
default:
|
||||
return 'tool_use';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract content from event
|
||||
*/
|
||||
private extractContent(event: ObservableEvent): ObservationContent {
|
||||
const content: ObservationContent = {
|
||||
action: this.getActionDescription(event),
|
||||
context: event.context || this.generateContext(event),
|
||||
};
|
||||
|
||||
if (event.output) {
|
||||
content.result = event.output;
|
||||
}
|
||||
|
||||
if (event.files && event.files.length > 0) {
|
||||
content.files = event.files;
|
||||
}
|
||||
|
||||
if (event.error) {
|
||||
content.error = event.error;
|
||||
}
|
||||
|
||||
if (event.type === 'solution_applied' && event.output) {
|
||||
content.solution = event.output;
|
||||
}
|
||||
|
||||
// Generate tags based on event
|
||||
content.tags = this.generateTags(event);
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get action description from event
|
||||
*/
|
||||
private getActionDescription(event: ObservableEvent): string {
|
||||
switch (event.type) {
|
||||
case 'task_start':
|
||||
return `Started task: ${event.taskName || 'unknown'}`;
|
||||
case 'task_complete':
|
||||
return `Completed task: ${event.taskName || 'unknown'}`;
|
||||
case 'task_failed':
|
||||
return `Task failed: ${event.taskName || 'unknown'}`;
|
||||
case 'checkpoint_reached':
|
||||
return `Checkpoint: ${event.taskName || 'unknown'}`;
|
||||
case 'checkpoint_decision':
|
||||
return `Decision made: ${event.decision || 'unknown'}`;
|
||||
case 'verification_passed':
|
||||
return `Verification passed: ${event.taskName || 'unknown'}`;
|
||||
case 'verification_failed':
|
||||
return `Verification failed: ${event.taskName || 'unknown'}`;
|
||||
case 'file_modified':
|
||||
return `Modified files: ${event.files?.join(', ') || 'unknown'}`;
|
||||
case 'error_encountered':
|
||||
return `Error: ${event.error?.slice(0, 100) || 'unknown'}`;
|
||||
case 'solution_applied':
|
||||
return `Solution applied: ${event.output?.slice(0, 100) || 'unknown'}`;
|
||||
case 'execution_start':
|
||||
return `Started skill: ${event.skillName || 'unknown'}`;
|
||||
case 'execution_complete':
|
||||
return `Completed skill: ${event.skillName || 'unknown'}`;
|
||||
case 'execution_paused':
|
||||
return `Paused skill: ${event.skillName || 'unknown'}`;
|
||||
default:
|
||||
return 'Unknown action';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate context if not provided
|
||||
*/
|
||||
private generateContext(event: ObservableEvent): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
if (event.skillName) {
|
||||
parts.push(`Skill: ${event.skillName}`);
|
||||
}
|
||||
|
||||
if (event.taskName) {
|
||||
parts.push(`Task: ${event.taskName}`);
|
||||
}
|
||||
|
||||
if (event.taskAction) {
|
||||
parts.push(`Action: ${event.taskAction}`);
|
||||
}
|
||||
|
||||
return parts.join(' | ') || 'No context available';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate tags for event
|
||||
*/
|
||||
private generateTags(event: ObservableEvent): string[] {
|
||||
const tags: string[] = [];
|
||||
|
||||
// Add event type as tag
|
||||
tags.push(event.type.replace(/_/g, '-'));
|
||||
|
||||
// Add skill name if present
|
||||
if (event.skillName) {
|
||||
tags.push(event.skillName.toLowerCase().replace(/[^a-z0-9-]/g, '-'));
|
||||
}
|
||||
|
||||
// Add error-related tags
|
||||
if (event.error) {
|
||||
if (event.error.toLowerCase().includes('type')) tags.push('typescript');
|
||||
if (event.error.toLowerCase().includes('import')) tags.push('imports');
|
||||
if (event.error.toLowerCase().includes('null') || event.error.toLowerCase().includes('undefined'))
|
||||
tags.push('null-check');
|
||||
if (event.error.toLowerCase().includes('async') || event.error.toLowerCase().includes('await'))
|
||||
tags.push('async');
|
||||
}
|
||||
|
||||
// Add file-related tags
|
||||
if (event.files) {
|
||||
for (const file of event.files) {
|
||||
if (file.endsWith('.ts') || file.endsWith('.tsx')) tags.push('typescript');
|
||||
if (file.endsWith('.js') || file.endsWith('.jsx')) tags.push('javascript');
|
||||
if (file.endsWith('.css') || file.endsWith('.scss')) tags.push('styles');
|
||||
if (file.includes('test') || file.includes('spec')) tags.push('testing');
|
||||
if (file.includes('component')) tags.push('components');
|
||||
}
|
||||
}
|
||||
|
||||
return [...new Set(tags)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Score relevance of event
|
||||
*/
|
||||
private scoreRelevance(event: ObservableEvent): number {
|
||||
// Use custom scorer if provided
|
||||
if (this.config.relevanceScorer) {
|
||||
return this.config.relevanceScorer(event);
|
||||
}
|
||||
|
||||
// Default relevance scoring
|
||||
let score = 50; // Base score
|
||||
|
||||
switch (event.type) {
|
||||
// High relevance events
|
||||
case 'error_encountered':
|
||||
case 'task_failed':
|
||||
score = 85;
|
||||
break;
|
||||
|
||||
case 'solution_applied':
|
||||
score = 90;
|
||||
// Bonus if it matches a pending error
|
||||
if (event.error) {
|
||||
const errorKey = this.generateErrorKey(event.error);
|
||||
if (this.pendingErrors.has(errorKey)) {
|
||||
score = 95;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'checkpoint_decision':
|
||||
score = 75;
|
||||
break;
|
||||
|
||||
case 'verification_failed':
|
||||
score = 80;
|
||||
break;
|
||||
|
||||
// Medium relevance events
|
||||
case 'file_modified':
|
||||
score = 60;
|
||||
// More files = higher relevance
|
||||
if (event.files && event.files.length > 3) {
|
||||
score = 70;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'checkpoint_reached':
|
||||
score = 55;
|
||||
break;
|
||||
|
||||
case 'task_complete':
|
||||
case 'verification_passed':
|
||||
score = 50;
|
||||
break;
|
||||
|
||||
// Lower relevance events
|
||||
case 'task_start':
|
||||
score = 30;
|
||||
break;
|
||||
|
||||
case 'execution_start':
|
||||
case 'execution_complete':
|
||||
score = 40;
|
||||
break;
|
||||
|
||||
case 'execution_paused':
|
||||
score = 60;
|
||||
break;
|
||||
|
||||
default:
|
||||
score = 50;
|
||||
}
|
||||
|
||||
// Adjust based on content richness
|
||||
if (event.context && event.context.length > 100) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
if (event.files && event.files.length > 0) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
// Cap at 100
|
||||
return Math.min(score, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a key for matching errors to solutions
|
||||
*/
|
||||
private generateErrorKey(error: string): string {
|
||||
// Normalize error string for matching
|
||||
return error
|
||||
.toLowerCase()
|
||||
.replace(/[0-9]+/g, 'N') // Replace numbers
|
||||
.replace(/['"`]/g, '') // Remove quotes
|
||||
.replace(/\s+/g, ' ') // Normalize whitespace
|
||||
.slice(0, 100); // Limit length
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session ID
|
||||
*/
|
||||
getSessionId(): string {
|
||||
return this.store.getSessionId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all observations
|
||||
*/
|
||||
getObservations(): Observation[] {
|
||||
return this.store.getAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get observation count
|
||||
*/
|
||||
getObservationCount(): number {
|
||||
return this.store.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all observations
|
||||
*/
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
this.pendingErrors.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a MemoryObserver instance
|
||||
*/
|
||||
export function createMemoryObserver(
|
||||
projectPath: string,
|
||||
sessionId?: string,
|
||||
config?: MemoryObserverConfig
|
||||
): MemoryObserver {
|
||||
return new MemoryObserver(projectPath, sessionId, config);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
export type ObservationType =
|
||||
| 'tool_use'
|
||||
| 'decision'
|
||||
| 'error'
|
||||
| 'solution'
|
||||
| 'pattern'
|
||||
| 'file_change'
|
||||
| 'checkpoint';
|
||||
|
||||
export interface ObservationContent {
|
||||
action: string;
|
||||
context: string;
|
||||
result?: string;
|
||||
files?: string[];
|
||||
tags?: string[];
|
||||
error?: string;
|
||||
solution?: string;
|
||||
}
|
||||
|
||||
export interface Observation {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
sessionId: string;
|
||||
agent: AgentType;
|
||||
type: ObservationType;
|
||||
content: ObservationContent;
|
||||
relevance: number;
|
||||
}
|
||||
|
||||
export interface Learning {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
source: 'session' | 'manual' | 'imported';
|
||||
sourceObservations?: string[];
|
||||
|
||||
title: string;
|
||||
content: string;
|
||||
|
||||
scope: 'project' | 'global';
|
||||
project?: string;
|
||||
|
||||
tags: string[];
|
||||
frameworks?: string[];
|
||||
patterns?: string[];
|
||||
|
||||
useCount: number;
|
||||
lastUsed?: string;
|
||||
effectiveness?: number;
|
||||
}
|
||||
|
||||
export interface MemoryIndex {
|
||||
version: 1;
|
||||
lastUpdated: string;
|
||||
entries: Record<string, string[]>;
|
||||
tags: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export interface MemorySummary {
|
||||
id: string;
|
||||
title: string;
|
||||
tags: string[];
|
||||
relevance: number;
|
||||
}
|
||||
|
||||
export interface MemoryPreview extends MemorySummary {
|
||||
excerpt: string;
|
||||
lastUsed?: string;
|
||||
}
|
||||
|
||||
export interface MemoryFull extends MemoryPreview {
|
||||
content: string;
|
||||
sourceObservations?: Observation[];
|
||||
}
|
||||
|
||||
export interface ObservationStoreData {
|
||||
version: 1;
|
||||
sessionId: string;
|
||||
observations: Observation[];
|
||||
}
|
||||
|
||||
export interface LearningStoreData {
|
||||
version: 1;
|
||||
learnings: Learning[];
|
||||
}
|
||||
|
||||
export interface MemoryConfig {
|
||||
autoCompress: boolean;
|
||||
compressionThreshold: number;
|
||||
compressionModel?: string;
|
||||
maxObservations: number;
|
||||
maxLearnings: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_MEMORY_CONFIG: MemoryConfig = {
|
||||
autoCompress: true,
|
||||
compressionThreshold: 50,
|
||||
maxObservations: 1000,
|
||||
maxLearnings: 500,
|
||||
};
|
||||
|
||||
export interface MemorySearchOptions {
|
||||
query?: string;
|
||||
tags?: string[];
|
||||
scope?: 'project' | 'global' | 'all';
|
||||
limit?: number;
|
||||
minRelevance?: number;
|
||||
}
|
||||
|
||||
export interface MemorySearchResult {
|
||||
learning: Learning;
|
||||
score: number;
|
||||
matchedKeywords: string[];
|
||||
matchedTags: string[];
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { MethodologyLoader, createMethodologyLoader } from '../loader.js';
|
||||
|
||||
describe('MethodologyLoader', () => {
|
||||
let testDir: string;
|
||||
let packsDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create temporary directory for tests
|
||||
testDir = join(tmpdir(), `skillkit-test-${Date.now()}`);
|
||||
packsDir = join(testDir, 'packs');
|
||||
mkdirSync(packsDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up
|
||||
if (existsSync(testDir)) {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function createTestPack(name: string, skills: string[]): void {
|
||||
const packDir = join(packsDir, name);
|
||||
mkdirSync(packDir, { recursive: true });
|
||||
|
||||
// Create pack.json
|
||||
const manifest = {
|
||||
name,
|
||||
version: '1.0.0',
|
||||
description: `Test ${name} pack`,
|
||||
skills,
|
||||
tags: [name],
|
||||
compatibility: ['all'],
|
||||
};
|
||||
writeFileSync(join(packDir, 'pack.json'), JSON.stringify(manifest, null, 2));
|
||||
|
||||
// Create skill directories and SKILL.md files
|
||||
for (const skill of skills) {
|
||||
const skillDir = join(packDir, skill);
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
|
||||
const skillContent = `---
|
||||
name: ${skill}
|
||||
description: Test skill ${skill}
|
||||
version: 1.0.0
|
||||
triggers:
|
||||
- ${skill}
|
||||
tags:
|
||||
- test
|
||||
---
|
||||
|
||||
# ${skill}
|
||||
|
||||
This is a test skill. You must follow these instructions.
|
||||
|
||||
## Instructions
|
||||
|
||||
Do the thing.
|
||||
`;
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), skillContent);
|
||||
}
|
||||
}
|
||||
|
||||
describe('loadAllPacks', () => {
|
||||
it('should load all available packs', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
createTestPack('debugging', ['skill3']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const packs = await loader.loadAllPacks();
|
||||
|
||||
expect(packs).toHaveLength(2);
|
||||
expect(packs.map(p => p.name).sort()).toEqual(['debugging', 'testing']);
|
||||
});
|
||||
|
||||
it('should return empty array when no packs exist', async () => {
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const packs = await loader.loadAllPacks();
|
||||
|
||||
expect(packs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadPack', () => {
|
||||
it('should load a specific pack by name', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const pack = await loader.loadPack('testing');
|
||||
|
||||
expect(pack).not.toBeNull();
|
||||
expect(pack?.name).toBe('testing');
|
||||
expect(pack?.skills).toEqual(['skill1', 'skill2']);
|
||||
});
|
||||
|
||||
it('should return null for non-existent pack', async () => {
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const pack = await loader.loadPack('nonexistent');
|
||||
|
||||
expect(pack).toBeNull();
|
||||
});
|
||||
|
||||
it('should cache loaded packs', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
|
||||
const pack1 = await loader.loadPack('testing');
|
||||
const pack2 = await loader.loadPack('testing');
|
||||
|
||||
expect(pack1).toBe(pack2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadPackSkills', () => {
|
||||
it('should load all skills from a pack', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skills = await loader.loadPackSkills('testing');
|
||||
|
||||
expect(skills).toHaveLength(2);
|
||||
expect(skills.map(s => s.id).sort()).toEqual(['testing/skill1', 'testing/skill2']);
|
||||
});
|
||||
|
||||
it('should throw error for non-existent pack', async () => {
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
|
||||
await expect(loader.loadPackSkills('nonexistent')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadSkill', () => {
|
||||
it('should load a specific skill', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skill = await loader.loadSkill('testing', 'skill1');
|
||||
|
||||
expect(skill).not.toBeNull();
|
||||
expect(skill?.id).toBe('testing/skill1');
|
||||
expect(skill?.name).toBe('skill1');
|
||||
expect(skill?.pack).toBe('testing');
|
||||
});
|
||||
|
||||
it('should return null for non-existent skill', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skill = await loader.loadSkill('testing', 'nonexistent');
|
||||
|
||||
expect(skill).toBeNull();
|
||||
});
|
||||
|
||||
it('should extract metadata from skill content', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skill = await loader.loadSkill('testing', 'skill1');
|
||||
|
||||
expect(skill?.metadata.triggers).toEqual(['skill1']);
|
||||
expect(skill?.tags).toEqual(['test']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSkillById', () => {
|
||||
it('should get skill by full ID', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skill = await loader.getSkillById('testing/skill1');
|
||||
|
||||
expect(skill).not.toBeNull();
|
||||
expect(skill?.id).toBe('testing/skill1');
|
||||
});
|
||||
|
||||
it('should return null for invalid ID format', async () => {
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skill = await loader.getSkillById('invalid');
|
||||
|
||||
expect(skill).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchSkills', () => {
|
||||
it('should search skills by name', async () => {
|
||||
createTestPack('testing', ['tdd-skill', 'debug-skill']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skills = await loader.searchSkills('tdd');
|
||||
|
||||
expect(skills).toHaveLength(1);
|
||||
expect(skills[0].id).toBe('testing/tdd-skill');
|
||||
});
|
||||
|
||||
it('should search skills by tag', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skills = await loader.searchSkills('test');
|
||||
|
||||
expect(skills).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should return all skills when query is empty', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
const skills = await loader.searchSkills('');
|
||||
|
||||
expect(skills).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('packExists', () => {
|
||||
it('should return true for existing pack', () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
expect(loader.packExists('testing')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-existent pack', () => {
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
expect(loader.packExists('nonexistent')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearCache', () => {
|
||||
it('should clear cached packs and skills', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const loader = new MethodologyLoader(packsDir);
|
||||
|
||||
// Load to populate cache
|
||||
await loader.loadPack('testing');
|
||||
await loader.loadSkill('testing', 'skill1');
|
||||
|
||||
// Clear cache
|
||||
loader.clearCache();
|
||||
|
||||
// Modify pack on disk
|
||||
const packDir = join(packsDir, 'testing');
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: '2.0.0',
|
||||
description: 'Updated pack',
|
||||
skills: ['skill1'],
|
||||
tags: ['testing'],
|
||||
compatibility: ['all'],
|
||||
};
|
||||
writeFileSync(join(packDir, 'pack.json'), JSON.stringify(manifest, null, 2));
|
||||
|
||||
// Reload should get new version
|
||||
const pack = await loader.loadPack('testing');
|
||||
expect(pack?.version).toBe('2.0.0');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMethodologyLoader', () => {
|
||||
it('should create a loader instance', () => {
|
||||
const loader = createMethodologyLoader();
|
||||
expect(loader).toBeInstanceOf(MethodologyLoader);
|
||||
});
|
||||
|
||||
it('should accept custom packs directory', () => {
|
||||
const customDir = '/custom/packs';
|
||||
const loader = createMethodologyLoader(customDir);
|
||||
expect(loader.getPacksDir()).toBe(customDir);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { MethodologyManager, createMethodologyManager } from '../manager.js';
|
||||
|
||||
describe('MethodologyManager', () => {
|
||||
let testDir: string;
|
||||
let packsDir: string;
|
||||
let projectPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create temporary directories for tests
|
||||
testDir = join(tmpdir(), `skillkit-manager-test-${Date.now()}`);
|
||||
packsDir = join(testDir, 'packs');
|
||||
projectPath = join(testDir, 'project');
|
||||
mkdirSync(packsDir, { recursive: true });
|
||||
mkdirSync(projectPath, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up
|
||||
if (existsSync(testDir)) {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function createTestPack(name: string, skills: string[]): void {
|
||||
const packDir = join(packsDir, name);
|
||||
mkdirSync(packDir, { recursive: true });
|
||||
|
||||
// Create pack.json
|
||||
const manifest = {
|
||||
name,
|
||||
version: '1.0.0',
|
||||
description: `Test ${name} pack`,
|
||||
skills,
|
||||
tags: [name],
|
||||
compatibility: ['all'],
|
||||
};
|
||||
writeFileSync(join(packDir, 'pack.json'), JSON.stringify(manifest, null, 2));
|
||||
|
||||
// Create skill directories and SKILL.md files
|
||||
for (const skill of skills) {
|
||||
const skillDir = join(packDir, skill);
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
|
||||
const skillContent = `---
|
||||
name: ${skill}
|
||||
description: Test skill ${skill}
|
||||
version: 1.0.0
|
||||
triggers:
|
||||
- ${skill}
|
||||
tags:
|
||||
- test
|
||||
---
|
||||
|
||||
# ${skill}
|
||||
|
||||
This is a test skill. You must follow these instructions.
|
||||
|
||||
## Instructions
|
||||
|
||||
Do the thing.
|
||||
`;
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), skillContent);
|
||||
}
|
||||
}
|
||||
|
||||
describe('installPack', () => {
|
||||
it('should install a pack and its skills', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.installPack('testing');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.installed).toHaveLength(2);
|
||||
expect(result.installed).toContain('testing/skill1');
|
||||
expect(result.installed).toContain('testing/skill2');
|
||||
});
|
||||
|
||||
it('should skip already installed packs', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
// Install first time
|
||||
await manager.installPack('testing');
|
||||
|
||||
// Install again
|
||||
const result = await manager.installPack('testing');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.skipped).toContain('testing');
|
||||
});
|
||||
|
||||
it('should fail for non-existent pack', async () => {
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.installPack('nonexistent');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.failed).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('installAllPacks', () => {
|
||||
it('should install all available packs', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
createTestPack('debugging', ['skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.installAllPacks();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.installed).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('installSkill', () => {
|
||||
it('should install a single skill', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.installSkill('testing/skill1');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.installed).toContain('testing/skill1');
|
||||
});
|
||||
|
||||
it('should fail for non-existent skill', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.installSkill('testing/nonexistent');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uninstallPack', () => {
|
||||
it('should uninstall a pack', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
await manager.installPack('testing');
|
||||
await manager.uninstallPack('testing');
|
||||
|
||||
const installed = manager.listInstalledPacks();
|
||||
expect(installed).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should throw for non-installed pack', async () => {
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
await expect(manager.uninstallPack('testing')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listInstalledPacks', () => {
|
||||
it('should list installed packs', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
await manager.installPack('testing');
|
||||
|
||||
const installed = manager.listInstalledPacks();
|
||||
|
||||
expect(installed).toHaveLength(1);
|
||||
expect(installed[0].name).toBe('testing');
|
||||
expect(installed[0].skills).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should return empty array when nothing installed', () => {
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const installed = manager.listInstalledPacks();
|
||||
expect(installed).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listInstalledSkills', () => {
|
||||
it('should list installed skills', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
await manager.installPack('testing');
|
||||
|
||||
const installed = manager.listInstalledSkills();
|
||||
|
||||
expect(installed).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listAvailablePacks', () => {
|
||||
it('should list packs not yet installed', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
createTestPack('debugging', ['skill2']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
await manager.installPack('testing');
|
||||
|
||||
const available = await manager.listAvailablePacks();
|
||||
|
||||
expect(available).toHaveLength(1);
|
||||
expect(available[0].name).toBe('debugging');
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
it('should search by query string', async () => {
|
||||
createTestPack('testing', ['tdd-skill']);
|
||||
createTestPack('debugging', ['debug-skill']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.search({ query: 'tdd' });
|
||||
|
||||
expect(result.skills).toHaveLength(1);
|
||||
expect(result.skills[0].id).toBe('testing/tdd-skill');
|
||||
});
|
||||
|
||||
it('should search by tags', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.search({ tags: ['test'] });
|
||||
|
||||
expect(result.skills).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should search by pack', async () => {
|
||||
createTestPack('testing', ['skill1', 'skill2']);
|
||||
createTestPack('debugging', ['skill3']);
|
||||
|
||||
const manager = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
|
||||
const result = await manager.search({ pack: 'testing' });
|
||||
|
||||
expect(result.skills).toHaveLength(2);
|
||||
expect(result.packs).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('state persistence', () => {
|
||||
it('should persist installed packs across instances', async () => {
|
||||
createTestPack('testing', ['skill1']);
|
||||
|
||||
// Install with first instance
|
||||
const manager1 = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
await manager1.installPack('testing');
|
||||
|
||||
// Check with second instance
|
||||
const manager2 = createMethodologyManager({
|
||||
projectPath,
|
||||
packsDir,
|
||||
autoSync: false,
|
||||
});
|
||||
const installed = manager2.listInstalledPacks();
|
||||
|
||||
expect(installed).toHaveLength(1);
|
||||
expect(installed[0].name).toBe('testing');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMethodologyManager', () => {
|
||||
it('should create a manager instance', () => {
|
||||
const testDir = join(tmpdir(), `skillkit-test-create-${Date.now()}`);
|
||||
mkdirSync(testDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const manager = createMethodologyManager({ projectPath: testDir });
|
||||
expect(manager).toBeInstanceOf(MethodologyManager);
|
||||
} finally {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
validatePackManifest,
|
||||
validateSkillContent,
|
||||
extractSkillMetadata,
|
||||
} from '../validator.js';
|
||||
|
||||
describe('validatePackManifest', () => {
|
||||
it('should validate a valid pack manifest', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: '1.0.0',
|
||||
description: 'Test-driven development methodology pack',
|
||||
skills: ['red-green-refactor', 'test-patterns'],
|
||||
tags: ['tdd', 'testing'],
|
||||
compatibility: ['all'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should reject manifest with missing name', () => {
|
||||
const manifest = {
|
||||
version: '1.0.0',
|
||||
description: 'Test pack',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'MISSING_NAME')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject manifest with invalid name format', () => {
|
||||
const manifest = {
|
||||
name: 'Invalid Name',
|
||||
version: '1.0.0',
|
||||
description: 'Test pack',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'INVALID_NAME')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject manifest with missing version', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
description: 'Test pack',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'MISSING_VERSION')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject manifest with invalid version format', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: 'v1',
|
||||
description: 'Test pack',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'INVALID_VERSION')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject manifest with empty skills array', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: '1.0.0',
|
||||
description: 'Test pack',
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'EMPTY_SKILLS')).toBe(true);
|
||||
});
|
||||
|
||||
it('should warn about short description', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: '1.0.0',
|
||||
description: 'Short',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.warnings.some(w => w.code === 'SHORT_DESCRIPTION')).toBe(true);
|
||||
});
|
||||
|
||||
it('should warn about missing tags', () => {
|
||||
const manifest = {
|
||||
name: 'testing',
|
||||
version: '1.0.0',
|
||||
description: 'A longer description for the pack',
|
||||
skills: ['skill1'],
|
||||
};
|
||||
|
||||
const result = validatePackManifest(manifest);
|
||||
expect(result.warnings.some(w => w.code === 'MISSING_TAGS')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateSkillContent', () => {
|
||||
it('should validate valid skill content', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
description: A test skill
|
||||
version: 1.0.0
|
||||
triggers:
|
||||
- test
|
||||
---
|
||||
|
||||
# Test Skill
|
||||
|
||||
## Description
|
||||
|
||||
This skill helps with testing. You should always write tests first.
|
||||
|
||||
## Instructions
|
||||
|
||||
1. Write a failing test
|
||||
2. Make it pass
|
||||
3. Refactor
|
||||
`;
|
||||
|
||||
const result = validateSkillContent(content);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should reject empty content', () => {
|
||||
const result = validateSkillContent('');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'EMPTY_CONTENT')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject unclosed frontmatter', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
description: A test skill
|
||||
|
||||
# Missing closing frontmatter
|
||||
`;
|
||||
|
||||
const result = validateSkillContent(content);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some(e => e.code === 'UNCLOSED_FRONTMATTER')).toBe(true);
|
||||
});
|
||||
|
||||
it('should warn about missing frontmatter', () => {
|
||||
const content = `# Test Skill
|
||||
|
||||
This is a skill without frontmatter. You should always follow these instructions.
|
||||
`;
|
||||
|
||||
const result = validateSkillContent(content);
|
||||
expect(result.valid).toBe(true); // Still valid, just a warning
|
||||
expect(result.warnings.some(w => w.code === 'NO_FRONTMATTER')).toBe(true);
|
||||
});
|
||||
|
||||
it('should warn about missing structure', () => {
|
||||
const content = `---
|
||||
name: Test
|
||||
---
|
||||
|
||||
Just some random text without proper sections. You must follow this.
|
||||
`;
|
||||
|
||||
const result = validateSkillContent(content);
|
||||
expect(result.warnings.some(w => w.code === 'MISSING_STRUCTURE')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractSkillMetadata', () => {
|
||||
it('should extract simple key-value pairs', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
version: 1.0.0
|
||||
difficulty: intermediate
|
||||
---
|
||||
|
||||
# Content
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata.name).toBe('Test Skill');
|
||||
expect(metadata.version).toBe('1.0.0');
|
||||
expect(metadata.difficulty).toBe('intermediate');
|
||||
});
|
||||
|
||||
it('should extract array values', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
triggers:
|
||||
- tdd
|
||||
- test driven
|
||||
- write tests
|
||||
tags:
|
||||
- testing
|
||||
- quality
|
||||
---
|
||||
|
||||
# Content
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata.triggers).toEqual(['tdd', 'test driven', 'write tests']);
|
||||
expect(metadata.tags).toEqual(['testing', 'quality']);
|
||||
});
|
||||
|
||||
it('should extract inline arrays', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
tags: [testing, quality]
|
||||
---
|
||||
|
||||
# Content
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata.tags).toEqual(['testing', 'quality']);
|
||||
});
|
||||
|
||||
it('should extract numeric values', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
estimatedTime: 15
|
||||
---
|
||||
|
||||
# Content
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata.estimatedTime).toBe(15);
|
||||
});
|
||||
|
||||
it('should extract boolean values', () => {
|
||||
const content = `---
|
||||
name: Test Skill
|
||||
deprecated: true
|
||||
active: false
|
||||
---
|
||||
|
||||
# Content
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata.deprecated).toBe(true);
|
||||
expect(metadata.active).toBe(false);
|
||||
});
|
||||
|
||||
it('should return empty object for content without frontmatter', () => {
|
||||
const content = `# Test Skill
|
||||
|
||||
No frontmatter here.
|
||||
`;
|
||||
|
||||
const metadata = extractSkillMetadata(content);
|
||||
expect(metadata).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Methodology Framework
|
||||
*
|
||||
* Provides a composable, community-driven methodology system for AI coding agents.
|
||||
* Supports multiple approaches (TDD, BDD, DDD, or custom methodologies) through
|
||||
* installable "packs" of related skills.
|
||||
*
|
||||
* Key features:
|
||||
* - Methodology packs: Collections of related skills (testing, debugging, planning)
|
||||
* - Universal translation: Skills work across all 17 supported agents
|
||||
* - Pack management: Install, uninstall, and sync methodology skills
|
||||
* - Community-driven: Open for custom methodology contributions
|
||||
*/
|
||||
|
||||
// Manager
|
||||
export { MethodologyManager, createMethodologyManager } from './manager.js';
|
||||
|
||||
// Loader
|
||||
export {
|
||||
MethodologyLoader,
|
||||
createMethodologyLoader,
|
||||
getBuiltinPacksDir,
|
||||
} from './loader.js';
|
||||
|
||||
// Validator
|
||||
export {
|
||||
validatePackManifest,
|
||||
validateSkillContent,
|
||||
validatePackDirectory,
|
||||
validateBuiltinPacks,
|
||||
extractSkillMetadata,
|
||||
} from './validator.js';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
MethodologyPack,
|
||||
MethodologySkill,
|
||||
MethodologySkillMetadata,
|
||||
MethodologyState,
|
||||
MethodologyManagerOptions,
|
||||
InstallResult,
|
||||
MethodologySyncResult,
|
||||
ValidationResult,
|
||||
ValidationError,
|
||||
ValidationWarning,
|
||||
MethodologySearchQuery,
|
||||
MethodologySearchResult,
|
||||
InstalledPackInfo,
|
||||
InstalledSkillInfo,
|
||||
} from './types.js';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user