feat: add session memory system for cross-agent learning (#3)

* feat: add session memory system for cross-agent learning

Implements a lightweight, local-first memory system that works across
all 17 AI coding agents. Key features:

- YAML-based storage (no databases or external services)
- Three memory layers: Session, Project, and Global
- AI-powered compression of observations into learnings
- Cross-agent memory injection with relevance matching
- Progressive disclosure for token efficiency

Core modules:
- ObservationStore: Capture raw session observations
- LearningStore: Persist compressed learnings
- MemoryCompressor: AI/rule-based compression engine
- MemoryInjector: Context-aware memory retrieval
- MemoryObserver: Automatic observation capture

CLI commands (skillkit memory):
- status, search, list, show, compress, export
- import, clear, add, rate, config

TUI integration:
- New Memory screen with tabs (Learnings/Observations/Search)
- useMemory hook for state management
- Updated navigation and keybindings

Code quality improvements:
- Replaced nested ternaries with explicit functions
- Added named constants for magic numbers
- Simplified navigation with lookup map

* feat: add marketplace, testing, CI/CD, workflows, and fix dry-run bug

New Features:
- Skill Marketplace: Aggregates skills from GitHub repos with caching
- Skill Testing Framework: 18+ assertion types for skill validation
- CI/CD Integration: Templates for GitHub Actions, GitLab CI, CircleCI
- Workflow Orchestration: Wave-based parallel skill execution
- Session Management: Pause/resume support with state persistence
- Agent Execution: CLI spawning for claude/codex/gemini/opencode/goose

New CLI Commands:
- skillkit marketplace - Browse and install from marketplace
- skillkit test - Run skill tests with assertions
- skillkit run - Execute skills with orchestration
- skillkit status - Show session state
- skillkit pause/resume - Session management
- skillkit workflow - Workflow management

New TUI Screens:
- Marketplace browser with search
- History viewer with session details
- Workflow management screen

Bug Fix:
- Fixed dry-run mode in memory compress command (Devin review)
  The --dry-run flag now properly prevents storing learnings

* fix: add missing yaml dependency to @skillkit/cli

* chore: update pnpm-lock.yaml

* fix: address 7 bugs identified by Devin code review

- Fix MemoryIndexStore ignoring isGlobal flag (memory-index.ts)
- Fix ESM runtime crash using require('yaml') in test runner (runner.ts)
- Fix ESM runtime crash using require('node:fs') in MarketplaceAggregator (aggregator.ts)
- Fix ESM runtime crash using require('node:fs') in SessionManager (manager.ts)
- Fix memory rate command parsing rating from --content instead of positional arg (memory.ts)
- Fix SkillExecutionEngine emitting failed status for paused executions (engine.ts)
- Fix run command misclassifying directories as skill markdown files (run.ts)

* fix: address CodeRabbit/Devin review issues (batch 2)

- Fix resume skipping checkpoint handling in engine.ts
- Add paused status guard before completeExecution call
- Fix NaN% progress when totalSteps=0 in Execute.tsx
- Fix effectiveness ?? instead of || to preserve 0% values in compressor.ts
- Clear cache on source change in aggregator.ts addSource/removeSource

* fix: address critical and major CodeRabbit/Devin issues (batch 3)

Security fixes:
- Remove shell: true from spawn to prevent shell injection (agents.ts)
- Add safe regex test with ReDoS protection (engine.ts)
- Add security warning for verification commands (engine.ts)

Bug fixes:
- Fix global memory index path to use ~/.skillkit/ (compressor.ts, memory-index.ts)
- Add task_complete events and verification to resumeExecution (engine.ts)
- Handle absolute URLs in skill entries (aggregator.ts)
- Implement actual port availability check (runner.ts)
- Remove invalid JUnit report format (templates.ts)
- Add crash guard to workflow list command (workflow/list.ts)

* fix: address remaining CodeRabbit/Devin issues (batch 4)

- ReDoS protection: Add pattern validator to reject dangerous regex patterns
  (nested quantifiers, overlapping alternations, excessive quantifiers)
- Add missing 'cancelled' status message in execution engine
- Make completedAt/durationMs optional in TaskExecutionResult
- Fix tag filter to skip untagged tests when tags are specified
- Improve error-solution matching: require keyword similarity + solution indicator
- Validate --limit and sanitize --tags in memory/marketplace CLI commands
- Guard against missing arrays when importing YAML learnings
- Escape YAML frontmatter values to prevent invalid output
- Preserve original learning source when merging learnings
- Fix keyword double-counting in memory index search
- Normalize keywords by stripping punctuation for better matching
This commit is contained in:
Rohit Ghumare
2026-01-23 18:12:15 +00:00
committed by GitHub
parent bc12775e0e
commit d3ffb79512
68 changed files with 15504 additions and 464 deletions
+8
View File
@@ -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';
+250
View File
@@ -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;
}
}
+872
View File
@@ -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');
}
}
+71
View File
@@ -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;
}
}
}
+66 -223
View File
@@ -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,
},
];
}
+83
View File
@@ -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;
}
}
}
+336
View File
@@ -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`;
}
}
+174
View File
@@ -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`;
}
}
+288
View File
@@ -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;
}
}
+204
View File
@@ -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.'));
}
}