# 🎓 Crafted Skills Tutorial - Getting Started

**Learn how to use Crafted Skills to supercharge your development workflow**

This tutorial will guide you through real-world examples of using Crafted Skills with Claude Code.

---

## 📋 Table of Contents

- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Tutorial 1: Building a Feature (Balanced Level)](#tutorial-1-building-a-feature-balanced-level)
- [Tutorial 2: Fixing a Bug](#tutorial-2-fixing-a-bug)
- [Tutorial 3: Refactoring Code](#tutorial-3-refactoring-code)
- [Tutorial 4: Security Review](#tutorial-4-security-review)
- [Tutorial 5: Using Agent Skills](#tutorial-5-using-agent-skills)
- [Tutorial 6: Quick Validations](#tutorial-6-quick-validations)
- [Best Practices](#best-practices)

---

## Prerequisites

Before starting this tutorial, ensure you have:

1. ✅ A Crafted SaaS project
2. ✅ Claude Code installed in VS Code
3. ✅ Crafted CLI installed (`npm install -g @crafted/cli`)
4. ✅ MCP servers configured (run `crafted install-mcp-all`)

---

## Installation

Install Crafted Skills in your project:

```bash
cd your-crafted-project
crafted install-skills
```

You should see:

```
✅ Skills installed successfully!

Available skills:
  📊 Level Skills: /rapid, /balanced, /crafted
  🔄 Workflow Skills: /feature, /bugfix, /refactor, /security
  👥 Agent Skills: /architect, /developer, /tester, /reviewer
  🛠️  Utility Skills: /validate, /guard, /coverage
```

---

## Tutorial 1: Building a Feature (Balanced Level)

**Scenario**: You want to add a product catalog with filtering and pagination.

**Your project**: Balanced level, Web platform

### Step 1: Start Claude Code

Open Claude Code in VS Code (Cmd+Shift+P → "Claude Code: Open")

### Step 2: Request the Feature

Simply describe what you want:

```
User: "I want to add a product catalog feature with filtering by category and pagination"
```

### Step 3: Claude Auto-Detects and Applies Workflow

Claude will:

**1. Auto-detect your project level**
```
🔍 Detecting project context...
  Level: balanced ⚖️
  Platform: web
```

**2. Design Architecture (Architect Mode)**
```
🏗️  Architect Mode Activated

Designing 3-layer architecture for Balanced level:

Router Layer (< 20 lines):
  - packages/api/routers/product.ts
  - Thin procedure: list()

Service Layer (< 50 lines):
  - packages/services/product.service.ts
  - Business logic: filtering, pagination

Repository Layer:
  - packages/database/repositories/product.repository.ts
  - Prisma queries with filters

Creating ADR-042: Use cursor pagination for scalability
```

**3. Implement (Developer Mode)**
```
👨‍💻 Developer Mode Activated

Implementing feature following Balanced rules:
  ✅ Router < 20 lines
  ✅ Service < 50 lines per function
  ✅ Max 3 parameters per function
  ✅ No inline comments
  ✅ Self-documenting code

Files created:
  ✅ packages/api/routers/product.ts (15 lines)
  ✅ packages/services/product.service.ts (45 lines)
  ✅ packages/database/repositories/product.repository.ts (38 lines)
  ✅ packages/validators/product.validator.ts (12 lines)

Validating code quality...
  ✅ No violations detected
```

**4. Test (Tester Mode)**
```
🧪 Tester Mode Activated

Writing tests for Balanced level (70% coverage):

Unit tests:
  ✅ ProductService.list() - happy path
  ✅ ProductService.list() - with filters
  ✅ ProductService.list() - pagination edge cases

Integration tests:
  ✅ Router → Service → Repository flow

Running tests...
  ✅ All tests pass
  ✅ Coverage: 75% (required: 70%)
```

**5. Review (Reviewer Mode)**
```
👀 Reviewer Mode Activated

Validating implementation:
  ✅ Code quality (no violations)
  ✅ Architecture (3-layer separation)
  ✅ Tests (75% coverage)
  ✅ Type safety (all functions typed)

Feature ready! 🎉
```

### Step 4: Review the Code

Claude will show you the generated code:

```typescript
// packages/api/routers/product.ts
export const productRouter = createTRPCRouter({
  list: publicProcedure
    .input(listProductsSchema)
    .query(({ input }) =>
      productService.list(input)
    ),
});

// packages/services/product.service.ts
export const productService = {
  async list(filters: ProductFilters) {
    const products = await productRepository.findMany(filters);
    const total = await productRepository.count(filters);

    return {
      products,
      total,
      page: filters.page,
      hasMore: total > filters.page * filters.limit,
    };
  },
};

// packages/database/repositories/product.repository.ts
export const productRepository = {
  findMany: (filters: ProductFilters) =>
    db.product.findMany({
      where: buildWhereClause(filters),
      skip: (filters.page - 1) * filters.limit,
      take: filters.limit,
    }),

  count: (filters: ProductFilters) =>
    db.product.count({
      where: buildWhereClause(filters),
    }),
};
```

### What Just Happened?

Claude:
- ✅ Detected your project is **Balanced level**
- ✅ Applied **3-layer architecture** (not flat like Rapid)
- ✅ Created **thin router** (< 20 lines, not 100 like Rapid)
- ✅ Wrote **unit tests** with **70% coverage** (not 0% like Rapid)
- ✅ Validated **architecture boundaries** (service doesn't import router)

**All automatically!** You didn't have to:
- ❌ Specify "use Balanced level rules"
- ❌ Say "create 3 layers"
- ❌ Tell it to "write tests with 70% coverage"

---

## Tutorial 2: Fixing a Bug

**Scenario**: Users report they can't update their email if it contains a `+` sign (e.g., `user+test@email.com`)

### Step 1: Report the Bug

```
User: "Bug: Users can't update their email when it contains a + sign"
```

### Step 2: Claude Executes Bug Fix Workflow

**1. Reproduce**
```
🔍 Step 1: Reproduce

Writing failing test to confirm bug...

it('should update email with plus sign', async () => {
  const result = await userService.updateEmail(
    'user-123',
    'user+test@email.com'
  );
  expect(result.isSuccess).toBe(true); // Currently FAILS ❌
});

Running test...
  ❌ Test fails (bug confirmed)
```

**2. Diagnose**
```
🔬 Step 2: Diagnose

Searching for updateEmail implementation...

Found issue in packages/domain/value-objects/Email.ts:
  Line 8: Email validation regex too strict
  Current: /^[a-zA-Z0-9@.]+$/
  Issue: Rejects + sign in email addresses

Root cause identified: Regex doesn't allow + character
```

**3. Fix**
```
🔧 Step 3: Fix

Updating Email value object validation:

export class Email {
  private static readonly REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  static create(email: string): Result<Email> {
    if (!Email.REGEX.test(email)) {
      return Result.fail('Invalid email format');
    }
    return Result.ok(new Email(email));
  }
}

Change: Now accepts + and other valid email characters
Follows: RFC 5322 email standard
```

**4. Test (Regression Test)**
```
🧪 Step 4: Test

Adding regression test to prevent bug from coming back:

it('should accept email with plus sign', async () => {
  const result = await userService.updateEmail(
    'user-123',
    'user+test@email.com'
  );
  expect(result.isSuccess).toBe(true);
  expect(result.value.email).toBe('user+test@email.com');
});

it('should accept email with dots', async () => {
  const result = await userService.updateEmail(
    'user-123',
    'user.name@email.com'
  );
  expect(result.isSuccess).toBe(true);
});

Running tests...
  ✅ All tests pass
```

**5. Validate**
```
✅ Step 5: Validate

Running full test suite...
  ✅ All tests pass (no side effects)

Checking coverage...
  ✅ Coverage maintained: 75%

Type check...
  ✅ No type errors

Bug fixed! 🎉
```

### What Just Happened?

Claude:
- ✅ **Reproduced** the bug with a failing test
- ✅ **Diagnosed** the root cause
- ✅ **Fixed** the issue properly
- ✅ **Added regression test** to prevent it from coming back
- ✅ **Validated** no side effects

All in one workflow!

---

## Tutorial 3: Refactoring Code

**Scenario**: Your `productRouter.ts` file is getting too big (250 lines) and hard to maintain.

### Step 1: Request Refactoring

```
User: "This productRouter file is too big, can you refactor it to follow Balanced architecture?"
```

### Step 2: Claude Executes Refactor Workflow

**1. Analyze**
```
🔍 Step 1: Analyze

Reading packages/api/routers/product.ts...
  Current: 250 lines
  Detected level: balanced ⚖️

Issues found:
  ❌ Router has 250 lines (should be < 20 for Balanced)
  ❌ Business logic mixed with API layer
  ❌ Price calculation duplicated 3 times
  ❌ No service layer

Violations:
  - Function length: 250 lines (max 20 for Balanced)
  - Architecture: Missing service layer
  - Duplication: Price calculation (3 occurrences)
```

**2. Plan**
```
📋 Step 2: Plan

Refactoring strategy:
  1. Extract productService with business logic
  2. Extract productRepository for data access
  3. Thin down router to < 20 lines per procedure
  4. Extract calculatePriceWithTax() to remove duplication

Expected outcome:
  ✅ Router: 15 lines (was 250)
  ✅ Service: 80 lines total
  ✅ Repository: 40 lines
  ✅ Utils: 15 lines
```

**3. Refactor**
```
🔨 Step 3: Refactor

Creating packages/services/product.service.ts...
  ✅ create() - 42 lines
  ✅ list() - 25 lines
  ✅ update() - 18 lines

Creating packages/database/repositories/product.repository.ts...
  ✅ Data access layer

Creating packages/utils/price.ts...
  ✅ calculatePriceWithTax() - extracted from 3 places

Updating packages/api/routers/product.ts...
  ✅ Thinned to 15 lines per procedure
```

**4. Test**
```
🧪 Step 4: Test

Running existing tests...
  ✅ All tests pass (behavior unchanged)

Coverage check...
  ✅ Coverage: 75% (maintained)
```

**5. Validate**
```
✅ Step 5: Validate

Validating architecture...
  ✅ 3-layer separation (Router → Service → Repository)
  ✅ No circular dependencies
  ✅ Services don't import from routers

Metrics improvement:
  📊 Before:
    - Router: 250 lines
    - Architecture violations: 5
    - Duplication: 3 places

  📊 After:
    - Router: 15 lines ✅
    - Service: 80 lines ✅
    - Repository: 40 lines ✅
    - Architecture violations: 0 ✅
    - Duplication: 0 ✅

Refactoring complete! 🎉
```

---

## Tutorial 4: Security Review

**Scenario**: You want to review the security of your authentication system before launching.

### Step 1: Request Security Review

```
User: "Can you review the security of our authentication system?"
```

### Step 2: Claude Executes Security Workflow

**1. Automated Scan**
```
🔍 Step 1: Automated Scan

Scanning dependencies...
  pnpm audit
  ⚠️  3 moderate vulnerabilities found
  💡 Run: pnpm update

Searching for hardcoded secrets...
  ✅ No hardcoded API keys found
  ✅ No hardcoded passwords found

Linting security rules...
  ✅ ESLint security checks pass
```

**2. OWASP Top 10 Analysis**
```
🛡️  Step 2: OWASP Top 10 Analysis

Checking authentication flows...

Issue 1: Missing rate limiting on login endpoint
  Severity: HIGH
  Risk: Brute-force attacks possible
  File: packages/api/routers/auth.ts:15

Issue 2: Weak password requirements
  Severity: MEDIUM
  Current: Min 8 characters
  Recommended: Min 12 chars + complexity rules

Issue 3: No audit logging for sensitive actions
  Severity: MEDIUM
  Risk: No trace of security events
  Affected: login, password reset, email change
```

**3. Harden**
```
🔧 Step 3: Harden

Implementing rate limiting...
  ✅ 5 login attempts per minute per IP
  ✅ Using @upstash/ratelimit

Strengthening password requirements...
  ✅ Min 12 characters
  ✅ Uppercase + lowercase
  ✅ Numbers + special chars

Adding audit logging...
  ✅ Login events logged
  ✅ Password changes logged
  ✅ Email changes logged
  ✅ Failed login attempts logged
```

**4. Security Tests**
```
🧪 Step 4: Security Tests

Testing authentication security...
  ✅ Should reject unauthenticated requests
  ✅ Should reject weak passwords
  ✅ Should rate limit after 5 attempts
  ✅ Should log security events

All security tests pass ✅
```

**5. Document**
```
📝 Step 5: Document

Creating ADR-050: Authentication Security Hardening
  ✅ Documents all security decisions
  ✅ Lists threat model
  ✅ Explains mitigations

Updating SECURITY.md...
  ✅ Authentication guidelines
  ✅ Password requirements
  ✅ Rate limiting policy

Security review complete! 🛡️
```

---

## Tutorial 5: Using Agent Skills

Sometimes you don't need a full workflow, just a specialized agent for one task.

### Example 1: Architecture Design Only

```
User: "I need help designing the architecture for a notification system"

You: /architect
```

Claude switches to **Architect Mode**:

```
🏗️  Architect Mode Activated

Designing notification system...

Detected level: balanced ⚖️

Balanced 3-Layer Architecture:

Router Layer:
  - packages/api/routers/notification.ts
  - Procedures: send(), list(), markAsRead()

Service Layer:
  - packages/services/notification.service.ts
  - Handles: email, SMS, push notifications
  - Strategy pattern for different notification types

Repository Layer:
  - packages/database/repositories/notification.repository.ts
  - Stores notification history

External Services:
  - Email: Resend
  - SMS: Twilio
  - Push: Expo Notifications (if mobile)

Creating ADR-051: Multi-Channel Notification System
  Decision: Use strategy pattern for extensibility
  Alternatives considered: Event-driven (rejected - overkill for Balanced)
```

### Example 2: Code Review Only

```
User: "Can you review this code?"

You: /reviewer
```

Claude switches to **Reviewer Mode**:

```
👀 Reviewer Mode Activated

Reviewing code against Balanced level rules...

✅ Code Quality:
  ✅ Self-documenting code
  ✅ No inline comments
  ✅ Proper error handling

❌ Violations Found:

1. Function too long
   File: packages/services/order.service.ts:42
   Current: 65 lines
   Max: 50 lines (Balanced)
   Fix: Extract helper functions

2. Too many parameters
   File: packages/services/order.service.ts:15
   Function: createOrder(userId, items, discount, shippingAddress, billingAddress)
   Current: 5 parameters
   Max: 3 parameters (Balanced)
   Fix: Use parameter object

Please address these violations before merging.
```

---

## Tutorial 6: Quick Validations

For quick checks during development, use utility skills:

### Validate Code Quality

```
You: /validate
```

```
✅ Code validates for BALANCED level

Checks:
  ✅ Function length: All < 50 lines
  ✅ Parameters: All < 3 params
  ✅ Type safety: All functions typed
  ⚠️  Duplication: Found in 2 places (acceptable for Balanced)

No blocking issues!
```

### Check Architecture Boundaries

```
You: /guard
```

```
✅ Architecture boundaries OK for BALANCED level

Checks:
  ✅ 3-layer separation
  ✅ No circular dependencies
  ✅ Services don't import routers
  ✅ Repositories don't import services

Architecture is clean!
```

### Check Test Coverage

```
You: /coverage
```

```
✅ Test coverage OK for BALANCED level

Coverage: 75% (required: 70%)

Breakdown:
  ✅ Services: 82%
  ✅ Repositories: 68%
  ✅ Routers: 75%

All requirements met!
```

---

## Best Practices

### 1. Let Skills Auto-Detect

✅ **DO**:
```
"Add user authentication"
```

❌ **DON'T**:
```
"Add user authentication using Balanced level with 3-layer architecture and 70% test coverage"
```

Skills already know!

### 2. Use Workflow Skills for Complete Tasks

✅ **DO**:
```
/feature "Add payment processing"
```

❌ **DON'T** (manually):
```
/architect "Design payment"
/developer "Implement payment"
/tester "Test payment"
/reviewer "Review payment"
```

Workflows handle all steps automatically!

### 3. Use Agent Skills for Specialized Tasks

✅ **DO**:
```
/architect "Design microservices split"
/reviewer "Review this PR"
```

When you ONLY need that specific role.

### 4. Use Utility Skills for Quick Checks

✅ **DO** (during development):
```
/validate
/guard
/coverage
```

Fast feedback loop!

### 5. Trust the Auto-Detection

Skills automatically:
- Detect your project level (rapid/balanced/crafted)
- Apply appropriate rules
- Use correct MCP tools
- Adapt workflows

You don't need to micro-manage!

---

## Troubleshooting

### "Skill not activating"

Make sure you're using the slash syntax:
```
/feature   ✅
feature    ❌
```

### "Wrong level detected"

Check your `.craftedrc.json`:
```json
{
  "level": "balanced",
  "platform": "web"
}
```

### "Want to override auto-detection"

You can specify level:
```
/validate crafted
/guard balanced
```

---

## Next Steps

Now that you've completed the tutorial:

1. 📚 **Read skill docs**: Explore `.claude/skills/README.md`
2. 🎯 **Try on real tasks**: Use skills in your actual project
3. 🔄 **Provide feedback**: What works? What doesn't?
4. 🚀 **Share with team**: Skills make the whole team more productive!

---

## Summary

Crafted Skills transform Claude Code into a **context-aware development partner**:

- **Auto-detects** your project level
- **Adapts** workflows and rules accordingly
- **Orchestrates** all tools automatically
- **Delivers** production-ready code

**No configuration needed. Just describe what you want!**

---

**Questions?**
- Documentation: `.claude/skills/README.md`
- Issues: https://github.com/crafted-saas/issues
- Discord: https://discord.gg/crafted-saas

Happy coding! 🚀
