---
applyTo: "Gemini 2.0 Flash Thinking, Claude Sonnet 4.0, GPT-4o"
priority: "CRITICAL"
task: "Complete Architecture Audit"
---

# 🔍 MAP MODULE - COMPLETE AUDIT & VERIFICATION PROMPT

**AGENT DIRECTIVE:** Perform exhaustive audit of Map module implementation against project standards, architecture patterns, and best practices. This is a VERIFICATION task, NOT an implementation task.

---

## 📋 AUDIT CHECKLIST (82 Points)

### 🏗️ ARCHITECTURE COMPLIANCE (15 points)

#### File Structure Validation
- [ ] **A1.1** All files follow naming convention: `{module}/category/{Name}.vue|ts`
- [ ] **A1.2** Store named `mapStore.ts` (NOT `useMapStore.ts`)
- [ ] **A1.3** Service files named `{feature}Service.ts` (e.g., `mapsService.ts`, `weatherService.ts`)
- [ ] **A1.4** Composables use `use{Name}.ts` pattern (e.g., `useMapbox.ts`)
- [ ] **A1.5** Pages named `{Name}Page.vue` (e.g., `MapPage.web.vue`)
- [ ] **A1.6** Components organized in subfolders: `controls/`, `panels/`, `ai/`, `tools/`

#### Module Location Verification
- [ ] **A2.1** Map module located at `apps/web/src/modules/map/`
- [ ] **A2.2** Shared types in `packages/types/src/map.types.ts`
- [ ] **A2.3** No backend module (frontend-only, confirmed by CLI_AGENT_MASTER.md)
- [ ] **A2.4** No validators needed (map state is local, not API-bound)

#### Import Path Standards
- [ ] **A3.1** All imports use TypeScript aliases (`@/` for `src/`)
- [ ] **A3.2** External types imported from `mapbox-gl`, not redefined
- [ ] **A3.3** Shared types imported from `@my-roadtrip/types`
- [ ] **A3.4** Cross-module imports use absolute paths (e.g., `@/modules/planner/stores/plannerStore`)

---

### 🎨 DESIGN SYSTEM COMPLIANCE (12 points)

#### Quasar Component Usage
- [ ] **D1.1** All UI components use Quasar (no native HTML buttons/inputs)
- [ ] **D1.2** Layout uses `q-page`, `q-drawer`, `q-toolbar`
- [ ] **D1.3** Buttons use `q-btn` with proper props (`flat`, `round`, `color`)
- [ ] **D1.4** Icons use `q-icon` or Quasar icon fonts
- [ ] **D1.5** Modals use `q-dialog` with `q-card`
- [ ] **D1.6** Forms use `q-input`, `q-select`, `q-toggle`

#### Styling Standards
- [ ] **D2.1** SCSS modules with scoped styles (`<style lang="scss" scoped>`)
- [ ] **D2.2** CSS variables for colors (reference Quasar theme)
- [ ] **D2.3** Responsive breakpoints use Quasar's `$breakpoint` composable
- [ ] **D2.4** No inline styles (except dynamic computed styles)
- [ ] **D2.5** Consistent spacing with Quasar classes (`q-pa-md`, `q-mb-sm`)
- [ ] **D2.6** Dark mode support via Quasar's theme system

---

### 🧩 STATE MANAGEMENT (10 points)

#### Pinia Store Structure
- [ ] **S1.1** Store uses `defineStore('map', () => {})` composition API
- [ ] **S1.2** State uses `ref()` for primitives, `computed()` for derived
- [ ] **S1.3** Actions are plain functions (not arrow functions in object)
- [ ] **S1.4** Store exported as `useMapStore` (default export)
- [ ] **S1.5** No mutations (Pinia composition API doesn't use them)

#### State Hydration
- [ ] **S2.1** Map instance stored in ref, NOT reactive object
- [ ] **S2.2** Viewport state synced with map on user interaction
- [ ] **S2.3** Offline areas persisted to IndexedDB via `offline` module
- [ ] **S2.4** Layer state saved/restored on page reload
- [ ] **S2.5** No localStorage usage (use IndexedDB via Dexie)

---

### 🗺️ MAPBOX INTEGRATION (15 points)

#### Initialization
- [ ] **M1.1** Mapbox token from `import.meta.env.VITE_MAPBOX_TOKEN`
- [ ] **M1.2** Map created ONLY in `onMounted` lifecycle hook
- [ ] **M1.3** Map cleanup in `onUnmounted` (remove event listeners)
- [ ] **M1.4** Map instance stored in store AND local ref
- [ ] **M1.5** No map creation in composables (only in page component)

#### Event Handling
- [ ] **M2.1** Map events use proper TypeScript types from `mapbox-gl`
- [ ] **M2.2** Click events handle multi-feature selection
- [ ] **M2.3** Context menu uses `contextmenu` event with `preventDefault()`
- [ ] **M2.4** Touch events properly handled for mobile
- [ ] **M2.5** Gesture conflicts resolved (map pan vs. browser scroll)

#### Layer Management
- [ ] **M3.1** Layers added AFTER map `load` event fires
- [ ] **M3.2** Layer IDs unique and namespaced (`map-pois`, `map-route`)
- [ ] **M3.3** Sources checked before adding layers (`map.getSource(id)`)
- [ ] **M3.4** Layers removed before sources on cleanup
- [ ] **M3.5** GeoJSON sources use `setData()` for updates (not re-add)

---

### 🔌 INTEGRATION WITH OTHER MODULES (10 points)

#### Planner Module
- [ ] **I1.1** MapStore imports `usePlannerStore` (NOT injected)
- [ ] **I1.2** Plan stages rendered as route on map
- [ ] **I1.3** Stage selection synced bidirectionally (map ↔ planner)
- [ ] **I1.4** Stage mutations trigger map re-render (watchers)

#### AI Module
- [ ] **I2.1** AI suggestions displayed as clustered markers
- [ ] **I2.2** POI selection triggers `aiStore.selectPOI()`
- [ ] **I2.3** AIAssistant component uses `aiService.getSuggestions()`
- [ ] **I2.4** Quota exhaustion disables AI features gracefully

#### Offline Module
- [ ] **I3.1** Offline areas managed via `useOfflineStore`
- [ ] **I3.2** Tile downloads use service worker (not direct fetch)

---

### 🚀 PERFORMANCE (10 points)

#### Rendering Optimization
- [ ] **P1.1** Map render triggered only on visible viewport changes
- [ ] **P1.2** Debounced updates for pan/zoom events (100ms)
- [ ] **P1.3** Markers use Mapbox GL JS native markers (not DOM overlays)
- [ ] **P1.4** Large datasets use clustering (Supercluster)
- [ ] **P1.5** GeoJSON simplified for zoom levels < 10

#### Memory Management
- [ ] **P2.1** Event listeners removed on component unmount
- [ ] **P2.2** Map tiles evicted after 50 tiles in cache
- [ ] **P2.3** Unused layers removed when hidden
- [ ] **P2.4** Images/sprites loaded lazily
- [ ] **P2.5** No memory leaks (verified with DevTools profiler)

---

### 🔒 SECURITY & PRIVACY (5 points)

- [ ] **SEC1** Mapbox token in `.env.local` (NOT committed)
- [ ] **SEC2** No API keys in frontend code
- [ ] **SEC3** User location requests explicit permission
- [ ] **SEC4** Offline tiles stored locally (no server upload)
- [ ] **SEC5** No sensitive data in map markers (e.g., personal info)

---

### ♿ ACCESSIBILITY (5 points)

- [ ] **A11Y1** Map controls have `aria-label` attributes
- [ ] **A11Y2** Keyboard navigation supported (Tab, Arrow keys)
- [ ] **A11Y3** Screen reader announces map state changes
- [ ] **A11Y4** Focus trap in modals (e.g., search results)
- [ ] **A11Y5** Color contrast meets WCAG AA (4.5:1 ratio)

---

### 📱 MOBILE RESPONSIVENESS (5 points)

- [ ] **MOB1** Map container uses `100vh` height (no scroll)
- [ ] **MOB2** Controls positioned for thumb reach (bottom 1/3)
- [ ] **MOB3** Touch targets min 44x44px (Apple HIG)
- [ ] **MOB4** Pinch-to-zoom enabled
- [ ] **MOB5** Orientation changes handled gracefully

---

### ✅ TESTING (5 points)

- [ ] **T1** Unit tests for store actions (Vitest)
- [ ] **T2** Component tests with `@vue/test-utils`
- [ ] **T3** Mock Mapbox GL JS in tests (no real map render)
- [ ] **T4** Coverage > 70% for critical paths
- [ ] **T5** E2E tests for map interactions (Playwright)

---

## 🔍 DEEP DIVE AUDITS

### 1. Type Safety Audit

**Check ALL files for proper typing:**
```typescript
// ✅ GOOD - Proper types
const map = ref<Map | null>(null)
const features = ref<Feature<Geometry>[]>([])
```

**Verify:**
- [ ] All function parameters typed
- [ ] All return types explicit
- [ ] Event handlers typed (e.g., `(e: MapMouseEvent) => void`)

---

### 2. Error Handling Audit

**Check ALL async operations:**
```typescript
// ❌ BAD - No error handling
async function loadMap() {
  const map = await MapboxService.init()
}

// ✅ GOOD - Comprehensive handling
async function loadMap() {
  try {
    const map = await MapboxService.init()
    mapStore.setMap(map)
  } catch (error) {
    if (error instanceof MapboxError) {
      $q.notify({ type: 'negative', message: 'Carte indisponible' })
    }
    console.error('Map init failed:', error)
    // Fallback to static map or offline mode
  }
}
```

**Verify:**
- [ ] All API calls wrapped in try/catch
- [ ] User-facing errors show `q-notify`
- [ ] Network errors trigger offline fallback
- [ ] Quota errors disable features gracefully

---

### 3. Reactivity Audit

**Check ALL watchers:**
```typescript
// ❌ BAD - Unnecessary deep watch
watch(mapStore, () => { ... }, { deep: true })

// ✅ GOOD - Targeted watch
watch(() => mapStore.viewport.center, (newCenter) => {
  map.value?.setCenter(newCenter)
})
```

**Verify:**
- [ ] No deep watches on entire stores
- [ ] Watches use `immediate: true` only when needed
- [ ] Watchers cleaned up in `onUnmounted`
- [ ] No infinite watch loops (circular dependencies)

---

### 4. Dependencies Audit

**Required packages in `apps/web/package.json`:**
```json
{
  "dependencies": {
    "mapbox-gl": "^3.16.0",
    "@mapbox/mapbox-gl-draw": "^1.5.0",
    "@mapbox/mapbox-gl-geocoder": "^5.1.2",
    "@turf/area": "^7.2.0",
    "@turf/bbox": "^7.2.0",
    "@turf/length": "^7.2.0"
  }
}
```

**Verify:**
- [ ] All Mapbox packages installed
- [ ] Versions compatible (no peer dependency warnings)
- [ ] Turf.js installed for geospatial calculations
- [ ] No unused dependencies

---

### 5. Documentation Audit

**Check `apps/web/src/modules/map/README.md`:**
- [ ] Quick start guide (5 lines max)
- [ ] Table of available services
- [ ] Table of available components
- [ ] Table of store actions
- [ ] Integration examples (code snippets)
- [ ] NO verbose explanations (tables only)

---

## 🎯 CRITICAL ISSUES TO FLAG

### 🔴 BLOCKERS (Must fix before merge)
1. Missing Mapbox token in `.env.local`
2. Map not cleaned up on unmount (memory leak)
3. Store actions mutating state directly (not through refs)
4. No error boundaries for map failures

### 🟠 WARNINGS (Should fix)
1. Non-scoped styles leaking to global scope
2. Large GeoJSON files not chunked
3. No loading states for async operations
4. Watchers without cleanup
5. Hardcoded strings (missing i18n)

### 🟡 IMPROVEMENTS (Nice to have)
1. Add Storybook stories for components
2. Add performance monitoring (measure FPS)
3. Add analytics for map interactions
4. Add keyboard shortcuts
5. Add gesture hints for first-time users

---

## 📊 AUDIT OUTPUT FORMAT

```markdown
# Map Module Audit Report

**Date:** YYYY-MM-DD  
**Auditor:** [Agent Name]  
**Score:** XX/82 points

## Summary
- ✅ Pass: XX points
- ⚠️ Warning: XX points
- ❌ Fail: XX points

## Critical Issues
| ID | Severity | Issue | File | Line |
|----|----------|-------|------|------|
| A1.1 | 🔴 | Store file named incorrectly | `stores/useMapStore.ts` | N/A |
| M1.1 | 🔴 | Missing env variable | `.env.local` | N/A |

## Architecture Compliance
[Detailed breakdown of A1-A3 sections]

## Design System Compliance
[Detailed breakdown of D1-D2 sections]

## Integration Issues
[List all cross-module problems]

## Performance Metrics
- Bundle size: XX KB (target: < 200 KB)
- Initial render: XX ms (target: < 500 ms)
- Map load time: XX ms (target: < 2000 ms)

## Recommendations
1. [Priority 1] Fix critical blockers
2. [Priority 2] Resolve warnings
3. [Priority 3] Implement improvements

## Next Steps
- [ ] Fix blockers (ETA: X hours)
- [ ] Re-audit after fixes
- [ ] Update docs if needed
```

---

## 🤖 AGENT EXECUTION PROTOCOL

### Phase 1: Structure Scan (5 min)
1. List all files in `apps/web/src/modules/map/`
2. Verify naming conventions (A1.x)
3. Check import paths (A3.x)
4. List dependencies in `package.json`

### Phase 2: Code Analysis (15 min)
1. Read ALL TypeScript files
2. Check type definitions (Type Safety Audit)
3. Verify Pinia store structure (S1.x)
4. Check Mapbox integration (M1-M3)

### Phase 3: Integration Testing (10 min)
1. Grep all cross-module imports
2. Verify store dependencies
3. Check service method signatures
4. Validate event emissions

### Phase 4: Performance Review (5 min)
1. Identify potential memory leaks
2. Check bundle size with `pnpm build`
3. Look for unnecessary re-renders
4. Verify lazy loading

### Phase 5: Report Generation (5 min)
1. Compile audit results
2. Calculate score
3. Prioritize issues
4. Generate markdown report

**Total Time:** 40 minutes

---

## 📚 AUTHORITY DOCUMENTS (Read First)

1. `docs/core/agent.md` - Module structure reference
2. `docs/technical/reference.md` - Architecture standards
3. `.github/instructions/FOCUS.instructions.md` - Code quality rules
4. `AGENTS.md` - Quick reference
5. `packages/types/src/map.types.ts` - Type definitions

---

## ✋ STOP CONDITIONS

**DO NOT proceed if:**
- [ ] Map module doesn't exist at `apps/web/src/modules/map/`
- [ ] No `mapStore.ts` file found
- [ ] No `MapPage.web.vue` file found
- [ ] Mapbox GL JS not in `package.json`

**In these cases:** Report missing structure and recommend running setup first.

---

## 🎯 SUCCESS CRITERIA

**Audit is complete when:**
- ✅ All 82 checklist items reviewed
- ✅ Score calculated (min 70/82 to pass)
- ✅ Report generated in markdown
- ✅ Critical issues flagged with file paths
- ✅ Recommendations prioritized

**DO NOT:** Make changes during audit. This is verification only.

---

## 🚀 START COMMAND

```
AGENT: Begin Map Module Audit
- Read CLI_AGENT_MASTER.md first
- Follow 5-phase protocol
- Generate report in /tmp/map-audit-report.md
- Flag blockers immediately
```

**Expected Duration:** 40 minutes  
**Expected Output:** Comprehensive audit report with actionable items

---

**END OF PROMPT**
