# Codebase Structure

**Analysis Date:** 2026-02-15

## Directory Layout

```
gravl/
├── .git/                     # Git repository
├── .planning/
│   └── codebase/             # Analysis documents (this file)
├── agents/                   # AI agent configurations (not active codebase)
│   ├── architect/
│   ├── backend-dev/
│   ├── coach/
│   ├── frontend-dev/
│   ├── nutritionist/
│   └── reviewer/
├── backend/                  # Express.js REST API server
│   ├── src/
│   │   └── index.js          # Main server file (all routes and handlers)
│   ├── package.json          # Backend dependencies
│   ├── Dockerfile            # Docker build config
│   └── node_modules/         # Dependencies (not committed)
├── frontend/                 # React SPA application
│   ├── src/
│   │   ├── main.jsx          # App entry point (routing, providers)
│   │   ├── App.jsx           # Main app shell (view routing)
│   │   ├── index.css         # Global styles
│   │   ├── App.css           # App component styles
│   │   ├── pages/            # Full-page components (views)
│   │   ├── components/       # Reusable components
│   │   └── context/          # React Context providers
│   ├── index.html            # HTML template
│   ├── vite.config.js        # Vite build configuration
│   ├── package.json          # Frontend dependencies
│   ├── Dockerfile            # Docker build config
│   └── node_modules/         # Dependencies (not committed)
├── db/                       # Database schema and initialization
│   └── init.sql              # PostgreSQL schema definition
├── docker/                   # Docker-related files
├── docker-compose.yml        # Multi-container orchestration
├── README.md                 # Project overview
├── CLAUDE.md                 # LLM context file
└── TODO.md                   # Project tasks and notes
```

## Directory Purposes

**backend/src/:**
- Purpose: Backend application code
- Contains: Single Express server file with all routes, middleware, and database handlers
- Key files: `index.js` (14,361 lines, monolithic backend)

**frontend/src/:**
- Purpose: Frontend application source code
- Contains: React component files, styling, and global state management
- Key files: `App.jsx`, `main.jsx`, page components, AuthContext

**frontend/src/pages/:**
- Purpose: Full-page/route components (views)
- Contains: 8 page components handling entire view logic
- Key files:
  - `Dashboard.jsx` - Main view showing program and scheduled workout
  - `WorkoutPage.jsx` - Active workout tracking interface
  - `ProfilePage.jsx` - User profile and measurements
  - `ProgressPage.jsx` - Progress tracking and statistics
  - `LoginPage.jsx` - Authentication entry
  - `RegisterPage.jsx` - Account creation
  - `OnboardingWizard.jsx` - Initial profile setup
  - `WorkoutSelectPage.jsx` - Program/day selection

**frontend/src/components/:**
- Purpose: Reusable UI components
- Contains: Shared UI building blocks
- Key files: `Icons.jsx` - Icon system and icon name mapping

**frontend/src/context/:**
- Purpose: React Context providers for global state
- Contains: Authentication state and session management
- Key files: `AuthContext.jsx` - User login, registration, profile updates, token management

**db/:**
- Purpose: Database schema and initialization
- Contains: SQL scripts for schema creation and seed data
- Key files: `init.sql` - Creates 8 tables, indexes, and inserts PPL program template

**docker/:**
- Purpose: Docker-related configuration (currently minimal)
- Contains: Likely Dockerfile templates or configuration

## Key File Locations

**Entry Points:**
- `frontend/index.html` - HTML template that loads React app
- `frontend/src/main.jsx` - React bootstrap, BrowserRouter setup, routing definitions
- `frontend/src/App.jsx` - Main app shell, view routing, workout state management
- `backend/src/index.js` - Express server initialization, all API routes

**Configuration:**
- `frontend/vite.config.js` - Vite build config, dev proxy setup
- `frontend/package.json` - React, React Router, Vite dependencies
- `backend/package.json` - Express, PostgreSQL driver, JWT, bcrypt dependencies
- `docker-compose.yml` - Service definitions, networking, Traefik routing labels

**Core Logic:**
- `frontend/src/context/AuthContext.jsx` - Authentication and session management
- `backend/src/index.js` - All API endpoints, auth middleware, database queries
- `db/init.sql` - Database schema and initial data

**Styling:**
- `frontend/src/index.css` - Global styles, CSS variables, base components
- `frontend/src/App.css` - Application layout styles
- `frontend/src/pages/*.jsx` - Inline inline className attributes (CSS-in-JS via CSS class selectors)

## Naming Conventions

**Files:**
- **Pages:** PascalCase with "Page" suffix (e.g., `LoginPage.jsx`, `WorkoutPage.jsx`)
- **Components:** PascalCase (e.g., `Icons.jsx`)
- **Context:** PascalCase with "Context" suffix (e.g., `AuthContext.jsx`)
- **Backend routes:** Lowercase with slashes (e.g., `/api/auth/login`, `/api/user/profile`)
- **Database tables:** Lowercase with underscores (e.g., `workout_logs`, `program_exercises`)

**Directories:**
- **Page directory:** `pages/` (plural)
- **Component directory:** `components/` (plural)
- **Context directory:** `context/` (singular, convention)
- **Backend:** `src/` (single index.js file, no subdirectories)

**Functions:**
- **React components:** PascalCase (e.g., `function Dashboard()`)
- **Hooks/helpers:** camelCase (e.g., `fetchProgram()`, `getCoachGreeting()`, `getMuscleGroups()`)
- **Constants:** camelCase (e.g., `API_URL`, `weekdays`, `warmupExercises`)
- **Middleware:** camelCase (e.g., `authMiddleware`)

**Variables:**
- **State:** camelCase (e.g., `user`, `loading`, `selectedDay`)
- **Props:** camelCase (e.g., `onStartWorkout`, `onNavigate`)
- **API endpoints:** Lowercase kebab-case in URLs, snake_case in query parameters and JSON bodies

**Types/Database:**
- **Columns:** snake_case (e.g., `password_hash`, `onboarding_complete`, `program_exercise_id`)
- **Tables:** Lowercase plural (e.g., `users`, `programs`, `workout_logs`)
- **Foreign keys:** Follow pattern `{table_id}` (e.g., `user_id`, `program_id`)

## Where to Add New Code

**New Feature (e.g., new page/view):**
- Primary code: `frontend/src/pages/{FeatureName}Page.jsx`
- Styling: Inline CSS class names in JSX or extend `App.css`
- API calls: Direct fetch in component useEffect hooks, passing API_URL from page file
- Routing: Add Route to `frontend/src/main.jsx` with Route path and component
- If requires auth: Wrap in `<ProtectedRoute>` wrapper in main.jsx
- If requires context: Use `useAuth()` hook from AuthContext

**New API Endpoint (backend):**
- Location: Add route handler in `backend/src/index.js`
- Pattern: Use `app.get()`, `app.post()`, `app.put()` with path and handler function
- Database: Use `pool.query()` for PostgreSQL queries with parameterized queries ($1, $2, etc.)
- Auth: Add `authMiddleware` parameter if endpoint requires authentication
- Response: Return `res.json()` with data or error object
- Error handling: Wrap in try-catch, return appropriate status codes (400, 401, 404, 500)

**New Component:**
- Location: `frontend/src/components/{ComponentName}.jsx`
- Export: Default export or named export function component
- Props: Accept props for reusability, avoid direct API calls
- Integration: Import into pages or other components as needed

**New Database Table/Schema Change:**
- Location: `db/init.sql`
- Pattern: Add CREATE TABLE statement with proper data types and constraints
- Relations: Use FOREIGN KEY references and ON DELETE CASCADE
- Indexes: Add indexes for frequently queried columns (user_id, date, etc.)
- Seed data: Use INSERT statements with ON CONFLICT DO NOTHING
- Application: Changes apply on container restart (init.sql runs every startup)

**Utilities/Helpers:**
- Location: Keep in page file if only used there, or create in `frontend/src/utils/` if reused
- Pattern: Export as named functions (no separate utils directory currently exists)
- Examples: `getCoachGreeting()`, `getMuscleGroups()`, `getWeekStart()` are defined in pages

**Authentication/State:**
- Location: Extend `frontend/src/context/AuthContext.jsx` if global
- Location: Add to page component state with useState if local to page
- Pattern: Use `useAuth()` hook for auth context, create custom hooks if reusable state pattern emerges

## Special Directories

**node_modules/:**
- Purpose: Installed npm dependencies
- Generated: Yes (by npm install)
- Committed: No (.gitignore)
- Notes: Frontend and backend have separate node_modules directories

**.git/:**
- Purpose: Git version control repository
- Generated: Yes (git init)
- Committed: N/A (git internal)

**.planning/codebase/:**
- Purpose: Architecture and codebase analysis documents
- Generated: Yes (by mapping tools)
- Committed: Yes (for orchestrator reference)
- Contains: ARCHITECTURE.md, STRUCTURE.md, and other analysis documents

**agents/:**
- Purpose: Agent configuration (not part of active codebase)
- Generated: Yes (from setup)
- Committed: Yes
- Notes: These are orchestrator definitions, not part of the running application

---

*Structure analysis: 2026-02-15*
