feat: add ecosystem positioning, install script & new commands

Ecosystem & Positioning:
- Add README section with competitive positioning (davila7, awesome-claude-code, wesammustafa)
- Add comparison table highlighting unique features (architecture, TDD/SDD, quiz, YAML index)
- Add ecosystem section to reference.yaml

Template Installation:
- Add scripts/install-templates.sh for one-liner template installation
- Support for agents, hooks, commands, skills, memory templates

New Commands:
- catchup, explain, optimize, refactor, security, ship

New Content:
- Semantic anchors catalog and documentation
- Extended guide content (+470 lines)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Florian BRUNIAUX 2026-01-19 08:42:33 +01:00
parent 77d6d8eeb6
commit a5f441bcea
16 changed files with 2333 additions and 62 deletions

View file

@ -19,6 +19,7 @@ Ready-to-use templates for Claude Code configuration.
| [`github-actions/`](./github-actions/) | CI/CD workflows for GitHub Actions |
| [`workflows/`](./workflows/) | Advanced development workflow guides |
| [`modes/`](./modes/) | Behavioral modes for Claude (SuperClaude) |
| [`semantic-anchors/`](./semantic-anchors/) | Precise vocabulary for better LLM outputs |
## Quick Start
@ -71,6 +72,12 @@ Ready-to-use templates for Claude Code configuration.
| [diagnose.md](./commands/diagnose.md) | `/diagnose` | Interactive troubleshooting assistant (FR/EN) |
| [validate-changes.md](./commands/validate-changes.md) | `/validate-changes` | LLM-as-a-Judge pre-commit validation |
| [quiz.md](./commands/quiz.md) | `/quiz` | Self-testing for learning concepts |
| [catchup.md](./commands/catchup.md) | `/catchup` | Restore context after /clear |
| [security.md](./commands/security.md) | `/security` | Quick OWASP security audit |
| [refactor.md](./commands/refactor.md) | `/refactor` | SOLID-based code improvements |
| [explain.md](./commands/explain.md) | `/explain` | Code explanations (3 depth levels) |
| [optimize.md](./commands/optimize.md) | `/optimize` | Performance analysis and roadmap |
| [ship.md](./commands/ship.md) | `/ship` | Pre-deploy checklist |
### Hooks
| File | Event | Purpose |
@ -147,6 +154,13 @@ Ready-to-use templates for Claude Code configuration.
> **See [modes/README.md](./modes/README.md) for installation and SuperClaude framework reference**
### Semantic Anchors
| File | Purpose |
|------|---------|
| [anchor-catalog.md](./semantic-anchors/anchor-catalog.md) | Comprehensive catalog of precise technical terms for prompting |
> **See [Section 2.7](../guide/ultimate-guide.md#27-semantic-anchors) in the guide for how to use semantic anchors**
---
*See the [main guide](../guide/ultimate-guide.md) for detailed explanations, or the [architecture guide](../guide/architecture.md) for how Claude Code works internally.*

View file

@ -0,0 +1,122 @@
# Context Catchup
Restore context after `/clear` - summarize recent work and project state.
## Purpose
After clearing context with `/clear`, use this command to quickly rebuild understanding of:
- What was recently modified
- Current project state
- Outstanding TODOs and issues
- Where to resume work
## Instructions
### Step 1: Git History Analysis
```bash
# Recent commits (last 10)
git log --oneline -10
# Files modified in last 5 commits
git diff --stat HEAD~5 2>/dev/null || git diff --stat $(git rev-list --max-parents=0 HEAD)
# Current branch and status
git branch --show-current
git status --short
```
### Step 2: Recent Changes Summary
```bash
# What changed today
git log --oneline --since="midnight" --author="$(git config user.name)" 2>/dev/null
# Uncommitted work
git diff --name-only
git diff --cached --name-only
```
### Step 3: TODO/FIXME Scan
```bash
# Find outstanding work markers in recently modified files
git diff --name-only HEAD~5 2>/dev/null | head -20 | xargs grep -n "TODO\|FIXME\|XXX\|HACK" 2>/dev/null | head -30
```
### Step 4: Project State Check
```bash
# Check for common state indicators
[ -f "package.json" ] && echo "📦 Node project: $(jq -r '.name // "unnamed"' package.json)"
[ -f "Cargo.toml" ] && echo "🦀 Rust project: $(grep '^name' Cargo.toml | head -1)"
[ -f "pyproject.toml" ] && echo "🐍 Python project"
[ -f "go.mod" ] && echo "🐹 Go project: $(head -1 go.mod | cut -d' ' -f2)"
# Active branch purpose (from branch name)
BRANCH=$(git branch --show-current)
echo "🌿 Branch: $BRANCH"
```
## Output Format
Provide a structured summary:
---
### 📍 Context Restored
**Project**: [name from package.json/Cargo.toml/etc]
**Branch**: [current branch]
**Last Activity**: [time of last commit]
### 🔄 Recent Work (Last 5 Commits)
1. [commit message 1] - [files affected]
2. [commit message 2] - [files affected]
...
### 📝 Uncommitted Changes
- [list of modified files with brief description of changes]
### ⚠️ Outstanding TODOs
- [file:line] TODO: [description]
- [file:line] FIXME: [description]
### 🎯 Suggested Next Steps
Based on recent activity:
1. [Most likely next action based on patterns]
2. [Alternative focus area]
---
## Usage Examples
**After a long break:**
```
/catchup
```
→ Full context restoration
**Quick status check:**
```
/catchup --brief
```
→ Just commits and uncommitted changes
**Focus on specific area:**
```
/catchup auth
```
→ Filter to auth-related changes
## Pro Tips
1. **Document before `/clear`**: Write a brief note in a commit message or CLAUDE.md before clearing context
2. **Use with Memory Bank**: Combine with `.claude/memory/` files for persistent state
3. **Branch naming**: Use descriptive branch names (e.g., `feat/user-auth`) to aid context restoration
$ARGUMENTS

View file

@ -0,0 +1,166 @@
# Code Explainer
Explain code, concepts, or system behavior with adjustable depth levels.
## Purpose
Get clear explanations of:
- How specific code works
- Why certain patterns are used
- What a system/module does
- Architectural decisions and trade-offs
## Instructions
### Step 1: Determine Scope
Identify what needs explanation:
- **File**: Entire file structure and purpose
- **Function/Method**: Specific implementation details
- **Concept**: Architectural pattern or design decision
- **Flow**: How data/control moves through the system
### Step 2: Assess Complexity
```
Simple (1-2 min read) → Quick summary, key points only
Standard (3-5 min read) → Purpose, how it works, key decisions
Deep (10+ min read) → Full breakdown, alternatives, trade-offs
```
### Step 3: Gather Context
```bash
# For file explanations
head -50 "$FILE" # See imports and structure
# For function explanations
grep -A 30 "function $NAME\|def $NAME\|fn $NAME" "$FILE"
# For module explanations
ls -la "$DIR"
cat "$DIR/index.ts" 2>/dev/null || cat "$DIR/__init__.py" 2>/dev/null
```
### Step 4: Structure the Explanation
## Output Format
---
### 📖 Explanation: [Target]
**Scope**: [file/function/concept/flow]
**Depth**: [simple/standard/deep]
### What It Does
[1-3 sentences describing the purpose]
### How It Works
[Step-by-step breakdown appropriate to depth level]
### Key Decisions
| Decision | Why | Alternative |
|----------|-----|-------------|
| [choice made] | [reasoning] | [what else could work] |
### Example Usage
```typescript
// How to use this correctly
```
### Related Code
- `path/to/related.ts` - [relationship]
- `path/to/dependency.ts` - [relationship]
### 💡 Learning Notes (if --learn flag)
[Additional context for understanding the broader pattern]
---
## Depth Levels
### Simple (`/explain --simple`)
```markdown
**validateUser()** checks if the user object has required fields
(email, password) and returns a boolean. Uses regex for email format.
```
### Standard (`/explain` - default)
```markdown
**validateUser(user: User): ValidationResult**
**Purpose**: Validates user input before database operations.
**Flow**:
1. Check required fields exist (email, password)
2. Validate email format with regex
3. Check password meets requirements (8+ chars, special char)
4. Return { valid: boolean, errors: string[] }
**Used by**: signup(), updateProfile()
```
### Deep (`/explain --deep`)
```markdown
[All of standard, plus:]
**Design Decisions**:
- Returns ValidationResult instead of throwing to allow batch validation
- Regex chosen over library for zero dependencies
- Password rules configurable via config.ts
**Trade-offs**:
- Pro: Fast, no dependencies
- Con: Regex email validation isn't RFC-compliant
**Alternatives Considered**:
- Zod schema: More powerful but adds 50KB
- Class-validator: Better for decorators but OOP-heavy
```
## Usage Examples
**Explain a file:**
```
/explain src/auth/middleware.ts
```
**Explain a function:**
```
/explain the handleWebhook function in payments.ts
```
**Explain a concept:**
```
/explain how our event sourcing works
```
**Explain with specific depth:**
```
/explain --deep the authentication flow
/explain --simple what useCallback does
```
**Explain for learning:**
```
/explain --learn the repository pattern used here
```
## Tips
1. **Be specific**: "Explain line 45-60" > "Explain this file"
2. **State your level**: "I'm new to TypeScript" helps calibrate
3. **Ask follow-ups**: "Why not use X instead?" deepens understanding
4. **Request analogies**: "Explain like I'm familiar with Python but not TS"
$ARGUMENTS

View file

@ -0,0 +1,217 @@
# Performance Optimizer
Analyze and suggest performance improvements for code, queries, or systems.
## Purpose
Identify optimization opportunities:
- Runtime performance bottlenecks
- Memory usage issues
- Database query inefficiencies
- Bundle size problems
- Algorithm complexity
## Instructions
### Step 1: Scope Identification
Determine optimization target:
- **Function**: Single function performance
- **Module**: Related functions/classes
- **Query**: Database query optimization
- **Bundle**: Frontend bundle analysis
- **System**: Architecture-level optimization
### Step 2: Performance Analysis
#### Runtime Analysis
```bash
# Find potentially slow patterns
grep -rn "forEach\|\.map\|\.filter\|\.reduce" --include="*.{ts,js}" . | head -20
# Find nested loops (O(n²) potential)
grep -rn "for.*for\|\.forEach.*\.forEach\|\.map.*\.map" --include="*.{ts,js}" . | head -10
# Find sync operations that could be async
grep -rn "readFileSync\|writeFileSync\|execSync" --include="*.{ts,js}" . | head -10
```
#### Memory Analysis
```bash
# Large array operations
grep -rn "new Array\|Array\.from\|\.concat\|spread" --include="*.{ts,js}" . | head -10
# Potential memory leaks (event listeners, intervals)
grep -rn "addEventListener\|setInterval\|setTimeout" --include="*.{ts,js}" . | head -10
```
#### Database Query Analysis
```bash
# N+1 query patterns
grep -rn "await.*find\|await.*query" --include="*.{ts,js}" . | head -15
# Missing indexes hints
grep -rn "WHERE\|ORDER BY\|GROUP BY" --include="*.{ts,js,sql}" . | head -15
```
#### Bundle Analysis
```bash
# Check bundle size (if applicable)
[ -f "package.json" ] && npm run build 2>/dev/null && ls -lh dist/*.js 2>/dev/null
# Large dependencies
[ -f "package.json" ] && cat package.json | jq '.dependencies | keys[]' | head -20
```
### Step 3: Prioritization
Rank findings by:
1. **Impact**: How much will this improve performance?
2. **Effort**: How hard is the fix?
3. **Risk**: What could break?
## Output Format
---
### ⚡ Performance Analysis
**Target**: [file/module/system]
**Analysis Date**: [timestamp]
### 📊 Current Metrics (if measurable)
| Metric | Current | Target | Gap |
|--------|---------|--------|-----|
| Response time | Xms | <Yms | -Z% needed |
| Memory usage | XMB | <YMB | -Z% needed |
| Bundle size | XKB | <YKB | -Z% needed |
### 🔴 Critical Issues
#### 1. [Issue Title] - [Location]
**Problem**: [What's slow and why]
**Current**:
```typescript
// O(n²) - nested loops
users.forEach(user => {
permissions.forEach(perm => {
if (user.id === perm.userId) { ... }
});
});
```
**Optimized**:
```typescript
// O(n) - Map lookup
const permMap = new Map(permissions.map(p => [p.userId, p]));
users.forEach(user => {
const perm = permMap.get(user.id);
if (perm) { ... }
});
```
**Impact**: ~10x faster for 1000 users
**Effort**: Low (5 min)
**Risk**: Low
### 🟠 High Priority
| Issue | Location | Impact | Effort |
|-------|----------|--------|--------|
| [description] | file:line | [estimate] | [time] |
### 🟡 Medium Priority
| Issue | Location | Impact | Effort |
|-------|----------|--------|--------|
| [description] | file:line | [estimate] | [time] |
### 💡 Quick Wins
1. [Small change with good impact]
2. [Another quick optimization]
3. [Low-hanging fruit]
### 📈 Optimization Roadmap
```
Week 1: Critical fixes (items 1-3)
Week 2: High priority (items 4-6)
Week 3: Measure and validate improvements
```
---
## Common Patterns
### Array Operations
| Pattern | Issue | Fix |
|---------|-------|-----|
| `arr.filter().map()` | Two iterations | Single `reduce()` or `flatMap()` |
| `arr.find()` in loop | O(n²) | Build Map/Set first |
| `[...arr1, ...arr2]` | Memory allocation | `arr1.concat(arr2)` or push |
### Database
| Pattern | Issue | Fix |
|---------|-------|-----|
| Loop with await | N+1 queries | Batch query with `IN` |
| `SELECT *` | Over-fetching | Select only needed columns |
| Missing WHERE index | Full table scan | Add composite index |
### React/Frontend
| Pattern | Issue | Fix |
|---------|-------|-----|
| Inline functions in JSX | Re-renders | `useCallback` |
| Large list rendering | DOM thrashing | Virtualization |
| Unoptimized images | Slow LCP | Next/Image, lazy loading |
### Node.js
| Pattern | Issue | Fix |
|---------|-------|-----|
| Sync file operations | Blocks event loop | Async alternatives |
| JSON.parse large files | Memory spike | Streaming parser |
| No connection pooling | Connection overhead | Pool with pg-pool, etc. |
## Usage
**Analyze specific file:**
```
/optimize src/services/user.ts
```
**Focus on specific area:**
```
/optimize --queries src/repositories/
/optimize --bundle
/optimize --memory src/workers/
```
**With target metrics:**
```
/optimize --target=100ms src/api/search.ts
```
**Quick scan:**
```
/optimize --quick
```
## Notes
- Measurements beat assumptions: profile before optimizing
- Premature optimization is the root of all evil (Knuth)
- Focus on hot paths: optimize what runs often
- Consider trade-offs: speed vs readability vs maintainability
$ARGUMENTS

View file

@ -0,0 +1,209 @@
# SOLID Refactoring Assistant
Analyze code for SOLID violations and suggest targeted improvements.
## Purpose
Identify refactoring opportunities based on:
- SOLID principle violations
- Code smells and anti-patterns
- Complexity metrics
- Duplication detection
## Instructions
### Step 1: Scope Analysis
Determine the refactoring scope from user input:
- Single file: Deep analysis
- Directory: Pattern detection across files
- Function/class: Focused extraction suggestions
```bash
# Get file/directory stats
if [ -f "$TARGET" ]; then
wc -l "$TARGET"
echo "Single file analysis"
elif [ -d "$TARGET" ]; then
find "$TARGET" -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" \) | wc -l
echo "Directory analysis"
fi
```
### Step 2: SOLID Violations Detection
#### S - Single Responsibility
Look for:
- Files > 300 lines
- Functions > 50 lines
- Classes with > 10 methods
- Mixed concerns (data + UI + business logic)
```bash
# Find large files
find . -name "*.{ts,js,py}" -exec wc -l {} + 2>/dev/null | sort -rn | head -10
# Functions with high line count (approximate)
grep -rn "function\|def \|fn " --include="*.{ts,js,py,rs}" . | head -20
```
#### O - Open/Closed Principle
Look for:
- Switch/case statements on types
- Repeated if/else type checking
- Direct modifications vs extensions
#### L - Liskov Substitution
Look for:
- Overridden methods that throw "not implemented"
- Type checks before method calls
- Empty method overrides
#### I - Interface Segregation
Look for:
- Large interfaces (> 10 methods)
- Classes implementing unused interface methods
- Fat service classes
#### D - Dependency Inversion
Look for:
- Direct instantiation of dependencies (`new Service()`)
- Hardcoded class references
- Missing dependency injection
### Step 3: Code Smells
```bash
# Duplication patterns
grep -rn --include="*.{ts,js,py}" . 2>/dev/null | \
awk -F: '{print $3}' | sort | uniq -c | sort -rn | head -10
# Long parameter lists (> 4 params)
grep -rn "function.*,.*,.*,.*," --include="*.{ts,js}" . 2>/dev/null | head -10
# Deep nesting (4+ levels)
grep -rn "^\s\{16,\}" --include="*.{ts,js,py}" . 2>/dev/null | head -10
```
### Step 4: Complexity Assessment
For each issue found, assess:
- **Impact**: How much code is affected?
- **Risk**: What could break?
- **Effort**: Lines to change, tests needed?
## Output Format
---
### 🔧 Refactoring Analysis
**Target**: [file/directory]
**Lines Analyzed**: [count]
### 📊 SOLID Scorecard
| Principle | Status | Issues Found |
|-----------|--------|--------------|
| Single Responsibility | 🟡 | 3 large classes |
| Open/Closed | 🟢 | OK |
| Liskov Substitution | 🟢 | OK |
| Interface Segregation | 🔴 | 2 fat interfaces |
| Dependency Inversion | 🟡 | 5 direct instantiations |
### 🎯 Priority Refactorings
#### 1. [Highest Impact] - Extract class from `UserService`
**Violation**: Single Responsibility
**Current**: 450 lines handling auth + profile + notifications
**Suggested**:
```
UserService.ts (450 lines)
↓ Extract
AuthService.ts (~150 lines)
ProfileService.ts (~150 lines)
NotificationService.ts (~100 lines)
```
**Risk**: Medium (update imports)
**Tests Needed**: Update dependency injection in tests
#### 2. [Second Priority] - Replace switch with polymorphism
**Location**: `src/handlers/payment.ts:45`
**Current**:
```typescript
switch (paymentType) {
case 'card': // 50 lines
case 'bank': // 50 lines
case 'crypto': // 50 lines
}
```
**Suggested**: Strategy pattern with `PaymentProcessor` interface
**Risk**: Low (isolated change)
### 📝 Code Smells
| Smell | Location | Severity |
|-------|----------|----------|
| Long Method | `api.ts:calculateTotal` (120 lines) | 🟠 High |
| Duplicate Code | `utils/*.ts` (3 similar blocks) | 🟡 Medium |
| Deep Nesting | `parser.ts:parse` (6 levels) | 🟡 Medium |
### 🚀 Quick Wins (Low Risk, High Value)
1. Extract `validateEmail()` to shared utils (used in 4 places)
2. Replace magic numbers with named constants
3. Add early returns to reduce nesting in `processOrder()`
### ⚠️ Technical Debt Notes
- [Item to track for future sprints]
---
## Refactoring Safety Checklist
Before applying suggestions:
- [ ] Tests exist for affected code
- [ ] Create feature branch
- [ ] Commit current state
- [ ] Apply one refactoring at a time
- [ ] Run tests after each change
- [ ] Review diff before committing
## Usage
**Analyze specific file:**
```
/refactor src/services/user.ts
```
**Analyze directory:**
```
/refactor src/api/
```
**Focus on specific principle:**
```
/refactor --focus=srp src/services/
```
**With complexity threshold:**
```
/refactor --threshold=high
```
## References
- Martin Fowler's Refactoring Catalog
- Clean Code by Robert C. Martin
- SOLID principles by Robert C. Martin
$ARGUMENTS

View file

@ -0,0 +1,160 @@
# Security Quick Audit
Rapid security assessment focused on OWASP Top 10 vulnerabilities.
## Purpose
Perform a quick security scan to identify common vulnerabilities:
- Hardcoded secrets and credentials
- SQL injection risks
- XSS vulnerabilities
- Insecure dependencies
- Authentication/authorization issues
## Instructions
### Step 1: Secrets Scan
```bash
# Common secret patterns
grep -rn --include="*.{js,ts,py,go,java,rb,php,env}" \
-E "(password|secret|api_key|apikey|token|auth|credential).*[=:].*['\"][^'\"]{8,}['\"]" \
--exclude-dir={node_modules,vendor,.git,dist,build} . 2>/dev/null | head -20
# .env files that might be committed
find . -name ".env*" -not -path "*/node_modules/*" -type f 2>/dev/null
# Check if secrets are gitignored
[ -f ".gitignore" ] && grep -q "\.env" .gitignore && echo "✅ .env in .gitignore" || echo "⚠️ .env NOT in .gitignore"
```
### Step 2: Injection Vulnerabilities
```bash
# SQL injection patterns (raw queries with string concat)
grep -rn --include="*.{js,ts,py,go,java,php}" \
-E "(query|execute|raw|sql).*\+.*\$|f['\"].*SELECT|\.format\(.*SELECT" \
--exclude-dir={node_modules,vendor,.git} . 2>/dev/null | head -15
# Command injection patterns
grep -rn --include="*.{js,ts,py,go,rb,php}" \
-E "(exec|spawn|system|shell_exec|popen)\s*\(" \
--exclude-dir={node_modules,vendor,.git} . 2>/dev/null | head -15
```
### Step 3: XSS Patterns
```bash
# Dangerous innerHTML/dangerouslySetInnerHTML usage
grep -rn --include="*.{js,ts,jsx,tsx,vue}" \
-E "(innerHTML|dangerouslySetInnerHTML|v-html)" \
--exclude-dir={node_modules,.git,dist} . 2>/dev/null | head -15
# Unescaped template literals in HTML context
grep -rn --include="*.{js,ts,jsx,tsx}" \
-E "\`.*\$\{.*\}.*<" \
--exclude-dir={node_modules,.git,dist} . 2>/dev/null | head -10
```
### Step 4: Dependency Check
```bash
# Check for known vulnerabilities in npm packages
[ -f "package-lock.json" ] && npm audit --json 2>/dev/null | jq '{vulnerabilities: .metadata.vulnerabilities}' 2>/dev/null
# Check for outdated packages with security issues
[ -f "package.json" ] && npm outdated --json 2>/dev/null | jq 'to_entries | map(select(.value.current != .value.latest)) | length' 2>/dev/null
```
### Step 5: Auth & Session Issues
```bash
# Hardcoded JWT secrets
grep -rn --include="*.{js,ts,py,go}" \
-E "(jwt|JWT).*secret.*[=:].*['\"].{8,}['\"]" \
--exclude-dir={node_modules,vendor,.git} . 2>/dev/null
# Missing CSRF protection patterns
grep -rn --include="*.{js,ts,py}" \
-E "(POST|PUT|DELETE|PATCH).*fetch|axios\.(post|put|delete|patch)" \
--exclude-dir={node_modules,vendor,.git} . 2>/dev/null | head -10
```
## Output Format
---
### 🛡️ Security Audit Report
**Scan Date**: [timestamp]
**Scope**: [directory scanned]
### 🔴 Critical Issues
| Issue | Location | Description |
|-------|----------|-------------|
| [type] | [file:line] | [brief description] |
### 🟠 High Severity
| Issue | Location | Recommendation |
|-------|----------|----------------|
| [type] | [file:line] | [fix suggestion] |
### 🟡 Medium Severity
| Issue | Location | Note |
|-------|----------|------|
| [type] | [file:line] | [context] |
### 📊 Summary
- **Critical**: X issues
- **High**: X issues
- **Medium**: X issues
- **Dependencies**: X vulnerabilities
### 🔧 Quick Fixes
1. [Highest priority fix with command/code]
2. [Second priority]
3. [Third priority]
---
## Severity Levels
| Level | Examples | Action |
|-------|----------|--------|
| 🔴 Critical | Hardcoded prod secrets, SQL injection | Fix immediately |
| 🟠 High | Missing auth, XSS vectors | Fix before deploy |
| 🟡 Medium | Outdated deps, missing CSRF | Plan remediation |
| 🟢 Low | Best practice violations | Track for improvement |
## Usage
**Full audit:**
```
/security
```
**Focus on specific area:**
```
/security auth
/security deps
/security injection
```
**Specific file/directory:**
```
/security src/api/
```
## Notes
- This is a quick heuristic scan, not a comprehensive security audit
- For production systems, complement with dedicated tools (Snyk, SonarQube, OWASP ZAP)
- False positives are possible - verify findings manually
- See `examples/hooks/security-hooks.sh` for automated pre-commit security checks
$ARGUMENTS

232
examples/commands/ship.md Normal file
View file

@ -0,0 +1,232 @@
# Ship Command - Pre-Deploy Checklist
Comprehensive pre-deployment verification to ensure release readiness.
## Purpose
Run before every production deployment to verify:
- Code quality gates
- Test coverage
- Security checks
- Documentation updates
- Environment readiness
## Pre-Deploy Checklist
### 🔴 Blockers (Must Pass)
```bash
# 1. All tests passing
npm test 2>/dev/null || pnpm test 2>/dev/null || yarn test 2>/dev/null
echo "Exit code: $?"
# 2. No TypeScript/lint errors
npm run typecheck 2>/dev/null || npx tsc --noEmit
npm run lint 2>/dev/null || npx eslint .
# 3. Build succeeds
npm run build 2>/dev/null || pnpm build 2>/dev/null
# 4. No secrets in code
grep -rn "API_KEY=\|SECRET=\|PASSWORD=" --include="*.{ts,js,json}" . 2>/dev/null | grep -v node_modules | grep -v ".env.example"
```
### 🟠 High Priority (Should Pass)
```bash
# 5. Security audit
npm audit --audit-level=high 2>/dev/null || echo "Run manually: npm audit"
# 6. No console.log in production code
grep -rn "console\.log\|console\.debug" --include="*.{ts,js,tsx,jsx}" src/ 2>/dev/null | grep -v "// allowed" | head -10
# 7. No TODO/FIXME in critical paths
grep -rn "TODO\|FIXME\|XXX\|HACK" --include="*.{ts,js}" src/ 2>/dev/null | head -10
# 8. Database migrations ready
[ -d "prisma/migrations" ] && echo "Prisma migrations: $(ls prisma/migrations | wc -l) total"
[ -d "migrations" ] && echo "Migrations: $(ls migrations | wc -l) total"
```
### 🟡 Recommended (Nice to Have)
```bash
# 9. Documentation updated
git diff --name-only HEAD~5 | grep -E "README|CHANGELOG|docs/" | head -10
# 10. Version bumped
cat package.json | jq -r '.version' 2>/dev/null || echo "Check version manually"
# 11. Environment variables documented
[ -f ".env.example" ] && echo "✅ .env.example exists" || echo "⚠️ Missing .env.example"
```
## Output Format
---
### 🚀 Ship Readiness Report
**Branch**: [current branch]
**Commit**: [HEAD short hash]
**Target**: [production/staging]
**Timestamp**: [date/time]
### Blockers (Must Fix Before Deploy)
| Check | Status | Details |
|-------|--------|---------|
| Tests | ✅/❌ | X passed, Y failed |
| TypeScript | ✅/❌ | X errors |
| Lint | ✅/❌ | X warnings, Y errors |
| Build | ✅/❌ | Success/Failed |
| Secrets | ✅/❌ | X potential leaks |
### High Priority
| Check | Status | Action |
|-------|--------|--------|
| Security Audit | ⚠️/✅ | X vulnerabilities |
| Console Logs | ⚠️/✅ | X found in src/ |
| TODOs | ⚠️/✅ | X critical TODOs |
| Migrations | ⚠️/✅ | X pending |
### Recommended
| Check | Status | Note |
|-------|--------|------|
| Docs Updated | ⚠️/✅ | CHANGELOG updated |
| Version Bumped | ⚠️/✅ | Current: X.Y.Z |
| Env Documented | ⚠️/✅ | .env.example present |
### 📊 Summary
```
🔴 Blockers: X/5 passed
🟠 High: X/4 passed
🟡 Recommended: X/3 passed
─────────────────────────
Overall: [READY TO SHIP / NOT READY]
```
### 🎯 Action Items
1. [Most critical fix needed]
2. [Second priority]
3. [Third priority]
---
## Environment-Specific Checks
### Production Deploy
```bash
# Verify production env vars
[ -f ".env.production" ] && echo "Production env exists"
# Check for debug flags
grep -rn "DEBUG=true\|NODE_ENV=development" .env* 2>/dev/null
# Verify API endpoints point to production
grep -rn "localhost\|127\.0\.0\.1" --include="*.{ts,js,json}" src/ 2>/dev/null | grep -v test | head -5
```
### Staging Deploy
```bash
# Staging-specific checks
[ -f ".env.staging" ] && echo "Staging env exists"
# Feature flags for staging
grep -rn "FEATURE_FLAG\|ENABLE_" .env* 2>/dev/null
```
## CI/CD Integration
Add to your pipeline:
```yaml
# GitHub Actions example
ship-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run ship checklist
run: |
npm ci
npm test
npm run typecheck
npm run lint
npm run build
npm audit --audit-level=high
```
## Post-Deploy Verification
After deployment, verify:
```bash
# 1. Health check
curl -s https://your-app.com/health | jq .
# 2. Version check
curl -s https://your-app.com/version | jq .
# 3. Smoke tests
npm run test:smoke 2>/dev/null || echo "Run smoke tests manually"
```
## Rollback Preparation
Before shipping, ensure you can rollback:
```bash
# Note current production tag
git describe --tags --abbrev=0
# Verify rollback procedure exists
[ -f "docs/runbooks/rollback.md" ] && echo "✅ Rollback docs exist"
# Check database migration reversibility
# Prisma: prisma migrate diff
# Rails: rails db:rollback (dry-run)
```
## Usage
**Full checklist:**
```
/ship
```
**Production deploy:**
```
/ship --production
```
**Quick check (blockers only):**
```
/ship --quick
```
**With specific target:**
```
/ship --target=staging
```
## Tips
1. **Run early, run often**: Don't wait until deploy day
2. **Automate in CI**: Make blockers fail the pipeline
3. **Team agreement**: Define what's a blocker vs warning
4. **Document exceptions**: If skipping a check, note why
5. **Monitor after deploy**: Ship is not done until monitoring confirms success
## Related Commands
- `/release-notes` - Generate changelog and announcements
- `/validate-changes` - LLM-based code review
- `/security` - Deep security audit
$ARGUMENTS

View file

@ -0,0 +1,310 @@
# Semantic Anchors Catalog
> **Concept**: Alexandre Soyer
> **Source**: [github.com/LLM-Coding/Semantic-Anchors](https://github.com/LLM-Coding/Semantic-Anchors) (Apache-2.0)
> **Adapted for**: Claude Code workflows
## What Are Semantic Anchors?
LLMs are statistical pattern matchers. When you use **precise technical vocabulary**, you help Claude access the right patterns from its training data. Generic terms produce generic code; specific terms produce specific, well-structured code.
**Analogy**: Technical terms are GPS coordinates into Claude's knowledge base.
---
## Testing & Quality Assurance
### Test Methodologies
| Vague | Semantic Anchor | What It Activates |
|-------|-----------------|-------------------|
| "write tests" | "TDD London School (mockist)" | Outside-in, mock collaborators, focus on behavior |
| "write tests" | "TDD Chicago School (classicist)" | Bottom-up, real collaborators, state verification |
| "test edge cases" | "Property-Based Testing (QuickCheck)" | Generative testing, shrinking, invariant discovery |
| "thorough testing" | "Mutation Testing (Stryker/PIT)" | Kill mutants, measure test effectiveness |
| "behavior tests" | "BDD Gherkin syntax (Given/When/Then)" | Cucumber-style, living documentation |
### Test Quality
| Vague | Semantic Anchor | Effect |
|-------|-----------------|--------|
| "good test names" | "Roy Osherove naming: MethodName_Scenario_ExpectedBehavior" | Consistent, descriptive names |
| "isolated tests" | "Test Pyramid (Fowler): 70% unit, 20% integration, 10% E2E" | Proper test distribution |
| "fast tests" | "Sociable unit tests with test doubles at boundaries" | Speed with realistic behavior |
| "readable tests" | "Arrange-Act-Assert (AAA) pattern" | Clear test structure |
| "maintainable tests" | "Object Mother / Test Data Builder pattern" | Reusable test fixtures |
---
## Architecture & Design
### Architectural Patterns
| Vague | Semantic Anchor | When to Use |
|-------|-----------------|-------------|
| "clean architecture" | "Hexagonal Architecture (Ports & Adapters)" | Domain isolation, testability |
| "layered architecture" | "Onion Architecture (Palermo)" | Dependency toward center |
| "microservices" | "Domain-Driven Design bounded contexts" | Service boundaries |
| "event-driven" | "CQRS with Event Sourcing" | Read/write separation, audit trail |
| "scalable" | "Event-Driven Architecture with message broker" | Async processing, decoupling |
### Domain-Driven Design (Evans)
| Vague | Semantic Anchor | Purpose |
|-------|-----------------|---------|
| "business logic" | "DDD Aggregate pattern" | Transactional consistency |
| "data access" | "DDD Repository pattern" | Persistence abstraction |
| "object mapping" | "DDD Value Objects" | Immutable, equality by value |
| "complex objects" | "DDD Entity pattern" | Identity-based equality |
| "business rules" | "DDD Domain Services" | Stateless operations |
| "integration" | "DDD Anti-Corruption Layer (ACL)" | External system isolation |
### SOLID Principles
| Vague | Semantic Anchor | Specific Guidance |
|-------|-----------------|-------------------|
| "single purpose" | "SRP: one reason to change (Robert C. Martin)" | Cohesion focus |
| "extensible" | "OCP: open for extension, closed for modification" | Plugin architecture |
| "substitutable" | "LSP: subtypes must be substitutable" | Contract preservation |
| "minimal interfaces" | "ISP: clients shouldn't depend on unused methods" | Interface segregation |
| "decoupled" | "DIP: depend on abstractions, not concretions" | Inversion of control |
---
## Code Quality & Refactoring
### Refactoring Catalog (Fowler)
| Vague | Semantic Anchor | Trigger |
|-------|-----------------|---------|
| "extract logic" | "Extract Method refactoring" | Long methods |
| "remove conditionals" | "Replace Conditional with Polymorphism" | Complex if/switch |
| "simplify creation" | "Replace Constructor with Factory Method" | Complex instantiation |
| "remove duplication" | "Extract Class / Extract Superclass" | Similar classes |
| "improve naming" | "Rename Method/Variable (intention-revealing names)" | Unclear names |
### Code Smells (Fowler/Beck)
| Smell | Semantic Anchor | Solution |
|-------|-----------------|----------|
| "long method" | "Extract Method until comments become unnecessary" | Methods < 10 lines |
| "large class" | "Extract Class following SRP" | Single responsibility |
| "feature envy" | "Move Method to class that owns data" | Better cohesion |
| "primitive obsession" | "Replace Primitive with Value Object" | Type safety |
| "shotgun surgery" | "Move Field/Method to consolidate changes" | Centralize logic |
### Clean Code (Martin)
| Vague | Semantic Anchor | Application |
|-------|-----------------|-------------|
| "readable" | "Screaming Architecture: package structure reveals intent" | Folder naming |
| "clear names" | "Intention-revealing names (Clean Code Ch. 2)" | Self-documenting |
| "no comments" | "Code should be self-explanatory (comments lie)" | Refactor instead |
| "small functions" | "Functions should do one thing (max 20 lines)" | Single responsibility |
| "no side effects" | "Command-Query Separation (CQS)" | Predictable behavior |
---
## Error Handling
### Functional Patterns
| Vague | Semantic Anchor | Benefits |
|-------|-----------------|----------|
| "error handling" | "Railway Oriented Programming with Either<L,R>" | Composable errors |
| "null safety" | "Option/Maybe monad (never return null)" | Explicit absence |
| "error accumulation" | "Validation applicative functor" | Collect all errors |
| "async errors" | "Task/Future monad with error channel" | Async error flow |
### Exception Strategies
| Vague | Semantic Anchor | Use Case |
|-------|-----------------|----------|
| "handle errors" | "Checked exceptions at boundaries only" | External integration |
| "error recovery" | "Circuit Breaker pattern (Nygard)" | Fault tolerance |
| "graceful degradation" | "Bulkhead pattern" | Isolation |
| "retry logic" | "Exponential backoff with jitter" | Resilience |
---
## API Design
### REST Maturity
| Vague | Semantic Anchor | Level |
|-------|-----------------|-------|
| "REST API" | "REST Level 0: HTTP as tunnel" | Basic |
| "proper REST" | "REST Level 2: HTTP verbs + status codes" | Standard |
| "HATEOAS" | "REST Level 3: Hypermedia controls" | Full REST |
| "API versioning" | "URL path versioning (/v1/) or header versioning" | Evolution |
### API Quality
| Vague | Semantic Anchor | Application |
|-------|-----------------|-------------|
| "consistent API" | "JSON:API specification" | Response format |
| "documented API" | "OpenAPI 3.0 (Swagger)" | Spec-first design |
| "secure API" | "OAuth 2.0 + PKCE flow" | Authentication |
| "rate limiting" | "Token bucket algorithm" | Traffic control |
---
## Documentation
### Architecture Documentation
| Vague | Semantic Anchor | Output |
|-------|-----------------|--------|
| "document architecture" | "C4 Model (Context, Container, Component, Code)" | Diagrams |
| "architecture docs" | "arc42 template structure" | Comprehensive docs |
| "design decisions" | "ADR (Architecture Decision Records) - Nygard format" | Decision log |
| "system overview" | "4+1 View Model (Kruchten)" | Multiple perspectives |
### Code Documentation
| Vague | Semantic Anchor | Format |
|-------|-----------------|--------|
| "API docs" | "JSDoc / TSDoc with @example tags" | Generated docs |
| "README" | "README-driven development (Tom Preston-Werner)" | Project intro |
| "changelog" | "Keep a Changelog format (semver)" | Release notes |
| "contributing" | "CONTRIBUTING.md with PR template" | Contributor guide |
---
## Requirements & Specifications
### Requirements Syntax
| Vague | Semantic Anchor | Format |
|-------|-----------------|--------|
| "requirements" | "EARS syntax (Easy Approach to Requirements)" | Structured requirements |
| "user stories" | "Connextra format: As a [role] I want [goal] so that [benefit]" | User perspective |
| "acceptance criteria" | "BDD Gherkin: Given/When/Then" | Testable criteria |
| "use cases" | "Cockburn's use case template (brief/casual/fully dressed)" | Interaction flows |
### Discovery & Mapping
| Vague | Semantic Anchor | Technique |
|-------|-----------------|-----------|
| "understand users" | "User Story Mapping (Jeff Patton)" | Journey visualization |
| "prioritize features" | "MoSCoW method (Must/Should/Could/Won't)" | Priority triage |
| "user needs" | "Jobs-to-be-Done framework (Christensen)" | Outcome focus |
| "event modeling" | "Event Storming (Brandolini)" | Domain discovery |
---
## Security
### OWASP & Common Vulnerabilities
| Vague | Semantic Anchor | Protection |
|-------|-----------------|------------|
| "secure code" | "OWASP Top 10 mitigations" | Comprehensive checklist |
| "input validation" | "Allowlist validation + parameterized queries" | Injection prevention |
| "authentication" | "OWASP ASVS Level 2 requirements" | Auth standards |
| "secrets management" | "HashiCorp Vault or cloud KMS" | Secret storage |
### Security Patterns
| Vague | Semantic Anchor | Implementation |
|-------|-----------------|----------------|
| "secure by default" | "Principle of least privilege" | Minimal permissions |
| "defense in depth" | "Multiple security layers (network, app, data)" | Layered security |
| "secure communication" | "TLS 1.3 with certificate pinning" | Transport security |
| "audit logging" | "Immutable audit trail with tamper detection" | Compliance |
---
## Performance
### Optimization Patterns
| Vague | Semantic Anchor | Application |
|-------|-----------------|-------------|
| "caching" | "Cache-aside pattern with TTL" | Read performance |
| "batch processing" | "Bulk operations with chunking" | Write performance |
| "lazy loading" | "Virtual proxy pattern" | Resource optimization |
| "memoization" | "Function memoization with LRU eviction" | Computation caching |
### Scalability
| Vague | Semantic Anchor | Technique |
|-------|-----------------|-----------|
| "horizontal scaling" | "Stateless services + external state store" | Scale-out |
| "database scaling" | "Read replicas + write-through caching" | DB performance |
| "async processing" | "Message queue with competing consumers" | Throughput |
| "load balancing" | "Round-robin with health checks" | Distribution |
---
## CLAUDE.md Template with Semantic Anchors
```markdown
# Project Architecture
## Principles (Semantic Anchors)
### Architecture
- **Pattern**: Hexagonal Architecture (Ports & Adapters)
- **Domain modeling**: Domain-Driven Design tactical patterns (Aggregates, Value Objects, Domain Events)
- **Documentation**: ADR (Architecture Decision Records) for significant decisions
### Code Quality
- **Design**: SOLID principles, especially SRP and DIP
- **Refactoring**: Apply Fowler's catalog - Extract Method, Replace Conditional with Polymorphism
- **Naming**: Intention-revealing names, Screaming Architecture for packages
### Testing
- **Methodology**: TDD London School - outside-in, mock collaborators
- **Structure**: Arrange-Act-Assert (AAA) pattern
- **Coverage**: Test Pyramid - 70% unit, 20% integration, 10% E2E
### Error Handling
- **Pattern**: Railway Oriented Programming with Result<T, E>
- **Never**: Return null, throw for control flow
- **Always**: Use Option/Maybe for optional values
### API Design
- **Style**: REST Level 2 with proper HTTP verbs and status codes
- **Documentation**: OpenAPI 3.0 spec-first
- **Security**: OAuth 2.0 + PKCE for authentication
### Requirements
- **Format**: EARS syntax for formal requirements
- **User stories**: Connextra format with acceptance criteria
- **Discovery**: Event Storming for domain exploration
```
---
## Quick Reference
### Before/After Examples
| Before (Vague) | After (Anchored) |
|----------------|------------------|
| "Make it clean" | "Apply SRP: each class has one reason to change" |
| "Add error handling" | "Use Railway Oriented Programming with Either monad" |
| "Write good tests" | "Follow TDD London School with mock collaborators" |
| "Document the API" | "Generate OpenAPI 3.0 spec from annotations" |
| "Make it secure" | "Mitigate OWASP Top 10, specifically A03:Injection" |
| "Refactor this" | "Apply Extract Method until comments are unnecessary" |
| "Scale this service" | "Implement CQRS with Event Sourcing for read/write separation" |
---
## Usage Tips
1. **Combine anchors**: "Apply Hexagonal Architecture with DDD tactical patterns and Railway Oriented error handling"
2. **Specify versions/authors**: "Following Kent Beck's TDD (2003)" is more specific than "TDD"
3. **Reference books**: "Clean Code Chapter 2 naming conventions" activates specific knowledge
4. **Name patterns explicitly**: "Strategy pattern" > "pluggable behavior"
5. **Use with XML tags**: Combine anchors with `<constraints>` and `<quality_criteria>` tags for maximum effect
---
> **Remember**: The goal is precision, not jargon. Use anchors that Claude has seen extensively in its training data. When in doubt, reference the authoritative source (book, paper, framework).