# Validate - Code Quality Validation

This skill provides quick code quality validation using the rules-validator MCP tool.

## Purpose

Validate code against level-specific rules:
- **Rapid**: Max 100 lines/function, duplication OK < 3 times
- **Balanced**: Max 50 lines/function, max 3 params, 70% coverage
- **Crafted**: Max 20 lines/function, max 2 params, ZERO duplication, 100% domain coverage

## Usage

### Auto-detect level
```bash
/validate
```

The skill will:
1. Detect project level using `get_architecture_info`
2. Validate code against appropriate rules
3. Report violations

### Specify level
```bash
/validate rapid
/validate balanced
/validate crafted
```

### Validate specific file
```bash
/validate balanced packages/services/product.service.ts
```

## What It Checks

### For ALL Levels
- ✅ Self-documenting code
- ✅ No inline comments (WHY only)
- ✅ Type safety
- ✅ Proper naming
- ✅ Error handling

### For Rapid
- ✅ Functions < 100 lines
- ⚠️ Duplication warning if 3+ times
- ✅ Basic error handling

### For Balanced
- ✅ Functions < 50 lines
- ✅ Max 3 parameters
- ⚠️ Duplication flag if > 2 times
- ✅ Cyclomatic complexity < 10
- ✅ 70% test coverage

### For Crafted
- ✅ Functions < 20 lines
- ✅ Max 2 parameters
- ❌ ZERO duplication (CI fails)
- ✅ Cyclomatic complexity < 5
- ✅ 100% domain coverage
- ✅ Domain has ZERO external dependencies

## MCP Tools Used

```typescript
// Detect level
mcp__crafted-context__get_architecture_info()

// Validate code
mcp__rules-validator__validate_code({
  code: fileContent,
  filePath: "packages/services/product.service.ts",
  level: "balanced"
})

// Check coverage
mcp__rules-validator__check_test_coverage({
  testPath: "packages/services",
  level: "balanced"
})
```

## Example Output

### Rapid (Pass)
```
✅ Code validates for RAPID level

Checks:
✅ Function length: 85 lines (< 100)
✅ Type safety: All functions typed
✅ Error handling: Basic try-catch present
⚠️ Duplication: Found in 2 places (OK for Rapid)

No blocking issues. Ready to ship!
```

### Balanced (Violations)
```
❌ Code has violations for BALANCED level

Violations:
❌ Function too long: productService.create() is 65 lines (max 50)
   File: packages/services/product.service.ts:42-107
   Fix: Extract helper functions

❌ Too many parameters: createProduct(name, price, description, category, userId)
   File: packages/services/product.service.ts:15
   Fix: Use parameter object

⚠️ Duplication detected: Price calculation logic repeated 3 times
   Files: product.service.ts:45, order.service.ts:23, cart.service.ts:67
   Fix: Extract calculatePriceWithTax() function

❌ Test coverage: 62% (required: 70%)
   Missing tests for: ProductService.update(), ProductService.delete()

Please fix violations before merging.
```

### Crafted (Critical)
```
❌ CRITICAL: Domain layer has external dependencies!

File: packages/domain/entities/Product.ts
Line: 3
Issue: import { db } from '@/database';

CRAFTED level requires domain layer to have ZERO external dependencies.

This violates hexagonal architecture principles.

Fix:
1. Remove db import from domain
2. Define IProductRepository interface in domain layer
3. Move Prisma implementation to infrastructure layer

Additional violations:
❌ Function too long: Product.create() is 35 lines (max 20)
❌ Too many parameters: Product.create(name, price, category, userId, description)
   Use parameter object with max 2 params

Domain coverage: 85% (required: 100%)
Missing tests for: Product.updatePrice(), Product.publish()
```

## Common Violations & Fixes

### 1. Function Too Long

**Violation**:
```typescript
function processOrder(order) {
  // 80 lines of logic
}
```

**Fix**: Extract functions
```typescript
function processOrder(order: Order): OrderResult {
  validateOrder(order);
  const total = calculateTotal(order);
  return processPayment(order, total);
}
```

### 2. Too Many Parameters

**Violation**:
```typescript
function createUser(name, email, age, city, country) { }
```

**Fix**: Parameter object
```typescript
interface CreateUserInput {
  name: string;
  email: string;
  age: number;
  city: string;
  country: string;
}

function createUser(input: CreateUserInput) { }
```

### 3. Duplication

**Violation**:
```typescript
// In 3 different files
const priceWithTax = price * 1.2;
```

**Fix**: Extract function
```typescript
function calculatePriceWithTax(price: number): number {
  const TAX_RATE = 0.2;
  return price * (1 + TAX_RATE);
}
```

### 4. Inline Comments

**Violation**:
```typescript
// Loop through users
users.forEach(u => process(u))
```

**Fix**: Refactor
```typescript
users.forEach(user => processActiveUser(user))
```

### 5. External Dependency in Domain (Crafted)

**Violation**:
```typescript
// packages/domain/entities/Product.ts
import { db } from '@/database';

export class Product {
  async save() {
    await db.product.create({ ... });
  }
}
```

**Fix**: Repository pattern
```typescript
// packages/domain/repositories/IProductRepository.ts
export interface IProductRepository {
  save(product: Product): Promise<void>;
}

// packages/domain/entities/Product.ts
export class Product {
  // Pure domain logic, no external deps
}

// packages/infrastructure/database/PrismaProductRepository.ts
export class PrismaProductRepository implements IProductRepository {
  async save(product: Product): Promise<void> {
    await db.product.create({ ... });
  }
}
```

## Integration with Workflows

This skill is automatically invoked by:
- `/feature` workflow (Step 2: Implementation validation)
- `/bugfix` workflow (Step 3: Fix validation)
- `/refactor` workflow (Step 5: Validate improvement)
- `/reviewer` workflow (Step 1: Automated checks)

## Tips

1. **Run early and often** - Validate after each significant change
2. **Fix incrementally** - Don't accumulate violations
3. **Use auto-fix when possible** - Extract functions, parameters objects
4. **Level up gradually** - Rapid → Balanced → Crafted

## Commands

```bash
# Auto-detect level and validate
/validate

# Validate for specific level
/validate rapid
/validate balanced
/validate crafted

# Validate specific file
/validate balanced packages/services/product.service.ts

# Validate and show detailed report
/validate crafted --verbose
```

## Exit Codes

- `0` - All checks passed ✅
- `1` - Warnings (won't block CI) ⚠️
- `2` - Violations (blocks CI for Crafted) ❌
