commit 96f735d5ddea0ea1e2f5aeca8a2b8bb43d8f1b83 Author: Zhongwei Li Date: Sun Nov 30 08:27:59 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..28c0225 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "name": "next-project-starter", + "description": "Starter bundle for Next.js projects with commands, hooks, scripts, and MCP integration", + "version": "0.1.0", + "author": { + "name": "ClaudeSmith" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..20201c2 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# next-project-starter + +Starter bundle for Next.js projects with commands, hooks, scripts, and MCP integration diff --git a/commands/dev-docs-update.md b/commands/dev-docs-update.md new file mode 100644 index 0000000..35242a9 --- /dev/null +++ b/commands/dev-docs-update.md @@ -0,0 +1,55 @@ +--- +description: Update dev documentation before context compaction +argument-hint: Optional - specific context or tasks to focus on (leave empty for comprehensive update) +--- + +We're approaching context limits. Please update the development documentation to ensure seamless continuation after context reset. + +## Required Updates + +### 1. Update Active Task Documentation +For each task in `/dev/active/`: +- Update `[task-name]-context.md` with: + - Current implementation state + - Key decisions made this session + - Files modified and why + - Any blockers or issues discovered + - Next immediate steps + - Last Updated timestamp + +- Update `[task-name]-tasks.md` with: + - Mark completed tasks as ✅ + - Add any new tasks discovered + - Update in-progress tasks with current status + - Reorder priorities if needed + +### 2. Capture Session Context +Include any relevant information about: +- Complex problems solved +- Architectural decisions made +- Tricky bugs found and fixed +- Integration points discovered +- Testing approaches used +- Performance optimizations made + +### 3. Update Memory (if applicable) +- Store any new patterns or solutions in project memory/documentation +- Update entity relationships discovered +- Add observations about system behavior + +### 4. Document Unfinished Work +- What was being worked on when context limit approached +- Exact state of any partially completed features +- Commands that need to be run on restart +- Any temporary workarounds that need permanent fixes + +### 5. Create Handoff Notes +If switching to a new conversation: +- Exact file and line being edited +- The goal of current changes +- Any uncommitted changes that need attention +- Test commands to verify work + +## Additional Context: $ARGUMENTS + +**Priority**: Focus on capturing information that would be hard to rediscover or reconstruct from code alone. diff --git a/commands/dev-docs.md b/commands/dev-docs.md new file mode 100644 index 0000000..d368739 --- /dev/null +++ b/commands/dev-docs.md @@ -0,0 +1,51 @@ +--- +description: Create a comprehensive strategic plan with structured task breakdown +argument-hint: Describe what you need planned (e.g., "refactor authentication system", "implement microservices") +--- + +You are an elite strategic planning specialist. Create a comprehensive, actionable plan for: $ARGUMENTS + +## Instructions + +1. **Analyze the request** and determine the scope of planning needed +2. **Examine relevant files** in the codebase to understand current state +3. **Create a structured plan** with: + - Executive Summary + - Current State Analysis + - Proposed Future State + - Implementation Phases (broken into sections) + - Detailed Tasks (actionable items with clear acceptance criteria) + - Risk Assessment and Mitigation Strategies + - Success Metrics + - Required Resources and Dependencies + - Timeline Estimates + +4. **Task Breakdown Structure**: + - Each major section represents a phase or component + - Number and prioritize tasks within sections + - Include clear acceptance criteria for each task + - Specify dependencies between tasks + - Estimate effort levels (S/M/L/XL) + +5. **Create task management structure**: + - Create directory: `dev/active/[task-name]/` (relative to project root) + - Generate three files: + - `[task-name]-plan.md` - The comprehensive plan + - `[task-name]-context.md` - Key files, decisions, dependencies + - `[task-name]-tasks.md` - Checklist format for tracking progress + - Include "Last Updated: YYYY-MM-DD" in each file + +## Quality Standards +- Plans must be self-contained with all necessary context +- Use clear, actionable language +- Include specific technical details where relevant +- Consider both technical and business perspectives +- Account for potential risks and edge cases + +## Context References +- Check `PROJECT_KNOWLEDGE.md` for architecture overview (if exists) +- Consult `BEST_PRACTICES.md` for coding standards (if exists) +- Reference `TROUBLESHOOTING.md` for common issues to avoid (if exists) +- Use `dev/README.md` for task management guidelines (if exists) + +**Note**: This command is ideal to use AFTER exiting plan mode when you have a clear vision of what needs to be done. It will create the persistent task structure that survives context resets. diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..fa1967e --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,18 @@ +{ + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PLUGIN_ROOT/scripts/tsc-check.sh" + }, + { + "type": "command", + "command": "$CLAUDE_PLUGIN_ROOT/scripts/trigger-build-resolver.sh" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..7bb3c97 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,113 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:JNLei/claude-tools:plugins/bundles/next-project-starter", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "0193e23d4aa31ead5268a166704f6812f48ab97f", + "treeHash": "602b5ed51b398249e2b291e506924765e49de3a27ce2164b9a81296dfb457291", + "generatedAt": "2025-11-28T10:11:44.278869Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "next-project-starter", + "description": "Starter bundle for Next.js projects with commands, hooks, scripts, and MCP integration", + "version": "0.1.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "06914be9fb96e7f92b6ccbe1a2433ae56be1ab18eb79fdb1202553b10c4bd1af" + }, + { + "path": "hooks/hooks.json", + "sha256": "93fb21e1a59d63bd2e70f62053f669f104c8e4714a93c2dca42e471956f7f085" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "316d5c48459cc0863d27018b3bd385c98955d966840e217b1296c5497454b655" + }, + { + "path": "commands/dev-docs-update.md", + "sha256": "d646991cb570e0fd8997c9d2a5a5c056d9a8ed0e82679cb9cd4a2f93be13fc1f" + }, + { + "path": "commands/dev-docs.md", + "sha256": "b57d5ebed8414e3d513200ab6cdd1ecfa8980a923ff2bf7563a265041df39b86" + }, + { + "path": "skills/frontend-development/EXAMPLES.md", + "sha256": "ec19cfb7b4c6c1226451c1bf7e3b7f56b4a5766e739f0c4c5877d11bb7fe0661" + }, + { + "path": "skills/frontend-development/NEW-PROJECT-DESIGN.md", + "sha256": "42fa68402825ea9f8563d3a057cf6fb1ccd3e10947fbebba28ca1090e1d9ab50" + }, + { + "path": "skills/frontend-development/REFERENCE.md", + "sha256": "e4be9c20f3904fd27ac888403783f396c1d9531b1c884a4dda8b0981372be470" + }, + { + "path": "skills/frontend-development/SKILL.md", + "sha256": "ae07734934c1f5c9abcbef0ccd750357f7544e48eeae8818d5e277c13a7c0aa8" + }, + { + "path": "skills/frontend-development/EXISTING-CODEBASE-CHECKLIST.md", + "sha256": "fae943ea6a89df10e9fa9bf1932854141e983ac5c3ba55db32003f084ad349e9" + }, + { + "path": "skills/skill-optimizer/REFERENCE.md", + "sha256": "50e1bad80b59bf74c8b663e06ee376f4d30e29edc701e471b32f63eaa9b5b97f" + }, + { + "path": "skills/skill-optimizer/SKILL.md", + "sha256": "24c2eaaf73e4c7fb8a2ea045fdec038fa6efc8dd407c3c17d01181a8ad2de1bd" + }, + { + "path": "skills/skill-developer/HOOK_MECHANISMS.md", + "sha256": "05302c5cde78b50f9c540419b055914c57c8125b47021fb8d6a968e37d24b5ed" + }, + { + "path": "skills/skill-developer/SKILL_RULES_REFERENCE.md", + "sha256": "c8a797d56f9e0eb34d617eb4cfee634bb93a584f0c65d54d42ac08122ac7d5dd" + }, + { + "path": "skills/skill-developer/TROUBLESHOOTING.md", + "sha256": "ef2a88b968cf16f17397faf199ee0a01608330a31ffb00789339a9aa66381a18" + }, + { + "path": "skills/skill-developer/ADVANCED.md", + "sha256": "0071ca449978bf2035599126a0b462f53efe2f3cfdae57e23499aa4e0b0560aa" + }, + { + "path": "skills/skill-developer/SKILL.md", + "sha256": "6413b039ed0917024c9dd4f6fe5a34025a5e27f4f86af0b55b8b74bc56518221" + }, + { + "path": "skills/skill-developer/HOW-SKILL-WORKS.md", + "sha256": "c6e5b346f9b52aadb7f221710990f57ff094e041098a40c16bcacbc1cdc7234e" + }, + { + "path": "skills/skill-developer/PATTERNS_LIBRARY.md", + "sha256": "9c516c5f10f12cecba40abb217fac981b2cc1f92af37090262da184c9e2eb62a" + }, + { + "path": "skills/skill-developer/TRIGGER_TYPES.md", + "sha256": "120b3222b5d3c96e3f2b397673782967d463114107af2e420c170e7fb44f966c" + } + ], + "dirSha256": "602b5ed51b398249e2b291e506924765e49de3a27ce2164b9a81296dfb457291" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/frontend-development/EXAMPLES.md b/skills/frontend-development/EXAMPLES.md new file mode 100644 index 0000000..866c011 --- /dev/null +++ b/skills/frontend-development/EXAMPLES.md @@ -0,0 +1,484 @@ +# Examples & Case Studies + +Real-world examples demonstrating correct and incorrect application of frontend design principles. + +--- + +## Table of Contents + +1. [Case Study: Blog Search Bar (Design Consistency)](#case-study-blog-search-bar) +2. [Example: Component Reuse Decision Matrix](#example-component-reuse-decision) +3. [Example: Typography Consistency](#example-typography-consistency) +4. [Example: Layout Pattern Matching](#example-layout-pattern-matching) +5. [Anti-Example: Generic AI Slop](#anti-example-generic-ai-slop) + +--- + +## Case Study: Blog Search Bar + +**Context:** Adding a search bar to a blog page in an existing Next.js application. + +### ❌ WRONG APPROACH (Autopilot Mode) + +**What happened:** +``` +User: "Blog page needs a search bar" +Assistant: [Sees SearchBar component exists] → [Pastes component into blog page] → Done +``` + +**Implementation:** +```tsx +// Blog page +
+
+ +
+
+ +// SearchBar component (from tools page) +export default function SearchBar({ value, onChange }: SearchBarProps) { + return ( +
{/* ← PROBLEM: Centered with narrow container */} + + +
+ ); +} +``` + +**Result:** +- ❌ Search bar centered on left-aligned page +- ❌ max-w-2xl container inside max-w-5xl container +- ❌ Visual inconsistency with rest of blog page +- ❌ Breaks design language + +**Visual outcome:** +``` +Blog Page (LEFT-ALIGNED, max-w-5xl) +┌─────────────────────────────────────────────────┐ +│ Blog │ +│ Real-world guides... │ +│ │ +│ ┌──────────────────┐ │ ← Centered, narrow +│ │ [Search bar] │ │ +│ └──────────────────┘ │ +│ │ +│ [All Posts - left-aligned cards] │ +└─────────────────────────────────────────────────┘ +``` + +### ✅ RIGHT APPROACH (Design-Thinking Mode) + +**Process:** + +**Phase 1: Design Language Analysis** + +```markdown +## Design Language Analysis + +### Files Scanned +- src/app/blog/page.tsx (blog landing page) +- src/app/page.tsx (tools page for comparison) +- src/components/SearchBar.tsx +- src/components/CategoryFilter.tsx +- src/app/globals.css + +### Layout Patterns +- Blog page: LEFT-ALIGNED layout throughout +- All blog sections use max-w-5xl container +- Category filter buttons are left-aligned +- Blog cards grid is left-aligned + +- Tools page (for comparison): CENTERED layout +- Tools hero uses max-w-3xl centered +- Tools SearchBar uses max-w-2xl centered + +**Key insight:** Blog page has CONSISTENT left-aligned pattern with max-w-5xl containers. + +### Component Patterns +- SearchBar component exists with built-in max-w-2xl mx-auto (centered) +- This pattern works for tools page but NOT for blog page +- Category filter on blog page is left-aligned (not centered) +``` + +**Phase 2: Design Decisions** + +```markdown +## Design Decisions + +### Pattern Application +Blog page requires LEFT-ALIGNED full-width search within max-w-5xl container. +Cannot use SearchBar's centered max-w-2xl pattern - would break consistency. + +### Component Approach +Options: +1. Add width/alignment variant props to SearchBar component +2. Create inline search input specifically for blog page +3. Create new FullWidthSearchBar component + +Decision: Option 1 - Extend SearchBar with optional props +- Maintains component reuse +- Allows flexibility for different layout contexts +- Avoids code duplication + +### Consistency Requirements +MUST maintain: +- max-w-5xl container (matches rest of blog page) +- Full width within container (left-aligned, not centered) +- Same input styling (h-11, pl-10, bg-card, search icon) +- Same search functionality + +CAN vary: +- Container width and alignment (adapts to page context) +``` + +**Phase 3: Implementation** + +```tsx +// Enhanced SearchBar component with layout props +interface SearchBarProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; + fullWidth?: boolean; // New prop +} + +export default function SearchBar({ + value, + onChange, + placeholder = "Search...", + fullWidth = false // Default to centered (backward compatible) +}: SearchBarProps) { + return ( +
+ + onChange(e.target.value)} + placeholder={placeholder} + className="w-full pl-10 pr-4 h-11 bg-card" + /> +
+ ); +} + +// Blog page usage +
+
+ +
+
+ +// Tools page usage (unchanged, backward compatible) +
+
+ +
+
+``` + +**Result:** +- ✅ Search bar matches blog page's left-aligned layout +- ✅ Consistent max-w-5xl container width +- ✅ Component reuse with flexibility +- ✅ Backward compatible (tools page unchanged) +- ✅ Design language preserved + +**Visual outcome:** +``` +Blog Page (LEFT-ALIGNED, max-w-5xl) +┌─────────────────────────────────────────────────┐ +│ Blog │ +│ Real-world guides... │ +│ │ +│ ┌─────────────────────────────────────────────┐ │ ← Full width, left-aligned +│ │ [Search bar] │ │ +│ └─────────────────────────────────────────────┘ │ +│ │ +│ [All Posts - left-aligned cards] │ +└─────────────────────────────────────────────────┘ +``` + +### Key Lessons + +1. **Don't skip analysis** - The checklist exists for a reason +2. **Scan multiple files** - Understanding context requires comprehensive analysis +3. **Document patterns** - Explicit output makes thinking visible +4. **Consider reuse vs creation** - Adapt existing components when possible +5. **Match the context** - Blog's left-aligned pattern ≠ Tools' centered pattern + +--- + +## Example: Component Reuse Decision + +**Scenario:** Need a card component for a new dashboard section. + +### Analysis + +**Existing components found:** +1. `ToolCard` - Border, rounded corners, hover effect, vertical layout +2. `BlogPostCard` - Border, rounded corners, gradient header, vertical layout +3. `FeatureCard` - No border, shadow effect, horizontal layout + +### Decision Matrix + +| Option | Pros | Cons | Decision | +|--------|------|------|----------| +| Reuse ToolCard | Matches border/rounded style | Vertical layout might not fit | ❌ Layout mismatch | +| Reuse FeatureCard | Horizontal layout fits | No border/rounded style | ❌ Style mismatch | +| Create DashboardCard | Perfect fit for needs | New component = maintenance | ⚠️ Only if truly different | +| **Extend ToolCard with layout prop** | Reuses existing + flexible | Small refactor needed | ✅ **Best choice** | + +### Implementation + +```tsx +// Extended ToolCard with layout variant +interface ToolCardProps { + tool: Tool; + layout?: 'vertical' | 'horizontal'; +} + +export default function ToolCard({ tool, layout = 'vertical' }: ToolCardProps) { + const isHorizontal = layout === 'horizontal'; + + return ( +
+ {/* Content adapts to layout */} +
+ ); +} +``` + +--- + +## Example: Typography Consistency + +**Scenario:** Adding a new "About" page to existing site. + +### Analysis Output + +```markdown +## Typography Patterns (from existing pages) + +### Heading Hierarchy +- H1: text-3xl md:text-4xl, font-semibold, tracking-tight +- H2: text-xl md:text-2xl, font-semibold +- H3: text-lg, font-medium + +### Body Text +- Default: text-base, leading-relaxed +- Small: text-sm +- Meta/timestamps: text-xs, text-muted-foreground + +### Font Family +- Primary: Inter with fallbacks +- No display font used +- No monospace needed (no code samples) +``` + +### Correct Implementation + +```tsx +// About page - matches existing hierarchy +
+

+ About Us +

+ +

+ Our story begins... +

+ +

+ Our Mission +

+ +

+ We believe in... +

+
+``` + +### ❌ Incorrect Implementation + +```tsx +// DON'T: Different sizes, weights, tracking +
+

{/* ← Too large, too bold */} + About Us +

+ +

{/* ← Larger than existing pages */} + Our story begins... +

+ +

{/* ← font-bold instead of font-semibold */} + Our Mission +

+
+``` + +--- + +## Example: Layout Pattern Matching + +**Scenario:** Adding a "Pricing" page. + +### Pattern Analysis + +**Existing page patterns:** +- Home: Centered hero (max-w-3xl) → Wide content (max-w-5xl) +- Blog: All sections left-aligned (max-w-5xl) +- Tools: Centered hero (max-w-3xl) → Wide grid (max-w-5xl) + +**Decision:** Pricing is marketing content, matches "Home" pattern. + +### Correct Implementation + +```tsx +// Pricing page - matches Home pattern +export default function PricingPage() { + return ( +
+ {/* Hero: Centered, narrow */} +
+
+

+ Simple, Transparent Pricing +

+
+
+ + {/* Plans: Wide, centered grid */} +
+
+
+ {/* Pricing cards */} +
+
+
+
+ ); +} +``` + +--- + +## Anti-Example: Generic AI Slop + +### ❌ The Problem + +**Request:** "Create a landing page for a SaaS product" + +**Generic AI Output:** +```tsx +// Predictable, seen-it-before structure +
+ {/* Purple gradient hero */} +
+
+

+ Revolutionize Your Workflow +

+

+ The all-in-one platform for modern teams +

+ +
+
+ + {/* Three feature cards */} +
+
+ + + +
+
+ + {/* Testimonials */} + {/* CTA */} +
+``` + +**Font:** Inter (of course) +**Colors:** Purple gradient (of course) +**Layout:** Centered everything (of course) + +**Problem:** Indistinguishable from 1000 other AI-generated SaaS pages. + +### ✅ Better Approach + +**Apply design thinking:** +- What makes THIS product different? +- Who is the audience? (Technical? Creative? Enterprise?) +- What feeling should the design evoke? +- What's ONE memorable element? + +**Example re-design (Brutalist/Technical Direction):** +```tsx +// Bold, distinctive approach +
+ {/* Terminal-style hero */} +
+
+
$ initialize_revolution.sh
+

+ SYSTEM
+ OVERRIDE +

+

+ For developers who don't compromise. Raw power. Zero abstraction. +

+
+ +
+
+
+ + {/* Asymmetric feature layout */} +
+
+
+ {/* Main feature */} +
+
+ {/* Stats ticker */} +
+
+
+
+``` + +**Distinctive elements:** +- Terminal/command-line aesthetic +- Monospace typography +- High-contrast green-on-black +- Asymmetric grid layout +- Technical/hacker vibe +- Memorable and specific to audience + +--- + +## More Examples + +For additional examples and techniques, see: +- [REFERENCE.md](REFERENCE.md#advanced-techniques) - Deep-dive patterns +- [NEW-PROJECT-DESIGN.md](NEW-PROJECT-DESIGN.md) - Aesthetic philosophy +- [EXISTING-CODEBASE-CHECKLIST.md](EXISTING-CODEBASE-CHECKLIST.md) - Consistency workflow diff --git a/skills/frontend-development/EXISTING-CODEBASE-CHECKLIST.md b/skills/frontend-development/EXISTING-CODEBASE-CHECKLIST.md new file mode 100644 index 0000000..c05f84c --- /dev/null +++ b/skills/frontend-development/EXISTING-CODEBASE-CHECKLIST.md @@ -0,0 +1,174 @@ +# Existing Codebase: Design Consistency Checklist + +**⚠️ MANDATORY WORKFLOW FOR EXISTING CODEBASES** + +When adding components, pages, or UI elements to an existing codebase, you MUST complete this analysis and OUTPUT your findings BEFORE writing any code. This prevents design language inconsistencies. + +--- + +## Phase 1: Design Language Analysis (REQUIRED OUTPUT) + +**YOU MUST OUTPUT A "DESIGN LANGUAGE ANALYSIS" SECTION** showing: + +### 1. Files Scanned +- List specific files you examined (components, pages, layouts) +- Minimum 3-5 related files + +### 2. Layout Patterns Identified +- Document: Centered vs left-aligned content +- Document: Container max-widths used (e.g., max-w-2xl, max-w-5xl, max-w-7xl) +- Document: Spacing patterns (section padding, element gaps) +- Document: Grid systems and responsive breakpoints + +### 3. Typography Patterns Identified +- Document: Font families used (primary, display, mono) +- Document: Heading hierarchy (h1, h2, h3 styles) +- Document: Font sizes, weights, line heights +- Document: Text colors and muted text patterns + +### 4. Component Patterns Identified +- Document: How similar existing components are structured +- Document: Reusable UI components available (buttons, inputs, cards) +- Document: State management patterns +- Document: Animation and interaction patterns + +### 5. Color & Theme Patterns +- Document: CSS variables or theme system used +- Document: Color palette (background, foreground, accent, muted) +- Document: Light/dark mode approach + +### Example Output Format + +```markdown +## Design Language Analysis + +### Files Scanned +- src/app/page.tsx (tools landing page) +- src/app/blog/page.tsx (blog landing page) +- src/components/SearchBar.tsx +- src/components/ToolCard.tsx +- src/app/globals.css + +### Layout Patterns +- Blog page: LEFT-ALIGNED with max-w-5xl containers +- Tools page: CENTERED hero with max-w-3xl, then max-w-5xl for content +- Consistent: py-8 px-6 section padding +- Consistent: max-w-5xl for main content areas + +### Typography Patterns +- Font: Inter with fallbacks +- H1: text-3xl md:text-4xl, font-semibold +- Body: text-base, text-sm for meta +- Muted text: text-muted-foreground + +### Component Patterns +- SearchBar: Exists, uses max-w-2xl centered layout +- Cards: Border, rounded-lg, hover states +- Inputs: h-11 height, pl-10 with icon, bg-card background + +### Color & Theme +- Dark theme via CSS variables +- Background: hsl(0 0% 7%) +- Muted: hsl(0 0% 60%) +``` + +--- + +## Phase 2: Design Decisions (REQUIRED OUTPUT) + +**YOU MUST OUTPUT A "DESIGN DECISIONS" SECTION** documenting: + +### 1. Which patterns apply to this new component/page? +- What layout approach matches the context? +- What typography styles should be used? +- What spacing values maintain consistency? + +### 2. Should you adapt existing components or create new ones? +- Can existing components be reused as-is? +- Do existing components need props/variants added? +- Is a new component justified, or would it create inconsistency? + +### 3. What are the consistency requirements? +- What MUST stay the same (e.g., container width on blog pages) +- What CAN vary (e.g., component-specific details) + +### Example Output Format + +```markdown +## Design Decisions + +### Pattern Application +Blog page uses LEFT-ALIGNED layout with max-w-5xl containers throughout. +The search bar must match this pattern, NOT the centered max-w-2xl pattern from tools page. + +### Component Approach +SearchBar component exists but is designed for centered layouts (max-w-2xl mx-auto). +Options: +1. Add width variant prop to SearchBar +2. Create inline search input for blog page +Decision: Option 2 - create inline search to match blog's full-width pattern + +### Consistency Requirements +MUST maintain: +- max-w-5xl container (matches rest of blog page) +- Full width within container (left-aligned, not centered) +- Same input styling (h-11, pl-10, bg-card) +- Same search icon positioning + +CAN vary: +- Container width (must match blog's max-w-5xl, not tools' max-w-2xl) +``` + +--- + +## Phase 3: Implementation + +**ONLY AFTER** completing Phase 1 and Phase 2 outputs above, proceed with writing code. + +### Implementation Guidelines + +**For existing codebases**, maintain consistency with identified patterns: + +- **Typography**: Use existing font families, sizes, weights +- **Color & Theme**: Use existing CSS variables and color tokens +- **Spacing**: Match existing padding, margin, gap patterns +- **Components**: Reuse or extend existing components when possible +- **Animations**: Match existing motion and interaction patterns + +**See also:** +- [EXAMPLES.md](EXAMPLES.md) - Real-world case studies +- [REFERENCE.md](REFERENCE.md) - Deep aesthetic principles (apply only where consistent) + +--- + +## Common Mistakes to Avoid + +❌ **Skipping Phase 1** - Jumping straight to implementation without analysis +❌ **Shallow scanning** - Only looking at 1-2 files instead of comprehensive analysis +❌ **Ignoring patterns** - Seeing patterns but not applying them +❌ **Component bloat** - Creating new components when existing ones could be adapted +❌ **Inconsistent widths** - Mixing centered and left-aligned layouts on the same page type +❌ **Typography drift** - Using different fonts, sizes, or weights without justification +❌ **Color divergence** - Adding new color values instead of using existing tokens + +--- + +## Checklist Summary + +Before writing any code: + +- [ ] Scanned 3-5 related files +- [ ] Documented layout patterns (alignment, containers, spacing) +- [ ] Documented typography patterns (fonts, hierarchy, colors) +- [ ] Documented component patterns (structure, reusable components) +- [ ] Documented color/theme patterns (variables, palette, mode) +- [ ] OUTPUT complete "Design Language Analysis" section +- [ ] Decided which patterns apply to new work +- [ ] Decided on component reuse vs creation strategy +- [ ] Identified consistency requirements (MUST vs CAN) +- [ ] OUTPUT complete "Design Decisions" section +- [ ] **Only then**: Proceed to implementation + +--- + +**Remember:** The goal is consistency, not perfection. When in doubt, match existing patterns. diff --git a/skills/frontend-development/NEW-PROJECT-DESIGN.md b/skills/frontend-development/NEW-PROJECT-DESIGN.md new file mode 100644 index 0000000..508069d --- /dev/null +++ b/skills/frontend-development/NEW-PROJECT-DESIGN.md @@ -0,0 +1,335 @@ +# New Project: Aesthetic Design Philosophy + +**Use this when building from scratch** - no existing codebase to match, full creative freedom. + +This guide helps you create bold, distinctive frontend interfaces that avoid generic "AI slop" aesthetics and deliver memorable user experiences. + +--- + +## Design Thinking Process + +Before coding, understand the context and commit to a BOLD aesthetic direction. + +### 1. Understand the Context + +**Purpose** +- What problem does this interface solve? +- Who are the users? +- What are their goals and pain points? + +**Constraints** +- Technical requirements (framework, performance targets) +- Accessibility standards (WCAG compliance) +- Browser support needs +- Device/viewport considerations + +**Differentiation** +- What makes this interface UNFORGETTABLE? +- What's the one thing someone will remember? +- How does it stand out from competitors? + +### 2. Choose an Aesthetic Direction + +**Pick an extreme** - commit fully to a clear conceptual direction: + +- **Brutally minimal**: Sparse layouts, monochrome palette, extreme negative space +- **Maximalist chaos**: Dense information, bold colors, layered complexity +- **Retro-futuristic**: Nostalgic elements with modern tech aesthetic +- **Organic/natural**: Flowing forms, earthy tones, biomimicry +- **Luxury/refined**: Sophisticated typography, muted elegance, premium feel +- **Playful/toy-like**: Rounded shapes, bright colors, whimsical interactions +- **Editorial/magazine**: Strong typography hierarchy, grid-based, content-focused +- **Brutalist/raw**: Exposed structure, harsh contrasts, utilitarian +- **Art deco/geometric**: Symmetry, geometric patterns, metallic accents +- **Soft/pastel**: Gentle gradients, low contrast, calming atmosphere +- **Industrial/utilitarian**: Function-first, mechanical aesthetics, technical precision + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +### 3. Implementation Goals + +Create working code that is: + +✅ **Production-grade and functional** +- Real, working code (not mockups) +- Properly structured components +- Responsive across devices +- Accessible to all users + +✅ **Visually striking and memorable** +- Immediate visual impact +- Distinctive from generic templates +- Reinforces brand/purpose + +✅ **Cohesive with clear aesthetic point-of-view** +- Every element serves the chosen direction +- Consistent visual language +- Intentional design decisions throughout + +✅ **Meticulously refined in every detail** +- Precise spacing and alignment +- Thoughtful micro-interactions +- Polish in typography, color, motion + +--- + +## Frontend Aesthetics Guidelines + +Apply these principles when executing your design vision: + +### Typography + +**Go beyond generic fonts** - typography is personality. + +✅ **DO:** +- Choose distinctive, characterful fonts +- Pair a bold display font with a refined body font +- Use font variation (weight, width, slant) for hierarchy +- Consider custom/variable fonts for uniqueness +- Test readability across sizes and contexts + +❌ **AVOID:** +- Generic system fonts (Arial, Helvetica, system-ui) +- Overused web fonts (Inter, Roboto - unless intentional) +- Poor contrast or readability +- Inconsistent font pairing + +**Examples:** +- Display: Ginto, Clash Display, Syne, Archivo Black, Fraunces +- Body: Work Sans, Söhne, Untitled Sans, Sentient, Supreme +- Mono: JetBrains Mono, Commit Mono, Berkeley Mono + +### Color & Theme + +**Commit to a cohesive palette** - colors create atmosphere. + +✅ **DO:** +- Use CSS variables for consistency +- Choose dominant colors with sharp accents +- Create intentional color relationships +- Consider color psychology (warm/cool, energetic/calming) +- Test contrast for accessibility (WCAG AA minimum) + +❌ **AVOID:** +- Timid, evenly-distributed palettes +- Clichéd combinations (purple gradient on white) +- Poor contrast ratios +- Randomness without purpose + +**Approaches:** +- **Monochrome + accent**: Single base color with one bold accent +- **Analogous harmony**: Adjacent colors on color wheel +- **Bold contrast**: High-contrast complementary colors +- **Muted elegance**: Desaturated tones with subtle variation + +### Motion & Animation + +**Animate with purpose** - motion should delight and inform. + +✅ **DO:** +- Prioritize CSS-only solutions for performance +- Use Motion library (Framer Motion) for React when needed +- Focus on high-impact moments (page load, key interactions) +- Use staggered reveals (animation-delay) for orchestration +- Add scroll-triggered animations for engagement +- Create surprising hover states + +❌ **AVOID:** +- Scattered, meaningless micro-interactions +- Performance-heavy JavaScript animations for simple effects +- Motion that distracts from content +- Animations without easing (linear motion feels robotic) + +**High-Impact Patterns:** +- Staggered fade-in on page load +- Smooth scroll-triggered reveals +- Morphing shapes on interaction +- Parallax effects (use sparingly) +- Magnetic cursor effects +- Elastic hover states + +### Spatial Composition + +**Break expectations** - layouts should surprise and guide. + +✅ **DO:** +- Use asymmetry intentionally +- Overlap elements for depth +- Create diagonal flow to guide eye +- Add grid-breaking elements for interest +- Use generous negative space OR controlled density (not in-between) + +❌ **AVOID:** +- Predictable centered layouts +- Uniform spacing everywhere +- Tight, cramped compositions +- Lack of visual hierarchy + +**Techniques:** +- **Asymmetric grids**: Offset columns, uneven distribution +- **Z-index layering**: Overlap for depth and dimensionality +- **Diagonal flow**: Angles create energy and movement +- **Negative space**: Breathing room emphasizes important content +- **Controlled density**: Information-rich areas with clear structure + +### Backgrounds & Visual Details + +**Create atmosphere** - go beyond solid colors. + +✅ **DO:** +- Add contextual textures and effects +- Use gradient meshes for depth +- Apply subtle noise/grain overlays +- Create layered transparencies +- Add dramatic shadows for elevation +- Consider decorative borders and ornaments +- Experiment with custom cursor styles + +❌ **AVOID:** +- Plain solid color backgrounds everywhere +- Overused gradient patterns +- Details that don't match aesthetic direction +- Visual noise without purpose + +**Techniques:** +- **Gradient meshes**: Soft, organic color transitions +- **Noise textures**: Subtle grain for tactile quality +- **Geometric patterns**: Structured, repeating motifs +- **Radial gradients**: Spotlight effects, vignettes +- **Blurred shapes**: Abstract background elements +- **Glass morphism**: Frosted glass effects (backdrop-filter) + +--- + +## Anti-Patterns: Avoiding AI Slop + +**NEVER** create generic AI-generated aesthetics. Recognize and avoid these patterns: + +❌ **Overused font families** +- Inter everywhere (it's become the Arial of AI-generated designs) +- Roboto (overused, lacks character) +- System fonts without intentionality +- Space Grotesk (recently overused in AI designs) + +❌ **Clichéd color schemes** +- Purple gradients on white backgrounds +- Generic blue/teal combinations +- Pastel everything without purpose +- Rainbow gradients without restraint + +❌ **Predictable layouts** +- Centered hero → 3 feature cards → testimonials → CTA +- Same component patterns as every SaaS landing page +- No surprises, no memorable moments +- Cookie-cutter grid systems + +❌ **Lack of context-specific character** +- Designs that could be for any product/service +- No connection to brand, purpose, or audience +- Generic stock photography aesthetic +- Templated feel throughout + +--- + +## Creative Freedom Guidelines + +**Interpret creatively** - make unexpected choices that feel genuinely designed for the context. + +### Vary Your Approach + +**No two designs should be the same.** Intentionally vary: + +- **Theme**: Light vs dark (or something in between) +- **Density**: Spacious vs information-rich +- **Tone**: Professional vs playful vs experimental +- **Complexity**: Minimal vs maximalist +- **Typography**: Serif vs sans-serif vs mixed +- **Color**: Monochrome vs vibrant vs muted + +**NEVER converge on common choices** across different projects. If you used Space Grotesk last time, choose something completely different this time. + +### Match Complexity to Vision + +**Aesthetic vision dictates code complexity:** + +**Maximalist designs** → Elaborate implementation +- Extensive animations and effects +- Complex layering and composition +- Rich interactions and micro-animations +- Advanced CSS techniques + +**Minimalist designs** → Restrained implementation +- Precise spacing and alignment +- Subtle, purposeful animations +- Careful typography tuning +- Attention to micro-details + +**Elegance comes from executing the vision well**, not from choosing "simple" vs "complex." + +--- + +## Implementation Checklist + +Before finalizing your design: + +### Context & Strategy +- [ ] Clearly defined purpose and audience +- [ ] Identified key differentiator (the memorable element) +- [ ] Chosen specific aesthetic direction (not generic) +- [ ] Considered technical constraints + +### Typography +- [ ] Distinctive font choices (not Inter/Roboto by default) +- [ ] Clear hierarchy (display vs body vs UI) +- [ ] Tested readability across sizes +- [ ] Proper font pairing + +### Color & Theme +- [ ] Cohesive color palette with CSS variables +- [ ] Intentional color relationships +- [ ] Tested contrast for accessibility (WCAG AA+) +- [ ] Avoided clichéd combinations + +### Motion & Animation +- [ ] High-impact moments identified and animated +- [ ] CSS-first approach for performance +- [ ] Easing curves feel natural +- [ ] Animations enhance, not distract + +### Spatial Composition +- [ ] Unexpected or intentional layout choices +- [ ] Visual hierarchy guides user attention +- [ ] Appropriate use of space (generous or dense) +- [ ] Breaking the grid where appropriate + +### Visual Details +- [ ] Contextual backgrounds and textures +- [ ] Atmospheric depth (gradients, shadows, layers) +- [ ] Details match chosen aesthetic +- [ ] Polish in every interaction + +### Originality +- [ ] Doesn't look like generic AI output +- [ ] Context-specific character throughout +- [ ] Memorable and distinctive +- [ ] Different from previous projects + +--- + +## Remember + +**Claude is capable of extraordinary creative work.** + +Don't hold back. Show what can truly be created when: +- Thinking outside the box +- Committing fully to a distinctive vision +- Avoiding generic templates and patterns +- Designing with intention and purpose + +Create something unforgettable. + +--- + +**See also:** +- [EXAMPLES.md](EXAMPLES.md) - Real-world design examples and case studies +- [REFERENCE.md](REFERENCE.md) - Deep-dive into specific aesthetic techniques diff --git a/skills/frontend-development/REFERENCE.md b/skills/frontend-development/REFERENCE.md new file mode 100644 index 0000000..c302f13 --- /dev/null +++ b/skills/frontend-development/REFERENCE.md @@ -0,0 +1,769 @@ +# Frontend Design Reference + +Comprehensive guide to aesthetic principles, advanced techniques, and deep-dive guidance for creating exceptional frontend interfaces. + +--- + +## Table of Contents + +1. [Advanced Typography Techniques](#advanced-typography-techniques) +2. [Color Theory & Application](#color-theory--application) +3. [Motion Design Principles](#motion-design-principles) +4. [Spatial Composition Techniques](#spatial-composition-techniques) +5. [Visual Depth & Atmosphere](#visual-depth--atmosphere) +6. [Responsive Design Patterns](#responsive-design-patterns) +7. [Accessibility & Inclusive Design](#accessibility--inclusive-design) +8. [Performance Optimization](#performance-optimization) +9. [Design System Patterns](#design-system-patterns) + +--- + +## Advanced Typography Techniques + +### Font Pairing Strategies + +**Rule of Contrast** +Pair fonts that are different enough to create hierarchy, but harmonious enough to feel cohesive. + +**Successful Pairings:** +```css +/* Display + Sans */ +--font-display: 'Clash Display', sans-serif; /* Bold, geometric */ +--font-body: 'Inter', sans-serif; /* Clean, readable */ + +/* Serif + Sans */ +--font-display: 'Fraunces', serif; /* Classic, elegant */ +--font-body: 'Untitled Sans', sans-serif; /* Modern, neutral */ + +/* Mono + Sans */ +--font-code: 'JetBrains Mono', monospace; /* Technical */ +--font-body: 'Work Sans', sans-serif; /* Professional */ +``` + +**Font Pairing Framework:** +1. **Contrast in style** - Serif vs Sans, Geometric vs Humanist +2. **Harmony in proportion** - Similar x-heights or cap heights +3. **Shared characteristics** - Similar stroke contrast or terminals +4. **Appropriate mood** - Both match the aesthetic direction + +### Variable Fonts + +**Advantages:** +- Single file, multiple styles +- Smooth animations between weights/widths +- Fine-tuned responsive typography +- Performance benefits + +**Implementation:** +```css +@font-face { + font-family: 'InterVariable'; + src: url('/fonts/Inter-Variable.woff2') format('woff2'); + font-weight: 100 900; + font-display: swap; +} + +.heading { + font-family: 'InterVariable', sans-serif; + font-weight: 700; + + @media (max-width: 768px) { + font-weight: 600; /* Lighter weight on mobile */ + } +} + +/* Animate weight on interaction */ +.button { + font-weight: 500; + transition: font-weight 0.2s ease; +} + +.button:hover { + font-weight: 700; +} +``` + +### Typographic Rhythm + +**Vertical Rhythm:** +Consistent spacing based on baseline grid. + +```css +:root { + --baseline: 8px; + --line-height: 1.5; +} + +h1 { + font-size: 48px; + line-height: calc(var(--baseline) * 8); /* 64px */ + margin-bottom: calc(var(--baseline) * 4); /* 32px */ +} + +p { + font-size: 16px; + line-height: calc(var(--baseline) * 3); /* 24px */ + margin-bottom: calc(var(--baseline) * 3); /* 24px */ +} +``` + +**Modular Scale:** +Type sizes based on mathematical ratio. + +```css +:root { + --ratio: 1.25; /* Major third */ + --base-size: 16px; +} + +.text-xs { font-size: calc(var(--base-size) / var(--ratio) / var(--ratio)); } +.text-sm { font-size: calc(var(--base-size) / var(--ratio)); } +.text-base { font-size: var(--base-size); } +.text-lg { font-size: calc(var(--base-size) * var(--ratio)); } +.text-xl { font-size: calc(var(--base-size) * var(--ratio) * var(--ratio)); } +.text-2xl { font-size: calc(var(--base-size) * var(--ratio) * var(--ratio) * var(--ratio)); } +``` + +### Advanced Typography CSS + +**Optical alignment:** +```css +.heading { + /* Hanging punctuation */ + hanging-punctuation: first last; + + /* Adjust spacing for visual balance */ + letter-spacing: -0.02em; /* Tighter tracking for large headings */ +} +``` + +**OpenType features:** +```css +.body-text { + /* Enable ligatures and contextual alternates */ + font-feature-settings: + "liga" 1, /* Standard ligatures */ + "calt" 1, /* Contextual alternates */ + "kern" 1; /* Kerning */ + + /* Better for body text */ + text-rendering: optimizeLegibility; +} + +.numbers { + /* Tabular figures for alignment */ + font-variant-numeric: tabular-nums; +} +``` + +--- + +## Color Theory & Application + +### Color Psychology + +**Warm Colors** - Energy, passion, urgency +- Red: Bold, attention-grabbing, urgent +- Orange: Friendly, enthusiastic, creative +- Yellow: Optimistic, cheerful, attention + +**Cool Colors** - Trust, calm, professionalism +- Blue: Trustworthy, stable, corporate +- Green: Natural, growth, health +- Purple: Luxury, creativity, wisdom + +**Neutral Colors** - Balance, sophistication +- Black: Elegant, powerful, formal +- White: Clean, minimal, pure +- Gray: Professional, timeless, neutral + +### Advanced Color Systems + +**HSL-Based Design:** +Benefits of HSL over RGB/Hex: +- Easier to create variations (lighter, darker) +- Intuitive manipulation (hue, saturation, lightness) +- Better for programmatic generation + +```css +:root { + /* Base color in HSL */ + --hue: 220; + --saturation: 70%; + --lightness: 50%; + + /* Generate color scale */ + --color-50: hsl(var(--hue), var(--saturation), 95%); + --color-100: hsl(var(--hue), var(--saturation), 90%); + --color-200: hsl(var(--hue), var(--saturation), 80%); + --color-300: hsl(var(--hue), var(--saturation), 70%); + --color-400: hsl(var(--hue), var(--saturation), 60%); + --color-500: hsl(var(--hue), var(--saturation), 50%); + --color-600: hsl(var(--hue), var(--saturation), 40%); + --color-700: hsl(var(--hue), var(--saturation), 30%); + --color-800: hsl(var(--hue), var(--saturation), 20%); + --color-900: hsl(var(--hue), var(--saturation), 10%); +} +``` + +**Semantic Color Tokens:** +```css +:root { + /* Primitive colors */ + --blue-500: hsl(220, 70%, 50%); + --red-500: hsl(0, 70%, 50%); + --green-500: hsl(140, 60%, 45%); + + /* Semantic tokens */ + --color-primary: var(--blue-500); + --color-danger: var(--red-500); + --color-success: var(--green-500); + + /* Contextual usage */ + --button-bg: var(--color-primary); + --error-text: var(--color-danger); +} + +/* Easily theme by changing primitives */ +[data-theme="orange"] { + --blue-500: hsl(30, 70%, 50%); /* Override to orange */ +} +``` + +### Color Accessibility + +**WCAG Contrast Requirements:** +- **AA** (minimum): 4.5:1 for normal text, 3:1 for large text +- **AAA** (enhanced): 7:1 for normal text, 4.5:1 for large text + +**Testing contrast:** +```css +/* Bad: Insufficient contrast */ +.low-contrast { + color: #999; /* Gray */ + background: #fff; /* White */ + /* Ratio: ~2.8:1 - FAILS AA */ +} + +/* Good: Meets AA */ +.good-contrast { + color: #666; /* Darker gray */ + background: #fff; /* White */ + /* Ratio: ~5.7:1 - PASSES AA */ +} + +/* Better: Meets AAA */ +.best-contrast { + color: #333; /* Even darker */ + background: #fff; /* White */ + /* Ratio: ~12.6:1 - PASSES AAA */ +} +``` + +--- + +## Motion Design Principles + +### Easing Functions + +**Never use linear easing** - it feels robotic and unnatural. + +**Standard easings:** +```css +/* Ease-out: Fast start, slow end (entering elements) */ +.enter { + animation: slideIn 0.3s cubic-bezier(0, 0, 0.2, 1); +} + +/* Ease-in: Slow start, fast end (exiting elements) */ +.exit { + animation: slideOut 0.2s cubic-bezier(0.4, 0, 1, 1); +} + +/* Ease-in-out: Smooth both ends (position changes) */ +.move { + transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); +} + +/* Spring/bounce: Playful, energetic */ +.bounce { + animation: bounce 0.6s cubic-bezier(0.68, -0.55, 0.27, 1.55); +} +``` + +**Custom easings for character:** +```css +:root { + --ease-smooth: cubic-bezier(0.4, 0, 0.2, 1); + --ease-bounce: cubic-bezier(0.68, -0.55, 0.27, 1.55); + --ease-snap: cubic-bezier(0.87, 0, 0.13, 1); +} +``` + +### Orchestrated Animations + +**Staggered delays create rhythm:** +```css +.card-grid > .card { + opacity: 0; + animation: fadeInUp 0.5s var(--ease-smooth) forwards; +} + +.card:nth-child(1) { animation-delay: 0.1s; } +.card:nth-child(2) { animation-delay: 0.2s; } +.card:nth-child(3) { animation-delay: 0.3s; } +.card:nth-child(4) { animation-delay: 0.4s; } + +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} +``` + +**Or programmatic delays:** +```jsx +{items.map((item, index) => ( + +))} +``` + +### Performance-First Animation + +**Use transform and opacity only** - these are GPU-accelerated. + +```css +/* ❌ BAD: Causes repaints */ +.slow { + transition: width 0.3s, height 0.3s, top 0.3s, left 0.3s; +} + +/* ✅ GOOD: GPU-accelerated */ +.fast { + transition: transform 0.3s, opacity 0.3s; +} +``` + +**Will-change hint:** +```css +.animated-element { + /* Tell browser this will animate */ + will-change: transform; +} + +/* Remove after animation completes */ +.animated-element.animation-done { + will-change: auto; +} +``` + +### Scroll-Triggered Animations + +**Intersection Observer pattern:** +```jsx +useEffect(() => { + const observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + entry.target.classList.add('visible'); + } + }); + }, + { threshold: 0.1 } + ); + + document.querySelectorAll('.reveal-on-scroll').forEach((el) => { + observer.observe(el); + }); + + return () => observer.disconnect(); +}, []); +``` + +```css +.reveal-on-scroll { + opacity: 0; + transform: translateY(30px); + transition: opacity 0.6s var(--ease-smooth), + transform 0.6s var(--ease-smooth); +} + +.reveal-on-scroll.visible { + opacity: 1; + transform: translateY(0); +} +``` + +--- + +## Spatial Composition Techniques + +### Grid Breaking + +**Start with a grid, then selectively break it:** + +```css +.grid-container { + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 1.5rem; +} + +/* Standard grid items */ +.grid-item { + grid-column: span 4; +} + +/* Break the grid for emphasis */ +.featured-item { + grid-column: 1 / -1; /* Full width */ + grid-row: span 2; /* Double height */ +} + +.offset-item { + grid-column: 3 / 11; /* Offset from edges */ +} +``` + +### Asymmetric Layouts + +**Visual tension creates interest:** + +```css +/* Asymmetric two-column */ +.asymmetric-layout { + display: grid; + grid-template-columns: 2fr 1fr; /* 66% / 33% split */ + gap: 3rem; +} + +/* Diagonal composition */ +.diagonal-section { + display: grid; + grid-template-columns: repeat(3, 1fr); + transform: rotate(-2deg); /* Subtle tilt */ +} + +.diagonal-section > * { + transform: rotate(2deg); /* Counter-rotate content */ +} +``` + +### Z-Index Layering + +**Create depth through layering:** + +```css +:root { + /* Z-index scale */ + --z-base: 0; + --z-elevated: 10; + --z-sticky: 100; + --z-overlay: 1000; + --z-modal: 10000; +} + +.layered-composition { + position: relative; +} + +.background-shape { + position: absolute; + z-index: var(--z-base); + opacity: 0.1; +} + +.content { + position: relative; + z-index: var(--z-elevated); +} + +.floating-element { + position: absolute; + z-index: calc(var(--z-elevated) + 1); + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); +} +``` + +--- + +## Visual Depth & Atmosphere + +### Shadow System + +**Layered shadows for realism:** + +```css +:root { + /* Elevation system */ + --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1), + 0 2px 4px rgba(0, 0, 0, 0.06); + --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1), + 0 4px 6px rgba(0, 0, 0, 0.05); + --shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1), + 0 10px 10px rgba(0, 0, 0, 0.04); +} + +/* Colored shadows for vibrancy */ +.vibrant-button { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4); +} +``` + +### Gradient Meshes + +**Complex, organic color transitions:** + +```css +.gradient-mesh { + background: + radial-gradient(at 20% 30%, hsl(220, 70%, 60%) 0px, transparent 50%), + radial-gradient(at 80% 20%, hsl(280, 70%, 60%) 0px, transparent 50%), + radial-gradient(at 40% 80%, hsl(180, 70%, 50%) 0px, transparent 50%), + radial-gradient(at 90% 70%, hsl(30, 80%, 60%) 0px, transparent 50%), + hsl(240, 20%, 10%); +} +``` + +### Texture & Grain + +**Subtle texture adds tactility:** + +```css +.noise-texture { + position: relative; +} + +.noise-texture::after { + content: ''; + position: absolute; + inset: 0; + background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' /%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' /%3E%3C/svg%3E"); + opacity: 0.03; + pointer-events: none; +} +``` + +### Glass Morphism + +**Frosted glass effect:** + +```css +.glass { + background: rgba(255, 255, 255, 0.1); + backdrop-filter: blur(10px) saturate(180%); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 12px; +} + +/* Dark mode variation */ +[data-theme="dark"] .glass { + background: rgba(0, 0, 0, 0.3); + border-color: rgba(255, 255, 255, 0.1); +} +``` + +--- + +## Responsive Design Patterns + +### Container Queries + +**Component-based responsive design:** + +```css +.card-container { + container-type: inline-size; +} + +.card { + display: flex; + flex-direction: column; +} + +/* Respond to container width, not viewport */ +@container (min-width: 400px) { + .card { + flex-direction: row; + } +} +``` + +### Fluid Typography + +**Smooth scaling between viewports:** + +```css +:root { + --fluid-min-width: 320; + --fluid-max-width: 1200; + + --fluid-screen: 100vw; + --fluid-bp: calc( + (var(--fluid-screen) - var(--fluid-min-width) / 16 * 1rem) / + (var(--fluid-max-width) - var(--fluid-min-width)) + ); +} + +h1 { + font-size: clamp(2rem, calc(2rem + 2 * var(--fluid-bp)), 4rem); +} + +/* Or use modern clamp directly */ +h1 { + font-size: clamp(2rem, 5vw, 4rem); + /* Min: 2rem, Preferred: 5vw, Max: 4rem */ +} +``` + +--- + +## Accessibility & Inclusive Design + +### Focus Management + +**Visible, clear focus indicators:** + +```css +/* Remove default outline, add custom */ +:focus { + outline: none; +} + +:focus-visible { + outline: 2px solid var(--color-primary); + outline-offset: 2px; + border-radius: 4px; +} + +/* High contrast for keyboard users */ +.button:focus-visible { + outline: 3px solid var(--color-primary); + outline-offset: 4px; + box-shadow: 0 0 0 6px rgba(var(--primary-rgb), 0.2); +} +``` + +### Screen Reader Considerations + +**Visually hidden but accessible:** + +```css +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} +``` + +```jsx + +``` + +### Reduced Motion + +**Respect user preferences:** + +```css +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} +``` + +--- + +## Performance Optimization + +### Critical CSS + +**Inline critical CSS, defer rest:** + +```html + + + + + + + + +``` + +### Image Optimization + +**Modern formats with fallbacks:** + +```jsx + + + + Description + +``` + +--- + +## Design System Patterns + +### Token Architecture + +**Layered token system:** + +```css +:root { + /* Layer 1: Primitive tokens */ + --color-blue-500: hsl(220, 70%, 50%); + --color-red-500: hsl(0, 70%, 50%); + --spacing-4: 1rem; + + /* Layer 2: Semantic tokens */ + --color-primary: var(--color-blue-500); + --color-danger: var(--color-red-500); + --button-padding: var(--spacing-4); + + /* Layer 3: Component tokens */ + --button-bg: var(--color-primary); + --button-text: white; + --button-padding-x: var(--button-padding); +} +``` + +--- + +**This reference provides deep-dive guidance. For workflows, see:** +- [SKILL.md](SKILL.md) - Scenario router +- [EXISTING-CODEBASE-CHECKLIST.md](EXISTING-CODEBASE-CHECKLIST.md) - Consistency workflow +- [NEW-PROJECT-DESIGN.md](NEW-PROJECT-DESIGN.md) - Aesthetic philosophy +- [EXAMPLES.md](EXAMPLES.md) - Real-world case studies diff --git a/skills/frontend-development/SKILL.md b/skills/frontend-development/SKILL.md new file mode 100644 index 0000000..99849c5 --- /dev/null +++ b/skills/frontend-development/SKILL.md @@ -0,0 +1,60 @@ +--- +name: frontend-design +description: Create distinctive, production-grade frontend interfaces with exceptional design quality. Two modes - (1) New projects - bold aesthetic design philosophy including typography, color theory, spatial composition, motion design, visual details, avoiding generic AI aesthetics, creating unforgettable interfaces. (2) Existing codebases - mandatory design language analysis enforcing consistency by scanning layout patterns, typography hierarchy, component structure, spacing, theme systems before implementation. Use when building components, pages, applications, design systems, UI modifications. Covers React, Vue, Next.js, HTML/CSS, Tailwind. Keywords - create component, build page, design interface, add UI, aesthetic design, visual design, typography, animations, spatial layout, design system, consistency, pattern analysis, existing codebase. +--- + +# Frontend Design Skill + +This skill provides two distinct workflows for creating production-grade frontend interfaces: + +## Scenario Detector + +**Answer this question:** Is there an existing codebase with components, pages, or a design system? + +### ✅ YES → Existing Codebase (Most Common) +**Use this workflow:** [EXISTING-CODEBASE-CHECKLIST.md](EXISTING-CODEBASE-CHECKLIST.md) + +**Purpose:** Enforce design language consistency by analyzing existing patterns before implementation. + +**When to use:** +- Adding components to existing project +- Creating new pages in existing app +- Modifying UI in established codebase +- Working with design system + +**Process:** Mandatory 3-phase checklist (Design Analysis → Decisions → Implementation) + +--- + +### ✅ NO → New Project (Greenfield) +**Use this workflow:** [NEW-PROJECT-DESIGN.md](NEW-PROJECT-DESIGN.md) + +**Purpose:** Create bold, distinctive aesthetic design from scratch. + +**When to use:** +- Starting new projects +- Building standalone components/pages +- No existing design system to match +- Full creative freedom + +**Process:** Design thinking → Aesthetic principles → Implementation + +--- + +## Quick Reference + +**For consistency in existing codebases:** +→ [EXISTING-CODEBASE-CHECKLIST.md](EXISTING-CODEBASE-CHECKLIST.md) + +**For aesthetic design philosophy:** +→ [NEW-PROJECT-DESIGN.md](NEW-PROJECT-DESIGN.md) + +**For real-world examples:** +→ [EXAMPLES.md](EXAMPLES.md) + +**For deep-dive principles:** +→ [REFERENCE.md](REFERENCE.md) + +--- + +**Still unsure which scenario applies?** Default to **EXISTING-CODEBASE-CHECKLIST** if there's any existing code to reference. diff --git a/skills/skill-developer/ADVANCED.md b/skills/skill-developer/ADVANCED.md new file mode 100644 index 0000000..711fa81 --- /dev/null +++ b/skills/skill-developer/ADVANCED.md @@ -0,0 +1,197 @@ +# Advanced Topics & Future Enhancements + +Ideas and concepts for future improvements to the skill system. + +--- + +## Dynamic Rule Updates + +**Current State:** Requires Claude Code restart to pick up changes to skill-rules.json + +**Future Enhancement:** Hot-reload configuration without restart + +**Implementation Ideas:** +- Watch skill-rules.json for changes +- Reload on file modification +- Invalidate cached compiled regexes +- Notify user of reload + +**Benefits:** +- Faster iteration during skill development +- No need to restart Claude Code +- Better developer experience + +--- + +## Skill Dependencies + +**Current State:** Skills are independent + +**Future Enhancement:** Specify skill dependencies and load order + +**Configuration Idea:** +```json +{ + "my-advanced-skill": { + "dependsOn": ["prerequisite-skill", "base-skill"], + "type": "domain", + ... + } +} +``` + +**Use Cases:** +- Advanced skill builds on base skill knowledge +- Ensure foundational skills loaded first +- Chain skills for complex workflows + +**Benefits:** +- Better skill composition +- Clearer skill relationships +- Progressive disclosure + +--- + +## Conditional Enforcement + +**Current State:** Enforcement level is static + +**Future Enhancement:** Enforce based on context or environment + +**Configuration Idea:** +```json +{ + "enforcement": { + "default": "suggest", + "when": { + "production": "block", + "development": "suggest", + "ci": "block" + } + } +} +``` + +**Use Cases:** +- Stricter enforcement in production +- Relaxed rules during development +- CI/CD pipeline requirements + +**Benefits:** +- Environment-appropriate enforcement +- Flexible rule application +- Context-aware guardrails + +--- + +## Skill Analytics + +**Current State:** No usage tracking + +**Future Enhancement:** Track skill usage patterns and effectiveness + +**Metrics to Collect:** +- Skill trigger frequency +- False positive rate +- False negative rate +- Time to skill usage after suggestion +- User override rate (skip markers, env vars) +- Performance metrics (execution time) + +**Dashbord Ideas:** +- Most/least used skills +- Skills with highest false positive rate +- Performance bottlenecks +- Skill effectiveness scores + +**Benefits:** +- Data-driven skill improvement +- Identify problems early +- Optimize patterns based on real usage + +--- + +## Skill Versioning + +**Current State:** No version tracking + +**Future Enhancement:** Version skills and track compatibility + +**Configuration Idea:** +```json +{ + "my-skill": { + "version": "2.1.0", + "minClaudeVersion": "1.5.0", + "changelog": "Added support for new workflow patterns", + ... + } +} +``` + +**Benefits:** +- Track skill evolution +- Ensure compatibility +- Document changes +- Support migration paths + +--- + +## Multi-Language Support + +**Current State:** English only + +**Future Enhancement:** Support multiple languages for skill content + +**Implementation Ideas:** +- Language-specific SKILL.md variants +- Automatic language detection +- Fallback to English + +**Use Cases:** +- International teams +- Localized documentation +- Multi-language projects + +--- + +## Skill Testing Framework + +**Current State:** Manual testing with npx tsx commands + +**Future Enhancement:** Automated skill testing + +**Features:** +- Test cases for trigger patterns +- Assertion framework +- CI/CD integration +- Coverage reports + +**Example Test:** +```typescript +describe('database-verification', () => { + it('triggers on Prisma imports', () => { + const result = testSkill({ + prompt: "add user tracking", + file: "services/user.ts", + content: "import { PrismaService } from './prisma'" + }); + + expect(result.triggered).toBe(true); + expect(result.skill).toBe('database-verification'); + }); +}); +``` + +**Benefits:** +- Prevent regressions +- Validate patterns before deployment +- Confidence in changes + +--- + +## Related Files + +- [SKILL.md](SKILL.md) - Main skill guide +- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Current debugging guide +- [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md) - How hooks work today \ No newline at end of file diff --git a/skills/skill-developer/HOOK_MECHANISMS.md b/skills/skill-developer/HOOK_MECHANISMS.md new file mode 100644 index 0000000..fa5a212 --- /dev/null +++ b/skills/skill-developer/HOOK_MECHANISMS.md @@ -0,0 +1,306 @@ +# Hook Mechanisms - Deep Dive + +Technical deep dive into how the UserPromptSubmit and PreToolUse hooks work. + +## Table of Contents + +- [UserPromptSubmit Hook Flow](#userpromptsubmit-hook-flow) +- [PreToolUse Hook Flow](#pretooluse-hook-flow) +- [Exit Code Behavior (CRITICAL)](#exit-code-behavior-critical) +- [Session State Management](#session-state-management) +- [Performance Considerations](#performance-considerations) + +--- + +## UserPromptSubmit Hook Flow + +### Execution Sequence + +``` +User submits prompt + ↓ +.claude/settings.json registers hook + ↓ +skill-activation-prompt.sh executes + ↓ +npx tsx skill-activation-prompt.ts + ↓ +Hook reads stdin (JSON with prompt) + ↓ +Loads skill-rules.json + ↓ +Matches keywords + intent patterns + ↓ +Groups matches by priority (critical → high → medium → low) + ↓ +Outputs formatted message to stdout + ↓ +stdout becomes context for Claude (injected before prompt) + ↓ +Claude sees: [skill suggestion] + user's prompt +``` + +### Key Points + +- **Exit code**: Always 0 (allow) +- **stdout**: → Claude's context (injected as system message) +- **Timing**: Runs BEFORE Claude processes prompt +- **Behavior**: Non-blocking, advisory only +- **Purpose**: Make Claude aware of relevant skills + +### Input Format + +```json +{ + "session_id": "abc-123", + "transcript_path": "/path/to/transcript.json", + "cwd": "/root/git/your-project", + "permission_mode": "normal", + "hook_event_name": "UserPromptSubmit", + "prompt": "how does the layout system work?" +} +``` + +### Output Format (to stdout) + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +🎯 SKILL ACTIVATION CHECK +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📚 RECOMMENDED SKILLS: + → project-catalog-developer + +ACTION: Use Skill tool BEFORE responding +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +Claude sees this output as additional context before processing the user's prompt. + +--- + +## PreToolUse Hook Flow + +### Execution Sequence + +``` +Claude calls Edit/Write tool + ↓ +.claude/settings.json registers hook (matcher: Edit|Write) + ↓ +skill-verification-guard.sh executes + ↓ +npx tsx skill-verification-guard.ts + ↓ +Hook reads stdin (JSON with tool_name, tool_input) + ↓ +Loads skill-rules.json + ↓ +Checks file path patterns (glob matching) + ↓ +Reads file for content patterns (if file exists) + ↓ +Checks session state (was skill already used?) + ↓ +Checks skip conditions (file markers, env vars) + ↓ +IF MATCHED AND NOT SKIPPED: + Update session state (mark skill as enforced) + Output block message to stderr + Exit with code 2 (BLOCK) +ELSE: + Exit with code 0 (ALLOW) + ↓ +IF BLOCKED: + stderr → Claude sees message + Edit/Write tool does NOT execute + Claude must use skill and retry +IF ALLOWED: + Tool executes normally +``` + +### Key Points + +- **Exit code 2**: BLOCK (stderr → Claude) +- **Exit code 0**: ALLOW +- **Timing**: Runs BEFORE tool execution +- **Session tracking**: Prevents repeated blocks in same session +- **Fail open**: On errors, allows operation (don't break workflow) +- **Purpose**: Enforce critical guardrails + +### Input Format + +```json +{ + "session_id": "abc-123", + "transcript_path": "/path/to/transcript.json", + "cwd": "/root/git/your-project", + "permission_mode": "normal", + "hook_event_name": "PreToolUse", + "tool_name": "Edit", + "tool_input": { + "file_path": "/root/git/your-project/form/src/services/user.ts", + "old_string": "...", + "new_string": "..." + } +} +``` + +### Output Format (to stderr when blocked) + +``` +⚠️ BLOCKED - Database Operation Detected + +📋 REQUIRED ACTION: +1. Use Skill tool: 'database-verification' +2. Verify ALL table and column names against schema +3. Check database structure with DESCRIBE commands +4. Then retry this edit + +Reason: Prevent column name errors in Prisma queries +File: form/src/services/user.ts + +💡 TIP: Add '// @skip-validation' comment to skip future checks +``` + +Claude receives this message and understands it needs to use the skill before retrying the edit. + +--- + +## Exit Code Behavior (CRITICAL) + +### Exit Code Reference Table + +| Exit Code | stdout | stderr | Tool Execution | Claude Sees | +|-----------|--------|--------|----------------|-------------| +| 0 (UserPromptSubmit) | → Context | → User only | N/A | stdout content | +| 0 (PreToolUse) | → User only | → User only | **Proceeds** | Nothing | +| 2 (PreToolUse) | → User only | → **CLAUDE** | **BLOCKED** | stderr content | +| Other | → User only | → User only | Blocked | Nothing | + +### Why Exit Code 2 Matters + +This is THE critical mechanism for enforcement: + +1. **Only way** to send message to Claude from PreToolUse +2. stderr content is "fed back to Claude automatically" +3. Claude sees the block message and understands what to do +4. Tool execution is prevented +5. Critical for enforcement of guardrails + +### Example Conversation Flow + +``` +User: "Add a new user service with Prisma" + +Claude: "I'll create the user service..." + [Attempts to Edit form/src/services/user.ts] + +PreToolUse Hook: [Exit code 2] + stderr: "⚠️ BLOCKED - Use database-verification" + +Claude sees error, responds: + "I need to verify the database schema first." + [Uses Skill tool: database-verification] + [Verifies column names] + [Retries Edit - now allowed (session tracking)] +``` + +--- + +## Session State Management + +### Purpose + +Prevent repeated nagging in the same session - once Claude uses a skill, don't block again. + +### State File Location + +`.claude/hooks/state/skills-used-{session_id}.json` + +### State File Structure + +```json +{ + "skills_used": [ + "database-verification", + "error-tracking" + ], + "files_verified": [] +} +``` + +### How It Works + +1. **First edit** of file with Prisma: + - Hook blocks with exit code 2 + - Updates session state: adds "database-verification" to skills_used + - Claude sees message, uses skill + +2. **Second edit** (same session): + - Hook checks session state + - Finds "database-verification" in skills_used + - Exits with code 0 (allow) + - No message to Claude + +3. **Different session**: + - New session ID = new state file + - Hook blocks again + +### Limitation + +The hook cannot detect when the skill is *actually* invoked - it just blocks once per session per skill. This means: + +- If Claude doesn't use the skill but makes a different edit, it won't block again +- Trust that Claude follows the instruction +- Future enhancement: detect actual Skill tool usage + +--- + +## Performance Considerations + +### Target Metrics + +- **UserPromptSubmit**: < 100ms +- **PreToolUse**: < 200ms + +### Performance Bottlenecks + +1. **Loading skill-rules.json** (every execution) + - Future: Cache in memory + - Future: Watch for changes, reload only when needed + +2. **Reading file content** (PreToolUse) + - Only when contentPatterns configured + - Only if file exists + - Can be slow for large files + +3. **Glob matching** (PreToolUse) + - Regex compilation for each pattern + - Future: Compile once, cache + +4. **Regex matching** (Both hooks) + - Intent patterns (UserPromptSubmit) + - Content patterns (PreToolUse) + - Future: Lazy compile, cache compiled regexes + +### Optimization Strategies + +**Reduce patterns:** +- Use more specific patterns (fewer to check) +- Combine similar patterns where possible + +**File path patterns:** +- More specific = fewer files to check +- Example: `form/src/services/**` better than `form/**` + +**Content patterns:** +- Only add when truly necessary +- Simpler regex = faster matching + +--- + +**Related Files:** +- [SKILL.md](SKILL.md) - Main skill guide +- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Debug hook issues +- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Configuration reference \ No newline at end of file diff --git a/skills/skill-developer/HOW-SKILL-WORKS.md b/skills/skill-developer/HOW-SKILL-WORKS.md new file mode 100644 index 0000000..1a941bf --- /dev/null +++ b/skills/skill-developer/HOW-SKILL-WORKS.md @@ -0,0 +1,193 @@ +# How Skills work + +Skills leverage Claude's VM environment to provide capabilities beyond what's possible with prompts alone. Claude operates in a virtual machine with filesystem access, allowing Skills to exist as directories containing instructions, executable code, and reference materials, organized like an onboarding guide you'd create for a new team member. + +This filesystem-based architecture enables **progressive disclosure**: Claude loads information in stages as needed, rather than consuming context upfront. + +### Three types of Skill content, three levels of loading + +Skills can contain three types of content, each loaded at different times: + +### Level 1: Metadata (always loaded) + +**Content type: Instructions**. The Skill's YAML frontmatter provides discovery information: + +```yaml theme={null} +--- +name: pdf-processing +description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. +--- +``` + +Claude loads this metadata at startup and includes it in the system prompt. This lightweight approach means you can install many Skills without context penalty; Claude only knows each Skill exists and when to use it. + +### Level 2: Instructions (loaded when triggered) + +**Content type: Instructions**. The main body of SKILL.md contains procedural knowledge: workflows, best practices, and guidance: + +````markdown theme={null} +# PDF Processing + +## Quick start + +Use pdfplumber to extract text from PDFs: + +```python +import pdfplumber + +with pdfplumber.open("document.pdf") as pdf: + text = pdf.pages[0].extract_text() +``` + +For advanced form filling, see [FORMS.md](FORMS.md). +```` + +When you request something that matches a Skill's description, Claude reads SKILL.md from the filesystem via bash. Only then does this content enter the context window. + +### Level 3: Resources and code (loaded as needed) + +**Content types: Instructions, code, and resources**. Skills can bundle additional materials: + +``` +pdf-skill/ +├── SKILL.md (main instructions) +├── FORMS.md (form-filling guide) +├── REFERENCE.md (detailed API reference) +└── scripts/ + └── fill_form.py (utility script) +``` + +**Instructions**: Additional markdown files (FORMS.md, REFERENCE.md) containing specialized guidance and workflows + +**Code**: Executable scripts (fill\_form.py, validate.py) that Claude runs via bash; scripts provide deterministic operations without consuming context + +**Resources**: Reference materials like database schemas, API documentation, templates, or examples + +Claude accesses these files only when referenced. The filesystem model means each content type has different strengths: instructions for flexible guidance, code for reliability, resources for factual lookup. + +| Level | When Loaded | Token Cost | Content | +| ------------------------- | ----------------------- | ---------------------- | --------------------------------------------------------------------- | +| **Level 1: Metadata** | Always (at startup) | \~100 tokens per Skill | `name` and `description` from YAML frontmatter | +| **Level 2: Instructions** | When Skill is triggered | Under 5k tokens | SKILL.md body with instructions and guidance | +| **Level 3+: Resources** | As needed | Effectively unlimited | Bundled files executed via bash without loading contents into context | + +Progressive disclosure ensures only relevant content occupies the context window at any given time. + +### The Skills architecture + +Skills run in a code execution environment where Claude has filesystem access, bash commands, and code execution capabilities. Think of it like this: Skills exist as directories on a virtual machine, and Claude interacts with them using the same bash commands you'd use to navigate files on your computer. + +Agent Skills Architecture - showing how Skills integrate with the agent's configuration and virtual machine + +**How Claude accesses Skill content:** + +When a Skill is triggered, Claude uses bash to read SKILL.md from the filesystem, bringing its instructions into the context window. If those instructions reference other files (like FORMS.md or a database schema), Claude reads those files too using additional bash commands. When instructions mention executable scripts, Claude runs them via bash and receives only the output (the script code itself never enters context). + +**What this architecture enables:** + +**On-demand file access**: Claude reads only the files needed for each specific task. A Skill can include dozens of reference files, but if your task only needs the sales schema, Claude loads just that one file. The rest remain on the filesystem consuming zero tokens. + +**Efficient script execution**: When Claude runs `validate_form.py`, the script's code never loads into the context window. Only the script's output (like "Validation passed" or specific error messages) consumes tokens. This makes scripts far more efficient than having Claude generate equivalent code on the fly. + +**No practical limit on bundled content**: Because files don't consume context until accessed, Skills can include comprehensive API documentation, large datasets, extensive examples, or any reference materials you need. There's no context penalty for bundled content that isn't used. + +This filesystem-based model is what makes progressive disclosure work. Claude navigates your Skill like you'd reference specific sections of an onboarding guide, accessing exactly what each task requires. + +### Example: Loading a PDF processing skill + +Here's how Claude loads and uses a PDF processing skill: + +1. **Startup**: System prompt includes: `PDF Processing - Extract text and tables from PDF files, fill forms, merge documents` +2. **User request**: "Extract the text from this PDF and summarize it" +3. **Claude invokes**: `bash: read pdf-skill/SKILL.md` → Instructions loaded into context +4. **Claude determines**: Form filling is not needed, so FORMS.md is not read +5. **Claude executes**: Uses instructions from SKILL.md to complete the task + +Skills loading into context window - showing the progressive loading of skill metadata and content + +The diagram shows: + +1. Default state with system prompt and skill metadata pre-loaded +2. Claude triggers the skill by reading SKILL.md via bash +3. Claude optionally reads additional bundled files like FORMS.md as needed +4. Claude proceeds with the task + +This dynamic loading ensures only relevant skill content occupies the context window. + +## Skill structure + +Every Skill requires a `SKILL.md` file with YAML frontmatter: + +```yaml theme={null} +--- +name: your-skill-name +description: Brief description of what this Skill does and when to use it +--- + +# Your Skill Name + +## Instructions +[Clear, step-by-step guidance for Claude to follow] + +## Examples +[Concrete examples of using this Skill] +``` + +**Required fields**: `name` and `description` + +**Field requirements**: + +`name`: + +* Maximum 64 characters +* Must contain only lowercase letters, numbers, and hyphens +* Cannot contain XML tags +* Cannot contain reserved words: "anthropic", "claude" + +`description`: + +* Must be non-empty +* Maximum 1024 characters +* Cannot contain XML tags + +The `description` should include both what the Skill does and when Claude should use it. For complete authoring guidance, see the [best practices guide](/en/docs/agents-and-tools/agent-skills/best-practices). + +## Limitations and constraints + +Understanding these limitations helps you plan your Skills deployment effectively. + +### Cross-surface availability + +**Custom Skills do not sync across surfaces**. Skills uploaded to one surface are not automatically available on others: + +* Skills uploaded to Claude.ai must be separately uploaded to the API +* Skills uploaded via the API are not available on Claude.ai +* Claude Code Skills are filesystem-based and separate from both Claude.ai and API + +You'll need to manage and upload Skills separately for each surface where you want to use them. + +### Sharing scope + +Skills have different sharing models depending on where you use them: + +* **Claude.ai**: Individual user only; each team member must upload separately +* **Claude API**: Workspace-wide; all workspace members can access uploaded Skills +* **Claude Code**: Personal (`~/.claude/skills/`) or project-based (`.claude/skills/`); can also be shared via Claude Code Plugins + +Claude.ai does not currently support centralized admin management or org-wide distribution of custom Skills. + +### Runtime environment constraints + +The exact runtime environment available to your skill depends on the product surface where you use it. + +* **Claude.ai**: + * **Varying network access**: Depending on user/admin settings, Skills may have full, partial, or no network access. For more details, see the [Create and Edit Files](https://support.claude.com/en/articles/12111783-create-and-edit-files-with-claude#h_6b7e833898) support article. +* **Claude API**: + * **No network access**: Skills cannot make external API calls or access the internet + * **No runtime package installation**: Only pre-installed packages are available. You cannot install new packages during execution. + * **Pre-configured dependencies only**: Check the [code execution tool documentation](/en/docs/agents-and-tools/tool-use/code-execution-tool) for the list of available packages +* **Claude Code**: + * **Full network access**: Skills have the same network access as any other program on the user's computer + * **Global package installation discouraged**: Skills should only install packages locally in order to avoid interfering with the user's computer + +Plan your Skills to work within these constraints. diff --git a/skills/skill-developer/PATTERNS_LIBRARY.md b/skills/skill-developer/PATTERNS_LIBRARY.md new file mode 100644 index 0000000..e959e94 --- /dev/null +++ b/skills/skill-developer/PATTERNS_LIBRARY.md @@ -0,0 +1,152 @@ +# Common Patterns Library + +Ready-to-use regex and glob patterns for skill triggers. + +--- + +## Intent Patterns (Regex) + +### Feature/Endpoint Creation +```regex +(add|create|implement|build).*?(feature|endpoint|route|service|controller|api) +``` + +### Component Creation +```regex +(create|add|make|build).*?(component|UI|page|modal|dialog|form) +``` + +### Database Work +```regex +(add|create|modify|update).*?(user|table|column|field|schema|migration) +(database|prisma).*?(change|update|query) +``` + +### Error Handling +```regex +(fix|handle|catch|debug).*?(error|exception|bug) +(add|implement).*?(try|catch|error.*?handling) +``` + +### Explanation Requests +```regex +(how does|how do|explain|what is|describe|tell me about).*? +``` + +### Workflow Operations +```regex +(create|add|modify|update).*?(workflow|step|branch|condition) +(debug|troubleshoot|fix).*?workflow +``` + +### Testing +```regex +(write|create|add).*?(test|spec|unit.*?test) +``` + +--- + +## File Path Patterns (Glob) + +### Frontend +```glob +packages/ui/src/**/*.tsx # All React components +packages/ui/src/**/*.ts # All TypeScript files +packages/ui/src/components/** # Only components directory +``` + +### API Service +```glob +packages/api/src/routes/*.ts # +email/src/**/*.ts # Email service +users/src/**/*.ts # Users service +projects/src/**/*.ts # Projects service +``` + +### Database +```glob +**/schema.prisma # Prisma schema (anywhere) +**/migrations/**/*.sql # Migration files +database/src/**/*.ts # Database scripts +``` + +### Workflows +```glob +form/src/workflow/**/*.ts # Workflow engine +form/src/workflow-definitions/**/*.json # Workflow definitions +``` + +### Test Exclusions +```glob +**/*.test.ts # TypeScript tests +**/*.test.tsx # React component tests +**/*.spec.ts # Spec files +``` + +--- + +## Content Patterns (Regex) + +### Prisma/Database +```regex +import.*[Pp]risma # Prisma imports +PrismaService # PrismaService usage +prisma\. # prisma.something +\.findMany\( # Prisma query methods +\.create\( +\.update\( +\.delete\( +``` + +### Controllers/Routes +```regex +export class.*Controller # Controller classes +router\. # Express router +app\.(get|post|put|delete|patch) # Express app routes +``` + +### Error Handling +```regex +try\s*\{ # Try blocks +catch\s*\( # Catch blocks +throw new # Throw statements +``` + +### React/Components +```regex +export.*React\.FC # React functional components +export default function.* # Default function exports +useState|useEffect # React hooks +``` + +--- + +**Usage Example:** + +```json +{ + "my-skill": { + "promptTriggers": { + "intentPatterns": [ + "(create|add|build).*?(component|UI|page)" + ] + }, + "fileTriggers": { + "pathPatterns": [ + "frontend/src/**/*.tsx" + ], + "contentPatterns": [ + "export.*React\\.FC", + "useState|useEffect" + ] + } + } +} +``` + +--- + +**Related Files:** +- [SKILL.md](SKILL.md) - Main skill guide +- [TRIGGER_TYPES.md](TRIGGER_TYPES.md) - Detailed trigger documentation +- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Complete schema \ No newline at end of file diff --git a/skills/skill-developer/SKILL.md b/skills/skill-developer/SKILL.md new file mode 100644 index 0000000..fdbb32a --- /dev/null +++ b/skills/skill-developer/SKILL.md @@ -0,0 +1,435 @@ +--- +name: skill-developer +description: Create and manage Claude Code skills following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns, file paths, content patterns), enforcement levels (block, suggest, warn), hook mechanisms (UserPromptSubmit, PreToolUse), session tracking, and the 500-line rule. +--- + +# Skill Developer Guide + +## Purpose + +Comprehensive guide for creating and managing skills in Claude Code with auto-activation system, following Anthropic's official best practices including the 500-line rule and progressive disclosure pattern. + +## When to Use This Skill + +Automatically activates when you mention: +- Creating or adding skills +- Modifying skill triggers or rules +- Understanding how skill activation works +- Debugging skill activation issues +- Working with skill-rules.json +- Hook system mechanics +- Claude Code best practices +- Progressive disclosure +- YAML frontmatter +- 500-line rule + +--- + +## System Overview + +### Two-Hook Architecture + +**1. UserPromptSubmit Hook** (Proactive Suggestions) +- **File**: `.claude/hooks/skill-activation-prompt.ts` +- **Trigger**: BEFORE Claude sees user's prompt +- **Purpose**: Suggest relevant skills based on keywords + intent patterns +- **Method**: Injects formatted reminder as context (stdout → Claude's input) +- **Use Cases**: Topic-based skills, implicit work detection + +**2. Stop Hook - Error Handling Reminder** (Gentle Reminders) +- **File**: `.claude/hooks/error-handling-reminder.ts` +- **Trigger**: AFTER Claude finishes responding +- **Purpose**: Gentle reminder to self-assess error handling in code written +- **Method**: Analyzes edited files for risky patterns, displays reminder if needed +- **Use Cases**: Error handling awareness without blocking friction + +**Philosophy Change (2025-10-27):** We moved away from blocking PreToolUse for Sentry/error handling. Instead, use gentle post-response reminders that don't block workflow but maintain code quality awareness. + +### Configuration File + +**Location**: `.claude/skills/skill-rules.json` + +Defines: +- All skills and their trigger conditions +- Enforcement levels (block, suggest, warn) +- File path patterns (glob) +- Content detection patterns (regex) +- Skip conditions (session tracking, file markers, env vars) + +--- + +## Skill Types + +### 1. Guardrail Skills + +**Purpose:** Enforce critical best practices that prevent errors + +**Characteristics:** +- Type: `"guardrail"` +- Enforcement: `"block"` +- Priority: `"critical"` or `"high"` +- Block file edits until skill used +- Prevent common mistakes (column names, critical errors) +- Session-aware (don't repeat nag in same session) + +**Examples:** +- `database-verification` - Verify table/column names before Prisma queries +- `frontend-dev-guidelines` - Enforce React/TypeScript patterns + +**When to Use:** +- Mistakes that cause runtime errors +- Data integrity concerns +- Critical compatibility issues + +### 2. Domain Skills + +**Purpose:** Provide comprehensive guidance for specific areas + +**Characteristics:** +- Type: `"domain"` +- Enforcement: `"suggest"` +- Priority: `"high"` or `"medium"` +- Advisory, not mandatory +- Topic or domain-specific +- Comprehensive documentation + +**Examples:** +- `backend-dev-guidelines` - Node.js/Express/TypeScript patterns +- `frontend-dev-guidelines` - React/TypeScript best practices +- `error-tracking` - Sentry integration guidance + +**When to Use:** +- Complex systems requiring deep knowledge +- Best practices documentation +- Architectural patterns +- How-to guides + +--- + +## Quick Start: Creating a New Skill + +### Step 1: Create Skill File + +**Location:** `.claude/skills/{skill-name}/SKILL.md` + +**Template:** +```markdown +--- +name: my-new-skill +description: Brief description including keywords that trigger this skill. Mention topics, file types, and use cases. Be explicit about trigger terms. +--- + +# My New Skill + +## Purpose +What this skill helps with + +## When to Use +Specific scenarios and conditions + +## Key Information +The actual guidance, documentation, patterns, examples +``` + +**Best Practices:** +- ✅ **Name**: Lowercase, hyphens, gerund form (verb + -ing) preferred +- ✅ **Description**: Include ALL trigger keywords/phrases (max 1024 chars) +- ✅ **Examples**: Real code examples +- ✅ **Structure**: Clear headings, lists, code blocks + +### Step 2: Content refine + +By leveraging [How skill works](./HOW-SKILL-WORKS.md) and skill contents loading orders, refine the skill structure to keep each file small but highly correlated to a specific field and reference in main `SKILL.md` to reduce context and token usage. + +**Best Practices:** +- ✅ **Content**: Each markdown file content should be less than 500 lines and very focused on a specific purpose or task. +- ✅ **Reference**: Extra reference markdown files should be reference back to main `SKILL.md` to avoid untented ignorance. +- ✅ **SKILL.md**: `SKILL.md` should be short and focus on high level and common information and have references to other field-specific references documentations. + + +### Step 3: Add to skill-rules.json + +See [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) for complete schema. + +**Basic Template:** +```json +{ + "my-new-skill": { + "type": "domain", + "enforcement": "suggest", + "priority": "medium", + "promptTriggers": { + "keywords": ["keyword1", "keyword2"], + "intentPatterns": ["(create|add).*?something"] + } + } +} +``` + +### Step 4: Test Triggers + +**Test UserPromptSubmit:** +```bash +echo '{"session_id":"test","prompt":"your test prompt"}' | \ + npx tsx .claude/hooks/skill-activation-prompt.ts +``` + +**Test PreToolUse:** +```bash +cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts +{"session_id":"test","tool_name":"Edit","tool_input":{"file_path":"test.ts"}} +EOF +``` + +### Step 5: Refine Patterns + +Based on testing: +- Add missing keywords +- Refine intent patterns to reduce false positives +- Adjust file path patterns +- Test content patterns against actual files + +### Step 6: Follow Anthropic Best Practices + +✅ Keep SKILL.md under 500 lines +✅ Use progressive disclosure with reference files +✅ Add table of contents to reference files > 100 lines +✅ Write detailed description with trigger keywords +✅ Test with 3+ real scenarios before documenting +✅ Iterate based on actual usage + +--- + +## Enforcement Levels + +### BLOCK (Critical Guardrails) + +- Physically prevents Edit/Write tool execution +- Exit code 2 from hook, stderr → Claude +- Claude sees message and must use skill to proceed +- **Use For**: Critical mistakes, data integrity, security issues + +**Example:** Database column name verification + +### SUGGEST (Recommended) + +- Reminder injected before Claude sees prompt +- Claude is aware of relevant skills +- Not enforced, just advisory +- **Use For**: Domain guidance, best practices, how-to guides + +**Example:** Frontend development guidelines + +### WARN (Optional) + +- Low priority suggestions +- Advisory only, minimal enforcement +- **Use For**: Nice-to-have suggestions, informational reminders + +**Rarely used** - most skills are either BLOCK or SUGGEST. + +--- + +## Skip Conditions & User Control + +### 1. Session Tracking + +**Purpose:** Don't nag repeatedly in same session + +**How it works:** +- First edit → Hook blocks, updates session state +- Second edit (same session) → Hook allows +- Different session → Blocks again + +**State File:** `.claude/hooks/state/skills-used-{session_id}.json` + +### 2. File Markers + +**Purpose:** Permanent skip for verified files + +**Marker:** `// @skip-validation` + +**Usage:** +```typescript +// @skip-validation +import { PrismaService } from './prisma'; +// This file has been manually verified +``` + +**NOTE:** Use sparingly - defeats the purpose if overused + +### 3. Environment Variables + +**Purpose:** Emergency disable, temporary override + +**Global disable:** +```bash +export SKIP_SKILL_GUARDRAILS=true # Disables ALL PreToolUse blocks +``` + +**Skill-specific:** +```bash +export SKIP_DB_VERIFICATION=true +export SKIP_ERROR_REMINDER=true +``` + +--- + +## Testing Checklist + +When creating a new skill, verify: + +- [ ] Skill file created in `.claude/skills/{name}/SKILL.md` +- [ ] Proper frontmatter with name and description +- [ ] Entry added to `skill-rules.json` +- [ ] Keywords tested with real prompts +- [ ] Intent patterns tested with variations +- [ ] File path patterns tested with actual files +- [ ] Content patterns tested against file contents +- [ ] Block message is clear and actionable (if guardrail) +- [ ] Skip conditions configured appropriately +- [ ] Priority level matches importance +- [ ] No false positives in testing +- [ ] No false negatives in testing +- [ ] Performance is acceptable (<100ms or <200ms) +- [ ] JSON syntax validated: `jq . skill-rules.json` +- [ ] **SKILL.md under 500 lines** ⭐ +- [ ] Reference files created if needed +- [ ] Table of contents added to files > 100 lines + +--- + +## Reference Files + +For detailed information on specific topics, see: + +### [TRIGGER_TYPES.md](TRIGGER_TYPES.md) +Complete guide to all trigger types: +- Keyword triggers (explicit topic matching) +- Intent patterns (implicit action detection) +- File path triggers (glob patterns) +- Content patterns (regex in files) +- Best practices and examples for each +- Common pitfalls and testing strategies + +### [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) +Complete skill-rules.json schema: +- Full TypeScript interface definitions +- Field-by-field explanations +- Complete guardrail skill example +- Complete domain skill example +- Validation guide and common errors + +### [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md) +Deep dive into hook internals: +- UserPromptSubmit flow (detailed) +- PreToolUse flow (detailed) +- Exit code behavior table (CRITICAL) +- Session state management +- Performance considerations + +### [TROUBLESHOOTING.md](TROUBLESHOOTING.md) +Comprehensive debugging guide: +- Skill not triggering (UserPromptSubmit) +- PreToolUse not blocking +- False positives (too many triggers) +- Hook not executing at all +- Performance issues + +### [PATTERNS_LIBRARY.md](PATTERNS_LIBRARY.md) +Ready-to-use pattern collection: +- Intent pattern library (regex) +- File path pattern library (glob) +- Content pattern library (regex) +- Organized by use case +- Copy-paste ready + +### [ADVANCED.md](ADVANCED.md) +Future enhancements and ideas: +- Dynamic rule updates +- Skill dependencies +- Conditional enforcement +- Skill analytics +- Skill versioning + +--- + +## Quick Reference Summary + +### Create New Skill (5 Steps) + +1. Create `.claude/skills/{name}/SKILL.md` with frontmatter +2. Add entry to `.claude/skills/skill-rules.json` +3. Test with `npx tsx` commands +4. Refine patterns based on testing +5. Keep SKILL.md under 500 lines + +### Trigger Types + +- **Keywords**: Explicit topic mentions +- **Intent**: Implicit action detection +- **File Paths**: Location-based activation +- **Content**: Technology-specific detection + +See [TRIGGER_TYPES.md](TRIGGER_TYPES.md) for complete details. + +### Enforcement + +- **BLOCK**: Exit code 2, critical only +- **SUGGEST**: Inject context, most common +- **WARN**: Advisory, rarely used + +### Skip Conditions + +- **Session tracking**: Automatic (prevents repeated nags) +- **File markers**: `// @skip-validation` (permanent skip) +- **Env vars**: `SKIP_SKILL_GUARDRAILS` (emergency disable) + +### Anthropic Best Practices + +✅ **500-line rule**: Keep SKILL.md under 500 lines +✅ **Progressive disclosure**: Use reference files for details +✅ **Table of contents**: Add to reference files > 100 lines +✅ **One level deep**: Don't nest references deeply +✅ **Rich descriptions**: Include all trigger keywords (max 1024 chars) +✅ **Test first**: Build 3+ evaluations before extensive documentation +✅ **Gerund naming**: Prefer verb + -ing (e.g., "processing-pdfs") + +### Troubleshoot + +Test hooks manually: +```bash +# UserPromptSubmit +echo '{"prompt":"test"}' | npx tsx .claude/hooks/skill-activation-prompt.ts + +# PreToolUse +cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts +{"tool_name":"Edit","tool_input":{"file_path":"test.ts"}} +EOF +``` + +See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for complete debugging guide. + +--- + +## Related Files + +**Configuration:** +- `.claude/skills/skill-rules.json` - Master configuration +- `.claude/hooks/state/` - Session tracking +- `.claude/settings.json` - Hook registration + +**Hooks:** +- `.claude/hooks/skill-activation-prompt.ts` - UserPromptSubmit +- `.claude/hooks/error-handling-reminder.ts` - Stop event (gentle reminders) + +**All Skills:** +- `.claude/skills/*/SKILL.md` - Skill content files + +--- + +**Skill Status**: COMPLETE - Restructured following Anthropic best practices ✅ +**Line Count**: < 500 (following 500-line rule) ✅ +**Progressive Disclosure**: Reference files for detailed information ✅ + +**Next**: Create more skills, refine patterns based on usage \ No newline at end of file diff --git a/skills/skill-developer/SKILL_RULES_REFERENCE.md b/skills/skill-developer/SKILL_RULES_REFERENCE.md new file mode 100644 index 0000000..d9f9db6 --- /dev/null +++ b/skills/skill-developer/SKILL_RULES_REFERENCE.md @@ -0,0 +1,315 @@ +# skill-rules.json - Complete Reference + +Complete schema and configuration reference for `.claude/skills/skill-rules.json`. + +## Table of Contents + +- [File Location](#file-location) +- [Complete TypeScript Schema](#complete-typescript-schema) +- [Field Guide](#field-guide) +- [Example: Guardrail Skill](#example-guardrail-skill) +- [Example: Domain Skill](#example-domain-skill) +- [Validation](#validation) + +--- + +## File Location + +**Path:** `.claude/skills/skill-rules.json` + +This JSON file defines all skills and their trigger conditions for the auto-activation system. + +--- + +## Complete TypeScript Schema + +```typescript +interface SkillRules { + version: string; + skills: Record; +} + +interface SkillRule { + type: 'guardrail' | 'domain'; + enforcement: 'block' | 'suggest' | 'warn'; + priority: 'critical' | 'high' | 'medium' | 'low'; + + promptTriggers?: { + keywords?: string[]; + intentPatterns?: string[]; // Regex strings + }; + + fileTriggers?: { + pathPatterns: string[]; // Glob patterns + pathExclusions?: string[]; // Glob patterns + contentPatterns?: string[]; // Regex strings + createOnly?: boolean; // Only trigger on file creation + }; + + blockMessage?: string; // For guardrails, {file_path} placeholder + + skipConditions?: { + sessionSkillUsed?: boolean; // Skip if used in session + fileMarkers?: string[]; // e.g., ["@skip-validation"] + envOverride?: string; // e.g., "SKIP_DB_VERIFICATION" + }; +} +``` + +--- + +## Field Guide + +### Top Level + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `version` | string | Yes | Schema version (currently "1.0") | +| `skills` | object | Yes | Map of skill name → SkillRule | + +### SkillRule Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `type` | string | Yes | "guardrail" (enforced) or "domain" (advisory) | +| `enforcement` | string | Yes | "block" (PreToolUse), "suggest" (UserPromptSubmit), or "warn" | +| `priority` | string | Yes | "critical", "high", "medium", or "low" | +| `promptTriggers` | object | Optional | Triggers for UserPromptSubmit hook | +| `fileTriggers` | object | Optional | Triggers for PreToolUse hook | +| `blockMessage` | string | Optional* | Required if enforcement="block". Use `{file_path}` placeholder | +| `skipConditions` | object | Optional | Escape hatches and session tracking | + +*Required for guardrails + +### promptTriggers Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `keywords` | string[] | Optional | Exact substring matches (case-insensitive) | +| `intentPatterns` | string[] | Optional | Regex patterns for intent detection | + +### fileTriggers Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `pathPatterns` | string[] | Yes* | Glob patterns for file paths | +| `pathExclusions` | string[] | Optional | Glob patterns to exclude (e.g., test files) | +| `contentPatterns` | string[] | Optional | Regex patterns to match file content | +| `createOnly` | boolean | Optional | Only trigger when creating new files | + +*Required if fileTriggers is present + +### skipConditions Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `sessionSkillUsed` | boolean | Optional | Skip if skill already used this session | +| `fileMarkers` | string[] | Optional | Skip if file contains comment marker | +| `envOverride` | string | Optional | Environment variable name to disable skill | + +--- + +## Example: Guardrail Skill + +Complete example of a blocking guardrail skill with all features: + +```json +{ + "database-verification": { + "type": "guardrail", + "enforcement": "block", + "priority": "critical", + + "promptTriggers": { + "keywords": [ + "prisma", + "database", + "table", + "column", + "schema", + "query", + "migration" + ], + "intentPatterns": [ + "(add|create|implement).*?(user|login|auth|tracking|feature)", + "(modify|update|change).*?(table|column|schema|field)", + "database.*?(change|update|modify|migration)" + ] + }, + + "fileTriggers": { + "pathPatterns": [ + "**/schema.prisma", + "**/migrations/**/*.sql", + "database/src/**/*.ts", + "form/src/**/*.ts", + "email/src/**/*.ts", + "users/src/**/*.ts", + "projects/src/**/*.ts", + "utilities/src/**/*.ts" + ], + "pathExclusions": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "contentPatterns": [ + "import.*[Pp]risma", + "PrismaService", + "prisma\\.", + "\\.findMany\\(", + "\\.findUnique\\(", + "\\.findFirst\\(", + "\\.create\\(", + "\\.createMany\\(", + "\\.update\\(", + "\\.updateMany\\(", + "\\.upsert\\(", + "\\.delete\\(", + "\\.deleteMany\\(" + ] + }, + + "blockMessage": "⚠️ BLOCKED - Database Operation Detected\n\n📋 REQUIRED ACTION:\n1. Use Skill tool: 'database-verification'\n2. Verify ALL table and column names against schema\n3. Check database structure with DESCRIBE commands\n4. Then retry this edit\n\nReason: Prevent column name errors in Prisma queries\nFile: {file_path}\n\n💡 TIP: Add '// @skip-validation' comment to skip future checks", + + "skipConditions": { + "sessionSkillUsed": true, + "fileMarkers": [ + "@skip-validation" + ], + "envOverride": "SKIP_DB_VERIFICATION" + } + } +} +``` + +### Key Points for Guardrails + +1. **type**: Must be "guardrail" +2. **enforcement**: Must be "block" +3. **priority**: Usually "critical" or "high" +4. **blockMessage**: Required, clear actionable steps +5. **skipConditions**: Session tracking prevents repeated nagging +6. **fileTriggers**: Usually has both path and content patterns +7. **contentPatterns**: Catch actual usage of technology + +--- + +## Example: Domain Skill + +Complete example of a suggestion-based domain skill: + +```json +{ + "project-catalog-developer": { + "type": "domain", + "enforcement": "suggest", + "priority": "high", + + "promptTriggers": { + "keywords": [ + "layout", + "layout system", + "grid", + "grid layout", + "toolbar", + "column", + "cell editor", + "cell renderer", + "submission", + "submissions", + "blog dashboard", + "datagrid", + "data grid", + "CustomToolbar", + "GridLayoutDialog", + "useGridLayout", + "auto-save", + "column order", + "column width", + "filter", + "sort" + ], + "intentPatterns": [ + "(how does|how do|explain|what is|describe).*?(layout|grid|toolbar|column|submission|catalog)", + "(add|create|modify|change).*?(toolbar|column|cell|editor|renderer)", + "blog dashboard.*?" + ] + }, + + "fileTriggers": { + "pathPatterns": [ + "frontend/src/features/submissions/**/*.tsx", + "frontend/src/features/submissions/**/*.ts" + ], + "pathExclusions": [ + "**/*.test.tsx", + "**/*.test.ts" + ] + } + } +} +``` + +### Key Points for Domain Skills + +1. **type**: Must be "domain" +2. **enforcement**: Usually "suggest" +3. **priority**: "high" or "medium" +4. **blockMessage**: Not needed (doesn't block) +5. **skipConditions**: Optional (less critical) +6. **promptTriggers**: Usually has extensive keywords +7. **fileTriggers**: May have only path patterns (content less important) + +--- + +## Validation + +### Check JSON Syntax + +```bash +cat .claude/skills/skill-rules.json | jq . +``` + +If valid, jq will pretty-print the JSON. If invalid, it will show the error. + +### Common JSON Errors + +**Trailing comma:** +```json +{ + "keywords": ["one", "two",] // ❌ Trailing comma +} +``` + +**Missing quotes:** +```json +{ + type: "guardrail" // ❌ Missing quotes on key +} +``` + +**Single quotes (invalid JSON):** +```json +{ + 'type': 'guardrail' // ❌ Must use double quotes +} +``` + +### Validation Checklist + +- [ ] JSON syntax valid (use `jq`) +- [ ] All skill names match SKILL.md filenames +- [ ] Guardrails have `blockMessage` +- [ ] Block messages use `{file_path}` placeholder +- [ ] Intent patterns are valid regex (test on regex101.com) +- [ ] File path patterns use correct glob syntax +- [ ] Content patterns escape special characters +- [ ] Priority matches enforcement level +- [ ] No duplicate skill names + +--- + +**Related Files:** +- [SKILL.md](SKILL.md) - Main skill guide +- [TRIGGER_TYPES.md](TRIGGER_TYPES.md) - Complete trigger documentation +- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Debugging configuration issues \ No newline at end of file diff --git a/skills/skill-developer/TRIGGER_TYPES.md b/skills/skill-developer/TRIGGER_TYPES.md new file mode 100644 index 0000000..4afdcda --- /dev/null +++ b/skills/skill-developer/TRIGGER_TYPES.md @@ -0,0 +1,305 @@ +# Trigger Types - Complete Guide + +Complete reference for configuring skill triggers in Claude Code's skill auto-activation system. + +## Table of Contents + +- [Keyword Triggers (Explicit)](#keyword-triggers-explicit) +- [Intent Pattern Triggers (Implicit)](#intent-pattern-triggers-implicit) +- [File Path Triggers](#file-path-triggers) +- [Content Pattern Triggers](#content-pattern-triggers) +- [Best Practices Summary](#best-practices-summary) + +--- + +## Keyword Triggers (Explicit) + +### How It Works + +Case-insensitive substring matching in user's prompt. + +### Use For + +Topic-based activation where user explicitly mentions the subject. + +### Configuration + +```json +"promptTriggers": { + "keywords": ["layout", "grid", "toolbar", "submission"] +} +``` + +### Example + +- User prompt: "how does the **layout** system work?" +- Matches: "layout" keyword +- Activates: `project-catalog-developer` + +### Best Practices + +- Use specific, unambiguous terms +- Include common variations ("layout", "layout system", "grid layout") +- Avoid overly generic words ("system", "work", "create") +- Test with real prompts + +--- + +## Intent Pattern Triggers (Implicit) + +### How It Works + +Regex pattern matching to detect user's intent even when they don't mention the topic explicitly. + +### Use For + +Action-based activation where user describes what they want to do rather than the specific topic. + +### Configuration + +```json +"promptTriggers": { + "intentPatterns": [ + "(create|add|implement).*?(feature|endpoint)", + "(how does|explain).*?(layout|workflow)" + ] +} +``` + +### Examples + +**Database Work:** +- User prompt: "add user tracking feature" +- Matches: `(add).*?(feature)` +- Activates: `database-verification`, `error-tracking` + +**Component Creation:** +- User prompt: "create a dashboard widget" +- Matches: `(create).*?(component)` (if component in pattern) +- Activates: `frontend-dev-guidelines` + +### Best Practices + +- Capture common action verbs: `(create|add|modify|build|implement)` +- Include domain-specific nouns: `(feature|endpoint|component|workflow)` +- Use non-greedy matching: `.*?` instead of `.*` +- Test patterns thoroughly with regex tester (https://regex101.com/) +- Don't make patterns too broad (causes false positives) +- Don't make patterns too specific (causes false negatives) + +### Common Pattern Examples + +```regex +# Database Work +(add|create|implement).*?(user|login|auth|feature) + +# Explanations +(how does|explain|what is|describe).*? + +# Frontend Work +(create|add|make|build).*?(component|UI|page|modal|dialog) + +# Error Handling +(fix|handle|catch|debug).*?(error|exception|bug) + +# Workflow Operations +(create|add|modify).*?(workflow|step|branch|condition) +``` + +--- + +## File Path Triggers + +### How It Works + +Glob pattern matching against the file path being edited. + +### Use For + +Domain/area-specific activation based on file location in the project. + +### Configuration + +```json +"fileTriggers": { + "pathPatterns": [ + "frontend/src/**/*.tsx", + "form/src/**/*.ts" + ], + "pathExclusions": [ + "**/*.test.ts", + "**/*.spec.ts" + ] +} +``` + +### Glob Pattern Syntax + +- `**` = Any number of directories (including zero) +- `*` = Any characters within a directory name +- Examples: + - `frontend/src/**/*.tsx` = All .tsx files in frontend/src and subdirs + - `**/schema.prisma` = schema.prisma anywhere in project + - `form/src/**/*.ts` = All .ts files in form/src subdirs + +### Example + +- File being edited: `frontend/src/components/Dashboard.tsx` +- Matches: `frontend/src/**/*.tsx` +- Activates: `frontend-dev-guidelines` + +### Best Practices + +- Be specific to avoid false positives +- Use exclusions for test files: `**/*.test.ts` +- Consider subdirectory structure +- Test patterns with actual file paths +- Use narrower patterns when possible: `form/src/services/**` not `form/**` + +### Common Path Patterns + +```glob +# Frontend +frontend/src/**/*.tsx # All React components +frontend/src/**/*.ts # All TypeScript files +frontend/src/components/** # Only components directory + +# Backend Services +form/src/**/*.ts # Form service +email/src/**/*.ts # Email service +users/src/**/*.ts # Users service + +# Database +**/schema.prisma # Prisma schema (anywhere) +**/migrations/**/*.sql # Migration files +database/src/**/*.ts # Database scripts + +# Workflows +form/src/workflow/**/*.ts # Workflow engine +form/src/workflow-definitions/**/*.json # Workflow definitions + +# Test Exclusions +**/*.test.ts # TypeScript tests +**/*.test.tsx # React component tests +**/*.spec.ts # Spec files +``` + +--- + +## Content Pattern Triggers + +### How It Works + +Regex pattern matching against the file's actual content (what's inside the file). + +### Use For + +Technology-specific activation based on what the code imports or uses (Prisma, controllers, specific libraries). + +### Configuration + +```json +"fileTriggers": { + "contentPatterns": [ + "import.*[Pp]risma", + "PrismaService", + "\\.findMany\\(", + "\\.create\\(" + ] +} +``` + +### Examples + +**Prisma Detection:** +- File contains: `import { PrismaService } from '@project/database'` +- Matches: `import.*[Pp]risma` +- Activates: `database-verification` + +**Controller Detection:** +- File contains: `export class UserController {` +- Matches: `export class.*Controller` +- Activates: `error-tracking` + +### Best Practices + +- Match imports: `import.*[Pp]risma` (case-insensitive with [Pp]) +- Escape special regex chars: `\\.findMany\\(` not `.findMany(` +- Patterns use case-insensitive flag +- Test against real file content +- Make patterns specific enough to avoid false matches + +### Common Content Patterns + +```regex +# Prisma/Database +import.*[Pp]risma # Prisma imports +PrismaService # PrismaService usage +prisma\. # prisma.something +\.findMany\( # Prisma query methods +\.create\( +\.update\( +\.delete\( + +# Controllers/Routes +export class.*Controller # Controller classes +router\. # Express router +app\.(get|post|put|delete|patch) # Express app routes + +# Error Handling +try\s*\{ # Try blocks +catch\s*\( # Catch blocks +throw new # Throw statements + +# React/Components +export.*React\.FC # React functional components +export default function.* # Default function exports +useState|useEffect # React hooks +``` + +--- + +## Best Practices Summary + +### DO: +✅ Use specific, unambiguous keywords +✅ Test all patterns with real examples +✅ Include common variations +✅ Use non-greedy regex: `.*?` +✅ Escape special characters in content patterns +✅ Add exclusions for test files +✅ Make file path patterns narrow and specific + +### DON'T: +❌ Use overly generic keywords ("system", "work") +❌ Make intent patterns too broad (false positives) +❌ Make patterns too specific (false negatives) +❌ Forget to test with regex tester (https://regex101.com/) +❌ Use greedy regex: `.*` instead of `.*?` +❌ Match too broadly in file paths + +### Testing Your Triggers + +**Test keyword/intent triggers:** +```bash +echo '{"session_id":"test","prompt":"your test prompt"}' | \ + npx tsx .claude/hooks/skill-activation-prompt.ts +``` + +**Test file path/content triggers:** +```bash +cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts +{ + "session_id": "test", + "tool_name": "Edit", + "tool_input": {"file_path": "/path/to/test/file.ts"} +} +EOF +``` + +--- + +**Related Files:** +- [SKILL.md](SKILL.md) - Main skill guide +- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Complete skill-rules.json schema +- [PATTERNS_LIBRARY.md](PATTERNS_LIBRARY.md) - Ready-to-use pattern library \ No newline at end of file diff --git a/skills/skill-developer/TROUBLESHOOTING.md b/skills/skill-developer/TROUBLESHOOTING.md new file mode 100644 index 0000000..8eef2f0 --- /dev/null +++ b/skills/skill-developer/TROUBLESHOOTING.md @@ -0,0 +1,514 @@ +# Troubleshooting - Skill Activation Issues + +Complete debugging guide for skill activation problems. + +## Table of Contents + +- [Skill Not Triggering](#skill-not-triggering) + - [UserPromptSubmit Not Suggesting](#userpromptsubmit-not-suggesting) + - [PreToolUse Not Blocking](#pretooluse-not-blocking) +- [False Positives](#false-positives) +- [Hook Not Executing](#hook-not-executing) +- [Performance Issues](#performance-issues) + +--- + +## Skill Not Triggering + +### UserPromptSubmit Not Suggesting + +**Symptoms:** Ask a question, but no skill suggestion appears in output. + +**Common Causes:** + +#### 1. Keywords Don't Match + +**Check:** +- Look at `promptTriggers.keywords` in skill-rules.json +- Are the keywords actually in your prompt? +- Remember: case-insensitive substring matching + +**Example:** +```json +"keywords": ["layout", "grid"] +``` +- "how does the layout work?" → ✅ Matches "layout" +- "how does the grid system work?" → ✅ Matches "grid" +- "how do layouts work?" → ✅ Matches "layout" +- "how does it work?" → ❌ No match + +**Fix:** Add more keyword variations to skill-rules.json + +#### 2. Intent Patterns Too Specific + +**Check:** +- Look at `promptTriggers.intentPatterns` +- Test regex at https://regex101.com/ +- May need broader patterns + +**Example:** +```json +"intentPatterns": [ + "(create|add).*?(database.*?table)" // Too specific +] +``` +- "create a database table" → ✅ Matches +- "add new table" → ❌ Doesn't match (missing "database") + +**Fix:** Broaden the pattern: +```json +"intentPatterns": [ + "(create|add).*?(table|database)" // Better +] +``` + +#### 3. Typo in Skill Name + +**Check:** +- Skill name in SKILL.md frontmatter +- Skill name in skill-rules.json +- Must match exactly + +**Example:** +```yaml +# SKILL.md +name: project-catalog-developer +``` +```json +// skill-rules.json +"project-catalogue-developer": { // ❌ Typo: catalogue vs catalog + ... +} +``` + +**Fix:** Make names match exactly + +#### 4. JSON Syntax Error + +**Check:** +```bash +cat .claude/skills/skill-rules.json | jq . +``` + +If invalid JSON, jq will show the error. + +**Common errors:** +- Trailing commas +- Missing quotes +- Single quotes instead of double +- Unescaped characters in strings + +**Fix:** Correct JSON syntax, validate with jq + +#### Debug Command + +Test the hook manually: + +```bash +echo '{"session_id":"debug","prompt":"your test prompt here"}' | \ + npx tsx .claude/hooks/skill-activation-prompt.ts +``` + +Expected: Your skill should appear in the output. + +--- + +### PreToolUse Not Blocking + +**Symptoms:** Edit a file that should trigger a guardrail, but no block occurs. + +**Common Causes:** + +#### 1. File Path Doesn't Match Patterns + +**Check:** +- File path being edited +- `fileTriggers.pathPatterns` in skill-rules.json +- Glob pattern syntax + +**Example:** +```json +"pathPatterns": [ + "frontend/src/**/*.tsx" +] +``` +- Editing: `frontend/src/components/Dashboard.tsx` → ✅ Matches +- Editing: `frontend/tests/Dashboard.test.tsx` → ✅ Matches (add exclusion!) +- Editing: `backend/src/app.ts` → ❌ Doesn't match + +**Fix:** Adjust glob patterns or add the missing path + +#### 2. Excluded by pathExclusions + +**Check:** +- Are you editing a test file? +- Look at `fileTriggers.pathExclusions` + +**Example:** +```json +"pathExclusions": [ + "**/*.test.ts", + "**/*.spec.ts" +] +``` +- Editing: `services/user.test.ts` → ❌ Excluded +- Editing: `services/user.ts` → ✅ Not excluded + +**Fix:** If test exclusion too broad, narrow it or remove + +#### 3. Content Pattern Not Found + +**Check:** +- Does the file actually contain the pattern? +- Look at `fileTriggers.contentPatterns` +- Is the regex correct? + +**Example:** +```json +"contentPatterns": [ + "import.*[Pp]risma" +] +``` +- File has: `import { PrismaService } from './prisma'` → ✅ Matches +- File has: `import { Database } from './db'` → ❌ Doesn't match + +**Debug:** +```bash +# Check if pattern exists in file +grep -i "prisma" path/to/file.ts +``` + +**Fix:** Adjust content patterns or add missing imports + +#### 4. Session Already Used Skill + +**Check session state:** +```bash +ls .claude/hooks/state/ +cat .claude/hooks/state/skills-used-{session-id}.json +``` + +**Example:** +```json +{ + "skills_used": ["database-verification"], + "files_verified": [] +} +``` + +If the skill is in `skills_used`, it won't block again in this session. + +**Fix:** Delete the state file to reset: +```bash +rm .claude/hooks/state/skills-used-{session-id}.json +``` + +#### 5. File Marker Present + +**Check file for skip marker:** +```bash +grep "@skip-validation" path/to/file.ts +``` + +If found, the file is permanently skipped. + +**Fix:** Remove the marker if verification is needed again + +#### 6. Environment Variable Override + +**Check:** +```bash +echo $SKIP_DB_VERIFICATION +echo $SKIP_SKILL_GUARDRAILS +``` + +If set, the skill is disabled. + +**Fix:** Unset the environment variable: +```bash +unset SKIP_DB_VERIFICATION +``` + +#### Debug Command + +Test the hook manually: + +```bash +cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts 2>&1 +{ + "session_id": "debug", + "tool_name": "Edit", + "tool_input": {"file_path": "/root/git/your-project/form/src/services/user.ts"} +} +EOF +echo "Exit code: $?" +``` + +Expected: +- Exit code 2 + stderr message if should block +- Exit code 0 + no output if should allow + +--- + +## False Positives + +**Symptoms:** Skill triggers when it shouldn't. + +**Common Causes & Solutions:** + +### 1. Keywords Too Generic + +**Problem:** +```json +"keywords": ["user", "system", "create"] // Too broad +``` +- Triggers on: "user manual", "file system", "create directory" + +**Solution:** Make keywords more specific +```json +"keywords": [ + "user authentication", + "user tracking", + "create feature" +] +``` + +### 2. Intent Patterns Too Broad + +**Problem:** +```json +"intentPatterns": [ + "(create)" // Matches everything with "create" +] +``` +- Triggers on: "create file", "create folder", "create account" + +**Solution:** Add context to patterns +```json +"intentPatterns": [ + "(create|add).*?(database|table|feature)" // More specific +] +``` + +**Advanced:** Use negative lookaheads to exclude +```regex +(create)(?!.*test).*?(feature) // Don't match if "test" appears +``` + +### 3. File Paths Too Generic + +**Problem:** +```json +"pathPatterns": [ + "form/**" // Matches everything in form/ +] +``` +- Triggers on: test files, config files, everything + +**Solution:** Use narrower patterns +```json +"pathPatterns": [ + "form/src/services/**/*.ts", // Only service files + "form/src/controllers/**/*.ts" +] +``` + +### 4. Content Patterns Catching Unrelated Code + +**Problem:** +```json +"contentPatterns": [ + "Prisma" // Matches in comments, strings, etc. +] +``` +- Triggers on: `// Don't use Prisma here` +- Triggers on: `const note = "Prisma is cool"` + +**Solution:** Make patterns more specific +```json +"contentPatterns": [ + "import.*[Pp]risma", // Only imports + "PrismaService\\.", // Only actual usage + "prisma\\.(findMany|create)" // Specific methods +] +``` + +### 5. Adjust Enforcement Level + +**Last resort:** If false positives are frequent: + +```json +{ + "enforcement": "block" // Change to "suggest" +} +``` + +This makes it advisory instead of blocking. + +--- + +## Hook Not Executing + +**Symptoms:** Hook doesn't run at all - no suggestion, no block. + +**Common Causes:** + +### 1. Hook Not Registered + +**Check `.claude/settings.json`:** +```bash +cat .claude/settings.json | jq '.hooks.UserPromptSubmit' +cat .claude/settings.json | jq '.hooks.PreToolUse' +``` + +Expected: Hook entries present + +**Fix:** Add missing hook registration: +```json +{ + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh" + } + ] + } + ] + } +} +``` + +### 2. Bash Wrapper Not Executable + +**Check:** +```bash +ls -l .claude/hooks/*.sh +``` + +Expected: `-rwxr-xr-x` (executable) + +**Fix:** +```bash +chmod +x .claude/hooks/*.sh +``` + +### 3. Incorrect Shebang + +**Check:** +```bash +head -1 .claude/hooks/skill-activation-prompt.sh +``` + +Expected: `#!/bin/bash` + +**Fix:** Add correct shebang to first line + +### 4. npx/tsx Not Available + +**Check:** +```bash +npx tsx --version +``` + +Expected: Version number + +**Fix:** Install dependencies: +```bash +cd .claude/hooks +npm install +``` + +### 5. TypeScript Compilation Error + +**Check:** +```bash +cd .claude/hooks +npx tsc --noEmit skill-activation-prompt.ts +``` + +Expected: No output (no errors) + +**Fix:** Correct TypeScript syntax errors + +--- + +## Performance Issues + +**Symptoms:** Hooks are slow, noticeable delay before prompt/edit. + +**Common Causes:** + +### 1. Too Many Patterns + +**Check:** +- Count patterns in skill-rules.json +- Each pattern = regex compilation + matching + +**Solution:** Reduce patterns +- Combine similar patterns +- Remove redundant patterns +- Use more specific patterns (faster matching) + +### 2. Complex Regex + +**Problem:** +```regex +(create|add|modify|update|implement|build).*?(feature|endpoint|route|service|controller|component|UI|page) +``` +- Long alternations = slow + +**Solution:** Simplify +```regex +(create|add).*?(feature|endpoint) // Fewer alternatives +``` + +### 3. Too Many Files Checked + +**Problem:** +```json +"pathPatterns": [ + "**/*.ts" // Checks ALL TypeScript files +] +``` + +**Solution:** Be more specific +```json +"pathPatterns": [ + "form/src/services/**/*.ts", // Only specific directory + "form/src/controllers/**/*.ts" +] +``` + +### 4. Large Files + +Content pattern matching reads entire file - slow for large files. + +**Solution:** +- Only use content patterns when necessary +- Consider file size limits (future enhancement) + +### Measure Performance + +```bash +# UserPromptSubmit +time echo '{"prompt":"test"}' | npx tsx .claude/hooks/skill-activation-prompt.ts + +# PreToolUse +time cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts +{"tool_name":"Edit","tool_input":{"file_path":"test.ts"}} +EOF +``` + +**Target metrics:** +- UserPromptSubmit: < 100ms +- PreToolUse: < 200ms + +--- + +**Related Files:** +- [SKILL.md](SKILL.md) - Main skill guide +- [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md) - How hooks work +- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Configuration reference \ No newline at end of file diff --git a/skills/skill-optimizer/REFERENCE.md b/skills/skill-optimizer/REFERENCE.md new file mode 100644 index 0000000..bbb6cf8 --- /dev/null +++ b/skills/skill-optimizer/REFERENCE.md @@ -0,0 +1,1484 @@ +# Skill Optimizer Reference + +Detailed optimization patterns, anti-patterns, migration workflows, and advanced techniques. + +## Table of Contents + +- [Detailed Optimization Patterns](#detailed-optimization-patterns) + - [Pattern 1: Extract API Documentation](#pattern-1-extract-api-documentation) + - [Pattern 2: Extract Pattern Libraries](#pattern-2-extract-pattern-libraries) + - [Pattern 3: Extract Troubleshooting](#pattern-3-extract-troubleshooting) + - [Pattern 4: Convert Code to Scripts](#pattern-4-convert-code-to-scripts) +- [Common Anti-Patterns](#common-anti-patterns) +- [Complete Migration Workflow](#complete-migration-workflow) +- [Advanced Optimization Techniques](#advanced-optimization-techniques) +- [Measurement & Validation](#measurement--validation) + +--- + +## Detailed Optimization Patterns + +### Pattern 1: Extract API Documentation + +**Before (in SKILL.md - consuming tokens):** +```markdown +## API Reference + +### Function: processData() +**Signature**: processData(input: DataInput): Promise +**Parameters**: +- input.field1: string - Description of field1 with detailed explanation of valid values, constraints, and validation rules +- input.field2: number - Description of field2 with range specifications, default values, and edge cases to consider +- input.field3: boolean - Description of field3 with behavior when true vs false and implications +- input.field4: object - Nested object with multiple sub-fields + - field4.subfield1: string - Description... + - field4.subfield2: array - Description... +**Returns**: Promise +- output.result: string - Detailed description of result format, possible values, and interpretation +- output.metadata: object - Metadata object containing: + - metadata.timestamp: number - Unix timestamp + - metadata.version: string - API version used + - metadata.requestId: string - Unique request identifier +**Throws**: +- ValidationError - When input validation fails +- ProcessingError - When data processing encounters issues +- NetworkError - When network operations fail + +**Example**: +\`\`\`typescript +import { processData } from './processor'; + +async function example() { + try { + const input = { + field1: 'example value', + field2: 42, + field3: true, + field4: { + subfield1: 'nested value', + subfield2: ['item1', 'item2'] + } + }; + + const result = await processData(input); + + console.log('Result:', result.result); + console.log('Processed at:', new Date(result.metadata.timestamp)); + console.log('Request ID:', result.metadata.requestId); + + return result; + } catch (error) { + if (error instanceof ValidationError) { + console.error('Invalid input:', error.message); + } else if (error instanceof ProcessingError) { + console.error('Processing failed:', error.message); + } else { + console.error('Unexpected error:', error); + } + throw error; + } +} +\`\`\` + +**Error Handling**: +- Always wrap calls in try-catch blocks +- Check for specific error types to handle appropriately +- Log errors with context for debugging +- Consider retry logic for transient failures +- Implement circuit breakers for external dependencies + +**Performance Considerations**: +- Batch multiple calls when possible +- Cache results when appropriate +- Monitor processing time +- Set appropriate timeouts +``` + +**After (in SKILL.md - minimal reference):** +```markdown +## API Overview + +Key functions: `processData()`, `validateInput()`, `formatOutput()` + +**Quick usage:** +\`\`\`typescript +const result = await processData({ field1: 'value' }); +\`\`\` + +**Complete API reference**: [REFERENCE.md](REFERENCE.md#api-reference-complete) +``` + +**Savings**: ~80 lines → 10 lines (87% reduction, ~1,400 tokens saved) + +**When to apply:** +- API documentation >30 lines +- Multiple function signatures +- Detailed parameter descriptions +- Extensive error handling documentation +- Performance considerations and examples + +--- + +### Pattern 2: Extract Pattern Libraries + +**Before (in SKILL.md - consuming tokens):** +```markdown +## Common Patterns + +### Pattern 1: Authentication Flow +\`\`\`typescript +import { authenticate, refreshToken, logout } from './auth'; + +async function authenticationFlow() { + // Initial authentication + const { accessToken, refreshToken: refresh } = await authenticate({ + username: process.env.USERNAME, + password: process.env.PASSWORD + }); + + // Store tokens securely + secureStorage.set('access_token', accessToken); + secureStorage.set('refresh_token', refresh); + + // Set up token refresh + const refreshInterval = setInterval(async () => { + try { + const newTokens = await refreshToken(refresh); + secureStorage.set('access_token', newTokens.accessToken); + } catch (error) { + clearInterval(refreshInterval); + await logout(); + } + }, 15 * 60 * 1000); // Refresh every 15 minutes + + return { accessToken, cleanup: () => clearInterval(refreshInterval) }; +} +\`\`\` + +**Explanation**: This pattern handles initial authentication, secure token storage, and automatic token refresh with cleanup. + +### Pattern 2: Error Handling with Retry Logic +\`\`\`typescript +async function withRetry( + fn: () => Promise, + maxRetries: number = 3, + delayMs: number = 1000 +): Promise { + let lastError: Error; + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + return await fn(); + } catch (error) { + lastError = error as Error; + + // Don't retry on certain errors + if (error instanceof ValidationError) { + throw error; + } + + if (attempt < maxRetries) { + // Exponential backoff + const delay = delayMs * Math.pow(2, attempt); + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + } + + throw new Error(`Failed after ${maxRetries} retries: ${lastError.message}`); +} + +// Usage +const result = await withRetry(() => fetchData(), 3, 500); +\`\`\` + +**Explanation**: Implements exponential backoff retry logic with configurable attempts and delays. + +### Pattern 3: Data Validation +\`\`\`typescript +import { z } from 'zod'; + +// Define schema +const UserSchema = z.object({ + id: z.string().uuid(), + email: z.string().email(), + age: z.number().int().min(0).max(120), + roles: z.array(z.enum(['admin', 'user', 'guest'])), + metadata: z.record(z.unknown()).optional() +}); + +type User = z.infer; + +// Validation function +function validateUser(data: unknown): User { + try { + return UserSchema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + const issues = error.issues.map(i => `${i.path.join('.')}: ${i.message}`); + throw new ValidationError(`Invalid user data: ${issues.join(', ')}`); + } + throw error; + } +} + +// Usage +const user = validateUser(rawData); +\`\`\` + +**Explanation**: Uses Zod for runtime type validation with clear error messages. + +### Pattern 4: Database Transaction Pattern +[25 lines of code...] + +### Pattern 5: Event-Driven Architecture +[30 lines of code...] + +### Pattern 6: Caching Strategy +[20 lines of code...] + +[10 more patterns, 200+ total lines] +``` + +**After (in SKILL.md - minimal reference):** +```markdown +## Common Patterns + +Quick reference to implementation patterns: +- Authentication Flow - Token-based auth with refresh +- Error Handling - Retry logic with exponential backoff +- Data Validation - Schema-based validation +- Database Transactions - ACID-compliant patterns +- Event-Driven - Event sourcing and CQRS +- Caching - Multi-level cache strategies + +**Complete pattern library**: [REFERENCE.md](REFERENCE.md#pattern-library-complete) + +**Quick example:** +\`\`\`typescript +// Retry pattern +const result = await withRetry(() => fetchData()); +\`\`\` +``` + +**Savings**: 200+ lines → 18 lines (91% reduction, ~3,640 tokens saved) + +**When to apply:** +- Multiple code patterns >15 lines each +- Pattern collection >100 lines total +- Detailed explanations for each pattern +- More than 5 distinct patterns + +--- + +### Pattern 3: Extract Troubleshooting + +**Before (in SKILL.md - consuming tokens):** +```markdown +## Troubleshooting + +### Issue 1: Connection Timeout + +**Symptoms**: +- Requests hanging for extended periods +- Socket timeout errors after 30-60 seconds +- Intermittent connection failures +- Error messages: "ETIMEDOUT", "ECONNREFUSED" + +**Causes**: +1. Network connectivity issues +2. Firewall blocking outbound connections +3. Server overload or not responding +4. DNS resolution failures +5. Incorrect host/port configuration + +**Solutions**: +1. Verify network connectivity: + \`\`\`bash + ping api.example.com + telnet api.example.com 443 + \`\`\` + +2. Check firewall rules: + \`\`\`bash + # Linux + sudo iptables -L -n + # macOS + sudo pfctl -sr + \`\`\` + +3. Test DNS resolution: + \`\`\`bash + nslookup api.example.com + dig api.example.com + \`\`\` + +4. Verify configuration: + \`\`\`typescript + console.log('Host:', process.env.API_HOST); + console.log('Port:', process.env.API_PORT); + \`\`\` + +5. Increase timeout values: + \`\`\`typescript + const client = new ApiClient({ + timeout: 60000, // 60 seconds + retries: 3 + }); + \`\`\` + +6. Check server status: + \`\`\`bash + curl -I https://api.example.com/health + \`\`\` + +**Prevention**: +- Implement connection pooling +- Set appropriate timeout values +- Use health checks before critical operations +- Monitor network latency +- Configure retry logic with exponential backoff + +### Issue 2: Authentication Failure + +**Symptoms**: +- 401 Unauthorized responses +- "Invalid credentials" errors +- Token expired messages +- Access denied errors + +**Causes**: +1. Incorrect credentials +2. Expired authentication tokens +3. Invalid API keys +4. Clock skew issues +5. Token refresh failures + +**Solutions**: +[Similar detailed breakdown...] + +### Issue 3: Rate Limiting + +**Symptoms**: +- 429 Too Many Requests responses +- Throttling errors +- Requests being rejected + +**Causes**: +[Detailed causes...] + +**Solutions**: +[Detailed solutions...] + +[20 more issues with similar detail level, 300+ total lines] +``` + +**After (in SKILL.md - minimal reference):** +```markdown +## Troubleshooting + +Common issues and quick fixes: +1. Connection timeout → Check network and increase timeout values +2. Authentication failure → Verify credentials and token expiration +3. Rate limiting → Implement backoff and request queuing +4. Data validation errors → Check input schema +5. Performance issues → Enable caching and optimize queries + +**Complete troubleshooting guide**: [REFERENCE.md](REFERENCE.md#troubleshooting-complete) + +**Quick diagnostics:** +\`\`\`bash +# Check connectivity +curl -I https://api.example.com/health +\`\`\` +``` + +**Savings**: 300+ lines → 18 lines (94% reduction, ~5,400 tokens saved) + +**When to apply:** +- More than 5 troubleshooting scenarios +- Detailed diagnostic steps >10 lines each +- Multiple solutions per issue +- Extensive prevention guidelines + +--- + +### Pattern 4: Convert Code to Scripts + +**Before (in SKILL.md - consuming tokens):** +```markdown +## Configuration Validation + +Use this script to validate your complete configuration: + +\`\`\`bash +#!/bin/bash +set -e + +echo "=========================================" +echo " Configuration Validation Script" +echo "=========================================" +echo "" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Check database connection +echo -n "Checking database connection... " +if psql "$DATABASE_URL" -c "SELECT 1" > /dev/null 2>&1; then + echo -e "${GREEN}✓${NC}" +else + echo -e "${RED}✗${NC}" + echo "Database connection failed. Check DATABASE_URL environment variable." + exit 1 +fi + +# Check Redis connection +echo -n "Checking Redis connection... " +if redis-cli -u "$REDIS_URL" ping > /dev/null 2>&1; then + echo -e "${GREEN}✓${NC}" +else + echo -e "${RED}✗${NC}" + echo "Redis connection failed. Check REDIS_URL environment variable." + exit 1 +fi + +# Validate API key +echo -n "Validating API key... " +if [ -z "$API_KEY" ]; then + echo -e "${RED}✗${NC}" + echo "API_KEY environment variable not set." + exit 1 +else + echo -e "${GREEN}✓${NC}" +fi + +# Check file permissions +echo -n "Checking file permissions... " +if [ -r "./config.json" ] && [ -w "./logs" ]; then + echo -e "${GREEN}✓${NC}" +else + echo -e "${RED}✗${NC}" + echo "Permission issues detected." + exit 1 +fi + +# Validate port availability +echo -n "Checking port availability... " +if lsof -Pi :3000 -sTCP:LISTEN -t >/dev/null 2>&1; then + echo -e "${YELLOW}⚠${NC} Port 3000 already in use" +else + echo -e "${GREEN}✓${NC}" +fi + +echo "" +echo -e "${GREEN}All checks passed!${NC}" +\`\`\` + +Run this before starting your application to ensure everything is configured correctly. +``` + +**After (in SKILL.md - script reference only):** +```markdown +## Configuration Validation + +Run validation script to check your setup: +\`\`\`bash +bash .claude/skills/skill-name/scripts/validate-config.sh +\`\`\` + +Checks database, Redis, API keys, permissions, and port availability. +``` + +**Create file**: `scripts/validate-config.sh` (with the actual script content) + +```bash +chmod +x .claude/skills/skill-name/scripts/validate-config.sh +``` + +**Savings**: ~55 lines → 7 lines (87% reduction, ~1,100 tokens saved) + +**Bonus**: Script code never enters context - only output is visible when Claude runs it + +**When to apply:** +- Reusable scripts >20 lines +- Diagnostic or validation tools +- Configuration generators +- Data transformation utilities +- Setup or installation helpers + +--- + +## Common Anti-Patterns + +### ❌ Anti-Pattern 1: Monolithic Skills + +**Problem**: Single SKILL.md file containing everything (1000-2000+ lines) + +**Example structure:** +``` +skill-name/ +└── SKILL.md (1500 lines) + ├── Purpose (10 lines) + ├── Quick Start (50 lines) + ├── API Documentation (300 lines) + ├── Examples (400 lines) + ├── Pattern Library (350 lines) + ├── Troubleshooting (250 lines) + └── Advanced Topics (140 lines) +``` + +**Impact**: +- **Token consumption**: ~22,500-30,000 tokens loaded every time skill triggers +- **Navigation difficulty**: Hard to find specific information in large file +- **Maintenance burden**: Changes require editing massive file +- **Violates 500-line rule**: 3-4x over the limit +- **Poor user experience**: Overwhelming amount of information at once + +**Solution**: +``` +skill-name/ +├── SKILL.md (350 lines) +│ ├── Purpose (10 lines) +│ ├── Quick Start (50 lines) +│ ├── Common Patterns Summary (30 lines) +│ ├── Troubleshooting Summary (20 lines) +│ └── References to detailed docs (10 lines) +├── REFERENCE.md (600 lines - API docs) +├── EXAMPLES.md (400 lines - code examples) +├── PATTERNS.md (350 lines - pattern library) +└── TROUBLESHOOTING.md (250 lines - debug guide) +``` + +**Result**: Only 350 lines (~5,250 tokens) loaded initially, detailed docs loaded on-demand + +--- + +### ❌ Anti-Pattern 2: Incomplete References + +**Problem**: Reference files exist but aren't linked from main SKILL.md + +**Example SKILL.md:** +```markdown +## API Reference + +Here's how to use the API... + +[No mention of REFERENCE.md which contains complete API docs] +``` + +**File structure:** +``` +skill-name/ +├── SKILL.md (mentions "API Reference" but no link) +├── REFERENCE.md (contains full API docs - orphaned!) +└── EXAMPLES.md (contains examples - never discovered!) +``` + +**Impact**: +- **Wasted effort**: Reference files created but never used +- **Poor discoverability**: Users don't know detailed docs exist +- **Inconsistent info**: Main file may contradict reference files +- **Claude can't access**: Without explicit file paths, Claude won't read them + +**Solution**: +```markdown +## API Reference + +Quick reference for common operations. + +**For complete API documentation**: [REFERENCE.md](REFERENCE.md#api-complete) +**For usage examples**: [EXAMPLES.md](EXAMPLES.md#api-usage) + +### Quick Example +\`\`\`typescript +// Basic usage +const result = await api.call(); +\`\`\` +``` + +**Best practice**: Every reference file should be linked at least once from SKILL.md + +--- + +### ❌ Anti-Pattern 3: Nested References + +**Problem**: References pointing to other references (>1 level deep) + +**Example**: +``` +SKILL.md + → "See REFERENCE.md for details" + → REFERENCE.md: "See ADVANCED.md for edge cases" + → ADVANCED.md: "See DEEP_DIVE.md for implementation" + → DEEP_DIVE.md: [actual content] +``` + +**Impact**: +- **Cognitive load**: Users must navigate multiple files to find information +- **Navigation complexity**: Easy to get lost in reference chain +- **Time waste**: Multiple file reads to reach actual content +- **Frustration**: "Just tell me the answer!" + +**Solution**: Flat hierarchy (max 1 level) +``` +SKILL.md + → REFERENCE.md [complete reference] + → EXAMPLES.md [all examples] + → PATTERNS.md [all patterns] + → TROUBLESHOOTING.md [all debugging info] +``` + +**Each reference file should be self-contained and comprehensive** + +--- + +### ❌ Anti-Pattern 4: Sparse Frontmatter + +**Problem**: Minimal YAML description missing critical trigger keywords + +**Bad example:** +```yaml +--- +name: api-helper +description: Helps with API development. +--- +``` + +**Impact**: +- **Poor discoverability**: Skill won't trigger when relevant +- **Missed opportunities**: Users manually invoke instead of auto-suggest +- **Wasted potential**: Skill could help but isn't activated +- **Low utilization**: Skill sits unused despite being valuable + +**Good example:** +```yaml +--- +name: api-development +description: API development guidance for REST, GraphQL, and gRPC APIs including Express, Fastify, Node.js, TypeScript, authentication, authorization, JWT, OAuth, rate limiting, error handling, validation, middleware, routing, database integration, testing, documentation, OpenAPI, Swagger, and deployment. Use when building APIs, creating endpoints, handling requests, implementing auth, validating input, error handling, or working with HTTP, REST, GraphQL, or gRPC. +--- +``` + +**What to include in description**: +- Technologies (Express, GraphQL, JWT, etc.) +- Use cases (building APIs, authentication, validation) +- Actions (creating, implementing, handling, validating) +- Concepts (REST, middleware, error handling, routing) +- Related terms (HTTP, endpoints, authorization, OpenAPI) + +**Aim for 500-1000 characters** to maximize trigger coverage while staying under 1024 char limit + +--- + +### ❌ Anti-Pattern 5: Code as Documentation + +**Problem**: Large executable scripts embedded in markdown instead of separate files + +**Bad example in SKILL.md:** +```markdown +## Database Migration Script + +\`\`\`bash +#!/bin/bash +# Complete migration script (100+ lines) + +set -e + +echo "Starting migration..." + +# [100+ lines of migration logic] +# [Connection setup] +# [Transaction handling] +# [Rollback logic] +# [Validation] +# [Cleanup] + +echo "Migration complete" +\`\`\` + +Copy this script to your project and run it. +``` + +**Impact**: +- **Token waste**: 100+ lines of script code in context every time +- **Not reusable**: Can't execute directly, must copy-paste +- **Hard to maintain**: Updates require editing SKILL.md +- **Version control issues**: Script and documentation coupled + +**Good example in SKILL.md:** +```markdown +## Database Migration + +Run migration script: +\`\`\`bash +bash .claude/skills/skill-name/scripts/migrate-db.sh +\`\`\` + +Script handles: +- Connection validation +- Transaction management +- Automatic rollback on failure +- Post-migration verification +``` + +**Script in `scripts/migrate-db.sh`:** +- Executable directly by Claude via bash command +- Code never enters context +- Only script output visible +- Easy to maintain and version + +--- + +## Complete Migration Workflow + +### Phase 1: Discovery and Analysis + +**Step 1.1: Identify candidate skills** +```bash +# Find all skills +find .claude/skills -name "SKILL.md" -type f + +# Check sizes +for skill in .claude/skills/*/SKILL.md; do + lines=$(wc -l < "$skill") + name=$(basename $(dirname "$skill")) + echo "$lines lines - $name" +done | sort -rn + +# Focus on skills >500 lines +``` + +**Step 1.2: Analyze content structure** +```bash +# Extract section headers +grep "^##" .claude/skills/skill-name/SKILL.md + +# Count lines per section +awk '/^## Section1/,/^## Section2/{count++} END{print count}' SKILL.md +``` + +**Step 1.3: Identify extraction candidates** + +Sections to extract if >30 lines: +- API documentation +- Code examples (multiple >20 lines) +- Pattern libraries +- Troubleshooting guides +- Reference tables +- Configuration details +- Advanced topics + +**Step 1.4: Create optimization plan** + +Document: +- Current line count +- Target line count (<500) +- Sections to extract +- New reference files needed +- Scripts to create +- Estimated token savings + +--- + +### Phase 2: Structure Planning + +**Step 2.1: Design file hierarchy** + +``` +skill-name/ +├── SKILL.md # <500 lines - core workflow +├── REFERENCE.md # API docs, detailed reference +├── EXAMPLES.md # Code examples +├── PATTERNS.md # Pattern library (if needed) +├── TROUBLESHOOTING.md # Debug guide (if needed) +└── scripts/ # Executable utilities + ├── validate.sh + └── setup.sh +``` + +**Step 2.2: Plan content distribution** + +**SKILL.md should contain:** +- Purpose and scope (1-2 paragraphs) +- When to use (bulleted list) +- Quick start workflow (5-10 steps) +- Common patterns (summaries only) +- Troubleshooting (summaries only) +- Cross-references to detailed docs + +**Reference files should contain:** +- Complete API documentation +- Detailed examples with explanations +- Comprehensive pattern library +- Full troubleshooting procedures +- Advanced topics and edge cases + +**Scripts should contain:** +- Reusable validation/setup logic +- Configuration generators +- Diagnostic tools +- Data transformation utilities + +--- + +### Phase 3: Implementation + +**Step 3.1: Create reference file structure** +```bash +cd .claude/skills/skill-name + +# Create reference files +touch REFERENCE.md EXAMPLES.md +mkdir -p scripts + +# Add table of contents templates +cat > REFERENCE.md <<'EOF' +# [Skill Name] Reference + +Complete reference documentation. + +## Table of Contents +- [Section 1](#section-1) +- [Section 2](#section-2) + +## Section 1 +... +EOF +``` + +**Step 3.2: Extract content systematically** + +Process for each section: +1. **Copy section to reference file** (preserve formatting) +2. **Replace in SKILL.md with summary + link** +3. **Verify link path is correct** +4. **Remove detailed content from SKILL.md** +5. **Test navigation works** + +**Example extraction:** +```bash +# Before: Section in SKILL.md (80 lines) +## API Reference +[80 lines of detailed API docs] + +# After: Summary in SKILL.md (5 lines) +## API Reference + +Quick reference: `processData()`, `validateInput()`, `formatOutput()` + +**Complete API docs**: [REFERENCE.md](REFERENCE.md#api-reference) + +# Content moved to REFERENCE.md +## API Reference + +[Original 80 lines of detailed API docs] +``` + +**Step 3.3: Convert scripts** +```bash +# Extract embedded scripts +# Find scripts in SKILL.md +grep -A 50 '```bash' SKILL.md + +# Create script file +cat > scripts/validate.sh <<'EOF' +#!/bin/bash +[script content] +EOF + +# Make executable +chmod +x scripts/validate.sh + +# Replace in SKILL.md +\`\`\`bash +bash .claude/skills/skill-name/scripts/validate.sh +\`\`\` +``` + +**Step 3.4: Update cross-references** + +Ensure all references use relative paths: +```markdown +✅ Correct: [Details](REFERENCE.md#section) +✅ Correct: [Examples](EXAMPLES.md#example-1) +✅ Correct: Run `scripts/validate.sh` + +❌ Wrong: [Details](../skill-name/REFERENCE.md#section) +❌ Wrong: [Examples](/full/path/EXAMPLES.md) +``` + +--- + +### Phase 4: Optimization + +**Step 4.1: Trim remaining content** + +After extractions, optimize what remains: +- Remove verbose explanations → concise bullets +- Combine related bullet points +- Use tables instead of paragraphs +- Remove redundant examples +- Condense repeated concepts + +**Before:** +```markdown +The API provides several methods for data processing. The first method is processData which takes input and returns processed output. This method is very useful when you need to transform data. The second method is validateInput which checks if the input meets requirements. This is important to run before processing. +``` + +**After:** +```markdown +API methods: +- `processData()` - Transform input data +- `validateInput()` - Check input requirements +``` + +**Step 4.2: Optimize frontmatter** + +Extract all key terms from content: +```bash +# Extract common terms +grep -o '\*\*[^*]*\*\*' SKILL.md | sort | uniq + +# Build description with: +# - Technology names +# - Action verbs +# - Use cases +# - File types +# - Related concepts +``` + +**Step 4.3: Add navigation aids** + +If SKILL.md is still >300 lines, add table of contents: +```markdown +# Skill Name + +## Table of Contents +- [Quick Start](#quick-start) +- [Common Patterns](#common-patterns) +- [Troubleshooting](#troubleshooting) +- [Reference Docs](#reference-docs) + +## Quick Start +... +``` + +Add to reference files >100 lines: +```markdown +# Reference Documentation + +## Table of Contents +[...] +``` + +--- + +### Phase 5: Validation + +**Step 5.1: Verify line counts** +```bash +# Check SKILL.md is under 500 +wc -l .claude/skills/skill-name/SKILL.md + +# Calculate total lines +find .claude/skills/skill-name -name "*.md" -exec wc -l {} \; | awk '{sum+=$1} END{print sum, "total lines"}' + +# Before/after comparison +echo "Before: $BEFORE_LINES lines" +echo "After: $AFTER_LINES lines" +echo "Saved: $((BEFORE_LINES - AFTER_LINES)) lines (~$((( BEFORE_LINES - AFTER_LINES) * 20)) tokens)" +``` + +**Step 5.2: Test links** +```bash +# Extract all markdown links +grep -o '\[.*\](.*\.md#.*)' SKILL.md + +# Verify files exist +for file in REFERENCE.md EXAMPLES.md PATTERNS.md; do + [ -f "$file" ] && echo "✓ $file" || echo "✗ $file missing" +done + +# Verify anchors exist +# (manually check that #section-name anchors match headers) +``` + +**Step 5.3: Validate content completeness** + +Checklist: +- [ ] All original information preserved (in SKILL.md or reference files) +- [ ] No broken links +- [ ] All reference files linked from SKILL.md +- [ ] Scripts are executable and work correctly +- [ ] Table of contents accurate for files >100 lines +- [ ] YAML frontmatter includes all trigger keywords + +**Step 5.4: Test with real usage** + +Manually test skill: +1. Trigger skill with typical prompt +2. Verify SKILL.md provides sufficient quick reference +3. Navigate to reference file for details +4. Verify reference file has complete information +5. Test scripts execute correctly + +--- + +### Phase 6: Documentation + +**Step 6.1: Update skill documentation** + +If migration involved significant restructuring, document changes: +```markdown +# Skill Name + +## Recent Updates +- **2025-11-09**: Optimized for progressive disclosure + - Reduced SKILL.md from 850 to 420 lines + - Created REFERENCE.md for API docs + - Created EXAMPLES.md for code examples + - Extracted scripts to scripts/ directory + - Estimated token savings: ~8,600 tokens +``` + +**Step 6.2: Share patterns learned** + +Document any unique optimization techniques discovered: +- Novel extraction patterns +- Effective summary techniques +- Script conversion strategies +- Navigation improvements + +--- + +## Advanced Optimization Techniques + +### Technique 1: Conditional Content Loading + +**Concept**: Structure content so advanced/optional sections are only loaded when explicitly needed + +**Implementation pattern:** +```markdown +## Feature Overview + +Basic usage covers 80% of use cases. + +**Quick start:** +\`\`\`typescript +basicUsage(); +\`\`\` + +**Advanced scenarios** (for edge cases and complex requirements): +- Multi-tenant configuration → [ADVANCED.md](ADVANCED.md#multi-tenant) +- Custom authentication → [ADVANCED.md](ADVANCED.md#custom-auth) +- Performance tuning → [ADVANCED.md](ADVANCED.md#performance) +- Enterprise deployment → [ADVANCED.md](ADVANCED.md#enterprise) +``` + +**Benefits**: +- Most users never load advanced content +- Advanced users can easily find detailed docs +- Clear separation of concerns +- Reduces cognitive load for beginners + +**When to use**: +- Content has distinct basic vs advanced levels +- Advanced content is >30% of total +- Most users won't need advanced features + +--- + +### Technique 2: Layered Examples + +**Concept**: Progressive complexity in examples + +**Implementation:** +```markdown +## Examples + +### Level 1: Minimal Example (most common) +\`\`\`typescript +const result = await api.call({ id: '123' }); +\`\`\` + +### Level 2: Production Example +Production-ready with error handling: [EXAMPLES.md](EXAMPLES.md#production) + +### Level 3: Enterprise Example +Complete implementation with auth, retry, logging: [EXAMPLES.md](EXAMPLES.md#enterprise) +``` + +**In EXAMPLES.md:** +```markdown +## Production Example + +\`\`\`typescript +async function callApi(id: string) { + try { + return await api.call({ id }); + } catch (error) { + logger.error('API call failed', { id, error }); + throw error; + } +} +\`\`\` + +## Enterprise Example + +\`\`\`typescript +// [50+ lines of enterprise-grade implementation] +\`\`\` +``` + +**Benefits**: +- Beginners see simple examples immediately +- Advanced users can access complex examples +- Gradual learning curve +- SKILL.md stays minimal + +--- + +### Technique 3: Executable Documentation + +**Concept**: Scripts that both execute and document behavior + +**Example script**: `scripts/check-setup.sh` +```bash +#!/bin/bash +# Diagnostic script that explains what it's checking + +echo "=== Setup Validation ===" +echo "" + +echo "[1/5] Checking Node.js version..." +node_version=$(node -v) +echo " Found: $node_version" +if [[ "$node_version" =~ v1[89]|v2[0-9] ]]; then + echo " ✓ Node.js version compatible" +else + echo " ✗ Node.js 18+ required" + exit 1 +fi + +echo "" +echo "[2/5] Checking package manager..." +if command -v pnpm >/dev/null 2>&1; then + echo " ✓ pnpm installed" +else + echo " ✗ pnpm not found - install with: npm install -g pnpm" + exit 1 +fi + +echo "" +echo "[3/5] Checking environment variables..." +required_vars=("DATABASE_URL" "REDIS_URL" "API_KEY") +for var in "${required_vars[@]}"; do + if [ -z "${!var}" ]; then + echo " ✗ $var not set" + missing=true + else + echo " ✓ $var configured" + fi +done +[[ -z "$missing" ]] || exit 1 + +echo "" +echo "[4/5] Checking database connection..." +if psql "$DATABASE_URL" -c "SELECT 1" >/dev/null 2>&1; then + echo " ✓ Database accessible" +else + echo " ✗ Cannot connect to database" + exit 1 +fi + +echo "" +echo "[5/5] Checking file permissions..." +if [ -w "./logs" ]; then + echo " ✓ Write permissions OK" +else + echo " ✗ Cannot write to ./logs directory" + exit 1 +fi + +echo "" +echo "✅ All checks passed! Ready to start." +``` + +**In SKILL.md:** +```markdown +## Setup Validation + +Verify your environment is configured correctly: +\`\`\`bash +bash .claude/skills/skill-name/scripts/check-setup.sh +\`\`\` + +Checks Node.js version, package manager, environment variables, database connection, and permissions. +``` + +**Benefits**: +- Self-documenting (output explains what's being checked) +- Executable (Claude can run it directly) +- Zero token cost (code doesn't enter context) +- Reusable (can run multiple times) +- Maintainable (script separate from docs) + +--- + +### Technique 4: Tabular Compression + +**Concept**: Use tables to compress information + +**Before (verbose list - 20 lines):** +```markdown +## Configuration Options + +### Option: timeout +- Type: number +- Default: 30000 +- Description: Request timeout in milliseconds +- Valid range: 1000-300000 + +### Option: retries +- Type: number +- Default: 3 +- Description: Number of retry attempts +- Valid range: 0-10 + +[More options...] +``` + +**After (table - 8 lines):** +```markdown +## Configuration Options + +| Option | Type | Default | Range | Description | +|--------|------|---------|-------|-------------| +| timeout | number | 30000 | 1000-300000 | Request timeout (ms) | +| retries | number | 3 | 0-10 | Retry attempts | +| maxSize | number | 1048576 | 1024-10485760 | Max payload size (bytes) | +| cache | boolean | true | - | Enable response caching | +``` + +**Savings**: 20 lines → 8 lines (60% reduction) + +**When to use**: +- Structured data (configurations, options, parameters) +- Repetitive format across multiple items +- Quick reference needed +- Space constraints + +--- + +### Technique 5: Smart Chunking + +**Concept**: Group related small sections instead of individual extraction + +**Before (scattered references):** +```markdown +## Topic A +Brief content... +**Details**: [REF.md](REF.md#topic-a) + +## Topic B +Brief content... +**Details**: [REF.md](REF.md#topic-b) + +## Topic C +Brief content... +**Details**: [REF.md](REF.md#topic-c) +``` + +**After (grouped):** +```markdown +## Related Topics + +Quick overview: +- **Topic A**: Brief summary +- **Topic B**: Brief summary +- **Topic C**: Brief summary + +**Complete documentation**: [REFERENCE.md](REFERENCE.md#related-topics) +``` + +**Benefits**: +- Fewer cross-references to manage +- Better narrative flow +- Easier navigation +- Less repetitive linking + +--- + +## Measurement & Validation + +### Token Estimation Methods + +**Method 1: Line-based estimation** +```bash +# Count lines +lines=$(wc -l < SKILL.md) + +# Estimate tokens (conservative: 20 tokens/line, aggressive: 15 tokens/line) +tokens_conservative=$((lines * 20)) +tokens_aggressive=$((lines * 15)) + +echo "Estimated tokens: $tokens_aggressive - $tokens_conservative" +``` + +**Method 2: Character-based estimation** +```bash +# Count characters +chars=$(wc -m < SKILL.md) + +# Estimate tokens (rough: 1 token ≈ 4 characters) +tokens=$((chars / 4)) + +echo "Estimated tokens: $tokens" +``` + +**Method 3: Word-based estimation** +```bash +# Count words +words=$(wc -w < SKILL.md) + +# Estimate tokens (rough: 1 token ≈ 0.75 words) +tokens=$((words * 4 / 3)) + +echo "Estimated tokens: $tokens" +``` + +**Reality check**: Actual token count varies by content type +- Code: ~25-30 tokens/line +- Markdown text: ~15-20 tokens/line +- Tables: ~10-15 tokens/line +- Comments: ~12-18 tokens/line + +--- + +### Before/After Analysis + +**Comprehensive comparison script:** +```bash +#!/bin/bash +# optimization-metrics.sh + +SKILL_NAME=$1 + +echo "Optimization Metrics for $SKILL_NAME" +echo "======================================" + +# Before metrics (from git history or backup) +BEFORE_LINES=$(git show HEAD~1:.claude/skills/$SKILL_NAME/SKILL.md | wc -l) +BEFORE_CHARS=$(git show HEAD~1:.claude/skills/$SKILL_NAME/SKILL.md | wc -m) + +# After metrics (current) +AFTER_LINES=$(wc -l < .claude/skills/$SKILL_NAME/SKILL.md) +AFTER_CHARS=$(wc -m < .claude/skills/$SKILL_NAME/SKILL.md) + +# Calculate savings +LINE_SAVINGS=$((BEFORE_LINES - AFTER_LINES)) +CHAR_SAVINGS=$((BEFORE_CHARS - AFTER_CHARS)) +TOKEN_SAVINGS=$((LINE_SAVINGS * 20)) # Conservative estimate + +# Calculate percentages +LINE_PCT=$((LINE_SAVINGS * 100 / BEFORE_LINES)) +CHAR_PCT=$((CHAR_SAVINGS * 100 / BEFORE_CHARS)) + +echo "" +echo "Lines: $BEFORE_LINES → $AFTER_LINES (saved $LINE_SAVINGS, ${LINE_PCT}%)" +echo "Chars: $BEFORE_CHARS → $AFTER_CHARS (saved $CHAR_SAVINGS, ${CHAR_PCT}%)" +echo "Tokens: ~$((BEFORE_LINES * 20)) → ~$((AFTER_LINES * 20)) (saved ~$TOKEN_SAVINGS)" +echo "" + +# New reference files +echo "New reference files:" +for file in .claude/skills/$SKILL_NAME/*.md; do + if [ "$file" != ".claude/skills/$SKILL_NAME/SKILL.md" ]; then + lines=$(wc -l < "$file") + name=$(basename "$file") + echo " - $name: $lines lines" + fi +done + +echo "" +echo "Total documentation lines: $(find .claude/skills/$SKILL_NAME -name "*.md" -exec wc -l {} + | tail -1 | awk '{print $1}')" +``` + +**Usage:** +```bash +bash optimization-metrics.sh skill-name +``` + +--- + +### Quality Validation Checklist + +After optimization, verify quality hasn't degraded: + +**Content Integrity:** +- [ ] All original information preserved +- [ ] No loss of critical details +- [ ] Examples still complete and correct +- [ ] No broken workflows or procedures + +**Navigation:** +- [ ] All cross-references work +- [ ] Reference files are discoverable +- [ ] Table of contents accurate +- [ ] Clear path from overview to details + +**Usability:** +- [ ] SKILL.md provides sufficient quick reference +- [ ] Common use cases covered in main file +- [ ] Advanced topics clearly marked +- [ ] Scripts executable and functional + +**Technical:** +- [ ] SKILL.md < 500 lines +- [ ] YAML description < 1024 chars +- [ ] All trigger keywords included +- [ ] File hierarchy is flat (max 1 level) +- [ ] Scripts have proper permissions (chmod +x) + +**Performance:** +- [ ] Reduced token consumption +- [ ] Faster initial load +- [ ] Reference files load only when needed +- [ ] No duplicate content + +--- + +### Success Metrics + +**Quantitative:** +- Line count reduction: Target >50% +- Token savings: Target >5,000 tokens +- File count: 3-5 organized files better than 1 monolithic +- Load time: Faster initial context load + +**Qualitative:** +- User feedback: Easier to navigate? +- Claude feedback: More relevant? +- Maintenance: Easier to update? +- Discoverability: Better trigger rate? + +**Track over time:** +```bash +# Create metrics log +cat >> .claude/skills/optimization-log.txt < 500 lines? +- [ ] Detailed API docs in main file? +- [ ] Extensive examples in main file? +- [ ] Long reference tables or schemas? +- [ ] Code snippets that could be scripts? +- [ ] Multiple distinct topics/sections? + +### 2. Apply 500-Line Rule + +**If SKILL.md > 500 lines:** + +✅ **Keep in main file:** +- Purpose and when to use +- Quick start / common workflows +- Critical best practices +- Brief examples (5-10 lines) +- Cross-references to detailed files + +❌ **Move to reference files:** +- Comprehensive API documentation +- Extensive code examples (>20 lines) +- Detailed troubleshooting guides +- Pattern libraries +- Schema definitions +- Long reference tables + +### 3. Structure Reference Files + +**Create organized reference hierarchy:** +``` +skill-name/ +├── SKILL.md # <500 lines, workflows & quick ref +├── REFERENCE.md # Comprehensive documentation +├── EXAMPLES.md # Detailed code examples +├── PATTERNS.md # Pattern library +├── TROUBLESHOOTING.md # Debug guide +└── scripts/ # Executable utilities + └── helper.sh +``` + +**Add table of contents to files >100 lines** + +### 4. Optimize YAML Frontmatter + +**Description optimization (max 1024 chars):** + +✅ **Include:** +- All trigger keywords and phrases +- Use cases and scenarios +- File types and technologies +- Common action verbs +- Related concepts + +❌ **Avoid:** +- Generic descriptions +- Missing key terms +- Overly verbose explanations + +**Example:** +```yaml +--- +name: database-development +description: Database development guidance for PostgreSQL including schema design, migrations, RLS policies, indexing strategies, privacy-preserving patterns, query optimization, and Prisma ORM. Use when working with tables, columns, indexes, migrations, RLS, Row-Level Security, database schema, SQL queries, Prisma schema, database optimization, privacy architecture, or PostgreSQL best practices. +--- +``` + +### 5. Implement Progressive Disclosure + +**Pattern:** +```markdown +## Topic Overview + +Brief explanation (2-3 sentences). + +**Key Points:** +- Important consideration 1 +- Important consideration 2 + +**For detailed information**: [REFERENCE.md](REFERENCE.md#topic-details) + +**Quick Example:** +\`\`\`typescript +// Minimal working example (5-10 lines) +\`\`\` + +**For more examples**: [EXAMPLES.md](EXAMPLES.md#topic-examples) +``` + +--- + +## Optimization Patterns Summary + +### Pattern 1: Extract API Documentation + +**Strategy**: Move detailed API docs to REFERENCE.md + +**Before**: 80+ lines of API documentation in SKILL.md +**After**: 10-line summary with link to complete docs +**Savings**: ~70 lines (~1,400 tokens) + +**For complete pattern details**: [REFERENCE.md](REFERENCE.md#pattern-1-extract-api-documentation) + +### Pattern 2: Extract Pattern Libraries + +**Strategy**: Move code patterns to PATTERNS.md + +**Before**: 200+ lines of pattern code in SKILL.md +**After**: 18-line summary with quick example +**Savings**: ~182 lines (~3,640 tokens) + +**For complete pattern details**: [REFERENCE.md](REFERENCE.md#pattern-2-extract-pattern-libraries) + +### Pattern 3: Extract Troubleshooting + +**Strategy**: Move debug guides to TROUBLESHOOTING.md + +**Before**: 300+ lines of troubleshooting in SKILL.md +**After**: 18-line summary with quick diagnostics +**Savings**: ~282 lines (~5,640 tokens) + +**For complete pattern details**: [REFERENCE.md](REFERENCE.md#pattern-3-extract-troubleshooting) + +### Pattern 4: Convert Code to Scripts + +**Strategy**: Move executable code to scripts/ directory + +**Before**: 55+ lines of bash script in SKILL.md +**After**: 7-line reference to executable script +**Savings**: ~48 lines (~960 tokens) + script code never enters context + +**For complete pattern details**: [REFERENCE.md](REFERENCE.md#pattern-4-convert-code-to-scripts) + +--- + +## Common Anti-Patterns + +Avoid these common mistakes when creating or optimizing skills: + +❌ **Anti-Pattern 1: Monolithic Skills** +- Single SKILL.md with 1000+ lines +- Solution: Split into main + reference files + +❌ **Anti-Pattern 2: Incomplete References** +- Reference files exist but not linked +- Solution: Link all reference files from SKILL.md + +❌ **Anti-Pattern 3: Nested References** +- References pointing to other references (>1 level) +- Solution: Keep hierarchy flat (max 1 level) + +❌ **Anti-Pattern 4: Sparse Frontmatter** +- Minimal YAML description missing keywords +- Solution: Rich description with all triggers + +❌ **Anti-Pattern 5: Code as Documentation** +- 100+ line scripts embedded in markdown +- Solution: Move to scripts/ directory + +**For detailed anti-patterns and solutions**: [REFERENCE.md](REFERENCE.md#common-anti-patterns) + +--- + +## Migration Workflow + +### Quick Migration Steps + +**Phase 1: Discovery** +```bash +# Check skill size +wc -l .claude/skills/skill-name/SKILL.md + +# Identify sections to extract +grep "^##" .claude/skills/skill-name/SKILL.md +``` + +**Phase 2: Planning** +- Design file hierarchy (SKILL.md + reference files) +- Plan content distribution +- Identify scripts to extract + +**Phase 3: Implementation** +```bash +# Create reference files +touch REFERENCE.md EXAMPLES.md +mkdir -p scripts + +# Extract content systematically +# 1. Copy section to reference file +# 2. Replace in SKILL.md with summary + link +# 3. Verify link works +# 4. Remove detailed content from SKILL.md +``` + +**Phase 4: Optimization** +- Trim remaining content +- Optimize frontmatter with trigger keywords +- Add navigation aids (table of contents) + +**Phase 5: Validation** +```bash +# Verify under 500 lines +wc -l .claude/skills/skill-name/SKILL.md + +# Test links work +grep -o '\[.*\](.*\.md#.*)' SKILL.md +``` + +**For complete migration workflow**: [REFERENCE.md](REFERENCE.md#complete-migration-workflow) + +--- + +## Advanced Techniques + +Quick reference to advanced optimization strategies: + +**Technique 1: Conditional Content Loading** +- Structure content so advanced sections load only when needed +- Benefits: Most users don't load advanced content + +**Technique 2: Layered Examples** +- Progressive complexity: minimal → production → enterprise +- Benefits: Beginners see simple examples, advanced users access complex ones + +**Technique 3: Executable Documentation** +- Scripts that both execute and document +- Benefits: Zero token cost, self-documenting output + +**Technique 4: Tabular Compression** +- Use tables to compress structured data +- Benefits: 60%+ space reduction for configurations/options + +**Technique 5: Smart Chunking** +- Group related small sections instead of individual extraction +- Benefits: Better narrative flow, fewer cross-references + +**For detailed advanced techniques**: [REFERENCE.md](REFERENCE.md#advanced-optimization-techniques) + +--- + +## Optimization Checklist + +When optimizing a skill, verify: + +### Content Structure +- [ ] SKILL.md is under 500 lines +- [ ] Main file contains quick reference only +- [ ] Detailed docs moved to reference files +- [ ] Reference files have table of contents (if >100 lines) +- [ ] Cross-references use relative links +- [ ] No deeply nested references (max 1 level) + +### YAML Frontmatter +- [ ] Description includes all trigger keywords +- [ ] Description is under 1024 characters +- [ ] Description covers use cases and scenarios +- [ ] Description mentions file types/technologies +- [ ] Name follows kebab-case convention + +### Progressive Disclosure +- [ ] Overview → Details pattern used +- [ ] Quick examples in main file (5-10 lines) +- [ ] Extensive examples in EXAMPLES.md +- [ ] Brief summaries with references to details +- [ ] Common workflows highlighted in main file + +### File Organization +- [ ] Reference files named clearly +- [ ] Scripts in scripts/ directory +- [ ] Scripts are executable (chmod +x) +- [ ] No redundant content across files +- [ ] Each file has single, clear purpose + +### Token Efficiency +- [ ] Eliminated verbose explanations +- [ ] Removed duplicate information +- [ ] Used bullet points vs paragraphs +- [ ] Moved large code blocks to reference files +- [ ] Converted reusable code to scripts + +--- + +## Measurement & Validation + +### Token Estimation + +**Quick estimate:** +```bash +lines=$(wc -l < SKILL.md) +tokens=$((lines * 20)) # Conservative: 20 tokens/line +echo "Estimated tokens: ~$tokens" +``` + +**Target**: Keep SKILL.md under 10,000 tokens (~500 lines) + +### Before/After Comparison + +```bash +# Calculate savings +BEFORE=850 # lines before optimization +AFTER=420 # lines after optimization +SAVINGS=$((BEFORE - AFTER)) +TOKEN_SAVINGS=$((SAVINGS * 20)) + +echo "Reduced by $SAVINGS lines" +echo "Estimated token savings: ~$TOKEN_SAVINGS tokens" +``` + +### Quality Checks + +- [ ] All original information preserved +- [ ] Links work correctly +- [ ] Main file comprehensive for common cases +- [ ] Reference files well-organized +- [ ] Navigation intuitive + +**For detailed measurement methods**: [REFERENCE.md](REFERENCE.md#measurement--validation) + +--- + +## Best Practices Summary + +✅ **DO:** +- Keep SKILL.md minimum but use other reference files to keep the full and detailed knowledge base +- Use progressive disclosure (overview → details) +- Include all trigger keywords in description +- Create clear cross-references to detailed docs +- Add table of contents to reference files >100 lines +- Convert reusable code to scripts +- Test optimization with real usage + +❌ **DON'T:** +- Exceed 500 lines in SKILL.md +- Nest references more than 1 level deep +- Include API docs in main file +- Embed long code examples in main file +- Create reference files without linking them +- Use sparse YAML descriptions +- Optimize without preserving critical info + +--- + +## Quick Reference + +**File size limits:** +- SKILL.md: <500 lines (strict) +- Reference files: No limit (loaded on-demand) +- YAML description: 1024 chars max + +**Optimization priority:** +1. Apply 500-line rule to SKILL.md +2. Extract API docs to REFERENCE.md +3. Move examples to EXAMPLES.md or PATTERNS.md +4. Convert scripts to scripts/ directory +5. Enrich YAML frontmatter description + +**Common extractions:** +- API documentation → REFERENCE.md +- Code examples → EXAMPLES.md +- Troubleshooting → TROUBLESHOOTING.md +- Pattern library → PATTERNS.md +- Scripts → scripts/ directory + +**Typical token savings:** +- API extraction: ~1,400 tokens +- Pattern library: ~3,640 tokens +- Troubleshooting: ~5,640 tokens +- Scripts: ~960 tokens + no code in context + +**For comprehensive optimization patterns and detailed workflows**: [REFERENCE.md](REFERENCE.md) + +--- + +## Real-World Example + +**Before optimization:** +``` +skill-example/ +└── SKILL.md (850 lines, ~17,000 tokens) +``` + +**After optimization:** +``` +skill-example/ +├── SKILL.md (420 lines, ~8,400 tokens) +├── REFERENCE.md (350 lines, loaded on-demand) +├── EXAMPLES.md (180 lines, loaded on-demand) +└── scripts/ + ├── validate.sh (code never enters context) + └── setup.sh (code never enters context) +``` + +**Result**: 50% token reduction on initial load, comprehensive docs still available on-demand + +--- + +**Next Steps**: +1. Audit existing skills: `wc -l .claude/skills/*/SKILL.md` +2. Identify candidates for optimization (>500 lines) +3. Apply optimization workflow +4. Measure token savings +5. Validate with real usage + +**For detailed guidance**: See [REFERENCE.md](REFERENCE.md) for complete optimization patterns, anti-patterns, migration workflows, and advanced techniques.