# CLAUDE.md - Mawidi Quick Reference

## Essentials

- **Port**: 9000 (not 3000!)
- **Dev**: `cd mawidi-site && npm run dev`
- **Test**: `npm run test` | `npm run test:e2e`
- **Docker**: `npm run docker:infra:start` then `npm run docker:app:dev`
- **Database**: Convex (primary) -- NOT Prisma/Supabase for new code
- **Auth**: Clerk (primary, env-gated) -- NextAuth is legacy fallback

## User Working Style

The user operates as a **technical team lead** who delegates large, parallel workstreams with detailed upfront plans, then actively intervenes with firm course corrections when Claude misdiagnoses issues or works too sequentially. Expect **high-delegation with active course correction**:

- Act autonomously on delegated tasks — don't ask permission for obvious fixes, lint, or tests
- Report back with results, not questions about whether to proceed
- When given a multi-part task, decompose and dispatch parallel agents immediately
- Expect to be interrupted and redirected if you work sequentially or choose the wrong approach
- The user monitors output quality closely — 83% full/mostly achieved rate across 146 sessions

## Important Rules

1. **ALWAYS commit to git immediately** after making changes. Do not just edit files in-place — changes must be persisted via git commit so they survive container restarts and pulls. Never consider a task done until changes are committed and on the correct branch.
2. **Use parallel agent teams (Task tool)** for exploration and implementation whenever possible. Do NOT work sequentially on tasks that can be parallelized. When given a multi-part task, immediately decompose and dispatch sub-agents. User will interrupt if you work sequentially.
3. **Always use project-local CLI tools** (e.g., `npx prisma` not global `prisma`). Prisma schema is retained for types/documentation only — Convex is the active database.
4. **Use the /feature workflow** with worktrees and /commit-push-pr commands for feature implementation. Do NOT use Ralphy/threads or sequential single-branch workflows unless explicitly asked.
5. **Primary language is TypeScript**. Project uses Next.js, Convex, Clerk, Docker, and n8n. Translations are maintained in English and Arabic. Always lint after edits.
6. **Pre-commit hook false positives**: The pre-commit hook includes a secret scanner that triggers false positives on variable names like `JWT_SECRET` and `.env` file operations. When committing, identify and bypass specific false positives rather than fighting through multiple commit attempts.
7. **Verify the right target**: When applying fixes, always confirm you're editing files on the branch Docker is actually mounting, not just a worktree. Changes to the wrong branch mean the running app is unchanged.

## Core Principles (Boris Cherny Template)

### Simplicity First

Make every change as simple as possible and minimize code impact. No over-engineering.

### No Laziness

Find root causes. Avoid temporary fixes. Maintain senior-level engineering standards.

### Plan Mode Default

- Enter plan mode for any non-trivial task (3+ steps or architectural decisions)
- If something goes wrong, **STOP and re-plan immediately** — don't keep pushing
- Use plan mode for verification steps, not just building
- Write detailed specs upfront to reduce ambiguity

### Subagent Strategy

- Use subagents frequently to keep the main context window clean
- Offload research, exploration, and parallel analysis to subagents
- For complex problems, throw more compute via subagents
- Assign one task per subagent for focused execution

### Self-Improvement Loop

- After any correction from the user, update `tasks/lessons.md` with the pattern
- Write rules for yourself to prevent repeating the same mistake
- Ruthlessly iterate on these lessons until the mistake rate drops
- Review `tasks/lessons.md` at the start of each session

### Verification Before Done

- Never mark a task complete without proving it works
- Diff behavior between main and your changes when relevant
- Ask yourself: "Would a staff engineer approve this?"
- Run tests, check logs, and demonstrate correctness

### Demand Elegance (Balanced)

- For non-trivial changes, ask: "Is there a more elegant solution?"
- If a fix feels hacky, ask: "Knowing everything I know now, implement the elegant solution."
- Skip this for simple fixes — don't over-engineer
- Challenge your own work before presenting it

### Autonomous Bug Fixing

- When given a bug report: just fix it
- Use logs, errors, and failing tests to diagnose
- Require zero context switching from the user
- Fix failing CI tests automatically

### Task Management

1. **Plan First** — Write the plan in `tasks/todo.md` with checkable items
2. **Verify Plan** — Confirm the plan before implementation
3. **Track Progress** — Mark items complete as you go
4. **Explain Changes** — Provide a high-level summary at each step
5. **Document Results** — Add a review section to `tasks/todo.md`
6. **Capture Lessons** — Update `tasks/lessons.md` after corrections

## Test Accounts

- **User**: `guqo@mailinator.com` + OTP from MailHog (localhost:8025)
- **Staff**: `asim` / `AsimMawidi2025!` at `/staff/dashboard`

## Environment Files

**USE ONLY**: `mawidi-site/.env.local` for local development

| File                       | Purpose                                   | Status         |
| -------------------------- | ----------------------------------------- | -------------- |
| `.env.local`               | **Primary dev config** - all secrets here | ✅ USE THIS    |
| `.env.example`             | Template for new developers               | Reference only |
| `.env.docker`              | Docker container config                   | Docker only    |
| `.env.docker.example`      | Docker setup template                     | Reference only |
| `.env.voice-agent.example` | Voice agent feature template              | Reference only |

**DO NOT create** `.env`, `.env.development`, `.env.bak`, or other variants.
**Key APIs configured in `.env.local`:**

- `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` / `CLERK_SECRET_KEY` - Clerk auth
- `CONVEX_DEPLOYMENT` / `CONVEX_URL` - Convex database
- `GOOGLE_API_KEY` - Knowledge Base RAG (Gemini FileSearch)
- `GOOGLE_CLOUD_API_KEY` - AI image generation
- `STRIPE_*` - Payment processing
- `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` - Redis cache + rate limiting

## Project Overview

Mawidi is a **production-ready** B2B SaaS platform providing AI-powered appointment management, customer communication, and business operations solutions for service-based businesses across the **GCC region** (Qatar, Saudi Arabia, UAE, Kuwait, Bahrain, Oman).

### What We Do

- **AI Voice & Chat Agents**: Bilingual (Arabic/English) AI that handles customer inquiries, bookings, and payments via WhatsApp and voice
- **Smart Booking Automation**: <10 second response times, 24/7 availability, real-time calendar sync
- **Payment Collection**: Deposits, refunds, and financial reporting via local payment gateways (Mada, Visa, Apple Pay, Sadad)
- **No-Show Reduction**: Automated reminders achieving 85% average reduction in missed appointments
- **Operations Dashboard**: Unified inbox, analytics, SLA tracking, and owner digests

### Industries We Serve (17+ Verticals)

| Category                   | Examples                                               |
| -------------------------- | ------------------------------------------------------ |
| **Healthcare & Wellness**  | Clinics, Dental, Physiotherapy, Spas, Gyms, Veterinary |
| **Beauty & Personal Care** | Salons, Barbershops, Aesthetic Studios                 |
| **Food & Hospitality**     | Restaurants, Cafés, Hotels, Catering                   |
| **Retail**                 | Electronics, Furniture, Fashion Boutiques              |
| **Professional Services**  | Legal, Accounting, Insurance, Education                |
| **Property & Facilities**  | Real Estate, Leasing, Office Rentals                   |
| **Mobility & Industry**    | Transport, Construction, Manufacturing                 |
| **Entertainment & Events** | Venues, Sports Academies, Pet Services                 |
| **Public Sector**          | Non-profits, Community Centers, Government             |

**Stats**: 70+ pages • 333 API routes • 197+ components • 17+ verticals • 200+ tests

## Debugging Guidelines (MANDATORY)

**This project runs in Docker.** When debugging issues, always check Docker container status and logs FIRST before assuming code-level problems.

### Docker-First Diagnostic Protocol

Before investigating ANY code, run these checks first:

1. `docker compose ps` — are all containers healthy?
2. `docker compose logs --tail=30` — any recent errors?
3. Verify `.env` vars are loaded in the Docker container (especially `CONVEX_URL`, `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`)
4. Check Convex dashboard for function errors if DB queries fail
5. Confirm you're editing files on the branch Docker is actually mounting

**Only after all 5 are green, proceed to code-level debugging.**

### Parallel Root-Cause Diagnosis

For non-trivial bugs, spawn 5 parallel diagnosis agents BEFORE attempting any fix:

1. **Infrastructure Agent**: Docker status, logs, memory/CPU, env vars, service health
2. **Database Agent**: Convex function errors, adapter coverage gaps, schema mismatches between Prisma types and Convex schema
3. **Code Logic Agent**: Trace data flow from API route to DB call, type mismatches, missing await, incorrect response parsing
4. **Configuration Agent**: next.config, feature flags, role-based access lists, env vars, gating logic
5. **Recent Changes Agent**: `git log --oneline -20` and `git diff HEAD~5` for regressions

Each agent reports: (a) what they checked, (b) what they found, (c) confidence level. Synthesize all 5 reports, identify root cause, ONLY THEN propose a fix.

### Known Misdiagnosis Patterns to AVOID

- **Docker vs Code**: Do NOT blame host CPU overload when a container restart would fix it in seconds. Always check container state first.
- **Feature Tier vs Role-Based**: When a feature is missing, check the role-based allowed tabs/permissions list, not just the subscription tier gating.
- **Code Bug vs Convex Function Error**: Always check Convex dashboard/logs for function errors before assuming code logic errors.
- **Spam Filter vs Real Bug**: Browser extensions and honeypot fields can trigger false form failures — check these before debugging backend code.
- **Redirect loops / blank pages**: Check infrastructure first (is Postgres/Redis/Docker running?) before diving into application code.
- **Hypothesis cycling**: Don't spend more than 2 iterations on a single hypothesis. If a fix doesn't work after 2 attempts, step back and list alternative root causes.
- **Next.js SVG issues**: Use the `unoptimized` prop on `<Image>` for SVG files — don't reach for custom loaders first.
- **Missing UI elements**: Check webpack tree-shaking and barrel imports early, not just runtime filtering logic.
- **Phantom bugs after dependency changes**: Run `rm -rf .next node_modules/.cache` before rebuilding — stale webpack/Next.js caches are a top source of phantom bugs.

### Upfront Approach Clarification

Before implementing anything:

1. State your planned approach in 2-3 bullets
2. Identify the most likely root cause AND one alternative
3. Ask user to confirm before proceeding

This prevents the #1 friction type: wrong approach (30 occurrences in 146 sessions).

## Critical Patterns

- **New Feature**: types → validators → services → API → UI → tests
- **i18n**: `UI[params.lang].t.yourKey` | `UI[params.lang].dir` (rtl/ltr)
- **Database**: All queries go through `lib/db.ts` which routes to Convex via `lib/prisma-convex-adapter.ts`
- **Auth**: Check Clerk session first, fall back to NextAuth. Use `lib/clerk-user-bridge.ts` for user resolution
- **Staff API**: Always validate with `validateStaffSession(req)`

## Database Architecture (Convex + Prisma Adapter)

**Convex is the primary database.** All data flows through Convex queries and mutations.

- **How it works**: `lib/db.ts` exports a Prisma-compatible adapter (`lib/prisma-convex-adapter.ts`) that intercepts `prisma.*` calls and routes them to Convex. Existing API routes call `prisma.users.findUnique(...)` but hit Convex at runtime.
- **Never add direct Prisma DB calls** — always go through the adapter or write new Convex queries/mutations in `convex/`
- **Prisma schema** (`prisma/schema.prisma`) is kept as the canonical data model reference and for TypeScript type generation only
- **Supabase** is optional — only activates when `NEXT_PUBLIC_SUPABASE_URL` + `SUPABASE_SERVICE_ROLE_KEY` are set, used for post-mutation dual-write sync on critical tables (bookings, careers)
- Data-source routing lives in `lib/data-source.ts` — flip domains via env vars (e.g. `DS_BOOKINGS=convex`), don't hardcode
- After editing adapters or Convex functions, run `npx tsc --noEmit` — zero new TS errors before committing

## Auth Architecture (Clerk + NextAuth)

**Clerk is the primary auth system** when `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` is set.

- **Middleware**: `clerkMiddleware()` wraps all requests, adding auth context. Falls through to NextAuth when Clerk is not configured.
- **ClerkProvider**: Wraps the app in `app/layout.tsx` conditionally
- **Clerk routes**: `/app/[lang]/clerk-login` and `/app/[lang]/clerk-signup`
- **Convex auth**: `convex/auth.config.ts` expects Clerk issuer via `CLERK_ISSUER_URL`
- **User bridge**: `lib/clerk-user-bridge.ts` resolves users across both auth systems
- **NextAuth fallback**: When Clerk env vars are not set, NextAuth handles auth with Google OAuth + credentials provider
- **Staff login**: Still uses Redis OTP system (`lib/staff-session.ts`)

## Security Review Checklist

When auditing or reviewing Convex/API code:
- Check all `mutation()` calls for missing auth — prefer `internalMutation` for server-only operations
- File uploads (avatars, attachments): enforce extension allowlists **server-side**, not just client-side
- When assessing a potential vulnerability, state confidence level (1–10) and true/false positive verdict before recommending fixes

## Pre-Deploy (MANDATORY)

```bash
npx tsc --noEmit             # Zero TypeScript errors
npm run lint                  # Zero lint errors
npm run test                  # All tests pass
npx convex deploy --dry-run   # Verify Convex functions compile
```

## Key Files

- **Auth (Clerk)**: `lib/clerk.ts`, `lib/clerk-user-bridge.ts`, `lib/clerk-theme.ts`, `middleware.ts`
- **Auth (NextAuth legacy)**: `lib/auth.ts`, `lib/staff-session.ts`
- **DB (Convex)**: `convex/schema.ts`, `convex/customers/`, `convex/organizations/`, `convex/auth.config.ts`
- **DB Adapter**: `lib/db.ts`, `lib/prisma-convex-adapter.ts` (routes prisma.* calls to Convex)
- **Data Source Routing**: `lib/data-source.ts` (flip domains via env vars e.g. `DS_BOOKINGS=convex`)
- **Supabase (optional sync)**: `lib/supabase.ts` (conditional post-mutation dual-write)
- **Stripe**: `lib/stripe.ts`, `app/api/stripe/webhook/route.ts`
- **Services**: `lib/services/*` (7 modules)
- **Adapters**: `lib/adapters/*` (Convex-backed service adapters)

## Workflow Best Practices (Boris Cherny Style)

### Plan Mode First

For any non-trivial task, START in Plan Mode (Shift+Tab twice).
Iterate on the plan until it's solid, then switch to execution.

### Parallel Development with Worktrees

Run multiple Claude sessions on different features:

```bash
/worktree create feature-auth    # Session 1: Auth work
/worktree create feature-payments # Session 2: Payments work
/worktree list                    # See all active work
/worktree merge                   # Finish and merge
```

### Model Preference

- **Opus 4.5 + thinking**: All non-trivial tasks (fewer iterations = faster)
- **Sonnet**: Quick lookups, simple edits

### Verification is Critical

Every implementation MUST have verification:

- UI changes → Browser test or screenshot
- API changes → Unit test or curl verification
- Schema changes → `npm run check:schema`

## One-Command Feature Development

### `/feature` - Complete Automated Workflow

The easiest way to build a feature. One command handles everything:

```bash
/feature auth-oauth Add OAuth2 login with Google provider
```

**What happens automatically:**

1. **Setup** → Creates isolated worktree (`feature/auth-oauth`)
2. **Plan** → Enters plan mode, researches codebase, creates implementation plan
3. **Approval** → Shows plan, waits for your OK
4. **Implement** → Builds the feature following the plan
5. **Verify** → Runs lint, typecheck, tests (fixes issues automatically)
6. **Ship** → Commits, pushes, creates PR
7. **Merge** → Asks to merge, cleans up worktree

**Format:** `/feature <branch-name> <description of what to build>`

### Quick Commands Reference

| Command                        | What It Does                                        |
| ------------------------------ | --------------------------------------------------- |
| `/feature name description`    | Full workflow: worktree → plan → build → PR → merge |
| `/fix description`             | Quick in-place fix with auto-verification           |
| `/fix branch-name description` | Isolated fix: worktree → fix → PR → merge           |
| `/worktree create name`        | Just create worktree (manual workflow)              |
| `/commit-push-pr`              | Just commit and create PR (no worktree)             |

### When to Use What

- **New feature**: `/feature name desc` - full automated workflow
- **Quick bug fix**: `/fix desc` - stays in current branch, fast
- **Risky/big fix**: `/fix branch-name desc` - isolated with PR
- **Parallel work**: `/worktree create` - manual control, multiple sessions
- **Already done coding**: `/commit-push-pr` - just ship it

## Thread Types - Multi-Agent Orchestration

Choose the right thread pattern for your task:

| Thread | Pattern  | Command     | Best For                             |
| ------ | -------- | ----------- | ------------------------------------ |
| **P**  | Parallel | `/p-thread` | Independent research, max throughput |
| **C**  | Chained  | `/c-thread` | Multi-phase with human review        |
| **F**  | Fusion   | `/f-thread` | Creative tasks, pick best result     |
| **B**  | Big      | `/b-thread` | Complex systems, nested agents       |
| **L**  | Long     | `/l-thread` | Batch processing, high autonomy      |

**Quick Examples:**

```bash
/p-thread "research auth patterns" --threads 4           # Parallel exploration
/c-thread "schema → API → UI → tests" --trust medium    # Sequential with reviews
/f-thread "write signup CTA" --mode synthesize          # Generate options, combine best
/b-thread "implement full auth system" --depth 2        # Meta-orchestration
/l-thread "migrate all routes to zod" --trust high      # Autonomous batch
```

**Four Ways to Improve:**

1. **More threads** (width) - `--threads 8`
2. **Longer threads** (depth) - `--max-iterations 50`
3. **Thicker threads** (density) - combine operations per agent
4. **Fewer checkpoints** (trust) - `--trust high`

See [claudedocs/thread-types.md](./claudedocs/thread-types.md) for full documentation.

## Advanced Workflow Patterns

### Batch TypeScript Error Fixes with Parallel Agents

When fixing multiple TypeScript errors across the project:

1. Run `npx tsc --noEmit` and categorize errors by directory
2. Spawn parallel agents — one per directory — to fix errors simultaneously
3. Each agent verifies its directory is clean before reporting done
4. Do NOT work sequentially on 80+ errors — always parallelize by directory

### Self-Healing CI Fix Loop

When CI or pre-commit hooks fail after a commit:

1. Parse the error output and categorize: TypeScript errors, lint failures, secret scanner false positives, test failures
2. Spawn parallel fix agents per category:
   - **TypeScript agent**: reads failing files, fixes type errors, runs `npx tsc --noEmit`
   - **Lint agent**: runs linter, applies auto-fixes, handles edge cases like duplicate keys
   - **Hook agent**: identifies false positives in secret scanning (like `JWT_SECRET` variable names or `.env.docker` deletions) and handles appropriately
3. After all agents complete, re-run the full CI check locally
4. Loop max 3 iterations until pipeline is green
5. Report summary of what was fixed and iterations needed

### Test-Driven Autonomous Feature Implementation

For new features, use strict test-first approach:

- **Phase 1 (Agent 1)**: Write comprehensive failing tests covering happy path, edge cases, error handling, integration points
- **Phase 2 (Agent 2)**: Implement code, running `npx tsc --noEmit` and tests after each file, loop until all pass (max 5 iterations)
- **Phase 3 (Agent 3)**: Run full test suite for regressions, full typecheck, pre-commit checks
- **Phase 4**: Only after all phases pass, run `/commit-push-pr`

## Legacy Commands

For backwards compatibility, these still work:

- `/swarm` - Original parallel orchestration
- `/ralph-auto` - Autonomous issue fixing (uses L-Thread patterns)

## Autonomous Issue Fixing with /ralph-auto

For bug fixes and codebase-wide issues, use `/ralph-auto` for autonomous 4-phase execution:

```bash
/ralph-auto Fix CSRF token issues --max-iterations 25 --promise CSRF_FIXED
/ralph-auto Fix authentication session problems
/ralph-auto Update deprecated API endpoints --promise API_UPDATED
```

**What it does automatically:**

1. **Discovery** - Spawns 4 parallel Explore agents to find all related code
2. **Analysis** - Documents patterns, identifies inconsistencies
3. **Fixes** - Creates beads issues and fixes them one by one
4. **Verification** - Runs lint/tests/typecheck before completing

**Options:**

- `--max-iterations N` - Max loop iterations (default: 20)
- `--promise KEYWORD` - Completion signal (auto-generated if omitted)

## Ralphy - Autonomous PRD Execution

Ralphy runs Claude Code autonomously through a PRD until all tasks complete. See [RALPHY.md](./RALPHY.md) for full docs.

### Quick Start

```bash
# 1. Create PRD with checkbox tasks
cat > PRD.md << 'EOF'
# Feature: User Notifications

- [ ] Create notifications table in Prisma schema
- [ ] Add GET /api/notifications endpoint with pagination
- [ ] Add POST /api/notifications/mark-read endpoint
- [ ] Create NotificationBell component with badge
- [ ] Write tests for notification endpoints
EOF

# 2. Run Ralphy
./ralphy.sh
```

### Choosing Parallel Concurrency

| Task Type            | `--max-parallel` | Why                |
| -------------------- | ---------------- | ------------------ |
| Independent features | `4-6`            | No file conflicts  |
| Same directory work  | `2-3`            | Some overlap risk  |
| Same file changes    | `1` (sequential) | Avoid conflicts    |
| Testing tasks        | `4-8`            | Tests are isolated |

```bash
# Independent features - max throughput
./ralphy.sh --parallel --max-parallel 6

# Related components - moderate parallelism
./ralphy.sh --parallel --max-parallel 3

# Tightly coupled changes - sequential
./ralphy.sh
```

### Common Patterns

```bash
# Feature branch per task with PRs
./ralphy.sh --branch-per-task --create-pr --base-branch main

# Fast prototyping (skip tests/lint)
./ralphy.sh --fast --max-iterations 5

# Preview without executing
./ralphy.sh --dry-run --verbose

# YAML with dependency groups
./ralphy.sh --yaml tasks.yaml --parallel --max-parallel 4
```

## 📚 Detailed Docs (Load As Needed)

| Topic                         | File                                                                                 | When to Load                             |
| ----------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------- |
| **Ralphy (PRD Loop)**         | [RALPHY.md](./RALPHY.md)                                                             | Autonomous task execution, PRD format    |
| **Ralphy Parallel Guide**     | [RALPHY-PARALLEL-GUIDE.md](./RALPHY-PARALLEL-GUIDE.md)                               | Parallel execution patterns, when to use |
| **Thread Types**              | [claudedocs/thread-types.md](./claudedocs/thread-types.md)                           | Choosing P/C/F/B/L thread patterns       |
| **Multi-Agent Orchestration** | [claudedocs/multi-agent-orchestration.md](./claudedocs/multi-agent-orchestration.md) | Complex tasks, parallel agents           |
| **MCP & Token Optimization**  | [claudedocs/mcp.md](./claudedocs/mcp.md)                                             | Using MCP servers, reducing tokens       |
| **Architecture & Patterns**   | [claudedocs/architecture.md](./claudedocs/architecture.md)                           | Adding features, understanding structure |
| **Database System**           | [claudedocs/database.md](./claudedocs/database.md)                                   | DB operations, sync, schema changes      |
| **Security & Auth**           | [claudedocs/security.md](./claudedocs/security.md)                                   | Auth flows, rate limiting, CSRF          |
| **Features Overview**         | [claudedocs/features.md](./claudedocs/features.md)                                   | Staff dashboard, billing, careers        |
| **Testing Guide**             | [claudedocs/testing.md](./claudedocs/testing.md)                                     | Writing tests, running suites            |
| **Commands Reference**        | [claudedocs/commands.md](./claudedocs/commands.md)                                   | All npm scripts, docker commands         |
| **Deployment**                | [claudedocs/deployment.md](./claudedocs/deployment.md)                               | DigitalOcean, Docker, CI/CD              |

## Known Friction Patterns & Solutions

### Friction Statistics (from 146 sessions)

| Type                  | Count | Prevention                                                    |
| --------------------- | ----- | ------------------------------------------------------------- |
| Wrong Approach        | 30    | State approach in 2-3 bullets, ask to confirm before starting |
| Buggy Code            | 14    | Use test-driven approach, run tests after every file          |
| User Rejected Action  | 12    | Ask before non-trivial actions, especially destructive ones   |
| Misunderstood Request | 7     | Clarify ambiguous requests, don't assume context              |
| Tool Failure          | 3     | Fall back to API/unit test verification when browser fails    |
| Tool Errors           | 2     | Retry once, then try alternative approach                     |

### Top 3 Friction Patterns

**1. Incorrect Initial Diagnosis (waste debugging time)**

- Claude latches onto the wrong root cause first — e.g., blaming CPU overload when a container restart takes 0.32s, or assuming tier-gating when it's a role-based tab list bug
- **Fix**: Always run Docker-first diagnostic protocol. When debugging UI access issues, check role-based permissions AND tier gating — don't assume one over the other
- **User Context Matters**: Ask about account tier, environment setup, and recent changes BEFORE diving into code

**2. Ignoring Preferred Workflows (user interrupts to redirect)**

- Claude defaults to sequential, ad-hoc approaches instead of parallel agent teams and /feature worktree workflows
- **Fix**: For multi-file work, ALWAYS use parallel agents. For features, ALWAYS use /feature workflow. This is non-negotiable unless user explicitly says otherwise
- Sequential work = user will interrupt = wasted time

**3. Changes Not Persisted (fixes don't stick)**

- Claude applies fixes to worktrees instead of the running branch, skips git commits, or fails to verify in the right environment
- **Fix**: After EVERY code change: (1) git commit immediately, (2) confirm which branch, (3) verify that's the branch Docker mounts
- "Make sure this change is permanent" should NEVER need to be said — always commit

## Verification Fallback Strategy

When browser/Playwright verification fails or Docker connectivity breaks during testing, **fall back to API-level or unit test verification** rather than abandoning the session. Do not keep retrying flaky browser automation — switch to:

1. `curl` or `fetch` for API endpoint verification
2. Unit tests for logic verification
3. `npx tsc --noEmit` for type verification
4. Direct database queries for data verification

## Auto-Verification (MANDATORY - DO THIS AUTOMATICALLY)

**For ALL code changes, Claude MUST automatically:**

1. Run `npm run lint -- <file>` after editing any .ts/.tsx file
2. Run relevant tests after implementation
3. Fix ANY failures WITHOUT asking - just fix them
4. Run `npx tsc --noEmit` before reporting completion
5. Only say "done" when ALL checks pass

**Never report completion until:**

- [ ] All tests pass
- [ ] No lint errors
- [ ] No TypeScript errors
- [ ] Code actually works

**If a test fails:** Fix it immediately and re-run. Do not ask permission.
**If lint fails:** Fix it immediately. Do not ask permission.
**If types fail:** Fix it immediately. Do not ask permission.

This is automatic behavior - not optional. The user should never have to ask for verification.

## Critical Reminders

1. **Port 9000** - Always 9000, not 3000
2. **RTL/LTR** - Test both Arabic and English
3. **Convex deploy** - Run `npx convex deploy --dry-run` before deploy
4. **Type Safety** - Strict TypeScript, no `any`
5. **Server Components** - Default, use 'use client' only when needed
6. **Auto-verify** - Always run tests/lint after changes (see above)
7. **Default branch is `master`** - NOT `main`. Always use `origin/master` in git commands. Auto-detect in scripts.
8. **Worktree sync** - After any PR merge, run `./sync-worktrees.sh` to rebase all worktree branches. Pre-push hook blocks pushes from behind branches.

## 🚫 PROTECTED FILES - DO NOT MODIFY

**These files should NEVER be changed unless a full redesign is explicitly requested:**

### Navigation & Layout

- `components/Nav.tsx` - Main navigation bar
- `lib/config/content/navigation.ts` - Navigation links and sectors
- `components/Footer.tsx` - Site footer
- `app/[lang]/layout.tsx` - Root layout

### Page Structure & Routing

- `lib/config/index.ts` - Core site configuration
- `lib/config/services.ts` - Services configuration (SERVICES, SERVICE_KEYS)
- `lib/config/locations.ts` - Locations configuration

### Industry Pages (with components)

- `app/[lang]/industries/*` - All industry pages and their components
- `app/[lang]/industries/health-care/components/*` - Healthcare section components
- `app/[lang]/industries/health-care/shared/*` - Shared industry components

### Feature Pages (with components)

- `app/[lang]/features/dashboard/*` - Dashboard page and components
- `app/[lang]/features/messages/*` - Messages page
- `app/[lang]/features/growth/*` - Growth page
- `app/[lang]/features/integrations/*` - Integrations page

### Service Pages

- `app/[lang]/services/[service]/*` - Dynamic service pages
- `app/[lang]/services/deposits-payments/*` - Deposits page
- `app/[lang]/services/waitlist-broadcast/*` - Waitlist page

### AI & Voice Pages

- `app/[lang]/ai-voice-agents/*` - AI Voice Agents page

### Pricing Pages

- `app/[lang]/pricing/*` - Pricing page and PricingClient component

**If you need to modify these files, STOP and ask the user first.**
**These are stable, production-tested pages that should not be altered for bug fixes or minor changes.**


## Worktree Sync Protocol (MANDATORY)

### Worktree Gotchas
- **Generated files**: Before rebasing a worktree, clean untracked generated files first: `rm -rf lib/generated/` — otherwise rebase may fail with untracked file conflicts.
- **zsh glob expansion**: Escape Next.js `[lang]` bracket paths in zsh with quotes or backslashes (e.g. `'app/[lang]'` or `app/\[lang\]`) to avoid glob expansion errors in shell commands.
- **Default branch**: Always auto-detect (`git remote show origin | grep 'HEAD branch'`) — this repo uses `origin/master`, NOT `origin/main`.

Before ANY commit, push, or PR creation in a worktree:
1. `git fetch origin`
2. `git log HEAD..origin/master --oneline` — check if behind
3. If behind: `git rebase origin/master`
4. Only push after a clean rebase

When starting work in any worktree, ALWAYS run first:
`git fetch origin && git rebase origin/master`

NEVER push a branch that is behind origin/master.
NEVER create a PR without rebasing onto latest origin/master first.
NEVER skip this even for small changes.
If rebase has conflicts, STOP and fix them before doing anything else.
