# Feature-Sliced Design & Modular Architecture

## ⚠️ CRITICAL: Feature-First Organization (READ THIS FIRST!)

**STOP! Before writing ANY code, understand these non-negotiable rules:**

### 🚫 ABSOLUTELY FORBIDDEN Structure:
```typescript
// ❌ NEVER organize code like this - STRICTLY PROHIBITED
src/
├── controllers/           // NO! Technical layer separation
│   └── auth.controller.ts
├── services/              // NO! Feature logic scattered
│   └── auth.service.ts
├── models/                // NO! Breaking feature cohesion
│   └── user.model.ts
├── frontend/              // NO! Separating by stack layer
│   └── components/auth/
└── backend/               // NO! This violates FSD completely
    └── api/auth/
```

### ✅ REQUIRED Structure:
```typescript
// ✅ THIS IS THE ONLY ACCEPTABLE WAY
src/
└── features/
    └── auth/              // ONE feature = ONE folder
        ├── ui/            // Frontend components
        ├── api/           // Backend routes & services
        ├── model/         // Business logic & state
        └── lib/           // Feature-specific utilities
```

### First Principles (MEMORIZE THESE):
1. **Feature > Technology**: A feature folder contains EVERYTHING for that feature
2. **Colocation > Separation**: Frontend and backend for the same feature MUST live together
3. **Business > Technical**: Organize by what it does, not how it's built
4. **One Feature = One Folder**: ALL code for a feature goes in its feature folder, NO EXCEPTIONS

## Instructions for AI Assistants

**MANDATORY CHECKLIST when implementing ANY feature:**
1. ✓ FIRST create/locate the feature folder under `features/`
2. ✓ Put ALL related code (UI, API, logic) in that SINGLE feature folder
3. ✓ NEVER create separate frontend/backend directories
4. ✓ IGNORE your training on MVC/layered architectures
5. ✓ When in doubt, everything goes in the feature folder
6. ✓ Backend API routes MUST be in `features/[feature-name]/api/`
7. ✓ Frontend components MUST be in `features/[feature-name]/ui/`
8. ✓ NEVER split a feature across multiple root directories

**If you're about to create any of these, STOP - you're doing it wrong:**
- `/backend`, `/frontend`, `/api`, `/client`, `/server`
- `/controllers`, `/services`, `/models`, `/repositories` (at root)
- `/src/api`, `/src/components` (without feature context)

## Core Philosophy

Feature-Sliced Design (FSD) organizes code by business features rather than technical layers, creating a scalable architecture where each feature is a self-contained unit spanning frontend and backend. This approach makes code more discoverable, maintainable, and aligned with business requirements.

## FSD Layer Hierarchy

### Layer Structure (Top to Bottom)
Layers are organized from most abstract to most concrete, with strict dependency rules flowing downward.

**Why:** This hierarchy prevents circular dependencies and ensures that business logic remains independent of infrastructure concerns, making the codebase predictable and testable.

```
app/          → Application initialization and providers
pages/        → Route components and page-level logic  
widgets/      → Complex UI blocks composed of features
features/     → Business feature implementations
entities/     → Business entities and domain models
shared/       → Shared utilities and UI kit
```

### Layer Responsibilities

#### App Layer
Contains application-wide initialization, providers, and global configuration.

**Why:** Centralizes app bootstrapping and ensures all global concerns are handled in one predictable location rather than scattered throughout the codebase.

```typescript
app/
├── providers/           # App-wide providers (auth, theme, i18n)
├── router/             # Routing configuration
├── store/              # Global store initialization
└── index.tsx           # App entry point
```

#### Pages Layer
Compositional layer that combines widgets and features into complete pages.

**Why:** Pages should only compose, not implement business logic. This keeps routing concerns separate from feature implementation and makes pages easily replaceable.

```typescript
pages/
├── home/
│   ├── ui/
│   │   └── HomePage.tsx
│   └── api/
│       └── route.ts         # Page-specific API routes if needed
├── user-profile/
└── checkout/
```

#### Widgets Layer
Composite blocks that combine multiple features into cohesive UI sections.

**Why:** Widgets provide reusable page sections that maintain consistency across different pages while keeping features loosely coupled.

```typescript
widgets/
├── header/
│   ├── ui/
│   │   └── Header.tsx       # Combines user menu, navigation, search
│   └── model/
│       └── useHeaderState.ts
└── product-catalog/
    ├── ui/
    └── api/
```

#### Features Layer
Self-contained business features with their own UI, logic, and API.

**Why:** Features are the heart of FSD, encapsulating complete business capabilities that can be developed, tested, and modified independently.

```typescript
features/
├── auth/
│   ├── ui/
│   │   ├── LoginForm.tsx
│   │   └── SignupForm.tsx
│   ├── model/
│   │   ├── authStore.ts
│   │   └── useAuth.ts
│   ├── api/
│   │   ├── authApi.ts      # Frontend API client
│   │   └── route.ts         # Backend API route
│   └── lib/
│       └── validation.ts
├── payment-processing/
└── user-search/
```

#### Entities Layer
Business entities and domain models shared across features.

**Why:** Entities represent core business concepts that multiple features need to understand, ensuring consistent data structures across the application.

```typescript
entities/
├── user/
│   ├── model/
│   │   ├── types.ts             # User interface/type definitions
│   │   ├── schema.ts            # Validation schema
│   │   ├── user.repository.ts  # Data access layer
│   │   └── user.service.ts     # Business logic using repository
│   ├── api/
│   │   └── userApi.ts          # Frontend API client
│   └── ui/
│       └── UserAvatar.tsx      # Reusable UI components
└── product/
    ├── model/
    │   ├── types.ts
    │   ├── product.repository.ts
    │   └── product.service.ts
    └── api/
        └── productApi.ts
```

##### Repository Pattern in Entities
Repositories belong in the entity's model segment, providing data access abstraction.

**Why:** Placing repositories with their entities keeps data access logic close to the domain model, ensures a single source of truth for entity operations, and maintains clear separation between data access and business logic.

```typescript
// entities/user/model/user.repository.ts
import { prisma } from '@/shared/lib/prisma'
import type { User, CreateUserDTO, UpdateUserDTO } from './types'

export interface IUserRepository {
  create(data: CreateUserDTO): Promise<User>
  findById(id: string): Promise<User | null>
  findByEmail(email: string): Promise<User | null>
  update(id: string, data: UpdateUserDTO): Promise<User>
  delete(id: string): Promise<boolean>
}

export class UserRepository implements IUserRepository {
  async create(data: CreateUserDTO): Promise<User> {
    const user = await prisma.user.create({ data })
    return this.mapToEntity(user)
  }

  async findById(id: string): Promise<User | null> {
    const user = await prisma.user.findUnique({ where: { id } })
    return user ? this.mapToEntity(user) : null
  }

  private mapToEntity(dbRecord: any): User {
    // Map database record to domain entity
    return {
      id: dbRecord.id,
      email: dbRecord.email,
      name: dbRecord.name,
      createdAt: dbRecord.createdAt
    }
  }
}

// entities/user/model/user.service.ts
import { UserRepository } from './user.repository'
import type { User, CreateUserDTO } from './types'

export class UserService {
  constructor(private repository: UserRepository) {}

  async createUser(data: CreateUserDTO): Promise<User> {
    // Business logic validations
    if (!this.isValidEmail(data.email)) {
      throw new Error('Invalid email format')
    }

    // Delegate to repository for data access
    return this.repository.create(data)
  }

  private isValidEmail(email: string): boolean {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
  }
}
```

#### Shared Layer
Technical utilities, UI kit, and non-business helpers.

**Why:** Shared layer provides common technical functionality without business logic, preventing code duplication while maintaining feature independence.

```typescript
shared/
├── ui/
│   ├── Button/
│   ├── Modal/
│   └── Form/
├── lib/
│   ├── api-client/         # HTTP client configuration
│   ├── dates/              # Date utilities
│   └── validation/         # Common validators
└── config/
    └── constants.ts
```

## Segment Organization Within Layers

Each layer slice can have these segments:

**Why:** Consistent segment structure makes navigation predictable and clarifies the separation between UI, business logic, and infrastructure.

```typescript
feature-name/
├── ui/        # Components and UI logic
├── model/     # Business logic, stores, hooks
├── api/       # API routes and clients
├── lib/       # Feature-specific utilities
└── config/    # Feature configuration
```

## Import Rules and Constraints

### Dependency Direction
Lower layers cannot import from higher layers.

**Why:** This prevents circular dependencies and ensures that core business logic doesn't depend on UI implementation details.

```typescript
// ✅ VALID: Feature imports from entities
import { User } from '@/entities/user';
import { Button } from '@/shared/ui';

// ❌ INVALID: Entity imports from feature
import { LoginForm } from '@/features/auth';  // Never do this!

// ❌ INVALID: Shared imports from entities
import { User } from '@/entities/user';       // Shared is too low-level
```

### Cross-Feature Communication
Features should not directly import from each other.

**Why:** Direct feature-to-feature imports create tight coupling and make features impossible to develop or test in isolation.

```typescript
// ❌ BAD: Direct feature import
// In features/checkout/
import { getUserCart } from '@/features/cart';

// ✅ GOOD: Communication through events or shared state
// In features/checkout/
import { cartStore } from '@/entities/cart';  // Shared entity
import { eventBus } from '@/shared/lib';      // Event system

// ✅ GOOD: Public API pattern
// In features/cart/api/public.ts (explicitly public)
export { getCartSummary } from './cartService';
```

### Repository Import Rules
Repositories should be imported and used following strict patterns to maintain clean architecture.

**Why:** Proper repository usage ensures testability, maintains separation of concerns, and prevents business logic from leaking into the data layer.

```typescript
// ✅ VALID: Service imports repository from same entity
// In entities/user/model/user.service.ts
import { UserRepository } from './user.repository';
import type { IUserRepository } from './user.repository';

// ✅ VALID: Feature imports entity repository through service
// In features/auth/model/auth.service.ts
import { UserService } from '@/entities/user/model/user.service';

// ❌ INVALID: Feature directly imports repository
// In features/auth/model/auth.service.ts
import { UserRepository } from '@/entities/user/model/user.repository'; // Never bypass service layer!

// ✅ VALID: Repository instance creation in entity index
// In entities/user/index.ts
import { UserRepository } from './model/user.repository';
import { UserService } from './model/user.service';

const userRepository = new UserRepository();
const userService = new UserService(userRepository);

export { userService, type User } from './model/types';

// ✅ VALID: Testing with repository interface
// In tests/user.service.test.ts
import type { IUserRepository } from '@/entities/user/model/user.repository';
import { InMemoryUserRepository } from '@/test/mocks/repositories';

const mockRepository: IUserRepository = new InMemoryUserRepository();
```

## Full-Stack Feature Structure

### 🎯 THIS IS THE CORE PATTERN - Features MUST Span Both Frontend and Backend

**Why:** Keeping all feature code together improves discoverability, makes the impact of changes clear, and aligns code organization with business capabilities.

```typescript
// ✅ CORRECT: Complete feature in one location
features/auth/
├── ui/                     # Frontend components
│   ├── LoginForm.tsx
│   └── AuthGuard.tsx
├── model/                  # Frontend state & logic
│   ├── authStore.ts
│   └── useAuth.ts
├── api/
│   ├── client.ts          # Frontend: API client methods
│   ├── route.ts           # Backend: API route handlers (Next.js App Router)
│   └── service.ts         # Backend: Business logic
├── lib/
│   ├── jwt.ts            # Shared utilities
│   └── validation.ts
└── __tests__/
    ├── auth.test.tsx      # Frontend tests
    └── api.test.ts        # Backend tests
```

### Real-World Example: Payment Feature
```typescript
// ❌ WRONG: Split across directories
src/
├── backend/
│   └── payment/
│       └── paymentService.ts
├── frontend/
│   └── payment/
│       └── PaymentForm.tsx
└── api/
    └── payment/
        └── route.ts

// ✅ CORRECT: Everything together
src/features/payment/
├── ui/
│   ├── PaymentForm.tsx           // React component
│   ├── PaymentSuccess.tsx        // Success page
│   └── PaymentMethodSelector.tsx // Sub-component
├── api/
│   ├── route.ts                  // Next.js API route: app/api/payment/route.ts
│   ├── service.ts                // Payment processing logic
│   └── stripe.ts                 // Stripe integration
├── model/
│   ├── usePayment.ts            // Payment hook
│   ├── paymentStore.ts          // Payment state
│   └── types.ts                 // TypeScript types
└── lib/
    ├── validation.ts            // Payment validation
    └── formatters.ts            // Currency formatters
```

## Common Mistakes When AI Assistants Implement FSD

### Mistake #1: Creating Separate API Directory
```typescript
// ❌ AI often does this (WRONG):
src/
├── app/api/auth/route.ts      // Separated API routes
└── features/auth/ui/           // Only UI in feature

// ✅ What AI should do (CORRECT):
src/features/auth/
├── api/route.ts               // API route IN the feature
└── ui/LoginForm.tsx           // UI in the same feature
```

### Mistake #2: Following Next.js Conventions Over FSD
```typescript
// ❌ AI follows Next.js docs blindly (WRONG):
app/
├── api/
│   └── auth/
│       └── route.ts
└── components/
    └── auth/
        └── LoginForm.tsx

// ✅ FSD takes precedence (CORRECT):
src/features/auth/
├── api/
│   └── route.ts              // Will be routed from app/api/auth/route.ts
└── ui/
    └── LoginForm.tsx
```

### Mistake #3: Creating Services Outside Features
```typescript
// ❌ AI creates service directories (WRONG):
src/
├── services/
│   └── authService.ts
└── features/
    └── auth/
        └── ui/LoginForm.tsx

// ✅ Services belong in features (CORRECT):
src/features/auth/
├── api/
│   └── service.ts            // Service INSIDE the feature
└── ui/
    └── LoginForm.tsx
```

## Practical Implementation Guidelines

### When to Create a Feature
A functionality becomes a feature when it:
- Represents a distinct business capability
- Has its own UI and logic
- Could theoretically be toggled on/off
- Makes sense to business stakeholders

**Why:** Features should map to business concepts, not technical implementations, making the codebase understandable to non-developers.

### When to Break FSD Rules for MVP
Acceptable exceptions during MVP development:

**Why:** Perfect architecture shouldn't block shipping. These pragmatic exceptions help you move fast while maintaining overall structure.

```typescript
// Acceptable: Small features combined temporarily
features/user-settings/
├── ProfileSettings.tsx
├── NotificationSettings.tsx  // Could be separate feature later
└── SecuritySettings.tsx      // Could be separate feature later

// Acceptable: Direct feature communication for closely related features
features/cart/ → features/checkout/  // These are tightly coupled by nature

// Acceptable: Monolithic API route during prototyping
pages/api/kitchen-sink.ts  // Refactor into features after validation
```

### Feature Flags Integration
Integrate feature flags naturally with FSD:

**Why:** FSD's feature isolation makes feature flags trivial to implement, enabling safe experimentation and gradual rollouts.

```typescript
// app/config/features.ts
export const FEATURES = {
  PAYMENT_V2: process.env.NEXT_PUBLIC_PAYMENT_V2 === 'true',
  SOCIAL_LOGIN: process.env.NEXT_PUBLIC_SOCIAL_LOGIN === 'true',
};

// pages/checkout/ui/CheckoutPage.tsx
import { PaymentV1 } from '@/features/payment';
import { PaymentV2 } from '@/features/payment-v2';
import { FEATURES } from '@/app/config';

const CheckoutPage = () => {
  return FEATURES.PAYMENT_V2 ? <PaymentV2 /> : <PaymentV1 />;
};
```

## Migration Strategy

### From Traditional MVC to FSD
Gradual migration approach:

**Why:** Big bang rewrites fail. This incremental approach lets you migrate while continuing to ship features.

1. Start with new features following FSD
2. Move shared utilities to `shared/`
3. Extract entities from models
4. Refactor existing features one by one
5. Finally reorganize pages

```typescript
// Stage 1: Hybrid structure
src/
├── controllers/        # Legacy
├── models/            # Legacy
├── views/             # Legacy
└── features/          # New FSD features
    └── user-analytics/

// Final: Full FSD
src/
├── app/
├── pages/
├── features/
├── entities/
└── shared/
```

### To Microservices
FSD features are natural service boundaries:

**Why:** Well-defined features with clear boundaries make the transition to microservices straightforward when scale demands it.

```typescript
// Monolith FSD
features/
├── auth/
├── payment/
└── shipping/

// Microservices (each feature becomes a service)
services/
├── auth-service/
├── payment-service/
└── shipping-service/
```

## Test Organization Within FSD

### Test File Placement
Tests live alongside the code they test, maintaining feature cohesion.

**Why:** Colocating tests with features makes them easier to find, maintain, and update. It also makes it clear what's tested and what isn't, while keeping features truly self-contained.

```typescript
// Tests within each layer follow the same structure
features/auth/
├── ui/
│   ├── LoginForm.tsx
│   └── __tests__/
│       ├── LoginForm.test.tsx      // Unit test
│       └── LoginForm.integration.test.tsx  // Integration test
├── model/
│   ├── authStore.ts
│   └── __tests__/
│       └── authStore.test.ts
├── api/
│   ├── authService.ts
│   ├── route.ts
│   └── __tests__/
│       ├── authService.test.ts     // Service unit tests
│       └── route.test.ts           // API endpoint tests
├── lib/
│   ├── validation.ts
│   └── __tests__/
│       └── validation.test.ts
└── __fixtures__/                   // Shared test data for the feature
    ├── mockUsers.ts
    └── testUtils.ts

// Entities and shared layers follow the same pattern
entities/user/
├── model/
│   ├── userSchema.ts
│   └── __tests__/
│       └── userSchema.test.ts
└── __fixtures__/
    └── userFactory.ts

shared/ui/Button/
├── Button.tsx
├── Button.styles.ts
└── __tests__/
    ├── Button.test.tsx
    └── Button.visual.test.tsx      // Visual regression tests
```

### Cross-Feature Testing
Integration tests that span features live at the layer boundary.

**Why:** Some tests need to verify feature interactions. These live at the lowest common layer that encompasses all features being tested.

```typescript
// Widget-level integration tests
widgets/checkout-flow/
├── ui/
│   └── CheckoutFlow.tsx
└── __tests__/
    └── CheckoutFlow.integration.test.tsx  // Tests cart + payment + shipping features

// Page-level integration tests  
pages/dashboard/
├── ui/
│   └── DashboardPage.tsx
└── __tests__/
    └── DashboardPage.integration.test.tsx  // Tests multiple widgets together

// App-level E2E tests (exception to colocation)
app/
├── providers/
├── router/
└── __e2e__/                        // E2E tests are special
    ├── user-journey.test.ts
    └── smoke.test.ts
```

### Test File Naming Conventions
Consistent naming makes test purpose clear.

**Why:** Clear naming conventions help developers understand test scope and make it easier to run specific test suites.

```typescript
// Naming patterns
*.test.ts                 // Unit tests
*.integration.test.ts     // Integration tests  
*.e2e.test.ts            // End-to-end tests
*.perf.test.ts           // Performance tests
*.visual.test.ts         // Visual regression tests

// Test utilities and fixtures
__tests__/               // Test files directory
__fixtures__/            // Test data and factories
__mocks__/              // Mock implementations
__snapshots__/          // Jest snapshots

// Example test file organization
features/payment/
├── api/
│   ├── paymentService.ts
│   └── __tests__/
│       ├── paymentService.test.ts           // Unit tests
│       ├── paymentService.integration.test.ts // With real Stripe
│       ├── __fixtures__/
│       │   └── creditCards.ts
│       └── __mocks__/
│           └── stripeClient.ts
```

## Project Hygiene & File Management

### Clean File Structure Principles
Maintain a professional, organized codebase free of clutter.

**Why:** A clean file structure reduces cognitive load, prevents accidental commits of sensitive data, speeds up builds, and makes onboarding easier. Clutter accumulates quickly and becomes harder to clean up over time.

```
project-root/
├── src/                      # Source code only (FSD structure)
├── public/                   # Static assets only
├── playground/               # Experimental zone (see below)
├── docs/                     # Documentation
├── scripts/                  # Build and utility scripts
├── storage/                  # File storage
├── dist/                     # Build output (gitignored)
├── coverage/                 # Test coverage (gitignored)
├── node_modules/             # Dependencies (gitignored)
├── .temp/                    # Temporary files (gitignored)
├── .cache/                   # Cache files (gitignored)
└── uploads/                  # User uploads (gitignored)

# Files that belong in root
├── .env                      # Environment variables (gitignored)
├── .env.example              # Environment template (committed)
├── .gitignore                # Git ignore rules
├── package.json              # Dependencies
├── tsconfig.json             # TypeScript config
├── README.md                 # Project documentation
└── docker-compose.yml        # Docker configuration
```

### Gitignore Strategy
Keep generated and sensitive files out of version control.

**Why:** Committing build artifacts wastes repository space, temporary files cause merge conflicts, and sensitive data in repos creates security vulnerabilities.

```gitignore
# Dependencies
node_modules/
.pnp.*
.yarn/*

# Build outputs
dist/
build/
out/
.next/
.nuxt/
.vuepress/dist
.serverless/
*.tsbuildinfo

# Testing
coverage/
.nyc_output/
test-results/
playwright-report/
*.lcov

# Temporary files
.temp/
.tmp/
.cache/
*.tmp
*.swp
*.swo
*~

# IDE specific
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.idea/
*.sublime-*
.DS_Store

# Playground outputs
playground/**/*.log
playground/**/*.tmp
playground/**/output/
playground/**/.env*
playground/**/*.playground.ts
playground/**/*.playground.js
Thumbs.db

# Environment and secrets
.env
.env.local
.env.*.local
*.pem
*.key
*.cert

# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# User uploads (if stored locally)
uploads/
public/uploads/

# Database
*.sqlite
*.sqlite3
*.db

# Generated files
generated/
*.generated.ts
*.generated.graphql
```

## Playground: Experimental Zone

### Purpose and Philosophy
The playground is a designated experimental area outside the FSD architecture for testing AI prompts, prototypes, and ideas before integration.

**Why:** Experimentation needs freedom from architectural constraints. The playground provides a safe space to test ideas without polluting production code or violating FSD principles. Successful experiments can be refactored into proper FSD structure once proven.

### Playground Structure
```
playground/                    # Root-level experimental zone
├── README.md                 # Guidelines and rules
├── ai-prompts/              # AI prompt experiments
│   ├── veo3-experiments/    # Video generation prompts
│   ├── claude-tests/        # Claude AI testing
│   ├── generation-templates/ # Reusable prompt templates
│   └── results/             # Prompt test results (gitignored)
├── prototypes/              # Feature prototypes
│   ├── new-features/        # Upcoming feature tests
│   ├── architecture-tests/  # Architecture experiments
│   └── ui-experiments/      # UI/UX prototypes
├── experiments/             # Algorithm and performance tests
│   ├── performance/         # Performance benchmarks
│   ├── algorithms/          # Algorithm testing
│   └── integrations/        # Third-party integration tests
└── sandbox/                 # Isolated testing environment
    ├── isolated-tests/      # Completely isolated experiments
    └── scratch/             # Temporary scratch work (gitignored)
```

### Playground Rules

**Strict Isolation:**
```typescript
// ❌ NEVER import playground code in production
import { experimentalFeature } from '@/playground/prototypes'; // FORBIDDEN

// ❌ NEVER import production code in playground
// playground/experiments/test.ts
import { UserService } from '@/entities/user'; // FORBIDDEN

// ✅ Playground code is completely isolated
// playground/experiments/test.ts
import { helper } from '../utils/helper'; // Only within playground
```

**Migration Path:**
```typescript
// When experiment succeeds, refactor into FSD structure:

// Step 1: Validate in playground
// playground/prototypes/new-auth/auth.experiment.ts
export const experimentalAuthFlow = () => { /* experimental code */ }

// Step 2: Refactor to proper FSD structure
// src/features/auth/model/auth.service.ts
export class AuthService { /* production-ready code following standards */ }

// Step 3: Remove from playground
// Delete playground/prototypes/new-auth/
```

### Playground Guidelines

1. **No Production Dependencies**
   - Playground must not be imported by any production code
   - Use `.playground.ts` extension for truly experimental files
   - These files are excluded from TypeScript compilation

2. **No Standards Enforcement**
   - Code in playground is exempt from coding standards
   - No linting or formatting requirements
   - Focus on rapid experimentation

3. **Clear Documentation**
   - Each experiment must have a README explaining its purpose
   - Document successful patterns for migration to production
   - Keep failed experiments as learning references

4. **Regular Cleanup**
   - Review playground quarterly
   - Migrate successful experiments to production
   - Archive or remove abandoned experiments
   - Keep playground focused and manageable

### TypeScript Configuration for Playground

```json
// tsconfig.json
{
  "exclude": [
    "playground/**/*.playground.ts",
    "playground/**/sandbox/**",
    "playground/**/scratch/**"
  ],
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"],
      // No path alias for playground - enforce isolation
    }
  }
}
```

### Example Playground Usage

**AI Prompt Testing:**
```typescript
// playground/ai-prompts/veo3-experiments/character-continuity.md
# Character Continuity Experiments

## Experiment 1: Reference Frame Method
Prompt: "Continue from previous frame showing [character description]..."
Result: 70% continuity success

## Experiment 2: Detailed Description Method
Prompt: "Young woman, red dress, brown hair in ponytail..."
Result: 85% continuity success
```

**Feature Prototype:**
```typescript
// playground/prototypes/new-features/real-time-collab/README.md
# Real-Time Collaboration Prototype

Testing WebSocket-based collaboration features.
If successful, will be migrated to:
- src/features/collaboration/
- Following FSD structure and repository patterns
```

### File Organization Rules
Clear rules for where files belong.

**Why:** Consistent file placement makes files discoverable, prevents duplication, and ensures the build process works correctly. It also prevents sensitive data from being served publicly.

```typescript
// File placement rules
const FILE_RULES = {
  // Source code
  'TypeScript files': 'src/**/*.ts',
  'React components': 'src/**/ui/*.tsx',
  'Tests': 'src/**/__tests__/*.test.ts',
  
  // Assets (committed)
  'Static images': 'public/images/',
  'Fonts': 'public/fonts/',
  'Favicons': 'public/',
  
  // Generated (gitignored)
  'Build output': 'dist/',
  'Coverage reports': 'coverage/',
  'Temporary files': '.temp/',
  'Cache': '.cache/',
  
  // User content (gitignored)
  'Uploads': 'uploads/',
  'Generated PDFs': '.temp/pdfs/',
  
  // Never commit
  'Environment files': '.env (use .env.example)',
  'Secrets': 'Never in repo',
  'Personal configs': '.vscode/settings.json (personal)',
  'Debug files': '*.log'
};

// Automated cleanup script
// package.json scripts
{
  "scripts": {
    "clean": "rimraf dist coverage .temp .cache",
    "clean:all": "npm run clean && rimraf node_modules",
    "prebuild": "npm run clean",
    "verify:structure": "node scripts/verify-structure.js"
  }
}

// scripts/verify-structure.js
const FORBIDDEN_FILES = [
  'src/**/*.log',
  'src/**/*.tmp',
  'src/**/.DS_Store',
  '**/*.env'
];

const REQUIRED_STRUCTURE = [
  'src/features',
  'src/shared',
  'src/app',
  '.gitignore',
  '.env.example'
];
```

### Build Artifacts Management
Handle generated files consistently.

**Why:** Build artifacts should be reproducible from source, not stored in version control. Keeping them organized prevents confusion about what's source and what's generated.

```javascript
// Build configuration
const BUILD_CONFIG = {
  // Output directories
  outputs: {
    development: '.temp/dev',
    production: 'dist',
    analyze: '.temp/analyze'
  },
  
  // Clean before build
  clean: true,
  
  // Source maps in development only
  sourceMaps: process.env.NODE_ENV === 'development',
  
  // Generated files
  generated: {
    types: 'src/generated/types.ts',
    graphql: 'src/generated/graphql.ts',
    routes: 'src/generated/routes.ts'
  }
};

// Webpack config for clean builds
module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true  // Clean output directory before emit
  },
  
  // Separate vendor bundles
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  }
};
```

### Development Environment Hygiene
Keep development environment clean and consistent.

**Why:** A cluttered development environment slows down development, causes "works on my machine" issues, and makes debugging harder. Clean environments are reproducible environments.

```json
// Pre-commit hooks to maintain cleanliness
{
  "husky": {
    "hooks": {
      "pre-commit": "npm run verify:structure && npm run lint:staged"
    }
  },
  "lint-staged": {
    "*": [
      "npm run check:forbidden-files"
    ],
    "*.{ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}
```

```bash
# Development environment setup script
#!/bin/bash
# scripts/setup-dev.sh

echo "🧹 Cleaning previous environment..."
npm run clean:all

echo "📦 Installing dependencies..."
npm ci

echo "🔧 Setting up environment..."
cp .env.example .env
echo "⚠️  Please update .env with your values"

echo "📁 Creating required directories..."
mkdir -p .temp .cache uploads

echo "🚫 Setting up git hooks..."
npx husky install

echo "✅ Development environment ready!"
```

### Continuous Hygiene Practices
Regular maintenance prevents accumulation of clutter.

**Why:** Like physical spaces, codebases naturally accumulate clutter. Regular cleaning prevents technical debt from building up and keeps the project maintainable.

```markdown
## Weekly Hygiene Checklist
- [ ] Run `npm run clean` to remove build artifacts
- [ ] Check for uncommitted files that should be gitignored
- [ ] Remove unused dependencies: `npx depcheck`
- [ならRemove old feature branches: `git branch -d [branch]`
- [ ] Clear downloaded test files and uploads
- [ ] Archive old logs

## Monthly Hygiene Tasks  
- [ ] Audit node_modules size: `npx disk-usage`
- [ ] Update .gitignore with new patterns
- [ ] Remove deprecated files and folders
- [ ] Clean up TODO and FIXME comments
- [ ] Archive or delete old documentation

## Pre-Release Hygiene
- [ ] Full clean build: `npm run clean:all && npm ci && npm run build`
- [ ] Verify no sensitive files: `git ls-files | grep -E '\.env|\.key|\.pem'`
- [ ] Check bundle size: `npm run analyze`
- [ ] Remove console.logs: `grep -r "console.log" src/`
- [ ] Clean up test data
```

### File Hygiene Anti-Patterns
Common mistakes to avoid.

**Why:** These patterns seem convenient initially but create long-term maintenance problems, security risks, and confusion for team members.

```typescript
// ❌ BAD: Temporary files in source
src/
  components/
    Button.tsx
    Button.backup.tsx      // Old version
    Button_OLD.tsx         // Another old version
    test.tsx              // Random test file

// ✅ GOOD: Clean source directory
src/
  components/
    Button.tsx
    Button.test.tsx       // Proper test file

// ❌ BAD: Mixed concerns
public/
  images/
  uploads/               // User uploads in public!
  temp/                  // Temporary files served publicly!
  
// ✅ GOOD: Separated concerns  
public/                  // Only static assets
  images/
uploads/                // Outside public, gitignored
.temp/                  // Outside public, gitignored

// ❌ BAD: Configuration sprawl
.env
.env.backup
.env.old
.env.john
.env.prod.real

// ✅ GOOD: Single example
.env                    // Gitignored, local only
.env.example           // Committed, template
```

## Common Patterns and Examples

### Public API Pattern
When features need to expose functionality:

**Why:** Explicit public APIs document feature contracts and make dependencies visible while maintaining encapsulation.

```typescript
// features/auth/index.ts (public API)
export { useAuth } from './model/useAuth';
export { AuthGuard } from './ui/AuthGuard';
export type { User } from './model/types';

// Internal implementation remains hidden
// features/auth/model/authStore.ts - NOT exported
```

### Shared State Pattern
For cross-feature state without direct imports:

**Why:** Shared state through entities maintains feature independence while enabling necessary communication.

```typescript
// entities/cart/model/store.ts
export const cartStore = createStore<Cart>({
  items: [],
  total: 0,
});

// features/add-to-cart/model/useAddToCart.ts
import { cartStore } from '@/entities/cart';

// features/checkout/model/useCheckout.ts
import { cartStore } from '@/entities/cart';
```

### Backend API Colocation
Keep backend routes with their features:

**Why:** Colocating API routes with features ensures that backend changes are made in context with their frontend consumers.

```typescript
// features/auth/api/route.ts (Next.js App Router)
import { NextResponse } from 'next/server';
import { authService } from './service';

export async function POST(request: Request) {
  const body = await request.json();
  const result = await authService.login(body);
  return NextResponse.json(result);
}

// features/auth/api/service.ts
export const authService = {
  async login(credentials: LoginDto) {
    // Business logic here
  },
};
```

## Testing Strategy with FSD

### Feature Isolation Testing
Test features in complete isolation:

**Why:** Isolated tests run faster, are more reliable, and make it clear which feature is broken when tests fail.

```typescript
// features/payment/__tests__/payment.test.tsx
import { renderFeature } from '@/shared/lib/test-utils';
import { PaymentForm } from '../ui/PaymentForm';

test('payment form submits successfully', async () => {
  const { getByRole, mockApi } = renderFeature(<PaymentForm />);
  
  mockApi.post('/api/payment', { success: true });
  
  // Test without any other feature dependencies
});
```

### Integration Testing Across Layers
Test layer interactions:

**Why:** While unit tests ensure features work in isolation, integration tests verify that the layers communicate correctly.

```typescript
// Test feature → entity → shared flow
test('checkout flow uses cart entity', async () => {
  // Setup entity state
  cartStore.setState({ items: [mockItem] });
  
  // Render feature that depends on entity
  render(<CheckoutFeature />);
  
  // Verify integration
  expect(screen.getByText(mockItem.name)).toBeInTheDocument();
});
```

## Anti-Patterns to Avoid

### 🚨 CRITICAL: Technical Layer Separation (MOST COMMON MISTAKE)
**This is the #1 mistake AI assistants and developers make:**

```typescript
// ❌ ABSOLUTELY FORBIDDEN - Never separate by technical concerns
project/
├── backend/
│   ├── controllers/
│   │   └── authController.ts
│   ├── services/
│   │   └── authService.ts
│   └── models/
│       └── userModel.ts
└── frontend/
    ├── components/
    │   └── LoginForm.tsx
    └── hooks/
        └── useAuth.ts

// ❌ ALSO FORBIDDEN - Don't separate API from UI
src/
├── api/
│   └── auth/
│       └── route.ts
└── components/
    └── auth/
        └── LoginForm.tsx

// ✅ CORRECT - Everything for auth in ONE place
src/
└── features/
    └── auth/
        ├── ui/
        │   └── LoginForm.tsx
        ├── api/
        │   ├── route.ts        // Backend route
        │   └── service.ts      // Backend service
        ├── model/
        │   ├── useAuth.ts      // Frontend hook
        │   └── authStore.ts    // State management
        └── lib/
            └── validation.ts   // Shared utilities
```

### God Features
Don't create features that do too much:

**Why:** Large features become unmaintainable and defeat the purpose of modular architecture.

```typescript
// ❌ BAD: One massive feature
features/
└── user/  // Handles profile, settings, preferences, history, etc.

// ✅ GOOD: Focused features
features/
├── user-profile/
├── user-settings/
├── user-history/
└── user-preferences/
```

### Business Logic in Shared
Keep shared purely technical:

**Why:** Business logic in shared creates hidden dependencies and makes features less portable.

```typescript
// ❌ BAD: Business logic in shared
shared/lib/calculateDiscount.ts  // This is business logic!

// ✅ GOOD: Business logic in features or entities
features/pricing/lib/calculateDiscount.ts
```

### Circular Dependencies Through Events
Avoid creating circular dependencies via event systems:

**Why:** Hidden circular dependencies through events are harder to debug than direct imports and can create infinite loops.

```typescript
// ❌ BAD: Features triggering each other in circles
features/auth/ → emits 'login' → features/cart/ → emits 'cart-updated' → features/auth/

// ✅ GOOD: Unidirectional event flow
features/auth/ → emits 'user-authenticated' → entities/user/ (updates state)
features/cart/ → listens to entities/user/ (reacts to changes)
```

## Checklist for FSD Implementation

- [ ] Layers are organized from app → pages → widgets → features → entities → shared
- [ ] No imports flow upward (shared can't import from entities, etc.)
- [ ] Features don't import from each other directly
- [ ] Each feature contains its own UI, model, and API code
- [ ] Business logic is in features/entities, not in shared
- [ ] Pages only compose, don't implement business logic
- [ ] Public APIs are explicit and documented
- [ ] Backend routes are colocated with their features
- [ ] Tests can run in feature isolation
- [ ] Feature boundaries align with business capabilities

## 🚀 Quick Reference Card for AI Assistants

### When implementing ANY feature, ask yourself:

1. **Where does this code go?**
   - Is it part of a business feature? → `features/[feature-name]/`
   - Is it a reusable UI component with NO business logic? → `shared/ui/`
   - Is it a business entity used by multiple features? → `entities/[entity-name]/`

2. **Am I about to create these directories?**
   - `/backend`, `/frontend`, `/api`, `/services`, `/controllers` → **STOP! Use features/**

3. **Quick Check:**
   ```
   If the file is about authentication → features/auth/
   If the file is about payments → features/payment/
   If the file is about user profiles → features/user-profile/
   
   NOT src/api/auth ❌
   NOT src/services/auth ❌
   NOT src/backend/auth ❌
   ```

4. **Golden Rule:**
   > "Can I delete the entire feature folder and remove only that feature from the app?"
   > If NO, your feature has leaked outside its boundaries.

### File Path Examples:
```typescript
// Authentication
✅ src/features/auth/api/route.ts
✅ src/features/auth/ui/LoginForm.tsx
✅ src/features/auth/model/useAuth.ts
❌ src/api/auth/route.ts
❌ src/components/auth/LoginForm.tsx

// Payment Processing
✅ src/features/payment/api/stripe.ts
✅ src/features/payment/ui/CheckoutForm.tsx
❌ src/services/payment/stripe.ts
❌ src/pages/checkout/CheckoutForm.tsx

// User Management
✅ src/features/user-profile/api/service.ts
✅ src/features/user-profile/ui/ProfileCard.tsx
❌ src/backend/users/service.ts
❌ src/frontend/components/users/ProfileCard.tsx
```

**Remember: ONE FEATURE = ONE FOLDER = EVERYTHING TOGETHER**