# Balanced Mode - Pragmatic Quality

**Context**: 3-10 developers, 1-3 years lifespan, 100-10K users, $5K-100K MRR

When this skill is activated, you operate in **BALANCED mode** - pragmatic quality without dogmatism.

## Architecture Rules

### Structure: 3-Layer Architecture

**Layer 1: Routers (tRPC)** - Thin orchestration
- Max 20 lines per procedure
- Validation only (Zod)
- Call services for business logic

**Layer 2: Services** - Business logic
- Pure functions when possible
- Unit tested (70%+ coverage)
- Platform-agnostic (shared web/mobile)
- Max 50 lines per function

**Layer 3: Repositories** - Data access
- Prisma queries
- Complex data operations
- Tested with integration tests

### Code Quality Rules

| Aspect | Rule |
|--------|------|
| Max lines/function | 50 lines |
| Parameters | Max 3 |
| Duplication | > 2 times = extract (⚠️ Review flag) |
| Cyclomatic complexity | < 10 |
| SOLID | Full |
| Comments | WHY required for non-obvious code |

### Testing Strategy

**Coverage**: 70% minimum enforced

**What to test**:
- ✅ Unit tests (100% public methods in services)
- ✅ tRPC routers (happy path + errors)
- ✅ Component tests (critical flows)
- ✅ E2E (auth + checkout)
- ✅ Integration tests (with MSW)

**Test approach**: Test-After Generation (TAG)
1. Generate code + tests in parallel
2. Run tests automatically
3. Fix if fails
4. Validate 70% coverage
5. Refactor if architecture violations
6. Ship when passes

### Typical Structure

```
packages/
├── api/
│   └── routers/
│       └── product.ts              # Thin (< 20 lines)
├── services/
│   ├── product.service.ts          # Business logic
│   └── product.service.test.ts     # Tests
├── database/
│   └── repositories/
│       └── product.repository.ts   # Data access
└── validators/
    └── product.validator.ts        # Zod schemas
```

## MCP Tools to Use

### Context
```typescript
mcp__crafted-context__get_context_summary()
mcp__crafted-context__get_architecture_info() // Confirm level = balanced
```

### Validation (Enforced)
```typescript
mcp__rules-validator__validate_code({
  code: "...",
  level: "balanced" // Will enforce 50 lines, 3 params
})

mcp__rules-validator__check_test_coverage({
  testPath: "packages/services",
  level: "balanced" // Will require 70%
})
```

### Architecture
```typescript
mcp__architecture-guard__check_dependencies({
  filePath: "packages/services/user.service.ts",
  level: "balanced"
})

mcp__architecture-guard__check_layer_boundaries({
  level: "balanced"
})
```

### Development
```typescript
mcp__vitest__run_tests()
mcp__vitest__check_coverage({ threshold: 70 })
mcp__typescript__check_types()
```

## Philosophy

> "Quality where it matters. Pragmatic engineering, not dogmatism."

## Active Craft Principles (12/16)

All from Rapid +
- ✅ Architecture Layered (separation of concerns)
- ✅ Testing 70% coverage
- ✅ Code Review (AI-assisted)
- ✅ Documentation (key decisions)
- ✅ SOLID (all principles applied)
- ✅ Performance (basic optimization)

## When to Use This Skill

Invoke this skill when:
- Growing from MVP to sustainable product
- Team size > 3 developers
- Multi-year product vision
- Need to onboard developers easily

## Example Code Style

```typescript
// ✅ GOOD - Balanced style

// Router: Thin orchestration (< 20 lines)
export const productRouter = createTRPCRouter({
  create: protectedProcedure
    .input(createProductSchema)
    .mutation(async ({ ctx, input }) => {
      return await productService.create(input, ctx.session.user.id);
    }),
});

// Service: Business logic (< 50 lines)
export const productService = {
  async create(data: CreateProductInput, userId: string) {
    const priceInCents = convertToCents(data.price);

    const product = await productRepository.create({
      ...data,
      userId,
      priceInCents,
    });

    await stripeService.createProduct({
      productId: product.id,
      name: product.name,
      priceInCents,
    });

    return product;
  },
};

// Repository: Data access
export const productRepository = {
  async create(data: CreateProductData) {
    return await db.product.create({ data });
  },
};
```

## Commands You Can Run

```bash
# Generate feature with Balanced rules
/feature "Add product catalog"

# Validate architecture
/guard balanced

# Check coverage (must be 70%+)
/coverage balanced

# Run all tests
pnpm test

# Check types
pnpm typecheck
```

## ADR (Architecture Decision Records)

For Balanced level, create ADRs for:
- Major architectural changes
- Technology choices
- Breaking changes

Example:
```markdown
# ADR-001: Use tRPC for API Layer

## Status
Accepted

## Context
Need type-safe API without code generation

## Decision
Use tRPC for end-to-end type safety

## Consequences
- Positive: Full type safety, no codegen
- Negative: Couples frontend/backend deployment
```

## Transitioning to Crafted

When you reach:
- 10K+ users
- $100K+ MRR
- 10+ developers
- 5+ years lifespan

Consider switching to `/crafted` skill for enterprise-grade architecture.
