> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brainstormer.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Repository Structure

> Monorepo layout, service structure patterns, and file conventions for the Brainstormer V2 codebase.

## Monorepo Layout

Brainstormer V2 uses a **Turbo + npm workspaces** monorepo with three top-level workspace directories:

```
brainstormerv2/
├── apps/                          # Application layer
│   └── web/                       # Next.js frontend (Port 3000)
│
├── services/                      # Backend microservices
│   ├── gateway/                   # API Gateway (Port 4000)
│   ├── auth/                      # Auth Service (Port 4001)
│   ├── bot/                       # Agent Service (Port 4002)
│   ├── realtime-audio/            # Voice Service (Port 4003)
│   ├── knowledge/                 # Knowledge Service (Port 4005)
│   └── hitl/                      # HITL Service (Port 4006)
│
├── packages/                      # Shared packages
│   ├── shared/                    # Common utilities, types, crypto
│   └── config/                    # Base tsconfig
│
├── infrastructure/                # Infrastructure configs
│   └── postgres/
│       └── migrations/            # Sequential SQL migrations
│
├── docs/                          # Documentation
│   ├── architecture/              # Active design docs
│   ├── deployment/                # Deployment guides
│   ├── testing/                   # Test guides
│   └── archived/                  # Historical docs
│
├── scripts/                       # Utility scripts
│   └── dev-tools/                 # Development utilities
│
├── CLAUDE.md                      # Development guide
├── README.md                      # Project overview
├── SOLUTION_ARCHITECTURE.md       # System architecture
├── ROADMAP.md                     # Feature roadmap
└── CHANGELOG.md                   # Version history
```

## Backend Service Structure

All backend services follow the same standardized layout:

```
src/
├── index.ts          # Fastify server entry point
├── config.ts         # Environment config (reads .env + platform_config DB)
├── env.ts            # Zod env schema validation
├── routes/           # API route handlers
├── services/         # Business logic
├── repositories/     # Data access (raw SQL queries via pg driver)
├── middleware/        # Fastify hooks (auth, RBAC, etc.)
├── database/         # DB connection setup (pg Pool)
├── types/            # TypeScript interfaces
└── utils/            # Helpers
```

<Note>
  Each service has its own `CLAUDE.md` file with endpoints, configuration, and patterns specific to that module.
</Note>

## Request Flow

All authenticated frontend API calls follow this path:

```mermaid theme={null}
graph LR
    FE[Frontend<br/>Port 3000] -->|REST| GW[API Gateway<br/>Port 4000]
    GW -->|Verify JWT| GW
    GW -->|Headers: user-id,<br/>organization-id,<br/>user-email,<br/>x-platform-role,<br/>x-org-role| SVC[Backend Service]
```

The gateway verifies the JWT signature and forwards auth context as headers to downstream services.

<Warning>
  When adding new backend routes, you **must** also add the corresponding proxy route in `services/gateway/src/routes/proxy.ts`.
</Warning>

## Key Conventions

### Authentication Pattern

Every service follows the same JWT pattern:

* **NEVER** read `request.headers["organization-id"]` or `request.headers["user-id"]` directly
* **ALWAYS** use JWT auth middleware via `fastify.addHook("preHandler", ...)`
* **ALWAYS** access user info via `request.user.organizationId` and `request.user.id`
* Downstream services trust gateway-forwarded headers; the gateway verifies signatures with `verifyJwt(token, JWT_SECRET)`

### Database Access

* Raw SQL with parameterized queries (no ORM)
* Repository pattern for data access
* Connection pooling via `pg` Pool
* Credentials: db `brainstormer`, user `brainstormer`, password set by `POSTGRES_PASSWORD` on `localhost:5432`

### Platform Config

API keys and settings can be stored in the `platform_config` DB table:

<Steps>
  <Step title="DB Storage">
    Auth service manages `GET/POST /auth/admin/config` for encrypted key-value pairs.
  </Step>

  <Step title="Gateway Proxy">
    Gateway proxies config requests to auth service.
  </Step>

  <Step title="Service Loading">
    Services fetch config on startup. DB values take precedence over env vars.
  </Step>

  <Step title="Encryption">
    Sensitive values encrypted with AES-256-GCM via `packages/shared/src/crypto.ts`.
  </Step>
</Steps>

## Documentation Organization

### Root-Level Files

| File                       | Purpose                          |
| -------------------------- | -------------------------------- |
| `README.md`                | Project overview and quick start |
| `CLAUDE.md`                | Development guide and patterns   |
| `SOLUTION_ARCHITECTURE.md` | High-level architecture          |
| `ROADMAP.md`               | Feature roadmap                  |
| `CHANGELOG.md`             | Version history                  |

### Module-Level CLAUDE.md

Each service has its own `CLAUDE.md`:

| File                                | Content                                       |
| ----------------------------------- | --------------------------------------------- |
| `services/bot/CLAUDE.md`            | Chat flow, RAG, billing, endpoints            |
| `services/knowledge/CLAUDE.md`      | RAG pipeline, vector store, embeddings, graph |
| `services/auth/CLAUDE.md`           | JWT, platform config, user/org management     |
| `services/gateway/CLAUDE.md`        | Proxy routing, auth middleware, rate limiting |
| `services/realtime-audio/CLAUDE.md` | Voice pipeline, config DB fallback            |
| `apps/web/CLAUDE.md`                | Routes, API client, components, state         |
| `packages/shared/CLAUDE.md`         | Shared utilities, crypto                      |

### Docs Subfolders

| Folder               | Content                                  |
| -------------------- | ---------------------------------------- |
| `docs/architecture/` | Active design and architecture documents |
| `docs/deployment/`   | Deployment and setup guides              |
| `docs/testing/`      | Test guides                              |
| `docs/archived/`     | Superseded/historical docs               |

### File Naming

* **UPPERCASE** for major docs (e.g., `KNOWLEDGE_BASE_SYSTEM.md`)
* **lowercase-with-hyphens** for scripts
* Never commit test artifacts to root

## Development Commands

<CodeGroup>
  ```bash Start all services theme={null}
  npm run dev
  ```

  ```bash Build all services theme={null}
  npm run build
  ```

  ```bash Type checking theme={null}
  npm run typecheck
  ```

  ```bash Run tests theme={null}
  npm test
  ```

  ```bash Lint theme={null}
  npm run lint
  ```

  ```bash Format theme={null}
  npm run format
  ```

  ```bash Clean theme={null}
  npm run clean
  ```

  ```bash Start single service theme={null}
  cd services/bot && npm run dev
  ```
</CodeGroup>

## Infrastructure (Docker)

| Container               | Port | Purpose              |
| ----------------------- | ---- | -------------------- |
| `brainstormer-postgres` | 5432 | PostgreSQL 15        |
| `brainstormer-redis`    | 6379 | Redis 7              |
| `brainstormer-chroma`   | 8000 | ChromaDB (vector DB) |

```bash theme={null}
# Start infrastructure
docker start brainstormer-postgres brainstormer-redis brainstormer-chroma
```

## Migrations

Migrations live in `infrastructure/postgres/migrations/`. New files use a UTC timestamp prefix — `$(date -u +%Y%m%d%H%M%S)_short_snake_name.sql` — enforced by the `migration-guard` CI job; legacy files keep their sequential `NNN_` numbers and sort first. Run them with:

```bash theme={null}
docker exec -i brainstormer-postgres psql -U brainstormer -d brainstormer < infrastructure/postgres/migrations/<file>.sql
```
