Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:27:59 +08:00
commit 96f735d5dd
21 changed files with 6447 additions and 0 deletions

View File

@@ -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"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# next-project-starter
Starter bundle for Next.js projects with commands, hooks, scripts, and MCP integration

View File

@@ -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.

51
commands/dev-docs.md Normal file
View File

@@ -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.

18
hooks/hooks.json Normal file
View File

@@ -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"
}
]
}
]
}
}

113
plugin.lock.json Normal file
View File

@@ -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": []
}
}

View File

@@ -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
<section className="py-6 px-6">
<div className="max-w-5xl mx-auto">
<SearchBar value={searchQuery} onChange={setSearchQuery} />
</div>
</section>
// SearchBar component (from tools page)
export default function SearchBar({ value, onChange }: SearchBarProps) {
return (
<div className="relative max-w-2xl mx-auto"> {/* ← PROBLEM: Centered with narrow container */}
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" />
<Input value={value} onChange={onChange} className="pl-10" />
</div>
);
}
```
**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 (
<div className={`relative ${fullWidth ? 'w-full' : 'max-w-2xl mx-auto'}`}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" />
<Input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
className="w-full pl-10 pr-4 h-11 bg-card"
/>
</div>
);
}
// Blog page usage
<section className="py-6 px-6">
<div className="max-w-5xl mx-auto">
<SearchBar
value={searchQuery}
onChange={setSearchQuery}
placeholder="Search posts by title, author, or tags..."
fullWidth={true} // Matches blog's left-aligned pattern
/>
</div>
</section>
// Tools page usage (unchanged, backward compatible)
<section className="py-6 px-6">
<div className="max-w-5xl mx-auto">
<SearchBar
value={searchQuery}
onChange={setSearchQuery}
// No fullWidth prop = defaults to centered
/>
</div>
</section>
```
**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 (
<div className={`border rounded-lg p-4 hover:border-foreground/20 transition-all
${isHorizontal ? 'flex items-center gap-4' : 'flex flex-col'}`}
>
{/* Content adapts to layout */}
</div>
);
}
```
---
## 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
<div className="max-w-3xl mx-auto">
<h1 className="text-3xl md:text-4xl font-semibold tracking-tight mb-4">
About Us
</h1>
<p className="text-base leading-relaxed mb-6">
Our story begins...
</p>
<h2 className="text-xl md:text-2xl font-semibold mb-3">
Our Mission
</h2>
<p className="text-base leading-relaxed">
We believe in...
</p>
</div>
```
### ❌ Incorrect Implementation
```tsx
// DON'T: Different sizes, weights, tracking
<div className="max-w-3xl mx-auto">
<h1 className="text-5xl font-bold tracking-wide mb-6"> {/* ← Too large, too bold */}
About Us
</h1>
<p className="text-lg leading-normal mb-8"> {/* ← Larger than existing pages */}
Our story begins...
</p>
<h2 className="text-2xl font-bold mb-4"> {/* ← font-bold instead of font-semibold */}
Our Mission
</h2>
</div>
```
---
## 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 (
<main>
{/* Hero: Centered, narrow */}
<section className="py-12 px-6">
<div className="max-w-3xl mx-auto text-center">
<h1 className="text-3xl md:text-4xl font-semibold">
Simple, Transparent Pricing
</h1>
</div>
</section>
{/* Plans: Wide, centered grid */}
<section className="py-8 px-6">
<div className="max-w-5xl mx-auto">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* Pricing cards */}
</div>
</div>
</section>
</main>
);
}
```
---
## 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
<main className="bg-white">
{/* Purple gradient hero */}
<section className="bg-gradient-to-r from-purple-600 to-blue-500 text-white py-20">
<div className="max-w-4xl mx-auto text-center">
<h1 className="text-5xl font-bold mb-6">
Revolutionize Your Workflow
</h1>
<p className="text-xl mb-8">
The all-in-one platform for modern teams
</p>
<button className="bg-white text-purple-600 px-8 py-3 rounded-lg">
Get Started
</button>
</div>
</section>
{/* Three feature cards */}
<section className="py-20">
<div className="max-w-6xl mx-auto grid grid-cols-3 gap-8">
<Card icon="⚡" title="Fast" description="Lightning fast performance" />
<Card icon="🔒" title="Secure" description="Bank-level security" />
<Card icon="📈" title="Scalable" description="Grows with you" />
</div>
</section>
{/* Testimonials */}
{/* CTA */}
</main>
```
**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
<main className="bg-black text-green-400 font-mono">
{/* Terminal-style hero */}
<section className="min-h-screen p-6 flex items-center">
<div className="max-w-4xl">
<pre className="text-sm mb-4">$ initialize_revolution.sh</pre>
<h1 className="text-6xl font-bold mb-4 glitch-effect">
SYSTEM<br/>
OVERRIDE
</h1>
<p className="text-lg text-green-300 mb-8 max-w-xl">
For developers who don't compromise. Raw power. Zero abstraction.
</p>
<div className="flex gap-4">
<button className="border-2 border-green-400 px-6 py-2 hover:bg-green-400 hover:text-black transition-colors">
&gt; ssh access@deploy
</button>
</div>
</div>
</section>
{/* Asymmetric feature layout */}
<section className="p-6">
<div className="max-w-7xl mx-auto grid grid-cols-12 gap-4">
<div className="col-span-8 border-2 border-green-400 p-8">
{/* Main feature */}
</div>
<div className="col-span-4 border-2 border-green-400 p-4">
{/* Stats ticker */}
</div>
</div>
</section>
</main>
```
**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

View File

@@ -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.

View File

@@ -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

View File

@@ -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) => (
<Card
key={item.id}
style={{
animationDelay: `${index * 0.1}s`
}}
/>
))}
```
### 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
<button>
<Icon />
<span className="sr-only">Open menu</span>
</button>
```
### 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
<head>
<!-- Critical CSS inline -->
<style>
/* Above-the-fold styles */
body { margin: 0; font-family: system-ui; }
.header { /* ... */ }
</style>
<!-- Defer non-critical CSS -->
<link rel="preload" href="/styles/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/styles/main.css"></noscript>
</head>
```
### Image Optimization
**Modern formats with fallbacks:**
```jsx
<picture>
<source srcSet="/image.avif" type="image/avif" />
<source srcSet="/image.webp" type="image/webp" />
<img src="/image.jpg" alt="Description" loading="lazy" />
</picture>
```
---
## 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

View File

@@ -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.

View File

@@ -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

View File

@@ -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

View File

@@ -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.
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=44c5eab950e209f613a5a47f712550dc" alt="Agent Skills Architecture - showing how Skills integrate with the agent's configuration and virtual machine" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-architecture.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=fc06568b957c9c3617ea341548799568 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=5569fe72706deda67658467053251837 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=83c04e9248de7082971d623f835c2184 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d8e1900f8992d435088a565e098fd32a 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=b03b4a5df2a08f4be86889e6158975ee 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-architecture.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=b9cab267c168f6a480ba946b6558115c 2500w" />
**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
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0127e014bfc3dd3c86567aad8609111b" alt="Skills loading into context window - showing the progressive loading of skill metadata and content" data-og-width="2048" width="2048" data-og-height="1154" height="1154" data-path="images/agent-skills-context-window.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a17315d47b7c5a85b389026b70676e98 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=267349b063954588d4fae2650cb90cd8 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0864972aba7bcb10bad86caf82cb415f 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=631d661cbadcbdb62fd0935b91bd09f8 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c1f80d0e37c517eb335db83615483ae0 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-context-window.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=4b6d0f1baf011ff9b49de501d8d83cc7 2500w" />
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.

View File

@@ -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

View File

@@ -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

View File

@@ -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<string, SkillRule>;
}
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

View File

@@ -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

View File

@@ -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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,467 @@
---
name: skill-optimizer
description: Optimize Claude Code skills for token efficiency using progressive disclosure and content loading order. Use when optimizing skills, reducing token usage, restructuring skill content, improving skill performance, analyzing skill size, applying 500-line rule, implementing progressive disclosure, organizing reference files, optimizing YAML frontmatter, reducing context consumption, improving skill architecture, analyzing token costs, splitting large skills, or working with skill content loading. Covers Level 1 (metadata), Level 2 (instructions), Level 3 (resources) loading optimization.
---
# Skill Optimizer
## Purpose
Optimize existing Claude Code skills to minimize token consumption by leveraging the three-level content loading architecture and progressive disclosure patterns.
## When to Use
Use this skill when:
- Analyzing existing skills for optimization opportunities
- Skills are too large (approaching or exceeding 500 lines)
- Need to reduce context consumption
- Restructuring skills for progressive disclosure
- Converting monolithic skills to multi-file architecture
- Optimizing YAML frontmatter for better discovery
- Improving skill performance and load times
- Auditing skills for token efficiency
- Creating new skills with optimization in mind
---
## Content Loading Architecture
### Three-Level Loading System
**Level 1: Metadata (Always Loaded - ~100 tokens/skill)**
- YAML frontmatter in SKILL.md
- Loaded at startup into system prompt
- Enables skill discovery without context overhead
- **Optimization Target**: Description field (max 1024 chars)
**Level 2: Instructions (Loaded When Triggered - <5,000 tokens)**
- Main SKILL.md content
- Loads dynamically when skill is relevant
- Contains workflows, best practices, guidance
- **Optimization Target**: Keep under 500 lines
**Level 3: Resources (Loaded As Needed - Variable)**
- Additional markdown files (REFERENCE.md, EXAMPLES.md, etc.)
- Code scripts in scripts/ directory
- Templates, schemas, documentation
- **Optimization Target**: No penalty until accessed
### Key Principle
**"Files don't consume context until accessed"** - Bundle comprehensive documentation in reference files without context penalty.
---
## Quick Optimization Workflow
### 1. Analyze Current State
**Check skill size:**
```bash
wc -l .claude/skills/skill-name/SKILL.md
```
**Identify optimization opportunities:**
- [ ] SKILL.md > 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.