From 935f203a1e985ad5387ed8404febe6885f8804e3 Mon Sep 17 00:00:00 2001 From: wishket-pjw Date: Tue, 30 Dec 2025 01:14:28 +0900 Subject: [PATCH] feat: implement skills system - Implement cross-platform skills system and add initial skills - Implement skill schema and validation logic (Zod-based, YAML frontmatter parsing) - Add MCP tools (list_skills, get_skill) - Add initial skills (TDD, systematic-debugging, writing-plans, executing-plans, etc.) Update adapter documentation (claude-code, codex, cursor) - Add implementation plan documents - Add yaml package dependency close #116 --- apps/mcp-server/package.json | 1 + .../mcp-server/src/mcp/mcp-serverless.spec.ts | 120 +++- apps/mcp-server/src/mcp/mcp-serverless.ts | 119 ++++ apps/mcp-server/src/rules/agent.schema.ts | 48 +- .../mcp-server/src/rules/skill.schema.spec.ts | 167 ++++++ apps/mcp-server/src/rules/skill.schema.ts | 145 +++++ apps/mcp-server/src/shared/security.utils.ts | 57 ++ docs/skills-implementation-plan.md | 533 ++++++++++++++++++ .../rules/.ai-rules/adapters/claude-code.md | 30 + packages/rules/.ai-rules/adapters/codex.md | 25 + packages/rules/.ai-rules/adapters/cursor.md | 23 + packages/rules/.ai-rules/skills/README.md | 112 ++++ .../.ai-rules/skills/brainstorming/SKILL.md | 54 ++ .../dispatching-parallel-agents/SKILL.md | 180 ++++++ .../.ai-rules/skills/executing-plans/SKILL.md | 76 +++ .../.ai-rules/skills/frontend-design/SKILL.md | 42 ++ .../subagent-driven-development/SKILL.md | 240 ++++++++ .../skills/systematic-debugging/SKILL.md | 296 ++++++++++ .../skills/test-driven-development/SKILL.md | 371 ++++++++++++ .../.ai-rules/skills/writing-plans/SKILL.md | 116 ++++ yarn.lock | 10 + 21 files changed, 2717 insertions(+), 48 deletions(-) create mode 100644 apps/mcp-server/src/rules/skill.schema.spec.ts create mode 100644 apps/mcp-server/src/rules/skill.schema.ts create mode 100644 docs/skills-implementation-plan.md create mode 100644 packages/rules/.ai-rules/skills/README.md create mode 100644 packages/rules/.ai-rules/skills/brainstorming/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/dispatching-parallel-agents/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/executing-plans/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/frontend-design/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/subagent-driven-development/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/systematic-debugging/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/test-driven-development/SKILL.md create mode 100644 packages/rules/.ai-rules/skills/writing-plans/SKILL.md diff --git a/apps/mcp-server/package.json b/apps/mcp-server/package.json index cb9ea549..c0b57697 100644 --- a/apps/mcp-server/package.json +++ b/apps/mcp-server/package.json @@ -68,6 +68,7 @@ "codingbuddy-rules": "workspace:*", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", + "yaml": "^2.8.2", "zod": "^4.2.1" }, "devDependencies": { diff --git a/apps/mcp-server/src/mcp/mcp-serverless.spec.ts b/apps/mcp-server/src/mcp/mcp-serverless.spec.ts index c4016360..5768294e 100644 --- a/apps/mcp-server/src/mcp/mcp-serverless.spec.ts +++ b/apps/mcp-server/src/mcp/mcp-serverless.spec.ts @@ -1,5 +1,6 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as path from 'path'; +import * as fs from 'fs/promises'; import { McpServerlessService } from './mcp-serverless'; // ============================================================================ @@ -505,6 +506,121 @@ describe('McpServerlessService', () => { } }); }); + + // ========================================================================== + // Skills Tests + // ========================================================================== + + describe('listSkills', () => { + const testSkillsDir = path.join(TEST_RULES_DIR, 'skills', 'test-skill'); + + afterEach(async () => { + // Cleanup test skill directory + try { + await fs.rm(testSkillsDir, { recursive: true, force: true }); + } catch { + // Ignore cleanup errors + } + }); + + it('should return all skills with name and description', async () => { + // Create test skill + await fs.mkdir(testSkillsDir, { recursive: true }); + await fs.writeFile( + path.join(testSkillsDir, 'SKILL.md'), + `--- +name: test-skill +description: A test skill for testing +--- + +# Test Skill Content + +This is test content. +`, + ); + + const result = await invokeToolHandler(service, 'listSkills'); + const data = JSON.parse(result.content[0].text); + + expect(Array.isArray(data)).toBe(true); + const testSkill = data.find( + (s: { name: string }) => s.name === 'test-skill', + ); + expect(testSkill).toBeDefined(); + expect(testSkill.description).toBe('A test skill for testing'); + }); + + it('should return empty array when no skills exist', async () => { + // Use a service with empty skills directory + const emptyService = new McpServerlessService( + '/nonexistent/rules', + TEST_PROJECT_ROOT, + ); + + const result = await invokeToolHandler(emptyService, 'listSkills'); + const data = JSON.parse(result.content[0].text); + + expect(Array.isArray(data)).toBe(true); + expect(data.length).toBe(0); + }); + }); + + describe('getSkill', () => { + const testSkillsDir = path.join(TEST_RULES_DIR, 'skills', 'my-skill'); + + afterEach(async () => { + // Cleanup test skill directory + try { + await fs.rm(testSkillsDir, { recursive: true, force: true }); + } catch { + // Ignore cleanup errors + } + }); + + it('should return skill content by name', async () => { + // Create test skill + await fs.mkdir(testSkillsDir, { recursive: true }); + await fs.writeFile( + path.join(testSkillsDir, 'SKILL.md'), + `--- +name: my-skill +description: My skill description +--- + +# My Skill + +Detailed content here. +`, + ); + + const result = await invokeToolHandler(service, 'getSkill', 'my-skill'); + expect(result.isError).toBeUndefined(); + + const skill = JSON.parse(result.content[0].text); + expect(skill.name).toBe('my-skill'); + expect(skill.description).toBe('My skill description'); + expect(skill.content).toContain('# My Skill'); + }); + + it('should throw for non-existent skill', async () => { + const result = await invokeToolHandler( + service, + 'getSkill', + 'non-existent-skill', + ); + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('not found'); + }); + + it('should validate skill name format', async () => { + const result = await invokeToolHandler( + service, + 'getSkill', + 'Invalid Name!', + ); + expect(result.isError).toBe(true); + }); + }); }); // ============================================================================ @@ -534,6 +650,8 @@ async function invokeToolHandler( parseMode: 'handleParseMode', getProjectConfig: 'handleGetProjectConfig', suggestConfigUpdates: 'handleSuggestConfigUpdates', + listSkills: 'handleListSkills', + getSkill: 'handleGetSkill', }; const methodName = methodMap[handlerName]; diff --git a/apps/mcp-server/src/mcp/mcp-serverless.ts b/apps/mcp-server/src/mcp/mcp-serverless.ts index 65400e3b..19551766 100644 --- a/apps/mcp-server/src/mcp/mcp-serverless.ts +++ b/apps/mcp-server/src/mcp/mcp-serverless.ts @@ -15,6 +15,8 @@ import { loadConfig } from '../config/config.loader'; import type { CodingBuddyConfig } from '../config/config.schema'; import { isPathSafe } from '../shared/security.utils'; import { parseAgentProfile, AgentSchemaError } from '../rules/agent.schema'; +import { parseSkill, SkillSchemaError } from '../rules/skill.schema'; +import type { Skill } from '../rules/skill.schema'; import { validateQuery, validatePrompt, @@ -36,6 +38,11 @@ interface ParseModeResponse extends ParseModeResult { language?: string; } +interface SkillSummary { + name: string; + description: string; +} + // ============================================================================ // Default Configuration // ============================================================================ @@ -226,6 +233,34 @@ export class McpServerlessService { return this.handleSuggestConfigUpdates(projectRoot); }, ); + + // list_skills tool + this.server.registerTool( + 'list_skills', + { + title: 'List Skills', + description: 'List all available skills with descriptions', + inputSchema: {}, + }, + async (): Promise => { + return this.handleListSkills(); + }, + ); + + // get_skill tool + this.server.registerTool( + 'get_skill', + { + title: 'Get Skill', + description: 'Get skill content by name', + inputSchema: { + skillName: z.string().describe('Name of the skill'), + }, + }, + async ({ skillName }): Promise => { + return this.handleGetSkill(skillName); + }, + ); } private registerResources(): void { @@ -304,6 +339,31 @@ export class McpServerlessService { } } + private async handleListSkills(): Promise { + try { + const skills = await this.listSkills(); + return this.jsonResponse(skills); + } catch (error) { + return this.errorResponse( + `Failed to list skills: ${sanitizeError(error)}`, + ); + } + } + + private async handleGetSkill(skillName: string): Promise { + // Validate skill name + if (!skillName || !/^[a-z0-9-]+$/.test(skillName)) { + return this.errorResponse('Invalid skill name format'); + } + + try { + const skill = await this.getSkill(skillName); + return this.jsonResponse(skill); + } catch { + return this.errorResponse(`Skill '${skillName}' not found.`); + } + } + private async handleSuggestConfigUpdates( projectRoot?: string, ): Promise { @@ -467,6 +527,65 @@ export class McpServerlessService { return results.sort((a, b) => b.score - a.score); } + // ============================================================================ + // Skills Operations + // ============================================================================ + + async listSkills(): Promise { + const skillsDir = path.join(this.rulesDir, 'skills'); + const summaries: SkillSummary[] = []; + + try { + const entries = await fs.readdir(skillsDir, { withFileTypes: true }); + + for (const entry of entries) { + if (entry.isDirectory()) { + const skillPath = path.join(skillsDir, entry.name, 'SKILL.md'); + try { + const content = await fs.readFile(skillPath, 'utf-8'); + const skill = parseSkill(content, `skills/${entry.name}/SKILL.md`); + summaries.push({ + name: skill.name, + description: skill.description, + }); + } catch { + // Skip invalid skills + } + } + } + } catch { + // Skills directory doesn't exist + } + + return summaries; + } + + async getSkill(name: string): Promise { + // Validate name format + if (!/^[a-z0-9-]+$/.test(name)) { + throw new Error(`Invalid skill name format: ${name}`); + } + + const skillPath = `skills/${name}/SKILL.md`; + + // Security check + if (!isPathSafe(this.rulesDir, skillPath)) { + throw new Error('Access denied: Invalid path'); + } + + const fullPath = path.join(this.rulesDir, skillPath); + + try { + const content = await fs.readFile(fullPath, 'utf-8'); + return parseSkill(content, skillPath); + } catch (error) { + if (error instanceof SkillSchemaError) { + throw new Error(`Invalid skill: ${name}`); + } + throw new Error(`Skill not found: ${name}`); + } + } + // ============================================================================ // Keyword/Mode Operations (extracted from KeywordService) // ============================================================================ diff --git a/apps/mcp-server/src/rules/agent.schema.ts b/apps/mcp-server/src/rules/agent.schema.ts index 3142f532..3016fa06 100644 --- a/apps/mcp-server/src/rules/agent.schema.ts +++ b/apps/mcp-server/src/rules/agent.schema.ts @@ -8,53 +8,7 @@ */ import * as z from 'zod'; - -// ============================================================================ -// Dangerous Keys (Prototype Pollution Prevention) -// ============================================================================ - -const DANGEROUS_KEYS = ['__proto__', 'constructor', 'prototype'] as const; - -/** - * Recursively check for dangerous keys in an object - * Uses Object.getOwnPropertyNames to also check non-enumerable properties - */ -function containsDangerousKeys(obj: unknown, path = ''): string | null { - if (obj === null || typeof obj !== 'object') { - return null; - } - - if (Array.isArray(obj)) { - for (let i = 0; i < obj.length; i++) { - const result = containsDangerousKeys(obj[i], `${path}[${i}]`); - if (result) return result; - } - return null; - } - - // Use Object.getOwnPropertyNames to catch all properties including non-enumerable - // Also check with hasOwnProperty for keys like __proto__ that might be special - const keys = Object.getOwnPropertyNames(obj); - - for (const key of keys) { - if (DANGEROUS_KEYS.includes(key as (typeof DANGEROUS_KEYS)[number])) { - return path ? `${path}.${key}` : key; - } - } - - // Recursively check nested objects - for (const key of keys) { - if (!DANGEROUS_KEYS.includes(key as (typeof DANGEROUS_KEYS)[number])) { - const result = containsDangerousKeys( - (obj as Record)[key], - path ? `${path}.${key}` : key, - ); - if (result) return result; - } - } - - return null; -} +import { containsDangerousKeys } from '../shared/security.utils'; // ============================================================================ // Custom Error diff --git a/apps/mcp-server/src/rules/skill.schema.spec.ts b/apps/mcp-server/src/rules/skill.schema.spec.ts new file mode 100644 index 00000000..1bfa857f --- /dev/null +++ b/apps/mcp-server/src/rules/skill.schema.spec.ts @@ -0,0 +1,167 @@ +import { describe, it, expect } from 'vitest'; +import { parseSkill, SkillSchemaError } from './skill.schema'; + +describe('parseSkill', () => { + describe('valid skills', () => { + it('should parse valid SKILL.md with frontmatter', () => { + const content = `--- +name: test-skill +description: A test skill description +--- + +# Test Skill + +This is the skill content. +`; + const result = parseSkill(content, 'skills/test-skill/SKILL.md'); + + expect(result.name).toBe('test-skill'); + expect(result.description).toBe('A test skill description'); + expect(result.content).toContain('# Test Skill'); + expect(result.path).toBe('skills/test-skill/SKILL.md'); + }); + + it('should handle multiline description', () => { + const content = `--- +name: multi-desc +description: "This is a longer description that spans the full allowed length" +--- + +Content here. +`; + const result = parseSkill(content, 'skills/multi-desc/SKILL.md'); + + expect(result.description).toContain('longer description'); + }); + + it('should preserve content formatting', () => { + const content = `--- +name: formatted +description: Formatted skill +--- + +## Section 1 + +- Item 1 +- Item 2 + +\`\`\`typescript +const x = 1; +\`\`\` +`; + const result = parseSkill(content, 'path'); + + expect(result.content).toContain('## Section 1'); + expect(result.content).toContain('- Item 1'); + expect(result.content).toContain('const x = 1;'); + }); + }); + + describe('invalid skills', () => { + it('should reject missing name', () => { + const content = `--- +description: No name field +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject missing description', () => { + const content = `--- +name: no-desc +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject invalid name format (uppercase)', () => { + const content = `--- +name: InvalidName +description: Has uppercase +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject invalid name format (spaces)', () => { + const content = `--- +name: invalid name +description: Has spaces +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject empty content after frontmatter', () => { + const content = `--- +name: empty-content +description: No content +--- +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject missing frontmatter', () => { + const content = `# No Frontmatter + +Just content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject malformed frontmatter', () => { + const content = `--- +name: test +description: [invalid yaml array as description] +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + }); + + describe('security - prototype pollution prevention', () => { + it('should reject __proto__ key in frontmatter', () => { + const content = `--- +name: malicious +description: Test +__proto__: + isAdmin: true +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + + it('should reject constructor key', () => { + const content = `--- +name: malicious +description: Test +constructor: + prototype: + isAdmin: true +--- + +Content. +`; + expect(() => parseSkill(content, 'path')).toThrow(SkillSchemaError); + }); + }); +}); + +describe('SkillSchemaError', () => { + it('should have correct error name', () => { + const error = new SkillSchemaError('test message'); + expect(error.name).toBe('SkillSchemaError'); + }); +}); diff --git a/apps/mcp-server/src/rules/skill.schema.ts b/apps/mcp-server/src/rules/skill.schema.ts new file mode 100644 index 00000000..c6155e79 --- /dev/null +++ b/apps/mcp-server/src/rules/skill.schema.ts @@ -0,0 +1,145 @@ +/** + * Skill Schema Validation + * + * Provides Zod-based validation for SKILL.md files with: + * - YAML frontmatter parsing + * - Required field validation + * - Prototype pollution prevention + * - Type safety + */ + +import * as z from 'zod'; +import * as yaml from 'yaml'; +import { containsDangerousKeys } from '../shared/security.utils'; + +// ============================================================================ +// Custom Error +// ============================================================================ + +export class SkillSchemaError extends Error { + constructor( + message: string, + public readonly details?: z.ZodError, + ) { + super(message); + this.name = 'SkillSchemaError'; + } +} + +// ============================================================================ +// Zod Schemas +// ============================================================================ + +/** + * Skill frontmatter schema + * - name: lowercase with hyphens only (a-z0-9-) + * - description: 1-500 characters + */ +export const SkillFrontmatterSchema = z.object({ + name: z + .string() + .min(1) + .regex( + /^[a-z0-9-]+$/, + 'Skill name must be lowercase alphanumeric with hyphens only', + ), + description: z.string().min(1).max(500), +}); + +// ============================================================================ +// Types +// ============================================================================ + +export interface Skill { + name: string; + description: string; + content: string; + path: string; +} + +export type SkillFrontmatter = z.infer; + +// ============================================================================ +// Frontmatter Parsing +// ============================================================================ + +const FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/; + +function parseFrontmatter(content: string): { + frontmatter: unknown; + body: string; +} { + const match = content.match(FRONTMATTER_REGEX); + + if (!match) { + throw new SkillSchemaError( + 'Invalid skill file: Missing or malformed YAML frontmatter', + ); + } + + const [, yamlStr, body] = match; + + try { + const frontmatter = yaml.parse(yamlStr); + return { frontmatter, body: body.trim() }; + } catch (error) { + throw new SkillSchemaError( + `Invalid skill file: YAML parsing failed - ${error instanceof Error ? error.message : 'Unknown error'}`, + ); + } +} + +// ============================================================================ +// Public API +// ============================================================================ + +/** + * Parse and validate a skill from SKILL.md content + * + * @param content - Raw file content with YAML frontmatter + * @param filePath - Path to the skill file (for reference) + * @returns Validated skill object + * @throws SkillSchemaError if validation fails + */ +export function parseSkill(content: string, filePath: string): Skill { + // Parse frontmatter + const { frontmatter, body } = parseFrontmatter(content); + + // Check for prototype pollution + const dangerousKey = containsDangerousKeys(frontmatter); + if (dangerousKey) { + throw new SkillSchemaError( + `Invalid skill: Dangerous key "${dangerousKey}" detected`, + ); + } + + // Validate frontmatter with Zod + const result = SkillFrontmatterSchema.safeParse(frontmatter); + + if (!result.success) { + const errorMessage = result.error.issues + .map(issue => { + const pathStr = issue.path.length > 0 ? issue.path.join('.') : 'root'; + return `${pathStr}: ${issue.message}`; + }) + .join(', '); + throw new SkillSchemaError( + `Invalid skill frontmatter: ${errorMessage}`, + result.error, + ); + } + + // Validate content is not empty + if (!body || body.trim().length === 0) { + throw new SkillSchemaError( + 'Invalid skill: Content after frontmatter is empty', + ); + } + + return { + name: result.data.name, + description: result.data.description, + content: body, + path: filePath, + }; +} diff --git a/apps/mcp-server/src/shared/security.utils.ts b/apps/mcp-server/src/shared/security.utils.ts index 59f501b0..5703de24 100644 --- a/apps/mcp-server/src/shared/security.utils.ts +++ b/apps/mcp-server/src/shared/security.utils.ts @@ -4,6 +4,63 @@ import * as path from 'path'; +// ============================================================================ +// Prototype Pollution Prevention +// ============================================================================ + +const DANGEROUS_KEYS = ['__proto__', 'constructor', 'prototype'] as const; + +/** + * Recursively check for dangerous keys in an object (prototype pollution prevention) + * Uses Object.getOwnPropertyNames to also check non-enumerable properties + * + * @param obj - Object to check + * @param objPath - Current path in object (for error messages) + * @returns The path to the dangerous key if found, null otherwise + */ +export function containsDangerousKeys( + obj: unknown, + objPath = '', +): string | null { + if (obj === null || typeof obj !== 'object') { + return null; + } + + if (Array.isArray(obj)) { + for (let i = 0; i < obj.length; i++) { + const result = containsDangerousKeys(obj[i], `${objPath}[${i}]`); + if (result) return result; + } + return null; + } + + // Use Object.getOwnPropertyNames to catch all properties including non-enumerable + const keys = Object.getOwnPropertyNames(obj); + + for (const key of keys) { + if (DANGEROUS_KEYS.includes(key as (typeof DANGEROUS_KEYS)[number])) { + return objPath ? `${objPath}.${key}` : key; + } + } + + // Recursively check nested objects + for (const key of keys) { + if (!DANGEROUS_KEYS.includes(key as (typeof DANGEROUS_KEYS)[number])) { + const result = containsDangerousKeys( + (obj as Record)[key], + objPath ? `${objPath}.${key}` : key, + ); + if (result) return result; + } + } + + return null; +} + +// ============================================================================ +// Path Safety +// ============================================================================ + /** * Check if a relative path is safe (doesn't escape base directory) * diff --git a/docs/skills-implementation-plan.md b/docs/skills-implementation-plan.md new file mode 100644 index 00000000..ae2f01fb --- /dev/null +++ b/docs/skills-implementation-plan.md @@ -0,0 +1,533 @@ +# Skills System Implementation Plan + +## Overview + +Implement a cross-platform skills system for CodingBuddy following TDD methodology. + +**Related Ticket**: `docs/skills-ticket.md` + +--- + +## Phase 1: Skills Infrastructure + +### 1.1 Create Skills Directory Structure + +**Files to create:** +``` +packages/rules/.ai-rules/skills/ +├── README.md # Skill catalog +└── .gitkeep # Ensure directory tracked +``` + +**Tasks:** +- [ ] Create `skills/` directory +- [ ] Create `README.md` with format specification +- [ ] Document YAML frontmatter requirements + +### 1.2 Define Skill Schema (TDD) + +**File**: `apps/mcp-server/src/rules/skill.schema.ts` + +**Red** - Write failing tests: +```typescript +// skill.schema.spec.ts +describe('parseSkill', () => { + it('should parse valid SKILL.md with frontmatter'); + it('should reject missing name'); + it('should reject missing description'); + it('should reject invalid name format'); + it('should extract content after frontmatter'); +}); +``` + +**Green** - Implement schema: +```typescript +// skill.schema.ts +import * as z from 'zod'; + +export const SkillFrontmatterSchema = z.object({ + name: z.string().min(1).regex(/^[a-z0-9-]+$/, + 'Skill name must be lowercase with hyphens only'), + description: z.string().min(1).max(500), +}); + +export interface Skill { + name: string; + description: string; + content: string; + path: string; +} + +export function parseSkill(content: string, filePath: string): Skill; +``` + +### 1.3 Add Skill Loading to RulesService + +**File**: `apps/mcp-server/src/rules/rules.service.ts` + +**Methods to add:** +```typescript +async listSkills(): Promise; +async getSkill(name: string): Promise; +``` + +**Tests:** +```typescript +describe('listSkills', () => { + it('should return all skills with name and description'); + it('should return empty array when no skills exist'); +}); + +describe('getSkill', () => { + it('should return skill content by name'); + it('should throw for non-existent skill'); + it('should validate skill name format'); +}); +``` + +### 1.4 Add MCP Tools + +**File**: `apps/mcp-server/src/mcp/mcp-serverless.ts` + +**Tools to register:** + +```typescript +// list_skills tool +this.server.registerTool( + 'list_skills', + { + title: 'List Skills', + description: 'List all available skills with descriptions', + inputSchema: {}, + }, + async (): Promise => { + return this.handleListSkills(); + }, +); + +// get_skill tool +this.server.registerTool( + 'get_skill', + { + title: 'Get Skill', + description: 'Get skill content by name', + inputSchema: { + skillName: z.string().describe('Name of the skill'), + }, + }, + async ({ skillName }): Promise => { + return this.handleGetSkill(skillName); + }, +); +``` + +**Handlers:** +```typescript +private async handleListSkills(): Promise; +private async handleGetSkill(skillName: string): Promise; +``` + +--- + +## Phase 2: Core Skills + +### 2.1 TDD Skill + +**File**: `packages/rules/.ai-rules/skills/tdd/SKILL.md` + +```markdown +--- +name: tdd +description: "Use before implementing any feature. Guides Red-Green-Refactor cycle with test-first approach." +--- + +# Test-Driven Development + +## When to Use +- Before writing any new functionality +- When fixing bugs (write failing test first) +- When refactoring (ensure tests exist first) + +## The Cycle + +### 1. Red - Write Failing Test +- Write the smallest test that fails +- Test should express desired behavior +- Verify test actually fails + +### 2. Green - Make It Pass +- Write minimum code to pass test +- Don't optimize yet +- Focus on correctness only + +### 3. Refactor - Improve +- Clean up code while tests pass +- Remove duplication +- Improve naming + +## Checklist +- [ ] Test written before implementation +- [ ] Test fails for the right reason +- [ ] Implementation is minimal +- [ ] All tests pass after changes +- [ ] Code is refactored and clean +``` + +### 2.2 Debugging Skill + +**File**: `packages/rules/.ai-rules/skills/debugging/SKILL.md` + +```markdown +--- +name: debugging +description: "Use when encountering bugs or unexpected behavior. Systematic approach to find root cause." +--- + +# Systematic Debugging + +## When to Use +- Test failures +- Unexpected behavior +- Error messages +- Performance issues + +## The Process + +### 1. Reproduce +- Create minimal reproduction +- Document exact steps +- Note environment details + +### 2. Hypothesize +- Form 2-3 hypotheses about cause +- Rank by likelihood +- Plan verification for each + +### 3. Verify +- Test most likely hypothesis first +- Use logging/debugging tools +- Gather evidence + +### 4. Fix +- Address root cause, not symptoms +- Write regression test +- Verify fix works + +## Checklist +- [ ] Bug is reproducible +- [ ] Hypotheses documented +- [ ] Root cause identified +- [ ] Fix addresses root cause +- [ ] Regression test added +``` + +### 2.3 Code Review Skill + +**File**: `packages/rules/.ai-rules/skills/code-review/SKILL.md` + +```markdown +--- +name: code-review +description: "Use when reviewing code changes. Structured checklist for thorough review." +--- + +# Code Review + +## When to Use +- Before merging PRs +- Self-review before committing +- Evaluating code quality + +## Review Checklist + +### Correctness +- [ ] Logic is correct +- [ ] Edge cases handled +- [ ] Error handling present +- [ ] No obvious bugs + +### Design +- [ ] Single responsibility +- [ ] Appropriate abstraction +- [ ] No code duplication +- [ ] Dependencies reasonable + +### Quality +- [ ] Clear naming +- [ ] Readable code +- [ ] Appropriate comments +- [ ] Consistent style + +### Testing +- [ ] Tests exist +- [ ] Tests are meaningful +- [ ] Coverage adequate +- [ ] Edge cases tested + +### Security +- [ ] No hardcoded secrets +- [ ] Input validated +- [ ] Output sanitized +- [ ] Auth/authz correct +``` + +### 2.4 Planning Skill + +**File**: `packages/rules/.ai-rules/skills/planning/SKILL.md` + +```markdown +--- +name: planning +description: "Use before implementing complex features. Creates structured implementation plan." +--- + +# Implementation Planning + +## When to Use +- Multi-file changes +- New features +- Architectural decisions +- Complex refactoring + +## Planning Process + +### 1. Understand +- Clarify requirements +- Identify constraints +- Note dependencies + +### 2. Explore +- Review existing code +- Identify affected areas +- Consider approaches + +### 3. Design +- Choose approach +- Define interfaces +- Plan data flow + +### 4. Break Down +- List discrete tasks +- Order by dependency +- Estimate complexity + +### 5. Document +- Write plan to file +- Include rationale +- Note risks + +## Plan Template + +```markdown +# [Feature] Implementation Plan + +## Goal +[What we're building and why] + +## Approach +[Chosen approach and rationale] + +## Tasks +1. [ ] Task 1 +2. [ ] Task 2 +... + +## Risks +- Risk 1: Mitigation +``` +``` + +--- + +## Phase 3: Adapter Integration + +### 3.1 Claude Code Adapter Update + +**File**: `packages/rules/.ai-rules/adapters/claude-code.md` + +**Add section:** +```markdown +## Skills + +CodingBuddy skills are accessible via MCP tools: + +### List Available Skills +Use `list_skills` MCP tool to see all available skills. + +### Use a Skill +Use `get_skill` MCP tool with skill name: +- `get_skill("tdd")` - Test-Driven Development +- `get_skill("debugging")` - Systematic Debugging +- `get_skill("code-review")` - Code Review Checklist +- `get_skill("planning")` - Implementation Planning + +### When to Use Skills +- **tdd**: Before implementing any feature +- **debugging**: When encountering bugs +- **code-review**: Before merging or committing +- **planning**: For complex multi-step tasks +``` + +### 3.2 Codex Adapter Update + +**File**: `packages/rules/.ai-rules/adapters/codex.md` + +**Add section:** +```markdown +## Skills + +### Using Skills in Codex + +Skills are located in `.ai-rules/skills/`. To use a skill: + +1. Read the skill file: + ```bash + cat .ai-rules/skills//SKILL.md + ``` + +2. Follow the skill's checklist and process. + +### Available Skills +- `tdd` - Test-Driven Development workflow +- `debugging` - Systematic debugging process +- `code-review` - Code review checklist +- `planning` - Implementation planning +``` + +### 3.3 Cursor Adapter Update + +**File**: `packages/rules/.ai-rules/adapters/cursor.md` + +**Add section:** +```markdown +## Skills + +### Using Skills in Cursor + +Reference skills in your prompts using file inclusion: + +``` +@.ai-rules/skills/tdd/SKILL.md +``` + +Or manually include skill content in `.cursorrules`. + +### Available Skills +- `.ai-rules/skills/tdd/SKILL.md` +- `.ai-rules/skills/debugging/SKILL.md` +- `.ai-rules/skills/code-review/SKILL.md` +- `.ai-rules/skills/planning/SKILL.md` +``` + +--- + +## Phase 4: Documentation + +### 4.1 Skills README + +**File**: `packages/rules/.ai-rules/skills/README.md` + +```markdown +# CodingBuddy Skills + +Reusable workflows for consistent development practices. + +## Available Skills + +| Skill | Description | When to Use | +|-------|-------------|-------------| +| tdd | Test-Driven Development | Before implementing features | +| debugging | Systematic Debugging | When encountering bugs | +| code-review | Code Review Checklist | Before merging/committing | +| planning | Implementation Planning | For complex tasks | + +## Skill Format + +Skills use YAML frontmatter + Markdown: + +```markdown +--- +name: skill-name +description: "Brief description" +--- + +# Skill Title + +## Content... +``` + +## Usage by Platform + +- **Claude Code**: Use `get_skill` MCP tool +- **Codex**: Read skill file directly +- **Cursor**: Include via `@` reference + +## Creating Custom Skills + +1. Create directory: `skills//` +2. Create `SKILL.md` with frontmatter +3. Follow existing skill structure +``` + +--- + +## Implementation Order + +``` +Phase 1.1 → Phase 1.2 → Phase 1.3 → Phase 1.4 + ↓ +Phase 2.1 → Phase 2.2 → Phase 2.3 → Phase 2.4 + ↓ +Phase 3.1 → Phase 3.2 → Phase 3.3 + ↓ +Phase 4.1 +``` + +## Test Commands + +```bash +# Run all tests +yarn workspace codingbuddy test + +# Run specific test file +yarn workspace codingbuddy test src/rules/skill.schema.spec.ts + +# Type check +yarn workspace codingbuddy tsc --noEmit + +# Build +yarn workspace codingbuddy build +``` + +--- + +## Checklist Summary + +### Phase 1: Infrastructure +- [ ] 1.1 Create skills directory structure +- [ ] 1.2 Implement skill schema (TDD) +- [ ] 1.3 Add skill loading to RulesService +- [ ] 1.4 Add MCP tools (list_skills, get_skill) + +### Phase 2: Core Skills +- [ ] 2.1 Create tdd skill +- [ ] 2.2 Create debugging skill +- [ ] 2.3 Create code-review skill +- [ ] 2.4 Create planning skill + +### Phase 3: Adapters +- [ ] 3.1 Update claude-code.md +- [ ] 3.2 Update codex.md +- [ ] 3.3 Update cursor.md + +### Phase 4: Documentation +- [ ] 4.1 Create skills/README.md + +--- + +## Notes + +- Follow TDD for all code changes +- Run tests after each phase +- Commit after each completed phase +- Update ticket status as work progresses diff --git a/packages/rules/.ai-rules/adapters/claude-code.md b/packages/rules/.ai-rules/adapters/claude-code.md index 6f3ff3d3..6e224639 100644 --- a/packages/rules/.ai-rules/adapters/claude-code.md +++ b/packages/rules/.ai-rules/adapters/claude-code.md @@ -115,3 +115,33 @@ Claude can directly read and reference: 1. Update `.ai-rules/rules/*.md` for universal changes 2. Update `.claude/rules/custom-instructions.md` for Claude-specific features 3. Sync Claude Project instructions when rules change significantly + +## Skills + +CodingBuddy skills are accessible via MCP tools: + +### List Available Skills + +Use `list_skills` MCP tool to see all available skills. + +### Use a Skill + +Use `get_skill` MCP tool with skill name: + +- `get_skill("brainstorming")` - Explore requirements before implementation +- `get_skill("test-driven-development")` - TDD workflow +- `get_skill("systematic-debugging")` - Debug methodically +- `get_skill("writing-plans")` - Create implementation plans +- `get_skill("executing-plans")` - Execute plans with checkpoints +- `get_skill("subagent-driven-development")` - In-session plan execution +- `get_skill("dispatching-parallel-agents")` - Handle parallel tasks +- `get_skill("frontend-design")` - Build production-grade UI + +### When to Use Skills + +- **brainstorming**: Before any creative work or new features +- **test-driven-development**: Before implementing features or bugfixes +- **systematic-debugging**: When encountering bugs or test failures +- **writing-plans**: For multi-step tasks with specs +- **executing-plans**: Following written implementation plans +- **frontend-design**: Building web components or pages diff --git a/packages/rules/.ai-rules/adapters/codex.md b/packages/rules/.ai-rules/adapters/codex.md index 1c86eeb0..6fc1c933 100644 --- a/packages/rules/.ai-rules/adapters/codex.md +++ b/packages/rules/.ai-rules/adapters/codex.md @@ -122,3 +122,28 @@ When using Copilot Workspace: 1. Update `.ai-rules/rules/*.md` for universal rule changes 2. Keep `.github/copilot-instructions.md` concise (Copilot's context limit) 3. Link to detailed rules in `.ai-rules/` rather than duplicating + +## Skills + +### Using Skills in Codex + +Skills are located in `.ai-rules/skills/`. To use a skill: + +1. Read the skill file: + + ```bash + cat .ai-rules/skills//SKILL.md + ``` + +2. Follow the skill's checklist and process. + +### Available Skills + +- `brainstorming` - Explore requirements before implementation +- `test-driven-development` - TDD workflow +- `systematic-debugging` - Debug methodically +- `writing-plans` - Create implementation plans +- `executing-plans` - Execute plans with checkpoints +- `subagent-driven-development` - In-session plan execution +- `dispatching-parallel-agents` - Handle parallel tasks +- `frontend-design` - Build production-grade UI diff --git a/packages/rules/.ai-rules/adapters/cursor.md b/packages/rules/.ai-rules/adapters/cursor.md index 1ee924aa..8530306e 100644 --- a/packages/rules/.ai-rules/adapters/cursor.md +++ b/packages/rules/.ai-rules/adapters/cursor.md @@ -126,3 +126,26 @@ When updating rules: 1. Update `.ai-rules/rules/*.md` for changes affecting all AI tools 2. Update `.cursor/rules/*.mdc` only for Cursor-specific changes 3. Keep both in sync for best experience + +## Skills + +### Using Skills in Cursor + +Reference skills in your prompts using file inclusion: + +``` +@.ai-rules/skills/test-driven-development/SKILL.md +``` + +Or manually include skill content in `.cursorrules`. + +### Available Skills + +- `.ai-rules/skills/brainstorming/SKILL.md` +- `.ai-rules/skills/test-driven-development/SKILL.md` +- `.ai-rules/skills/systematic-debugging/SKILL.md` +- `.ai-rules/skills/writing-plans/SKILL.md` +- `.ai-rules/skills/executing-plans/SKILL.md` +- `.ai-rules/skills/subagent-driven-development/SKILL.md` +- `.ai-rules/skills/dispatching-parallel-agents/SKILL.md` +- `.ai-rules/skills/frontend-design/SKILL.md` diff --git a/packages/rules/.ai-rules/skills/README.md b/packages/rules/.ai-rules/skills/README.md new file mode 100644 index 00000000..fbe1c0b1 --- /dev/null +++ b/packages/rules/.ai-rules/skills/README.md @@ -0,0 +1,112 @@ +# CodingBuddy Skills + +Reusable workflows for consistent development practices. + +## Available Skills + +| Skill | Description | When to Use | +|-------|-------------|-------------| +| brainstorming | Explores user intent, requirements and design before implementation | Before any creative work | +| dispatching-parallel-agents | Handle 2+ independent tasks without shared state | Parallel task execution | +| executing-plans | Execute implementation plans with review checkpoints | Following written plans | +| frontend-design | Create distinctive, production-grade frontend interfaces | Building web components/pages | +| subagent-driven-development | Execute plans with independent tasks in current session | In-session plan execution | +| systematic-debugging | Systematic approach before proposing fixes | Encountering bugs or failures | +| test-driven-development | Write tests first, then minimal code to pass | Before implementing features | +| writing-plans | Create implementation plans before coding | Multi-step tasks with specs | + +## Skill Format + +Skills use YAML frontmatter + Markdown: + +```markdown +--- +name: skill-name +description: "Brief description (max 500 chars)" +--- + +# Skill Title + +## When to Use +... + +## Process/Checklist +... +``` + +### Frontmatter Requirements + +- `name`: lowercase alphanumeric with hyphens only (`^[a-z0-9-]+$`) +- `description`: 1-500 characters + +## Usage by Platform + +### Claude Code (MCP) + +``` +list_skills # List all available skills +get_skill("test-driven-development") # Get specific skill content +``` + +### Codex / GitHub Copilot + +```bash +cat .ai-rules/skills//SKILL.md +``` + +### Cursor + +``` +@.ai-rules/skills/test-driven-development/SKILL.md +``` + +## Creating Custom Skills + +1. Create directory: `skills//` +2. Create `SKILL.md` with YAML frontmatter +3. Follow the format specification above + +### Example + +```bash +mkdir -p .ai-rules/skills/my-skill +cat > .ai-rules/skills/my-skill/SKILL.md << 'EOF' +--- +name: my-skill +description: My custom skill for specific workflow +--- + +# My Skill + +## When to Use +- Specific scenario 1 +- Specific scenario 2 + +## Checklist +- [ ] Step 1 +- [ ] Step 2 +EOF +``` + +## Directory Structure + +``` +.ai-rules/skills/ +├── README.md # This file +├── brainstorming/ +│ └── SKILL.md +├── dispatching-parallel-agents/ +│ └── SKILL.md +├── executing-plans/ +│ └── SKILL.md +├── frontend-design/ +│ └── SKILL.md +├── subagent-driven-development/ +│ └── SKILL.md +├── systematic-debugging/ +│ └── SKILL.md +├── test-driven-development/ +│ └── SKILL.md +└── writing-plans/ + └── SKILL.md +``` diff --git a/packages/rules/.ai-rules/skills/brainstorming/SKILL.md b/packages/rules/.ai-rules/skills/brainstorming/SKILL.md new file mode 100644 index 00000000..2fd19ba1 --- /dev/null +++ b/packages/rules/.ai-rules/skills/brainstorming/SKILL.md @@ -0,0 +1,54 @@ +--- +name: brainstorming +description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation." +--- + +# Brainstorming Ideas Into Designs + +## Overview + +Help turn ideas into fully formed designs and specs through natural collaborative dialogue. + +Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design in small sections (200-300 words), checking after each section whether it looks right so far. + +## The Process + +**Understanding the idea:** +- Check out the current project state first (files, docs, recent commits) +- Ask questions one at a time to refine the idea +- Prefer multiple choice questions when possible, but open-ended is fine too +- Only one question per message - if a topic needs more exploration, break it into multiple questions +- Focus on understanding: purpose, constraints, success criteria + +**Exploring approaches:** +- Propose 2-3 different approaches with trade-offs +- Present options conversationally with your recommendation and reasoning +- Lead with your recommended option and explain why + +**Presenting the design:** +- Once you believe you understand what you're building, present the design +- Break it into sections of 200-300 words +- Ask after each section whether it looks right so far +- Cover: architecture, components, data flow, error handling, testing +- Be ready to go back and clarify if something doesn't make sense + +## After the Design + +**Documentation:** +- Write the validated design to `docs/plans/YYYY-MM-DD--design.md` +- Use elements-of-style:writing-clearly-and-concisely skill if available +- Commit the design document to git + +**Implementation (if continuing):** +- Ask: "Ready to set up for implementation?" +- Use superpowers:using-git-worktrees to create isolated workspace +- Use superpowers:writing-plans to create detailed implementation plan + +## Key Principles + +- **One question at a time** - Don't overwhelm with multiple questions +- **Multiple choice preferred** - Easier to answer than open-ended when possible +- **YAGNI ruthlessly** - Remove unnecessary features from all designs +- **Explore alternatives** - Always propose 2-3 approaches before settling +- **Incremental validation** - Present design in sections, validate each +- **Be flexible** - Go back and clarify when something doesn't make sense diff --git a/packages/rules/.ai-rules/skills/dispatching-parallel-agents/SKILL.md b/packages/rules/.ai-rules/skills/dispatching-parallel-agents/SKILL.md new file mode 100644 index 00000000..33b14859 --- /dev/null +++ b/packages/rules/.ai-rules/skills/dispatching-parallel-agents/SKILL.md @@ -0,0 +1,180 @@ +--- +name: dispatching-parallel-agents +description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies +--- + +# Dispatching Parallel Agents + +## Overview + +When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel. + +**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently. + +## When to Use + +```dot +digraph when_to_use { + "Multiple failures?" [shape=diamond]; + "Are they independent?" [shape=diamond]; + "Single agent investigates all" [shape=box]; + "One agent per problem domain" [shape=box]; + "Can they work in parallel?" [shape=diamond]; + "Sequential agents" [shape=box]; + "Parallel dispatch" [shape=box]; + + "Multiple failures?" -> "Are they independent?" [label="yes"]; + "Are they independent?" -> "Single agent investigates all" [label="no - related"]; + "Are they independent?" -> "Can they work in parallel?" [label="yes"]; + "Can they work in parallel?" -> "Parallel dispatch" [label="yes"]; + "Can they work in parallel?" -> "Sequential agents" [label="no - shared state"]; +} +``` + +**Use when:** +- 3+ test files failing with different root causes +- Multiple subsystems broken independently +- Each problem can be understood without context from others +- No shared state between investigations + +**Don't use when:** +- Failures are related (fix one might fix others) +- Need to understand full system state +- Agents would interfere with each other + +## The Pattern + +### 1. Identify Independent Domains + +Group failures by what's broken: +- File A tests: Tool approval flow +- File B tests: Batch completion behavior +- File C tests: Abort functionality + +Each domain is independent - fixing tool approval doesn't affect abort tests. + +### 2. Create Focused Agent Tasks + +Each agent gets: +- **Specific scope:** One test file or subsystem +- **Clear goal:** Make these tests pass +- **Constraints:** Don't change other code +- **Expected output:** Summary of what you found and fixed + +### 3. Dispatch in Parallel + +```typescript +// In Claude Code / AI environment +Task("Fix agent-tool-abort.test.ts failures") +Task("Fix batch-completion-behavior.test.ts failures") +Task("Fix tool-approval-race-conditions.test.ts failures") +// All three run concurrently +``` + +### 4. Review and Integrate + +When agents return: +- Read each summary +- Verify fixes don't conflict +- Run full test suite +- Integrate all changes + +## Agent Prompt Structure + +Good agent prompts are: +1. **Focused** - One clear problem domain +2. **Self-contained** - All context needed to understand the problem +3. **Specific about output** - What should the agent return? + +```markdown +Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts: + +1. "should abort tool with partial output capture" - expects 'interrupted at' in message +2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed +3. "should properly track pendingToolCount" - expects 3 results but gets 0 + +These are timing/race condition issues. Your task: + +1. Read the test file and understand what each test verifies +2. Identify root cause - timing issues or actual bugs? +3. Fix by: + - Replacing arbitrary timeouts with event-based waiting + - Fixing bugs in abort implementation if found + - Adjusting test expectations if testing changed behavior + +Do NOT just increase timeouts - find the real issue. + +Return: Summary of what you found and what you fixed. +``` + +## Common Mistakes + +**❌ Too broad:** "Fix all the tests" - agent gets lost +**✅ Specific:** "Fix agent-tool-abort.test.ts" - focused scope + +**❌ No context:** "Fix the race condition" - agent doesn't know where +**✅ Context:** Paste the error messages and test names + +**❌ No constraints:** Agent might refactor everything +**✅ Constraints:** "Do NOT change production code" or "Fix tests only" + +**❌ Vague output:** "Fix it" - you don't know what changed +**✅ Specific:** "Return summary of root cause and changes" + +## When NOT to Use + +**Related failures:** Fixing one might fix others - investigate together first +**Need full context:** Understanding requires seeing entire system +**Exploratory debugging:** You don't know what's broken yet +**Shared state:** Agents would interfere (editing same files, using same resources) + +## Real Example from Session + +**Scenario:** 6 test failures across 3 files after major refactoring + +**Failures:** +- agent-tool-abort.test.ts: 3 failures (timing issues) +- batch-completion-behavior.test.ts: 2 failures (tools not executing) +- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0) + +**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions + +**Dispatch:** +``` +Agent 1 → Fix agent-tool-abort.test.ts +Agent 2 → Fix batch-completion-behavior.test.ts +Agent 3 → Fix tool-approval-race-conditions.test.ts +``` + +**Results:** +- Agent 1: Replaced timeouts with event-based waiting +- Agent 2: Fixed event structure bug (threadId in wrong place) +- Agent 3: Added wait for async tool execution to complete + +**Integration:** All fixes independent, no conflicts, full suite green + +**Time saved:** 3 problems solved in parallel vs sequentially + +## Key Benefits + +1. **Parallelization** - Multiple investigations happen simultaneously +2. **Focus** - Each agent has narrow scope, less context to track +3. **Independence** - Agents don't interfere with each other +4. **Speed** - 3 problems solved in time of 1 + +## Verification + +After agents return: +1. **Review each summary** - Understand what changed +2. **Check for conflicts** - Did agents edit same code? +3. **Run full suite** - Verify all fixes work together +4. **Spot check** - Agents can make systematic errors + +## Real-World Impact + +From debugging session (2025-10-03): +- 6 failures across 3 files +- 3 agents dispatched in parallel +- All investigations completed concurrently +- All fixes integrated successfully +- Zero conflicts between agent changes diff --git a/packages/rules/.ai-rules/skills/executing-plans/SKILL.md b/packages/rules/.ai-rules/skills/executing-plans/SKILL.md new file mode 100644 index 00000000..ca77290c --- /dev/null +++ b/packages/rules/.ai-rules/skills/executing-plans/SKILL.md @@ -0,0 +1,76 @@ +--- +name: executing-plans +description: Use when you have a written implementation plan to execute in a separate session with review checkpoints +--- + +# Executing Plans + +## Overview + +Load plan, review critically, execute tasks in batches, report for review between batches. + +**Core principle:** Batch execution with checkpoints for architect review. + +**Announce at start:** "I'm using the executing-plans skill to implement this plan." + +## The Process + +### Step 1: Load and Review Plan +1. Read plan file +2. Review critically - identify any questions or concerns about the plan +3. If concerns: Raise them with your human partner before starting +4. If no concerns: Create TodoWrite and proceed + +### Step 2: Execute Batch +**Default: First 3 tasks** + +For each task: +1. Mark as in_progress +2. Follow each step exactly (plan has bite-sized steps) +3. Run verifications as specified +4. Mark as completed + +### Step 3: Report +When batch complete: +- Show what was implemented +- Show verification output +- Say: "Ready for feedback." + +### Step 4: Continue +Based on feedback: +- Apply changes if needed +- Execute next batch +- Repeat until complete + +### Step 5: Complete Development + +After all tasks complete and verified: +- Announce: "I'm using the finishing-a-development-branch skill to complete this work." +- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch +- Follow that skill to verify tests, present options, execute choice + +## When to Stop and Ask for Help + +**STOP executing immediately when:** +- Hit a blocker mid-batch (missing dependency, test fails, instruction unclear) +- Plan has critical gaps preventing starting +- You don't understand an instruction +- Verification fails repeatedly + +**Ask for clarification rather than guessing.** + +## When to Revisit Earlier Steps + +**Return to Review (Step 1) when:** +- Partner updates the plan based on your feedback +- Fundamental approach needs rethinking + +**Don't force through blockers** - stop and ask. + +## Remember +- Review plan critically first +- Follow plan steps exactly +- Don't skip verifications +- Reference skills when plan says to +- Between batches: just report and wait +- Stop when blocked, don't guess diff --git a/packages/rules/.ai-rules/skills/frontend-design/SKILL.md b/packages/rules/.ai-rules/skills/frontend-design/SKILL.md new file mode 100644 index 00000000..43aec9ae --- /dev/null +++ b/packages/rules/.ai-rules/skills/frontend-design/SKILL.md @@ -0,0 +1,42 @@ +--- +name: frontend-design +description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics. +license: Complete terms in LICENSE.txt +--- + +This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices. + +The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints. + +## Design Thinking + +Before coding, understand the context and commit to a BOLD aesthetic direction: +- **Purpose**: What problem does this interface solve? Who uses it? +- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction. +- **Constraints**: Technical requirements (framework, performance, accessibility). +- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is: +- Production-grade and functional +- Visually striking and memorable +- Cohesive with a clear aesthetic point-of-view +- Meticulously refined in every detail + +## Frontend Aesthetics Guidelines + +Focus on: +- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font. +- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. +- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise. +- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density. +- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays. + +NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character. + +Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations. + +**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well. + +Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision. diff --git a/packages/rules/.ai-rules/skills/subagent-driven-development/SKILL.md b/packages/rules/.ai-rules/skills/subagent-driven-development/SKILL.md new file mode 100644 index 00000000..a9a94547 --- /dev/null +++ b/packages/rules/.ai-rules/skills/subagent-driven-development/SKILL.md @@ -0,0 +1,240 @@ +--- +name: subagent-driven-development +description: Use when executing implementation plans with independent tasks in the current session +--- + +# Subagent-Driven Development + +Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review. + +**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration + +## When to Use + +```dot +digraph when_to_use { + "Have implementation plan?" [shape=diamond]; + "Tasks mostly independent?" [shape=diamond]; + "Stay in this session?" [shape=diamond]; + "subagent-driven-development" [shape=box]; + "executing-plans" [shape=box]; + "Manual execution or brainstorm first" [shape=box]; + + "Have implementation plan?" -> "Tasks mostly independent?" [label="yes"]; + "Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"]; + "Tasks mostly independent?" -> "Stay in this session?" [label="yes"]; + "Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"]; + "Stay in this session?" -> "subagent-driven-development" [label="yes"]; + "Stay in this session?" -> "executing-plans" [label="no - parallel session"]; +} +``` + +**vs. Executing Plans (parallel session):** +- Same session (no context switch) +- Fresh subagent per task (no context pollution) +- Two-stage review after each task: spec compliance first, then code quality +- Faster iteration (no human-in-loop between tasks) + +## The Process + +```dot +digraph process { + rankdir=TB; + + subgraph cluster_per_task { + label="Per Task"; + "Dispatch implementer subagent (./implementer-prompt.md)" [shape=box]; + "Implementer subagent asks questions?" [shape=diamond]; + "Answer questions, provide context" [shape=box]; + "Implementer subagent implements, tests, commits, self-reviews" [shape=box]; + "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box]; + "Spec reviewer subagent confirms code matches spec?" [shape=diamond]; + "Implementer subagent fixes spec gaps" [shape=box]; + "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box]; + "Code quality reviewer subagent approves?" [shape=diamond]; + "Implementer subagent fixes quality issues" [shape=box]; + "Mark task complete in TodoWrite" [shape=box]; + } + + "Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box]; + "More tasks remain?" [shape=diamond]; + "Dispatch final code reviewer subagent for entire implementation" [shape=box]; + "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; + + "Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?"; + "Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"]; + "Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"]; + "Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)"; + "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?"; + "Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"]; + "Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"]; + "Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"]; + "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?"; + "Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"]; + "Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"]; + "Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"]; + "Mark task complete in TodoWrite" -> "More tasks remain?"; + "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"]; + "More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"]; + "Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch"; +} +``` + +## Prompt Templates + +- `./implementer-prompt.md` - Dispatch implementer subagent +- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent +- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent + +## Example Workflow + +``` +You: I'm using Subagent-Driven Development to execute this plan. + +[Read plan file once: docs/plans/feature-plan.md] +[Extract all 5 tasks with full text and context] +[Create TodoWrite with all tasks] + +Task 1: Hook installation script + +[Get Task 1 text and context (already extracted)] +[Dispatch implementation subagent with full task text + context] + +Implementer: "Before I begin - should the hook be installed at user or system level?" + +You: "User level (~/.config/superpowers/hooks/)" + +Implementer: "Got it. Implementing now..." +[Later] Implementer: + - Implemented install-hook command + - Added tests, 5/5 passing + - Self-review: Found I missed --force flag, added it + - Committed + +[Dispatch spec compliance reviewer] +Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra + +[Get git SHAs, dispatch code quality reviewer] +Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved. + +[Mark Task 1 complete] + +Task 2: Recovery modes + +[Get Task 2 text and context (already extracted)] +[Dispatch implementation subagent with full task text + context] + +Implementer: [No questions, proceeds] +Implementer: + - Added verify/repair modes + - 8/8 tests passing + - Self-review: All good + - Committed + +[Dispatch spec compliance reviewer] +Spec reviewer: ❌ Issues: + - Missing: Progress reporting (spec says "report every 100 items") + - Extra: Added --json flag (not requested) + +[Implementer fixes issues] +Implementer: Removed --json flag, added progress reporting + +[Spec reviewer reviews again] +Spec reviewer: ✅ Spec compliant now + +[Dispatch code quality reviewer] +Code reviewer: Strengths: Solid. Issues (Important): Magic number (100) + +[Implementer fixes] +Implementer: Extracted PROGRESS_INTERVAL constant + +[Code reviewer reviews again] +Code reviewer: ✅ Approved + +[Mark Task 2 complete] + +... + +[After all tasks] +[Dispatch final code-reviewer] +Final reviewer: All requirements met, ready to merge + +Done! +``` + +## Advantages + +**vs. Manual execution:** +- Subagents follow TDD naturally +- Fresh context per task (no confusion) +- Parallel-safe (subagents don't interfere) +- Subagent can ask questions (before AND during work) + +**vs. Executing Plans:** +- Same session (no handoff) +- Continuous progress (no waiting) +- Review checkpoints automatic + +**Efficiency gains:** +- No file reading overhead (controller provides full text) +- Controller curates exactly what context is needed +- Subagent gets complete information upfront +- Questions surfaced before work begins (not after) + +**Quality gates:** +- Self-review catches issues before handoff +- Two-stage review: spec compliance, then code quality +- Review loops ensure fixes actually work +- Spec compliance prevents over/under-building +- Code quality ensures implementation is well-built + +**Cost:** +- More subagent invocations (implementer + 2 reviewers per task) +- Controller does more prep work (extracting all tasks upfront) +- Review loops add iterations +- But catches issues early (cheaper than debugging later) + +## Red Flags + +**Never:** +- Skip reviews (spec compliance OR code quality) +- Proceed with unfixed issues +- Dispatch multiple implementation subagents in parallel (conflicts) +- Make subagent read plan file (provide full text instead) +- Skip scene-setting context (subagent needs to understand where task fits) +- Ignore subagent questions (answer before letting them proceed) +- Accept "close enough" on spec compliance (spec reviewer found issues = not done) +- Skip review loops (reviewer found issues = implementer fixes = review again) +- Let implementer self-review replace actual review (both are needed) +- **Start code quality review before spec compliance is ✅** (wrong order) +- Move to next task while either review has open issues + +**If subagent asks questions:** +- Answer clearly and completely +- Provide additional context if needed +- Don't rush them into implementation + +**If reviewer finds issues:** +- Implementer (same subagent) fixes them +- Reviewer reviews again +- Repeat until approved +- Don't skip the re-review + +**If subagent fails task:** +- Dispatch fix subagent with specific instructions +- Don't try to fix manually (context pollution) + +## Integration + +**Required workflow skills:** +- **superpowers:writing-plans** - Creates the plan this skill executes +- **superpowers:requesting-code-review** - Code review template for reviewer subagents +- **superpowers:finishing-a-development-branch** - Complete development after all tasks + +**Subagents should use:** +- **superpowers:test-driven-development** - Subagents follow TDD for each task + +**Alternative workflow:** +- **superpowers:executing-plans** - Use for parallel session instead of same-session execution diff --git a/packages/rules/.ai-rules/skills/systematic-debugging/SKILL.md b/packages/rules/.ai-rules/skills/systematic-debugging/SKILL.md new file mode 100644 index 00000000..111d2a98 --- /dev/null +++ b/packages/rules/.ai-rules/skills/systematic-debugging/SKILL.md @@ -0,0 +1,296 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Overview + +Random fixes waste time and create new bugs. Quick patches mask underlying issues. + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +## The Iron Law + +``` +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST +``` + +If you haven't completed Phase 1, you cannot propose fixes. + +## When to Use + +Use for ANY technical issue: +- Test failures +- Bugs in production +- Unexpected behavior +- Performance problems +- Build failures +- Integration issues + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- Previous fix didn't work +- You don't fully understand the issue + +**Don't skip when:** +- Issue seems simple (simple bugs have root causes too) +- You're in a hurry (rushing guarantees rework) +- Manager wants it fixed NOW (systematic is faster than thrashing) + +## The Four Phases + +You MUST complete each phase before proceeding to the next. + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read Error Messages Carefully** + - Don't skip past errors or warnings + - They often contain the exact solution + - Read stack traces completely + - Note line numbers, file paths, error codes + +2. **Reproduce Consistently** + - Can you trigger it reliably? + - What are the exact steps? + - Does it happen every time? + - If not reproducible → gather more data, don't guess + +3. **Check Recent Changes** + - What changed that could cause this? + - Git diff, recent commits + - New dependencies, config changes + - Environmental differences + +4. **Gather Evidence in Multi-Component Systems** + + **WHEN system has multiple components (CI → build → signing, API → service → database):** + + **BEFORE proposing fixes, add diagnostic instrumentation:** + ``` + For EACH component boundary: + - Log what data enters component + - Log what data exits component + - Verify environment/config propagation + - Check state at each layer + + Run once to gather evidence showing WHERE it breaks + THEN analyze evidence to identify failing component + THEN investigate that specific component + ``` + + **Example (multi-layer system):** + ```bash + # Layer 1: Workflow + echo "=== Secrets available in workflow: ===" + echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}" + + # Layer 2: Build script + echo "=== Env vars in build script: ===" + env | grep IDENTITY || echo "IDENTITY not in environment" + + # Layer 3: Signing script + echo "=== Keychain state: ===" + security list-keychains + security find-identity -v + + # Layer 4: Actual signing + codesign --sign "$IDENTITY" --verbose=4 "$APP" + ``` + + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗) + +5. **Trace Data Flow** + + **WHEN error is deep in call stack:** + + See `root-cause-tracing.md` in this directory for the complete backward tracing technique. + + **Quick version:** + - Where does bad value originate? + - What called this with bad value? + - Keep tracing up until you find the source + - Fix at source, not at symptom + +### Phase 2: Pattern Analysis + +**Find the pattern before fixing:** + +1. **Find Working Examples** + - Locate similar working code in same codebase + - What works that's similar to what's broken? + +2. **Compare Against References** + - If implementing pattern, read reference implementation COMPLETELY + - Don't skim - read every line + - Understand the pattern fully before applying + +3. **Identify Differences** + - What's different between working and broken? + - List every difference, however small + - Don't assume "that can't matter" + +4. **Understand Dependencies** + - What other components does this need? + - What settings, config, environment? + - What assumptions does it make? + +### Phase 3: Hypothesis and Testing + +**Scientific method:** + +1. **Form Single Hypothesis** + - State clearly: "I think X is the root cause because Y" + - Write it down + - Be specific, not vague + +2. **Test Minimally** + - Make the SMALLEST possible change to test hypothesis + - One variable at a time + - Don't fix multiple things at once + +3. **Verify Before Continuing** + - Did it work? Yes → Phase 4 + - Didn't work? Form NEW hypothesis + - DON'T add more fixes on top + +4. **When You Don't Know** + - Say "I don't understand X" + - Don't pretend to know + - Ask for help + - Research more + +### Phase 4: Implementation + +**Fix the root cause, not the symptom:** + +1. **Create Failing Test Case** + - Simplest possible reproduction + - Automated test if possible + - One-off test script if no framework + - MUST have before fixing + - Use the `superpowers:test-driven-development` skill for writing proper failing tests + +2. **Implement Single Fix** + - Address the root cause identified + - ONE change at a time + - No "while I'm here" improvements + - No bundled refactoring + +3. **Verify Fix** + - Test passes now? + - No other tests broken? + - Issue actually resolved? + +4. **If Fix Doesn't Work** + - STOP + - Count: How many fixes have you tried? + - If < 3: Return to Phase 1, re-analyze with new information + - **If ≥ 3: STOP and question the architecture (step 5 below)** + - DON'T attempt Fix #4 without architectural discussion + +5. **If 3+ Fixes Failed: Question Architecture** + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + **STOP and question fundamentals:** + - Is this pattern fundamentally sound? + - Are we "sticking with it through sheer inertia"? + - Should we refactor architecture vs. continue fixing symptoms? + + **Discuss with your human partner before attempting more fixes** + + This is NOT a failed hypothesis - this is a wrong architecture. + +## Red Flags - STOP and Follow Process + +If you catch yourself thinking: +- "Quick fix for now, investigate later" +- "Just try changing X and see if it works" +- "Add multiple changes, run tests" +- "Skip the test, I'll manually verify" +- "It's probably X, let me fix that" +- "I don't fully understand but this might work" +- "Pattern says X but I'll adapt it differently" +- "Here are the main problems: [lists fixes without investigation]" +- Proposing solutions before tracing data flow +- **"One more fix attempt" (when already tried 2+)** +- **Each fix reveals new problem in different place** + +**ALL of these mean: STOP. Return to Phase 1.** + +**If 3+ fixes failed:** Question the architecture (see Phase 4.5) + +## your human partner's Signals You're Doing It Wrong + +**Watch for these redirections:** +- "Is that not happening?" - You assumed without verifying +- "Will it show us...?" - You should have added evidence gathering +- "Stop guessing" - You're proposing fixes without understanding +- "Ultrathink this" - Question fundamentals, not just symptoms +- "We're stuck?" (frustrated) - Your approach isn't working + +**When you see these:** STOP. Return to Phase 1. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. | +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. | +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. | +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. | +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. | +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. | +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. | +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. | + +## Quick Reference + +| Phase | Key Activities | Success Criteria | +|-------|---------------|------------------| +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY | +| **2. Pattern** | Find working examples, compare | Identify differences | +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis | +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass | + +## When Process Reveals "No Root Cause" + +If systematic investigation reveals issue is truly environmental, timing-dependent, or external: + +1. You've completed the process +2. Document what you investigated +3. Implement appropriate handling (retry, timeout, error message) +4. Add monitoring/logging for future investigation + +**But:** 95% of "no root cause" cases are incomplete investigation. + +## Supporting Techniques + +These techniques are part of systematic debugging and available in this directory: + +- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger +- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause +- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling + +**Related skills:** +- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1) +- **superpowers:verification-before-completion** - Verify fix worked before claiming success + +## Real-World Impact + +From debugging sessions: +- Systematic approach: 15-30 minutes to fix +- Random fixes approach: 2-3 hours of thrashing +- First-time fix rate: 95% vs 40% +- New bugs introduced: Near zero vs common diff --git a/packages/rules/.ai-rules/skills/test-driven-development/SKILL.md b/packages/rules/.ai-rules/skills/test-driven-development/SKILL.md new file mode 100644 index 00000000..7a751fa9 --- /dev/null +++ b/packages/rules/.ai-rules/skills/test-driven-development/SKILL.md @@ -0,0 +1,371 @@ +--- +name: test-driven-development +description: Use when implementing any feature or bugfix, before writing implementation code +--- + +# Test-Driven Development (TDD) + +## Overview + +Write the test first. Watch it fail. Write minimal code to pass. + +**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing. + +**Violating the letter of the rules is violating the spirit of the rules.** + +## When to Use + +**Always:** +- New features +- Bug fixes +- Refactoring +- Behavior changes + +**Exceptions (ask your human partner):** +- Throwaway prototypes +- Generated code +- Configuration files + +Thinking "skip TDD just this once"? Stop. That's rationalization. + +## The Iron Law + +``` +NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST +``` + +Write code before the test? Delete it. Start over. + +**No exceptions:** +- Don't keep it as "reference" +- Don't "adapt" it while writing tests +- Don't look at it +- Delete means delete + +Implement fresh from tests. Period. + +## Red-Green-Refactor + +```dot +digraph tdd_cycle { + rankdir=LR; + red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"]; + verify_red [label="Verify fails\ncorrectly", shape=diamond]; + green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"]; + verify_green [label="Verify passes\nAll green", shape=diamond]; + refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"]; + next [label="Next", shape=ellipse]; + + red -> verify_red; + verify_red -> green [label="yes"]; + verify_red -> red [label="wrong\nfailure"]; + green -> verify_green; + verify_green -> refactor [label="yes"]; + verify_green -> green [label="no"]; + refactor -> verify_green [label="stay\ngreen"]; + verify_green -> next; + next -> red; +} +``` + +### RED - Write Failing Test + +Write one minimal test showing what should happen. + + +```typescript +test('retries failed operations 3 times', async () => { + let attempts = 0; + const operation = () => { + attempts++; + if (attempts < 3) throw new Error('fail'); + return 'success'; + }; + + const result = await retryOperation(operation); + + expect(result).toBe('success'); + expect(attempts).toBe(3); +}); +``` +Clear name, tests real behavior, one thing + + + +```typescript +test('retry works', async () => { + const mock = jest.fn() + .mockRejectedValueOnce(new Error()) + .mockRejectedValueOnce(new Error()) + .mockResolvedValueOnce('success'); + await retryOperation(mock); + expect(mock).toHaveBeenCalledTimes(3); +}); +``` +Vague name, tests mock not code + + +**Requirements:** +- One behavior +- Clear name +- Real code (no mocks unless unavoidable) + +### Verify RED - Watch It Fail + +**MANDATORY. Never skip.** + +```bash +npm test path/to/test.test.ts +``` + +Confirm: +- Test fails (not errors) +- Failure message is expected +- Fails because feature missing (not typos) + +**Test passes?** You're testing existing behavior. Fix test. + +**Test errors?** Fix error, re-run until it fails correctly. + +### GREEN - Minimal Code + +Write simplest code to pass the test. + + +```typescript +async function retryOperation(fn: () => Promise): Promise { + for (let i = 0; i < 3; i++) { + try { + return await fn(); + } catch (e) { + if (i === 2) throw e; + } + } + throw new Error('unreachable'); +} +``` +Just enough to pass + + + +```typescript +async function retryOperation( + fn: () => Promise, + options?: { + maxRetries?: number; + backoff?: 'linear' | 'exponential'; + onRetry?: (attempt: number) => void; + } +): Promise { + // YAGNI +} +``` +Over-engineered + + +Don't add features, refactor other code, or "improve" beyond the test. + +### Verify GREEN - Watch It Pass + +**MANDATORY.** + +```bash +npm test path/to/test.test.ts +``` + +Confirm: +- Test passes +- Other tests still pass +- Output pristine (no errors, warnings) + +**Test fails?** Fix code, not test. + +**Other tests fail?** Fix now. + +### REFACTOR - Clean Up + +After green only: +- Remove duplication +- Improve names +- Extract helpers + +Keep tests green. Don't add behavior. + +### Repeat + +Next failing test for next feature. + +## Good Tests + +| Quality | Good | Bad | +|---------|------|-----| +| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` | +| **Clear** | Name describes behavior | `test('test1')` | +| **Shows intent** | Demonstrates desired API | Obscures what code should do | + +## Why Order Matters + +**"I'll write tests after to verify it works"** + +Tests written after code pass immediately. Passing immediately proves nothing: +- Might test wrong thing +- Might test implementation, not behavior +- Might miss edge cases you forgot +- You never saw it catch the bug + +Test-first forces you to see the test fail, proving it actually tests something. + +**"I already manually tested all the edge cases"** + +Manual testing is ad-hoc. You think you tested everything but: +- No record of what you tested +- Can't re-run when code changes +- Easy to forget cases under pressure +- "It worked when I tried it" ≠ comprehensive + +Automated tests are systematic. They run the same way every time. + +**"Deleting X hours of work is wasteful"** + +Sunk cost fallacy. The time is already gone. Your choice now: +- Delete and rewrite with TDD (X more hours, high confidence) +- Keep it and add tests after (30 min, low confidence, likely bugs) + +The "waste" is keeping code you can't trust. Working code without real tests is technical debt. + +**"TDD is dogmatic, being pragmatic means adapting"** + +TDD IS pragmatic: +- Finds bugs before commit (faster than debugging after) +- Prevents regressions (tests catch breaks immediately) +- Documents behavior (tests show how to use code) +- Enables refactoring (change freely, tests catch breaks) + +"Pragmatic" shortcuts = debugging in production = slower. + +**"Tests after achieve the same goals - it's spirit not ritual"** + +No. Tests-after answer "What does this do?" Tests-first answer "What should this do?" + +Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones. + +Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't). + +30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Too simple to test" | Simple code breaks. Test takes 30 seconds. | +| "I'll test after" | Tests passing immediately prove nothing. | +| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" | +| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. | +| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. | +| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. | +| "Need to explore first" | Fine. Throw away exploration, start with TDD. | +| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. | +| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. | +| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. | +| "Existing code has no tests" | You're improving it. Add tests for existing code. | + +## Red Flags - STOP and Start Over + +- Code before test +- Test after implementation +- Test passes immediately +- Can't explain why test failed +- Tests added "later" +- Rationalizing "just this once" +- "I already manually tested it" +- "Tests after achieve the same purpose" +- "It's about spirit not ritual" +- "Keep as reference" or "adapt existing code" +- "Already spent X hours, deleting is wasteful" +- "TDD is dogmatic, I'm being pragmatic" +- "This is different because..." + +**All of these mean: Delete code. Start over with TDD.** + +## Example: Bug Fix + +**Bug:** Empty email accepted + +**RED** +```typescript +test('rejects empty email', async () => { + const result = await submitForm({ email: '' }); + expect(result.error).toBe('Email required'); +}); +``` + +**Verify RED** +```bash +$ npm test +FAIL: expected 'Email required', got undefined +``` + +**GREEN** +```typescript +function submitForm(data: FormData) { + if (!data.email?.trim()) { + return { error: 'Email required' }; + } + // ... +} +``` + +**Verify GREEN** +```bash +$ npm test +PASS +``` + +**REFACTOR** +Extract validation for multiple fields if needed. + +## Verification Checklist + +Before marking work complete: + +- [ ] Every new function/method has a test +- [ ] Watched each test fail before implementing +- [ ] Each test failed for expected reason (feature missing, not typo) +- [ ] Wrote minimal code to pass each test +- [ ] All tests pass +- [ ] Output pristine (no errors, warnings) +- [ ] Tests use real code (mocks only if unavoidable) +- [ ] Edge cases and errors covered + +Can't check all boxes? You skipped TDD. Start over. + +## When Stuck + +| Problem | Solution | +|---------|----------| +| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. | +| Test too complicated | Design too complicated. Simplify interface. | +| Must mock everything | Code too coupled. Use dependency injection. | +| Test setup huge | Extract helpers. Still complex? Simplify design. | + +## Debugging Integration + +Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression. + +Never fix bugs without a test. + +## Testing Anti-Patterns + +When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls: +- Testing mock behavior instead of real behavior +- Adding test-only methods to production classes +- Mocking without understanding dependencies + +## Final Rule + +``` +Production code → test exists and failed first +Otherwise → not TDD +``` + +No exceptions without your human partner's permission. diff --git a/packages/rules/.ai-rules/skills/writing-plans/SKILL.md b/packages/rules/.ai-rules/skills/writing-plans/SKILL.md new file mode 100644 index 00000000..448ca319 --- /dev/null +++ b/packages/rules/.ai-rules/skills/writing-plans/SKILL.md @@ -0,0 +1,116 @@ +--- +name: writing-plans +description: Use when you have a spec or requirements for a multi-step task, before touching code +--- + +# Writing Plans + +## Overview + +Write comprehensive implementation plans assuming the engineer has zero context for our codebase and questionable taste. Document everything they need to know: which files to touch for each task, code, testing, docs they might need to check, how to test it. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits. + +Assume they are a skilled developer, but know almost nothing about our toolset or problem domain. Assume they don't know good test design very well. + +**Announce at start:** "I'm using the writing-plans skill to create the implementation plan." + +**Context:** This should be run in a dedicated worktree (created by brainstorming skill). + +**Save plans to:** `docs/plans/YYYY-MM-DD-.md` + +## Bite-Sized Task Granularity + +**Each step is one action (2-5 minutes):** +- "Write the failing test" - step +- "Run it to make sure it fails" - step +- "Implement the minimal code to make the test pass" - step +- "Run the tests and make sure they pass" - step +- "Commit" - step + +## Plan Document Header + +**Every plan MUST start with this header:** + +```markdown +# [Feature Name] Implementation Plan + +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** [One sentence describing what this builds] + +**Architecture:** [2-3 sentences about approach] + +**Tech Stack:** [Key technologies/libraries] + +--- +``` + +## Task Structure + +```markdown +### Task N: [Component Name] + +**Files:** +- Create: `exact/path/to/file.py` +- Modify: `exact/path/to/existing.py:123-145` +- Test: `tests/exact/path/to/test.py` + +**Step 1: Write the failing test** + +```python +def test_specific_behavior(): + result = function(input) + assert result == expected +``` + +**Step 2: Run test to verify it fails** + +Run: `pytest tests/path/test.py::test_name -v` +Expected: FAIL with "function not defined" + +**Step 3: Write minimal implementation** + +```python +def function(input): + return expected +``` + +**Step 4: Run test to verify it passes** + +Run: `pytest tests/path/test.py::test_name -v` +Expected: PASS + +**Step 5: Commit** + +```bash +git add tests/path/test.py src/path/file.py +git commit -m "feat: add specific feature" +``` +``` + +## Remember +- Exact file paths always +- Complete code in plan (not "add validation") +- Exact commands with expected output +- Reference relevant skills with @ syntax +- DRY, YAGNI, TDD, frequent commits + +## Execution Handoff + +After saving the plan, offer execution choice: + +**"Plan complete and saved to `docs/plans/.md`. Two execution options:** + +**1. Subagent-Driven (this session)** - I dispatch fresh subagent per task, review between tasks, fast iteration + +**2. Parallel Session (separate)** - Open new session with executing-plans, batch execution with checkpoints + +**Which approach?"** + +**If Subagent-Driven chosen:** +- **REQUIRED SUB-SKILL:** Use superpowers:subagent-driven-development +- Stay in this session +- Fresh subagent per task + code review + +**If Parallel Session chosen:** +- Guide them to open new session in worktree +- **REQUIRED SUB-SKILL:** New session uses superpowers:executing-plans diff --git a/yarn.lock b/yarn.lock index 7d53f444..46bbc8cf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2738,6 +2738,7 @@ __metadata: typescript: "npm:^5.1.3" typescript-eslint: "npm:^8.50.0" vitest: "npm:^4.0.15" + yaml: "npm:^2.8.2" zod: "npm:^4.2.1" bin: codingbuddy: ./dist/src/cli/cli.js @@ -7243,6 +7244,15 @@ __metadata: languageName: node linkType: hard +"yaml@npm:^2.8.2": + version: 2.8.2 + resolution: "yaml@npm:2.8.2" + bin: + yaml: bin.mjs + checksum: 10c0/703e4dc1e34b324aa66876d63618dcacb9ed49f7e7fe9b70f1e703645be8d640f68ab84f12b86df8ac960bac37acf5513e115de7c970940617ce0343c8c9cd96 + languageName: node + linkType: hard + "yargs-parser@npm:21.1.1": version: 21.1.1 resolution: "yargs-parser@npm:21.1.1"