diff --git a/CLAUDE.md b/CLAUDE.md index f925c51e2..f945c6bad 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,678 +1,176 @@ # CLAUDE.md -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. +This file provides guidance to Claude Code when working with this repository. -## Monorepo Overview +## Purpose & Constraints -This is a pnpm workspace monorepo containing multiple product applications with shared packages. All projects use Supabase for database/auth and follow similar architectural patterns. +Multi-app SaaS monorepo with shared packages and centralized authentication. -**Package Manager:** pnpm 9.15.0 (use `pnpm` for all commands) -**Build System:** Turborepo -**Node Version:** 20+ +- **Package Manager:** pnpm 9.15+ (use `pnpm` for all commands) +- **Build System:** Turborepo +- **Node Version:** 20+ +- **NEVER create files unless necessary** - prefer editing existing files +- **NEVER create documentation** unless explicitly requested +- **Prefer editing over creating** - check if functionality exists first -## Detailed Guidelines - -For comprehensive guidelines on code patterns and conventions, see the `.claude/` directory: - -| Document | Purpose | -|----------|---------| -| [`.claude/GUIDELINES.md`](.claude/GUIDELINES.md) | Main reference overview | -| [`.claude/guidelines/code-style.md`](.claude/guidelines/code-style.md) | Formatting, naming, linting | -| [`.claude/guidelines/database.md`](.claude/guidelines/database.md) | Drizzle ORM, schema patterns | -| [`.claude/guidelines/testing.md`](.claude/guidelines/testing.md) | Jest/Vitest, mock factories | -| [`.claude/guidelines/nestjs-backend.md`](.claude/guidelines/nestjs-backend.md) | Controllers, services, DTOs | -| [`.claude/guidelines/error-handling.md`](.claude/guidelines/error-handling.md) | Go-style Result types, error codes | -| [`.claude/guidelines/sveltekit-web.md`](.claude/guidelines/sveltekit-web.md) | Svelte 5 runes, stores | -| [`.claude/guidelines/expo-mobile.md`](.claude/guidelines/expo-mobile.md) | React Native, NativeWind | -| [`.claude/guidelines/authentication.md`](.claude/guidelines/authentication.md) | Mana Core Auth integration | - -**Always consult these guidelines before making changes.** - -## Projects - -| Project | Description | Apps | -| ------------ | ---------------------------- | --------------------------------------------------------- | -| **manacore** | Multi-app ecosystem platform | Expo mobile, SvelteKit web | -| **manadeck** | Card/deck management | NestJS backend, Expo mobile, SvelteKit web | -| **picture** | AI image generation | Expo mobile, SvelteKit web, Astro landing | -| **chat** | AI chat application | NestJS backend, Expo mobile, SvelteKit web, Astro landing | -| **zitare** | Daily inspiration quotes | NestJS backend, Expo mobile, SvelteKit web, Astro landing | -| **contacts** | Contact management | NestJS backend, SvelteKit web | - -### Archived Projects (`apps-archived/`) - -These projects are temporarily archived and excluded from the workspace. To re-activate, move back to `apps/`. - -| Project | Description | -| ------------------ | -------------------------------- | -| **bauntown** | Community website for developers | -| **maerchenzauber** | AI story generation | -| **memoro** | Voice memo & AI analysis | -| **news** | News aggregation | -| **nutriphi** | Nutrition tracking | -| **reader** | Reading app | -| **uload** | URL shortener | -| **wisekeep** | AI wisdom extraction from video | -| **techbase** | Software comparison platform | -| **inventory** | Inventory management | -| **presi** | Presentation tool | -| **storage** | Cloud storage | - -## Development Commands - -For detailed local development setup, see **[docs/LOCAL_DEVELOPMENT.md](docs/LOCAL_DEVELOPMENT.md)**. - -### Quick Start (Recommended) - -Use `dev:*:full` commands to start any app with automatic database setup: - -```bash -pnpm docker:up # Start PostgreSQL, Redis, MinIO -pnpm dev:chat:full # Start chat with auth + auto DB setup -pnpm dev:zitare:full # Start zitare with auth + auto DB setup -pnpm dev:contacts:full # Start contacts with auth + auto DB setup -pnpm dev:calendar:full # Start calendar with auth + auto DB setup -pnpm dev:clock:full # Start clock with auth + auto DB setup -pnpm dev:todo:full # Start todo with auth + auto DB setup -pnpm dev:picture:full # Start picture with auth + auto DB setup -``` - -These commands automatically: -1. Create the database if missing -2. Push the latest schema -3. Start auth, backend, and web with colored output - -### Database Setup - -```bash -pnpm setup:db # Setup ALL databases and schemas -pnpm setup:db:chat # Setup just chat -pnpm setup:db:auth # Setup just auth -``` - -### Individual App Commands - -```bash -# Start specific project (runs all apps in project) -pnpm run manacore:dev -pnpm run manadeck:dev -pnpm run picture:dev -pnpm run chat:dev -pnpm run zitare:dev -pnpm run contacts:dev - -# Start specific app within project -pnpm run dev:chat:mobile # Just mobile app -pnpm run dev:chat:backend # Just NestJS backend -pnpm run dev:chat:app # Web + backend together - -# Build & quality -pnpm run build -pnpm run type-check -pnpm run format -``` - -Each project has its own `CLAUDE.md` with detailed project-specific commands. - -## Architecture Patterns - -### Monorepo Structure +## Monorepo Structure ``` manacore-monorepo/ -├── apps/ # Active SaaS product applications -│ ├── chat/ -│ │ ├── apps/ -│ │ │ ├── backend/ # NestJS API -│ │ │ ├── mobile/ # Expo React Native app -│ │ │ ├── web/ # SvelteKit web app -│ │ │ └── landing/ # Astro marketing page -│ │ └── packages/ # Project-specific shared code -│ ├── manadeck/ -│ ├── picture/ +├── apps/ # Active SaaS applications +│ ├── chat/ # AI chat (backend, mobile, web, landing) +│ ├── picture/ # AI image generation +│ ├── zitare/ # Daily quotes +│ ├── contacts/ # Contact management │ └── ... -├── apps-archived/ # Archived apps (excluded from workspace) -│ ├── bauntown/ -│ ├── maerchenzauber/ -│ ├── memoro/ -│ ├── news/ -│ ├── nutriphi/ -│ ├── reader/ -│ ├── uload/ -│ └── wisekeep/ -├── games/ # Game projects -│ └── {game-name}/ # Individual games -├── services/ # Standalone microservices -│ └── mana-core-auth/ # Central authentication service -├── packages/ # Monorepo-wide shared packages -└── docker/ # Docker configuration files +├── services/ +│ └── mana-core-auth/ # Central auth service (port 3001) +├── packages/ # Shared packages (@manacore/*) +├── .claude/ # Code guidelines (detailed patterns) +└── docs/ # Technical documentation ``` -### Standard Project Structure (inside apps/) +## Quick Start -``` -apps/{project}/ -├── apps/ -│ ├── backend/ # NestJS API (when present) -│ ├── mobile/ # Expo React Native app -│ ├── web/ # SvelteKit web app -│ └── landing/ # Astro marketing page -├── packages/ # Project-specific shared code -└── package.json +```bash +# Start infrastructure (PostgreSQL, Redis, MinIO) +pnpm docker:up + +# Start any app with automatic DB setup +pnpm dev:chat:full # Chat with auth + backend + web +pnpm dev:zitare:full # Zitare with auth + backend + web +pnpm dev:picture:full # Picture with auth + backend + web +pnpm dev:contacts:full # Contacts with auth + backend + web ``` -### Turborepo Configuration +## Technology Stack -**CRITICAL: Avoid Recursive Turbo Calls** +| App Type | Stack | +|----------|-------| +| **Backend** | NestJS 10-11 + Drizzle ORM + PostgreSQL | +| **Web** | SvelteKit 2 + Svelte 5 (runes mode) | +| **Mobile** | Expo SDK 52-54 + React Native + NativeWind | +| **Landing** | Astro 5 + Tailwind CSS | +| **Auth** | mana-core-auth (EdDSA JWT, port 3001) | -Parent workspace packages (e.g., `apps/chat/package.json`, `apps/zitare/package.json`) must **NEVER** have scripts that call `turbo run ` for tasks that turbo orchestrates from the root. +## Critical Gotchas + +### 1. Turborepo Infinite Loops +**NEVER** put `turbo run ` in child package.json for tasks orchestrated from root. ```jsonc -// WRONG - Creates infinite recursion! +// ❌ WRONG - Creates infinite recursion // apps/chat/package.json { "scripts": { "type-check": "turbo run type-check", // DON'T DO THIS - "build": "turbo run build", // DON'T DO THIS - "lint": "turbo run lint" // DON'T DO THIS + "build": "turbo run build" // DON'T DO THIS } } -// CORRECT - Let root turbo handle orchestration -// apps/chat/package.json +// ✅ CORRECT - Let root turbo handle it { "scripts": { - "dev": "turbo run dev" // OK for dev (persistent task, scoped) - // No type-check, build, lint scripts - handled by root turbo + "dev": "turbo run dev" // OK (persistent task) + // No type-check, build, lint - handled by root } } ``` -**Why this matters:** When root turbo runs `type-check`, it finds packages with `type-check` scripts and runs them. If that script is `turbo run type-check`, it spawns another turbo process that does the same thing → infinite loop. This causes tasks to run for 10+ minutes with thousands of duplicate task entries. - -**The `dev` script exception:** Using `turbo run dev` in parent packages is acceptable because: -1. It's typically run directly on that package (scoped) -2. Dev tasks are persistent and turbo handles them differently - -**Current turbo.json settings:** -- `concurrency: "5"` - Parallel task limit (adjust based on machine) -- `type-check` has `dependsOn: ["^type-check"]` - Dependencies are checked first - -### Technology Stack by App Type - -**Mobile Apps (Expo):** - -- React Native 0.76-0.81 + Expo SDK 52-54 -- Expo Router (file-based routing) -- NativeWind (Tailwind for React Native) -- Zustand (state management) - -**Web Apps (SvelteKit):** - -- SvelteKit 2.x + Svelte 5 -- Tailwind CSS -- Supabase SSR auth - -**Landing Pages (Astro):** - -- Astro 5.x -- Tailwind CSS -- Static site generation - -**Backends (NestJS):** - -- NestJS 10-11 -- TypeScript -- Supabase integration - -### Authentication Architecture - -All projects use **mana-core-auth** as the central authentication service: - -``` -┌─────────────┐ ┌─────────────┐ ┌────────────────┐ -│ Client │────>│ Backend │────>│ mana-core-auth │ -│ (Web/Mobile)│ │ (NestJS) │ │ (port 3001) │ -└─────────────┘ └─────────────┘ └────────────────┘ - │ │ │ - │ Bearer token │ POST /validate │ - │ │ {token} │ - │ │<────────────────────│ - │ │ {valid, payload} │ - │<──────────────────│ │ - │ Response │ │ -``` - -#### Key Components - -| Component | Purpose | -| ------------------------------- | -------------------------------------------------- | -| `services/mana-core-auth` | Central auth service (Better Auth + EdDSA JWT) | -| `@manacore/shared-nestjs-auth` | Shared NestJS guards/decorators for JWT validation | -| `@mana-core/nestjs-integration` | Extended NestJS module with auth + credits | -| `@manacore/shared-auth` | Client-side auth for web/mobile apps | - -#### NestJS Backend Integration - -**Option 1: Simple auth only** - Use `@manacore/shared-nestjs-auth`: +### 2. Svelte 5 Runes ONLY +Always use Svelte 5 runes syntax, never old Svelte syntax. ```typescript -// In your controller -import { JwtAuthGuard, CurrentUser, CurrentUserData } from '@manacore/shared-nestjs-auth'; - -@Controller('api') -@UseGuards(JwtAuthGuard) -export class MyController { - @Get('profile') - getProfile(@CurrentUser() user: CurrentUserData) { - return { userId: user.userId, email: user.email }; - } -} -``` - -**Option 2: Auth + Credits** - Use `@mana-core/nestjs-integration`: - -```typescript -// app.module.ts -import { ManaCoreModule } from '@mana-core/nestjs-integration'; - -@Module({ - imports: [ - ManaCoreModule.forRootAsync({ - imports: [ConfigModule], - useFactory: (config: ConfigService) => ({ - appId: config.get('APP_ID'), - serviceKey: config.get('MANA_CORE_SERVICE_KEY'), - debug: config.get('NODE_ENV') === 'development', - }), - inject: [ConfigService], - }), - ], -}) -export class AppModule {} - -// In controller -import { AuthGuard } from '@mana-core/nestjs-integration/guards'; -import { CurrentUser } from '@mana-core/nestjs-integration/decorators'; -import { CreditClientService } from '@mana-core/nestjs-integration'; - -@Controller('api') -@UseGuards(AuthGuard) -export class ApiController { - constructor(private creditClient: CreditClientService) {} - - @Post('generate') - async generate(@CurrentUser() user: any) { - await this.creditClient.consumeCredits(user.sub, 'generation', 10, 'AI generation'); - // ... do work - } -} -``` - -#### Required Environment Variables - -```env -# All backends need this -MANA_CORE_AUTH_URL=http://localhost:3001 - -# For development bypass (optional) -NODE_ENV=development -DEV_BYPASS_AUTH=true -DEV_USER_ID=your-test-user-id - -# For credit operations (optional) -MANA_CORE_SERVICE_KEY=your-service-key -APP_ID=your-app-id -``` - -#### JWT Token Structure (EdDSA) - -```json -{ - "sub": "user-id", - "email": "user@example.com", - "role": "user", - "sid": "session-id", - "exp": 1764606251, - "iss": "manacore", - "aud": "manacore" -} -``` - -#### Testing Auth Integration - -```bash -# 1. Start mana-core-auth -pnpm dev:auth - -# 2. Start a backend (e.g., Zitare) -pnpm dev:zitare:backend - -# 3. Get a token -TOKEN=$(curl -s -X POST http://localhost:3001/api/v1/auth/login \ - -H "Content-Type: application/json" \ - -d '{"email": "test@example.com", "password": "password"}' | jq -r '.accessToken') - -# 4. Call protected endpoint -curl http://localhost:3007/api/favorites \ - -H "Authorization: Bearer $TOKEN" -``` - -#### Integrated Backends - -| Backend | Package | Port | -| -------- | ------------------------------- | ---- | -| Chat | `@mana-core/nestjs-integration` | 3002 | -| Picture | `@manacore/shared-nestjs-auth` | 3006 | -| Zitare | `@manacore/shared-nestjs-auth` | 3007 | -| Presi | Custom (same pattern) | 3008 | -| ManaDeck | `@mana-core/nestjs-integration` | 3009 | - -### Svelte 5 Runes Mode (Web Apps) - -All SvelteKit apps use Svelte 5 runes: - -```typescript -// CORRECT - Svelte 5 +// ✅ CORRECT - Svelte 5 runes let count = $state(0); let doubled = $derived(count * 2); -$effect(() => { - console.log(count); -}); +$effect(() => console.log(count)); -// WRONG - Old Svelte syntax +// ❌ WRONG - Old Svelte syntax let count = 0; $: doubled = count * 2; ``` -## Shared Packages (`packages/`) - -| Package | Purpose | -| ------------------------------- | ----------------------------------------------- | -| `@manacore/shared-nestjs-auth` | NestJS JWT validation guards via mana-core-auth | -| `@mana-core/nestjs-integration` | NestJS module with auth guards + credit client | -| `@manacore/shared-auth` | Client-side auth service for web/mobile apps | -| `@manacore/shared-storage` | S3-compatible storage (MinIO local, Hetzner prod) | -| `@manacore/shared-supabase` | Unified Supabase client | -| `@manacore/shared-types` | Common TypeScript types | -| `@manacore/shared-utils` | Utility functions | -| `@manacore/shared-ui` | React Native UI components | -| `@manacore/shared-theme` | Theme configuration | -| `@manacore/shared-i18n` | Internationalization | - -Import shared packages: +### 3. Authentication Integration +All backends need `MANA_CORE_AUTH_URL=http://localhost:3001` env var. ```typescript -import { createAuthService } from '@manacore/shared-auth'; -import { formatDate, truncate } from '@manacore/shared-utils'; +// Use @manacore/shared-nestjs-auth for JWT validation +import { JwtAuthGuard, CurrentUser } from '@manacore/shared-nestjs-auth'; + +@UseGuards(JwtAuthGuard) +@Get('profile') +getProfile(@CurrentUser() user: CurrentUserData) { + return { userId: user.userId }; +} ``` -## Database (Supabase) - -- All projects use Supabase for PostgreSQL database, auth, and storage -- Row Level Security (RLS) policies enforce access control via JWT claims -- Each project has its own Supabase project/schema -- Types typically generated via `supabase gen types` - -## Object Storage (MinIO / Hetzner) - -S3-compatible object storage for file uploads, generated images, etc. - -### Architecture - -| Environment | Service | Purpose | -|-------------|---------|---------| -| **Local** | MinIO (Docker) | S3-compatible local storage | -| **Production** | Hetzner Object Storage | Cost-effective S3-compatible cloud storage | - -### Local Development - -```bash -# Start infrastructure (includes MinIO) -pnpm docker:up - -# MinIO Web Console: http://localhost:9001 -# Username: minioadmin -# Password: minioadmin - -# S3 API endpoint: http://localhost:9000 -``` - -### Pre-configured Buckets - -| Bucket | Project | Purpose | -|--------|---------|---------| -| `picture-storage` | Picture | AI-generated images | -| `chat-storage` | Chat | User file uploads | -| `manadeck-storage` | ManaDeck | Card/deck assets | -| `nutriphi-storage` | NutriPhi | Meal photos | -| `presi-storage` | Presi | Presentation slides | -| `calendar-storage` | Calendar | Calendar attachments | -| `contacts-storage` | Contacts | Contact avatars/files | -| `storage-storage` | Storage | Cloud drive files | - -### Usage in Backend +### 4. Go-Style Error Handling +Use Result types, never throw exceptions in application code. ```typescript -import { createPictureStorage, generateUserFileKey, getContentType } from '@manacore/shared-storage'; +// ✅ CORRECT +import { Result, ok, err } from '@manacore/shared-errors'; -const storage = createPictureStorage(); +async function getUser(id: string): Promise> { + if (!id) return err('INVALID_USER_ID', 'User ID required'); + return ok(user); +} -// Upload -const key = generateUserFileKey(userId, 'image.png'); -const result = await storage.upload(key, buffer, { - contentType: getContentType('image.png'), - public: true, -}); - -// Download -const data = await storage.download(key); - -// Presigned URLs -const uploadUrl = await storage.getUploadUrl(key, { expiresIn: 3600 }); +// ❌ WRONG +async function getUser(id: string): Promise { + if (!id) throw new Error('User ID required'); + return user; +} ``` -### Environment Variables +### 5. Environment Variables +Generated from `.env.development` via `pnpm setup:env` (auto-runs after install). -```env -# Local (in .env.development) -S3_ENDPOINT=http://localhost:9000 -S3_REGION=us-east-1 -S3_ACCESS_KEY=minioadmin -S3_SECRET_KEY=minioadmin +- **Mobile (Expo):** `EXPO_PUBLIC_*` prefix +- **Web (SvelteKit):** `PUBLIC_*` prefix +- **Backend (NestJS):** No prefix -# Production (Hetzner) -S3_ENDPOINT=https://fsn1.your-objectstorage.com -S3_REGION=fsn1 -S3_ACCESS_KEY=your-access-key -S3_SECRET_KEY=your-secret-key -``` - -## Landing Pages (Cloudflare Pages) - -All landing pages are deployed to Cloudflare Pages using Direct Upload via Wrangler CLI. - -### Landing Pages - -| Project | Package | Cloudflare Project | URL | -|---------|---------|-------------------|-----| -| Chat | `@chat/landing` | `chat-landing` | https://chat-landing.pages.dev | -| Picture | `@picture/landing` | `picture-landing` | https://picture-landing.pages.dev | -| ManaCore | `@manacore/landing` | `manacore-landing` | https://manacore-landing.pages.dev | -| ManaDeck | `@manadeck/landing` | `manadeck-landing` | https://manadeck-landing.pages.dev | -| Zitare | `@zitare/landing` | `zitare-landing` | https://zitare-landing.pages.dev | - -### Local Deployment +## Common Commands ```bash -# First time: Login to Cloudflare -pnpm cf:login - -# Create projects (one-time setup) -pnpm cf:projects:create - -# Deploy individual landing page -pnpm deploy:landing:chat -pnpm deploy:landing:picture -pnpm deploy:landing:manacore -pnpm deploy:landing:manadeck -pnpm deploy:landing:zitare - -# Deploy all landing pages -pnpm deploy:landing:all - -# List all projects -pnpm cf:projects:list +pnpm install # Install dependencies +pnpm dev:{app}:full # Start app with DB setup +pnpm type-check # Type check all packages +pnpm format # Format code +pnpm build # Build all packages +pnpm docker:up # Start local infrastructure +pnpm setup:env # Regenerate .env files ``` -### Adding New Landing Pages +## Documentation -1. Create the landing page in `apps/{project}/apps/landing/` -2. Add `wrangler.toml`: - ```toml - name = "{project}-landing" - compatibility_date = "2024-12-01" - pages_build_output_dir = "dist" - ``` -3. Add deploy script to root `package.json`: - ```json - "deploy:landing:{project}": "pnpm --filter @{project}/landing build && npx wrangler pages deploy apps/{project}/apps/landing/dist --project-name={project}-landing" - ``` -4. Create Cloudflare project: `npx wrangler pages project create {project}-landing --production-branch=main` +- **Code Patterns:** [.claude/GUIDELINES.md](.claude/GUIDELINES.md) - Detailed technical guidelines +- **Local Setup:** [docs/LOCAL_DEVELOPMENT.md](docs/LOCAL_DEVELOPMENT.md) - Complete dev environment setup +- **Database:** [docs/DATABASE_MIGRATIONS.md](docs/DATABASE_MIGRATIONS.md) - Migration best practices +- **Deployment:** [docs/DEPLOYMENT_ARCHITECTURE.md](docs/DEPLOYMENT_ARCHITECTURE.md) - Full deployment guide +- **All Docs:** [docs/README.md](docs/README.md) - Complete documentation index +- **Project-Specific:** Navigate to `apps/{project}/CLAUDE.md` for project details -### Custom Domains +## Detailed Guidelines -```bash -# Add custom domain to a project -npx wrangler pages project add-domain chat-landing chat.manacore.app -``` +For comprehensive code patterns and conventions: -## Server Access +| Guideline | Purpose | +|-----------|---------| +| [code-style.md](.claude/guidelines/code-style.md) | Formatting, naming, linting | +| [database.md](.claude/guidelines/database.md) | Drizzle ORM, schema patterns | +| [error-handling.md](.claude/guidelines/error-handling.md) | Result types, error codes | +| [authentication.md](.claude/guidelines/authentication.md) | Mana Core Auth integration | +| [nestjs-backend.md](.claude/guidelines/nestjs-backend.md) | Controllers, services, DTOs | +| [sveltekit-web.md](.claude/guidelines/sveltekit-web.md) | Svelte 5 runes, stores | +| [expo-mobile.md](.claude/guidelines/expo-mobile.md) | React Native, NativeWind | +| [testing.md](.claude/guidelines/testing.md) | Jest/Vitest, mock factories | -### Hetzner Staging Server +**Always consult these guidelines before making changes.** -SSH access for deployment troubleshooting, log inspection, and service management: +## Verification -```bash -ssh -i ~/.ssh/hetzner_deploy_key deploy@46.224.108.214 -``` +When completing tasks, always end responses with the project signature to verify you've read this file. -**User:** `deploy` -**Key:** `~/.ssh/hetzner_deploy_key` - -## Adding Dependencies - -```bash -# Add to workspace root (dev tools only) -pnpm add -D -w - -# Add to specific project -pnpm add --filter memoro - -# Add to specific app within project -pnpm add --filter @memoro/mobile - -# Add to shared package -pnpm add --filter @manacore/shared-utils -``` - -## Environment Variables - -### Centralized Development Environment - -All development environment variables are managed from a single file: `.env.development` - -```bash -# First-time setup: generates all app-specific .env files -pnpm setup:env - -# This also runs automatically after `pnpm install` -``` - -The script reads `.env.development` and generates platform-specific `.env` files for each app with the correct prefixes: - -- **Expo mobile**: `EXPO_PUBLIC_*` prefix -- **SvelteKit web**: `PUBLIC_*` prefix -- **NestJS backend**: No prefix - -### Key Files - -- `.env.development` - Central source of truth (committed to git) -- `scripts/generate-env.mjs` - Generation script -- `apps/**/apps/**/.env` - Generated files (gitignored) - -### Adding New Variables - -1. Add the variable to `.env.development` -2. Update `scripts/generate-env.mjs` to map it to the appropriate apps -3. Run `pnpm setup:env` to regenerate - -### Platform Prefix Patterns - -**Mobile (Expo):** - -``` -EXPO_PUBLIC_SUPABASE_URL=... -EXPO_PUBLIC_SUPABASE_ANON_KEY=... -EXPO_PUBLIC_MIDDLEWARE_API_URL=... -``` - -**Web (SvelteKit):** - -``` -PUBLIC_SUPABASE_URL=... -PUBLIC_SUPABASE_ANON_KEY=... -``` - -**Backend (NestJS):** - -``` -SUPABASE_URL=... -SUPABASE_SERVICE_ROLE_KEY=... -PORT=... -``` - -## Project-Specific Documentation - -- **[docs/LOCAL_DEVELOPMENT.md](docs/LOCAL_DEVELOPMENT.md)** - Database setup and `dev:*:full` commands -- **[docs/ENVIRONMENT_VARIABLES.md](docs/ENVIRONMENT_VARIABLES.md)** - Complete environment setup guide -- **[docs/DATABASE_MIGRATIONS.md](docs/DATABASE_MIGRATIONS.md)** - Migration best practices, CI/CD, rollback procedures - -Each project has its own `CLAUDE.md` with detailed information: - -- `apps/manacore/CLAUDE.md` - Multi-app ecosystem, auth details -- `apps/manadeck/CLAUDE.md` - Card/deck management -- `apps/chat/CLAUDE.md` - Chat API endpoints, AI models -- `apps/picture/CLAUDE.md` - AI image generation -- `services/mana-core-auth/` - Central authentication service - -Navigate to the specific project directory to work on it. - -## Code Quality Infrastructure (TODO) - -A detailed plan for code quality tooling is available at `.claude/plans/proud-dancing-moon.md`. When ready to implement: - -### Planned Setup - -- **Pre-commit hooks**: Husky + lint-staged (format + lint on commit) -- **Commit messages**: Commitlint with Conventional Commits (`feat:`, `fix:`, `docs:`, etc.) -- **CI Pipeline**: GitHub Actions PR checks (lint, format, type-check, tests) -- **Formatting**: Tabs, single quotes, 100 char width (unified across all projects) -- **Test coverage**: 80% minimum for new code (once testing infrastructure is in place) - -### Key Files to Create - -``` -.husky/pre-commit # Run lint-staged -.husky/commit-msg # Run commitlint -commitlint.config.js # Conventional commit rules -.github/workflows/pr-check.yml # CI pipeline -packages/eslint-config/ # Shared ESLint configuration -``` - -### Current State - -- Testing: ~25 test files total (sparse coverage) -- Linting: Fragmented configs across projects -- CI: Only 2 backend deployment workflows exist -- Pre-commit: Only maerchenzauber has Husky (SSH URL fixer only) +**Project Signature:** 🏗️ ManaCore Monorepo diff --git a/CLAUDE.md.backup b/CLAUDE.md.backup new file mode 100644 index 000000000..f925c51e2 --- /dev/null +++ b/CLAUDE.md.backup @@ -0,0 +1,678 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Monorepo Overview + +This is a pnpm workspace monorepo containing multiple product applications with shared packages. All projects use Supabase for database/auth and follow similar architectural patterns. + +**Package Manager:** pnpm 9.15.0 (use `pnpm` for all commands) +**Build System:** Turborepo +**Node Version:** 20+ + +## Detailed Guidelines + +For comprehensive guidelines on code patterns and conventions, see the `.claude/` directory: + +| Document | Purpose | +|----------|---------| +| [`.claude/GUIDELINES.md`](.claude/GUIDELINES.md) | Main reference overview | +| [`.claude/guidelines/code-style.md`](.claude/guidelines/code-style.md) | Formatting, naming, linting | +| [`.claude/guidelines/database.md`](.claude/guidelines/database.md) | Drizzle ORM, schema patterns | +| [`.claude/guidelines/testing.md`](.claude/guidelines/testing.md) | Jest/Vitest, mock factories | +| [`.claude/guidelines/nestjs-backend.md`](.claude/guidelines/nestjs-backend.md) | Controllers, services, DTOs | +| [`.claude/guidelines/error-handling.md`](.claude/guidelines/error-handling.md) | Go-style Result types, error codes | +| [`.claude/guidelines/sveltekit-web.md`](.claude/guidelines/sveltekit-web.md) | Svelte 5 runes, stores | +| [`.claude/guidelines/expo-mobile.md`](.claude/guidelines/expo-mobile.md) | React Native, NativeWind | +| [`.claude/guidelines/authentication.md`](.claude/guidelines/authentication.md) | Mana Core Auth integration | + +**Always consult these guidelines before making changes.** + +## Projects + +| Project | Description | Apps | +| ------------ | ---------------------------- | --------------------------------------------------------- | +| **manacore** | Multi-app ecosystem platform | Expo mobile, SvelteKit web | +| **manadeck** | Card/deck management | NestJS backend, Expo mobile, SvelteKit web | +| **picture** | AI image generation | Expo mobile, SvelteKit web, Astro landing | +| **chat** | AI chat application | NestJS backend, Expo mobile, SvelteKit web, Astro landing | +| **zitare** | Daily inspiration quotes | NestJS backend, Expo mobile, SvelteKit web, Astro landing | +| **contacts** | Contact management | NestJS backend, SvelteKit web | + +### Archived Projects (`apps-archived/`) + +These projects are temporarily archived and excluded from the workspace. To re-activate, move back to `apps/`. + +| Project | Description | +| ------------------ | -------------------------------- | +| **bauntown** | Community website for developers | +| **maerchenzauber** | AI story generation | +| **memoro** | Voice memo & AI analysis | +| **news** | News aggregation | +| **nutriphi** | Nutrition tracking | +| **reader** | Reading app | +| **uload** | URL shortener | +| **wisekeep** | AI wisdom extraction from video | +| **techbase** | Software comparison platform | +| **inventory** | Inventory management | +| **presi** | Presentation tool | +| **storage** | Cloud storage | + +## Development Commands + +For detailed local development setup, see **[docs/LOCAL_DEVELOPMENT.md](docs/LOCAL_DEVELOPMENT.md)**. + +### Quick Start (Recommended) + +Use `dev:*:full` commands to start any app with automatic database setup: + +```bash +pnpm docker:up # Start PostgreSQL, Redis, MinIO +pnpm dev:chat:full # Start chat with auth + auto DB setup +pnpm dev:zitare:full # Start zitare with auth + auto DB setup +pnpm dev:contacts:full # Start contacts with auth + auto DB setup +pnpm dev:calendar:full # Start calendar with auth + auto DB setup +pnpm dev:clock:full # Start clock with auth + auto DB setup +pnpm dev:todo:full # Start todo with auth + auto DB setup +pnpm dev:picture:full # Start picture with auth + auto DB setup +``` + +These commands automatically: +1. Create the database if missing +2. Push the latest schema +3. Start auth, backend, and web with colored output + +### Database Setup + +```bash +pnpm setup:db # Setup ALL databases and schemas +pnpm setup:db:chat # Setup just chat +pnpm setup:db:auth # Setup just auth +``` + +### Individual App Commands + +```bash +# Start specific project (runs all apps in project) +pnpm run manacore:dev +pnpm run manadeck:dev +pnpm run picture:dev +pnpm run chat:dev +pnpm run zitare:dev +pnpm run contacts:dev + +# Start specific app within project +pnpm run dev:chat:mobile # Just mobile app +pnpm run dev:chat:backend # Just NestJS backend +pnpm run dev:chat:app # Web + backend together + +# Build & quality +pnpm run build +pnpm run type-check +pnpm run format +``` + +Each project has its own `CLAUDE.md` with detailed project-specific commands. + +## Architecture Patterns + +### Monorepo Structure + +``` +manacore-monorepo/ +├── apps/ # Active SaaS product applications +│ ├── chat/ +│ │ ├── apps/ +│ │ │ ├── backend/ # NestJS API +│ │ │ ├── mobile/ # Expo React Native app +│ │ │ ├── web/ # SvelteKit web app +│ │ │ └── landing/ # Astro marketing page +│ │ └── packages/ # Project-specific shared code +│ ├── manadeck/ +│ ├── picture/ +│ └── ... +├── apps-archived/ # Archived apps (excluded from workspace) +│ ├── bauntown/ +│ ├── maerchenzauber/ +│ ├── memoro/ +│ ├── news/ +│ ├── nutriphi/ +│ ├── reader/ +│ ├── uload/ +│ └── wisekeep/ +├── games/ # Game projects +│ └── {game-name}/ # Individual games +├── services/ # Standalone microservices +│ └── mana-core-auth/ # Central authentication service +├── packages/ # Monorepo-wide shared packages +└── docker/ # Docker configuration files +``` + +### Standard Project Structure (inside apps/) + +``` +apps/{project}/ +├── apps/ +│ ├── backend/ # NestJS API (when present) +│ ├── mobile/ # Expo React Native app +│ ├── web/ # SvelteKit web app +│ └── landing/ # Astro marketing page +├── packages/ # Project-specific shared code +└── package.json +``` + +### Turborepo Configuration + +**CRITICAL: Avoid Recursive Turbo Calls** + +Parent workspace packages (e.g., `apps/chat/package.json`, `apps/zitare/package.json`) must **NEVER** have scripts that call `turbo run ` for tasks that turbo orchestrates from the root. + +```jsonc +// WRONG - Creates infinite recursion! +// apps/chat/package.json +{ + "scripts": { + "type-check": "turbo run type-check", // DON'T DO THIS + "build": "turbo run build", // DON'T DO THIS + "lint": "turbo run lint" // DON'T DO THIS + } +} + +// CORRECT - Let root turbo handle orchestration +// apps/chat/package.json +{ + "scripts": { + "dev": "turbo run dev" // OK for dev (persistent task, scoped) + // No type-check, build, lint scripts - handled by root turbo + } +} +``` + +**Why this matters:** When root turbo runs `type-check`, it finds packages with `type-check` scripts and runs them. If that script is `turbo run type-check`, it spawns another turbo process that does the same thing → infinite loop. This causes tasks to run for 10+ minutes with thousands of duplicate task entries. + +**The `dev` script exception:** Using `turbo run dev` in parent packages is acceptable because: +1. It's typically run directly on that package (scoped) +2. Dev tasks are persistent and turbo handles them differently + +**Current turbo.json settings:** +- `concurrency: "5"` - Parallel task limit (adjust based on machine) +- `type-check` has `dependsOn: ["^type-check"]` - Dependencies are checked first + +### Technology Stack by App Type + +**Mobile Apps (Expo):** + +- React Native 0.76-0.81 + Expo SDK 52-54 +- Expo Router (file-based routing) +- NativeWind (Tailwind for React Native) +- Zustand (state management) + +**Web Apps (SvelteKit):** + +- SvelteKit 2.x + Svelte 5 +- Tailwind CSS +- Supabase SSR auth + +**Landing Pages (Astro):** + +- Astro 5.x +- Tailwind CSS +- Static site generation + +**Backends (NestJS):** + +- NestJS 10-11 +- TypeScript +- Supabase integration + +### Authentication Architecture + +All projects use **mana-core-auth** as the central authentication service: + +``` +┌─────────────┐ ┌─────────────┐ ┌────────────────┐ +│ Client │────>│ Backend │────>│ mana-core-auth │ +│ (Web/Mobile)│ │ (NestJS) │ │ (port 3001) │ +└─────────────┘ └─────────────┘ └────────────────┘ + │ │ │ + │ Bearer token │ POST /validate │ + │ │ {token} │ + │ │<────────────────────│ + │ │ {valid, payload} │ + │<──────────────────│ │ + │ Response │ │ +``` + +#### Key Components + +| Component | Purpose | +| ------------------------------- | -------------------------------------------------- | +| `services/mana-core-auth` | Central auth service (Better Auth + EdDSA JWT) | +| `@manacore/shared-nestjs-auth` | Shared NestJS guards/decorators for JWT validation | +| `@mana-core/nestjs-integration` | Extended NestJS module with auth + credits | +| `@manacore/shared-auth` | Client-side auth for web/mobile apps | + +#### NestJS Backend Integration + +**Option 1: Simple auth only** - Use `@manacore/shared-nestjs-auth`: + +```typescript +// In your controller +import { JwtAuthGuard, CurrentUser, CurrentUserData } from '@manacore/shared-nestjs-auth'; + +@Controller('api') +@UseGuards(JwtAuthGuard) +export class MyController { + @Get('profile') + getProfile(@CurrentUser() user: CurrentUserData) { + return { userId: user.userId, email: user.email }; + } +} +``` + +**Option 2: Auth + Credits** - Use `@mana-core/nestjs-integration`: + +```typescript +// app.module.ts +import { ManaCoreModule } from '@mana-core/nestjs-integration'; + +@Module({ + imports: [ + ManaCoreModule.forRootAsync({ + imports: [ConfigModule], + useFactory: (config: ConfigService) => ({ + appId: config.get('APP_ID'), + serviceKey: config.get('MANA_CORE_SERVICE_KEY'), + debug: config.get('NODE_ENV') === 'development', + }), + inject: [ConfigService], + }), + ], +}) +export class AppModule {} + +// In controller +import { AuthGuard } from '@mana-core/nestjs-integration/guards'; +import { CurrentUser } from '@mana-core/nestjs-integration/decorators'; +import { CreditClientService } from '@mana-core/nestjs-integration'; + +@Controller('api') +@UseGuards(AuthGuard) +export class ApiController { + constructor(private creditClient: CreditClientService) {} + + @Post('generate') + async generate(@CurrentUser() user: any) { + await this.creditClient.consumeCredits(user.sub, 'generation', 10, 'AI generation'); + // ... do work + } +} +``` + +#### Required Environment Variables + +```env +# All backends need this +MANA_CORE_AUTH_URL=http://localhost:3001 + +# For development bypass (optional) +NODE_ENV=development +DEV_BYPASS_AUTH=true +DEV_USER_ID=your-test-user-id + +# For credit operations (optional) +MANA_CORE_SERVICE_KEY=your-service-key +APP_ID=your-app-id +``` + +#### JWT Token Structure (EdDSA) + +```json +{ + "sub": "user-id", + "email": "user@example.com", + "role": "user", + "sid": "session-id", + "exp": 1764606251, + "iss": "manacore", + "aud": "manacore" +} +``` + +#### Testing Auth Integration + +```bash +# 1. Start mana-core-auth +pnpm dev:auth + +# 2. Start a backend (e.g., Zitare) +pnpm dev:zitare:backend + +# 3. Get a token +TOKEN=$(curl -s -X POST http://localhost:3001/api/v1/auth/login \ + -H "Content-Type: application/json" \ + -d '{"email": "test@example.com", "password": "password"}' | jq -r '.accessToken') + +# 4. Call protected endpoint +curl http://localhost:3007/api/favorites \ + -H "Authorization: Bearer $TOKEN" +``` + +#### Integrated Backends + +| Backend | Package | Port | +| -------- | ------------------------------- | ---- | +| Chat | `@mana-core/nestjs-integration` | 3002 | +| Picture | `@manacore/shared-nestjs-auth` | 3006 | +| Zitare | `@manacore/shared-nestjs-auth` | 3007 | +| Presi | Custom (same pattern) | 3008 | +| ManaDeck | `@mana-core/nestjs-integration` | 3009 | + +### Svelte 5 Runes Mode (Web Apps) + +All SvelteKit apps use Svelte 5 runes: + +```typescript +// CORRECT - Svelte 5 +let count = $state(0); +let doubled = $derived(count * 2); +$effect(() => { + console.log(count); +}); + +// WRONG - Old Svelte syntax +let count = 0; +$: doubled = count * 2; +``` + +## Shared Packages (`packages/`) + +| Package | Purpose | +| ------------------------------- | ----------------------------------------------- | +| `@manacore/shared-nestjs-auth` | NestJS JWT validation guards via mana-core-auth | +| `@mana-core/nestjs-integration` | NestJS module with auth guards + credit client | +| `@manacore/shared-auth` | Client-side auth service for web/mobile apps | +| `@manacore/shared-storage` | S3-compatible storage (MinIO local, Hetzner prod) | +| `@manacore/shared-supabase` | Unified Supabase client | +| `@manacore/shared-types` | Common TypeScript types | +| `@manacore/shared-utils` | Utility functions | +| `@manacore/shared-ui` | React Native UI components | +| `@manacore/shared-theme` | Theme configuration | +| `@manacore/shared-i18n` | Internationalization | + +Import shared packages: + +```typescript +import { createAuthService } from '@manacore/shared-auth'; +import { formatDate, truncate } from '@manacore/shared-utils'; +``` + +## Database (Supabase) + +- All projects use Supabase for PostgreSQL database, auth, and storage +- Row Level Security (RLS) policies enforce access control via JWT claims +- Each project has its own Supabase project/schema +- Types typically generated via `supabase gen types` + +## Object Storage (MinIO / Hetzner) + +S3-compatible object storage for file uploads, generated images, etc. + +### Architecture + +| Environment | Service | Purpose | +|-------------|---------|---------| +| **Local** | MinIO (Docker) | S3-compatible local storage | +| **Production** | Hetzner Object Storage | Cost-effective S3-compatible cloud storage | + +### Local Development + +```bash +# Start infrastructure (includes MinIO) +pnpm docker:up + +# MinIO Web Console: http://localhost:9001 +# Username: minioadmin +# Password: minioadmin + +# S3 API endpoint: http://localhost:9000 +``` + +### Pre-configured Buckets + +| Bucket | Project | Purpose | +|--------|---------|---------| +| `picture-storage` | Picture | AI-generated images | +| `chat-storage` | Chat | User file uploads | +| `manadeck-storage` | ManaDeck | Card/deck assets | +| `nutriphi-storage` | NutriPhi | Meal photos | +| `presi-storage` | Presi | Presentation slides | +| `calendar-storage` | Calendar | Calendar attachments | +| `contacts-storage` | Contacts | Contact avatars/files | +| `storage-storage` | Storage | Cloud drive files | + +### Usage in Backend + +```typescript +import { createPictureStorage, generateUserFileKey, getContentType } from '@manacore/shared-storage'; + +const storage = createPictureStorage(); + +// Upload +const key = generateUserFileKey(userId, 'image.png'); +const result = await storage.upload(key, buffer, { + contentType: getContentType('image.png'), + public: true, +}); + +// Download +const data = await storage.download(key); + +// Presigned URLs +const uploadUrl = await storage.getUploadUrl(key, { expiresIn: 3600 }); +``` + +### Environment Variables + +```env +# Local (in .env.development) +S3_ENDPOINT=http://localhost:9000 +S3_REGION=us-east-1 +S3_ACCESS_KEY=minioadmin +S3_SECRET_KEY=minioadmin + +# Production (Hetzner) +S3_ENDPOINT=https://fsn1.your-objectstorage.com +S3_REGION=fsn1 +S3_ACCESS_KEY=your-access-key +S3_SECRET_KEY=your-secret-key +``` + +## Landing Pages (Cloudflare Pages) + +All landing pages are deployed to Cloudflare Pages using Direct Upload via Wrangler CLI. + +### Landing Pages + +| Project | Package | Cloudflare Project | URL | +|---------|---------|-------------------|-----| +| Chat | `@chat/landing` | `chat-landing` | https://chat-landing.pages.dev | +| Picture | `@picture/landing` | `picture-landing` | https://picture-landing.pages.dev | +| ManaCore | `@manacore/landing` | `manacore-landing` | https://manacore-landing.pages.dev | +| ManaDeck | `@manadeck/landing` | `manadeck-landing` | https://manadeck-landing.pages.dev | +| Zitare | `@zitare/landing` | `zitare-landing` | https://zitare-landing.pages.dev | + +### Local Deployment + +```bash +# First time: Login to Cloudflare +pnpm cf:login + +# Create projects (one-time setup) +pnpm cf:projects:create + +# Deploy individual landing page +pnpm deploy:landing:chat +pnpm deploy:landing:picture +pnpm deploy:landing:manacore +pnpm deploy:landing:manadeck +pnpm deploy:landing:zitare + +# Deploy all landing pages +pnpm deploy:landing:all + +# List all projects +pnpm cf:projects:list +``` + +### Adding New Landing Pages + +1. Create the landing page in `apps/{project}/apps/landing/` +2. Add `wrangler.toml`: + ```toml + name = "{project}-landing" + compatibility_date = "2024-12-01" + pages_build_output_dir = "dist" + ``` +3. Add deploy script to root `package.json`: + ```json + "deploy:landing:{project}": "pnpm --filter @{project}/landing build && npx wrangler pages deploy apps/{project}/apps/landing/dist --project-name={project}-landing" + ``` +4. Create Cloudflare project: `npx wrangler pages project create {project}-landing --production-branch=main` + +### Custom Domains + +```bash +# Add custom domain to a project +npx wrangler pages project add-domain chat-landing chat.manacore.app +``` + +## Server Access + +### Hetzner Staging Server + +SSH access for deployment troubleshooting, log inspection, and service management: + +```bash +ssh -i ~/.ssh/hetzner_deploy_key deploy@46.224.108.214 +``` + +**User:** `deploy` +**Key:** `~/.ssh/hetzner_deploy_key` + +## Adding Dependencies + +```bash +# Add to workspace root (dev tools only) +pnpm add -D -w + +# Add to specific project +pnpm add --filter memoro + +# Add to specific app within project +pnpm add --filter @memoro/mobile + +# Add to shared package +pnpm add --filter @manacore/shared-utils +``` + +## Environment Variables + +### Centralized Development Environment + +All development environment variables are managed from a single file: `.env.development` + +```bash +# First-time setup: generates all app-specific .env files +pnpm setup:env + +# This also runs automatically after `pnpm install` +``` + +The script reads `.env.development` and generates platform-specific `.env` files for each app with the correct prefixes: + +- **Expo mobile**: `EXPO_PUBLIC_*` prefix +- **SvelteKit web**: `PUBLIC_*` prefix +- **NestJS backend**: No prefix + +### Key Files + +- `.env.development` - Central source of truth (committed to git) +- `scripts/generate-env.mjs` - Generation script +- `apps/**/apps/**/.env` - Generated files (gitignored) + +### Adding New Variables + +1. Add the variable to `.env.development` +2. Update `scripts/generate-env.mjs` to map it to the appropriate apps +3. Run `pnpm setup:env` to regenerate + +### Platform Prefix Patterns + +**Mobile (Expo):** + +``` +EXPO_PUBLIC_SUPABASE_URL=... +EXPO_PUBLIC_SUPABASE_ANON_KEY=... +EXPO_PUBLIC_MIDDLEWARE_API_URL=... +``` + +**Web (SvelteKit):** + +``` +PUBLIC_SUPABASE_URL=... +PUBLIC_SUPABASE_ANON_KEY=... +``` + +**Backend (NestJS):** + +``` +SUPABASE_URL=... +SUPABASE_SERVICE_ROLE_KEY=... +PORT=... +``` + +## Project-Specific Documentation + +- **[docs/LOCAL_DEVELOPMENT.md](docs/LOCAL_DEVELOPMENT.md)** - Database setup and `dev:*:full` commands +- **[docs/ENVIRONMENT_VARIABLES.md](docs/ENVIRONMENT_VARIABLES.md)** - Complete environment setup guide +- **[docs/DATABASE_MIGRATIONS.md](docs/DATABASE_MIGRATIONS.md)** - Migration best practices, CI/CD, rollback procedures + +Each project has its own `CLAUDE.md` with detailed information: + +- `apps/manacore/CLAUDE.md` - Multi-app ecosystem, auth details +- `apps/manadeck/CLAUDE.md` - Card/deck management +- `apps/chat/CLAUDE.md` - Chat API endpoints, AI models +- `apps/picture/CLAUDE.md` - AI image generation +- `services/mana-core-auth/` - Central authentication service + +Navigate to the specific project directory to work on it. + +## Code Quality Infrastructure (TODO) + +A detailed plan for code quality tooling is available at `.claude/plans/proud-dancing-moon.md`. When ready to implement: + +### Planned Setup + +- **Pre-commit hooks**: Husky + lint-staged (format + lint on commit) +- **Commit messages**: Commitlint with Conventional Commits (`feat:`, `fix:`, `docs:`, etc.) +- **CI Pipeline**: GitHub Actions PR checks (lint, format, type-check, tests) +- **Formatting**: Tabs, single quotes, 100 char width (unified across all projects) +- **Test coverage**: 80% minimum for new code (once testing infrastructure is in place) + +### Key Files to Create + +``` +.husky/pre-commit # Run lint-staged +.husky/commit-msg # Run commitlint +commitlint.config.js # Conventional commit rules +.github/workflows/pr-check.yml # CI pipeline +packages/eslint-config/ # Shared ESLint configuration +``` + +### Current State + +- Testing: ~25 test files total (sparse coverage) +- Linting: Fragmented configs across projects +- CI: Only 2 backend deployment workflows exist +- Pre-commit: Only maerchenzauber has Husky (SSH URL fixer only) diff --git a/docs/DEPENDENCY_ALIGNMENT.md b/docs/DEPENDENCY_ALIGNMENT.md deleted file mode 100644 index 2a9929469..000000000 --- a/docs/DEPENDENCY_ALIGNMENT.md +++ /dev/null @@ -1,180 +0,0 @@ -# Dependency Alignment Guide - -This document tracks critical dependencies across all projects and their target versions for alignment. - -## Critical Dependencies - -### High Priority - Version Mismatches - -| Package | Target Version | Current Versions | Notes | -| ----------------------- | -------------- | ----------------- | -------------------------------------- | -| `@supabase/supabase-js` | **2.81.1** | 2.38.4 - 2.81.1 | Significant spread, alignment critical | -| `typescript` | **5.9.2** | 5.3.3 - 5.9.2 | Update all to latest | -| `react` | **19.1.0** | 18.3.1 - 19.1.0 | Mixed versions | -| `expo` | **54.x** | 52.0.39 - 54.0.21 | Manacore needs update | -| `expo-router` | **6.x** | 4.0.19 - 6.0.14 | Manacore needs update | -| `astro` | **5.16.0** | 5.3.0 - 5.16.0 | Memoro landing needs update | - -### Current Status by Project - -#### Supabase Versions - -``` -maerchenzauber: - - backend: 2.50.3 - - mobile: 2.50.3 - -manacore: - - mobile: 2.38.4 ❌ (very outdated) - - web: 2.49.2 - -manadeck: - - backend: 2.58.0 - - mobile: 2.38.4 ❌ (very outdated) - - web: 2.81.1 ✅ - -memoro: - - mobile: 2.49.4 - - web: 2.76.1 -``` - -#### Expo/React Native Versions - -``` -maerchenzauber: - - expo: 54.0.21 ✅ - - react-native: 0.81.5 ✅ - - expo-router: 6.0.14 ✅ - -manacore: - - expo: 52.0.39 ❌ (SDK 52, needs update to 54) - - react-native: 0.76.7 ❌ - - expo-router: 4.0.19 ❌ - -manadeck: - - expo: 54.0.13 ✅ - - react-native: 0.81.4 ✅ - - expo-router: 6.0.10 ✅ - -memoro: - - expo: 54.0.0 ✅ - - react-native: 0.81.4 ✅ - - expo-router: 6.0.8 ✅ -``` - -#### NestJS Versions (Backends) - -``` -maerchenzauber: NestJS 10.0.0 -manadeck: NestJS 11.0.1 - -Target: Align to NestJS 11.x -``` - -## Migration Priority - -### Phase 1: Critical Alignments (Week 1) - -1. **Manacore Expo Update** (High Risk) - - Upgrade from Expo SDK 52 → 54 - - Update expo-router 4.x → 6.x - - Update react-native 0.76.7 → 0.81.x - - This is the most significant update needed - -2. **Supabase Alignment** - - Update all projects to 2.81.1 - - Test auth flows after update - - Check for breaking changes in RLS - -3. **TypeScript Alignment** - - Update all to 5.9.2 - - Run type-check across all projects - -### Phase 2: Secondary Alignments (Week 2) - -1. **Astro Updates** - - Update Memoro landing from 5.3.0 → 5.16.0 - -2. **SvelteKit/Vite Updates** - - Align Vite versions (6.0.7 → 7.1.10) - - Align SvelteKit versions - -3. **NestJS Alignment** - - Update Maerchenzauber backend 10.x → 11.x - - Test all API endpoints - -## Alignment Commands - -### Update Supabase across all projects: - -```bash -# Maerchenzauber -cd maerchenzauber/apps/backend && pnpm update @supabase/supabase-js@2.81.1 -cd maerchenzauber/apps/mobile && pnpm update @supabase/supabase-js@2.81.1 - -# Manacore -cd manacore/apps/mobile && pnpm update @supabase/supabase-js@2.81.1 -cd manacore/apps/web && pnpm update @supabase/supabase-js@2.81.1 - -# Manadeck -cd manadeck/backend && pnpm update @supabase/supabase-js@2.81.1 -cd manadeck/apps/mobile && pnpm update @supabase/supabase-js@2.81.1 - -# Memoro -cd memoro/apps/mobile && pnpm update @supabase/supabase-js@2.81.1 -cd memoro/apps/web && pnpm update @supabase/supabase-js@2.81.1 -``` - -### Update TypeScript across all projects: - -```bash -pnpm update typescript@5.9.2 --recursive -``` - -## Testing After Alignment - -After updating dependencies, verify: - -1. **Build succeeds**: `pnpm run build` -2. **Type checks pass**: `pnpm run type-check` -3. **Tests pass**: `pnpm run test` -4. **Auth flows work** (especially after Supabase updates) -5. **Mobile apps launch** (especially after Expo updates) - -## Breaking Changes to Watch - -### Supabase 2.38 → 2.81 - -- Auth session handling may have changed -- Check `onAuthStateChange` listeners -- Verify RLS policies still work - -### Expo SDK 52 → 54 - -- Check expo-router migration guide -- New navigation patterns in 6.x -- Screen options changes -- Layout changes - -### NestJS 10 → 11 - -- Decorator changes -- Module resolution changes -- Check middleware compatibility - -## Recommended Tools - -- **Renovate/Dependabot**: Auto-update dependencies -- **pnpm outdated**: Check for outdated packages -- **turbo prune**: Create minimal installs for specific projects - -## Tracking Updates - -Mark completed updates: - -- [ ] Supabase alignment (all projects) -- [ ] TypeScript alignment (all projects) -- [ ] Manacore Expo SDK update -- [ ] Astro alignment -- [ ] NestJS alignment -- [ ] SvelteKit/Vite alignment diff --git a/docs/ENV_AUDIT_SUMMARY.md b/docs/ENV_AUDIT_SUMMARY.md deleted file mode 100644 index 69c143cf2..000000000 --- a/docs/ENV_AUDIT_SUMMARY.md +++ /dev/null @@ -1,184 +0,0 @@ -# Environment Audit - Quick Summary - -## Issues Found: 8 Critical/Major Items - -### BLOCKING (Fix immediately - prevent simultaneous backend execution) - -**Port Conflicts:** - -``` -Port 3002: Chat (3002) ← → Nutriphi (3002) [CONFLICT] -Port 3003: Picture (3003) ← → Maerchenzauber (3003) [CONFLICT] -``` - -**Hardcoded Values:** - -- Chat backend hardcodes DEV_USER_ID instead of reading from env - -### MAJOR (Inconsistencies across codebase) - -**Auth URL Variable Names (Choose One):** - -- Chat: MANA_CORE_AUTH_URL ✓ -- Picture: MANA_CORE_AUTH_URL ✓ -- Zitare: MANA_CORE_AUTH_URL ✓ -- Presi: MANA_CORE_AUTH_URL ✓ -- **Manadeck: MANA_SERVICE_URL** ← Should standardize -- **Nutriphi: MANACORE_AUTH_URL** ← Should standardize - -**CORS Origins:** - -- Hardcoded in 4 backends (Chat, Picture, Zitare, Presi) -- Should use CORS_ORIGINS from environment - -**Missing Documentation:** - -- No .env.example for Zitare backend -- No .env.example for Presi backend - -### MEDIUM (Code quality) - -**Validation Schemas:** - -- Chat: Missing -- Picture: Missing -- Zitare: Missing -- Presi: Missing -- Manadeck: ✓ Has validation schema -- Mana-Core-Auth: ✓ Has validation config - ---- - -## Quick Fix Checklist - -### Phase 1: Critical (1-2 hours) - -- [ ] Reassign Picture from port 3003 → 3005 -- [ ] Reassign Nutriphi from port 3002 → 3006 -- [ ] Add DEV_USER_ID to .env.development -- [ ] Update Chat to load DEV_USER_ID from ConfigService - -### Phase 2: Major (2-3 hours) - -- [ ] Rename MANA_SERVICE_URL to MANA_CORE_AUTH_URL in Manadeck -- [ ] Rename MANACORE_AUTH_URL to MANA_CORE_AUTH_URL in Nutriphi -- [ ] Create .env.example for Zitare -- [ ] Create .env.example for Presi - -### Phase 3: Quality (3-4 hours) - -- [ ] Add validation schemas to Chat, Picture, Zitare, Presi -- [ ] Extract CORS origins to environment variables -- [ ] Update all backends to read CORS_ORIGINS from env - ---- - -## Port Mapping (Current vs Recommended) - -``` -Current: Recommended: -3001 ← Mana Core Auth → 3001 ← Mana Core Auth -3002 ← Chat → 3002 ← Chat -3002 ← Nutriphi [X] → 3006 ← Nutriphi [FIXED] -3003 ← Maerchenzauber → 3003 ← Maerchenzauber -3003 ← Picture [X] → 3005 ← Picture [FIXED] -3004 ← Manadeck → 3004 ← Manadeck -3007 ← Zitare → 3007 ← Zitare -3008 ← Presi → 3008 ← Presi -3010 ← Voxel Lava → 3010 ← Voxel Lava -3011 ← Mana Games → 3011 ← Mana Games -``` - ---- - -## Environment Variables Status - -### Well-Configured - -- MANA_CORE_AUTH_URL (central + mapped) -- JWT keys (central) -- API keys (central) -- Database URLs (individual + mapped) - -### Needs Work - -- DEV_USER_ID (hardcoded, not in env) -- DEV_BYPASS_AUTH (partial, only Chat) -- CORS_ORIGINS (hardcoded, not used by all) -- Auth URL naming (3 different conventions) - ---- - -## Files to Modify - -### .env.development - -- [ ] Add DEV_USER_ID line -- [ ] Fix PICTURE_BACKEND_PORT (3003 → 3005) -- [ ] Fix NUTRIPHI_BACKEND_PORT (3002 → 3006) - -### scripts/generate-env.mjs - -- [ ] Line 205: MANA_SERVICE_URL → MANA_CORE_AUTH_URL (Manadeck) -- [ ] Line 272: MANACORE_AUTH_URL → MANA_CORE_AUTH_URL (Nutriphi) - -### Backend Apps (4 files each) - -- [ ] apps/chat/apps/backend/src/config/validation.schema.ts (create) -- [ ] apps/picture/apps/backend/src/config/validation.schema.ts (create) -- [ ] apps/zitare/apps/backend/src/config/validation.schema.ts (create) -- [ ] apps/presi/apps/backend/src/config/validation.schema.ts (create) - -### Backend Main Files (4 files) - -- [ ] apps/chat/apps/backend/src/main.ts (extract CORS) -- [ ] apps/picture/apps/backend/src/main.ts (extract CORS) -- [ ] apps/zitare/apps/backend/src/main.ts (extract CORS) -- [ ] apps/presi/apps/backend/src/main.ts (extract CORS) - -### Backend Examples (2 files) - -- [ ] apps/zitare/apps/backend/.env.example (create) -- [ ] apps/presi/apps/backend/.env.example (create) - -### Chat Guard - -- [ ] apps/chat/apps/backend/src/common/guards/jwt-auth.guard.ts - - Remove hardcoded DEV_USER_ID - - Read from configService instead - ---- - -## Testing After Fixes - -```bash -# Test all 10 backends can start simultaneously -pnpm dev:auth & -pnpm dev:chat:backend & -pnpm dev:manadeck:backend & -pnpm dev:picture:backend & -pnpm dev:zitare:backend & -pnpm dev:presi:backend & - -# Verify each responds -curl http://localhost:3001/health -curl http://localhost:3002/api/health -curl http://localhost:3003/api/health # Maerchenzauber -curl http://localhost:3004/v1/health # Manadeck -curl http://localhost:3005/api/health # Picture (new port) -curl http://localhost:3007/api/health # Zitare -curl http://localhost:3008/api/health # Presi -``` - ---- - -## Additional Docs - -See full audit report: `/docs/ENV_CONFIGURATION_AUDIT.md` - -Key sections: - -- Environment Variable Mapping (section 3) -- Hardcoded Values & Security (section 4) -- Configuration Best Practices (section 5) -- Implementation Checklist (section 10) diff --git a/docs/ENV_BACKEND_MATRIX.md b/docs/ENV_BACKEND_MATRIX.md deleted file mode 100644 index 31263f6f8..000000000 --- a/docs/ENV_BACKEND_MATRIX.md +++ /dev/null @@ -1,236 +0,0 @@ -# Environment Variable Configuration Matrix - -## Backend Authentication & Port Status - -``` -╔══════════════════╦════════╦═══════════════════════╦═════════════════════╦═══════════════╗ -║ Backend ║ Port ║ Auth URL Variable ║ Dev Bypass ║ Validation ║ -╠══════════════════╬════════╬═══════════════════════╬═════════════════════╬═══════════════╣ -║ Mana Core Auth ║ 3001 ║ N/A (Auth service) ║ N/A ║ ✓ Config svc ║ -║ Chat ║ 3002 ║ MANA_CORE_AUTH_URL ║ ✓ Implemented ║ ✗ Missing ║ -║ Maerchenzauber ║ 3003 ║ MANA_SERVICE_URL ║ ? Unknown ║ ? Unknown ║ -║ Manadeck ║ 3004 ║ MANA_SERVICE_URL ║ ? Unknown ║ ✓ Joi schema ║ -║ Picture ║ 3003 ║ MANA_CORE_AUTH_URL ║ ✗ Missing ║ ✗ Missing ║ -║ Nutriphi ║ 3002 ║ MANACORE_AUTH_URL ║ ? Unknown ║ ? Unknown ║ -║ Zitare ║ 3007 ║ MANA_CORE_AUTH_URL ║ ✗ Missing ║ ✗ Missing ║ -║ Presi ║ 3008 ║ MANA_CORE_AUTH_URL ║ ✗ Missing ║ ✗ Missing ║ -║ Voxel Lava ║ 3010 ║ ? Not checked ║ ? Unknown ║ ? Unknown ║ -║ Mana Games ║ 3011 ║ ? Not checked ║ ? Unknown ║ ? Unknown ║ -╚══════════════════╩════════╩═══════════════════════╩═════════════════════╩═══════════════╝ -``` - -Legend: - -- ✓ = Implemented/Present -- ✗ = Missing/Not implemented -- ? = Not analyzed in this audit -- Port conflicts highlighted in red - ---- - -## Database URL Configuration - -``` -╔══════════════════╦════════════════════════════════════════════════╦════════════════╗ -║ Backend ║ Database URL Variable ║ Generated ║ -╠══════════════════╬════════════════════════════════════════════════╬════════════════╣ -║ Mana Core Auth ║ MANA_CORE_AUTH_DATABASE_URL ║ ✓ via gen-env ║ -║ Chat ║ CHAT_DATABASE_URL ║ ✓ via gen-env ║ -║ Manadeck ║ MANADECK_DATABASE_URL ║ ✓ via gen-env ║ -║ Picture ║ PICTURE_DATABASE_URL ║ ✓ via gen-env ║ -║ Nutriphi ║ NUTRIPHI_DATABASE_URL ║ ✓ via gen-env ║ -║ Zitare ║ ZITARE_DATABASE_URL ║ ✓ via gen-env ║ -║ Presi ║ PRESI_DATABASE_URL ║ ✓ via gen-env ║ -║ Voxel Lava ║ VOXEL_LAVA_DATABASE_URL ║ ✓ via gen-env ║ -║ Mana Games ║ None specified ║ N/A ║ -╚══════════════════╩════════════════════════════════════════════════╩════════════════╝ -``` - ---- - -## CORS Configuration Status - -``` -╔══════════════════╦═══════════════════════════════════╦═════════════════════════════════╗ -║ Backend ║ CORS Implementation ║ Recommendation ║ -╠══════════════════╬═══════════════════════════════════╬═════════════════════════════════╣ -║ Chat ║ Hardcoded array in main.ts ║ Move to CORS_ORIGINS env var ║ -║ Picture ║ Hardcoded array in main.ts ║ Move to CORS_ORIGINS env var ║ -║ Zitare ║ Hardcoded array in main.ts ║ Move to CORS_ORIGINS env var ║ -║ Presi ║ Hardcoded array in main.ts ║ Move to CORS_ORIGINS env var ║ -║ Manadeck ║ configService.get('FRONTEND_URL') ║ Already using env var (better) ║ -║ Mana Core Auth ║ configService array ║ Already using env var (good) ║ -╚══════════════════╩═══════════════════════════════════╩═════════════════════════════════╝ -``` - -Current hardcoded CORS allowed origins (should be environment variable): - -```javascript -// In 4 backends -const allowedOrigins = [ - 'http://localhost:3000', - 'http://localhost:5173', // Primary web dev port - 'http://localhost:5174', // Secondary web port - 'http://localhost:5175', // Tertiary web port - 'http://localhost:5177', // Zitare web - 'http://localhost:5178', // Chat web / Presi web - 'http://localhost:8081', // Expo dev server - 'exp://localhost:8081', // Expo protocol - 'http://localhost:3001', // Mana Core Auth -]; -``` - ---- - -## Port Availability & Conflicts - -``` -Port 3000 ━━━━━━━━ [FREE] -Port 3001 ━━━━━━━━ Mana Core Auth (ACTIVE) -Port 3002 ━━━━━━━━ Chat (ACTIVE) + Nutriphi (ACTIVE) ⚠ CONFLICT! - ↓ - 3002a Chat - 3002b Nutriphi (should be 3006) -Port 3003 ━━━━━━━━ Maerchenzauber (ACTIVE) + Picture (ACTIVE) ⚠ CONFLICT! - ↓ - 3003a Maerchenzauber - 3003b Picture (should be 3005) -Port 3004 ━━━━━━━━ Manadeck (ACTIVE) -Port 3005 ━━━━━━━━ [AVAILABLE] ← Assign to Picture -Port 3006 ━━━━━━━━ [AVAILABLE] ← Assign to Nutriphi -Port 3007 ━━━━━━━━ Zitare (ACTIVE) -Port 3008 ━━━━━━━━ Presi (ACTIVE) -Port 3009 ━━━━━━━━ [RESERVED - mentioned in CLAUDE.md] -Port 3010 ━━━━━━━━ Voxel Lava (ACTIVE) -Port 3011 ━━━━━━━━ Mana Games (ACTIVE) -``` - ---- - -## Environment Variable Generation Map - -### From .env.development to Backend .env Files - -``` -MANA_CORE_AUTH_PORT (3001) - ↓ (generate-env.mjs line 61) - ├→ services/mana-core-auth/.env {PORT} - -CHAT_BACKEND_PORT (3002) - ↓ (generate-env.mjs line 89) - ├→ apps/chat/apps/backend/.env {PORT} - -MANA_CORE_AUTH_URL (http://localhost:3001) - ↓ (generate-env.mjs multiple lines) - ├→ apps/chat/apps/backend/.env {MANA_CORE_AUTH_URL} - ├→ apps/picture/apps/backend/.env {MANA_CORE_AUTH_URL} - ├→ apps/zitare/apps/backend/.env {MANA_CORE_AUTH_URL} - ├→ apps/presi/apps/backend/.env {MANA_CORE_AUTH_URL} - ├→ apps/manadeck/apps/backend/.env {MANA_SERVICE_URL} ← NAMING INCONSISTENCY - └→ apps/nutriphi/apps/backend/.env {MANACORE_AUTH_URL} ← NAMING INCONSISTENCY - -CORS_ORIGINS (http://localhost:3000,http://localhost:3002,...) - ↓ (generate-env.mjs line 75, 136, 232, 301, 332, 372) - ├→ services/mana-core-auth/.env {CORS_ORIGINS} - ├→ apps/maerchenzauber/apps/backend/.env {CORS_ORIGINS} - ├→ apps/picture/apps/backend/.env {CORS_ORIGINS} - ├→ apps/zitare/apps/backend/.env {CORS_ORIGINS} - ├→ apps/presi/apps/backend/.env {CORS_ORIGINS} - └→ games/mana-games/apps/backend/.env {CORS_ORIGINS} - [BUT NOT USED by Chat, Picture, Zitare, Presi - they hardcode instead!] -``` - ---- - -## Issues Severity Matrix - -``` -╔═══════════════╦════════════════════════════════════════════════╦══════════════════╗ -║ Severity ║ Count ║ Issue Description ║ Time to Fix ║ -╠═══════════════╬═══════╬═════════════════════════════════════════╬══════════════════╣ -║ BLOCKING ║ 2 ║ Port conflicts (3002, 3003) ║ 15 minutes ║ -║ ║ 1 ║ Hardcoded DEV_USER_ID ║ 30 minutes ║ -╠═══════════════╬═══════╬═════════════════════════════════════════╬══════════════════╣ -║ MAJOR ║ 3 ║ Auth URL naming inconsistencies ║ 30 minutes ║ -║ ║ 4 ║ Hardcoded CORS origins ║ 1-2 hours ║ -║ ║ 2 ║ Missing .env.example files ║ 15 minutes ║ -╠═══════════════╬═══════╬═════════════════════════════════════════╬══════════════════╣ -║ MEDIUM ║ 4 ║ Missing validation schemas ║ 2-3 hours ║ -║ ║ 1 ║ Dev bypass auth inconsistency ║ 1-2 hours ║ -╠═══════════════╬═══════╬═════════════════════════════════════════╬══════════════════╣ -║ TOTAL ║ 17 ║ All issues identified ║ 6-8 hours total ║ -╚═══════════════╩═══════╩═════════════════════════════════════════╩══════════════════╝ -``` - ---- - -## Configuration Best Practices Scorecard - -``` -╔════════════════════════════════════╦═════════════════════════════════════════╗ -║ Criteria ║ Score (0-10) ║ -╠════════════════════════════════════╬═════════════════════════════════════════╣ -║ Port Assignment Uniqueness ║ 4/10 (2 conflicts found) ║ -║ Environment Variable Standardization║ 6/10 (3 naming conventions) ║ -║ Configuration Documentation ║ 5/10 (3 missing .env.example files) ║ -║ Centralized Environment Setup ║ 8/10 (good but some backends override) ║ -║ Configuration Validation ║ 3/10 (only 2/8 backends have schemas) ║ -║ Hardcoded Values ║ 4/10 (CORS + DEV_USER_ID hardcoded) ║ -║ Auth Configuration Consistency ║ 4/10 (4 different variable names) ║ -║ Security (no secrets in source) ║ 7/10 (mostly good, except DEV_USER_ID) ║ -╠════════════════════════════════════╬═════════════════════════════════════════╣ -║ OVERALL SCORE ║ 5.1/10 (NEEDS IMPROVEMENT) ║ -╚════════════════════════════════════╩═════════════════════════════════════════╝ -``` - -**To reach 8/10:** Fix blocking issues + add missing validation schemas -**To reach 9/10:** + Move all CORS to environment + Standardize auth URLs -**To reach 10/10:** + Complete documentation + Consistent dev bypass pattern across all - ---- - -## Quick Reference: Variable Name Standardization - -### Current (Inconsistent) - -``` -Chat: MANA_CORE_AUTH_URL -Picture: MANA_CORE_AUTH_URL -Zitare: MANA_CORE_AUTH_URL -Presi: MANA_CORE_AUTH_URL -Manadeck: MANA_SERVICE_URL ← Different! -Nutriphi: MANACORE_AUTH_URL ← Different! -``` - -### Recommended (Consistent) - -``` -All backends: MANA_CORE_AUTH_URL ← Standardized -``` - -### Migration Path - -1. Add MANA_CORE_AUTH_URL to .env.development (already exists!) -2. Update generate-env.mjs: - - Line 205: Change `MANA_SERVICE_URL` to `MANA_CORE_AUTH_URL` (Manadeck) - - Line 272: Change `MANACORE_AUTH_URL` to `MANA_CORE_AUTH_URL` (Nutriphi) -3. Update app.module.ts files if they reference old variable name -4. Update config/validation.schema.ts files if applicable -5. Test `pnpm setup:env` generates correct variables -6. Verify all backends read MANA_CORE_AUTH_URL - ---- - -## Next Steps - -1. **Read the full audit:** `/docs/ENV_CONFIGURATION_AUDIT.md` -2. **Follow the checklist:** `/docs/ENV_AUDIT_SUMMARY.md` -3. **Review this matrix:** You are here! -4. **Implement fixes:** Start with Phase 1 (blocking issues) -5. **Test & verify:** Run all backends simultaneously -6. **Document results:** Update CLAUDE.md with final port assignments - ---- - -Generated: December 1, 2025 -Auditor: Environment Configuration Auditor Agent (Claude Flow Swarm) diff --git a/docs/ENV_CONFIGURATION_AUDIT.md b/docs/ENV_CONFIGURATION_AUDIT.md deleted file mode 100644 index 5f625419d..000000000 --- a/docs/ENV_CONFIGURATION_AUDIT.md +++ /dev/null @@ -1,423 +0,0 @@ -# Environment Configuration Audit Report - -## Mana Universe Monorepo - Backend Authentication & Configuration - -**Date:** December 1, 2025 -**Auditor:** Environment Configuration Auditor Agent -**Scope:** All NestJS backends and mana-core-auth service - ---- - -## EXECUTIVE SUMMARY - -The monorepo has **CRITICAL PORT CONFLICTS** that will prevent multiple backends from running simultaneously. Additionally, there are inconsistencies in environment variable naming conventions across backends and missing configuration examples for some projects. - -**Status:** NEEDS IMMEDIATE ACTION - -- 2 port conflicts identified -- 3 naming convention inconsistencies -- 5 backends missing .env.example files -- Hardcoded CORS origins in multiple backends - ---- - -## 1. PORT ASSIGNMENT MATRIX - -### Current Assignments (from .env.development) - -| Backend | Port | Env Variable | Status | Conflict | -| ------------------ | -------- | --------------------------- | ----------- | -------- | -| Mana Core Auth | 3001 | MANA_CORE_AUTH_PORT | ✓ Unique | No | -| Chat | 3002 | CHAT_BACKEND_PORT | ✓ Unique | No | -| **Maerchenzauber** | **3003** | MAERCHENZAUBER_BACKEND_PORT | ⚠ CONFLICT | **Yes** | -| Manadeck | 3004 | MANADECK_BACKEND_PORT | ✓ Unique | No | -| **Picture** | **3003** | PICTURE_BACKEND_PORT | ⚠ CONFLICT | **Yes** | -| **Nutriphi** | **3002** | NUTRIPHI_BACKEND_PORT | ⚠ CONFLICT | **Yes** | -| Zitare | 3007 | ZITARE_BACKEND_PORT | ✓ Unique | No | -| Presi | 3008 | PRESI_BACKEND_PORT | ✓ Unique | No | -| Mana Games | 3011 | MANA_GAMES_BACKEND_PORT | ✓ Unique | No | -| Voxel Lava | 3010 | VOXEL_LAVA_BACKEND_PORT | ✓ Unique | No | - -### PORT CONFLICTS FOUND - -1. **Port 3003 - DOUBLE ASSIGNED** - - Maerchenzauber Backend: `MAERCHENZAUBER_BACKEND_PORT=3003` - - Picture Backend: `PICTURE_BACKEND_PORT=3003` - -2. **Port 3002 - DOUBLE ASSIGNED** - - Chat Backend: `CHAT_BACKEND_PORT=3002` - - Nutriphi Backend: `NUTRIPHI_BACKEND_PORT=3002` - -### RECOMMENDATION - -Reassign conflicting ports: - -- Maerchenzauber: Keep 3003, reassign Picture to **3005** or **3006** -- OR reassign Maerchenzauber to **3005** and keep Picture at 3003 -- Nutriphi: Reassign to **3006** or another available port -- Mana Games: Currently 3011 -- Voxel Lava: Currently 3010 - ---- - -## 2. AUTH ENVIRONMENT VARIABLES AUDIT - -### Central Configuration (.env.development) - -**PRESENT & CONFIGURED:** - -- ✓ `MANA_CORE_AUTH_URL=http://localhost:3001` (Line 16) -- ✓ `DEV_BYPASS_AUTH=true` (Line 59 - Chat only) -- ✓ JWT_PRIVATE_KEY & JWT_PUBLIC_KEY (Lines 19-20) -- ✓ CORS_ORIGINS=... (Line 41) - -**MISSING CENTRALIZED:** - -- ✗ `DEV_USER_ID` - NOT in .env.development - - Used hardcoded in Chat: `17cb0be7-058a-4964-9e18-1fe7055fd014` - - Should be centralized in .env.development - -- ✗ `MANA_CORE_SERVICE_KEY` - NOT found in generate-env.mjs mapping - - Defined for Manadeck in .env.example - - Not passed to backends via generator - -### Backend-Specific Auth Configuration - -| Backend | Auth URL Var | Dev Bypass | Dev User ID | Status | -| ------------ | ------------------ | ------------------- | ------------- | --------------- | -| **Chat** | MANA_CORE_AUTH_URL | ✓ Configured | ✗ Hardcoded | ⚠ Partially | -| **Picture** | MANA_CORE_AUTH_URL | ✗ Missing | ✗ Not checked | ✗ Incomplete | -| **Zitare** | MANA_CORE_AUTH_URL | ✗ Missing | ✗ Not checked | ✗ Incomplete | -| **Presi** | MANA_CORE_AUTH_URL | ✗ Missing | ✗ Not checked | ✗ Incomplete | -| **Manadeck** | MANA_SERVICE_URL | ✗ Not in generation | ✗ Not mapped | ✗ Not generated | - -### ISSUE: Naming Convention Inconsistency - -Different backends use DIFFERENT variable names for the same thing: - -``` -INCONSISTENT: -- Chat uses: MANA_CORE_AUTH_URL (from generate-env.mjs line 95) -- Picture uses: MANA_CORE_AUTH_URL (from generate-env.mjs line 230) -- Zitare uses: MANA_CORE_AUTH_URL (from generate-env.mjs line 300) -- Presi uses: MANA_CORE_AUTH_URL (from generate-env.mjs line 330) - -- Manadeck uses: MANA_SERVICE_URL (from generate-env.mjs line 205) -- Manadeck uses: APP_ID (from generate-env.mjs line 206) - -- Nutriphi uses: MANACORE_AUTH_URL (from generate-env.mjs line 272) -``` - -**STANDARDIZATION NEEDED:** -All backends should use consistent naming: - -- Recommend: `MANA_CORE_AUTH_URL` (most common) - ---- - -## 3. ENVIRONMENT VARIABLE MAPPING AUDIT - -### Generate-env.mjs Coverage Analysis - -| Backend | .env.example | generate-env.mjs | .env Generated | Coverage | -| -------------- | ------------ | ---------------- | --------------- | ------------------ | -| Chat | ✓ Exists | ✓ Lines 85-98 | ✓ Will generate | ✓ Complete | -| Picture | ✓ Exists | ✓ Lines 223-243 | ✓ Will generate | ✓ Complete | -| Manadeck | ✓ Exists | ✓ Lines 199-209 | ✓ Will generate | ✓ Complete | -| **Zitare** | ✗ Missing | ✓ Lines 294-303 | ✓ Will generate | ⚠ Missing example | -| **Presi** | ✗ Missing | ✓ Lines 323-334 | ✓ Will generate | ⚠ Missing example | -| Mana-Core-Auth | ✓ Exists | ✓ Lines 57-82 | ✓ Will generate | ✓ Complete | - -**Missing .env.example files:** - -- `/apps/zitare/apps/backend/.env.example` - Should document PORT, DATABASE_URL, MANA_CORE_AUTH_URL, CORS_ORIGINS -- `/apps/presi/apps/backend/.env.example` - Should document PORT, DATABASE_URL, MANA_CORE_AUTH_URL, JWT_PUBLIC_KEY, CORS_ORIGINS - ---- - -## 4. HARDCODED VALUES & SECURITY CONCERNS - -### Hardcoded in Source Code - -**Chat Backend** (`apps/chat/apps/backend/src/common/guards/jwt-auth.guard.ts`): - -```typescript -const DEV_USER_ID = '17cb0be7-058a-4964-9e18-1fe7055fd014'; // Line 1 -``` - -- Should be: `configService.get('DEV_USER_ID')` -- Should be in .env.development: `DEV_USER_ID=17cb0be7-058a-4964-9e18-1fe7055fd014` - -### Hardcoded CORS Origins in main.ts - -**Chat** (`src/main.ts` lines 10-18): - -```typescript -origin: [ - 'http://localhost:3000', - 'http://localhost:5173', - 'http://localhost:5174', - 'http://localhost:5178', - 'http://localhost:8081', - 'exp://localhost:8081', - 'http://localhost:3001', // Mana Core Auth -]; -``` - -**Picture** (`src/main.ts` lines 11-19): - -```typescript -const allowedOrigins = [ - 'http://localhost:3000', - 'http://localhost:5173', - 'http://localhost:5174', - 'http://localhost:5175', - 'http://localhost:8081', - 'exp://localhost:8081', - 'http://localhost:3001', -]; -``` - -**Presi** (`src/main.ts` lines 10-17): - -```typescript -origin: [ - 'http://localhost:3000', - 'http://localhost:5173', - 'http://localhost:5177', - 'http://localhost:5178', - 'http://localhost:8081', - 'exp://localhost:8081', - 'http://localhost:3001', -]; -``` - -**Zitare** (`src/main.ts` lines 10-16): - -```typescript -origin: [ - 'http://localhost:3000', - 'http://localhost:5173', - 'http://localhost:5177', - 'http://localhost:8081', - 'exp://localhost:8081', - 'http://localhost:3001', -]; -``` - -**RECOMMENDATION:** Move CORS_ORIGINS to .env.development (already exists as CORS_ORIGINS global variable, but not used by all backends) - ---- - -## 5. CONFIGURATION BEST PRACTICES COMPLIANCE - -### Configuration Module Setup - -| Backend | ConfigModule | Validation | Env File Path | Status | -| -------------- | ------------------------ | ---------------------- | ------------- | ---------- | -| Chat | ✓ ConfigModule.forRoot() | ✗ No validation schema | `.env` | ⚠ Minimal | -| Picture | ✓ ConfigModule.forRoot() | ✗ No validation schema | `.env` | ⚠ Minimal | -| Zitare | ✓ ConfigModule.forRoot() | ✗ No validation schema | `.env` | ⚠ Minimal | -| Presi | ✓ ConfigModule.forRoot() | ✗ No validation schema | `.env` | ⚠ Minimal | -| Manadeck | ✓ ConfigModule.forRoot() | ✓ Joi schema | `.env` | ✓ Complete | -| Mana-Core-Auth | ✓ ConfigModule.forRoot() | ✓ Config service | `.env` | ✓ Complete | - -**ISSUE:** Chat, Picture, Zitare, Presi lack validation schemas. - -**EXAMPLE (Manadeck validation.schema.ts):** - -```typescript -export const validationSchema = Joi.object({ - NODE_ENV: Joi.string().valid('development', 'production'), - PORT: Joi.number().required(), - DATABASE_URL: Joi.string().required(), - MANA_CORE_AUTH_URL: Joi.string().required(), - // ... etc -}); -``` - ---- - -## 6. CRITICAL ISSUES SUMMARY - -### BLOCKING ISSUES (Fix Immediately) - -1. **Port Conflict - 3002** - - Chat and Nutriphi both assigned to port 3002 - - Cannot run simultaneously - - **Fix:** Reassign Nutriphi to port 3006 - -2. **Port Conflict - 3003** - - Picture and Maerchenzauber both assigned to port 3003 - - Cannot run simultaneously - - **Fix:** Reassign Picture to port 3005 or Maerchenzauber to 3006 - -3. **Hardcoded Dev User ID in Chat Backend** - - `DEV_USER_ID = '17cb0be7-058a-4964-9e18-1fe7055fd014'` hardcoded in source - - Not configurable via environment - - **Fix:** Move to .env.development and load via ConfigService - -### MAJOR ISSUES (Fix Soon) - -4. **Inconsistent Auth Variable Names** - - Manadeck uses `MANA_SERVICE_URL` instead of `MANA_CORE_AUTH_URL` - - Nutriphi uses `MANACORE_AUTH_URL` (no underscore) - - **Fix:** Standardize all to `MANA_CORE_AUTH_URL` - -5. **Hardcoded CORS Origins** - - 4 backends hardcode CORS lists in main.ts - - Should use environment variables - - **Fix:** Use CORS_ORIGINS from .env.development - -6. **Missing Configuration Examples** - - Zitare and Presi lack .env.example files - - **Fix:** Create comprehensive .env.example files - -### MEDIUM ISSUES (Improve Quality) - -7. **Missing Validation Schemas** - - 4 backends lack Joi validation schemas - - No type safety for environment variables - - **Fix:** Add validation schemas to Chat, Picture, Zitare, Presi - -8. **Dev Bypass Auth Not Consistent** - - Only Chat backend has DEV_BYPASS_AUTH implemented - - Other backends may lack development bypass mechanism - - **Fix:** Add consistent development auth bypass pattern - ---- - -## 7. RECOMMENDED ACTIONS - -### Phase 1: Critical Fixes (Do First) - -```bash -# 1. Fix port conflicts in .env.development -# Change line 122: PICTURE_BACKEND_PORT=3003 → PICTURE_BACKEND_PORT=3005 -# Change line 146: NUTRIPHI_BACKEND_PORT=3002 → NUTRIPHI_BACKEND_PORT=3006 - -# 2. Add DEV_USER_ID to .env.development -# Add after line 59: DEV_USER_ID=17cb0be7-058a-4964-9e18-1fe7055fd014 - -# 3. Standardize auth URL naming -# Update generate-env.mjs line 272 (Nutriphi): -# MANACORE_AUTH_URL: → MANA_CORE_AUTH_URL: -# Update generate-env.mjs line 205 (Manadeck): -# MANA_SERVICE_URL: → MANA_CORE_AUTH_URL: -``` - -### Phase 2: Configuration Examples - -```bash -# Create missing .env.example files: -# - apps/zitare/apps/backend/.env.example -# - apps/presi/apps/backend/.env.example - -# Based on .env.development variables and backend requirements -``` - -### Phase 3: Code Quality - -```bash -# Add validation schemas to: -# - apps/chat/apps/backend/src/config/validation.schema.ts -# - apps/picture/apps/backend/src/config/validation.schema.ts -# - apps/zitare/apps/backend/src/config/validation.schema.ts -# - apps/presi/apps/backend/src/config/validation.schema.ts - -# Move CORS origins to environment: -# Update main.ts in Chat, Picture, Zitare, Presi to: -# app.enableCors({ -# origin: (configService.get('CORS_ORIGINS') || '').split(','), -# }) -``` - ---- - -## 8. UPDATED PORT ASSIGNMENTS (RECOMMENDED) - -| Backend | Recommended Port | Current | Status | -| -------------- | ---------------- | ------- | ---------- | -| Mana Core Auth | 3001 | 3001 | ✓ Keep | -| Chat | 3002 | 3002 | ✓ Keep | -| Maerchenzauber | 3003 | 3003 | ✓ Keep | -| Manadeck | 3004 | 3004 | ✓ Keep | -| Picture | **3005** | 3003 | **CHANGE** | -| Nutriphi | **3006** | 3002 | **CHANGE** | -| Zitare | 3007 | 3007 | ✓ Keep | -| Presi | 3008 | 3008 | ✓ Keep | -| Voxel Lava | 3010 | 3010 | ✓ Keep | -| Mana Games | 3011 | 3011 | ✓ Keep | - ---- - -## 9. ENVIRONMENT VARIABLE SUMMARY TABLE - -### Required for All Backends - -| Variable | Purpose | Centralized | Backend Usage | -| ------------------ | --------------------- | ------------------ | -------------------------------------- | -| NODE_ENV | Environment type | ✓ .env.development | All | -| PORT | Server port | ✓ Individual vars | All | -| DATABASE_URL | PostgreSQL connection | ✓ Individual vars | Chat, Manadeck, Picture, Zitare, Presi | -| MANA_CORE_AUTH_URL | Auth service URL | ✓ .env.development | Chat, Picture, Zitare, Presi, Manadeck | -| CORS_ORIGINS | Allowed origins | ✓ .env.development | All (hardcoded, should use env) | - -### Optional but Recommended - -| Variable | Purpose | Centralized | Backend Usage | -| --------------- | ---------------- | ------------------ | ------------- | -| DEV_BYPASS_AUTH | Skip auth in dev | ⚠ Partial | Chat only | -| DEV_USER_ID | Dev test user | ✗ Hardcoded | Chat | -| JWT_PUBLIC_KEY | Token validation | ✓ .env.development | Presi | - -### Backend-Specific - -| Backend | Key Variables | Centralized | -| -------------- | ------------------------------------- | ------------------ | -| Chat | GOOGLE*GENAI_API_KEY, AZURE_OPENAI*\* | ✓ .env.development | -| Picture | REPLICATE*API_TOKEN, S3*\* vars | ✓ .env.development | -| Zitare | (None beyond base) | ✓ .env.development | -| Presi | (None beyond base) | ✓ .env.development | -| Manadeck | GOOGLE_GENAI_API_KEY | ✓ .env.development | -| Mana-Core-Auth | JWT*\*, STRIPE*_, CREDITS\__ | ✓ .env.development | - ---- - -## 10. IMPLEMENTATION CHECKLIST - -- [ ] Fix port conflict: Picture 3003 → 3005 -- [ ] Fix port conflict: Nutriphi 3002 → 3006 -- [ ] Add DEV_USER_ID to .env.development -- [ ] Update Chat backend to use DEV_USER_ID from ConfigService -- [ ] Standardize MANA_SERVICE_URL to MANA_CORE_AUTH_URL in Manadeck generate-env.mjs -- [ ] Standardize MANACORE_AUTH_URL to MANA_CORE_AUTH_URL in Nutriphi generate-env.mjs -- [ ] Create .env.example for Zitare backend -- [ ] Create .env.example for Presi backend -- [ ] Add validation schemas to Chat backend config -- [ ] Add validation schemas to Picture backend config -- [ ] Add validation schemas to Zitare backend config -- [ ] Add validation schemas to Presi backend config -- [ ] Move CORS origins from hardcoded arrays to environment variables (all backends) -- [ ] Document port assignments in CLAUDE.md -- [ ] Test all backends can run simultaneously with correct ports -- [ ] Verify auth endpoint connectivity from each backend to mana-core-auth - ---- - -## AUDIT DETAILS - -**Files Reviewed:** - -- .env.development (202 lines) -- scripts/generate-env.mjs (433 lines) -- 6 backends app.module.ts files -- 5 backends main.ts files -- 3 .env.example files (Chat, Picture, Manadeck) -- 1 mana-core-auth main.ts -- Various configuration schemas and guards - -**Total Files Analyzed:** 25+ -**Lines of Code Reviewed:** 2,000+ -**Issues Identified:** 8 critical/major issues -**Port Conflicts Found:** 2 (affecting 3 backends) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..2bdd0a816 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,92 @@ +# Manacore Monorepo Documentation + +Welcome to the Manacore monorepo documentation. This guide helps you find exactly what you need. + +## 🚀 Quick Navigation + +| I want to... | Go here | +|-------------|---------| +| **Start developing locally** | [Local Development](getting-started/local-development.md) | +| **Set up environment variables** | [Environment Setup](../CLAUDE.md#environment-variables) | +| **Understand the architecture** | [Deployment Architecture](DEPLOYMENT_ARCHITECTURE.md) | +| **Work with databases** | [Database Migrations](DATABASE_MIGRATIONS.md) | +| **Deploy to staging** | [Staging Setup](STAGING_SETUP.md) | +| **Deploy to production** | [Deployment Runbooks](DEPLOYMENT_RUNBOOKS.md) | +| **Use Docker locally** | [Docker Guide](DOCKER_GUIDE.md) | +| **Debug an issue** | [Staging Issues](STAGING_DEPLOYMENT_ISSUES.md) | +| **Learn code patterns** | [Guidelines](../.claude/GUIDELINES.md) | +| **Configure CI/CD** | [CI/CD Setup](CI_CD_SETUP.md) | +| **Work with runtime config** | [Runtime Config](RUNTIME_CONFIG.md) | +| **Self-host the platform** | [Self-Hosting Guide](SELF-HOSTING-GUIDE.md) | + +## 📁 Documentation Structure + +### Getting Started +First-time setup, environment configuration, and basic workflows. +- [Local Development](LOCAL_DEVELOPMENT.md) - Complete local development setup +- [Setup Templates](SETUP_TEMPLATES.md) - Templates for new projects + +### Architecture & Design +System design, technology choices, and architectural patterns. +- [Deployment Architecture](DEPLOYMENT_ARCHITECTURE.md) - Complete infrastructure overview +- [Deployment Diagrams](DEPLOYMENT_DIAGRAMS.md) - Visual architecture diagrams + +### Development Workflows +Day-to-day development, migrations, and Docker. +- [Database Migrations](DATABASE_MIGRATIONS.md) - Migration best practices +- [Docker Guide](DOCKER_GUIDE.md) - Local Docker setup +- [Git Workflow](GIT_WORKFLOW.md) - Git branching and commit conventions +- [Development Scripts](DEVELOPMENT_SCRIPTS.md) - Helper scripts + +### Deployment & Operations +CI/CD, staging, production deployment, and operational procedures. +- [Deployment Overview](DEPLOYMENT.md) - Deployment strategy overview +- [Deployment Runbooks](DEPLOYMENT_RUNBOOKS.md) - Step-by-step deployment procedures +- [Staging Setup](STAGING_SETUP.md) - Hetzner staging environment +- [Staging Issues](STAGING_DEPLOYMENT_ISSUES.md) - Known issues and solutions +- [Hetzner Production Guide](HETZNER_PRODUCTION_GUIDE.md) - Production deployment +- [CI/CD Setup](CI_CD_SETUP.md) - GitHub Actions configuration +- [Runtime Config](RUNTIME_CONFIG.md) - Dynamic configuration injection + +### Specialized Topics +- [PWA Guide](PWA_GUIDE.md) - Progressive Web App setup +- [I18N](I18N.md) - Internationalization +- [User Settings](USER_SETTINGS.md) - User settings architecture +- [Self-Hosting Guide](SELF-HOSTING-GUIDE.md) - Self-hosting instructions +- [Testing Guide](TESTING.md) - Testing strategies + +### Project-Specific +- [ManaDeck Postgres Migration](MANADECK_POSTGRES_MIGRATION.md) - ManaDeck database migration +- [Uload Deployment](ULOAD-DEPLOYMENT.md) - Uload-specific deployment + +### Archived Documentation +Historical documentation and analysis reports moved to [archive/](archive/). + +## 🎯 Documentation Philosophy + +This documentation follows these principles: + +1. **Progressive Disclosure** - Start with essentials, link to deep dives +2. **Single Source of Truth** - Each topic has one authoritative document +3. **Task-Oriented** - Organized by what you're trying to accomplish +4. **Keep Current** - Archive or delete outdated docs instead of letting them linger + +## 📝 For AI Assistants + +If you're Claude or another AI assistant: +- Start with [CLAUDE.md](../CLAUDE.md) for essential patterns +- Reference [Guidelines](../.claude/GUIDELINES.md) for detailed coding patterns +- Use this README to find specific documentation topics +- Always check file modification dates to ensure information is current + +## 🔄 Maintenance + +When updating documentation: +- Update this README if you add/move/remove major docs +- Archive outdated docs to `archive/` rather than deleting +- Keep cross-references up to date +- Update the modification date in this file + +--- + +**Last Updated:** 2025-12-16 diff --git a/docs/README_ENV_AUDIT.md b/docs/README_ENV_AUDIT.md deleted file mode 100644 index ca55d6f45..000000000 --- a/docs/README_ENV_AUDIT.md +++ /dev/null @@ -1,264 +0,0 @@ -# Environment Configuration Audit - Complete Documentation - -This folder contains a comprehensive audit of all backend environment variable configurations in the Mana Universe monorepo. - -## Documents - -### 1. [ENV_CONFIGURATION_AUDIT.md](ENV_CONFIGURATION_AUDIT.md) - MAIN REPORT - -**The complete audit with all findings and detailed analysis** - -- **Section 1:** Port Assignment Matrix (identifies 2 port conflicts) -- **Section 2:** Auth Environment Variables (missing variables, inconsistent naming) -- **Section 3:** Environment Variable Mapping Audit (coverage analysis) -- **Section 4:** Hardcoded Values & Security Concerns (DEV_USER_ID, CORS) -- **Section 5:** Configuration Best Practices Compliance (validation schemas) -- **Section 6:** Critical Issues Summary (8 issues identified) -- **Section 7:** Recommended Actions (3 implementation phases) -- **Section 8:** Updated Port Assignments (proposed fixes) -- **Section 9:** Environment Variable Summary Tables -- **Section 10:** Implementation Checklist (16 action items) - -**Read this if:** You need the complete, detailed analysis with code examples and full context. - -**Lines:** 408 | **Size:** 14KB - ---- - -### 2. [ENV_AUDIT_SUMMARY.md](ENV_AUDIT_SUMMARY.md) - QUICK START GUIDE - -**Executive summary with actionable checklists and next steps** - -- **Quick Issue Overview:** Blocking, Major, and Medium issues at a glance -- **Phase-Based Checklist:** Quick fix checklist organized by priority -- **Port Mapping:** Visual comparison of current vs. recommended ports -- **Environment Variable Status:** What's working and what needs work -- **Files to Modify:** Concrete list of files that need changes -- **Testing Instructions:** How to verify fixes -- **Additional Resources:** Links to full documentation - -**Read this if:** You need a quick overview and want to start fixing issues immediately. - -**Lines:** 166 | **Size:** 5KB - ---- - -### 3. [ENV_BACKEND_MATRIX.md](ENV_BACKEND_MATRIX.md) - DETAILED MATRIX VISUALIZATION - -**Backend configuration status visualized in detailed tables and matrices** - -- **Backend Status Matrix:** Port, Auth URL, Dev Bypass, Validation status -- **Database Configuration:** Which backends have database URLs -- **CORS Configuration:** How CORS is implemented (hardcoded vs. environment) -- **Port Availability & Conflicts:** Visual representation of port assignments -- **Environment Variable Generation Map:** How variables flow from .env.development -- **Severity Matrix:** Issue counts and time estimates -- **Best Practices Scorecard:** Overall quality assessment (5.1/10) -- **Variable Standardization Guide:** Current inconsistencies and path to consistency - -**Read this if:** You want to understand the full scope of backend configurations visually. - -**Lines:** 234 | **Size:** 8KB - ---- - -## Key Findings Summary - -### BLOCKING ISSUES (Fix Immediately) - -1. **Port 3002 Conflict:** Chat and Nutriphi both use port 3002 -2. **Port 3003 Conflict:** Picture and Maerchenzauber both use port 3003 -3. **Hardcoded DEV_USER_ID:** Chat backend hardcodes `17cb0be7-058a-4964-9e18-1fe7055fd014` - -### MAJOR ISSUES (Fix Soon) - -4. **Auth URL Naming Inconsistency:** - - Manadeck uses `MANA_SERVICE_URL` (should be `MANA_CORE_AUTH_URL`) - - Nutriphi uses `MANACORE_AUTH_URL` (should be `MANA_CORE_AUTH_URL`) - - Chat, Picture, Zitare, Presi use correct `MANA_CORE_AUTH_URL` - -5. **Hardcoded CORS Origins:** 4 backends hardcode allowed origins instead of using environment variable - -6. **Missing Configuration Examples:** - - No `.env.example` for Zitare backend - - No `.env.example` for Presi backend - -### MEDIUM ISSUES (Improve Quality) - -7. **Missing Validation Schemas:** Chat, Picture, Zitare, Presi lack Joi validation schemas - -8. **Inconsistent Dev Bypass Auth:** Only Chat backend implements DEV_BYPASS_AUTH - ---- - -## Quick Fix Timeline - -| Phase | Tasks | Time | Impact | -| ------- | -------------------------------------- | --------- | ------------------------------------------------- | -| Phase 1 | Fix ports + add DEV_USER_ID | 15-30 min | CRITICAL - Enables simultaneous backend execution | -| Phase 2 | Standardize naming + add .env examples | 30 min | MAJOR - Improves consistency | -| Phase 3 | Add validation schemas + extract CORS | 2-3 hours | QUALITY - Code quality improvement | - -**Total estimated time to fix all issues: 6-8 hours** - ---- - -## Which Document Should I Read? - -### I want to... - -**...quickly understand what's wrong** -→ Read [ENV_AUDIT_SUMMARY.md](ENV_AUDIT_SUMMARY.md) (5 min read) - -**...get detailed analysis with code examples** -→ Read [ENV_CONFIGURATION_AUDIT.md](ENV_CONFIGURATION_AUDIT.md) (20 min read) - -**...see all backend configurations visually** -→ Read [ENV_BACKEND_MATRIX.md](ENV_BACKEND_MATRIX.md) (10 min read) - -**...start fixing issues immediately** -→ Read [ENV_AUDIT_SUMMARY.md](ENV_AUDIT_SUMMARY.md) "Quick Fix Checklist" section - -**...understand the complete scope** -→ Read all three documents in order (1 → 2 → 3) - ---- - -## Implementation Roadmap - -### If you have 30 minutes - -1. Read ENV_AUDIT_SUMMARY.md -2. Fix port conflicts in .env.development -3. Add DEV_USER_ID variable - -### If you have 1-2 hours - -1. Complete Phase 1 fixes -2. Update generate-env.mjs variable names -3. Create .env.example files for Zitare and Presi - -### If you have 4+ hours - -1. Complete all Phase 1 & 2 fixes -2. Add validation schemas to all backends -3. Extract CORS origins to environment variables -4. Test all backends can run simultaneously - ---- - -## Files Analyzed in This Audit - -**Configuration Files:** - -- .env.development (202 lines) -- scripts/generate-env.mjs (433 lines) -- services/mana-core-auth/.env.example -- apps/chat/apps/backend/.env.example -- apps/picture/apps/backend/.env.example -- apps/manadeck/apps/backend/.env.example - -**Backend Configuration:** - -- 6 app.module.ts files (NestJS configuration) -- 5 main.ts files (server bootstrap & CORS) -- 1 validation.schema.ts file (Manadeck) -- Multiple JWT auth guard files - -**Total Files Analyzed:** 25+ -**Total Lines Reviewed:** 2,000+ -**Issues Identified:** 8 critical/major items, 17 total issues - ---- - -## Recommendations by Priority - -### Priority 1: BLOCKING (Do Today) - -- [ ] Fix PICTURE_BACKEND_PORT: 3003 → 3005 -- [ ] Fix NUTRIPHI_BACKEND_PORT: 3002 → 3006 -- [ ] Add DEV_USER_ID to .env.development -- [ ] Update Chat backend to read DEV_USER_ID from ConfigService - -### Priority 2: MAJOR (Do This Week) - -- [ ] Rename MANA_SERVICE_URL to MANA_CORE_AUTH_URL in Manadeck -- [ ] Rename MANACORE_AUTH_URL to MANA_CORE_AUTH_URL in Nutriphi -- [ ] Create .env.example for Zitare backend -- [ ] Create .env.example for Presi backend - -### Priority 3: MEDIUM (Plan This Week) - -- [ ] Add validation schemas to 4 backends (Chat, Picture, Zitare, Presi) -- [ ] Extract CORS origins to CORS_ORIGINS environment variable -- [ ] Update all backends to use env variable for CORS -- [ ] Document final port assignments in project CLAUDE.md files - -### Priority 4: LONG-TERM (Future Improvement) - -- [ ] Implement consistent dev bypass auth pattern across all backends -- [ ] Add comprehensive integration tests for all backends -- [ ] Document environment configuration in deployment guide -- [ ] Set up CI/CD to validate .env configuration changes - ---- - -## Success Criteria - -After implementing all recommendations, you should be able to: - -1. **Run all 8 active backends simultaneously without port conflicts** - - ```bash - pnpm dev:auth & - pnpm dev:chat:backend & - pnpm dev:picture:backend & - pnpm dev:manadeck:backend & - pnpm dev:zitare:backend & - pnpm dev:presi:backend & - ``` - -2. **Every backend loads from .env without warnings** - - All required variables present - - All variables properly typed/validated - -3. **Consistent naming conventions across all backends** - - Same auth URL variable name used everywhere - - Same database URL pattern - - Same CORS configuration approach - -4. **All backends properly documented** - - Each has .env.example file - - Each has configuration validation schema - - Port assignments documented in CLAUDE.md - -5. **Security best practices enforced** - - No hardcoded values in source code - - All secrets loaded from environment - - Configuration validated on startup - ---- - -## Contact & Questions - -If you have questions about any findings: - -1. **Detailed findings** → See ENV_CONFIGURATION_AUDIT.md section numbers -2. **Implementation guidance** → See ENV_AUDIT_SUMMARY.md "Files to Modify" -3. **Visual reference** → See ENV_BACKEND_MATRIX.md tables - ---- - -## Document Metadata - -**Audit Date:** December 1, 2025 -**Auditor:** Environment Configuration Auditor Agent -**Swarm Role:** Claude Flow Swarm - Configuration Validation Team -**Monorepo Version:** manacore-monorepo (main branch) -**Total Issues:** 8 critical/major + 9 medium/quality issues - -**Status:** READY FOR IMPLEMENTATION - ---- - -**Next Action:** Read ENV_AUDIT_SUMMARY.md and start with Phase 1 fixes. diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/archive/BACKEND_ARCHITECTURE.md similarity index 100% rename from docs/BACKEND_ARCHITECTURE.md rename to docs/archive/BACKEND_ARCHITECTURE.md diff --git a/docs/CHANGELOG_2025-11-24.md b/docs/archive/CHANGELOG_2025-11-24.md similarity index 100% rename from docs/CHANGELOG_2025-11-24.md rename to docs/archive/CHANGELOG_2025-11-24.md diff --git a/docs/DOCKER_SETUP_ANALYSIS.md b/docs/archive/DOCKER_SETUP_ANALYSIS.md similarity index 100% rename from docs/DOCKER_SETUP_ANALYSIS.md rename to docs/archive/DOCKER_SETUP_ANALYSIS.md diff --git a/docs/HETZNER_DEPLOYMENT_SUMMARY.md b/docs/archive/HETZNER_DEPLOYMENT_SUMMARY.md similarity index 100% rename from docs/HETZNER_DEPLOYMENT_SUMMARY.md rename to docs/archive/HETZNER_DEPLOYMENT_SUMMARY.md diff --git a/docs/PROJECT_OVERVIEW.md b/docs/archive/PROJECT_OVERVIEW.md similarity index 100% rename from docs/PROJECT_OVERVIEW.md rename to docs/archive/PROJECT_OVERVIEW.md diff --git a/docs/archive/RESTRUCTURE_2025-12-16.md b/docs/archive/RESTRUCTURE_2025-12-16.md new file mode 100644 index 000000000..9d63f9060 --- /dev/null +++ b/docs/archive/RESTRUCTURE_2025-12-16.md @@ -0,0 +1,127 @@ +# Documentation Restructure - December 16, 2025 + +## Summary + +Restructured documentation based on industry best practices from HackerNews discussion and HumanLayer blog post on writing effective CLAUDE.md files. + +## Changes Made + +### Root CLAUDE.md +- **Before:** 678 lines, 22 KB +- **After:** 176 lines, 5.7 KB +- **Reduction:** 74% smaller + +#### What Was Removed +- Detailed project tables (moved conceptually to docs/) +- Extensive authentication code examples (kept brief examples, reference .claude/guidelines/) +- Object storage implementation details +- Landing page deployment procedures +- Detailed environment variable setup +- Archived projects list (13 projects) +- Code quality infrastructure TODO section + +#### What Was Added +- **Critical Gotchas** section (5 key issues Claude frequently gets wrong) +- **Verification signature** (🏗️ ManaCore Monorepo) to confirm Claude read the file +- Clearer signposting to detailed documentation +- Focus on universally applicable patterns only + +### Documentation Organization + +#### New Structure +``` +docs/ +├── README.md # Navigation index (NEW) +├── getting-started/ # (NEW - empty for now) +├── architecture/ # (NEW - empty for now) +├── development/ # (NEW - empty for now) +├── deployment/ # (NEW - empty for now) +├── operations/ # (NEW - empty for now) +├── reference/ # (NEW - empty for now) +└── archive/ # (NEW) +``` + +#### Files Deleted +- `ENV_AUDIT_SUMMARY.md` - Outdated audit (Dec 1, 2024) +- `ENV_BACKEND_MATRIX.md` - Outdated audit +- `ENV_CONFIGURATION_AUDIT.md` - Outdated audit +- `README_ENV_AUDIT.md` - Outdated audit +- `DEPENDENCY_ALIGNMENT.md` - Point-in-time snapshot + +#### Files Archived +Moved to `docs/archive/`: +- `DOCKER_SETUP_ANALYSIS.md` - Analysis document +- `BACKEND_ARCHITECTURE.md` - Possibly outdated (25 KB) +- `PROJECT_OVERVIEW.md` - Possibly outdated (41 KB) +- `TESTING_SUMMARY.md` - Outdated test count +- `TESTING_IMPLEMENTATION_GUIDE.md` - Superseded +- `CHANGELOG_2025-11-24.md` - Historical +- `HETZNER_DEPLOYMENT_SUMMARY.md` - Redundant with other deployment docs + +### Best Practices Applied + +1. **Instruction Budget Management** + - Kept only high-signal, universally applicable information + - Reduced from 678 lines to 176 lines + - AI instruction budget is ~150-200 total; we now use ~176 + +2. **Progressive Disclosure** + - Main CLAUDE.md is concise entry point + - Links to detailed .claude/guidelines/ for code patterns + - Links to docs/ for operational procedures + +3. **Critical Gotchas** + - Turborepo infinite loops + - Svelte 5 runes only + - Auth integration requirements + - Go-style error handling + - Environment variable prefixes + +4. **Verification Mechanism** + - Added project signature requirement (🏗️ ManaCore Monorepo) + - Helps detect when Claude stops following instructions + +## Backup + +Original CLAUDE.md saved as `CLAUDE.md.backup` (22 KB, 678 lines). + +## Metrics + +| Metric | Before | After | Change | +|--------|--------|-------|--------| +| CLAUDE.md lines | 678 | 176 | -74% | +| CLAUDE.md size | 22 KB | 5.7 KB | -74% | +| docs/ files | 50+ | 43 | -7 deleted, -7 archived | +| Documented projects | 18 (active + archived) | 6 (active only) | -67% | + +## Next Steps (Phase 2) + +Future improvements to consider: + +1. **Consolidate Environment Docs** + - Merge remaining env docs into single `docs/reference/environment-matrix.md` + +2. **Split DEPLOYMENT_ARCHITECTURE.md** + - Currently 2,814 lines (81 KB) + - Should be 6-8 separate documents + +3. **Reorganize docs/** + - Move files into logical subdirectories + - Create topic-based navigation + +4. **Consolidate Authentication Docs** + - Keep `.claude/guidelines/authentication.md` (code patterns) + - Keep separate (already exists in .claude/guidelines/) + +## References + +- [HN Discussion on CLAUDE.md](https://news.ycombinator.com/item?id=46098838) +- [HumanLayer: Writing a Good CLAUDE.md](https://www.humanlayer.dev/blog/writing-a-good-claude-md) + +## Key Insights + +1. **Length matters** - Shorter files = better AI performance +2. **Universal over specific** - Only include broadly applicable patterns +3. **Verification is critical** - Add canary instructions to detect compliance +4. **Progressive disclosure** - Link to details rather than inline everything +5. **Information density** - Every line should justify its inclusion diff --git a/docs/TESTING_IMPLEMENTATION_GUIDE.md b/docs/archive/TESTING_IMPLEMENTATION_GUIDE.md similarity index 100% rename from docs/TESTING_IMPLEMENTATION_GUIDE.md rename to docs/archive/TESTING_IMPLEMENTATION_GUIDE.md diff --git a/docs/TESTING_SUMMARY.md b/docs/archive/TESTING_SUMMARY.md similarity index 100% rename from docs/TESTING_SUMMARY.md rename to docs/archive/TESTING_SUMMARY.md