feat: add skillkit doctor command and enhance skillkit status (#64)

* feat: add `skillkit doctor` command and enhance `skillkit status`

- New `skillkit doctor` command with 10 health checks across 3 categories
  (environment, configuration, skills) with --json and --fix flags
- Enhanced `skillkit status` shows project overview dashboard when no
  active session exists instead of bare "No active session found" message
- Overview includes agent, config, version, skills count, recent history

* feat: add skill activity log, session snapshots, and session explain

Three new session intelligence features:

- Activity Log: tracks which skills were active per git commit
  (`skillkit activity` with --skill, --limit, --json flags)
- Session Snapshots: save/restore named snapshots of session state
  (`skillkit session snapshot save|restore|list|delete`)
- Session Explain: structured summary of current session
  (`skillkit session explain` with --json, --no-git flags)

Includes path traversal protection on snapshot names, YAML validation
on parsed activity data, and robust error handling on snapshot restore.

983 tests passing (942 core + 41 CLI including 14 E2E tests).

* feat: add issue planner - generate plans from GitHub Issues

New `skillkit issue plan` and `skillkit issue list` commands that
fetch GitHub Issues via `gh` CLI and generate StructuredPlans.
Parses checkboxes, file mentions, and labels from issue body.
29 new tests, all passing.

* fix: address CodeRabbit review suggestions for PR #64

- doctor.ts: use execFileSync, typed AgentType, remove as-any casts
- activity.ts: validate parseInt with radix and NaN guard
- issue.ts: wrap JSON.parse in try/catch for gh CLI output
- issue-planner.ts: guard JSON.parse, fix includeTests no-op ternary,
  remove duplicate IssuePlanMetadata (import from types.ts)
- status.ts: typed StatusOverview interface, remove as-any casts
- snapshot-manager.ts: align observations param with SessionSnapshot type
- session.ts: proper type mapping for observations (no double cast)
- activity-log.ts: min-length guard for SHA prefix match
- e2e tests: use top-level imports instead of inline require()
- commands.test.ts: add assertions for DoctorCommand, IssuePlanCommand,
  IssueListCommand

* fix: address review feedback from CodeRabbit and Devin

- Include test step in no-checklist fallback when includeTests is true
- Restore observations from snapshot in SessionSnapshotRestoreCommand

* fix: address remaining CodeRabbit and Devin review feedback

- doctor.ts: Use getAdapter() per AgentType instead of getAllAdapters()
  spread (which destroys prototype methods like isDetected)
- doctor.ts: Use getGlobalSkillsDir() from AGENT_CONFIG instead of
  hardcoded path formula
- session-explainer.ts: Defensively default state.history and
  state.decisions to empty arrays
- session-explainer.ts: Use loadConfig().agent with skillSource fallback
  instead of always using skillSource as agent name
- observation-store.ts: Add static readAll() that reads observations
  without sessionId mismatch clearing
- session.ts: Use ObservationStore.readAll() for snapshot save to avoid
  empty observations due to sessionId mismatch
This commit is contained in:
Rohit Ghumare
2026-02-11 20:26:51 +00:00
committed by GitHub
parent 344f081664
commit aafa086314
25 changed files with 3451 additions and 16 deletions
+8
View File
@@ -246,6 +246,14 @@ skillkit find <query> # Quick search
skillkit scan <path> # Security scan for skills
```
### Issue Planner
```bash
skillkit issue plan "#42" # Plan from GitHub Issue
skillkit issue plan owner/repo#42 # Cross-repo plan
skillkit issue list # List open issues
```
### Advanced
```bash
+19
View File
@@ -86,6 +86,12 @@ import {
SessionNoteCommand,
SessionCompleteCommand,
SessionInProgressCommand,
SessionSnapshotSaveCommand,
SessionSnapshotRestoreCommand,
SessionSnapshotListCommand,
SessionSnapshotDeleteCommand,
SessionExplainCommand,
ActivityCommand,
ProfileCommand,
ProfileListCommand,
ProfileCreateCommand,
@@ -104,11 +110,14 @@ import {
SkillMdCheckCommand,
ServeCommand,
ScanCommand,
DoctorCommand,
SaveCommand,
AgentsMdCommand,
AgentsMdInitCommand,
AgentsMdSyncCommand,
AgentsMdShowCommand,
IssuePlanCommand,
IssueListCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -215,6 +224,12 @@ cli.register(SessionListCommand);
cli.register(SessionNoteCommand);
cli.register(SessionCompleteCommand);
cli.register(SessionInProgressCommand);
cli.register(SessionSnapshotSaveCommand);
cli.register(SessionSnapshotRestoreCommand);
cli.register(SessionSnapshotListCommand);
cli.register(SessionSnapshotDeleteCommand);
cli.register(SessionExplainCommand);
cli.register(ActivityCommand);
cli.register(ProfileCommand);
cli.register(ProfileListCommand);
@@ -238,10 +253,14 @@ cli.register(SkillMdCheckCommand);
cli.register(ServeCommand);
cli.register(ScanCommand);
cli.register(DoctorCommand);
cli.register(SaveCommand);
cli.register(AgentsMdCommand);
cli.register(AgentsMdInitCommand);
cli.register(AgentsMdSyncCommand);
cli.register(AgentsMdShowCommand);
cli.register(IssuePlanCommand);
cli.register(IssueListCommand);
cli.runExit(process.argv.slice(2));
+35
View File
@@ -343,6 +343,41 @@ skillkit serve --cache-ttl 3600000
| GET | `/health` | Server health |
| GET | `/cache/stats` | Cache statistics |
## Issue Planner
Generate structured plans from GitHub Issues. Requires the `gh` CLI.
```bash
skillkit issue plan "#42" # Plan from current repo
skillkit issue plan rohitg00/skillkit#42 # Cross-repo
skillkit issue plan "#42" --agent cursor # Target specific agent
skillkit issue plan "#42" --no-tests # Skip test steps
skillkit issue plan "#42" --json # JSON output
skillkit issue plan "#42" --tech-stack react,ts # Override tech stack
```
### Issue Plan Options
| Option | Short | Default | Purpose |
|--------|-------|---------|---------|
| `--agent` | `-a` | `claude-code` | Target agent |
| `--output` | `-o` | `.skillkit/plans/issue-<n>.md` | Output file path |
| `--no-tests` | — | `false` | Skip test steps |
| `--json` | — | `false` | Output as JSON |
| `--tech-stack` | — | — | Comma-separated tech stack |
### Issue List
```bash
skillkit issue list # List open issues
skillkit issue list --repo owner/repo # Specific repo
skillkit issue list --label bug # Filter by label
skillkit issue list --limit 20 # More results
skillkit issue list --json # JSON output
```
The planner extracts task lists (checkboxes) from the issue body, infers file mentions from backtick-quoted paths, and maps labels to tags (e.g., `bug` → `fix`, `enhancement` → `feature`). Generated plans work with `skillkit plan validate` and `skillkit plan execute`.
## Utility Commands
```bash
+11
View File
@@ -93,6 +93,17 @@ const COMMAND_GROUPS: CommandGroup[] = [
{ cmd: 'validate', desc: 'Validate format' },
],
},
{
name: 'Issues',
commands: [
{ cmd: 'issue plan "#42"', desc: 'Plan from issue' },
{ cmd: 'issue plan owner/repo#42', desc: 'Cross-repo plan' },
{ cmd: 'issue plan "#42" --agent cursor', desc: 'Target agent' },
{ cmd: 'issue plan "#42" --json', desc: 'JSON output' },
{ cmd: 'issue list', desc: 'List open issues' },
{ cmd: 'issue list --label bug', desc: 'Filter by label' },
],
},
{
name: 'Advanced',
commands: [
@@ -20,6 +20,16 @@ describe('CLI Commands', () => {
expect(commands.TranslateCommand).toBeDefined();
expect(commands.ContextCommand).toBeDefined();
expect(commands.RecommendCommand).toBeDefined();
expect(commands.ActivityCommand).toBeDefined();
expect(commands.DoctorCommand).toBeDefined();
expect(commands.IssuePlanCommand).toBeDefined();
expect(commands.IssueListCommand).toBeDefined();
expect(commands.SessionSnapshotSaveCommand).toBeDefined();
expect(commands.SessionSnapshotRestoreCommand).toBeDefined();
expect(commands.SessionSnapshotListCommand).toBeDefined();
expect(commands.SessionSnapshotDeleteCommand).toBeDefined();
expect(commands.SessionExplainCommand).toBeDefined();
});
});
});
@@ -0,0 +1,232 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execSync } from 'node:child_process';
import { mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { stringify } from 'yaml';
const CLI = join(__dirname, '../../../../apps/skillkit/dist/cli.js');
function run(args: string, cwd: string): string {
try {
return execSync(`node ${CLI} ${args}`, {
cwd,
encoding: 'utf-8',
timeout: 15000,
env: { ...process.env, NO_COLOR: '1' },
});
} catch (err: any) {
return err.stdout || err.stderr || err.message;
}
}
describe('E2E: Session Features', () => {
let testDir: string;
beforeEach(() => {
testDir = join(tmpdir(), `skillkit-e2e-${Date.now()}`);
mkdirSync(testDir, { recursive: true });
});
afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
});
describe('skillkit activity', () => {
it('should show empty state message', () => {
const output = run('activity', testDir);
expect(output).toContain('No activity recorded');
});
it('should return empty JSON array', () => {
const output = run('activity --json', testDir);
const parsed = JSON.parse(output.trim());
expect(parsed).toEqual([]);
});
it('should accept --skill filter without error', () => {
const output = run('activity --skill code-simplifier', testDir);
expect(output).toContain('No activity recorded');
});
it('should accept --limit flag without error', () => {
const output = run('activity --limit 5', testDir);
expect(output).toContain('No activity recorded');
});
});
describe('skillkit session snapshot', () => {
it('should list no snapshots initially', () => {
const output = run('session snapshot list', testDir);
expect(output).toContain('No snapshots found');
});
it('should return empty JSON for snapshot list', () => {
const output = run('session snapshot list --json', testDir);
const parsed = JSON.parse(output.trim());
expect(parsed).toEqual([]);
});
it('should fail to save without active session', () => {
const output = run('session snapshot save test-snap', testDir);
expect(output).toContain('No active session');
});
it('should fail to restore nonexistent snapshot', () => {
const output = run('session snapshot restore nonexistent', testDir);
expect(output).toContain('not found');
});
it('should fail to delete nonexistent snapshot', () => {
const output = run('session snapshot delete nonexistent', testDir);
expect(output).toContain('not found');
});
it('should save and restore snapshot with active session', () => {
const skillkitDir = join(testDir, '.skillkit');
mkdirSync(skillkitDir, { recursive: true });
const sessionState = {
version: 1,
lastActivity: new Date().toISOString(),
projectPath: testDir,
currentExecution: {
skillName: 'code-simplifier',
skillSource: 'local',
currentStep: 1,
totalSteps: 2,
status: 'running',
startedAt: new Date().toISOString(),
tasks: [
{
id: 'task-1',
name: 'Test task',
type: 'auto',
status: 'completed',
},
],
},
history: [],
decisions: [{ key: 'test-key', value: 'test-value', madeAt: new Date().toISOString() }],
};
writeFileSync(
join(skillkitDir, 'session.yaml'),
stringify(sessionState)
);
const saveOutput = run('session snapshot save my-test-snap --desc "E2E test"', testDir);
expect(saveOutput).toContain('Snapshot saved: my-test-snap');
const snapshotFile = join(skillkitDir, 'snapshots', 'my-test-snap.yaml');
expect(existsSync(snapshotFile)).toBe(true);
const listOutput = run('session snapshot list', testDir);
expect(listOutput).toContain('my-test-snap');
expect(listOutput).toContain('E2E test');
const restoreOutput = run('session snapshot restore my-test-snap', testDir);
expect(restoreOutput).toContain('Snapshot restored: my-test-snap');
const deleteOutput = run('session snapshot delete my-test-snap', testDir);
expect(deleteOutput).toContain('Snapshot deleted: my-test-snap');
expect(existsSync(snapshotFile)).toBe(false);
});
});
describe('skillkit session explain', () => {
it('should show empty session summary', () => {
const output = run('session explain --no-git', testDir);
expect(output).toContain('Session Summary');
expect(output).toContain('Agent:');
expect(output).toContain('Files Modified: 0 files');
});
it('should return valid JSON', () => {
const output = run('session explain --json --no-git', testDir);
const parsed = JSON.parse(output.trim());
expect(parsed.date).toBeDefined();
expect(parsed.agent).toBe('unknown');
expect(parsed.skillsUsed).toEqual([]);
expect(parsed.observationCounts).toBeDefined();
expect(typeof parsed.observationCounts.errors).toBe('number');
expect(typeof parsed.observationCounts.solutions).toBe('number');
expect(typeof parsed.observationCounts.patterns).toBe('number');
});
it('should explain session with active execution', () => {
const skillkitDir = join(testDir, '.skillkit');
mkdirSync(skillkitDir, { recursive: true });
const sessionState = {
version: 1,
lastActivity: new Date().toISOString(),
projectPath: testDir,
currentExecution: {
skillName: 'remotion-best-practices',
skillSource: 'claude-code',
currentStep: 2,
totalSteps: 3,
status: 'running',
startedAt: new Date(Date.now() - 3600000).toISOString(),
tasks: [
{
id: 't1',
name: 'Setup video',
type: 'auto',
status: 'completed',
startedAt: new Date(Date.now() - 3600000).toISOString(),
completedAt: new Date(Date.now() - 1800000).toISOString(),
filesModified: ['src/video.tsx'],
},
{
id: 't2',
name: 'Add effects',
type: 'auto',
status: 'in_progress',
startedAt: new Date(Date.now() - 1800000).toISOString(),
},
],
},
history: [],
decisions: [
{ key: 'codec', value: 'h264', madeAt: new Date().toISOString() },
],
};
writeFileSync(
join(skillkitDir, 'session.yaml'),
stringify(sessionState)
);
const output = run('session explain --no-git', testDir);
expect(output).toContain('Session Summary');
expect(output).toContain('Duration:');
expect(output).toContain('claude-code');
expect(output).toContain('remotion-best-practices');
expect(output).toContain('Setup video');
expect(output).toContain('Add effects');
expect(output).toContain('codec');
const jsonOutput = run('session explain --json --no-git', testDir);
const parsed = JSON.parse(jsonOutput.trim());
expect(parsed.skillsUsed).toHaveLength(1);
expect(parsed.skillsUsed[0].name).toBe('remotion-best-practices');
expect(parsed.tasks).toHaveLength(2);
expect(parsed.decisions).toHaveLength(1);
expect(parsed.filesModified).toContain('src/video.tsx');
});
});
describe('skillkit session (help)', () => {
it('should list all subcommands including new ones', () => {
const output = run('session', testDir);
expect(output).toContain('session explain');
expect(output).toContain('session snapshot save');
expect(output).toContain('session snapshot restore');
expect(output).toContain('session snapshot list');
expect(output).toContain('session snapshot delete');
});
});
});
+94
View File
@@ -0,0 +1,94 @@
import { Command, Option } from 'clipanion';
import chalk from 'chalk';
import { ActivityLog } from '@skillkit/core';
export class ActivityCommand extends Command {
static override paths = [['activity']];
static override usage = Command.Usage({
description: 'Show skill activity log for git commits',
examples: [
['Show recent activity', '$0 activity'],
['Filter by skill', '$0 activity --skill code-simplifier'],
['JSON output', '$0 activity --json'],
],
});
skill = Option.String('--skill,-s', {
description: 'Filter by skill name',
});
limit = Option.String('--limit,-l', {
description: 'Number of entries to show (default: 10)',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
const projectPath = process.cwd();
const log = new ActivityLog(projectPath);
const parsed = this.limit ? parseInt(this.limit, 10) : 10;
const limit = Number.isFinite(parsed) && parsed > 0 ? parsed : 10;
const activities = this.skill
? log.getBySkill(this.skill)
: log.getRecent(limit);
if (this.json) {
console.log(JSON.stringify(activities.slice(0, limit), null, 2));
return 0;
}
if (activities.length === 0) {
console.log(chalk.yellow('No activity recorded'));
console.log(
chalk.dim(
'Activity is recorded when skills are active during git commits.'
)
);
return 0;
}
console.log(chalk.cyan(' Recent Skill Activity\n'));
const displayed = activities.slice(0, limit);
for (const activity of displayed) {
const shortSha = activity.commitSha.slice(0, 7);
const skills = activity.activeSkills.join(', ');
const files = activity.filesChanged.join(', ');
const ago = formatTimeAgo(activity.committedAt);
console.log(` ${chalk.bold(shortSha)} ${activity.message}`);
console.log(` Skills: ${chalk.green(skills)}`);
console.log(
` Files: ${files} ${chalk.dim(`(${ago})`)}`
);
console.log();
}
const topSkills = log.getMostUsedSkills().slice(0, 5);
if (topSkills.length > 0) {
const formatted = topSkills
.map((s) => `${s.skill} (${s.count})`)
.join(', ');
console.log(` Top Skills: ${formatted}`);
}
return 0;
}
}
function formatTimeAgo(isoDate: string): string {
const diff = Date.now() - new Date(isoDate).getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) return `${days}d ago`;
if (hours > 0) return `${hours}h ago`;
if (minutes > 0) return `${minutes}m ago`;
return 'just now';
}
+297
View File
@@ -0,0 +1,297 @@
import { Command, Option } from 'clipanion';
import { execFileSync } from 'node:child_process';
import { existsSync, lstatSync, readlinkSync, readdirSync, mkdirSync, unlinkSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { homedir } from 'node:os';
import { detectAgent, getAdapter } from '@skillkit/agents';
import { AgentType, findAllSkills, validateSkill, loadConfig, getProjectConfigPath, getGlobalSkillsDir } from '@skillkit/core';
import type { AgentType as AgentTypeT } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
import { colors, symbols } from '../onboarding/index.js';
interface CheckResult {
name: string;
status: 'pass' | 'warn' | 'fail';
message: string;
fix?: string;
}
export class DoctorCommand extends Command {
static override paths = [['doctor']];
static override usage = Command.Usage({
description: 'Diagnose setup issues and check environment health',
details: `
Runs a series of checks to verify your SkillKit setup is correct,
including environment, agent detection, skills health, and configuration.
`,
examples: [
['Run health checks', '$0 doctor'],
['JSON output', '$0 doctor --json'],
['Auto-fix issues', '$0 doctor --fix'],
],
});
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
fix = Option.Boolean('--fix', false, {
description: 'Auto-fix issues where possible',
});
async execute(): Promise<number> {
const results: CheckResult[] = [];
// --- Environment ---
const nodeVersion = process.version;
const nodeMajor = parseInt(nodeVersion.slice(1).split('.')[0], 10);
if (nodeMajor >= 18) {
results.push({ name: 'Node.js version', status: 'pass', message: `Node.js ${nodeVersion}` });
} else {
results.push({ name: 'Node.js version', status: 'fail', message: `Node.js ${nodeVersion} — upgrade to >=18 required` });
}
const npmVersion = this.whichVersion('npm');
if (npmVersion) {
results.push({ name: 'npm available', status: 'pass', message: `npm v${npmVersion}` });
} else {
results.push({ name: 'npm available', status: 'warn', message: 'npm not found' });
}
const pnpmVersion = this.whichVersion('pnpm');
if (pnpmVersion) {
results.push({ name: 'pnpm available', status: 'pass', message: `pnpm v${pnpmVersion}` });
}
const skillkitVersion = this.cli.binaryVersion ?? 'unknown';
results.push({ name: 'SkillKit version', status: 'pass', message: `skillkit v${skillkitVersion}` });
// --- Configuration ---
const configPath = getProjectConfigPath();
const hasConfig = existsSync(configPath);
if (hasConfig) {
try {
const agent = loadConfig().agent;
results.push({ name: 'Config file', status: 'pass', message: `skillkit.yaml (agent: ${agent})` });
} catch {
results.push({ name: 'Config file', status: 'warn', message: 'skillkit.yaml found but has parse errors' });
}
} else {
results.push({ name: 'Config file', status: 'warn', message: 'No config file (using defaults)' });
}
// --- Agent Detection ---
let detectedAgent: AgentTypeT = 'universal';
try {
detectedAgent = await detectAgent();
results.push({ name: 'Detected agent', status: 'pass', message: `Detected: ${detectedAgent}` });
} catch {
results.push({ name: 'Detected agent', status: 'warn', message: 'No agent detected (using universal)' });
}
const otherDetected: string[] = [];
try {
for (const agentType of AgentType.options) {
if (agentType === detectedAgent || agentType === 'universal') continue;
try {
const agentAdapter = getAdapter(agentType);
if (await agentAdapter.isDetected()) {
otherDetected.push(agentType);
}
} catch {
// skip
}
}
if (otherDetected.length > 0) {
results.push({ name: 'Other agents', status: 'warn', message: `Also detected: ${otherDetected.join(', ')}` });
}
} catch {
// skip
}
// --- Skills ---
const adapter = getAdapter(detectedAgent);
const skillsDir = resolve(adapter.skillsDir);
const skillsDirExists = existsSync(skillsDir);
if (skillsDirExists) {
const entries = readdirSync(skillsDir).filter(e => !e.startsWith('.'));
results.push({ name: 'Project skills dir', status: 'pass', message: `${adapter.skillsDir} (${entries.length} entries)` });
} else {
if (this.fix) {
mkdirSync(skillsDir, { recursive: true });
results.push({ name: 'Project skills dir', status: 'pass', message: `${adapter.skillsDir} (created)` });
} else {
results.push({
name: 'Project skills dir',
status: 'warn',
message: `${adapter.skillsDir} missing`,
fix: 'Run with --fix to create it',
});
}
}
const globalSkillsDirRaw = getGlobalSkillsDir(detectedAgent);
const globalSkillsDir = globalSkillsDirRaw ? globalSkillsDirRaw.replace(/^~/, homedir()) : null;
if (globalSkillsDir && existsSync(globalSkillsDir)) {
const entries = readdirSync(globalSkillsDir).filter(e => !e.startsWith('.'));
results.push({ name: 'Global skills dir', status: 'pass', message: `${globalSkillsDir} (${entries.length} entries)` });
} else {
results.push({ name: 'Global skills dir', status: 'pass', message: 'No global skills directory' });
}
// Skill validation
let searchDirs: string[] = [];
try {
searchDirs = getSearchDirs(detectedAgent);
} catch {
searchDirs = skillsDirExists ? [skillsDir] : [];
}
const allSkills = findAllSkills(searchDirs);
const invalidSkills: string[] = [];
for (const skill of allSkills) {
const validation = validateSkill(skill.path);
if (!validation.valid) {
invalidSkills.push(`${skill.name}: ${validation.errors.join(', ')}`);
}
}
if (allSkills.length === 0) {
results.push({ name: 'Installed skills', status: 'pass', message: 'No skills installed' });
} else if (invalidSkills.length === 0) {
results.push({ name: 'Installed skills', status: 'pass', message: `${allSkills.length} skills, all valid` });
} else {
results.push({
name: 'Installed skills',
status: 'fail',
message: `${invalidSkills.length} of ${allSkills.length} skills have errors`,
fix: invalidSkills.join('; '),
});
}
// Broken symlinks
const brokenSymlinks: string[] = [];
for (const dir of searchDirs) {
if (!existsSync(dir)) continue;
try {
const entries = readdirSync(dir);
for (const entry of entries) {
const fullPath = join(dir, entry);
try {
const stat = lstatSync(fullPath);
if (stat.isSymbolicLink()) {
const target = readlinkSync(fullPath);
const resolvedTarget = resolve(dir, target);
if (!existsSync(resolvedTarget)) {
brokenSymlinks.push(fullPath);
}
}
} catch {
// skip
}
}
} catch {
// skip
}
}
if (brokenSymlinks.length > 0) {
if (this.fix) {
let removed = 0;
const failed: string[] = [];
for (const link of brokenSymlinks) {
try {
unlinkSync(link);
removed++;
} catch {
failed.push(link);
}
}
if (failed.length > 0) {
results.push({ name: 'Broken symlinks', status: 'warn', message: `Removed ${removed}, failed to remove ${failed.length}` });
} else {
results.push({ name: 'Broken symlinks', status: 'pass', message: `Removed ${brokenSymlinks.length} broken symlink(s)` });
}
} else {
results.push({
name: 'Broken symlinks',
status: 'fail',
message: `${brokenSymlinks.length} broken symlink(s) found`,
fix: brokenSymlinks.map(l => ` ${l}`).join('\n'),
});
}
} else {
results.push({ name: 'Broken symlinks', status: 'pass', message: 'No broken symlinks' });
}
// --- Output ---
if (this.json) {
const summary = {
checks: results,
passed: results.filter(r => r.status === 'pass').length,
warnings: results.filter(r => r.status === 'warn').length,
errors: results.filter(r => r.status === 'fail').length,
};
console.log(JSON.stringify(summary, null, 2));
return summary.errors > 0 ? 1 : 0;
}
console.log('');
console.log(colors.primary('skillkit doctor'));
console.log('');
const sections: Record<string, string[]> = {
Environment: ['Node.js version', 'npm available', 'pnpm available', 'SkillKit version'],
Configuration: ['Config file', 'Detected agent', 'Other agents'],
Skills: ['Project skills dir', 'Global skills dir', 'Installed skills', 'Broken symlinks'],
};
for (const [section, checkNames] of Object.entries(sections)) {
const sectionResults = results.filter(r => checkNames.includes(r.name));
if (sectionResults.length === 0) continue;
console.log(` ${colors.primary(section)}`);
for (const result of sectionResults) {
const icon = this.statusIcon(result.status);
console.log(` ${icon} ${result.message}`);
if (result.fix && result.status !== 'pass') {
console.log(` ${colors.muted(result.fix)}`);
}
}
console.log('');
}
const passed = results.filter(r => r.status === 'pass').length;
const warnings = results.filter(r => r.status === 'warn').length;
const errors = results.filter(r => r.status === 'fail').length;
const parts = [`${passed} passed`];
if (warnings > 0) parts.push(`${warnings} warning(s)`);
if (errors > 0) parts.push(`${errors} error(s)`);
console.log(` ${colors.muted('Summary:')} ${parts.join(', ')}`);
console.log('');
return errors > 0 ? 1 : 0;
}
private statusIcon(status: CheckResult['status']): string {
switch (status) {
case 'pass': return colors.success(symbols.success);
case 'warn': return colors.warning(symbols.warning);
case 'fail': return colors.error(symbols.error);
}
}
private whichVersion(cmd: string): string | null {
try {
return execFileSync(cmd, ['--version'], { encoding: 'utf-8', timeout: 5000 })
.trim()
.replace(/^v/, '');
} catch {
return null;
}
}
}
+8
View File
@@ -90,7 +90,13 @@ export {
SessionNoteCommand,
SessionCompleteCommand,
SessionInProgressCommand,
SessionSnapshotSaveCommand,
SessionSnapshotRestoreCommand,
SessionSnapshotListCommand,
SessionSnapshotDeleteCommand,
SessionExplainCommand,
} from './session.js';
export { ActivityCommand } from './activity.js';
export {
ProfileCommand,
ProfileListCommand,
@@ -119,6 +125,8 @@ export { SkillMdValidateCommand, SkillMdInitCommand, SkillMdCheckCommand } from
// API server
export { ServeCommand } from './serve.js';
export { ScanCommand } from './scan.js';
export { IssuePlanCommand, IssueListCommand } from './issue.js';
export { DoctorCommand } from './doctor.js';
export { SaveCommand } from './save.js';
export {
AgentsMdCommand,
+284
View File
@@ -0,0 +1,284 @@
import { Command, Option } from 'clipanion';
import { execFileSync } from 'node:child_process';
import { writeFile, mkdir } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import {
createIssuePlanner,
createPlanGenerator,
createPlanValidator,
} from '@skillkit/core';
export class IssuePlanCommand extends Command {
static paths = [['issue', 'plan']];
static usage = Command.Usage({
category: 'Development',
description: 'Generate a structured plan from a GitHub Issue',
details: `
Fetches a GitHub Issue and generates a StructuredPlan that can be
validated and executed with existing plan commands.
Requires the \`gh\` CLI to be installed and authenticated.
Examples:
$ skillkit issue plan "#42"
$ skillkit issue plan rohitg00/skillkit#42
$ skillkit issue plan "#42" --agent cursor --no-tests
$ skillkit issue plan "#42" --json
`,
examples: [
['Plan from current repo issue', '$0 issue plan "#42"'],
['Plan from specific repo', '$0 issue plan rohitg00/skillkit#42'],
['Plan with JSON output', '$0 issue plan "#42" --json'],
],
});
ref = Option.String({ required: true });
agent = Option.String('--agent,-a', 'claude-code', {
description: 'Target agent',
});
output = Option.String('--output,-o', {
description: 'Output file path (default: .skillkit/plans/issue-<n>.md)',
});
noTests = Option.Boolean('--no-tests', false, {
description: 'Skip adding test steps',
});
json = Option.Boolean('--json', false, {
description: 'Output as JSON',
});
techStack = Option.String('--tech-stack', {
description: 'Comma-separated tech stack',
});
async execute(): Promise<number> {
try {
execFileSync('gh', ['--version'], { encoding: 'utf-8', timeout: 5_000 });
} catch {
this.context.stderr.write(
'Error: GitHub CLI (gh) is not installed or not in PATH.\n' +
'Install it from https://cli.github.com/\n'
);
return 1;
}
const planner = createIssuePlanner();
let issue;
try {
issue = planner.fetchIssue(this.ref);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.context.stderr.write(`Error fetching issue: ${message}\n`);
return 1;
}
const techStackArr = this.techStack
? this.techStack.split(',').map((s) => s.trim())
: undefined;
const plan = planner.generatePlan(issue, {
agent: this.agent,
techStack: techStackArr,
includeTests: !this.noTests,
});
const validator = createPlanValidator();
const validation = validator.validate(plan);
const generator = createPlanGenerator();
const markdown = generator.toMarkdown(plan);
const outputPath =
this.output || resolve(`.skillkit/plans/issue-${issue.number}.md`);
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, markdown, 'utf-8');
if (this.json) {
this.context.stdout.write(
JSON.stringify(
{
issue: {
number: issue.number,
title: issue.title,
url: issue.url,
state: issue.state,
labels: issue.labels,
},
plan: {
name: plan.name,
goal: plan.goal,
tasks: plan.tasks.map((t) => ({
id: t.id,
name: t.name,
files: t.files,
steps: t.steps.length,
status: t.status,
})),
metadata: plan.metadata,
},
validation: {
valid: validation.valid,
issues: validation.issues.length,
stats: validation.stats,
},
outputPath,
},
null,
2
) + '\n'
);
} else {
this.context.stdout.write(`\n Issue #${issue.number}: ${issue.title}\n\n`);
this.context.stdout.write(` Generated Plan: ${outputPath}\n\n`);
this.context.stdout.write(` Tasks (${plan.tasks.length})\n`);
for (const task of plan.tasks) {
const fileList: string[] = [];
if (task.files.create) {
fileList.push(...task.files.create.map((f) => `${f} (create)`));
}
if (task.files.modify) {
fileList.push(...task.files.modify.map((f) => `${f} (modify)`));
}
this.context.stdout.write(` ${task.id}. ${task.name}\n`);
if (fileList.length > 0) {
this.context.stdout.write(
` Files: ${fileList.join(', ')}\n`
);
}
}
if (plan.tags && plan.tags.length > 0) {
this.context.stdout.write(
`\n Labels: ${issue.labels.join(', ')} -> ${plan.tags.join(', ')}\n`
);
}
this.context.stdout.write(` Agent: ${this.agent}\n\n`);
if (!validation.valid) {
this.context.stdout.write(
` Warnings: ${validation.issues.length}\n`
);
}
this.context.stdout.write(
` Next: skillkit plan validate -f ${outputPath}\n` +
` skillkit plan execute -f ${outputPath} --dry-run\n\n`
);
}
return 0;
}
}
export class IssueListCommand extends Command {
static paths = [['issue', 'list']];
static usage = Command.Usage({
category: 'Development',
description: 'List open GitHub Issues',
details: `
Lists open issues from a GitHub repository. Useful for picking
which issue to plan.
Examples:
$ skillkit issue list
$ skillkit issue list --repo rohitg00/skillkit --label bug
$ skillkit issue list --limit 20 --json
`,
examples: [
['List issues in current repo', '$0 issue list'],
['Filter by label', '$0 issue list --label enhancement'],
],
});
repo = Option.String('--repo,-r', {
description: 'Repository (owner/repo)',
});
label = Option.String('--label,-l', {
description: 'Filter by label',
});
limit = Option.String('--limit', '10', {
description: 'Maximum issues to list',
});
json = Option.Boolean('--json', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
try {
execFileSync('gh', ['--version'], { encoding: 'utf-8', timeout: 5_000 });
} catch {
this.context.stderr.write(
'Error: GitHub CLI (gh) is not installed or not in PATH.\n'
);
return 1;
}
const args = [
'issue',
'list',
'--limit',
this.limit,
'--json',
'number,title,labels,assignees',
'--state',
'open',
];
if (this.repo) {
args.push('--repo', this.repo);
}
if (this.label) {
args.push('--label', this.label);
}
let result: string;
try {
result = execFileSync('gh', args, {
encoding: 'utf-8',
timeout: 15_000,
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.context.stderr.write(`Error listing issues: ${message}\n`);
return 1;
}
let issues: Array<{
number: number;
title: string;
labels: Array<{ name: string }>;
assignees: Array<{ login: string }>;
}>;
try {
issues = JSON.parse(result);
} catch {
this.context.stderr.write('Error: Failed to parse GitHub CLI response.\n');
return 1;
}
if (this.json) {
this.context.stdout.write(JSON.stringify(issues, null, 2) + '\n');
} else {
if (issues.length === 0) {
this.context.stdout.write(' No open issues found.\n');
return 0;
}
this.context.stdout.write('\n Open Issues\n\n');
for (const issue of issues) {
const labels = issue.labels.map((l) => l.name).join(', ');
const labelStr = labels ? ` [${labels}]` : '';
this.context.stdout.write(
` #${issue.number} ${issue.title}${labelStr}\n`
);
}
this.context.stdout.write(
`\n Use: skillkit issue plan "#<number>" to generate a plan\n\n`
);
}
return 0;
}
}
+223 -6
View File
@@ -7,7 +7,12 @@ import {
updateSessionFile,
listSessions,
getMostRecentSession,
SnapshotManager,
SessionManager,
SessionExplainer,
ObservationStore,
type SessionFile,
type SessionSnapshot,
} from '@skillkit/core';
export class SessionCommand extends Command {
@@ -28,12 +33,17 @@ export class SessionCommand extends Command {
async execute(): Promise<number> {
console.log(chalk.cyan('Session commands:\n'));
console.log(' session status Show current session state');
console.log(' session start Start a new session');
console.log(' session load Load session from specific date');
console.log(' session list List recent sessions');
console.log(' session note Add note to current session');
console.log(' session complete Mark task as completed');
console.log(' session status Show current session state');
console.log(' session start Start a new session');
console.log(' session load Load session from specific date');
console.log(' session list List recent sessions');
console.log(' session note Add note to current session');
console.log(' session complete Mark task as completed');
console.log(' session explain Explain current session');
console.log(' session snapshot save Save session snapshot');
console.log(' session snapshot restore Restore session snapshot');
console.log(' session snapshot list List snapshots');
console.log(' session snapshot delete Delete snapshot');
console.log();
return 0;
}
@@ -319,3 +329,210 @@ export class SessionInProgressCommand extends Command {
return 0;
}
}
export class SessionSnapshotSaveCommand extends Command {
static override paths = [['session', 'snapshot', 'save']];
static override usage = Command.Usage({
description: 'Save current session state as a named snapshot',
examples: [
['Save snapshot', '$0 session snapshot save my-feature'],
['With description', '$0 session snapshot save my-feature --desc "Before refactor"'],
],
});
name = Option.String({ required: true });
desc = Option.String('--desc,-d', {
description: 'Snapshot description',
});
async execute(): Promise<number> {
const projectPath = process.cwd();
const manager = new SnapshotManager(projectPath);
const sessionMgr = new SessionManager(projectPath);
const state = sessionMgr.get();
if (!state) {
console.log(chalk.yellow('No active session to snapshot'));
return 1;
}
let observations: SessionSnapshot['observations'] = [];
try {
const raw = ObservationStore.readAll(projectPath);
observations = raw.map((o) => ({
id: o.id,
timestamp: o.timestamp,
sessionId: o.sessionId,
agent: o.agent as string,
type: o.type as string,
content: { ...o.content } as Record<string, unknown>,
relevance: o.relevance,
}));
} catch {
// No observations available
}
manager.save(this.name, state, observations, this.desc);
console.log(chalk.green(`\u2713 Snapshot saved: ${this.name}`));
if (this.desc) {
console.log(chalk.dim(` ${this.desc}`));
}
return 0;
}
}
export class SessionSnapshotRestoreCommand extends Command {
static override paths = [['session', 'snapshot', 'restore']];
static override usage = Command.Usage({
description: 'Restore session state from a snapshot',
examples: [['Restore snapshot', '$0 session snapshot restore my-feature']],
});
name = Option.String({ required: true });
async execute(): Promise<number> {
const projectPath = process.cwd();
const manager = new SnapshotManager(projectPath);
if (!manager.exists(this.name)) {
console.log(chalk.red(`Snapshot "${this.name}" not found`));
return 1;
}
const { sessionState, observations } = manager.restore(this.name);
const sessionMgr = new SessionManager(projectPath);
const currentState = sessionMgr.getOrCreate();
Object.assign(currentState, {
currentExecution: sessionState.currentExecution,
history: sessionState.history,
decisions: sessionState.decisions,
});
sessionMgr.save();
try {
if (observations && observations.length > 0) {
const store = new ObservationStore(projectPath);
for (const obs of observations) {
store.add(
obs.type as Parameters<ObservationStore['add']>[0],
obs.content as unknown as Parameters<ObservationStore['add']>[1],
obs.agent as Parameters<ObservationStore['add']>[2],
obs.relevance,
);
}
}
} catch {
// Non-critical: session state restored even if observations fail
}
console.log(chalk.green(`\u2713 Snapshot restored: ${this.name}`));
return 0;
}
}
export class SessionSnapshotListCommand extends Command {
static override paths = [['session', 'snapshot', 'list'], ['session', 'snapshot', 'ls']];
static override usage = Command.Usage({
description: 'List all session snapshots',
examples: [['List snapshots', '$0 session snapshot list']],
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
const projectPath = process.cwd();
const manager = new SnapshotManager(projectPath);
const snapshots = manager.list();
if (this.json) {
console.log(JSON.stringify(snapshots, null, 2));
return 0;
}
if (snapshots.length === 0) {
console.log(chalk.yellow('No snapshots found'));
console.log(chalk.dim('Save one with: skillkit session snapshot save <name>'));
return 0;
}
console.log(chalk.cyan(`Snapshots (${snapshots.length}):\n`));
for (const snap of snapshots) {
console.log(` ${chalk.bold(snap.name)}`);
console.log(` Created: ${snap.createdAt}`);
if (snap.description) {
console.log(` ${chalk.dim(snap.description)}`);
}
console.log(` Skills in history: ${snap.skillCount}`);
console.log();
}
return 0;
}
}
export class SessionSnapshotDeleteCommand extends Command {
static override paths = [['session', 'snapshot', 'delete']];
static override usage = Command.Usage({
description: 'Delete a session snapshot',
examples: [['Delete snapshot', '$0 session snapshot delete my-feature']],
});
name = Option.String({ required: true });
async execute(): Promise<number> {
const projectPath = process.cwd();
const manager = new SnapshotManager(projectPath);
if (!manager.delete(this.name)) {
console.log(chalk.red(`Snapshot "${this.name}" not found`));
return 1;
}
console.log(chalk.green(`\u2713 Snapshot deleted: ${this.name}`));
return 0;
}
}
export class SessionExplainCommand extends Command {
static override paths = [['session', 'explain']];
static override usage = Command.Usage({
description: 'Explain what happened in the current session',
examples: [
['Explain session', '$0 session explain'],
['JSON output', '$0 session explain --json'],
['Skip git', '$0 session explain --no-git'],
],
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
noGit = Option.Boolean('--no-git', false, {
description: 'Skip git analysis',
});
async execute(): Promise<number> {
const projectPath = process.cwd();
const explainer = new SessionExplainer(projectPath);
const explanation = explainer.explain({ includeGit: !this.noGit });
if (this.json) {
console.log(explainer.formatJson(explanation));
return 0;
}
console.log(explainer.formatText(explanation));
return 0;
}
}
+101 -10
View File
@@ -1,7 +1,23 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import { existsSync } from 'node:fs';
import chalk from 'chalk';
import { SessionManager } from '@skillkit/core';
import type { AgentType } from '@skillkit/core';
import { SessionManager, findAllSkills, loadConfig, getProjectConfigPath } from '@skillkit/core';
import { detectAgent, getAdapter } from '@skillkit/agents';
import { getSearchDirs } from '../helpers.js';
interface StatusOverview {
agent: string;
config: string | null;
configAgent: string;
version: string;
totalSkills: number;
projectSkills: number;
globalSkills: number;
skillsDir: string;
recentHistory: Array<{ status: string; skillName: string; completedAt: string }>;
}
/**
* Status command - show current session state
@@ -22,22 +38,18 @@ export class StatusCommand extends Command {
],
});
// 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)',
});
@@ -47,14 +59,18 @@ export class StatusCommand extends Command {
const manager = new SessionManager(targetPath);
const state = manager.get();
if (this.json) {
console.log(JSON.stringify(state || { message: 'No session found' }, null, 2));
if (!state) {
const overview = await this.buildOverview(manager);
if (this.json) {
console.log(JSON.stringify({ session: null, overview }, null, 2));
return 0;
}
this.showOverview(overview);
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.'));
if (this.json) {
console.log(JSON.stringify(state, null, 2));
return 0;
}
@@ -134,6 +150,81 @@ export class StatusCommand extends Command {
return 0;
}
private async buildOverview(manager: SessionManager): Promise<StatusOverview> {
let agent: AgentType = 'universal';
try {
agent = await detectAgent();
} catch {
// fallback
}
const configPath = getProjectConfigPath();
const hasConfig = existsSync(configPath);
let configAgent = 'universal';
if (hasConfig) {
try {
configAgent = loadConfig().agent;
} catch {
// ignore
}
}
const version = this.cli.binaryVersion ?? 'unknown';
let searchDirs: string[] = [];
try {
searchDirs = getSearchDirs(agent);
} catch {
// fallback
}
const allSkills = findAllSkills(searchDirs);
const projectSkills = allSkills.filter(s => s.location === 'project');
const globalSkills = allSkills.filter(s => s.location === 'global');
const adapter = getAdapter(agent);
const recentHistory = manager.getHistory(3);
return {
agent,
config: hasConfig ? configPath : null,
configAgent,
version,
totalSkills: allSkills.length,
projectSkills: projectSkills.length,
globalSkills: globalSkills.length,
skillsDir: adapter.skillsDir,
recentHistory,
};
}
private showOverview(overview: StatusOverview): void {
console.log('');
console.log(chalk.cyan(' Project Overview'));
console.log(` Agent: ${chalk.bold(overview.agent)}`);
console.log(` Config: ${overview.config ? chalk.green('skillkit.yaml') : chalk.dim('none (defaults)')}`);
console.log(` Version: ${chalk.bold(overview.version)}`);
console.log('');
console.log(chalk.cyan(` Skills (${overview.totalSkills} installed)`));
console.log(` Project: ${overview.projectSkills} skills in ${overview.skillsDir}`);
console.log(` Global: ${overview.globalSkills} skills`);
console.log('');
console.log(chalk.cyan(' Recent Activity'));
if (overview.recentHistory.length === 0) {
console.log(chalk.dim(' No recent executions.'));
} else {
for (const entry of overview.recentHistory) {
const statusColor = entry.status === 'completed' ? chalk.green : chalk.red;
console.log(` ${statusColor('\u25cf')} ${entry.skillName} - ${new Date(entry.completedAt).toLocaleDateString()}`);
}
}
console.log('');
console.log(chalk.dim(' Tip: Run "skillkit doctor" for a full health check.'));
console.log('');
}
private getStatusIcon(status: string): string {
switch (status) {
case 'completed':
@@ -181,6 +181,18 @@ export class ObservationStore {
return this.load().observations;
}
static readAll(projectPath: string): Observation[] {
const filePath = join(projectPath, '.skillkit', 'memory', 'observations.yaml');
if (!existsSync(filePath)) return [];
try {
const content = readFileSync(filePath, 'utf-8');
const data = parseYaml(content) as ObservationStoreData;
return data?.observations ?? [];
} catch {
return [];
}
}
getByType(type: ObservationType): Observation[] {
return this.load().observations.filter((o) => o.type === type);
}
@@ -0,0 +1,307 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { IssuePlanner, createIssuePlanner } from '../issue-planner.js';
import type { GitHubIssue } from '../issue-planner.js';
vi.mock('node:child_process', () => ({
execFileSync: vi.fn(),
}));
import { execFileSync } from 'node:child_process';
const mockExecFileSync = vi.mocked(execFileSync);
describe('IssuePlanner', () => {
let planner: IssuePlanner;
beforeEach(() => {
planner = new IssuePlanner();
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('parseIssueRef', () => {
it('should parse short ref #123', () => {
const result = planner.parseIssueRef('#123');
expect(result).toEqual({ number: 123 });
});
it('should parse bare number 123', () => {
const result = planner.parseIssueRef('123');
expect(result).toEqual({ number: 123 });
});
it('should parse owner/repo#123', () => {
const result = planner.parseIssueRef('rohitg00/skillkit#42');
expect(result).toEqual({
owner: 'rohitg00',
repo: 'skillkit',
number: 42,
});
});
it('should parse full GitHub URL', () => {
const result = planner.parseIssueRef(
'https://github.com/rohitg00/skillkit/issues/42'
);
expect(result).toEqual({
owner: 'rohitg00',
repo: 'skillkit',
number: 42,
});
});
it('should throw on invalid ref', () => {
expect(() => planner.parseIssueRef('invalid')).toThrow(
'Invalid issue reference'
);
});
});
describe('extractTasksFromBody', () => {
it('should extract unchecked tasks', () => {
const body = '- [ ] Add auth\n- [ ] Add tests\n';
const tasks = planner.extractTasksFromBody(body);
expect(tasks).toEqual([
{ name: 'Add auth', checked: false },
{ name: 'Add tests', checked: false },
]);
});
it('should extract checked tasks', () => {
const body = '- [x] Setup project\n- [X] Add config\n';
const tasks = planner.extractTasksFromBody(body);
expect(tasks).toEqual([
{ name: 'Setup project', checked: true },
{ name: 'Add config', checked: true },
]);
});
it('should handle mixed tasks', () => {
const body = '- [x] Done task\n- [ ] Pending task\n';
const tasks = planner.extractTasksFromBody(body);
expect(tasks).toHaveLength(2);
expect(tasks[0].checked).toBe(true);
expect(tasks[1].checked).toBe(false);
});
it('should handle empty body', () => {
expect(planner.extractTasksFromBody('')).toEqual([]);
});
it('should ignore non-checkbox lines', () => {
const body = '- Regular list item\n- [ ] Checkbox item\n';
const tasks = planner.extractTasksFromBody(body);
expect(tasks).toHaveLength(1);
expect(tasks[0].name).toBe('Checkbox item');
});
it('should handle indented checkboxes', () => {
const body = ' - [ ] Indented task\n';
const tasks = planner.extractTasksFromBody(body);
expect(tasks).toHaveLength(1);
expect(tasks[0].name).toBe('Indented task');
});
});
describe('extractFileMentions', () => {
it('should extract file paths in backticks', () => {
const text = 'Update `src/foo.ts` and `lib/bar.js`';
const files = planner.extractFileMentions(text);
expect(files).toContain('src/foo.ts');
expect(files).toContain('lib/bar.js');
});
it('should deduplicate file mentions', () => {
const text = 'See `src/foo.ts` and also `src/foo.ts`';
const files = planner.extractFileMentions(text);
expect(files).toHaveLength(1);
});
it('should handle text with no file mentions', () => {
const text = 'No files here';
expect(planner.extractFileMentions(text)).toEqual([]);
});
it('should extract files with extensions', () => {
const text = 'Check `config.json` and `README.md`';
const files = planner.extractFileMentions(text);
expect(files).toContain('config.json');
expect(files).toContain('README.md');
});
});
describe('inferLabelsToTags', () => {
it('should map known labels', () => {
expect(planner.inferLabelsToTags(['bug'])).toEqual(['fix']);
expect(planner.inferLabelsToTags(['enhancement'])).toEqual(['feature']);
expect(planner.inferLabelsToTags(['documentation'])).toEqual(['docs']);
});
it('should handle case insensitivity', () => {
expect(planner.inferLabelsToTags(['Bug'])).toEqual(['fix']);
expect(planner.inferLabelsToTags(['ENHANCEMENT'])).toEqual(['feature']);
});
it('should skip unknown labels', () => {
expect(planner.inferLabelsToTags(['unknown-label'])).toEqual([]);
});
it('should deduplicate tags', () => {
expect(planner.inferLabelsToTags(['bug', 'fix'])).toEqual(['fix']);
});
});
describe('fetchIssue', () => {
it('should fetch issue from current repo', () => {
const ghResponse = JSON.stringify({
number: 42,
title: 'Add dark mode',
body: '- [ ] Add theme provider\n- [ ] Update styles',
labels: [{ name: 'enhancement' }],
assignees: [{ login: 'user1' }],
url: 'https://github.com/test/repo/issues/42',
state: 'OPEN',
});
mockExecFileSync.mockReturnValue(ghResponse as any);
const issue = planner.fetchIssue('#42');
expect(mockExecFileSync).toHaveBeenCalledWith(
'gh',
[
'issue',
'view',
'42',
'--json',
'number,title,body,labels,assignees,url,state',
],
expect.objectContaining({ encoding: 'utf-8' })
);
expect(issue.number).toBe(42);
expect(issue.title).toBe('Add dark mode');
expect(issue.labels).toEqual(['enhancement']);
expect(issue.assignees).toEqual(['user1']);
});
it('should fetch issue from specific repo', () => {
const ghResponse = JSON.stringify({
number: 10,
title: 'Fix bug',
body: '',
labels: [],
assignees: [],
url: 'https://github.com/owner/repo/issues/10',
state: 'OPEN',
});
mockExecFileSync.mockReturnValue(ghResponse as any);
planner.fetchIssue('owner/repo#10');
expect(mockExecFileSync).toHaveBeenCalledWith(
'gh',
[
'issue',
'view',
'10',
'--json',
'number,title,body,labels,assignees,url,state',
'--repo',
'owner/repo',
],
expect.objectContaining({ encoding: 'utf-8' })
);
});
});
describe('generatePlan', () => {
const baseIssue: GitHubIssue = {
number: 42,
title: 'Add dark mode support',
body: 'We need dark mode.\n\n- [ ] Add theme context provider\n- [ ] Update component styles\n- [x] Research themes',
labels: ['enhancement'],
assignees: ['user1'],
url: 'https://github.com/test/repo/issues/42',
state: 'OPEN',
};
it('should generate plan from issue with checklist', () => {
const plan = planner.generatePlan(baseIssue);
expect(plan.name).toBe('Issue #42: Add dark mode support');
expect(plan.goal).toBe('We need dark mode.');
expect(plan.tasks).toHaveLength(3);
expect(plan.tasks[0].name).toBe('Add theme context provider');
expect(plan.tasks[1].name).toBe('Update component styles');
expect(plan.tasks[2].name).toBe('Research themes');
expect(plan.tasks[2].status).toBe('completed');
});
it('should set metadata correctly', () => {
const plan = planner.generatePlan(baseIssue, { agent: 'cursor' });
expect(plan.metadata).toBeDefined();
expect(plan.metadata!.issueNumber).toBe(42);
expect(plan.metadata!.issueUrl).toBe(
'https://github.com/test/repo/issues/42'
);
expect(plan.metadata!.agent).toBe('cursor');
expect(plan.metadata!.generatedAt).toBeDefined();
});
it('should infer tags from labels', () => {
const plan = planner.generatePlan(baseIssue);
expect(plan.tags).toContain('feature');
});
it('should create single task when no checklist', () => {
const issue: GitHubIssue = {
...baseIssue,
body: 'Just a description with no checkboxes.\n\nUpdate `src/theme.ts`.',
};
const plan = planner.generatePlan(issue);
expect(plan.tasks).toHaveLength(1);
expect(plan.tasks[0].name).toBe('Add dark mode support');
expect(plan.tasks[0].files.modify).toContain('src/theme.ts');
});
it('should extract file mentions into task files', () => {
const issue: GitHubIssue = {
...baseIssue,
body: '- [ ] Update `src/components/App.tsx` for theming',
};
const plan = planner.generatePlan(issue);
expect(plan.tasks[0].files.modify).toContain(
'src/components/App.tsx'
);
});
it('should respect includeTests option', () => {
const plan = planner.generatePlan(baseIssue, { includeTests: false });
for (const task of plan.tasks) {
const hasTestStep = task.steps.some((s) => s.type === 'test');
expect(hasTestStep).toBe(false);
}
});
it('should use custom tech stack', () => {
const plan = planner.generatePlan(baseIssue, {
techStack: ['React', 'TypeScript'],
});
expect(plan.techStack).toEqual(['React', 'TypeScript']);
});
});
describe('createIssuePlanner', () => {
it('should create an IssuePlanner instance', () => {
const p = createIssuePlanner();
expect(p).toBeInstanceOf(IssuePlanner);
});
});
});
+7
View File
@@ -27,6 +27,10 @@ export type { TaskTemplate } from './generator.js';
export { PlanExecutor, createPlanExecutor, dryRunExecutor, shellExecutor } from './executor.js';
export type { StepExecutor } from './executor.js';
// Issue Planner
export { IssuePlanner, createIssuePlanner } from './issue-planner.js';
export type { GitHubIssue, IssuePlanOptions } from './issue-planner.js';
// Types
export type {
// Core types
@@ -53,4 +57,7 @@ export type {
// Events
PlanEvent,
PlanEventListener,
// Issue Plan
IssuePlanMetadata,
} from './types.js';
+252
View File
@@ -0,0 +1,252 @@
import { execFileSync } from 'node:child_process';
import { PlanGenerator } from './generator.js';
import type { StructuredPlan, PlanTaskFiles, IssuePlanMetadata } from './types.js';
export type { IssuePlanMetadata };
export interface GitHubIssue {
number: number;
title: string;
body: string;
labels: string[];
assignees: string[];
url: string;
state: string;
}
export interface IssuePlanOptions {
agent?: string;
techStack?: string[];
outputPath?: string;
includeTests?: boolean;
}
interface ParsedRef {
owner?: string;
repo?: string;
number: number;
}
interface ExtractedTask {
name: string;
checked: boolean;
}
const LABEL_TAG_MAP: Record<string, string> = {
bug: 'fix',
fix: 'fix',
enhancement: 'feature',
feature: 'feature',
documentation: 'docs',
docs: 'docs',
refactor: 'refactor',
refactoring: 'refactor',
test: 'test',
testing: 'test',
security: 'security',
performance: 'performance',
'good first issue': 'beginner',
chore: 'chore',
maintenance: 'chore',
};
const FILE_PATH_REGEX = /`([a-zA-Z0-9_./\-]+\.[a-zA-Z0-9]+)`/g;
export class IssuePlanner {
parseIssueRef(ref: string): ParsedRef {
const urlMatch = ref.match(
/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/
);
if (urlMatch) {
return {
owner: urlMatch[1],
repo: urlMatch[2],
number: parseInt(urlMatch[3], 10),
};
}
const fullMatch = ref.match(/^([^/]+)\/([^#]+)#(\d+)$/);
if (fullMatch) {
return {
owner: fullMatch[1],
repo: fullMatch[2],
number: parseInt(fullMatch[3], 10),
};
}
const shortMatch = ref.match(/^#?(\d+)$/);
if (shortMatch) {
return { number: parseInt(shortMatch[1], 10) };
}
throw new Error(
`Invalid issue reference: "${ref}". Use #123, owner/repo#123, or a GitHub URL.`
);
}
fetchIssue(ref: string): GitHubIssue {
const parsed = this.parseIssueRef(ref);
const args = [
'issue',
'view',
String(parsed.number),
'--json',
'number,title,body,labels,assignees,url,state',
];
if (parsed.owner && parsed.repo) {
args.push('--repo', `${parsed.owner}/${parsed.repo}`);
}
const result = execFileSync('gh', args, {
encoding: 'utf-8',
timeout: 15_000,
});
let data: {
number: number;
title: string;
body?: string;
labels?: Array<{ name: string }>;
assignees?: Array<{ login: string }>;
url: string;
state: string;
};
try {
data = JSON.parse(result);
} catch {
throw new Error(`Failed to parse GitHub CLI response for issue ${parsed.number}`);
}
return {
number: data.number,
title: data.title,
body: data.body || '',
labels: (data.labels || []).map((l) => l.name),
assignees: (data.assignees || []).map((a) => a.login),
url: data.url,
state: data.state,
};
}
extractTasksFromBody(body: string): ExtractedTask[] {
const tasks: ExtractedTask[] = [];
const lines = body.split('\n');
for (const line of lines) {
const match = line.match(/^[\s]*-\s*\[([ xX])\]\s+(.+)$/);
if (match) {
tasks.push({
name: match[2].trim(),
checked: match[1] !== ' ',
});
}
}
return tasks;
}
extractFileMentions(text: string): string[] {
const files = new Set<string>();
let match: RegExpExecArray | null;
const regex = new RegExp(FILE_PATH_REGEX.source, 'g');
while ((match = regex.exec(text)) !== null) {
const path = match[1];
if (path.includes('/') || path.includes('.')) {
files.add(path);
}
}
return [...files];
}
inferLabelsToTags(labels: string[]): string[] {
const tags: string[] = [];
for (const label of labels) {
const tag = LABEL_TAG_MAP[label.toLowerCase()];
if (tag && !tags.includes(tag)) {
tags.push(tag);
}
}
return tags;
}
generatePlan(
issue: GitHubIssue,
options?: IssuePlanOptions
): StructuredPlan {
const agent = options?.agent || 'claude-code';
const includeTests = options?.includeTests !== false;
const bodyFirstParagraph =
issue.body.split('\n\n')[0]?.trim() || issue.title;
const generator = new PlanGenerator({
includeTests,
includeCommits: true,
techStack: options?.techStack,
});
const plan = generator.createPlan(
`Issue #${issue.number}: ${issue.title}`,
bodyFirstParagraph
);
plan.tags = this.inferLabelsToTags(issue.labels);
const checklist = this.extractTasksFromBody(issue.body);
const allFileMentions = this.extractFileMentions(issue.body);
if (checklist.length > 0) {
for (const item of checklist) {
const taskFiles = this.extractFileMentions(item.name);
const files: PlanTaskFiles = {};
if (taskFiles.length > 0) {
files.modify = taskFiles;
}
const task = generator.addTask(plan, item.name, {
files,
tags: item.checked ? ['done'] : undefined,
steps: [
{ type: 'implement', description: item.name },
...(includeTests
? [{ type: 'test' as const, description: `Write tests for ${item.name}` }]
: []),
],
});
if (item.checked) {
task.status = 'completed';
}
}
} else {
const files: PlanTaskFiles = {};
if (allFileMentions.length > 0) {
files.modify = allFileMentions;
}
generator.addTask(plan, issue.title, {
description: bodyFirstParagraph,
files,
steps: [
{ type: 'implement', description: issue.title },
...(includeTests
? [{ type: 'test' as const, description: `Write tests for ${issue.title}` }]
: []),
],
});
}
plan.metadata = {
issueNumber: issue.number,
issueUrl: issue.url,
issueLabels: issue.labels,
agent,
generatedAt: new Date().toISOString(),
} satisfies IssuePlanMetadata;
return plan;
}
}
export function createIssuePlanner(): IssuePlanner {
return new IssuePlanner();
}
+8
View File
@@ -270,3 +270,11 @@ export type PlanEventListener = (
task?: PlanTask,
result?: PlanTaskResult
) => void | Promise<void>;
export interface IssuePlanMetadata {
issueNumber: number;
issueUrl: string;
issueLabels: string[];
agent: string;
generatedAt: string;
}
@@ -0,0 +1,334 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { ActivityLog } from '../activity-log.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
}));
describe('ActivityLog', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-02-10T12:00:00Z'));
});
afterEach(() => {
vi.useRealTimers();
vi.resetAllMocks();
});
describe('constructor', () => {
it('should create an instance', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
expect(log).toBeDefined();
});
});
describe('record', () => {
it('should record a new activity entry', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
log.record({
commitSha: 'abc1234',
message: 'fix: parser edge case',
activeSkills: ['code-simplifier'],
filesChanged: ['src/index.ts'],
});
expect(vi.mocked(writeFileSync)).toHaveBeenCalledTimes(1);
const content = vi.mocked(writeFileSync).mock.calls[0][1] as string;
expect(content).toContain('abc1234');
expect(content).toContain('code-simplifier');
expect(content).toContain('src/index.ts');
expect(content).toContain('fix: parser edge case');
});
it('should prepend new activities (most recent first)', () => {
const existing = `
version: 1
activities:
- commitSha: "old1234"
committedAt: "2026-02-09T10:00:00.000Z"
activeSkills:
- remotion-best-practices
filesChanged:
- src/old.ts
message: "feat: old feature"
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existing);
const log = new ActivityLog('/test/project');
log.record({
commitSha: 'new5678',
message: 'fix: new fix',
activeSkills: ['code-simplifier'],
filesChanged: ['src/new.ts'],
});
const content = vi.mocked(writeFileSync).mock.calls[0][1] as string;
const newIdx = content.indexOf('new5678');
const oldIdx = content.indexOf('old1234');
expect(newIdx).toBeLessThan(oldIdx);
});
it('should cap activities at 500', () => {
const activityEntries = Array.from({ length: 500 }, (_, i) => `
- commitSha: "sha${i}"
committedAt: "2026-02-09T10:00:00.000Z"
activeSkills:
- skill-a
filesChanged:
- file.ts
message: "commit ${i}"`).join('');
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
`version: 1\nactivities:${activityEntries}`
);
const log = new ActivityLog('/test/project');
log.record({
commitSha: 'newsha',
message: 'new commit',
activeSkills: ['skill-b'],
filesChanged: ['new.ts'],
});
expect(vi.mocked(writeFileSync)).toHaveBeenCalledTimes(1);
const content = vi.mocked(writeFileSync).mock.calls[0][1] as string;
expect(content).toContain('newsha');
const commitMatches = content.match(/commitSha:/g);
expect(commitMatches!.length).toBe(500);
});
});
describe('getByCommit', () => {
it('should find activity by full SHA', () => {
const existing = `
version: 1
activities:
- commitSha: "abc1234567890"
committedAt: "2026-02-10T10:00:00.000Z"
activeSkills:
- code-simplifier
filesChanged:
- src/index.ts
message: "fix: edge case"
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existing);
const log = new ActivityLog('/test/project');
const result = log.getByCommit('abc1234567890');
expect(result).toBeDefined();
expect(result!.commitSha).toBe('abc1234567890');
});
it('should find activity by short SHA prefix', () => {
const existing = `
version: 1
activities:
- commitSha: "abc1234567890"
committedAt: "2026-02-10T10:00:00.000Z"
activeSkills:
- code-simplifier
filesChanged:
- src/index.ts
message: "fix: edge case"
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existing);
const log = new ActivityLog('/test/project');
const result = log.getByCommit('abc1234');
expect(result).toBeDefined();
expect(result!.commitSha).toBe('abc1234567890');
});
it('should return undefined for unknown SHA', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
const result = log.getByCommit('nonexistent');
expect(result).toBeUndefined();
});
});
describe('getBySkill', () => {
it('should filter activities by skill name', () => {
const existing = `
version: 1
activities:
- commitSha: "sha1"
committedAt: "2026-02-10T12:00:00.000Z"
activeSkills:
- code-simplifier
filesChanged:
- src/a.ts
message: "fix: a"
- commitSha: "sha2"
committedAt: "2026-02-10T11:00:00.000Z"
activeSkills:
- remotion-best-practices
filesChanged:
- src/b.ts
message: "feat: b"
- commitSha: "sha3"
committedAt: "2026-02-10T10:00:00.000Z"
activeSkills:
- code-simplifier
- remotion-best-practices
filesChanged:
- src/c.ts
message: "refactor: c"
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existing);
const log = new ActivityLog('/test/project');
const results = log.getBySkill('code-simplifier');
expect(results).toHaveLength(2);
expect(results[0].commitSha).toBe('sha1');
expect(results[1].commitSha).toBe('sha3');
});
it('should return empty array for unknown skill', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
const results = log.getBySkill('nonexistent');
expect(results).toEqual([]);
});
});
describe('getRecent', () => {
it('should return recent activities with default limit', () => {
const activities = Array.from({ length: 25 }, (_, i) => `
- commitSha: "sha${i}"
committedAt: "2026-02-10T12:${String(i).padStart(2, '0')}:00.000Z"
activeSkills:
- skill-a
filesChanged:
- file${i}.ts
message: "commit ${i}"
`).join('');
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
`version: 1\nactivities:\n${activities}`
);
const log = new ActivityLog('/test/project');
const results = log.getRecent();
expect(results).toHaveLength(20);
});
it('should respect custom limit', () => {
const activities = Array.from({ length: 10 }, (_, i) => `
- commitSha: "sha${i}"
committedAt: "2026-02-10T12:${String(i).padStart(2, '0')}:00.000Z"
activeSkills:
- skill-a
filesChanged:
- file${i}.ts
message: "commit ${i}"
`).join('');
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
`version: 1\nactivities:\n${activities}`
);
const log = new ActivityLog('/test/project');
const results = log.getRecent(3);
expect(results).toHaveLength(3);
});
it('should return empty array when no activities exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
const results = log.getRecent();
expect(results).toEqual([]);
});
});
describe('getMostUsedSkills', () => {
it('should return skills sorted by usage count', () => {
const existing = `
version: 1
activities:
- commitSha: "sha1"
committedAt: "2026-02-10T12:00:00.000Z"
activeSkills:
- code-simplifier
filesChanged:
- a.ts
message: "a"
- commitSha: "sha2"
committedAt: "2026-02-10T11:00:00.000Z"
activeSkills:
- remotion-best-practices
- code-simplifier
filesChanged:
- b.ts
message: "b"
- commitSha: "sha3"
committedAt: "2026-02-10T10:00:00.000Z"
activeSkills:
- remotion-best-practices
- code-simplifier
- visual-storyteller
filesChanged:
- c.ts
message: "c"
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existing);
const log = new ActivityLog('/test/project');
const topSkills = log.getMostUsedSkills();
expect(topSkills).toHaveLength(3);
expect(topSkills[0]).toEqual({ skill: 'code-simplifier', count: 3 });
expect(topSkills[1]).toEqual({ skill: 'remotion-best-practices', count: 2 });
expect(topSkills[2]).toEqual({ skill: 'visual-storyteller', count: 1 });
});
it('should return empty array when no activities exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const log = new ActivityLog('/test/project');
const topSkills = log.getMostUsedSkills();
expect(topSkills).toEqual([]);
});
});
describe('corrupted file handling', () => {
it('should handle corrupted YAML gracefully', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue('{{invalid yaml');
const log = new ActivityLog('/test/project');
const results = log.getRecent();
expect(results).toEqual([]);
});
});
});
@@ -0,0 +1,332 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { SessionExplainer } from '../session-explainer.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
}));
vi.mock('node:child_process', () => ({
execSync: vi.fn().mockReturnValue(''),
}));
const sessionYaml = `
version: 1
lastActivity: "2026-02-10T14:00:00.000Z"
projectPath: /test/project
currentExecution:
skillName: code-simplifier
skillSource: claude-code
currentStep: 2
totalSteps: 3
status: running
startedAt: "2026-02-10T12:00:00.000Z"
tasks:
- id: task-1
name: Refactor SessionManager
type: auto
status: completed
startedAt: "2026-02-10T12:00:00.000Z"
completedAt: "2026-02-10T12:45:00.000Z"
filesModified:
- src/session/manager.ts
- id: task-2
name: Add snapshot tests
type: auto
status: completed
startedAt: "2026-02-10T12:45:00.000Z"
completedAt: "2026-02-10T13:17:00.000Z"
filesModified:
- src/session/__tests__/snapshot.test.ts
- id: task-3
name: Update documentation
type: auto
status: paused
history:
- skillName: remotion-best-practices
skillSource: local
completedAt: "2026-02-10T11:00:00.000Z"
durationMs: 120000
status: completed
commits:
- sha1
filesModified:
- src/video.ts
decisions:
- key: snapshot-format
value: YAML
madeAt: "2026-02-10T12:30:00.000Z"
- key: storage-location
value: ".skillkit/snapshots/"
madeAt: "2026-02-10T12:35:00.000Z"
`;
const observationsYaml = `
version: 1
sessionId: session-1
observations:
- id: obs-1
timestamp: "2026-02-10T12:10:00.000Z"
sessionId: session-1
agent: claude-code
type: error
content:
action: Build failed
context: Type error
relevance: 90
- id: obs-2
timestamp: "2026-02-10T12:15:00.000Z"
sessionId: session-1
agent: claude-code
type: solution
content:
action: Fixed type
context: Added annotation
relevance: 85
- id: obs-3
timestamp: "2026-02-10T12:20:00.000Z"
sessionId: session-1
agent: claude-code
type: pattern
content:
action: Detected pattern
context: Recurring fix
relevance: 70
- id: obs-4
timestamp: "2026-02-10T12:25:00.000Z"
sessionId: session-1
agent: claude-code
type: error
content:
action: Test failed
context: Assertion error
relevance: 80
- id: obs-5
timestamp: "2026-02-10T12:30:00.000Z"
sessionId: session-1
agent: claude-code
type: solution
content:
action: Fixed test
context: Updated assertion
relevance: 75
`;
describe('SessionExplainer', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-02-10T14:34:00Z'));
});
afterEach(() => {
vi.useRealTimers();
vi.resetAllMocks();
});
describe('explain', () => {
it('should return a full explanation with active session', () => {
vi.mocked(existsSync).mockImplementation((filepath: any) => {
const path = String(filepath);
if (path.includes('session.yaml')) return true;
if (path.includes('.git')) return false;
return false;
});
vi.mocked(readFileSync).mockImplementation((filepath: any) => {
const path = String(filepath);
if (path.includes('session.yaml')) return sessionYaml;
return '';
});
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
expect(explanation.agent).toBe('claude-code');
expect(explanation.duration).toBeDefined();
expect(explanation.skillsUsed).toHaveLength(2);
expect(explanation.skillsUsed[0].name).toBe('code-simplifier');
expect(explanation.skillsUsed[0].status).toBe('running');
expect(explanation.skillsUsed[1].name).toBe('remotion-best-practices');
expect(explanation.skillsUsed[1].status).toBe('completed');
expect(explanation.tasks).toHaveLength(3);
expect(explanation.tasks[0].name).toBe('Refactor SessionManager');
expect(explanation.tasks[0].duration).toBe('45m');
expect(explanation.tasks[1].name).toBe('Add snapshot tests');
expect(explanation.tasks[1].duration).toBe('32m');
expect(explanation.tasks[2].name).toBe('Update documentation');
expect(explanation.filesModified).toContain('src/session/manager.ts');
expect(explanation.filesModified).toContain('src/video.ts');
expect(explanation.decisions).toHaveLength(2);
expect(explanation.decisions[0].key).toBe('snapshot-format');
expect(explanation.decisions[0].value).toBe('YAML');
});
it('should deduplicate files across current execution and history', () => {
const sessionWithDupes = `
version: 1
lastActivity: "2026-02-10T14:00:00.000Z"
projectPath: /test/project
currentExecution:
skillName: skill-a
skillSource: local
currentStep: 1
totalSteps: 1
status: completed
startedAt: "2026-02-10T12:00:00.000Z"
tasks:
- id: task-1
name: Task A
type: auto
status: completed
filesModified:
- src/shared.ts
- src/a.ts
history:
- skillName: skill-b
skillSource: local
completedAt: "2026-02-10T11:00:00.000Z"
durationMs: 60000
status: completed
commits: []
filesModified:
- src/shared.ts
- src/b.ts
decisions: []
`;
vi.mocked(existsSync).mockImplementation((filepath: any) => {
return String(filepath).includes('session.yaml');
});
vi.mocked(readFileSync).mockReturnValue(sessionWithDupes);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
expect(explanation.filesModified).toHaveLength(3);
expect(explanation.filesModified).toContain('src/shared.ts');
expect(explanation.filesModified).toContain('src/a.ts');
expect(explanation.filesModified).toContain('src/b.ts');
});
it('should return empty explanation when no session exists', () => {
vi.mocked(existsSync).mockReturnValue(false);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
expect(explanation.agent).toBe('unknown');
expect(explanation.skillsUsed).toEqual([]);
expect(explanation.tasks).toEqual([]);
expect(explanation.filesModified).toEqual([]);
expect(explanation.decisions).toEqual([]);
expect(explanation.gitCommits).toBe(0);
});
it('should skip git when includeGit is false', () => {
vi.mocked(existsSync).mockReturnValue(false);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
expect(explanation.gitCommits).toBe(0);
});
it('should default observation counts to zero when store is unavailable', () => {
vi.mocked(existsSync).mockReturnValue(false);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
expect(explanation.observationCounts).toEqual({
errors: 0,
solutions: 0,
patterns: 0,
total: 0,
});
});
});
describe('formatText', () => {
it('should format explanation as readable text', () => {
vi.mocked(existsSync).mockImplementation((filepath: any) => {
const path = String(filepath);
if (path.includes('session.yaml')) return true;
if (path.includes('observations.yaml')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((filepath: any) => {
const path = String(filepath);
if (path.includes('session.yaml')) return sessionYaml;
if (path.includes('observations.yaml')) return observationsYaml;
return '';
});
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
const text = explainer.formatText(explanation);
expect(text).toContain('Session Summary');
expect(text).toContain('Duration:');
expect(text).toContain('Agent:');
expect(text).toContain('Skills Used');
expect(text).toContain('code-simplifier');
expect(text).toContain('Tasks');
expect(text).toContain('Refactor SessionManager');
expect(text).toContain('Files Modified:');
expect(text).toContain('Decisions');
expect(text).toContain('snapshot-format');
expect(text).toContain('Observations:');
});
it('should handle empty explanation', () => {
vi.mocked(existsSync).mockReturnValue(false);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
const text = explainer.formatText(explanation);
expect(text).toContain('Session Summary');
expect(text).toContain('Agent:');
expect(text).toContain('Files Modified: 0 files');
});
});
describe('formatJson', () => {
it('should format explanation as valid JSON', () => {
vi.mocked(existsSync).mockReturnValue(false);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
const json = explainer.formatJson(explanation);
const parsed = JSON.parse(json);
expect(parsed.date).toBeDefined();
expect(parsed.agent).toBe('unknown');
expect(parsed.skillsUsed).toEqual([]);
expect(parsed.observationCounts).toBeDefined();
});
it('should output valid JSON for a full explanation', () => {
vi.mocked(existsSync).mockImplementation((filepath: any) => {
const path = String(filepath);
if (path.includes('session.yaml')) return true;
return false;
});
vi.mocked(readFileSync).mockReturnValue(sessionYaml);
const explainer = new SessionExplainer('/test/project');
const explanation = explainer.explain({ includeGit: false });
const json = explainer.formatJson(explanation);
const parsed = JSON.parse(json);
expect(parsed.skillsUsed).toHaveLength(2);
expect(parsed.tasks).toHaveLength(3);
expect(parsed.decisions).toHaveLength(2);
});
});
});
@@ -0,0 +1,376 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
existsSync,
readFileSync,
writeFileSync,
mkdirSync,
readdirSync,
unlinkSync,
} from 'node:fs';
import { SnapshotManager } from '../snapshot-manager.js';
import type { SessionState } from '../types.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
readdirSync: vi.fn(),
unlinkSync: vi.fn(),
}));
const mockSessionState: SessionState = {
version: 1,
lastActivity: '2026-02-10T12:00:00.000Z',
projectPath: '/test/project',
history: [
{
skillName: 'code-simplifier',
skillSource: 'local',
completedAt: '2026-02-10T11:00:00.000Z',
durationMs: 60000,
status: 'completed',
commits: ['sha1'],
filesModified: ['src/index.ts'],
},
],
decisions: [
{
key: 'format',
value: 'yaml',
madeAt: '2026-02-10T10:00:00.000Z',
},
],
};
const mockObservations = [
{
id: 'obs-1',
timestamp: '2026-02-10T10:00:00.000Z',
sessionId: 'session-1',
agent: 'claude-code',
type: 'error',
content: { action: 'Build failed', context: 'TS error' },
relevance: 80,
},
];
describe('SnapshotManager', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-02-10T12:00:00Z'));
});
afterEach(() => {
vi.useRealTimers();
vi.resetAllMocks();
});
describe('save', () => {
it('should save a snapshot to disk', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
manager.save('my-feature', mockSessionState, mockObservations, 'Before refactor');
expect(vi.mocked(mkdirSync)).toHaveBeenCalledWith(
expect.stringContaining('snapshots'),
{ recursive: true }
);
expect(vi.mocked(writeFileSync)).toHaveBeenCalledTimes(1);
const content = vi.mocked(writeFileSync).mock.calls[0][1] as string;
expect(content).toContain('my-feature');
expect(content).toContain('Before refactor');
expect(content).toContain('code-simplifier');
});
it('should save without description', () => {
vi.mocked(existsSync).mockReturnValue(true);
const manager = new SnapshotManager('/test/project');
manager.save('quick-save', mockSessionState, []);
const content = vi.mocked(writeFileSync).mock.calls[0][1] as string;
expect(content).toContain('quick-save');
});
});
describe('restore', () => {
it('should restore a snapshot from disk', () => {
const snapshotYaml = `
version: 1
name: my-feature
createdAt: "2026-02-10T12:00:00.000Z"
description: Before refactor
sessionState:
version: 1
lastActivity: "2026-02-10T12:00:00.000Z"
projectPath: /test/project
history:
- skillName: code-simplifier
skillSource: local
completedAt: "2026-02-10T11:00:00.000Z"
durationMs: 60000
status: completed
commits:
- sha1
filesModified:
- src/index.ts
decisions:
- key: format
value: yaml
madeAt: "2026-02-10T10:00:00.000Z"
observations:
- id: obs-1
timestamp: "2026-02-10T10:00:00.000Z"
sessionId: session-1
agent: claude-code
type: error
content:
action: Build failed
context: TS error
relevance: 80
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(snapshotYaml);
const manager = new SnapshotManager('/test/project');
const result = manager.restore('my-feature');
expect(result.sessionState.version).toBe(1);
expect(result.sessionState.history).toHaveLength(1);
expect(result.sessionState.history[0].skillName).toBe('code-simplifier');
expect(result.observations).toHaveLength(1);
expect(result.observations[0].id).toBe('obs-1');
});
it('should throw if snapshot does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
expect(() => manager.restore('nonexistent')).toThrow(
'Snapshot "nonexistent" not found'
);
});
});
describe('list', () => {
it('should list all snapshots sorted by creation date', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readdirSync).mockReturnValue([
'old-snap.yaml',
'new-snap.yaml',
] as unknown as ReturnType<typeof readdirSync>);
vi.mocked(readFileSync).mockImplementation((filepath: any) => {
if (String(filepath).includes('old-snap')) {
return `
version: 1
name: old-snap
createdAt: "2026-02-09T10:00:00.000Z"
sessionState:
version: 1
lastActivity: "2026-02-09T10:00:00.000Z"
projectPath: /test/project
history: []
decisions: []
observations: []
`;
}
return `
version: 1
name: new-snap
createdAt: "2026-02-10T10:00:00.000Z"
description: Latest snapshot
sessionState:
version: 1
lastActivity: "2026-02-10T10:00:00.000Z"
projectPath: /test/project
history:
- skillName: code-simplifier
skillSource: local
completedAt: "2026-02-10T09:00:00.000Z"
durationMs: 30000
status: completed
commits: []
filesModified: []
decisions: []
observations: []
`;
});
const manager = new SnapshotManager('/test/project');
const snapshots = manager.list();
expect(snapshots).toHaveLength(2);
expect(snapshots[0].name).toBe('new-snap');
expect(snapshots[0].description).toBe('Latest snapshot');
expect(snapshots[0].skillCount).toBe(1);
expect(snapshots[1].name).toBe('old-snap');
expect(snapshots[1].skillCount).toBe(0);
});
it('should return empty array when no snapshots dir exists', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
const snapshots = manager.list();
expect(snapshots).toEqual([]);
});
it('should skip corrupted snapshot files', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readdirSync).mockReturnValue([
'good.yaml',
'bad.yaml',
] as unknown as ReturnType<typeof readdirSync>);
vi.mocked(readFileSync).mockImplementation((filepath: any) => {
if (String(filepath).includes('bad')) {
return '{{invalid yaml';
}
return `
version: 1
name: good
createdAt: "2026-02-10T10:00:00.000Z"
sessionState:
version: 1
lastActivity: "2026-02-10T10:00:00.000Z"
projectPath: /test/project
history: []
decisions: []
observations: []
`;
});
const manager = new SnapshotManager('/test/project');
const snapshots = manager.list();
expect(snapshots).toHaveLength(1);
expect(snapshots[0].name).toBe('good');
});
});
describe('get', () => {
it('should return snapshot by name', () => {
const snapshotYaml = `
version: 1
name: test-snap
createdAt: "2026-02-10T12:00:00.000Z"
sessionState:
version: 1
lastActivity: "2026-02-10T12:00:00.000Z"
projectPath: /test/project
history: []
decisions: []
observations: []
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(snapshotYaml);
const manager = new SnapshotManager('/test/project');
const snapshot = manager.get('test-snap');
expect(snapshot).toBeDefined();
expect(snapshot!.name).toBe('test-snap');
});
it('should return undefined for nonexistent snapshot', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
const snapshot = manager.get('nonexistent');
expect(snapshot).toBeUndefined();
});
});
describe('delete', () => {
it('should delete a snapshot file', () => {
vi.mocked(existsSync).mockReturnValue(true);
const manager = new SnapshotManager('/test/project');
const result = manager.delete('my-feature');
expect(result).toBe(true);
expect(vi.mocked(unlinkSync)).toHaveBeenCalledWith(
expect.stringContaining('my-feature.yaml')
);
});
it('should return false for nonexistent snapshot', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
const result = manager.delete('nonexistent');
expect(result).toBe(false);
expect(vi.mocked(unlinkSync)).not.toHaveBeenCalled();
});
});
describe('exists', () => {
it('should return true when snapshot file exists', () => {
vi.mocked(existsSync).mockReturnValue(true);
const manager = new SnapshotManager('/test/project');
expect(manager.exists('my-feature')).toBe(true);
});
it('should return false when snapshot file does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
expect(manager.exists('nonexistent')).toBe(false);
});
});
describe('path traversal protection', () => {
it('should reject names with path separators', () => {
const manager = new SnapshotManager('/test/project');
expect(() => manager.exists('../../etc/passwd')).toThrow('Invalid snapshot name');
expect(() => manager.exists('../config')).toThrow('Invalid snapshot name');
});
it('should reject names with special characters', () => {
const manager = new SnapshotManager('/test/project');
expect(() => manager.exists('snap shot')).toThrow('Invalid snapshot name');
expect(() => manager.exists('snap.shot')).toThrow('Invalid snapshot name');
});
it('should allow valid names with hyphens and underscores', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new SnapshotManager('/test/project');
expect(() => manager.exists('my-feature_v2')).not.toThrow();
});
});
describe('restore validation', () => {
it('should throw on corrupted YAML', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue('{{invalid yaml');
const manager = new SnapshotManager('/test/project');
expect(() => manager.restore('corrupted')).toThrow('Failed to read snapshot');
});
it('should throw on missing sessionState', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
name: broken
createdAt: "2026-02-10T12:00:00.000Z"
observations: []
`);
const manager = new SnapshotManager('/test/project');
expect(() => manager.restore('broken')).toThrow('corrupted or invalid');
});
});
});
+107
View File
@@ -0,0 +1,107 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { parse, stringify } from 'yaml';
import type { SkillActivity, ActivityLogData } from './types.js';
const ACTIVITY_FILE = 'activity.yaml';
export class ActivityLog {
private readonly filePath: string;
private readonly projectPath: string;
private data: ActivityLogData | null = null;
constructor(projectPath: string) {
this.projectPath = projectPath;
this.filePath = join(projectPath, '.skillkit', ACTIVITY_FILE);
}
private createEmpty(): ActivityLogData {
return { version: 1, activities: [] };
}
private load(): ActivityLogData {
if (this.data) return this.data;
if (!existsSync(this.filePath)) {
this.data = this.createEmpty();
return this.data;
}
try {
const content = readFileSync(this.filePath, 'utf-8');
const parsed = parse(content);
if (parsed && Array.isArray(parsed.activities)) {
this.data = parsed as ActivityLogData;
} else {
this.data = this.createEmpty();
}
} catch {
this.data = this.createEmpty();
}
return this.data;
}
private save(): void {
const dir = join(this.projectPath, '.skillkit');
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(this.filePath, stringify(this.data));
}
record(entry: {
commitSha: string;
message: string;
activeSkills: string[];
filesChanged: string[];
}): void {
const data = this.load();
data.activities.unshift({
commitSha: entry.commitSha,
committedAt: new Date().toISOString(),
activeSkills: entry.activeSkills,
filesChanged: entry.filesChanged,
message: entry.message,
});
if (data.activities.length > 500) {
data.activities = data.activities.slice(0, 500);
}
this.save();
}
getByCommit(sha: string): SkillActivity | undefined {
if (sha.length < 4) return undefined;
const data = this.load();
return data.activities.find(
(a) => a.commitSha === sha || a.commitSha.startsWith(sha)
);
}
getBySkill(skillName: string): SkillActivity[] {
const data = this.load();
return data.activities.filter((a) => a.activeSkills.includes(skillName));
}
getRecent(limit = 20): SkillActivity[] {
const data = this.load();
return data.activities.slice(0, limit);
}
getMostUsedSkills(): Array<{ skill: string; count: number }> {
const data = this.load();
const counts = new Map<string, number>();
for (const activity of data.activities) {
for (const skill of activity.activeSkills) {
counts.set(skill, (counts.get(skill) ?? 0) + 1);
}
}
return Array.from(counts.entries())
.map(([skill, count]) => ({ skill, count }))
.sort((a, b) => b.count - a.count);
}
}
+3
View File
@@ -8,3 +8,6 @@ export * from './types.js';
export * from './manager.js';
export * from './state-file.js';
export { SessionManager, createSessionManager } from './manager.js';
export { ActivityLog } from './activity-log.js';
export { SnapshotManager } from './snapshot-manager.js';
export { SessionExplainer } from './session-explainer.js';
@@ -0,0 +1,195 @@
import type { SessionExplanation } from './types.js';
import { SessionManager } from './manager.js';
import { ObservationStore } from '../memory/observation-store.js';
import { getGitCommits } from '../learning/git-analyzer.js';
import { loadConfig } from '../config.js';
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
const remainMinutes = minutes % 60;
return `${hours}h ${remainMinutes}m`;
}
if (minutes > 0) {
return `${minutes}m`;
}
return `${seconds}s`;
}
export class SessionExplainer {
private readonly projectPath: string;
private readonly sessionManager: SessionManager;
constructor(projectPath: string) {
this.projectPath = projectPath;
this.sessionManager = new SessionManager(projectPath);
}
explain(options?: { includeGit?: boolean }): SessionExplanation {
const state = this.sessionManager.get();
const includeGit = options?.includeGit !== false;
const explanation: SessionExplanation = {
date: new Date().toISOString().split('T')[0],
agent: 'unknown',
skillsUsed: [],
tasks: [],
filesModified: [],
decisions: [],
observationCounts: { errors: 0, solutions: 0, patterns: 0, total: 0 },
gitCommits: 0,
};
if (!state) {
return explanation;
}
try {
const configAgent = loadConfig().agent;
if (configAgent && configAgent !== 'universal') {
explanation.agent = configAgent;
} else if (state.currentExecution?.skillSource) {
explanation.agent = state.currentExecution.skillSource;
}
} catch {
if (state.currentExecution?.skillSource) {
explanation.agent = state.currentExecution.skillSource;
}
}
if (state.currentExecution) {
const exec = state.currentExecution;
const startTime = new Date(exec.startedAt).getTime();
explanation.duration = formatDuration(Date.now() - startTime);
explanation.skillsUsed.push({
name: exec.skillName,
status: exec.status,
});
for (const task of exec.tasks) {
const taskEntry: { name: string; status: string; duration?: string } = {
name: task.name,
status: task.status,
};
if (task.startedAt && task.completedAt) {
const dur =
new Date(task.completedAt).getTime() -
new Date(task.startedAt).getTime();
taskEntry.duration = formatDuration(dur);
}
explanation.tasks.push(taskEntry);
if (task.filesModified) {
explanation.filesModified.push(...task.filesModified);
}
}
}
for (const hist of state.history ?? []) {
const alreadyListed = explanation.skillsUsed.some(
(s) => s.name === hist.skillName
);
if (!alreadyListed) {
explanation.skillsUsed.push({
name: hist.skillName,
status: hist.status,
});
}
if (hist.filesModified) {
explanation.filesModified.push(...hist.filesModified);
}
}
explanation.filesModified = [...new Set(explanation.filesModified)];
explanation.decisions = (state.decisions ?? []).map(({ key, value }) => ({ key, value }));
try {
const observations = ObservationStore.readAll(this.projectPath);
const countByType = (type: string) => observations.filter((o) => o.type === type).length;
explanation.observationCounts = {
total: observations.length,
errors: countByType('error'),
solutions: countByType('solution'),
patterns: countByType('pattern'),
};
} catch {
// No observation store available
}
if (includeGit) {
try {
const commits = getGitCommits(this.projectPath, { commits: 50 });
const today = new Date().toISOString().split('T')[0];
explanation.gitCommits = commits.filter((c) =>
c.date.startsWith(today)
).length;
} catch {
// Git not available
}
}
return explanation;
}
formatText(explanation: SessionExplanation): string {
const lines: string[] = [];
lines.push(' Session Summary\n');
if (explanation.duration) {
lines.push(` Duration: ${explanation.duration}`);
}
lines.push(` Agent: ${explanation.agent}`);
lines.push('');
if (explanation.skillsUsed.length > 0) {
lines.push(' Skills Used');
for (const skill of explanation.skillsUsed) {
const icon = skill.status === 'completed' ? '\u2713' : '\u25CB';
lines.push(` ${icon} ${skill.name} (${skill.status})`);
}
lines.push('');
}
if (explanation.tasks.length > 0) {
lines.push(` Tasks (${explanation.tasks.length} total)`);
for (const task of explanation.tasks) {
const icon = task.status === 'completed' ? '\u2713' : '\u25CB';
const dur = task.duration ? ` (${task.duration})` : '';
lines.push(` ${icon} ${task.name}${dur}`);
}
lines.push('');
}
lines.push(` Files Modified: ${explanation.filesModified.length} files`);
lines.push(` Git Commits: ${explanation.gitCommits}`);
lines.push('');
if (explanation.decisions.length > 0) {
lines.push(' Decisions');
for (const d of explanation.decisions) {
lines.push(` ${d.key} \u2192 ${d.value}`);
}
lines.push('');
}
const obs = explanation.observationCounts;
lines.push(
` Observations: ${obs.errors} errors, ${obs.solutions} solutions, ${obs.patterns} patterns`
);
return lines.join('\n');
}
formatJson(explanation: SessionExplanation): string {
return JSON.stringify(explanation, null, 2);
}
}
@@ -0,0 +1,154 @@
import {
existsSync,
mkdirSync,
readFileSync,
writeFileSync,
readdirSync,
unlinkSync,
} from 'node:fs';
import { join } from 'node:path';
import { parse, stringify } from 'yaml';
import type { SessionState, SessionSnapshot } from './types.js';
const SAFE_NAME_RE = /^[a-zA-Z0-9_-]+$/;
export class SnapshotManager {
private readonly snapshotsDir: string;
constructor(projectPath: string) {
this.snapshotsDir = join(projectPath, '.skillkit', 'snapshots');
}
private ensureDir(): void {
if (!existsSync(this.snapshotsDir)) {
mkdirSync(this.snapshotsDir, { recursive: true });
}
}
private sanitizeName(name: string): string {
if (!name || !SAFE_NAME_RE.test(name)) {
throw new Error(`Invalid snapshot name: "${name}". Use only letters, numbers, hyphens, and underscores.`);
}
return name;
}
private getPath(name: string): string {
const safe = this.sanitizeName(name);
return join(this.snapshotsDir, `${safe}.yaml`);
}
save(
name: string,
sessionState: SessionState,
observations: SessionSnapshot['observations'],
description?: string
): void {
this.ensureDir();
const snapshot: SessionSnapshot = {
version: 1,
name,
createdAt: new Date().toISOString(),
description,
sessionState,
observations,
};
writeFileSync(this.getPath(name), stringify(snapshot));
}
restore(name: string): {
sessionState: SessionState;
observations: SessionSnapshot['observations'];
} {
const filepath = this.getPath(name);
if (!existsSync(filepath)) {
throw new Error(`Snapshot "${name}" not found`);
}
let snapshot: SessionSnapshot;
try {
const content = readFileSync(filepath, 'utf-8');
snapshot = parse(content) as SessionSnapshot;
} catch (err) {
throw new Error(`Failed to read snapshot "${name}": ${err instanceof Error ? err.message : 'unknown error'}`);
}
if (!snapshot.sessionState || !snapshot.observations) {
throw new Error(`Snapshot "${name}" is corrupted or invalid`);
}
return {
sessionState: snapshot.sessionState,
observations: snapshot.observations,
};
}
list(): Array<{
name: string;
createdAt: string;
description?: string;
skillCount: number;
}> {
if (!existsSync(this.snapshotsDir)) {
return [];
}
const files = readdirSync(this.snapshotsDir).filter((f) =>
f.endsWith('.yaml')
);
return files
.map((f) => {
try {
const content = readFileSync(join(this.snapshotsDir, f), 'utf-8');
const snapshot = parse(content) as SessionSnapshot;
if (!snapshot.createdAt) {
return null;
}
const skillCount = snapshot.sessionState?.history?.length ?? 0;
return {
name: snapshot.name ?? f.replace(/\.yaml$/, ''),
createdAt: snapshot.createdAt,
description: snapshot.description,
skillCount,
};
} catch {
return null;
}
})
.filter((s): s is NonNullable<typeof s> => s !== null)
.sort((a, b) => {
const timeA = new Date(a.createdAt).getTime() || 0;
const timeB = new Date(b.createdAt).getTime() || 0;
return timeB - timeA;
});
}
get(name: string): SessionSnapshot | undefined {
const filepath = this.getPath(name);
if (!existsSync(filepath)) {
return undefined;
}
try {
const content = readFileSync(filepath, 'utf-8');
return parse(content) as SessionSnapshot;
} catch {
return undefined;
}
}
delete(name: string): boolean {
const filepath = this.getPath(name);
if (!existsSync(filepath)) {
return false;
}
unlinkSync(filepath);
return true;
}
exists(name: string): boolean {
return existsSync(this.getPath(name));
}
}
+42
View File
@@ -115,3 +115,45 @@ export interface SessionState {
* Session state file path within .skillkit directory
*/
export const SESSION_FILE = 'session.yaml';
export interface SkillActivity {
commitSha: string;
committedAt: string;
activeSkills: string[];
filesChanged: string[];
message: string;
}
export interface ActivityLogData {
version: 1;
activities: SkillActivity[];
}
export interface SessionSnapshot {
version: 1;
name: string;
createdAt: string;
description?: string;
sessionState: SessionState;
observations: Array<{
id: string;
timestamp: string;
sessionId: string;
agent: string;
type: string;
content: Record<string, unknown>;
relevance: number;
}>;
}
export interface SessionExplanation {
date: string;
agent: string;
duration?: string;
skillsUsed: Array<{ name: string; status: string }>;
tasks: Array<{ name: string; status: string; duration?: string }>;
filesModified: string[];
decisions: Array<{ key: string; value: string }>;
observationCounts: { errors: number; solutions: number; patterns: number; total: number };
gitCommits: number;
}