# Tara Development Guide

Complete guide to setting up and running the Tara meditation platform for local
development.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Project Structure](#project-structure)
- [Infrastructure Setup](#infrastructure-setup)
- [Environment Configuration](#environment-configuration)
- [Running Applications](#running-applications)
- [Testing](#testing)
- [Code Quality](#code-quality)
- [IDE Setup](#ide-setup)
- [Troubleshooting](#troubleshooting)

---

## Prerequisites

### Required Software

| Software | Version | Purpose            | Installation                     |
| -------- | ------- | ------------------ | -------------------------------- |
| Node.js  | 18+     | JavaScript runtime | [nodejs.org](https://nodejs.org) |
| pnpm     | 10+     | Package manager    | `npm install -g pnpm`            |
| Docker   | 24+     | Container runtime  | [docker.com](https://docker.com) |
| Git      | 2.40+   | Version control    | System package manager           |

### Optional (for Mobile Development)

| Software       | Version | Purpose            | Installation                                           |
| -------------- | ------- | ------------------ | ------------------------------------------------------ |
| Expo CLI       | Latest  | Mobile development | `npm install -g expo-cli`                              |
| Xcode          | 15+     | iOS Simulator      | Mac App Store                                          |
| Android Studio | Latest  | Android Emulator   | [developer.android.com](https://developer.android.com) |
| Maestro        | Latest  | Mobile E2E testing | `brew install maestro`                                 |

### Optional (for Testing)

| Software   | Version | Purpose         | Installation                        |
| ---------- | ------- | --------------- | ----------------------------------- |
| Playwright | Latest  | Web E2E testing | `pnpm e2e:install` (auto-installed) |
| k6         | Latest  | Load testing    | `brew install k6`                   |

---

## Quick Start

Get Tara running locally in under 5 minutes:

```bash
# 1. Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# 2. Install dependencies
pnpm install

# 3. Start infrastructure (PostgreSQL, Redis, MinIO, Mailpit)
docker compose -f docker/docker-compose.dev.yml up -d

# 4. Verify infrastructure is running
docker compose -f docker/docker-compose.dev.yml ps

# 5. Copy environment files
cp apps/tara/web/.env.example apps/tara/web/.env.local

# 6. Start the API (in one terminal)
pnpm nx serve @tara/api

# 7. Start the web app (in another terminal)
pnpm nx dev @tara/web

# 8. Open in browser
open http://localhost:3001
```

---

## Project Structure

```
oshun/
├── apps/
│   └── tara/
│       ├── api/                 # Backend REST API
│       │   ├── src/
│       │   │   ├── routes/      # API route handlers
│       │   │   ├── services/    # Business logic
│       │   │   ├── db/          # Database schemas & queries
│       │   │   ├── middleware/  # Auth, validation, etc.
│       │   │   └── lib/         # Utilities
│       │   ├── test/            # Tests
│       │   │   ├── unit/
│       │   │   ├── integration/
│       │   │   └── load/        # k6 load tests
│       │   └── Dockerfile
│       │
│       ├── web/                 # Next.js web application
│       │   ├── src/
│       │   │   ├── app/         # App Router pages
│       │   │   ├── components/  # React components
│       │   │   ├── lib/         # Utilities
│       │   │   └── styles/      # Global styles
│       │   ├── e2e/             # Playwright tests
│       │   ├── public/          # Static assets
│       │   └── Dockerfile
│       │
│       ├── mobile/              # React Native/Expo app
│       │   ├── app/             # Expo Router pages
│       │   ├── components/      # React Native components
│       │   ├── hooks/           # Custom hooks
│       │   ├── e2e/             # Maestro tests
│       │   └── app.json         # Expo config
│       │
│       ├── content/             # Static content
│       │   ├── teachers/        # Teacher profiles
│       │   └── meditations/     # Meditation data
│       │
│       └── docs/                # Tara-specific docs
│
├── libs/
│   ├── shared/                  # Shared foundation libraries
│   │   ├── types/               # TypeScript definitions
│   │   ├── errors/              # Error handling
│   │   ├── logging/             # Logging utilities
│   │   └── ...
│   └── tara/                    # Tara-specific libraries
│
└── docker/
    └── docker-compose.dev.yml   # Development infrastructure
```

---

## Infrastructure Setup

### Core Services

Start all required services:

```bash
docker compose -f docker/docker-compose.dev.yml up -d
```

| Service    | Port(s)    | Purpose                    | Access                |
| ---------- | ---------- | -------------------------- | --------------------- |
| PostgreSQL | 5432       | Primary database           | `localhost:5432`      |
| Redis      | 6379       | Caching & sessions         | `localhost:6379`      |
| MinIO      | 9000, 9001 | Object storage (S3-compat) | http://localhost:9001 |
| Mailpit    | 1025, 8025 | Email testing              | http://localhost:8025 |

### Database Setup

PostgreSQL is automatically configured with the following databases:

- `oshun_dev` - Main development database
- `tara` - Tara-specific database

To connect directly:

```bash
# Using psql
psql postgresql://oshun:oshun_dev@localhost:5432/tara

# Using Drizzle Studio (visual DB browser)
cd apps/tara/api && pnpm db:studio
```

### Database Migrations

```bash
# Generate migrations from schema changes
pnpm nx run @tara/api:db:generate

# Apply migrations
pnpm nx run @tara/api:db:migrate

# Push schema changes directly (dev only)
pnpm nx run @tara/api:db:push

# Reset database (DESTRUCTIVE)
pnpm nx run @tara/api:db:drop
```

### Optional Services

Start additional services using profiles:

```bash
# Search capabilities (Elasticsearch)
docker compose -f docker/docker-compose.dev.yml --profile search up -d

# Vector database (Qdrant)
docker compose -f docker/docker-compose.dev.yml --profile vectors up -d

# Admin tools (Redis Commander, PgAdmin, Kafka UI)
docker compose -f docker/docker-compose.dev.yml --profile tools up -d

# All services
docker compose -f docker/docker-compose.dev.yml --profile all up -d
```

### Stopping Infrastructure

```bash
# Stop containers (preserves data)
docker compose -f docker/docker-compose.dev.yml down

# Stop and remove all data
docker compose -f docker/docker-compose.dev.yml down -v
```

---

## Environment Configuration

### Root Environment

The root `.env` file contains shared configuration:

```bash
# Database
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
TARA_DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/tara

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_URL=redis://localhost:6379
TARA_REDIS_PREFIX=tara:

# Object Storage (MinIO)
S3_ENDPOINT=http://localhost:9000
S3_ACCESS_KEY=minioadmin
S3_SECRET_KEY=minioadmin
S3_BUCKET=tara-dev
S3_REGION=us-east-1
```

### Web App Environment

Create `apps/tara/web/.env.local` from the example:

```bash
cp apps/tara/web/.env.example apps/tara/web/.env.local
```

Key variables:

```bash
# API Connection (required)
NEXT_PUBLIC_API_BASE_URL=http://localhost:8080
NEXT_PUBLIC_WS_URL=ws://localhost:8080

# Environment
NEXT_PUBLIC_ENVIRONMENT=development
NEXT_PUBLIC_VERSION=local

# Features
NEXT_PUBLIC_ENABLE_PWA=true
NEXT_PUBLIC_ENABLE_OFFLINE=true
NEXT_PUBLIC_DEBUG=true

# Optional: CDN (leave empty for local)
NEXT_PUBLIC_CDN_URL=

# Optional: Analytics (leave empty for dev)
NEXT_PUBLIC_SENTRY_DSN=
NEXT_PUBLIC_ANALYTICS_ID=

# Optional: Payments (leave empty for dev)
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
```

### API Environment

The API uses root environment variables. For local overrides, create
`apps/tara/api/.env.local`:

```bash
# Server
PORT=8080
HOST=0.0.0.0
NODE_ENV=development

# Database
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/tara

# JWT Secrets (generate secure values for production)
JWT_SECRET=dev-jwt-secret-change-in-production
JWT_REFRESH_SECRET=dev-refresh-secret-change-in-production

# Session
SESSION_SECRET=dev-session-secret

# Email (Mailpit for local dev)
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_FROM=tara@localhost
```

### Mobile Environment

Expo uses app.json for configuration. For environment-specific settings, use
`eas.json` or environment variables:

```bash
# For local API connection
EXPO_PUBLIC_API_URL=http://localhost:8080

# For device testing (use your machine's IP)
EXPO_PUBLIC_API_URL=http://192.168.1.100:8080
```

---

## Running Applications

### Web Application

```bash
# Development server (hot reload)
pnpm nx dev @tara/web
# Or from the directory:
cd apps/tara/web && pnpm dev

# Access at: http://localhost:3001
```

**Available Scripts:**

| Script            | Description                 |
| ----------------- | --------------------------- |
| `pnpm dev`        | Start development server    |
| `pnpm build`      | Build for production        |
| `pnpm start`      | Start production server     |
| `pnpm lint`       | Run ESLint                  |
| `pnpm type-check` | TypeScript type checking    |
| `pnpm storybook`  | Start Storybook (port 6007) |

### API Server

```bash
# Development server (auto-reload on changes)
pnpm nx serve @tara/api
# Or from the directory:
cd apps/tara/api && pnpm dev

# Access at: http://localhost:8080
# API docs at: http://localhost:8080/docs
```

**Available Scripts:**

| Script             | Description                 |
| ------------------ | --------------------------- |
| `pnpm dev`         | Start with hot reload (tsx) |
| `pnpm build`       | Compile TypeScript          |
| `pnpm start`       | Run compiled build          |
| `pnpm db:studio`   | Database browser            |
| `pnpm db:generate` | Generate migrations         |
| `pnpm db:migrate`  | Apply migrations            |
| `pnpm db:push`     | Push schema changes         |

### Mobile Application

```bash
# Start Expo development server
pnpm nx start @tara/mobile
# Or from the directory:
cd apps/tara/mobile && pnpm start

# Run on iOS Simulator
pnpm nx start:ios @tara/mobile

# Run on Android Emulator
pnpm nx start:android @tara/mobile

# Run in web browser
pnpm nx start:web @tara/mobile
```

**Available Scripts:**

| Script               | Description              |
| -------------------- | ------------------------ |
| `pnpm start`         | Start Expo dev server    |
| `pnpm ios`           | Run on iOS Simulator     |
| `pnpm android`       | Run on Android Emulator  |
| `pnpm web`           | Run in web browser       |
| `pnpm prebuild`      | Generate native projects |
| `pnpm build:ios`     | Build iOS app (EAS)      |
| `pnpm build:android` | Build Android app (EAS)  |

### Running All Services

For full-stack development, run in separate terminals:

```bash
# Terminal 1: Infrastructure
docker compose -f docker/docker-compose.dev.yml up

# Terminal 2: API
pnpm nx serve @tara/api

# Terminal 3: Web
pnpm nx dev @tara/web

# Terminal 4 (optional): Mobile
pnpm nx start @tara/mobile
```

Or use Nx's run-many:

```bash
# Run API and Web in parallel
pnpm nx run-many -t serve,dev -p @tara/api,@tara/web
```

---

## Testing

### Unit Tests

**Web App:**

```bash
cd apps/tara/web

pnpm test              # Run all tests
pnpm test:watch        # Watch mode
pnpm test:coverage     # With coverage report
```

**API:**

```bash
cd apps/tara/api

pnpm test              # Run unit tests
pnpm test:watch        # Watch mode
```

### Integration Tests (API)

Requires a test database:

```bash
# Create test database
createdb tara_test

# Or via Docker
docker exec oshun-dev-postgres createdb -U oshun tara_test

# Run integration tests
cd apps/tara/api
pnpm test:integration

# Watch mode
pnpm test:integration:watch

# All tests (unit + integration)
pnpm test:all
```

**Test Database Configuration:**

```bash
# Set in environment or defaults to:
TEST_DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/tara_test
```

### E2E Tests (Web)

Uses Playwright for browser automation:

```bash
cd apps/tara/web

# Install browsers (first time only)
pnpm e2e:install

# Run all E2E tests
pnpm e2e

# Interactive UI mode
pnpm e2e:ui

# Debug mode (step through tests)
pnpm e2e:debug

# Run with visible browser
pnpm e2e:headed

# View test report
pnpm e2e:report

# Generate test code by recording
pnpm e2e:codegen
```

**Playwright Configuration:**

Tests run against browsers:

- Chromium (Desktop)
- Firefox (Desktop)
- WebKit/Safari (Desktop)
- Mobile Chrome (Pixel 5)
- Mobile Safari (iPhone 12)

### E2E Tests (Mobile)

Uses Maestro for mobile testing:

```bash
# Install Maestro (macOS)
brew install maestro

cd apps/tara/mobile

# Run all E2E tests
pnpm e2e

# Quick smoke tests
pnpm e2e:smoke

# Full regression suite
pnpm e2e:regression

# Interactive test builder
pnpm e2e:studio
```

**Required Test Users:**

Create these in your test environment:

```bash
# Regular test user
TEST_USER_EMAIL=e2e-test@tara.app
TEST_USER_PASSWORD=TestPassword123!

# Premium test user
PREMIUM_USER_EMAIL=e2e-premium@tara.app
PREMIUM_USER_PASSWORD=PremiumPassword123!
```

### Load Tests (API)

Uses k6 for performance testing:

```bash
# Install k6 (macOS)
brew install k6

cd apps/tara/api

# Run full load test suite
pnpm load-test

# Quick smoke test
pnpm load-test:smoke

# Stress test
pnpm load-test:stress
```

**Test Scenarios:**

| Scenario | Users | Duration | Purpose                |
| -------- | ----- | -------- | ---------------------- |
| Smoke    | 1     | 30s      | Basic functionality    |
| Load     | 50    | 5m       | Normal load simulation |
| Stress   | 200   | 12m      | Find breaking point    |
| Soak     | 30    | 10m      | Long-running stability |

**Performance Thresholds:**

- p95 Response: < 500ms (general)
- p95 Health Check: < 100ms
- p95 Search: < 800ms
- Error Rate: < 1%

### Performance Tests (Web)

```bash
cd apps/tara/web

# Run Lighthouse audit
pnpm lighthouse

# Collect metrics only
pnpm lighthouse:collect

# Assert against thresholds
pnpm lighthouse:assert
```

---

## Code Quality

### Linting

```bash
# Lint all Tara projects
pnpm nx run-many -t lint -p @tara/api,@tara/web,@tara/mobile

# Lint specific project
pnpm nx lint @tara/web

# Auto-fix issues
pnpm nx lint @tara/web -- --fix
```

### Type Checking

```bash
# Check all projects
pnpm nx run-many -t type-check -p @tara/api,@tara/web,@tara/mobile

# Check specific project
pnpm nx type-check @tara/web
```

### Formatting

```bash
# Format all files
pnpm prettier --write "apps/tara/**/*.{ts,tsx,js,jsx,json,md}"

# Check formatting
pnpm prettier --check "apps/tara/**/*.{ts,tsx,js,jsx,json,md}"
```

### Pre-commit Hooks

The monorepo uses lint-staged with Husky for pre-commit checks:

- ESLint for JS/TS files
- Prettier for formatting
- Type checking

---

## IDE Setup

### VS Code (Recommended)

**Recommended Extensions:**

- ESLint (`dbaeumer.vscode-eslint`)
- Prettier (`esbenp.prettier-vscode`)
- TypeScript Vue Plugin (Volar) (`Vue.volar`)
- Tailwind CSS IntelliSense (`bradlc.vscode-tailwindcss`)
- Expo Tools (`expo.vscode-expo-tools`)
- Playwright Test (`ms-playwright.playwright`)

**Workspace Settings:**

Create `.vscode/settings.json`:

```json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "tailwindCSS.experimental.classRegex": [
    ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],
    ["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
  ]
}
```

### WebStorm / IntelliJ

1. Enable ESLint: Preferences → Languages & Frameworks → JavaScript → Code
   Quality Tools → ESLint
2. Enable Prettier: Preferences → Languages & Frameworks → JavaScript → Prettier
3. Configure TypeScript: Use workspace TypeScript version

### Debugging

**VS Code Launch Configurations:**

Create `.vscode/launch.json`:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug API",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "runtimeArgs": ["nx", "serve", "@tara/api"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    },
    {
      "name": "Debug Web",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3001",
      "webRoot": "${workspaceFolder}/apps/tara/web"
    },
    {
      "name": "Debug API Tests",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "runtimeArgs": ["nx", "test", "@tara/api", "--", "--run"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal"
    }
  ]
}
```

---

## Troubleshooting

### Infrastructure Issues

**Port conflicts:**

```bash
# Check what's using a port
lsof -i :5432  # PostgreSQL
lsof -i :6379  # Redis
lsof -i :3001  # Web app
lsof -i :8080  # API

# Stop conflicting process
kill -9 <PID>

# Or stop existing containers
docker stop $(docker ps -q)
```

**Database not starting:**

```bash
# Check logs
docker logs oshun-dev-postgres

# Reset database completely
docker compose -f docker/docker-compose.dev.yml down -v
docker compose -f docker/docker-compose.dev.yml up -d
```

**Redis connection refused:**

```bash
# Verify Redis is running
docker exec oshun-dev-redis redis-cli ping
# Should return: PONG

# Check Redis logs
docker logs oshun-dev-redis
```

### Build Issues

**TypeScript errors after update:**

```bash
# Clear Nx cache
pnpm nx reset

# Reinstall dependencies
rm -rf node_modules pnpm-lock.yaml
pnpm install
```

**Next.js build errors:**

```bash
# Clear Next.js cache
rm -rf apps/tara/web/.next

# Rebuild
pnpm nx build @tara/web
```

**Expo build issues:**

```bash
# Clear Expo cache
cd apps/tara/mobile
pnpm prebuild:clean
```

### Test Issues

**Integration tests failing:**

```bash
# Ensure test database exists
docker exec oshun-dev-postgres createdb -U oshun tara_test

# Reset test database
cd apps/tara/api
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/tara_test pnpm db:push
```

**E2E tests timing out:**

```bash
# Ensure services are running
docker compose -f docker/docker-compose.dev.yml ps
pnpm nx serve @tara/api  # Should be running
pnpm nx dev @tara/web    # Should be running

# Run with debug output
DEBUG=pw:api pnpm e2e
```

**Mobile E2E tests failing:**

```bash
# Ensure simulator/emulator is running
xcrun simctl list devices  # iOS
adb devices                 # Android

# Check Maestro connection
maestro test --debug apps/tara/mobile/e2e/flows/smoke.yaml
```

### Common Errors

**"Cannot find module '@tara/...' "**

```bash
# Build shared libraries first
pnpm nx run-many -t build -p 'tag:scope:shared'
```

**"ECONNREFUSED 127.0.0.1:5432"**

```bash
# Start infrastructure
docker compose -f docker/docker-compose.dev.yml up -d

# Wait for PostgreSQL to be ready
until docker exec oshun-dev-postgres pg_isready; do sleep 1; done
```

**"JWT_SECRET is not defined"**

```bash
# Set in environment
export JWT_SECRET=dev-secret-change-in-production
export JWT_REFRESH_SECRET=dev-refresh-secret-change-in-production

# Or add to .env.local in API directory
```

---

## Additional Resources

- [Architecture Documentation](../architecture.md)
- [API Documentation](../api/README.md)
- [Deployment Guide](./deployment.md)
- [Content Management Guide](./content.md)
