# AdventureOS Architecture AdventureOS is a Next.js 16 full-stack monolith with npm workspaces. ## Layers ``` Browser (React + TanStack Query + Zustand) ↓ fetch /api/* Next.js Route Handlers (app/api/**) ↓ validation (lib/validation) + handleApi (lib/api) Domain Services (lib/services/**) ↓ Repositories (lib/repositories/**) — Drizzle queries Packages: @adventureos/db, @adventureos/shared ``` ## Frontend boundaries | Path | Responsibility | |------|----------------| | `app/*/page.tsx` | Route pages, data fetching via React Query | | `components/features/` | Domain UI components | | `components/ui/` | Reusable retro UI primitives | | `features/*/api.ts` | Typed client fetch wrappers | | `hooks/` | Shared React hooks (mutations, toasts) | | `stores/ui.ts` | Ephemeral UI state (toasts, modals) | | `themes/` | CSS token registry and runtime theme switching | ## Backend boundaries | Path | Responsibility | |------|----------------| | `app/api/**/route.ts` | HTTP entry; parse/validate; call services | | `lib/services/adventure/` | Daily adventures, materialization, scoring, templates | | `lib/services/reading/` | Shared reading log + action recording | | `lib/services/ai*.ts` | AI generation, config, memory, chat, context | | `lib/services/ai-memory.ts` | User-controlled personal AI memories | | `lib/services/ai-context.ts` | Layered context builder for local models | | `lib/services/ai-chat.ts` | Mentor chat sessions and messages | | `lib/services/day-boundary.ts` | Configurable day rollover (after-midnight logging) | | `lib/repositories/` | Drizzle data access only | | `lib/config/` | Environment variables and domain constants | | `lib/errors/` | Typed errors and response mapping | | `lib/validation/` | Zod request schemas | ## Data stores - **PostgreSQL** — primary app data via Drizzle (`packages/db`) - **Calibre metadata.db** — read-only SQLite via `better-sqlite3` when configured ## Service boundaries (rules) 1. Route handlers must not import Drizzle directly (use services/repositories). 2. Repositories contain no business rules. 3. Services orchestrate repositories, shared math, XP, and action events. 4. Client components use `features/*/api.ts`, not raw fetch scattered in UI. 5. `@adventureos/shared` holds pure domain types and formulas — no I/O. ## Known gaps See [KNOWN-ISSUES.md](./KNOWN-ISSUES.md). ## Refactor history See [REFACTOR-LOG.md](./REFACTOR-LOG.md).