mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-19 02:13:58 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
64b802a1e6 | ||
|
|
b008a46b8d | ||
|
|
ed90080786 | ||
|
|
b701bb5f47 | ||
|
|
1c4c9a794f | ||
|
|
cb37ebeca7 | ||
|
|
7053d1a2b2 | ||
|
|
1ea5ddd4c7 | ||
|
|
720532c020 | ||
|
|
bc12775e0e |
@@ -125,10 +125,14 @@ skillkit
|
||||
- **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
|
||||
- **Session Memory**: Cross-agent learning system that captures and shares knowledge
|
||||
- **Skill Marketplace**: Browse and install skills from curated GitHub repositories
|
||||
- **Skill Testing**: Test framework for validating skills with assertions
|
||||
- **Workflow Orchestration**: Compose skills into multi-step workflows
|
||||
- **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`)
|
||||
- **CI/CD Integration**: GitHub Actions, GitLab CI, CircleCI templates
|
||||
- **Zero Config**: Auto-detects your agent and configures appropriately
|
||||
|
||||
## Installation
|
||||
@@ -365,6 +369,74 @@ skillkit validate ./my-skill # Validate single skill
|
||||
skillkit validate ./skills --all # Validate all skills in directory
|
||||
```
|
||||
|
||||
### `skillkit marketplace`
|
||||
|
||||
Browse and install skills from the curated marketplace.
|
||||
|
||||
```bash
|
||||
skillkit marketplace # Browse all skills
|
||||
skillkit marketplace search typescript # Search for skills
|
||||
skillkit marketplace refresh # Refresh skill index
|
||||
skillkit marketplace tags # Show popular tags
|
||||
skillkit marketplace sources # List skill sources
|
||||
skillkit marketplace --limit 20 # Limit results
|
||||
skillkit marketplace --tags react,next # Filter by tags
|
||||
```
|
||||
|
||||
### `skillkit memory`
|
||||
|
||||
Manage session memory - learnings captured across AI coding sessions.
|
||||
|
||||
```bash
|
||||
skillkit memory status # Show memory status
|
||||
skillkit memory search "auth" # Search memories
|
||||
skillkit memory list # List all learnings
|
||||
skillkit memory show <id> # Show specific learning
|
||||
skillkit memory compress # Compress observations into learnings
|
||||
skillkit memory export <id> # Export learning as a skill
|
||||
skillkit memory import ./file.yaml # Import memories
|
||||
skillkit memory add --title "..." # Add manual learning
|
||||
skillkit memory rate <id> 85 # Rate effectiveness (0-100)
|
||||
skillkit memory --global # Use global memory scope
|
||||
```
|
||||
|
||||
### `skillkit test`
|
||||
|
||||
Test skills with the built-in testing framework.
|
||||
|
||||
```bash
|
||||
skillkit test # Run all skill tests
|
||||
skillkit test ./my-skill # Test specific skill
|
||||
skillkit test --tags unit # Run tests with specific tags
|
||||
skillkit test --json # Output results as JSON
|
||||
skillkit test --verbose # Verbose output
|
||||
```
|
||||
|
||||
### `skillkit workflow`
|
||||
|
||||
Manage and run skill workflows (multi-step skill compositions).
|
||||
|
||||
```bash
|
||||
skillkit workflow list # List available workflows
|
||||
skillkit workflow run <name> # Run a workflow
|
||||
skillkit workflow create <name> # Create new workflow
|
||||
skillkit workflow validate <name> # Validate workflow definition
|
||||
skillkit workflow --verbose # Verbose output
|
||||
```
|
||||
|
||||
### `skillkit cicd`
|
||||
|
||||
Generate CI/CD integration templates.
|
||||
|
||||
```bash
|
||||
skillkit cicd github-action # Generate GitHub Actions workflow
|
||||
skillkit cicd pre-commit # Generate pre-commit hook
|
||||
skillkit cicd gitlab-ci # Generate GitLab CI config
|
||||
skillkit cicd circleci # Generate CircleCI config
|
||||
skillkit cicd --list # List available templates
|
||||
skillkit cicd --output ./path # Output to specific path
|
||||
```
|
||||
|
||||
### `skillkit create <skill-name>`
|
||||
|
||||
Create a new skill with proper structure and template.
|
||||
@@ -481,6 +553,21 @@ import {
|
||||
ContextManager,
|
||||
initContext,
|
||||
syncToAllAgents,
|
||||
// Marketplace
|
||||
createMarketplaceAggregator,
|
||||
// Session Memory
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
LearningStore,
|
||||
ObservationStore,
|
||||
// Testing
|
||||
SkillTestRunner,
|
||||
// Workflows
|
||||
WorkflowOrchestrator,
|
||||
parseWorkflow,
|
||||
// CI/CD
|
||||
getCICDTemplate,
|
||||
listCICDTemplates,
|
||||
} from 'skillkit';
|
||||
|
||||
// Find all installed skills
|
||||
@@ -506,6 +593,23 @@ console.log(result.content); // Cursor MDC format
|
||||
const ctx = new ContextManager('./my-project');
|
||||
await ctx.init();
|
||||
await syncToAllAgents(ctx.getContext());
|
||||
|
||||
// Browse marketplace
|
||||
const marketplace = createMarketplaceAggregator();
|
||||
const results = await marketplace.search({ query: 'react' });
|
||||
|
||||
// Session memory
|
||||
const injector = createMemoryInjector('./my-project');
|
||||
const memories = injector.search('authentication patterns');
|
||||
|
||||
// Run skill tests
|
||||
const runner = new SkillTestRunner('./my-project');
|
||||
const testResults = await runner.runAll();
|
||||
|
||||
// Run workflows
|
||||
const workflow = parseWorkflow('./workflow.yaml');
|
||||
const orchestrator = new WorkflowOrchestrator(workflow);
|
||||
await orchestrator.execute();
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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 a skill
|
||||
skillkit install github.com/anthropics/courses:prompt-eng/interactive-tutorial
|
||||
|
||||
# List installed skills
|
||||
skillkit list
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **17+ Agent Support**: Claude Code, Cursor, Codex, Gemini CLI, Windsurf, GitHub Copilot, and more
|
||||
- **Universal Skill Translation**: Convert skills between different agent formats
|
||||
- **Smart Recommendations**: Get skill suggestions based on your project stack
|
||||
- **Project Context Sync**: One config, all agents
|
||||
- **Interactive TUI**: Browse, install, and manage skills visually
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.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,16 @@ import {
|
||||
TranslateCommand,
|
||||
ContextCommand,
|
||||
RecommendCommand,
|
||||
StatusCommand,
|
||||
PauseCommand,
|
||||
ResumeCommand,
|
||||
WorkflowRunCommand,
|
||||
WorkflowListCommand,
|
||||
WorkflowCreateCommand,
|
||||
RunCommand,
|
||||
TestCommand,
|
||||
MarketplaceCommand,
|
||||
MemoryCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
@@ -51,5 +61,15 @@ 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.runExit(process.argv.slice(2));
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "skillkit-monorepo",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"private": true,
|
||||
"description": "Universal skills loader for AI coding agents - Monorepo",
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# @skillkit/agents
|
||||
|
||||
Agent adapters for SkillKit - supports 17+ AI coding agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/agents
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
| Agent | Config Format | Skills Directory |
|
||||
|-------|--------------|------------------|
|
||||
| Claude Code | SKILL.md | `.claude/skills/` |
|
||||
| Cursor | .cursorrules, .mdc | `.cursor/skills/` |
|
||||
| Codex | SKILL.md | `.codex/skills/` |
|
||||
| Gemini CLI | SKILL.md | `.gemini/skills/` |
|
||||
| Windsurf | .windsurfrules | `.windsurf/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/copilot-instructions.md` |
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.amp/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` |
|
||||
| Kilo | SKILL.md | `.kilocode/skills/` |
|
||||
| Roo | SKILL.md | `.roo/skills/` |
|
||||
| Trae | SKILL.md | `.trae/skills/` |
|
||||
| And more... | | |
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import { getAdapter, detectAgent, listAdapters } from '@skillkit/agents';
|
||||
|
||||
// Get adapter for specific agent
|
||||
const adapter = getAdapter('claude-code');
|
||||
console.log(adapter.skillsDir); // .claude/skills/
|
||||
|
||||
// Detect installed agents
|
||||
const detected = detectAgent();
|
||||
console.log(detected); // ['claude-code', 'cursor']
|
||||
|
||||
// List all available adapters
|
||||
const adapters = listAdapters();
|
||||
```
|
||||
|
||||
## 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.4.0",
|
||||
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# @skillkit/cli
|
||||
|
||||
CLI commands for SkillKit - install, manage, and sync skills across AI agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/cli
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
skillkit init # Initialize skillkit in project
|
||||
skillkit install <skill> # Install a skill
|
||||
skillkit remove <skill> # Remove a skill
|
||||
skillkit list # List installed skills
|
||||
skillkit update # Update installed skills
|
||||
skillkit sync # Sync skills across agents
|
||||
skillkit translate # Translate skills between formats
|
||||
skillkit recommend # Get skill recommendations
|
||||
skillkit context # Manage project context
|
||||
skillkit ui # Launch interactive TUI
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import { installCommand, listCommand, syncCommand } from '@skillkit/cli';
|
||||
|
||||
// Programmatic access to CLI commands
|
||||
await installCommand('github.com/owner/repo:skill-name');
|
||||
await listCommand();
|
||||
await syncCommand({ all: true });
|
||||
```
|
||||
|
||||
## 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.4.0",
|
||||
"description": "CLI commands for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -26,7 +26,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",
|
||||
|
||||
@@ -13,3 +13,11 @@ 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';
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,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,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,204 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
loadWorkflowByName,
|
||||
loadWorkflow,
|
||||
validateWorkflow,
|
||||
createWorkflowOrchestrator,
|
||||
} 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)',
|
||||
});
|
||||
|
||||
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 orchestrator with mock executor (for now)
|
||||
const orchestrator = createWorkflowOrchestrator(
|
||||
async (_skillName, _config) => {
|
||||
// TODO: Integrate with actual skill execution
|
||||
// For now, simulate execution
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return { success: true };
|
||||
},
|
||||
(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,47 @@
|
||||
# @skillkit/core
|
||||
|
||||
Core functionality for SkillKit - skill discovery, parsing, translation, and context management.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/core
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Skill Discovery**: Find and parse SKILL.md files
|
||||
- **Skill Translation**: Convert between agent formats (Claude Code, Cursor, Windsurf, etc.)
|
||||
- **Project Context Detection**: Analyze project stack and dependencies
|
||||
- **Recommendation Engine**: Smart skill suggestions based on project profile
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import {
|
||||
loadConfig,
|
||||
getSearchDirs,
|
||||
translateSkill,
|
||||
ProjectDetector,
|
||||
RecommendationEngine
|
||||
} from '@skillkit/core';
|
||||
|
||||
// Load skillkit config
|
||||
const config = loadConfig();
|
||||
|
||||
// Detect project context
|
||||
const detector = new ProjectDetector();
|
||||
const profile = await detector.analyze('./my-project');
|
||||
|
||||
// Get skill recommendations
|
||||
const engine = new RecommendationEngine();
|
||||
const recommendations = await engine.recommend(profile);
|
||||
```
|
||||
|
||||
## 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.4.0",
|
||||
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -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' },
|
||||
];
|
||||
}
|
||||
@@ -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,26 @@
|
||||
/**
|
||||
* 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';
|
||||
@@ -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>;
|
||||
@@ -18,3 +18,24 @@ 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';
|
||||
|
||||
@@ -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,274 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, rmSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir, homedir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { SkillIndex, SkillSummary, IndexSource } from './types.js';
|
||||
import { discoverSkills, extractFrontmatter } from '../skills.js';
|
||||
|
||||
/**
|
||||
* Known skill repositories to index
|
||||
*/
|
||||
export const KNOWN_SKILL_REPOS = [
|
||||
{ owner: 'anthropics', repo: 'courses', description: 'Anthropic official courses and skills' },
|
||||
{ owner: 'vercel-labs', repo: 'ai-sdk-preview-internal-knowledge-base', description: 'Vercel AI SDK skills' },
|
||||
{ owner: 'composioHQ', repo: 'awesome-claude-code-skills', description: 'Curated Claude Code skills' },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Index file path
|
||||
*/
|
||||
export const INDEX_PATH = join(homedir(), '.skillkit', 'index.json');
|
||||
export const INDEX_CACHE_HOURS = 24;
|
||||
|
||||
/**
|
||||
* Fetch skills from a GitHub repository
|
||||
*/
|
||||
export async function fetchSkillsFromRepo(
|
||||
owner: string,
|
||||
repo: string
|
||||
): Promise<{ skills: SkillSummary[]; error?: string }> {
|
||||
const cloneUrl = `https://github.com/${owner}/${repo}.git`;
|
||||
const tempDir = join(tmpdir(), `skillkit-fetch-${randomUUID()}`);
|
||||
|
||||
try {
|
||||
// Shallow clone for speed
|
||||
execSync(`git clone --depth 1 ${cloneUrl} ${tempDir}`, {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
encoding: 'utf-8',
|
||||
timeout: 60000, // 60 second timeout
|
||||
});
|
||||
|
||||
// Discover skills in the cloned repo
|
||||
const discoveredSkills = discoverSkills(tempDir);
|
||||
const skills: SkillSummary[] = [];
|
||||
|
||||
for (const skill of discoveredSkills) {
|
||||
const skillMdPath = join(skill.path, 'SKILL.md');
|
||||
if (!existsSync(skillMdPath)) continue;
|
||||
|
||||
try {
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
const frontmatter = extractFrontmatter(content);
|
||||
|
||||
const summary: SkillSummary = {
|
||||
name: skill.name,
|
||||
description: skill.description || frontmatter?.description as string || 'No description',
|
||||
source: `${owner}/${repo}`,
|
||||
tags: (frontmatter?.tags as string[]) || [],
|
||||
compatibility: {
|
||||
frameworks: (frontmatter?.compatibility as Record<string, unknown>)?.frameworks as string[] || [],
|
||||
languages: (frontmatter?.compatibility as Record<string, unknown>)?.languages as string[] || [],
|
||||
libraries: (frontmatter?.compatibility as Record<string, unknown>)?.libraries as string[] || [],
|
||||
},
|
||||
popularity: 0,
|
||||
quality: 50,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: owner === 'anthropics' || owner === 'vercel-labs',
|
||||
};
|
||||
|
||||
skills.push(summary);
|
||||
} catch {
|
||||
// Skip skills that fail to parse
|
||||
}
|
||||
}
|
||||
|
||||
return { skills };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return { skills: [], error: `Failed to fetch ${owner}/${repo}: ${message}` };
|
||||
} finally {
|
||||
// Clean up temp directory
|
||||
if (existsSync(tempDir)) {
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch skills from all known repositories and build index
|
||||
*/
|
||||
export async function buildSkillIndex(
|
||||
repos: typeof KNOWN_SKILL_REPOS = KNOWN_SKILL_REPOS,
|
||||
onProgress?: (message: string) => void
|
||||
): Promise<{ index: SkillIndex; errors: string[] }> {
|
||||
const allSkills: SkillSummary[] = [];
|
||||
const sources: IndexSource[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const { owner, repo } of repos) {
|
||||
onProgress?.(`Fetching ${owner}/${repo}...`);
|
||||
|
||||
const result = await fetchSkillsFromRepo(owner, repo);
|
||||
|
||||
if (result.error) {
|
||||
errors.push(result.error);
|
||||
}
|
||||
|
||||
if (result.skills.length > 0) {
|
||||
allSkills.push(...result.skills);
|
||||
sources.push({
|
||||
name: `${owner}/${repo}`,
|
||||
url: `https://github.com/${owner}/${repo}`,
|
||||
lastFetched: new Date().toISOString(),
|
||||
skillCount: result.skills.length,
|
||||
});
|
||||
onProgress?.(` Found ${result.skills.length} skills`);
|
||||
} else if (!result.error) {
|
||||
onProgress?.(` No skills found`);
|
||||
}
|
||||
}
|
||||
|
||||
// Add fallback sample skills if no repos could be fetched
|
||||
if (allSkills.length === 0) {
|
||||
onProgress?.('No skills fetched, using sample index...');
|
||||
allSkills.push(...getSampleSkills());
|
||||
sources.push({
|
||||
name: 'skillkit-samples',
|
||||
url: 'https://github.com/skillkit/samples',
|
||||
lastFetched: new Date().toISOString(),
|
||||
skillCount: allSkills.length,
|
||||
});
|
||||
}
|
||||
|
||||
const index: SkillIndex = {
|
||||
version: 1,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
skills: allSkills,
|
||||
sources,
|
||||
};
|
||||
|
||||
return { index, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Save skill index to cache
|
||||
*/
|
||||
export function saveIndex(index: SkillIndex): void {
|
||||
const indexDir = join(homedir(), '.skillkit');
|
||||
if (!existsSync(indexDir)) {
|
||||
mkdirSync(indexDir, { recursive: true });
|
||||
}
|
||||
writeFileSync(INDEX_PATH, JSON.stringify(index, null, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load skill index from cache
|
||||
*/
|
||||
export function loadIndex(): SkillIndex | null {
|
||||
if (!existsSync(INDEX_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(INDEX_PATH, 'utf-8');
|
||||
return JSON.parse(content) as SkillIndex;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if index is stale
|
||||
*/
|
||||
export function isIndexStale(index: SkillIndex): boolean {
|
||||
const lastUpdated = new Date(index.lastUpdated);
|
||||
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
|
||||
return hoursSinceUpdate > INDEX_CACHE_HOURS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get index status
|
||||
*/
|
||||
export function getIndexStatus(): 'missing' | 'stale' | 'fresh' {
|
||||
const index = loadIndex();
|
||||
if (!index) return 'missing';
|
||||
return isIndexStale(index) ? 'stale' : 'fresh';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample skills fallback (when repos can't be fetched)
|
||||
*/
|
||||
function getSampleSkills(): SkillSummary[] {
|
||||
return [
|
||||
{
|
||||
name: 'react-best-practices',
|
||||
description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization',
|
||||
source: 'skillkit/samples',
|
||||
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-patterns',
|
||||
description: 'Tailwind CSS utility patterns, responsive design, and component styling best practices',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['tailwindcss'],
|
||||
},
|
||||
popularity: 1200,
|
||||
quality: 92,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'typescript-strict-patterns',
|
||||
description: 'TypeScript strict mode patterns, type safety, and advanced type utilities',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['typescript', 'types', 'safety', 'patterns'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 900,
|
||||
quality: 90,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'security-best-practices',
|
||||
description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['security', 'xss', 'csrf', 'headers', 'owasp'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript', 'python'],
|
||||
libraries: [],
|
||||
},
|
||||
popularity: 600,
|
||||
quality: 95,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: true,
|
||||
},
|
||||
{
|
||||
name: 'testing-patterns',
|
||||
description: 'Testing patterns with Vitest/Jest including mocking, assertions, and test organization',
|
||||
source: 'skillkit/samples',
|
||||
tags: ['vitest', 'jest', 'testing', 'typescript', 'mocking', 'tdd'],
|
||||
compatibility: {
|
||||
frameworks: [],
|
||||
languages: ['typescript', 'javascript'],
|
||||
libraries: ['vitest', 'jest'],
|
||||
},
|
||||
popularity: 700,
|
||||
quality: 86,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
verified: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -8,8 +8,20 @@
|
||||
* - Framework/language/library detection
|
||||
* - Task-based search
|
||||
* - Freshness checking
|
||||
* - Skill index fetching from GitHub repos
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './engine.js';
|
||||
export * from './fetcher.js';
|
||||
export { createRecommendationEngine, RecommendationEngine } from './engine.js';
|
||||
export {
|
||||
fetchSkillsFromRepo,
|
||||
buildSkillIndex,
|
||||
saveIndex,
|
||||
loadIndex,
|
||||
isIndexStale,
|
||||
getIndexStatus,
|
||||
KNOWN_SKILL_REPOS,
|
||||
INDEX_PATH,
|
||||
} from './fetcher.js';
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Session Management Module
|
||||
*
|
||||
* Provides session state tracking for skill execution with pause/resume support.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './manager.js';
|
||||
export { SessionManager, createSessionManager } from './manager.js';
|
||||
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* Session Manager
|
||||
*
|
||||
* Manages session state for skill execution with pause/resume support.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parse, stringify } from 'yaml';
|
||||
import type {
|
||||
SessionState,
|
||||
CurrentExecution,
|
||||
ExecutionHistory,
|
||||
SessionTask,
|
||||
TaskStatus,
|
||||
} from './types.js';
|
||||
import { SESSION_FILE } from './types.js';
|
||||
|
||||
/**
|
||||
* Session Manager for tracking skill execution state
|
||||
*/
|
||||
export class SessionManager {
|
||||
private projectPath: string;
|
||||
private sessionPath: string;
|
||||
private state: SessionState | null = null;
|
||||
|
||||
constructor(projectPath: string) {
|
||||
this.projectPath = projectPath;
|
||||
this.sessionPath = join(projectPath, '.skillkit', SESSION_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session file path
|
||||
*/
|
||||
getSessionPath(): string {
|
||||
return this.sessionPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load session state from disk
|
||||
*/
|
||||
load(): SessionState | null {
|
||||
if (!existsSync(this.sessionPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(this.sessionPath, 'utf-8');
|
||||
this.state = parse(content) as SessionState;
|
||||
return this.state;
|
||||
} catch (error) {
|
||||
console.error('Failed to load session:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session state to disk
|
||||
*/
|
||||
save(): void {
|
||||
if (!this.state) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dir = join(this.projectPath, '.skillkit');
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
this.state.lastActivity = new Date().toISOString();
|
||||
writeFileSync(this.sessionPath, stringify(this.state));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a new session
|
||||
*/
|
||||
init(): SessionState {
|
||||
this.state = {
|
||||
version: 1,
|
||||
lastActivity: new Date().toISOString(),
|
||||
projectPath: this.projectPath,
|
||||
history: [],
|
||||
decisions: [],
|
||||
};
|
||||
this.save();
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current session state (load if needed)
|
||||
*/
|
||||
get(): SessionState | null {
|
||||
if (!this.state) {
|
||||
this.state = this.load();
|
||||
}
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create session
|
||||
*/
|
||||
getOrCreate(): SessionState {
|
||||
const state = this.get();
|
||||
if (state) {
|
||||
return state;
|
||||
}
|
||||
return this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new skill execution
|
||||
*/
|
||||
startExecution(skillName: string, skillSource: string, tasks: Omit<SessionTask, 'status'>[]): CurrentExecution {
|
||||
const state = this.getOrCreate();
|
||||
|
||||
const execution: CurrentExecution = {
|
||||
skillName,
|
||||
skillSource,
|
||||
currentStep: 0,
|
||||
totalSteps: tasks.length,
|
||||
status: 'running',
|
||||
startedAt: new Date().toISOString(),
|
||||
tasks: tasks.map((t) => ({
|
||||
...t,
|
||||
status: 'pending' as TaskStatus,
|
||||
})),
|
||||
};
|
||||
|
||||
state.currentExecution = execution;
|
||||
this.save();
|
||||
return execution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update task status
|
||||
*/
|
||||
updateTask(
|
||||
taskId: string,
|
||||
updates: Partial<Pick<SessionTask, 'status' | 'output' | 'error' | 'filesModified' | 'commitSha'>>
|
||||
): void {
|
||||
const state = this.get();
|
||||
if (!state?.currentExecution) {
|
||||
return;
|
||||
}
|
||||
|
||||
const task = state.currentExecution.tasks.find((t) => t.id === taskId);
|
||||
if (!task) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.assign(task, updates);
|
||||
|
||||
if (updates.status === 'in_progress' && !task.startedAt) {
|
||||
task.startedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
if (updates.status === 'completed' || updates.status === 'failed') {
|
||||
task.completedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
// Update current step
|
||||
const completedCount = state.currentExecution.tasks.filter(
|
||||
(t) => t.status === 'completed' || t.status === 'failed'
|
||||
).length;
|
||||
state.currentExecution.currentStep = completedCount;
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance to next task
|
||||
*/
|
||||
advanceToNextTask(): SessionTask | null {
|
||||
const state = this.get();
|
||||
if (!state?.currentExecution) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const nextTask = state.currentExecution.tasks.find((t) => t.status === 'pending');
|
||||
if (nextTask) {
|
||||
nextTask.status = 'in_progress';
|
||||
nextTask.startedAt = new Date().toISOString();
|
||||
this.save();
|
||||
}
|
||||
|
||||
return nextTask || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause current execution
|
||||
*/
|
||||
pause(): boolean {
|
||||
const state = this.get();
|
||||
if (!state?.currentExecution || state.currentExecution.status !== 'running') {
|
||||
return false;
|
||||
}
|
||||
|
||||
state.currentExecution.status = 'paused';
|
||||
state.currentExecution.pausedAt = new Date().toISOString();
|
||||
|
||||
// Mark any in-progress tasks as paused
|
||||
for (const task of state.currentExecution.tasks) {
|
||||
if (task.status === 'in_progress') {
|
||||
task.status = 'paused';
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume paused execution
|
||||
*/
|
||||
resume(): boolean {
|
||||
const state = this.get();
|
||||
if (!state?.currentExecution || state.currentExecution.status !== 'paused') {
|
||||
return false;
|
||||
}
|
||||
|
||||
state.currentExecution.status = 'running';
|
||||
delete state.currentExecution.pausedAt;
|
||||
|
||||
// Resume paused tasks
|
||||
for (const task of state.currentExecution.tasks) {
|
||||
if (task.status === 'paused') {
|
||||
task.status = 'in_progress';
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete current execution
|
||||
*/
|
||||
completeExecution(status: 'completed' | 'failed' | 'cancelled', error?: string): void {
|
||||
const state = this.get();
|
||||
if (!state?.currentExecution) {
|
||||
return;
|
||||
}
|
||||
|
||||
const execution = state.currentExecution;
|
||||
const startTime = new Date(execution.startedAt).getTime();
|
||||
const endTime = Date.now();
|
||||
|
||||
const historyEntry: ExecutionHistory = {
|
||||
skillName: execution.skillName,
|
||||
skillSource: execution.skillSource,
|
||||
completedAt: new Date().toISOString(),
|
||||
durationMs: endTime - startTime,
|
||||
status,
|
||||
commits: execution.tasks
|
||||
.map((t) => t.commitSha)
|
||||
.filter((sha): sha is string => !!sha),
|
||||
filesModified: Array.from(
|
||||
new Set(execution.tasks.flatMap((t) => t.filesModified || []))
|
||||
),
|
||||
error,
|
||||
};
|
||||
|
||||
state.history.unshift(historyEntry);
|
||||
delete state.currentExecution;
|
||||
|
||||
// Keep only last 50 history entries
|
||||
if (state.history.length > 50) {
|
||||
state.history = state.history.slice(0, 50);
|
||||
}
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a user decision
|
||||
*/
|
||||
recordDecision(key: string, value: string, skillName?: string): void {
|
||||
const state = this.getOrCreate();
|
||||
|
||||
// Update existing decision or add new one
|
||||
const existing = state.decisions.find((d) => d.key === key);
|
||||
if (existing) {
|
||||
existing.value = value;
|
||||
existing.madeAt = new Date().toISOString();
|
||||
existing.skillName = skillName;
|
||||
} else {
|
||||
state.decisions.push({
|
||||
key,
|
||||
value,
|
||||
madeAt: new Date().toISOString(),
|
||||
skillName,
|
||||
});
|
||||
}
|
||||
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a decision value
|
||||
*/
|
||||
getDecision(key: string): string | undefined {
|
||||
const state = this.get();
|
||||
return state?.decisions.find((d) => d.key === key)?.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get execution history
|
||||
*/
|
||||
getHistory(limit?: number): ExecutionHistory[] {
|
||||
const state = this.get();
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return limit ? state.history.slice(0, limit) : state.history;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there's an active execution
|
||||
*/
|
||||
hasActiveExecution(): boolean {
|
||||
const state = this.get();
|
||||
return !!state?.currentExecution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if execution is paused
|
||||
*/
|
||||
isPaused(): boolean {
|
||||
const state = this.get();
|
||||
return state?.currentExecution?.status === 'paused';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear session (delete file)
|
||||
*/
|
||||
clear(): void {
|
||||
if (existsSync(this.sessionPath)) {
|
||||
unlinkSync(this.sessionPath);
|
||||
}
|
||||
this.state = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session manager
|
||||
*/
|
||||
export function createSessionManager(projectPath: string): SessionManager {
|
||||
return new SessionManager(projectPath);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Session State Types
|
||||
*
|
||||
* Types for managing skill execution sessions with pause/resume support.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Status of a task in execution
|
||||
*/
|
||||
export type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'paused';
|
||||
|
||||
/**
|
||||
* A single task within a skill execution
|
||||
*/
|
||||
export interface SessionTask {
|
||||
/** Task identifier */
|
||||
id: string;
|
||||
/** Task name/description */
|
||||
name: string;
|
||||
/** Task type (auto, checkpoint:human-verify, checkpoint:decision, checkpoint:human-action) */
|
||||
type: 'auto' | 'checkpoint:human-verify' | 'checkpoint:decision' | 'checkpoint:human-action';
|
||||
/** Current status */
|
||||
status: TaskStatus;
|
||||
/** Start time */
|
||||
startedAt?: string;
|
||||
/** Completion time */
|
||||
completedAt?: string;
|
||||
/** Error message if failed */
|
||||
error?: string;
|
||||
/** Output/result of the task */
|
||||
output?: string;
|
||||
/** Files modified by this task */
|
||||
filesModified?: string[];
|
||||
/** Git commit SHA if committed */
|
||||
commitSha?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current skill execution state
|
||||
*/
|
||||
export interface CurrentExecution {
|
||||
/** Skill being executed */
|
||||
skillName: string;
|
||||
/** Skill source (repo) */
|
||||
skillSource: string;
|
||||
/** Current step/task index */
|
||||
currentStep: number;
|
||||
/** Total steps */
|
||||
totalSteps: number;
|
||||
/** Execution status */
|
||||
status: 'running' | 'paused' | 'completed' | 'failed';
|
||||
/** When execution started */
|
||||
startedAt: string;
|
||||
/** When execution was paused (if paused) */
|
||||
pausedAt?: string;
|
||||
/** Tasks in this execution */
|
||||
tasks: SessionTask[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical execution record
|
||||
*/
|
||||
export interface ExecutionHistory {
|
||||
/** Skill name */
|
||||
skillName: string;
|
||||
/** Skill source */
|
||||
skillSource: string;
|
||||
/** When execution completed */
|
||||
completedAt: string;
|
||||
/** Duration in milliseconds */
|
||||
durationMs: number;
|
||||
/** Final status */
|
||||
status: 'completed' | 'failed' | 'cancelled';
|
||||
/** Git commits created */
|
||||
commits: string[];
|
||||
/** Files modified */
|
||||
filesModified: string[];
|
||||
/** Error if failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* User decisions made during skill execution
|
||||
*/
|
||||
export interface SessionDecision {
|
||||
/** Decision key/identifier */
|
||||
key: string;
|
||||
/** Decision value */
|
||||
value: string;
|
||||
/** When decision was made */
|
||||
madeAt: string;
|
||||
/** Skill that prompted the decision */
|
||||
skillName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full session state
|
||||
*/
|
||||
export interface SessionState {
|
||||
/** Schema version */
|
||||
version: 1;
|
||||
/** Last activity timestamp */
|
||||
lastActivity: string;
|
||||
/** Project path this session is for */
|
||||
projectPath: string;
|
||||
/** Current execution (if any) */
|
||||
currentExecution?: CurrentExecution;
|
||||
/** Execution history */
|
||||
history: ExecutionHistory[];
|
||||
/** User decisions */
|
||||
decisions: SessionDecision[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Session state file path within .skillkit directory
|
||||
*/
|
||||
export const SESSION_FILE = 'session.yaml';
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Skill Testing Framework
|
||||
*
|
||||
* Provides test case definitions and a test runner for skill verification.
|
||||
*
|
||||
* @example
|
||||
* ```yaml
|
||||
* # In skill frontmatter
|
||||
* tests:
|
||||
* - name: "Creates config file"
|
||||
* assertions:
|
||||
* - type: file_exists
|
||||
* target: config.json
|
||||
* - name: "Valid JSON output"
|
||||
* assertions:
|
||||
* - type: json_valid
|
||||
* target: config.json
|
||||
* - name: "Types check"
|
||||
* assertions:
|
||||
* - type: type_check
|
||||
* ```
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './runner.js';
|
||||
|
||||
export {
|
||||
runTestSuite,
|
||||
createTestSuiteFromFrontmatter,
|
||||
} from './runner.js';
|
||||
|
||||
export type {
|
||||
TestAssertionType,
|
||||
TestAssertion,
|
||||
SkillTestCase,
|
||||
SkillTestSuite,
|
||||
AssertionResult,
|
||||
TestCaseResult,
|
||||
TestSuiteResult,
|
||||
TestRunnerOptions,
|
||||
TestProgressEvent,
|
||||
} from './types.js';
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Skill Testing Framework Types
|
||||
*
|
||||
* Define test cases in skill frontmatter for automated verification.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Test assertion types
|
||||
*/
|
||||
export type TestAssertionType =
|
||||
| 'file_exists'
|
||||
| 'file_not_exists'
|
||||
| 'file_contains'
|
||||
| 'file_not_contains'
|
||||
| 'file_matches'
|
||||
| 'command_succeeds'
|
||||
| 'command_fails'
|
||||
| 'command_output_contains'
|
||||
| 'json_valid'
|
||||
| 'json_has_key'
|
||||
| 'yaml_valid'
|
||||
| 'type_check'
|
||||
| 'lint_passes'
|
||||
| 'test_passes'
|
||||
| 'env_var_set'
|
||||
| 'port_available'
|
||||
| 'url_responds'
|
||||
| 'custom';
|
||||
|
||||
/**
|
||||
* Test assertion definition
|
||||
*/
|
||||
export interface TestAssertion {
|
||||
/** Assertion type */
|
||||
type: TestAssertionType;
|
||||
/** Target file, command, or URL */
|
||||
target?: string;
|
||||
/** Expected value or pattern */
|
||||
expected?: string | boolean | number;
|
||||
/** Custom command for 'custom' type */
|
||||
command?: string;
|
||||
/** Timeout in milliseconds */
|
||||
timeout?: number;
|
||||
/** Error message on failure */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test case definition
|
||||
*/
|
||||
export interface SkillTestCase {
|
||||
/** Test name */
|
||||
name: string;
|
||||
/** Test description */
|
||||
description?: string;
|
||||
/** Assertions to run */
|
||||
assertions: TestAssertion[];
|
||||
/** Setup commands to run before test */
|
||||
setup?: string[];
|
||||
/** Cleanup commands to run after test */
|
||||
cleanup?: string[];
|
||||
/** Skip this test */
|
||||
skip?: boolean;
|
||||
/** Only run this test */
|
||||
only?: boolean;
|
||||
/** Tags for filtering */
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Test suite for a skill
|
||||
*/
|
||||
export interface SkillTestSuite {
|
||||
/** Skill name */
|
||||
skillName: string;
|
||||
/** Test cases */
|
||||
tests: SkillTestCase[];
|
||||
/** Global setup commands */
|
||||
globalSetup?: string[];
|
||||
/** Global cleanup commands */
|
||||
globalCleanup?: string[];
|
||||
/** Default timeout for all tests */
|
||||
defaultTimeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Individual assertion result
|
||||
*/
|
||||
export interface AssertionResult {
|
||||
/** Assertion that was run */
|
||||
assertion: TestAssertion;
|
||||
/** Whether assertion passed */
|
||||
passed: boolean;
|
||||
/** Actual value found */
|
||||
actual?: string;
|
||||
/** Expected value */
|
||||
expected?: string;
|
||||
/** Error message if failed */
|
||||
error?: string;
|
||||
/** Duration in milliseconds */
|
||||
duration: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test case result
|
||||
*/
|
||||
export interface TestCaseResult {
|
||||
/** Test case that was run */
|
||||
testCase: SkillTestCase;
|
||||
/** Whether all assertions passed */
|
||||
passed: boolean;
|
||||
/** Individual assertion results */
|
||||
assertions: AssertionResult[];
|
||||
/** Setup error if any */
|
||||
setupError?: string;
|
||||
/** Cleanup error if any */
|
||||
cleanupError?: string;
|
||||
/** Total duration in milliseconds */
|
||||
duration: number;
|
||||
/** Whether test was skipped */
|
||||
skipped: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test suite result
|
||||
*/
|
||||
export interface TestSuiteResult {
|
||||
/** Skill name */
|
||||
skillName: string;
|
||||
/** Whether all tests passed */
|
||||
passed: boolean;
|
||||
/** Individual test results */
|
||||
tests: TestCaseResult[];
|
||||
/** Number of tests passed */
|
||||
passedCount: number;
|
||||
/** Number of tests failed */
|
||||
failedCount: number;
|
||||
/** Number of tests skipped */
|
||||
skippedCount: number;
|
||||
/** Total duration in milliseconds */
|
||||
duration: number;
|
||||
/** Global setup error if any */
|
||||
globalSetupError?: string;
|
||||
/** Global cleanup error if any */
|
||||
globalCleanupError?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test runner options
|
||||
*/
|
||||
export interface TestRunnerOptions {
|
||||
/** Working directory */
|
||||
cwd?: string;
|
||||
/** Default timeout in milliseconds */
|
||||
timeout?: number;
|
||||
/** Only run tests with these tags */
|
||||
tags?: string[];
|
||||
/** Skip tests with these tags */
|
||||
skipTags?: string[];
|
||||
/** Verbose output */
|
||||
verbose?: boolean;
|
||||
/** Stop on first failure */
|
||||
bail?: boolean;
|
||||
/** Run tests in parallel */
|
||||
parallel?: boolean;
|
||||
/** Progress callback */
|
||||
onProgress?: (event: TestProgressEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test progress event
|
||||
*/
|
||||
export interface TestProgressEvent {
|
||||
type: 'suite_start' | 'suite_end' | 'test_start' | 'test_end' | 'assertion_start' | 'assertion_end';
|
||||
skillName?: string;
|
||||
testName?: string;
|
||||
assertionType?: TestAssertionType;
|
||||
passed?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Workflow Module
|
||||
*
|
||||
* Provides skill composition and workflow orchestration.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './parser.js';
|
||||
export * from './orchestrator.js';
|
||||
export { WorkflowOrchestrator, createWorkflowOrchestrator } from './orchestrator.js';
|
||||
export {
|
||||
parseWorkflow,
|
||||
loadWorkflow,
|
||||
loadWorkflowByName,
|
||||
listWorkflows,
|
||||
saveWorkflow,
|
||||
serializeWorkflow,
|
||||
validateWorkflow,
|
||||
createWorkflowTemplate,
|
||||
} from './parser.js';
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* Workflow Orchestrator
|
||||
*
|
||||
* Executes workflows with wave-based orchestration.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type {
|
||||
Workflow,
|
||||
WorkflowWave,
|
||||
WorkflowSkill,
|
||||
WorkflowExecution,
|
||||
WorkflowExecutionStatus,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Skill executor function type
|
||||
*/
|
||||
export type SkillExecutor = (
|
||||
skillName: string,
|
||||
config?: Record<string, unknown>
|
||||
) => Promise<{ success: boolean; error?: string }>;
|
||||
|
||||
/**
|
||||
* Progress callback for workflow execution
|
||||
*/
|
||||
export type WorkflowProgressCallback = (event: {
|
||||
type: 'wave_start' | 'wave_complete' | 'skill_start' | 'skill_complete' | 'workflow_complete';
|
||||
waveIndex?: number;
|
||||
waveName?: string;
|
||||
skillName?: string;
|
||||
status?: WorkflowExecutionStatus;
|
||||
error?: string;
|
||||
}) => void;
|
||||
|
||||
/**
|
||||
* Workflow Orchestrator
|
||||
*
|
||||
* Manages the execution of workflows with parallel/sequential waves.
|
||||
*/
|
||||
export class WorkflowOrchestrator {
|
||||
private execution: WorkflowExecution | null = null;
|
||||
private executor: SkillExecutor;
|
||||
private onProgress?: WorkflowProgressCallback;
|
||||
|
||||
constructor(executor: SkillExecutor, onProgress?: WorkflowProgressCallback) {
|
||||
this.executor = executor;
|
||||
this.onProgress = onProgress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current execution state
|
||||
*/
|
||||
getExecution(): WorkflowExecution | null {
|
||||
return this.execution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a workflow
|
||||
*/
|
||||
async execute(workflow: Workflow): Promise<WorkflowExecution> {
|
||||
// Initialize execution state
|
||||
this.execution = {
|
||||
workflow,
|
||||
executionId: randomUUID(),
|
||||
status: 'running',
|
||||
currentWave: 0,
|
||||
waves: workflow.waves.map((wave, index) => ({
|
||||
waveIndex: index,
|
||||
waveName: wave.name,
|
||||
status: 'pending',
|
||||
skills: wave.skills.map((s) => ({
|
||||
skill: typeof s === 'string' ? s : s.skill,
|
||||
status: 'pending' as WorkflowExecutionStatus,
|
||||
})),
|
||||
})),
|
||||
startedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
// Execute each wave
|
||||
for (let i = 0; i < workflow.waves.length; i++) {
|
||||
if (this.execution.status === 'cancelled' || this.execution.status === 'paused') {
|
||||
break;
|
||||
}
|
||||
|
||||
this.execution.currentWave = i;
|
||||
await this.executeWave(workflow.waves[i], i);
|
||||
|
||||
// Check if wave failed and should stop
|
||||
const waveStatus = this.execution.waves[i];
|
||||
if (waveStatus.status === 'failed' && !workflow.waves[i].continueOnError) {
|
||||
this.execution.status = 'failed';
|
||||
this.execution.error = `Wave ${i + 1} failed`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark as completed if not already failed/cancelled/paused
|
||||
if (this.execution.status === 'running') {
|
||||
this.execution.status = 'completed';
|
||||
}
|
||||
|
||||
this.execution.completedAt = new Date().toISOString();
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'workflow_complete',
|
||||
status: this.execution.status,
|
||||
error: this.execution.error,
|
||||
});
|
||||
|
||||
return this.execution;
|
||||
} catch (error) {
|
||||
this.execution.status = 'failed';
|
||||
this.execution.error = error instanceof Error ? error.message : String(error);
|
||||
this.execution.completedAt = new Date().toISOString();
|
||||
return this.execution;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a single wave
|
||||
*/
|
||||
private async executeWave(wave: WorkflowWave, waveIndex: number): Promise<void> {
|
||||
const waveStatus = this.execution!.waves[waveIndex];
|
||||
waveStatus.status = 'running';
|
||||
waveStatus.startedAt = new Date().toISOString();
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'wave_start',
|
||||
waveIndex,
|
||||
waveName: wave.name,
|
||||
});
|
||||
|
||||
const skills = wave.skills.map((s) => ({
|
||||
name: typeof s === 'string' ? s : s.skill,
|
||||
config: typeof s === 'string' ? undefined : (s as WorkflowSkill).config,
|
||||
}));
|
||||
|
||||
if (wave.parallel) {
|
||||
// Execute skills in parallel
|
||||
await Promise.all(
|
||||
skills.map((skill, skillIndex) =>
|
||||
this.executeSkill(skill.name, skill.config, waveIndex, skillIndex)
|
||||
)
|
||||
);
|
||||
} else {
|
||||
// Execute skills sequentially
|
||||
for (let i = 0; i < skills.length; i++) {
|
||||
if (this.execution!.status === 'cancelled' || this.execution!.status === 'paused') {
|
||||
break;
|
||||
}
|
||||
|
||||
await this.executeSkill(skills[i].name, skills[i].config, waveIndex, i);
|
||||
|
||||
// Stop on first failure in sequential mode
|
||||
const skillStatus = waveStatus.skills[i];
|
||||
if (skillStatus.status === 'failed' && !wave.continueOnError) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine wave status based on skill statuses
|
||||
const hasFailures = waveStatus.skills.some((s) => s.status === 'failed');
|
||||
const allCompleted = waveStatus.skills.every(
|
||||
(s) => s.status === 'completed' || s.status === 'failed'
|
||||
);
|
||||
|
||||
if (allCompleted) {
|
||||
waveStatus.status = hasFailures ? 'failed' : 'completed';
|
||||
}
|
||||
|
||||
waveStatus.completedAt = new Date().toISOString();
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'wave_complete',
|
||||
waveIndex,
|
||||
waveName: wave.name,
|
||||
status: waveStatus.status,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a single skill
|
||||
*/
|
||||
private async executeSkill(
|
||||
skillName: string,
|
||||
config: Record<string, unknown> | undefined,
|
||||
waveIndex: number,
|
||||
skillIndex: number
|
||||
): Promise<void> {
|
||||
const skillStatus = this.execution!.waves[waveIndex].skills[skillIndex];
|
||||
skillStatus.status = 'running';
|
||||
skillStatus.startedAt = new Date().toISOString();
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'skill_start',
|
||||
waveIndex,
|
||||
skillName,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await this.executor(skillName, config);
|
||||
|
||||
if (result.success) {
|
||||
skillStatus.status = 'completed';
|
||||
} else {
|
||||
skillStatus.status = 'failed';
|
||||
skillStatus.error = result.error;
|
||||
}
|
||||
} catch (error) {
|
||||
skillStatus.status = 'failed';
|
||||
skillStatus.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
skillStatus.completedAt = new Date().toISOString();
|
||||
|
||||
this.onProgress?.({
|
||||
type: 'skill_complete',
|
||||
waveIndex,
|
||||
skillName,
|
||||
status: skillStatus.status,
|
||||
error: skillStatus.error,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause execution
|
||||
*/
|
||||
pause(): boolean {
|
||||
if (!this.execution || this.execution.status !== 'running') {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.execution.status = 'paused';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if execution should continue
|
||||
*/
|
||||
private shouldContinue(): boolean {
|
||||
if (!this.execution) return false;
|
||||
return this.execution.status === 'running';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume execution
|
||||
*/
|
||||
async resume(): Promise<WorkflowExecution | null> {
|
||||
if (!this.execution || this.execution.status !== 'paused') {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.execution.status = 'running';
|
||||
|
||||
// Continue from current wave
|
||||
const workflow = this.execution.workflow;
|
||||
for (let i = this.execution.currentWave; i < workflow.waves.length; i++) {
|
||||
if (!this.shouldContinue()) {
|
||||
break;
|
||||
}
|
||||
|
||||
this.execution.currentWave = i;
|
||||
|
||||
// Skip already completed waves
|
||||
if (this.execution.waves[i].status === 'completed') {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.executeWave(workflow.waves[i], i);
|
||||
|
||||
const waveStatus = this.execution.waves[i];
|
||||
if (waveStatus.status === 'failed' && !workflow.waves[i].continueOnError) {
|
||||
this.execution.status = 'failed';
|
||||
this.execution.error = `Wave ${i + 1} failed`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.execution.status === 'running') {
|
||||
this.execution.status = 'completed';
|
||||
}
|
||||
|
||||
this.execution.completedAt = new Date().toISOString();
|
||||
return this.execution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel execution
|
||||
*/
|
||||
cancel(): boolean {
|
||||
if (!this.execution || this.execution.status === 'completed' || this.execution.status === 'failed') {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.execution.status = 'cancelled';
|
||||
this.execution.completedAt = new Date().toISOString();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new workflow orchestrator
|
||||
*/
|
||||
export function createWorkflowOrchestrator(
|
||||
executor: SkillExecutor,
|
||||
onProgress?: WorkflowProgressCallback
|
||||
): WorkflowOrchestrator {
|
||||
return new WorkflowOrchestrator(executor, onProgress);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Workflow Parser
|
||||
*
|
||||
* Parses workflow YAML files into Workflow objects.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parse, stringify } from 'yaml';
|
||||
import type { Workflow, WorkflowWave, WorkflowSkill } from './types.js';
|
||||
import { WORKFLOWS_DIR, WORKFLOW_EXTENSION } from './types.js';
|
||||
|
||||
/**
|
||||
* Parse a workflow from YAML content
|
||||
*/
|
||||
export function parseWorkflow(content: string): Workflow {
|
||||
const data = parse(content) as Record<string, unknown>;
|
||||
|
||||
if (!data.name || typeof data.name !== 'string') {
|
||||
throw new Error('Workflow must have a name');
|
||||
}
|
||||
|
||||
if (!data.waves || !Array.isArray(data.waves)) {
|
||||
throw new Error('Workflow must have waves array');
|
||||
}
|
||||
|
||||
const waves: WorkflowWave[] = data.waves.map((wave: unknown, index: number) => {
|
||||
if (typeof wave !== 'object' || wave === null) {
|
||||
throw new Error(`Wave ${index} must be an object`);
|
||||
}
|
||||
|
||||
const waveObj = wave as Record<string, unknown>;
|
||||
const skills = waveObj.skills;
|
||||
|
||||
if (!skills || !Array.isArray(skills)) {
|
||||
throw new Error(`Wave ${index} must have skills array`);
|
||||
}
|
||||
|
||||
return {
|
||||
name: waveObj.name as string | undefined,
|
||||
parallel: waveObj.parallel === true,
|
||||
skills: skills.map((s: unknown) => {
|
||||
if (typeof s === 'string') {
|
||||
return s;
|
||||
}
|
||||
if (typeof s === 'object' && s !== null) {
|
||||
const skillObj = s as Record<string, unknown>;
|
||||
return {
|
||||
skill: skillObj.skill as string,
|
||||
config: skillObj.config as Record<string, unknown> | undefined,
|
||||
condition: skillObj.condition as string | undefined,
|
||||
} as WorkflowSkill;
|
||||
}
|
||||
throw new Error(`Invalid skill in wave ${index}`);
|
||||
}),
|
||||
continueOnError: waveObj.continueOnError === true,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
name: data.name as string,
|
||||
description: data.description as string | undefined,
|
||||
version: data.version as string | undefined,
|
||||
author: data.author as string | undefined,
|
||||
tags: data.tags as string[] | undefined,
|
||||
waves,
|
||||
env: data.env as Record<string, string> | undefined,
|
||||
preHooks: data.preHooks as string[] | undefined,
|
||||
postHooks: data.postHooks as string[] | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a workflow from a file
|
||||
*/
|
||||
export function loadWorkflow(filePath: string): Workflow {
|
||||
if (!existsSync(filePath)) {
|
||||
throw new Error(`Workflow file not found: ${filePath}`);
|
||||
}
|
||||
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
return parseWorkflow(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a workflow by name from the project's workflows directory
|
||||
*/
|
||||
export function loadWorkflowByName(projectPath: string, name: string): Workflow | null {
|
||||
const workflowsDir = join(projectPath, '.skillkit', WORKFLOWS_DIR);
|
||||
|
||||
if (!existsSync(workflowsDir)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Try exact name match first
|
||||
const exactPath = join(workflowsDir, `${name}${WORKFLOW_EXTENSION}`);
|
||||
if (existsSync(exactPath)) {
|
||||
return loadWorkflow(exactPath);
|
||||
}
|
||||
|
||||
// Try finding by workflow name property
|
||||
const files = readdirSync(workflowsDir).filter((f) => f.endsWith(WORKFLOW_EXTENSION));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const workflow = loadWorkflow(join(workflowsDir, file));
|
||||
if (workflow.name === name) {
|
||||
return workflow;
|
||||
}
|
||||
} catch {
|
||||
// Skip invalid workflow files
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all workflows in a project
|
||||
*/
|
||||
export function listWorkflows(projectPath: string): Workflow[] {
|
||||
const workflowsDir = join(projectPath, '.skillkit', WORKFLOWS_DIR);
|
||||
|
||||
if (!existsSync(workflowsDir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const files = readdirSync(workflowsDir).filter((f) => f.endsWith(WORKFLOW_EXTENSION));
|
||||
const workflows: Workflow[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const workflow = loadWorkflow(join(workflowsDir, file));
|
||||
workflows.push(workflow);
|
||||
} catch {
|
||||
// Skip invalid workflow files
|
||||
}
|
||||
}
|
||||
|
||||
return workflows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a workflow to a file
|
||||
*/
|
||||
export function saveWorkflow(projectPath: string, workflow: Workflow): string {
|
||||
const workflowsDir = join(projectPath, '.skillkit', WORKFLOWS_DIR);
|
||||
|
||||
if (!existsSync(workflowsDir)) {
|
||||
mkdirSync(workflowsDir, { recursive: true });
|
||||
}
|
||||
|
||||
const fileName = `${workflow.name.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}${WORKFLOW_EXTENSION}`;
|
||||
const filePath = join(workflowsDir, fileName);
|
||||
|
||||
writeFileSync(filePath, stringify(workflow));
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a workflow to YAML
|
||||
*/
|
||||
export function serializeWorkflow(workflow: Workflow): string {
|
||||
return stringify(workflow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a workflow
|
||||
*/
|
||||
export function validateWorkflow(workflow: Workflow): { valid: boolean; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (!workflow.name) {
|
||||
errors.push('Workflow must have a name');
|
||||
}
|
||||
|
||||
if (!workflow.waves || workflow.waves.length === 0) {
|
||||
errors.push('Workflow must have at least one wave');
|
||||
}
|
||||
|
||||
for (let i = 0; i < workflow.waves.length; i++) {
|
||||
const wave = workflow.waves[i];
|
||||
|
||||
if (!wave.skills || wave.skills.length === 0) {
|
||||
errors.push(`Wave ${i + 1} must have at least one skill`);
|
||||
}
|
||||
|
||||
for (let j = 0; j < wave.skills.length; j++) {
|
||||
const skill = wave.skills[j];
|
||||
const skillName = typeof skill === 'string' ? skill : skill.skill;
|
||||
|
||||
if (!skillName) {
|
||||
errors.push(`Wave ${i + 1}, skill ${j + 1} must have a name`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new workflow from a template
|
||||
*/
|
||||
export function createWorkflowTemplate(name: string, description?: string): Workflow {
|
||||
return {
|
||||
name,
|
||||
description: description || `Workflow: ${name}`,
|
||||
version: '1.0.0',
|
||||
waves: [
|
||||
{
|
||||
name: 'Setup',
|
||||
parallel: true,
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
name: 'Main',
|
||||
parallel: false,
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Workflow Types
|
||||
*
|
||||
* Types for skill composition and workflow orchestration.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A skill reference within a workflow
|
||||
*/
|
||||
export interface WorkflowSkill {
|
||||
/** Skill name or source (e.g., "typescript-strict-mode" or "owner/repo/skill") */
|
||||
skill: string;
|
||||
/** Optional configuration overrides */
|
||||
config?: Record<string, unknown>;
|
||||
/** Optional condition to run this skill */
|
||||
condition?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A wave of skills to execute (parallel or sequential)
|
||||
*/
|
||||
export interface WorkflowWave {
|
||||
/** Wave name/description */
|
||||
name?: string;
|
||||
/** Whether skills in this wave run in parallel */
|
||||
parallel: boolean;
|
||||
/** Skills to execute in this wave */
|
||||
skills: (string | WorkflowSkill)[];
|
||||
/** Continue to next wave even if this wave has failures */
|
||||
continueOnError?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workflow definition
|
||||
*/
|
||||
export interface Workflow {
|
||||
/** Workflow name (used as identifier) */
|
||||
name: string;
|
||||
/** Human-readable description */
|
||||
description?: string;
|
||||
/** Workflow version */
|
||||
version?: string;
|
||||
/** Author information */
|
||||
author?: string;
|
||||
/** Tags for discovery */
|
||||
tags?: string[];
|
||||
/** Waves of skills to execute */
|
||||
waves: WorkflowWave[];
|
||||
/** Environment variables to set */
|
||||
env?: Record<string, string>;
|
||||
/** Pre-execution hooks */
|
||||
preHooks?: string[];
|
||||
/** Post-execution hooks */
|
||||
postHooks?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Workflow execution status
|
||||
*/
|
||||
export type WorkflowExecutionStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled';
|
||||
|
||||
/**
|
||||
* Status of a wave execution
|
||||
*/
|
||||
export interface WaveExecutionStatus {
|
||||
/** Wave index */
|
||||
waveIndex: number;
|
||||
/** Wave name */
|
||||
waveName?: string;
|
||||
/** Status */
|
||||
status: WorkflowExecutionStatus;
|
||||
/** Skills statuses */
|
||||
skills: {
|
||||
skill: string;
|
||||
status: WorkflowExecutionStatus;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
error?: string;
|
||||
}[];
|
||||
/** When wave started */
|
||||
startedAt?: string;
|
||||
/** When wave completed */
|
||||
completedAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workflow execution state
|
||||
*/
|
||||
export interface WorkflowExecution {
|
||||
/** Workflow being executed */
|
||||
workflow: Workflow;
|
||||
/** Execution ID */
|
||||
executionId: string;
|
||||
/** Overall status */
|
||||
status: WorkflowExecutionStatus;
|
||||
/** Current wave index */
|
||||
currentWave: number;
|
||||
/** Wave statuses */
|
||||
waves: WaveExecutionStatus[];
|
||||
/** When execution started */
|
||||
startedAt: string;
|
||||
/** When execution completed */
|
||||
completedAt?: string;
|
||||
/** Error if failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workflow file location
|
||||
*/
|
||||
export const WORKFLOWS_DIR = 'workflows';
|
||||
export const WORKFLOW_EXTENSION = '.yaml';
|
||||
@@ -0,0 +1,61 @@
|
||||
# @skillkit/tui
|
||||
|
||||
Interactive terminal UI for SkillKit - browse, install, and manage skills visually.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/tui
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Browse Skills**: Discover skills from the marketplace
|
||||
- **Smart Recommendations**: Project-aware skill suggestions
|
||||
- **Skill Translation**: Convert between agent formats
|
||||
- **Context Management**: View and sync project context
|
||||
- **Keyboard Navigation**: Fast, intuitive controls
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import { startTUI } from '@skillkit/tui';
|
||||
|
||||
// Launch the interactive TUI
|
||||
await startTUI();
|
||||
```
|
||||
|
||||
Or via CLI:
|
||||
|
||||
```bash
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## Screens
|
||||
|
||||
- **Home**: Overview and quick actions
|
||||
- **Browse**: Explore available skills
|
||||
- **Recommend**: Get personalized recommendations
|
||||
- **Translate**: Convert skills between formats
|
||||
- **Context**: Manage project context
|
||||
- **Installed**: View and manage installed skills
|
||||
- **Sync**: Sync skills across agents
|
||||
- **Settings**: Configure skillkit
|
||||
|
||||
## Keyboard Shortcuts
|
||||
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| `↑/↓` | Navigate |
|
||||
| `Enter` | Select |
|
||||
| `Tab` | Switch focus |
|
||||
| `?` | Help |
|
||||
| `q` | Quit |
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/tui",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"description": "Terminal UI for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
+32
-10
@@ -9,8 +9,13 @@ import { Settings } from './screens/Settings.js';
|
||||
import { Recommend } from './screens/Recommend.js';
|
||||
import { Translate } from './screens/Translate.js';
|
||||
import { Context } from './screens/Context.js';
|
||||
import { Workflow } from './screens/Workflow.js';
|
||||
import { Execute } from './screens/Execute.js';
|
||||
import { History } from './screens/History.js';
|
||||
import { Marketplace } from './screens/Marketplace.js';
|
||||
import { Memory } from './screens/Memory.js';
|
||||
|
||||
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context';
|
||||
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context' | 'workflow' | 'execute' | 'history' | 'marketplace' | 'memory';
|
||||
|
||||
export function App() {
|
||||
const [screen, setScreen] = useState<Screen>('home');
|
||||
@@ -21,6 +26,22 @@ export function App() {
|
||||
const rows = stdout?.rows || 24;
|
||||
const showSidebar = cols >= 70;
|
||||
|
||||
const NAV_KEYS: Record<string, Screen> = {
|
||||
h: 'home',
|
||||
m: 'marketplace',
|
||||
b: 'browse',
|
||||
w: 'workflow',
|
||||
x: 'execute',
|
||||
y: 'history',
|
||||
r: 'recommend',
|
||||
t: 'translate',
|
||||
c: 'context',
|
||||
e: 'memory',
|
||||
i: 'installed',
|
||||
s: 'sync',
|
||||
',': 'settings',
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (input === 'q') {
|
||||
exit();
|
||||
@@ -30,14 +51,10 @@ export function App() {
|
||||
setScreen('home');
|
||||
return;
|
||||
}
|
||||
if (input === 'h') setScreen('home');
|
||||
if (input === 'b') setScreen('browse');
|
||||
if (input === 'l') setScreen('installed');
|
||||
if (input === 's') setScreen('sync');
|
||||
if (input === ',') setScreen('settings');
|
||||
if (input === 'r') setScreen('recommend');
|
||||
if (input === 't') setScreen('translate');
|
||||
if (input === 'c') setScreen('context');
|
||||
const targetScreen = NAV_KEYS[input];
|
||||
if (targetScreen) {
|
||||
setScreen(targetScreen);
|
||||
}
|
||||
});
|
||||
|
||||
const renderScreen = () => {
|
||||
@@ -50,6 +67,11 @@ export function App() {
|
||||
case 'recommend': return <Recommend cols={cols} rows={rows} />;
|
||||
case 'translate': return <Translate cols={cols} rows={rows} />;
|
||||
case 'context': return <Context cols={cols} rows={rows} />;
|
||||
case 'workflow': return <Workflow cols={cols} rows={rows} />;
|
||||
case 'execute': return <Execute cols={cols} rows={rows} />;
|
||||
case 'history': return <History cols={cols} rows={rows} />;
|
||||
case 'marketplace': return <Marketplace cols={cols} rows={rows} />;
|
||||
case 'memory': return <Memory cols={cols} rows={rows} />;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -64,7 +86,7 @@ export function App() {
|
||||
</Box>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>h Home b Browse r Rec t Trans c Ctx l List s Sync , Config q Quit</Text>
|
||||
<Text dimColor>h Home m Market b Browse i Inst w Wflow x Exec y Hist r Rec t Trans c Ctx e Mem s Sync , Cfg q Quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -8,15 +8,24 @@ interface SidebarProps {
|
||||
isCompact?: boolean;
|
||||
}
|
||||
|
||||
const NAV: { id: Screen; label: string }[] = [
|
||||
{ id: 'home', label: 'Home' },
|
||||
{ id: 'browse', label: 'Browse' },
|
||||
{ id: 'recommend', label: 'Recommend' },
|
||||
{ id: 'translate', label: 'Translate' },
|
||||
{ id: 'context', label: 'Context' },
|
||||
{ id: 'installed', label: 'List' },
|
||||
{ id: 'sync', label: 'Sync' },
|
||||
{ id: 'settings', label: 'Config' },
|
||||
const NAV: { id: Screen; label: string; key: string }[] = [
|
||||
// Discovery
|
||||
{ id: 'home', label: 'Home', key: 'h' },
|
||||
{ id: 'marketplace', label: 'Marketplace', key: 'm' },
|
||||
{ id: 'browse', label: 'Browse', key: 'b' },
|
||||
// Execution
|
||||
{ id: 'workflow', label: 'Workflows', key: 'w' },
|
||||
{ id: 'execute', label: 'Execute', key: 'x' },
|
||||
{ id: 'history', label: 'History', key: 'y' },
|
||||
// Tools
|
||||
{ id: 'recommend', label: 'Recommend', key: 'r' },
|
||||
{ id: 'translate', label: 'Translate', key: 't' },
|
||||
{ id: 'context', label: 'Context', key: 'c' },
|
||||
{ id: 'memory', label: 'Memory', key: 'e' },
|
||||
// Management
|
||||
{ id: 'installed', label: 'Installed', key: 'i' },
|
||||
{ id: 'sync', label: 'Sync', key: 's' },
|
||||
{ id: 'settings', label: 'Config', key: ',' },
|
||||
];
|
||||
|
||||
export function Sidebar({ screen }: SidebarProps) {
|
||||
@@ -24,6 +33,7 @@ export function Sidebar({ screen }: SidebarProps) {
|
||||
<Box flexDirection="column" width={14} borderStyle="single" paddingX={1}>
|
||||
<Text bold color={colors.primary}>SkillKit</Text>
|
||||
|
||||
{/* Discovery (0-2) */}
|
||||
{NAV.slice(0, 3).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
@@ -32,7 +42,8 @@ export function Sidebar({ screen }: SidebarProps) {
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{NAV.slice(3, 5).map((item) => (
|
||||
{/* Execution (3-5) */}
|
||||
{NAV.slice(3, 6).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
@@ -40,7 +51,17 @@ export function Sidebar({ screen }: SidebarProps) {
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{NAV.slice(5).map((item) => (
|
||||
{/* Tools (6-9) */}
|
||||
{NAV.slice(6, 10).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Management (10-12) */}
|
||||
{NAV.slice(10).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
|
||||
@@ -2,3 +2,4 @@ export { useSkills } from './useSkills.js';
|
||||
export { useMarketplace } from './useMarketplace.js';
|
||||
export { useKeyboard, useListNavigation } from './useKeyboard.js';
|
||||
export { useRecommend } from './useRecommend.js';
|
||||
export { useMemory } from './useMemory.js';
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
LearningStore,
|
||||
ObservationStore,
|
||||
getMemoryStatus,
|
||||
createMemoryInjector,
|
||||
type Learning,
|
||||
type Observation,
|
||||
type MemoryStatus,
|
||||
} from '@skillkit/core';
|
||||
|
||||
interface UseMemoryResult {
|
||||
learnings: Learning[];
|
||||
observations: Observation[];
|
||||
status: MemoryStatus | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
isGlobal: boolean;
|
||||
setIsGlobal: (isGlobal: boolean) => void;
|
||||
refresh: () => void;
|
||||
search: (query: string) => Learning[];
|
||||
deleteLearning: (id: string) => boolean;
|
||||
deleteObservation: (id: string) => boolean;
|
||||
}
|
||||
|
||||
export function useMemory(): UseMemoryResult {
|
||||
const [learnings, setLearnings] = useState<Learning[]>([]);
|
||||
const [observations, setObservations] = useState<Observation[]>([]);
|
||||
const [status, setStatus] = useState<MemoryStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isGlobal, setIsGlobal] = useState(false);
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Get memory status
|
||||
const memStatus = getMemoryStatus(projectPath);
|
||||
setStatus(memStatus);
|
||||
|
||||
// Load learnings
|
||||
const learningStore = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
setLearnings(learningStore.getAll());
|
||||
|
||||
// Load observations (project only)
|
||||
if (memStatus.hasObservations) {
|
||||
const obsStore = new ObservationStore(projectPath);
|
||||
setObservations(obsStore.getAll());
|
||||
} else {
|
||||
setObservations([]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load memory');
|
||||
setLearnings([]);
|
||||
setObservations([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectPath, isGlobal]);
|
||||
|
||||
const search = useCallback(
|
||||
(query: string): Learning[] => {
|
||||
if (!query.trim()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const injector = createMemoryInjector(projectPath);
|
||||
const results = injector.search(query, {
|
||||
includeGlobal: true,
|
||||
maxLearnings: 50,
|
||||
minRelevance: 0,
|
||||
});
|
||||
return results.map((r) => r.learning);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
[projectPath]
|
||||
);
|
||||
|
||||
const deleteLearning = useCallback(
|
||||
(id: string): boolean => {
|
||||
try {
|
||||
const store = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
const result = store.delete(id);
|
||||
if (result) {
|
||||
refresh();
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[projectPath, isGlobal, refresh]
|
||||
);
|
||||
|
||||
const deleteObservation = useCallback(
|
||||
(id: string): boolean => {
|
||||
try {
|
||||
const store = new ObservationStore(projectPath);
|
||||
const result = store.delete(id);
|
||||
if (result) {
|
||||
refresh();
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[projectPath, refresh]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return {
|
||||
learnings,
|
||||
observations,
|
||||
status,
|
||||
loading,
|
||||
error,
|
||||
isGlobal,
|
||||
setIsGlobal,
|
||||
refresh,
|
||||
search,
|
||||
deleteLearning,
|
||||
deleteObservation,
|
||||
};
|
||||
}
|
||||
@@ -4,14 +4,12 @@ import {
|
||||
ContextManager,
|
||||
type ScoredSkill,
|
||||
type ProjectProfile,
|
||||
type SkillIndex,
|
||||
type SkillSummary,
|
||||
loadIndex as loadIndexFromCache,
|
||||
saveIndex,
|
||||
buildSkillIndex,
|
||||
isIndexStale,
|
||||
KNOWN_SKILL_REPOS,
|
||||
} from '@skillkit/core';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const INDEX_PATH = join(process.env.HOME || '~', '.skillkit', 'index.json');
|
||||
const INDEX_CACHE_HOURS = 24;
|
||||
|
||||
interface UseRecommendResult {
|
||||
recommendations: ScoredSkill[];
|
||||
@@ -26,164 +24,6 @@ interface UseRecommendResult {
|
||||
searchResults: ScoredSkill[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample skills for the index (matches CLI implementation)
|
||||
*/
|
||||
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,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function useRecommend(projectPath: string = process.cwd()): UseRecommendResult {
|
||||
const [recommendations, setRecommendations] = useState<ScoredSkill[]>([]);
|
||||
const [searchResults, setSearchResults] = useState<ScoredSkill[]>([]);
|
||||
@@ -194,31 +34,22 @@ export function useRecommend(projectPath: string = process.cwd()): UseRecommendR
|
||||
const [indexStatus, setIndexStatus] = useState<'missing' | 'stale' | 'fresh'>('missing');
|
||||
const [engine] = useState(() => new RecommendationEngine());
|
||||
|
||||
const loadIndex = useCallback((): SkillIndex | null => {
|
||||
if (!existsSync(INDEX_PATH)) {
|
||||
const loadIndex = useCallback(() => {
|
||||
const index = loadIndexFromCache();
|
||||
|
||||
if (!index) {
|
||||
setIndexStatus('missing');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(INDEX_PATH, 'utf-8');
|
||||
const index = JSON.parse(content) as SkillIndex;
|
||||
|
||||
// Check if index is stale
|
||||
const lastUpdated = new Date(index.lastUpdated);
|
||||
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
|
||||
|
||||
if (hoursSinceUpdate > INDEX_CACHE_HOURS) {
|
||||
setIndexStatus('stale');
|
||||
} else {
|
||||
setIndexStatus('fresh');
|
||||
}
|
||||
|
||||
return index;
|
||||
} catch {
|
||||
setIndexStatus('missing');
|
||||
return null;
|
||||
// Check if index is stale
|
||||
if (isIndexStale(index)) {
|
||||
setIndexStatus('stale');
|
||||
} else {
|
||||
setIndexStatus('fresh');
|
||||
}
|
||||
|
||||
return index;
|
||||
}, []);
|
||||
|
||||
const getProjectProfile = useCallback((): ProjectProfile | null => {
|
||||
@@ -293,42 +124,24 @@ export function useRecommend(projectPath: string = process.cwd()): UseRecommendR
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
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,
|
||||
},
|
||||
],
|
||||
};
|
||||
// Fetch skills from known GitHub repositories
|
||||
buildSkillIndex(KNOWN_SKILL_REPOS)
|
||||
.then(({ index, errors }) => {
|
||||
if (errors.length > 0) {
|
||||
console.warn('Index update warnings:', errors);
|
||||
}
|
||||
|
||||
// Save index
|
||||
const indexDir = join(process.env.HOME || '~', '.skillkit');
|
||||
if (!existsSync(indexDir)) {
|
||||
mkdirSync(indexDir, { recursive: true });
|
||||
}
|
||||
// Save the fetched index
|
||||
saveIndex(index);
|
||||
setIndexStatus('fresh');
|
||||
|
||||
writeFileSync(INDEX_PATH, JSON.stringify(sampleIndex, null, 2));
|
||||
setIndexStatus('fresh');
|
||||
|
||||
// Reload recommendations
|
||||
loadRecommendations();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update index');
|
||||
setLoading(false);
|
||||
}
|
||||
// Reload recommendations with new index
|
||||
loadRecommendations();
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update index');
|
||||
setLoading(false);
|
||||
});
|
||||
}, [loadRecommendations]);
|
||||
|
||||
const search = useCallback((query: string) => {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { createSessionManager, type SessionState, type CurrentExecution } from '@skillkit/core';
|
||||
|
||||
interface Props {
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Execute({ rows = 24 }: Props) {
|
||||
const [session, setSession] = useState<SessionState | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
|
||||
useEffect(() => {
|
||||
loadSession();
|
||||
// Poll for updates
|
||||
const interval = setInterval(loadSession, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const loadSession = () => {
|
||||
try {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
const state = manager.get();
|
||||
setSession(state);
|
||||
} catch {
|
||||
setSession(null);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, _key) => {
|
||||
if (input === 'r') loadSession();
|
||||
else if (input === 'p' && session?.currentExecution?.status === 'running') {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
manager.pause();
|
||||
loadSession();
|
||||
}
|
||||
else if (input === 'c' && session?.currentExecution?.status === 'paused') {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
manager.resume();
|
||||
loadSession();
|
||||
}
|
||||
});
|
||||
|
||||
const renderExecution = (exec: CurrentExecution) => {
|
||||
const completedTasks = exec.tasks.filter(t => t.status === 'completed').length;
|
||||
const failedTasks = exec.tasks.filter(t => t.status === 'failed').length;
|
||||
const progress = exec.totalSteps > 0 ? Math.round((completedTasks / exec.totalSteps) * 100) : 0;
|
||||
|
||||
const statusColor = exec.status === 'running' ? 'yellow' :
|
||||
exec.status === 'completed' ? 'green' :
|
||||
exec.status === 'paused' ? 'blue' :
|
||||
exec.status === 'failed' ? 'red' : 'white';
|
||||
|
||||
const visibleTasks = exec.tasks.slice(0, maxVisible);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text bold>{exec.skillName}</Text>
|
||||
<Text>Source: <Text dimColor>{exec.skillSource}</Text></Text>
|
||||
<Text>Status: <Text color={statusColor}>{exec.status.toUpperCase()}</Text></Text>
|
||||
<Text>Progress: {completedTasks}/{exec.totalSteps} ({progress}%)</Text>
|
||||
|
||||
{/* Progress bar */}
|
||||
<Box marginY={1}>
|
||||
<Text>[</Text>
|
||||
<Text color="green">{'█'.repeat(Math.floor(progress / 5))}</Text>
|
||||
<Text dimColor>{'░'.repeat(20 - Math.floor(progress / 5))}</Text>
|
||||
<Text>]</Text>
|
||||
</Box>
|
||||
|
||||
{/* Task list */}
|
||||
<Text bold>Tasks:</Text>
|
||||
{visibleTasks.map((task, i) => {
|
||||
const icon = task.status === 'completed' ? symbols.success :
|
||||
task.status === 'failed' ? symbols.error :
|
||||
task.status === 'in_progress' ? symbols.warning :
|
||||
task.status === 'paused' ? symbols.info :
|
||||
symbols.bullet;
|
||||
const color = task.status === 'completed' ? 'green' :
|
||||
task.status === 'failed' ? 'red' :
|
||||
task.status === 'in_progress' ? 'yellow' :
|
||||
task.status === 'paused' ? 'blue' : 'white';
|
||||
return (
|
||||
<Text key={task.id || i} color={color}>
|
||||
{icon} {task.name} {task.error && <Text dimColor>({task.error})</Text>}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{exec.tasks.length > maxVisible && (
|
||||
<Text dimColor> ... and {exec.tasks.length - maxVisible} more</Text>
|
||||
)}
|
||||
|
||||
{failedTasks > 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{failedTasks} task(s) failed</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>EXECUTION MONITOR</Text>
|
||||
|
||||
{loading && <Text>Loading session...</Text>}
|
||||
|
||||
{!loading && !session?.currentExecution && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No active execution.</Text>
|
||||
<Text dimColor>Run a skill with: skillkit run {'<skill>'}</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{!loading && session?.currentExecution && renderExecution(session.currentExecution)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{session?.currentExecution?.status === 'running' ? 'p=pause ' : ''}
|
||||
{session?.currentExecution?.status === 'paused' ? 'c=continue ' : ''}
|
||||
r=refresh q=quit
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { createSessionManager, type ExecutionHistory } from '@skillkit/core';
|
||||
|
||||
interface Props {
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function History({ rows = 24 }: Props) {
|
||||
const [history, setHistory] = useState<ExecutionHistory[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 8);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), history.length - maxVisible));
|
||||
const visible = history.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, []);
|
||||
|
||||
const loadHistory = () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
const h = manager.getHistory(50);
|
||||
setHistory(h);
|
||||
} catch {
|
||||
setHistory([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
if (key.upArrow) {
|
||||
setSel(i => Math.max(0, i - 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (key.downArrow) {
|
||||
setSel(i => Math.min(history.length - 1, i + 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (input === 'r') loadHistory();
|
||||
else if (key.return) setExpanded(e => !e);
|
||||
});
|
||||
|
||||
const formatDuration = (ms: number): string => {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
return `${(ms / 60000).toFixed(1)}m`;
|
||||
};
|
||||
|
||||
const formatDate = (iso: string): string => {
|
||||
const d = new Date(iso);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - d.getTime();
|
||||
|
||||
if (diff < 60000) return 'Just now';
|
||||
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
|
||||
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
|
||||
return d.toLocaleDateString();
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>EXECUTION HISTORY</Text>
|
||||
<Text dimColor>{history.length} execution(s)</Text>
|
||||
|
||||
{loading && <Text>Loading history...</Text>}
|
||||
|
||||
{!loading && history.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No execution history.</Text>
|
||||
<Text dimColor>Run a skill with: skillkit run {'<skill>'}</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{!loading && history.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((entry, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const icon = entry.status === 'completed' ? symbols.success :
|
||||
entry.status === 'failed' ? symbols.error :
|
||||
symbols.warning;
|
||||
const color = entry.status === 'completed' ? 'green' :
|
||||
entry.status === 'failed' ? 'red' : 'yellow';
|
||||
|
||||
return (
|
||||
<Box key={idx} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}<Text color={color}>{icon}</Text> {entry.skillName.padEnd(25)} {formatDate(entry.completedAt).padEnd(12)} {formatDuration(entry.durationMs)}
|
||||
</Text>
|
||||
{isSel && expanded && (
|
||||
<Box flexDirection="column" marginLeft={3}>
|
||||
<Text dimColor>Source: {entry.skillSource}</Text>
|
||||
<Text dimColor>Status: {entry.status}</Text>
|
||||
{entry.commits.length > 0 && (
|
||||
<Text dimColor>Commits: {entry.commits.join(', ')}</Text>
|
||||
)}
|
||||
{entry.filesModified.length > 0 && (
|
||||
<Text dimColor>Files: {entry.filesModified.length} modified</Text>
|
||||
)}
|
||||
{entry.error && (
|
||||
<Text color="red">Error: {entry.error}</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < history.length && <Text dimColor> ↓ {history.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=expand r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
|
||||
interface MarketplaceSkill {
|
||||
name: string;
|
||||
description: string;
|
||||
source: string;
|
||||
repo: string;
|
||||
tags?: string[];
|
||||
stars?: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
// Known skill repositories to aggregate from
|
||||
const SKILL_SOURCES = [
|
||||
{ owner: 'composioHQ', repo: 'awesome-claude-code-skills', name: 'Composio Curated' },
|
||||
{ owner: 'anthropics', repo: 'courses', name: 'Anthropic Official' },
|
||||
];
|
||||
|
||||
export function Marketplace({ rows = 24 }: Props) {
|
||||
const [skills, setSkills] = useState<MarketplaceSkill[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const [installing, setInstalling] = useState<string | null>(null);
|
||||
|
||||
const filtered = skills.filter(s =>
|
||||
s.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.description.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.tags?.some(t => t.toLowerCase().includes(search.toLowerCase()))
|
||||
);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), filtered.length - maxVisible));
|
||||
const visible = filtered.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadMarketplace();
|
||||
}, []);
|
||||
|
||||
const loadMarketplace = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Aggregate skills from known sources
|
||||
const allSkills: MarketplaceSkill[] = [];
|
||||
|
||||
for (const source of SKILL_SOURCES) {
|
||||
try {
|
||||
// Try to fetch skill index from GitHub
|
||||
const indexUrl = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/main/skills.json`;
|
||||
const response = await fetch(indexUrl);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (Array.isArray(data)) {
|
||||
allSkills.push(...data.map((s: Record<string, unknown>) => ({
|
||||
name: String(s.name || 'Unknown'),
|
||||
description: String(s.description || ''),
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
tags: Array.isArray(s.tags) ? s.tags as string[] : [],
|
||||
stars: typeof s.stars === 'number' ? s.stars : undefined,
|
||||
})));
|
||||
}
|
||||
} else {
|
||||
// Fallback: add the repo itself as a skill source
|
||||
allSkills.push({
|
||||
name: source.repo,
|
||||
description: `Skills from ${source.name}`,
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Add repo as fallback
|
||||
allSkills.push({
|
||||
name: source.repo,
|
||||
description: `Skills from ${source.name}`,
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add some example skills for demo
|
||||
if (allSkills.length === 0) {
|
||||
allSkills.push(
|
||||
{ name: 'typescript-strict', description: 'Enable strict TypeScript mode', source: 'Built-in', repo: 'skillkit/skills', tags: ['typescript', 'config'] },
|
||||
{ name: 'eslint-setup', description: 'Set up ESLint with recommended rules', source: 'Built-in', repo: 'skillkit/skills', tags: ['eslint', 'linting'] },
|
||||
{ name: 'prettier-config', description: 'Configure Prettier formatting', source: 'Built-in', repo: 'skillkit/skills', tags: ['prettier', 'formatting'] },
|
||||
{ name: 'jest-setup', description: 'Set up Jest testing framework', source: 'Built-in', repo: 'skillkit/skills', tags: ['jest', 'testing'] },
|
||||
{ name: 'nextjs-auth', description: 'Add authentication to Next.js', source: 'Community', repo: 'community/skills', tags: ['nextjs', 'auth'] },
|
||||
);
|
||||
}
|
||||
|
||||
setSkills(allSkills);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load marketplace');
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || installing) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(filtered.length - 1, i + 1));
|
||||
else if (input === 'r') loadMarketplace();
|
||||
else if (input === '/') setSearch('');
|
||||
else if (key.backspace || key.delete) setSearch(s => s.slice(0, -1));
|
||||
else if (key.return && filtered[sel]) {
|
||||
setInstalling(filtered[sel].name);
|
||||
// Simulate installation
|
||||
setTimeout(() => setInstalling(null), 1500);
|
||||
}
|
||||
else if (input.length === 1 && /[a-zA-Z0-9-_]/.test(input)) {
|
||||
setSearch(s => s + input);
|
||||
setSel(0);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SKILL MARKETPLACE</Text>
|
||||
<Text dimColor>{skills.length} skills from {SKILL_SOURCES.length} sources</Text>
|
||||
|
||||
{search && (
|
||||
<Text>Search: <Text color="yellow">{search}</Text> ({filtered.length} results)</Text>
|
||||
)}
|
||||
|
||||
{loading && <Text>Loading marketplace...</Text>}
|
||||
{error && <Text color="red">{error}</Text>}
|
||||
{installing && <Text color="yellow">Installing {installing}...</Text>}
|
||||
|
||||
{!loading && !installing && filtered.length === 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>No skills found{search ? ` matching "${search}"` : ''}.</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{!loading && !installing && filtered.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((skill, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={`${skill.repo}/${skill.name}`} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {skill.name.padEnd(25)} <Text dimColor>{skill.source}</Text>
|
||||
</Text>
|
||||
{isSel && (
|
||||
<Box flexDirection="column" marginLeft={3}>
|
||||
<Text dimColor>{skill.description}</Text>
|
||||
{skill.tags && skill.tags.length > 0 && (
|
||||
<Text dimColor>Tags: {skill.tags.join(', ')}</Text>
|
||||
)}
|
||||
<Text dimColor>Repo: {skill.repo}</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < filtered.length && <Text dimColor> ↓ {filtered.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=install type=search r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
ObservationStore,
|
||||
LearningStore,
|
||||
getMemoryStatus,
|
||||
getMemoryPaths,
|
||||
createMemoryInjector,
|
||||
type Learning,
|
||||
} from '@skillkit/core';
|
||||
|
||||
interface Props {
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
type Tab = 'learnings' | 'observations' | 'search';
|
||||
|
||||
export function Memory({ rows = 24 }: Props) {
|
||||
const [tab, setTab] = useState<Tab>('learnings');
|
||||
const [learnings, setLearnings] = useState<Learning[]>([]);
|
||||
const [observationCount, setObservationCount] = useState(0);
|
||||
const [globalCount, setGlobalCount] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<Learning[]>([]);
|
||||
const [isGlobal, setIsGlobal] = useState(false);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const currentList = tab === 'search' ? searchResults : learnings;
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), currentList.length - maxVisible));
|
||||
const visible = currentList.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadMemory();
|
||||
}, [isGlobal]);
|
||||
|
||||
const loadMemory = () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const projectPath = process.cwd();
|
||||
const status = getMemoryStatus(projectPath);
|
||||
|
||||
// Load learnings
|
||||
const store = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
setLearnings(store.getAll());
|
||||
|
||||
// Get counts
|
||||
if (status.hasObservations) {
|
||||
const obsStore = new ObservationStore(projectPath);
|
||||
setObservationCount(obsStore.count());
|
||||
} else {
|
||||
setObservationCount(0);
|
||||
}
|
||||
|
||||
if (status.hasGlobalLearnings) {
|
||||
const globalStore = new LearningStore('global');
|
||||
setGlobalCount(globalStore.count());
|
||||
} else {
|
||||
setGlobalCount(0);
|
||||
}
|
||||
} catch {
|
||||
setLearnings([]);
|
||||
setObservationCount(0);
|
||||
setGlobalCount(0);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleSearch = (query: string) => {
|
||||
if (!query.trim()) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const projectPath = process.cwd();
|
||||
const injector = createMemoryInjector(projectPath);
|
||||
const results = injector.search(query, {
|
||||
includeGlobal: true,
|
||||
maxLearnings: 20,
|
||||
minRelevance: 0,
|
||||
});
|
||||
setSearchResults(results.map(r => r.learning));
|
||||
} catch {
|
||||
setSearchResults([]);
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
// Tab navigation
|
||||
if (input === '1') { setTab('learnings'); setSel(0); setExpanded(false); }
|
||||
else if (input === '2') { setTab('observations'); setSel(0); setExpanded(false); }
|
||||
else if (input === '3') { setTab('search'); setSel(0); setExpanded(false); }
|
||||
|
||||
// List navigation
|
||||
else if (key.upArrow) {
|
||||
setSel(i => Math.max(0, i - 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (key.downArrow) {
|
||||
setSel(i => Math.min(currentList.length - 1, i + 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
|
||||
// Actions (use 'f' for refresh to avoid conflict with global 'r' for Recommend)
|
||||
else if (input === 'f') loadMemory();
|
||||
else if (input === 'g') setIsGlobal(g => !g);
|
||||
else if (key.return) setExpanded(e => !e);
|
||||
|
||||
// Search input (basic)
|
||||
else if (tab === 'search' && input && input.length === 1 && !key.ctrl && !key.meta) {
|
||||
const newQuery = searchQuery + input;
|
||||
setSearchQuery(newQuery);
|
||||
handleSearch(newQuery);
|
||||
}
|
||||
else if (tab === 'search' && key.backspace) {
|
||||
const newQuery = searchQuery.slice(0, -1);
|
||||
setSearchQuery(newQuery);
|
||||
handleSearch(newQuery);
|
||||
}
|
||||
});
|
||||
|
||||
const ONE_MINUTE = 60_000;
|
||||
const ONE_HOUR = 3_600_000;
|
||||
const ONE_DAY = 86_400_000;
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
const diff = Date.now() - d.getTime();
|
||||
|
||||
if (diff < ONE_MINUTE) return 'Just now';
|
||||
if (diff < ONE_HOUR) return `${Math.floor(diff / ONE_MINUTE)}m ago`;
|
||||
if (diff < ONE_DAY) return `${Math.floor(diff / ONE_HOUR)}h ago`;
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function formatEffectiveness(eff?: number): string {
|
||||
if (eff === undefined) return ' -';
|
||||
return eff.toString().padStart(3) + '%';
|
||||
}
|
||||
|
||||
function getEffectivenessColor(eff?: number): string | undefined {
|
||||
if (eff === undefined) return undefined;
|
||||
if (eff >= 70) return 'green';
|
||||
if (eff >= 40) return 'yellow';
|
||||
return 'red';
|
||||
}
|
||||
|
||||
const renderLearnings = () => (
|
||||
<Box flexDirection="column">
|
||||
{currentList.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No learnings found.</Text>
|
||||
<Text dimColor>Run skills to capture learnings, or add manually:</Text>
|
||||
<Text dimColor> skillkit memory add --title "..." --content "..."</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{currentList.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> {symbols.arrowUp} {start} more</Text>}
|
||||
{visible.map((learning, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
|
||||
return (
|
||||
<Box key={learning.id} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}
|
||||
<Text color={colors.primary}>{symbols.bullet}</Text>
|
||||
{' '}{learning.title.slice(0, 35).padEnd(35)}{' '}
|
||||
<Text dimColor>{learning.tags.slice(0, 2).join(', ').slice(0, 15).padEnd(15)}</Text>
|
||||
{' '}<Text color={getEffectivenessColor(learning.effectiveness)}>{formatEffectiveness(learning.effectiveness)}</Text>
|
||||
{' '}<Text dimColor>{formatDate(learning.updatedAt)}</Text>
|
||||
</Text>
|
||||
{isSel && expanded && (
|
||||
<Box flexDirection="column" marginLeft={3} marginY={1}>
|
||||
<Text dimColor>ID: {learning.id.slice(0, 8)}</Text>
|
||||
<Text dimColor>Scope: {learning.scope}</Text>
|
||||
<Text dimColor>Source: {learning.source}</Text>
|
||||
<Text dimColor>Tags: {learning.tags.join(', ')}</Text>
|
||||
{learning.frameworks && learning.frameworks.length > 0 && (
|
||||
<Text dimColor>Frameworks: {learning.frameworks.join(', ')}</Text>
|
||||
)}
|
||||
<Text dimColor>Uses: {learning.useCount}</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text wrap="wrap">{learning.content.slice(0, 300)}{learning.content.length > 300 ? '...' : ''}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < currentList.length && (
|
||||
<Text dimColor> {symbols.arrowDown} {currentList.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
|
||||
const renderObservations = () => (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text>Session Observations: <Text bold color={colors.primary}>{observationCount}</Text></Text>
|
||||
<Text dimColor>Observations are raw captures from skill execution.</Text>
|
||||
|
||||
{observationCount > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text>Compress observations into learnings:</Text>
|
||||
<Text dimColor> skillkit memory compress</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{observationCount >= 50 && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">{symbols.warning} You have many uncompressed observations.</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Observations are stored at:</Text>
|
||||
</Box>
|
||||
<Text dimColor> {getMemoryPaths(process.cwd()).observationsFile}</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
const renderSearch = () => (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text>Search: </Text>
|
||||
<Text color={colors.primary}>{searchQuery}</Text>
|
||||
<Text color={colors.secondary}>_</Text>
|
||||
</Box>
|
||||
|
||||
{searchQuery && searchResults.length === 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>No results found for "{searchQuery}"</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{searchResults.length > 0 && renderLearnings()}
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>MEMORY</Text>
|
||||
<Text dimColor>
|
||||
{isGlobal ? 'Global' : 'Project'}: {learnings.length} learning(s)
|
||||
{!isGlobal && globalCount > 0 && <Text> | Global: {globalCount}</Text>}
|
||||
</Text>
|
||||
|
||||
{/* Tabs */}
|
||||
<Box marginTop={1}>
|
||||
<Text inverse={tab === 'learnings'}>[1] Learnings</Text>
|
||||
<Text> </Text>
|
||||
<Text inverse={tab === 'observations'}>[2] Observations</Text>
|
||||
<Text> </Text>
|
||||
<Text inverse={tab === 'search'}>[3] Search</Text>
|
||||
</Box>
|
||||
|
||||
{loading && <Box marginTop={1}><Text>Loading...</Text></Box>}
|
||||
|
||||
{!loading && tab === 'learnings' && renderLearnings()}
|
||||
{!loading && tab === 'observations' && renderObservations()}
|
||||
{!loading && tab === 'search' && renderSearch()}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
Enter=expand g=toggle global f=refresh 1-3=tabs
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { listWorkflows, type Workflow as WorkflowType } from '@skillkit/core';
|
||||
|
||||
interface Props {
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Workflow({ rows = 24 }: Props) {
|
||||
const [workflows, setWorkflows] = useState<WorkflowType[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [running, setRunning] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 8);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), workflows.length - maxVisible));
|
||||
const visible = workflows.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadWorkflows();
|
||||
}, []);
|
||||
|
||||
const loadWorkflows = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const wfs = listWorkflows(process.cwd());
|
||||
setWorkflows(wfs);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load workflows');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || running) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(workflows.length - 1, i + 1));
|
||||
else if (input === 'r') loadWorkflows();
|
||||
else if (key.return && workflows[sel]) {
|
||||
// Simulate running workflow
|
||||
setRunning(workflows[sel].name);
|
||||
setTimeout(() => setRunning(null), 2000);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>WORKFLOWS</Text>
|
||||
<Text dimColor>{workflows.length} workflow(s) found</Text>
|
||||
|
||||
{loading && <Text>Loading workflows...</Text>}
|
||||
{error && <Text color="red">{error}</Text>}
|
||||
{running && <Text color="yellow">Running: {running}...</Text>}
|
||||
|
||||
{!loading && !running && workflows.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No workflows found.</Text>
|
||||
<Text dimColor>Create one with: skillkit workflow create</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{!loading && !running && workflows.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((wf, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={wf.name} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {wf.name}
|
||||
</Text>
|
||||
{isSel && wf.description && (
|
||||
<Text dimColor> {wf.description}</Text>
|
||||
)}
|
||||
{isSel && (
|
||||
<Text dimColor> {wf.waves.length} wave(s), {wf.waves.reduce((acc, w) => acc + w.skills.length, 0)} skill(s)</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < workflows.length && <Text dimColor> ↓ {workflows.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=run r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -6,3 +6,8 @@ export { Settings } from './Settings.js';
|
||||
export { Recommend } from './Recommend.js';
|
||||
export { Translate } from './Translate.js';
|
||||
export { Context } from './Context.js';
|
||||
export { Memory } from './Memory.js';
|
||||
export { Workflow } from './Workflow.js';
|
||||
export { Execute } from './Execute.js';
|
||||
export { History } from './History.js';
|
||||
export { Marketplace } from './Marketplace.js';
|
||||
|
||||
@@ -19,6 +19,12 @@ export const symbols = {
|
||||
check: chalk.white('✓'),
|
||||
star: '★',
|
||||
spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
|
||||
arrowUp: '↑',
|
||||
arrowDown: '↓',
|
||||
success: '✓',
|
||||
error: '✗',
|
||||
warning: '⚠',
|
||||
info: 'ℹ',
|
||||
};
|
||||
|
||||
export const logo = `
|
||||
|
||||
Generated
+3
@@ -103,6 +103,9 @@ importers:
|
||||
ora:
|
||||
specifier: ^8.1.0
|
||||
version: 8.2.0
|
||||
yaml:
|
||||
specifier: ^2.7.0
|
||||
version: 2.8.2
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.10.5
|
||||
|
||||
@@ -38,6 +38,7 @@ const POPULAR_REPOS: RepoInfo[] = [
|
||||
{ source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' },
|
||||
{ source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' },
|
||||
{ source: 'intellectronica/agent-skills', name: 'Context7' },
|
||||
{ source: 'alirezarezvani/claude-skills', name: 'Alireza Rezvani' },
|
||||
];
|
||||
|
||||
interface FetchedSkill {
|
||||
|
||||
Reference in New Issue
Block a user