---
applyTo: '**'
---

#  GEMINI – Code Quality Standards (AGENT EDITION)

**Pragmatic, fast, no bureaucracy. Just ship code.**

---

## ⚡ Quick Start (30 seconds)

1. Know your pattern (table below)
2. Check property names (table below)
3. Find related files (1 grep command)
4. Build it
5. Done

### 📍 File Locations (Pattern - Copy This)

```
apps/web/src/modules/{domain}/
  ├── components/{Name}.vue          # UI
  ├── pages/{Name}Page.vue           # Routes
  ├── services/{domain}Service.ts    # API calls
  ├── stores/{domain}Store.ts        # Pinia
  └── composables/use{Name}.ts       # Hooks

apps/api/src/modules/{domain}/
  ├── {domain}.routes.ts             # Routes
  ├── {domain}.controller.ts         # Handlers
  ├── {domain}.service.ts            # Logic
  ├── {domain}.repository.ts         # DB
  └── {domain}.schemas.ts            # Validation

packages/
  ├── types/src/{domain}.types.ts
  └── validators/src/{domain}.validators.ts
```

**Domains:** `planner`, `ai`, `collab`, `offline`, `auth`, `gamification`, `map`, `sharing`, `search`, `admin`

###  Modules (Complete List)

| Module | Frontend | Backend | Purpose | Persistence |
|--------|----------|---------|---------|-------------|
| planner | ✅ | ✅ | Core planning (plans/stages CRUD) | CRUD (Firestore) |
| ai | ✅ | ✅ | POI suggestions (OpenAI) | CRUD (Firestore) |
| collab | ✅ | ✅ | Real-time collaboration (Yjs) | CRDT (Redis + Firestore) |
| offline | ✅ | ❌ | PWA + IndexedDB sync | IndexedDB only |
| gamification | ✅ | ✅ | Points/badges/leaderboard | CRUD (Firestore) |
| map | ✅ | ❌ | Mapbox integration | Frontend only |
| auth | ✅ | ✅ | Auth0 authentication | Firebase Auth |
| sharing | ✅ | ✅ | Public/private shares | CRUD (Firestore) |
| search | ✅ | ✅ | Full-text search + discovery | CRUD (Firestore) |
| admin | ✅ | ✅ | Admin dashboard | CRUD (Firestore) |

### 🎯 Core Architecture (Rules, Not Suggestions)

| Rule | Implementation |
|------|----------------|
| NO WebSocket | Use HTTP polling (10-60s) |
| CRUD mode (90%) | Firestore = source of truth |
| CRDT mode (10%) | Redis + Yjs for collab |
| Backend layers | controller → service → repo |
| Persistence | One mode per feature |
| Security | Always validate + auth |
| Pagination | Cursor-based, never offset |

### Core Types (MEMORIZE THESE)

**Plan Type:**
```typescript
interface Plan {
  id: string
  userId: string
  name: string              // ✅ USE THIS (not title)
  description?: string
  coverImage?: string
  isPublic: boolean
  tags: string[]
  createdAt: Date
  updatedAt: Date
}
```

**Stage Type:**
```typescript
interface Stage {
  id: string
  planId: string
  name: string              // ✅ USE THIS (not title)
  notes?: string            // ✅ USE THIS (not description)
  location: Location        // ✅ Nested object
  estimatedArrival?: Date
  actualArrival?: Date
  order: number
  completedAt?: Date
}
```

**Location Type:**
```typescript
interface Location {
  address: string           // ✅ stage.location.address
  coordinates: {
    lat: number
    lng: number
  }
  placeId?: string
  name?: string
}
```

**Common Property Mistakes:**

| ❌ WRONG | ✅ CORRECT | Type |
|----------|-----------|------|
| `plan.title` | `plan.name` | Plan |
| `stage.title` | `stage.name` | Stage |
| `stage.description` | `stage.notes` | Stage |
| `stage.address` | `stage.location.address` | Stage |
| `stage.origin` | ❌ REMOVED | Stage |
| `stage.destination` | ❌ REMOVED | Stage |
| `result.thumbnail` | `result.coverImage` | SearchResult |

### 🏗️ Architecture Decisions (WHY + HOW)

| Decision | Reason | Implementation | Impact |
|----------|--------|----------------|--------|
| ❌ NO WebSocket | Mobile disconnections at 130km/h | HTTP polling (10s-60s adaptive) | +30% battery life |
| ✅ CRDT (Yjs) | Conflict-free collab | Y.Doc in Redis + IndexedDB | Real-time sync |
| ✅ Y.Doc Compression | Redis memory optimization | gzip (-90% size) | -80% Redis costs |
| ✅ Adaptive Sync | Battery optimization | 10s-60s based on queue | -60% network calls |
| ✅ IndexedDB First | Offline-first | Dexie.js + sync queue | Instant UI |
| ✅ Firestore | Source of truth (CRUD) | Admin SDK + batch writes | Consistency |
| ✅ Redis | CRDT state + cache | Compression enabled | Performance |

### 📦 Tech Stack

| Layer | Technology | Version | Purpose |
|-------|-----------|---------|---------|
| Frontend Framework | Vue 3 | 3.5.12 | Composition API |
| State Management | Pinia | 2.2.0 | Store per domain |
| UI Framework | Quasar | 2.17.0 | Material Design |
| Map Engine | Mapbox GL JS | 3.7.0 | Interactive maps |
| CRDT Engine | Yjs | 13.6.0 | Collaboration |
| Offline Storage | Dexie | 4.0.0 | IndexedDB |
| Backend Framework | Fastify | 5.1.0 | High performance |
| Database | Firestore | - | Document store |
| Cache/Queue | Redis | 7.x | CRDT + cache |
| Validation | Zod | 3.23.0 | Runtime validation |
| Monorepo | Turborepo | 2.2.3 | Build caching |
| Language | TypeScript | 5.6.0 | Type safety |

### Find Files Commands (Copy-Paste Ready)

```bash
# Find component usages
grep -r "import.*ComponentName" apps/web/src/

# Find endpoint usages
grep -r "POST.*plans" apps/api/src/

# Find type usages
grep -r "interface Plan" packages/types/

# Find store actions
grep -r "createPlan\|updatePlan" apps/web/src/

# Check for wrong property names
grep -r "plan\.title\|stage\.description" apps/web/src/

# Find all components in a domain
find apps/web/src/modules/planner -name "*.vue"

# Find all services
find apps/web/src/modules -name "*Service.ts"
```

### 🔄 Data Flow Patterns

**CRUD Mode (90% of features):**
```
User Action → IndexedDB (instant, optimistic)
                ↓
          Sync Queue (background)
                ↓
         API Endpoint
                ↓
          Firestore ✅ SOURCE OF TRUTH
                ↓
         Response → Update IndexedDB cache
```

**CRDT Mode (10% - Collaboration only):**
```
User Edit → Y.Doc (local CRDT)
              ↓
          Redis (sync, compressed)
              ↓
       Other Clients (real-time)
              ↓
    Firestore Snapshot (every 5 min, backup)
```

**Rule:** Each feature uses ONE mode. DON'T MIX!

---

# Find type usages
grep -r "interface Plan" packages/types/

# Find store actions
grep -r "createPlan\|updatePlan" apps/web/src/

# Check for wrong property names
grep -r "plan\.title\|stage\.description" apps/web/src/
```

---

## 🎯 SESSION START PROTOCOL (MANDATORY - 2 MIN MAX)

**BEFORE ANY CODE CHANGE:**

1. **Scan CRITICAL KNOWLEDGE Above** (1 min)
   - File locations (where to find things)
   - Core types (Plan, Stage, Location)
   - Common mistakes (plan.title → plan.name)
   - Architecture decisions (CRUD vs CRDT)
   - Data flow patterns

2. **Check Related Files** (30 sec)
   ```bash
   # Find what depends on the file you're editing:
   grep -r "import.*YourComponent" apps/web/src/
   grep -r "YourEndpoint" apps/api/src/
   ```

3. **Validate Before Edit** (30 sec)
   ```bash
   pnpm type-check                    # Check current state
   ./scripts/validate-quality.sh      # Check code quality (optional)
   ```

**WHY:** 90% of bugs come from NOT checking related files first.

**FOR DEEP DIVE (optional):** Read `docs/core/agent.md` for 600+ lines complete reference.

---

## 📋 Code Standards

✅ Enterprise-quality code (production-ready)
✅ Verify end-to-end logic (trace full call chain)
✅ No dangling references or half-finished code
✅ Comment complex logic inline (WHY, not WHAT)
✅ Build validation: `pnpm build` (fix root cause, NOT silence errors)
✅ Check related files BEFORE editing (5-10 files minimum)

---

## 🔒 Type Safety Rule (CRITICAL - READ FIRST)

**⚠️ EMBEDDED REFERENCE - NO EXTERNAL READS NEEDED**

### Property Names (MEMORIZE THIS TABLE)

| ❌ WRONG | ✅ CORRECT | Type | Reason |
|----------|-----------|------|---------|
| `plan.title` | `plan.name` | Plan | Property doesn't exist |
| `stage.title` | `stage.name` | Stage | Property doesn't exist |
| `stage.description` | `stage.notes` | Stage | Property doesn't exist |
| `stage.address` | `stage.location.address` | Stage | Nested object |
| `stage.origin` | ❌ REMOVED | Stage | Use route calculation |
| `stage.destination` | ❌ REMOVED | Stage | Use route calculation |
| `result.thumbnail` | `result.coverImage` | SearchResult | Property doesn't exist |
| `author.displayName` | `author.name` | User | Property doesn't exist |
| `user.name` | `user.displayName` | UserProfile | Different context |

### Complete Type Definitions

**Plan Type:**
```typescript
interface Plan {
  id: string
  userId: string
  name: string              // ✅ USE THIS (not title)
  description?: string
  coverImage?: string
  isPublic: boolean
  tags: string[]
  createdAt: Date
  updatedAt: Date
}
```

**Stage Type:**
```typescript
interface Stage {
  id: string
  planId: string
  name: string              // ✅ USE THIS (not title)
  notes?: string            // ✅ USE THIS (not description)
  location: Location        // ✅ Nested object
  estimatedArrival?: Date
  actualArrival?: Date
  order: number
  completedAt?: Date
}
```

**Location Type:**
```typescript
interface Location {
  address: string           // ✅ stage.location.address
  coordinates: {
    lat: number
    lng: number
  }
  placeId?: string
  name?: string
}
```

**Package Import (CRITICAL):**
```typescript
// ✅ CORRECT
import { Plan, Stage, Location } from '@my-roadtrip/types'

// ❌ WRONG (note the dash)
import { Plan, Stage } from '@my-road-trip/types'
```

### Pre-Edit Commands (30 seconds)

```bash
# Check if type exists
grep -r "export interface TypeName" packages/types/src/

# Find correct property names
grep -A 20 "export interface Plan" packages/types/src/planner.types.ts

# Verify current usage
grep -r "plan\.title\|stage\.description" apps/web/src/
```

### Validation

```bash
# Check for common errors
grep -r "plan\.title" apps/web/src/          # Should be 0 results
grep -r "stage\.description" apps/web/src/   # Should be 0 results
grep -r "@my-road-trip/types" apps/          # Should be 0 results (wrong dash)
```

❌ **NEVER:**
- Create duplicate type definitions (check `packages/types/` first)
- Create local types that exist in `packages/types/`

✅ **ALWAYS:**
- Import types from `@my-roadtrip/types`
- Use exact property names from table above
- Check `packages/types/src/` before creating new types

### 💻 Common Code Patterns (Copy-Paste Examples)

**Create Plan:**
```typescript
// ✅ CORRECT
const newPlan = await plannerStore.createPlan({
  name: 'Road Trip USA',           // ← name, NOT title
  description: 'Coast to coast',
  isPublic: false,
  tags: ['usa', 'roadtrip']
})

// ❌ WRONG
const newPlan = await plannerStore.createPlan({
  title: 'Road Trip USA',          // ← WRONG property
  // ...
})
```

**Create Stage:**
```typescript
// ✅ CORRECT
const newStage = await plannerStore.createStage({
  planId: plan.id,
  name: 'Grand Canyon',            // ← name, NOT title
  notes: 'Visit South Rim',        // ← notes, NOT description
  location: {                      // ← nested object
    address: 'Grand Canyon, AZ',
    coordinates: { lat: 36.1069, lng: -112.1129 }
  },
  estimatedArrival: new Date('2025-06-15')
})

// ❌ WRONG
const newStage = await plannerStore.createStage({
  title: 'Grand Canyon',           // ← WRONG
  description: 'Visit South Rim',  // ← WRONG
  address: 'Grand Canyon, AZ',     // ← WRONG (not nested)
})
```

**Display Plan:**
```vue
<template>
  <!-- ✅ CORRECT -->
  <h1>{{ plan.name }}</h1>
  <p>{{ plan.description }}</p>

  <!-- ❌ WRONG -->
  <h1>{{ plan.title }}</h1>
</template>
```

**Display Stage:**
```vue
<template>
  <!-- ✅ CORRECT -->
  <h2>{{ stage.name }}</h2>
  <p>{{ stage.notes }}</p>
  <p>{{ stage.location.address }}</p>

  <!-- ❌ WRONG -->
  <h2>{{ stage.title }}</h2>
  <p>{{ stage.description }}</p>
  <p>{{ stage.address }}</p>
</template>
```

---

✅ **ALWAYS:**
- Import types from `@my-roadtrip/types`
- Use exact property names from table above
- Check `packages/types/src/` before creating new types

---

## 🏗️ Code Quality Rule (ARCHITECTURE - READ BEFORE EDITING)

**⚠️ EMBEDDED REFERENCE - NO EXTERNAL READS NEEDED**

### Architecture Rules (NO EXCEPTIONS)

| Rule | Reason | Implementation |
|------|--------|----------------|
| ❌ NO WebSocket | Mobile disconnections at 130km/h | ✅ HTTP polling (10s-60s adaptive intervals) |
| ✅ Domain isolation | Code organization & maintainability | ✅ `apps/web/src/modules/{domain}/{components,services,stores,pages}` |
| ✅ Layered backend | Separation of concerns | ✅ `controller → service → repository` pattern |
| ✅ CRUD Mode (90%) | Data consistency & simplicity | ✅ Firestore = source of truth, IndexedDB = cache |
| ✅ CRDT Mode (10%) | Real-time collaboration | ✅ Redis (Y.Doc) = live state, Firestore = snapshots |

### Data Persistence (CRITICAL - DON'T MIX MODES)

**CRUD Mode (Plans, Stages, User Profile) - 90% of features:**

```
User Action → IndexedDB (instant, optimistic)
                ↓
          Sync Queue
                ↓
         API Endpoint
                ↓
          Firestore ✅ SOURCE OF TRUTH
                ↓
         Response → Update IndexedDB cache
```

**CRDT Mode (Collaboration Only) - 10% of features:**

```
User Edit → Y.Doc (local CRDT)
              ↓
          Redis (sync)
              ↓
       Other Clients (real-time)
              ↓
    Firestore Snapshot (every 5 min, backup)
```

**Rule:** Each feature uses ONE mode. DON'T MIX!
- Solo editing? → CRUD mode
- Real-time collab? → CRDT mode

### File Structure (Strict Convention)

```
apps/web/src/modules/{domain}/
  ├── components/        # UI components (PlanCard.vue, StageList.vue)
  ├── pages/            # Route pages (PlanListPage.vue, PlanViewPage.vue)
  ├── services/         # API calls ({domain}Service.ts)
  ├── stores/           # Pinia stores ({domain}Store.ts)
  └── composables/      # Reusable logic (use{Feature}.ts)

apps/api/src/modules/{domain}/
  ├── {domain}.module.ts       # Module registration
  ├── {domain}.routes.ts       # Route definitions
  ├── {domain}.controller.ts   # Request handling
  ├── {domain}.service.ts      # Business logic
  ├── {domain}.repository.ts   # Data access
  └── {domain}.schemas.ts      # Zod validation schemas
```

### Security Checklist (MANDATORY)

```typescript
// ✅ ALWAYS validate inputs with Zod
import { z } from 'zod'

const createPlanSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().optional(),
  isPublic: z.boolean()
})

const validated = createPlanSchema.parse(req.body)

// ✅ ALWAYS protect routes with auth middleware
fastify.get('/api/plans', {
  preHandler: [requireAuth],  // ← MANDATORY for protected routes
  handler: async (request, reply) => {
    const userId = request.user.sub  // From JWT
    // ... your logic
  }
})

// ✅ ALWAYS use Firebase Admin SDK on backend (NOT client SDK)
import * as admin from 'firebase-admin'

const db = admin.firestore()
const plansRef = db.collection('plans')

// ❌ NEVER use Firebase client SDK on backend
// import { getFirestore } from 'firebase/firestore'  // WRONG!

// ✅ ALWAYS batch Firestore writes (atomicity)
const batch = db.batch()
batch.set(planRef, planData)
batch.set(stageRef, stageData)
await batch.commit()  // ← Atomic: all or nothing
```

### Performance Rules (MANDATORY)

```typescript
// ✅ Cursor pagination (NOT offset/limit)
const query = db.collection('plans')
  .orderBy('createdAt', 'desc')
  .startAfter(lastDoc)  // ← Cursor (efficient)
  .limit(20)

// ❌ NEVER use offset pagination (slow on large datasets)
// .offset(100).limit(20)  // WRONG!

// ✅ Memoize expensive computations
import { computed } from 'vue'

const totalDistance = computed(() => {
  return stages.value.reduce((sum, stage) => sum + stage.distance, 0)
})

// ✅ Debounce user input (reduce API calls)
import { useDebounceFn } from '@vueuse/core'

const debouncedSearch = useDebounceFn(async (query: string) => {
  await searchService.search(query)
}, 300)  // Wait 300ms after user stops typing

// ✅ Lazy load routes and heavy components
const PlannerPage = () => import('./pages/PlannerPage.vue')
const MapView = defineAsyncComponent(() => import('./components/MapView.vue'))
```

### Quick Validation Commands

```bash
# Before committing - run ALL of these:
./scripts/validate-quality.sh      # Architecture compliance
./scripts/validate-persistence.sh  # Data flow validation
./scripts/validate-types.sh        # Type safety
pnpm type-check                    # TypeScript errors
pnpm build                         # Build validation
```

### Anti-Patterns (FORBIDDEN)

```typescript
// ❌ FORBIDDEN - Don't do this!
try { await saveData() } catch (e) { }          // Always handle errors!
await Promise.all([write1(), write2()])         // Use Firestore batch instead

// ✅ CORRECT - Do this instead
try {
  await saveData()
} catch (error) {
  logger.error('Failed to save', error)
  throw new Error('Save failed')
}

const batch = db.batch()
batch.set(ref1, data1)
batch.set(ref2, data2)
await batch.commit()  // Atomic operation
```

### Module Registry (Know Your Domains)

| Domain | Frontend | Backend | Persistence Mode |
|--------|----------|---------|------------------|
| `planner` | ✅ | ✅ | CRUD (Firestore) |
| `ai` | ✅ | ✅ | CRUD (Firestore) |
| `collab` | ✅ | ✅ | CRDT (Redis + Firestore) |
| `offline` | ✅ | ❌ | IndexedDB only |
| `gamification` | ✅ | ✅ | CRUD (Firestore) |
| `map` | ✅ | ❌ | Frontend only |
| `auth` | ✅ | ✅ | Firebase Auth |
| `sharing` | ✅ | ✅ | CRUD (Firestore) |
| `search` | ✅ | ✅ | CRUD (Firestore) |
| `admin` | ✅ | ✅ | CRUD (Firestore) |

---

```
User Edit → Y.Doc (local CRDT)
              ↓
          Redis (sync)
              ↓
       Other Clients (real-time)
              ↓
    Firestore Snapshot (every 5 min, backup)
```

**Rule:** Each feature uses ONE mode. DON'T MIX!
- Solo editing? → CRUD mode
- Real-time collab? → CRDT mode

### File Structure (Strict Convention)

```
apps/web/src/modules/{domain}/
  ├── components/        # UI components (PlanCard.vue, StageList.vue)
  ├── pages/            # Route pages (PlanListPage.vue, PlanViewPage.vue)
  ├── services/         # API calls ({domain}Service.ts)
  ├── stores/           # Pinia stores ({domain}Store.ts)
  └── composables/      # Reusable logic (use{Feature}.ts)

apps/api/src/modules/{domain}/
  ├── {domain}.module.ts       # Module registration
  ├── {domain}.routes.ts       # Route definitions
  ├── {domain}.controller.ts   # Request handling
  ├── {domain}.service.ts      # Business logic
  ├── {domain}.repository.ts   # Data access
  └── {domain}.schemas.ts      # Zod validation schemas
```

### Security Checklist (MANDATORY)

```typescript
// ✅ ALWAYS validate inputs with Zod
import { z } from 'zod'

const createPlanSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().optional(),
  isPublic: z.boolean()
})

const validated = createPlanSchema.parse(req.body)

// ✅ ALWAYS protect routes with auth middleware
fastify.get('/api/plans', {
  preHandler: [requireAuth],  // ← MANDATORY for protected routes
  handler: async (request, reply) => {
    const userId = request.user.sub  // From JWT
    // ... your logic
  }
})

// ✅ ALWAYS use Firebase Admin SDK on backend (NOT client SDK)
import * as admin from 'firebase-admin'

const db = admin.firestore()
const plansRef = db.collection('plans')

// ❌ NEVER use Firebase client SDK on backend
// import { getFirestore } from 'firebase/firestore'  // WRONG!

// ✅ ALWAYS batch Firestore writes (atomicity)
const batch = db.batch()
batch.set(planRef, planData)
batch.set(stageRef, stageData)
await batch.commit()  // ← Atomic: all or nothing
```

### Performance Rules (MANDATORY)

```typescript
// ✅ Cursor pagination (NOT offset/limit)
const query = db.collection('plans')
  .orderBy('createdAt', 'desc')
  .startAfter(lastDoc)  // ← Cursor (efficient)
  .limit(20)

// ❌ NEVER use offset pagination (slow on large datasets)
// .offset(100).limit(20)  // WRONG!

// ✅ Memoize expensive computations
import { computed } from 'vue'

const totalDistance = computed(() => {
  return stages.value.reduce((sum, stage) => sum + stage.distance, 0)
})

// ✅ Debounce user input (reduce API calls)
import { useDebounceFn } from '@vueuse/core'

const debouncedSearch = useDebounceFn(async (query: string) => {
  await searchService.search(query)
}, 300)  // Wait 300ms after user stops typing

// ✅ Lazy load routes and heavy components
const PlannerPage = () => import('./pages/PlannerPage.vue')
const MapView = defineAsyncComponent(() => import('./components/MapView.vue'))
```

### Quick Validation Commands

```bash
# Before committing - run ALL of these:
./scripts/validate-quality.sh      # Architecture compliance
./scripts/validate-persistence.sh  # Data flow validation
./scripts/validate-types.sh        # Type safety
pnpm type-check                    # TypeScript errors
pnpm build                         # Build validation
```

### Anti-Patterns (FORBIDDEN)

```typescript
// ❌ FORBIDDEN - Don't do this!
try { await saveData() } catch (e) { }          // Always handle errors!
await Promise.all([write1(), write2()])         // Use Firestore batch instead

// ✅ CORRECT - Do this instead
try {
  await saveData()
} catch (error) {
  logger.error('Failed to save', error)
  throw new Error('Save failed')
}

const batch = db.batch()
batch.set(ref1, data1)
batch.set(ref2, data2)
await batch.commit()  // Atomic operation
```

### Module Registry (Know Your Domains)

| Domain | Frontend | Backend | Persistence Mode |
|--------|----------|---------|------------------|
| `planner` | ✅ | ✅ | CRUD (Firestore) |
| `ai` | ✅ | ✅ | CRUD (Firestore) |
| `collab` | ✅ | ✅ | CRDT (Redis + Firestore) |
| `offline` | ✅ | ❌ | IndexedDB only |
| `gamification` | ✅ | ✅ | CRUD (Firestore) |
| `map` | ✅ | ❌ | Frontend only |
| `auth` | ✅ | ✅ | Firebase Auth |
| `sharing` | ✅ | ✅ | CRUD (Firestore) |
| `search` | ✅ | ✅ | CRUD (Firestore) |
| `admin` | ✅ | ✅ | CRUD (Firestore) |

---

## 🔗 Related Files Rule (CRITICAL - MOST IMPORTANT)

**THE NUMBER ONE CAUSE OF BUGS: Editing files in isolation**

### Before Editing ANY File

```bash
# 1. Find component usages (2 min)
grep -r "import.*YourComponent" apps/web/src/
grep -r "<YourComponent" apps/web/src/

# 2. Find endpoint usages (1 min)
grep -r "YourEndpoint" apps/api/src/
grep -r "fetch.*your-endpoint" apps/web/src/

# 3. Find type usages (1 min)
grep -r "YourType" apps/ packages/

# 4. Check imports chain (1 min)
# Open 5-10 files that import/use your target file
```

### Examples of What to Check

**Editing a Component:**
```
PlanCard.vue
  ↓ Check parents
  ├─ PlanList.vue (uses PlanCard)
  ├─ DashboardPage.vue (uses PlanList)
  └─ plannerStore.ts (provides data)

Before editing PlanCard → Open all 3 files
```

**Editing an Endpoint:**
```
POST /api/plans
  ↓ Check usage
  ├─ plannerService.ts (calls endpoint)
  ├─ PlanCreateDialog.vue (uses service)
  └─ plannerStore.ts (stores result)

Before editing endpoint → Open all 3 files
```

**Editing a Type:**
```
Plan type in packages/types/
  ↓ Check usages
  ├─ 15 components use Plan
  ├─ 8 services use Plan
  └─ 3 stores use Plan

Before editing Plan type → Check ALL usages
```

### Validation Checklist

- [ ] Found all files that import this file (grep)
- [ ] Found all files that use this component/function (grep)
- [ ] Opened 5-10 related files
- [ ] Traced the full call chain (user action → UI → service → API → DB)
- [ ] Verified changes won't break dependent files
- [ ] Tested the full flow end-to-end

❌ **NEVER:**
- Edit a single file without checking related files
- Change a type without checking all usages
- Modify an API without checking frontend calls
- Update a component without checking parents

✅ **ALWAYS:**
- Check 5-10 related files BEFORE editing
- Trace the full call chain
- Verify end-to-end flow
- Test with real data

---

## 📝 Documentation Rule (NEW 2025-10-29)

**NO HUMANS READ /docs. AGENTS ONLY.**

✅ **DO:**
- Tables only (compressed info)
- Location: `/docs/` with subfolders
- One master file per topic
- Update index files

❌ **DON'T:**
- Verbose prose
- Multiple docs for same topic
- Docs outside `/docs/`
- Leave outdated docs

**Rule:** If doc > 500 lines without tables → compress to tables

### Folder Structure
```
/docs/
  ├── README.md (master index)
  ├── DOC_INDEX.md (complete catalog)
  ├── REFERENCE.md (technical authority)
  ├── modules/ (module-specific docs)
  └── archive/ (old/outdated docs)
```

### When Adding Documentation

1. **Check existing:** `ls docs/*.md | grep -i "topic"`
2. **Update index:** Add entry to `docs/DOC_INDEX.md`
3. **Use tables:** Convert prose to tables/lists
4. **Archive old:** Move superseded docs to `docs/archive/`

---

## CLI Tools

You are “Codex CLI Agent”, running on macOS ARM (zsh) with Roadtripper CLI optimization.
Your environment includes:
  • ripgrep (rg)  – main text search engine
  • fd + fzf + bat – fuzzy navigation with previews
  • watchman / ctags – live index refresh
  • zoxide – adaptive cd navigation
  • hyperfine – command benchmarking
  • RAMDisk cache (/Volumes/RAMDisk/tmp)
  • ~/.rt-cli/config.json – runtime preferences

## ⚡ Session Start (30 seconds for COMPLETE analysis!)

**🚀 NEW REALITY:** Commands are **50x faster**. Do **10x more searches**. Still faster than before.

### Step 1: Deep Analysis (100ms)
```bash
rt-deep deep-analyze <target-file>
```
Returns: imports, exports, functions, stats

### Step 2: Find Related (50ms)
```bash
rt-deep find-related <symbol>
```
Returns: definitions, imports, references

### Step 3: Impact Analysis (150ms)
```bash
rt-deep impact <target-file>
```
Returns: blast radius, symbol usage

### Step 4: Module Context (200ms)
```bash
rt-deep analyze-module <domain>
```
Returns: all components, pages, services, stores

### Step 5: Search Patterns (30ms each - do 10+)
```bash
rt-agent search/text "import.*YourThing"     # 30ms
rt-agent search/text "YourFunction"          # 30ms
rt-agent search/count "YourComponent"        # 10ms
```

### Step 6: Health Check (300ms)
```bash
rt-deep health
```
Returns: TODOs, console.logs, @ts-ignores, large files

**TOTAL TIME: ~500ms for COMPLETE project understanding**

**⚠️ No excuses: If you haven't done 10-20 searches, you're being lazy.**

---

## 🎯 Execution Workflow

### Step-by-Step Process

1. **Find Related Files** (1 min)
   ```bash
   grep -r "import.*ComponentName" apps/web/src/
   grep -r "endpointPath" apps/api/src/
   ```

2. **Open 5-10 Files** (1 min)
   - Components that import this file
   - Services that call this endpoint
   - Stores that use this data
   - Types that define this structure

3. **Make Changes** (varies)
   - Follow Type Safety Protocol (see above)
   - Follow Code Quality Protocol (see above)
   - Keep persistence architecture in mind (CRUD vs CRDT)
   - Write clean, commented code

4. **Validate Changes** (2 min)
   ```bash
   pnpm type-check                    # TypeScript
   ./scripts/validate-quality.sh      # Architecture
   ./scripts/validate-types.sh        # Type safety
   pnpm build                         # Build
   ```

5. **Verify End-to-End** (3 min)
   - Test user flow (UI → service → API → DB)
   - Check related components still work
   - Verify no broken imports/exports

### Time Budget per Task

| Task Type | Find Files | Code | Validate | Total |
|-----------|------------|------|----------|-------|
| Small fix | 1 min | 5 min | 2 min | 8 min |
| Component | 2 min | 15 min | 3 min | 20 min |
| Endpoint | 2 min | 20 min | 5 min | 27 min |
| Feature | 5 min | 60 min | 10 min | 75 min |

---

## 📚 Key References (Quick Lookup)

| Need | Document | Section |
|------|----------|---------|
| All info | `docs/core/agent.md` | Complete reference |
| Endpoints | `docs/core/agent.md` | API Endpoints table |
| Components | `docs/core/agent.md` | Module Locations |
| Type safety | `docs/TYPE_SAFETY_QUICK_REF.md` | Property names |
| Persistence | `docs/PERSISTENCE_ARCHITECTURE.md` | CRUD vs CRDT |
| Security | `docs/SECURITY_CHECKLIST.md` | All checks |
| Performance | `docs/PERFORMANCE_CHECKLIST.md` | Optimization rules |
| Architecture | `docs/core/architecture.md` | System diagrams |

---

## ⚠️ Common Mistakes to Avoid

| Mistake | Impact | Prevention |
|---------|--------|------------|
| Not checking related files | Broken imports, runtime errors | grep before editing |
| Using wrong property names | TypeScript errors | Check TYPE_SAFETY_QUICK_REF.md |
| Mixing CRUD and CRDT | Data inconsistency | Read PERSISTENCE_ARCHITECTURE.md |
| Creating duplicate types | Type conflicts | grep packages/types/ first |
| No input validation | Security vulnerability | Always use Zod schemas |
| Missing auth middleware | Unauthorized access | Check SECURITY_CHECKLIST.md |
| Offset pagination | Performance issues | Use cursor pagination |
| Using WebSocket | Mobile disconnections | Use HTTP polling |

---

**Tu es ingénieur responsable. Livre du code propre, complet. Pas de bullshit.**