---
applyTo: '**'
priority: CRITICAL
enforced: true
---

# Type Safety & Naming Protocol

**MANDATORY FOR ALL AGENTS. ENFORCED ON EVERY FILE EDIT.**

---

## 🚨 Pre-Edit Validation (REQUIRED)

Before editing ANY file, agents MUST:

### 1. Check Type Definitions

```bash
# Find existing type
grep -r "export interface TypeName" packages/types/src/

# Check for duplicates
grep -r "interface TypeName" packages/ apps/

# Verify imports
grep -r "import.*TypeName" apps/ packages/
```

**Rule:** If type exists, USE IT. Never create duplicate.

### 2. Check Property Names

```bash
# Verify property naming in type definition
grep -A 20 "export interface Plan" packages/types/src/planner.types.ts

# Check actual usage in codebase
grep -r "plan\.name\|plan\.title" apps/web/src/
```

**Rule:** Match EXACT property names from type definition.

### 3. Check Import Paths

```bash
# Verify package name
cat packages/types/package.json | grep '"name"'

# Find correct import
grep -r "from '@my-roadtrip/types'" apps/
```

**Rule:** Always `@my-roadtrip/types` (NOT `@my-road-trip/types`)

---

## 📋 Type System Authority

### Single Source of Truth

| Type | File | Import From |
|------|------|-------------|
| `Plan` | `packages/types/src/planner.types.ts` | `@my-roadtrip/types` |
| `Stage` | `packages/types/src/planner.types.ts` | `@my-roadtrip/types` |
| `UserProfile` | `packages/types/src/gamification.types.ts` | `@my-roadtrip/types` |
| `ShareLink` | `packages/types/src/sharing.types.ts` | `@my-roadtrip/types` |
| `CRDTUpdate` | `packages/types/src/collab.types.ts` | `@my-roadtrip/types` |

**CRITICAL:** These types MUST NOT be redefined anywhere else.

### Canonical Property Names

| Entity | Properties | DO NOT USE |
|--------|------------|------------|
| **Plan** | `name`, `description`, `userId`, `stages[]` | ❌ `title`, ❌ `user`, ❌ `items` |
| **Stage** | `name`, `notes`, `location`, `planId`, `order` | ❌ `title`, ❌ `description`, ❌ `address` |
| **UserProfile** | `displayName`, `email`, `gamification?` (nested object) | ❌ `name`, ❌ `username`, ❌ direct `points/level/badges` |
| **GamificationData** | `points`, `level`, `badges`, `stats` (nested under UserProfile) | ❌ At root of UserProfile |

---

## 🔒 Naming Enforcement Rules

### Rule 1: No Type Duplication

```typescript
// ❌ FORBIDDEN - Duplicate type definition
export interface Plan {
  id: string
  title: string  // Wrong property name too!
}

// ✅ CORRECT - Import existing type
import type { Plan } from '@my-roadtrip/types'
```

### Rule 2: No Local Type Overrides

```typescript
// ❌ FORBIDDEN - Local type shadows global
interface Plan {
  id: string
  customField: string
}

// ✅ CORRECT - Extend or use as-is
import type { Plan } from '@my-roadtrip/types'
// If need extension:
interface ExtendedPlan extends Plan {
  customField: string
}
```

### Rule 3: Property Name Consistency

```vue
<!-- ❌ FORBIDDEN - Wrong property name -->
<template>
  <h1>{{ plan.title }}</h1>
</template>

<!-- ✅ CORRECT - Match type definition -->
<template>
  <h1>{{ plan.name }}</h1>
</template>
```

### Rule 4: Package Name Consistency

```typescript
// ❌ FORBIDDEN - Typo in package name
import type { Plan } from '@my-road-trip/types'

// ✅ CORRECT - No dash in "roadtrip"
import type { Plan } from '@my-roadtrip/types'
```

---

## 🛠️ Agent Pre-Flight Checklist

Before ANY code change involving types or properties:

- [ ] **Step 1:** Run `grep -r "export interface TypeName" packages/types/src/`
- [ ] **Step 2:** If exists, note file location and properties
- [ ] **Step 3:** Use EXACT property names from definition
- [ ] **Step 4:** Import from `@my-roadtrip/types`
- [ ] **Step 5:** NEVER create local duplicate
- [ ] **Step 6:** Verify with `pnpm type-check`

---

## 📚 Type Definition Workflow

### When Adding New Type

```typescript
// 1. Check if type already exists
// grep -r "export interface MyNewType" packages/types/

// 2. If not exists, add to domain file
// File: packages/types/src/{domain}.types.ts
export interface MyNewType {
  id: string
  name: string  // Use 'name' for identifiers
  // ... other properties
}

// 3. Re-export in index.ts
// File: packages/types/src/index.ts
export type { MyNewType } from './{domain}.types.js'

// 4. Use in application code
import type { MyNewType } from '@my-roadtrip/types'
```

### When Modifying Existing Type

```typescript
// 1. Find authoritative definition
// grep -r "export interface Plan" packages/types/src/

// 2. Edit ONLY the authoritative file
// File: packages/types/src/planner.types.ts
export interface Plan {
  id: string
  name: string  // Canonical name
  newProperty?: string  // Add new property
}

// 3. Update all usages
// grep -r "plan\." apps/ | grep -v "plan\.name"

// 4. Never modify local copies (there shouldn't be any!)
```

---

## 🚫 Common Mistakes to AVOID

### ❌ Mistake 1: Creating Duplicate Types

```typescript
// WRONG - Creating duplicate in component
interface Plan {
  id: string
  title: string
}

// RIGHT - Import from types package
import type { Plan } from '@my-roadtrip/types'
```

### ❌ Mistake 2: Using Wrong Property Names

```typescript
// WRONG - Property doesn't exist in type
const planTitle = plan.title  // Type error!

// RIGHT - Use canonical property name
const planName = plan.name  // ✅ Correct
```

### ❌ Mistake 3: Inconsistent Naming

```typescript
// WRONG - Mixed naming conventions
createPlan({ title: 'Trip' })      // Backend expects 'name'
updatePlan({ name: 'Updated' })    // Inconsistent!

// RIGHT - Always use canonical names
createPlan({ name: 'Trip' })
updatePlan({ name: 'Updated' })
```

### ❌ Mistake 4: Package Name Typos

```typescript
// WRONG - Various typos
import { Plan } from '@my-road-trip/types'   // Dash in wrong place
import { Plan } from '@myroadtrip/types'     // Missing dash
import { Plan } from '@my-roadtrip-types'    // Wrong format

// RIGHT - Exact package name
import { Plan } from '@my-roadtrip/types'
```

---

## 🔍 Validation Commands

### Before Committing Code

```bash
# 1. Check for duplicate type definitions
find packages apps -name "*.ts" -o -name "*.vue" | \
  xargs grep -l "export interface Plan" | \
  grep -v "packages/types/src/planner.types.ts"
# Expected: No results (no duplicates)

# 2. Check for wrong property usage
grep -r "plan\.title" apps/web/src/modules/planner/
# Expected: No results (should use plan.name)

# 3. Check for package name typos
grep -r "@my-road-trip/types" apps/ packages/
# Expected: No results (should be @my-roadtrip)

# 4. Run type checker
pnpm type-check
# Expected: 0 errors in planner module

# 5. Check for type conflicts
grep -r "interface Plan {" apps/ packages/ | wc -l
# Expected: 1 (only in planner.types.ts)
```

---

## 📖 Type System Map (Quick Reference)

### Domain-Specific Types

```
packages/types/src/
├── index.ts                    ← Re-exports only (no definitions)
├── planner.types.ts            ← Plan, Stage, POI, Route
├── gamification.types.ts       ← UserProfile, Badge, Achievement
├── collab.types.ts             ← CRDTUpdate, Presence
├── sharing.types.ts            ← ShareLink, Comment
├── search.types.ts             ← SearchResult, SearchFilters
└── admin.types.ts              ← AdminStats, AdminUser
```

### Import Patterns

```typescript
// ✅ Always import from package root
import type { Plan, Stage } from '@my-roadtrip/types'

// ❌ Never import from specific file
import type { Plan } from '@my-roadtrip/types/planner.types'

// ❌ Never use relative paths for types
import type { Plan } from '../../../../../packages/types/src/planner.types'
```

---

## 🎯 Agent Decision Tree

```
Need to use a type?
├─ Does it exist in packages/types/?
│  ├─ YES → Import from @my-roadtrip/types
│  └─ NO → Continue to next question
├─ Is it domain-specific (Plan, User, etc.)?
│  ├─ YES → Add to packages/types/src/{domain}.types.ts
│  └─ NO → Create locally (component-specific only)
├─ Check property names match definition
├─ Verify no duplicates exist
└─ Run pnpm type-check
```

---

## 🔄 Migration from Old Code

If you find old code with wrong patterns:

### Fix Type Import

```typescript
// OLD (wrong)
interface Plan { id: string; title: string }

// NEW (correct)
import type { Plan } from '@my-roadtrip/types'
```

### Fix Property Names

```typescript
// OLD (wrong)
const title = plan.title
const desc = stage.description

// NEW (correct)
const name = plan.name
const notes = stage.notes
```

### Fix Package Name

```typescript
// OLD (wrong)
import { Plan } from '@my-road-trip/types'

// NEW (correct)
import { Plan } from '@my-roadtrip/types'
```

---

## ⚡ Auto-Fix Commands

### Find and Report Issues

```bash
# Find all wrong property usages
echo "=== Wrong Properties ==="
grep -rn "plan\.title" apps/web/src/modules/planner/ || echo "✅ None"
grep -rn "stage\.description" apps/web/src/modules/planner/ || echo "✅ None"

# Find package name typos
echo "=== Package Name Typos ==="
grep -rn "@my-road-trip/types" apps/ packages/ || echo "✅ None"

# Find duplicate type definitions
echo "=== Duplicate Types ==="
grep -rn "export interface Plan" packages/ apps/ | \
  grep -v "packages/types/src/planner.types.ts" || echo "✅ None"

# Summary
echo "=== Type Check ==="
pnpm type-check 2>&1 | grep -E "error TS|Tasks:" | tail -5
```

---

## 📊 Quality Gates

Code MUST pass these gates before merge:

| Gate | Command | Expected Result |
|------|---------|-----------------|
| **No Duplicates** | `grep -r "interface Plan" packages/ apps/ \| wc -l` | `1` (only in planner.types.ts) |
| **No Wrong Props** | `grep -r "plan\.title" apps/web/src/modules/planner/ \| wc -l` | `0` |
| **No Typos** | `grep -r "@my-road-trip/types" apps/ \| wc -l` | `0` |
| **Type Check** | `pnpm type-check` | `0 errors in planner` |

---

## 🆘 Emergency Fix Protocol

If you discover a type inconsistency:

1. **STOP** - Don't make it worse
2. **Find** - Locate authoritative definition: `grep -r "export interface" packages/types/`
3. **Document** - Note all wrong usages: `grep -r "wrongProperty" apps/`
4. **Fix** - Update ALL usages to match authoritative definition
5. **Verify** - Run `pnpm type-check`
6. **Commit** - With message: `fix: unify TypeName property names`

---

## 📝 Commit Message Format

When fixing type issues:

```bash
# Type system fixes
fix(types): remove duplicate Plan definition in ComponentName
fix(types): rename plan.title → plan.name across planner module
fix(types): correct package import @my-road-trip → @my-roadtrip
refactor(types): consolidate UserStats in gamification.types.ts
```

---

## ✅ Success Criteria

Your code is type-safe when:

- ✅ Zero duplicate type definitions
- ✅ All properties match type definitions exactly
- ✅ All imports use `@my-roadtrip/types`
- ✅ `pnpm type-check` passes with 0 planner errors
- ✅ No use of deprecated types (`User`, `PlanSettings`, etc.)

---

**REMINDER: This protocol is MANDATORY. All agents must follow it on EVERY edit.**

**See also:**
- `docs/TYPE_SYSTEM_CLEANUP.md` - History of cleanup
- `docs/core/agent.md` - Type reference table
- `.github/instructions/FOCUS.instructions.md` - Code quality rules
