first commit

This commit is contained in:
2025-11-24 23:10:55 -06:00
commit 8315fa51c9
279 changed files with 74600 additions and 0 deletions

921
docs/ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,921 @@
# Architecture
## System Overview
**Microservices Architecture** - Three independent, deployable components:
```
┌─────────────────────────────────────────────────────────────┐
│ Frontend Layer (2 options) │
│ │
│ ┌──────────────────────┐ ┌──────────────────────┐ │
│ │ Public Web │ │ Godot Client │ │
│ │ (Flask + Jinja2) │ │ (Native Game) │ │
│ │ │ │ │ │
│ │ - Browser-based UI │ │ - Desktop/Mobile │ │
│ │ - HTMX interactions │ │ - Cross-platform │ │
│ │ - Server-side │ │ - GDScript │ │
│ │ rendering │ │ │ │
│ └──────────────────────┘ └──────────────────────┘ │
│ │ │ │
│ └──────────────┬───────────────┘ │
│ │ │
│ │ HTTP/REST │
└──────────────────────────┼─────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ API Backend (Flask) │
│ │
│ Single Source of Truth - All Business Logic │
│ - Authentication (via Appwrite) │
│ - Game logic & mechanics │
│ - Character management │
│ - Combat system │
│ - Marketplace transactions │
│ - Session management │
│ - Data models & validation │
│ - AI orchestration │
└─────────────────────────────────────────────────────────────┘
┌───────────────────┼──────────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Appwrite │ │ Redis + RQ │ │ AI APIs │
│ │ │ │ │ │
│ - Auth │ │ - Job Queue │ │ - Replicate │
│ - Database │ │ - Caching │ │ - Anthropic │
│ - Storage │ │ - Sessions │ │ │
│ - Realtime │ │ │ │ │
└──────────────┘ └──────────────┘ └──────────────┘
```
### Component Responsibilities
**`/api` - API Backend (Port 5000)**
- **Role:** Single source of truth, all business logic
- **Tech:** Flask REST API + Appwrite + RQ + Redis
- **Contains:** Models, services, game logic, AI integration
- **Deployment:** Independent with own venv, config, tests
- **Location:** `/api` directory
**`/public_web` - Web Frontend (Port 5001)**
- **Role:** Thin UI layer for browsers
- **Tech:** Flask + Jinja2 + HTMX
- **Contains:** Views, templates, static assets
- **Communication:** HTTP requests to API backend
- **Deployment:** Independent with own venv, config
- **Location:** `/public_web` directory
**`/godot_client` - Game Client**
- **Role:** Native cross-platform game client
- **Tech:** Godot 4.5 + GDScript
- **Contains:** UI, scenes, client-side logic
- **Communication:** HTTP requests to API backend
- **Deployment:** Exports to Desktop/Mobile/Web
- **Location:** `/godot_client` directory
---
## Core Design Principles
1. **Microservices Architecture:** Three independent, deployable components (API, Web, Godot)
2. **API as Single Source of Truth:** All business logic centralized in API backend
3. **AI-Driven Narrative:** Claude models generate story, NPC dialogue, combat descriptions
4. **Code-Driven Mechanics:** All game mechanics (damage, stats, effects) use deterministic formulas (JRPG-style)
5. **Turn-Based Gameplay:** Classic D&D style, not real-time
6. **Scalable Architecture:** Independent services, horizontal scaling ready
7. **Security First:** Developer is cybersecurity senior engineer/director - security is paramount
8. **Monetization:** Tiered subscription model with free tier
---
## Tech Stack
### API Backend (`/api`)
| Component | Technology | Purpose |
|-----------|-----------|---------|
| **Framework** | Flask 3.x | REST API framework |
| **Authentication** | Appwrite Auth | User management, session tokens |
| **Database** | Appwrite Database | NoSQL document storage |
| **Realtime** | Appwrite Realtime | WebSocket connections for multiplayer |
| **Storage** | Appwrite Storage | User assets, logs |
| **Job Queue** | RQ (Redis Queue) | Async AI calls, background tasks |
| **Caching** | Redis | Session data, rate limiting |
| **AI (Free)** | Replicate API | Free tier users (Llama 3 70B) |
| **AI (Paid)** | Anthropic Claude | Paid tier users (Haiku/Sonnet) |
| **Data Models** | Dataclasses | Typed domain models |
| **Logging** | Structlog | Structured logging |
| **Testing** | Pytest | Unit and integration tests |
| **WSGI Server** | Gunicorn | Production WSGI server |
### Web Frontend (`/public_web`)
| Component | Technology | Purpose |
|-----------|-----------|---------|
| **Framework** | Flask 3.x | Lightweight web server |
| **Templates** | Jinja2 | Server-side HTML rendering |
| **UI Enhancement** | HTMX | Dynamic updates without heavy JS |
| **Styling** | Vanilla CSS | Custom dark theme |
| **API Client** | Python requests | HTTP calls to API backend |
| **Logging** | Structlog | Structured logging |
| **WSGI Server** | Gunicorn | Production WSGI server |
### Godot Client (`/godot_client`)
| Component | Technology | Purpose |
|-----------|-----------|---------|
| **Engine** | Godot 4.5 | Cross-platform game engine |
| **Language** | GDScript | Game logic and UI |
| **HTTP Client** | HTTPClient singleton | API communication |
| **State Management** | StateManager singleton | Global game state |
| **Fonts** | Cinzel + Lato | Display and body fonts |
| **Exports** | Desktop/Mobile/Web | Multi-platform deployment |
### Shared Infrastructure
| Component | Technology | Purpose |
|-----------|-----------|---------|
| **Configuration** | YAML files | Environment-specific settings |
| **Secrets** | .env files | API keys, credentials |
| **Deployment** | Docker | Containerized services |
| **Version Control** | Git | Source code management |
---
## AI Model Strategy
### Model Selection Philosophy
- Use **Anthropic Claude models** for all paid tier interactions
- Use **Replicate free models** only for free tier users
- Model selection is **per-call based**, determined by context importance and user tier
### Model Tiers
| Tier | Provider | Model | Max Tokens | Temperature | Use Cases |
|------|----------|-------|------------|-------------|-----------|
| **FREE** | Replicate | meta-llama-3-70b-instruct | 256 | 0.7 | Free tier users only |
| **STANDARD** | Anthropic | claude-3-5-haiku-20241022 | 512 | 0.8 | Most interactions (paid) |
| **PREMIUM** | Anthropic | claude-3-5-sonnet-20241022 | 1024 | 0.9 | Important moments (paid) |
### Context-Based Model Selection
| Context | Model Tier | Examples |
|---------|-----------|----------|
| Simple acknowledgment | FREE | "You enter the room", "Item picked up" |
| Item description | FREE | Basic item lore |
| NPC dialogue | STANDARD | Merchant conversations, quest givers |
| Combat narrative | STANDARD | Regular combat descriptions |
| Story progression | PREMIUM | Major plot developments |
| Boss encounter | PREMIUM | Epic boss fight narratives |
| Character death | PREMIUM | Dramatic death scenes |
**Note:** Free tier users always get FREE tier models regardless of context.
### Prompt Management
- Use **Jinja2 templates** for all AI prompts
- Enable easy data injection and maintainability
- Templates stored in `app/ai/prompt_templates.py`
---
## Appwrite Collections
### users
Handled automatically by Appwrite Auth.
### characters
| Field | Type | Description |
|-------|------|-------------|
| `$id` | String | Unique ID |
| `userId` | String | Owner user ID |
| `characterData` | JSON String | Serialized Character dataclass |
| `created_at` | ISO Timestamp | Creation time |
| `updated_at` | ISO Timestamp | Last update |
| `is_active` | Boolean | Active character flag |
### game_sessions
| Field | Type | Description |
|-------|------|-------------|
| `$id` | String | Session ID |
| `party_member_ids` | Array[String] | Character IDs in party |
| `config` | Object | Session configuration |
| `combat_encounter` | JSON String | Current combat or null |
| `conversation_history` | Array[Object] | Turn-by-turn history |
| `game_state` | Object | Current location, quests, events |
| `turn_order` | Array[String] | Character IDs in turn order |
| `current_turn` | Integer | Index in turn_order |
| `turn_number` | Integer | Global turn counter |
| `created_at` | ISO Timestamp | Session start |
| `last_activity` | ISO Timestamp | Last action |
| `status` | String | active, completed, timeout |
**Session Config Structure:**
```json
{
"min_players": 2,
"timeout_minutes": 30,
"auto_save_interval": 5
}
```
**Conversation History Entry:**
```json
{
"turn": 1,
"character_id": "char_id_1",
"character_name": "Aragorn",
"action": "I search for traps",
"dm_response": "You notice...",
"combat_log": []
}
```
### marketplace_listings
| Field | Type | Description |
|-------|------|-------------|
| `$id` | String | Listing ID |
| `seller_id` | String | User ID |
| `character_id` | String | Character ID |
| `item_data` | Object | Full item details |
| `listing_type` | String | "auction" or "fixed_price" |
| `price` | Integer | For fixed_price |
| `starting_bid` | Integer | For auction |
| `current_bid` | Integer | For auction |
| `buyout_price` | Integer | Optional instant buy |
| `bids` | Array[Object] | Bid history |
| `auction_end` | ISO Timestamp | For auction |
| `status` | String | active, sold, expired, removed |
| `created_at` | ISO Timestamp | Listing creation |
### transactions
| Field | Type | Description |
|-------|------|-------------|
| `$id` | String | Transaction ID |
| `buyer_id` | String | User ID |
| `seller_id` | String | User ID |
| `listing_id` | String | Listing ID |
| `item_data` | Object | Item details |
| `price` | Integer | Final price |
| `timestamp` | ISO Timestamp | Transaction time |
| `transaction_type` | String | marketplace_sale, shop_purchase, etc. |
---
## Project Structure
**Repository Root:**
```
/coc
├── api/ # API Backend Component
├── public_web/ # Web Frontend Component
├── godot_client/ # Godot Game Client Component
├── docs/ # Project-wide documentation
├── CLAUDE.md # Development guidelines
└── README.md # Project overview
```
### API Backend (`/api`)
**Single source of truth - All business logic**
```
api/
├── app/
│ ├── __init__.py # Flask app factory
│ ├── config.py # Configuration management
│ ├── models/ # Data models (dataclasses)
│ │ ├── __init__.py
│ │ ├── enums.py # All enum types
│ │ ├── stats.py # Stats dataclass
│ │ ├── effects.py # Effect dataclass
│ │ ├── abilities.py # Ability dataclass
│ │ ├── items.py # Item dataclass
│ │ ├── skills.py # SkillNode, SkillTree, PlayerClass
│ │ ├── origins.py # Origin dataclass
│ │ ├── character.py # Character with get_effective_stats()
│ │ ├── combat.py # Combatant, CombatEncounter
│ │ ├── session.py # GameSession, SessionConfig
│ │ └── marketplace.py # Marketplace models
│ ├── api/ # REST API endpoints
│ │ ├── __init__.py
│ │ ├── health.py # Health check
│ │ ├── auth.py # Authentication endpoints
│ │ ├── characters.py # Character CRUD
│ │ ├── sessions.py # Session management (TODO)
│ │ ├── combat.py # Combat actions (TODO)
│ │ ├── marketplace.py # Marketplace operations (TODO)
│ │ └── shop.py # NPC shop (TODO)
│ ├── game_logic/ # Game mechanics
│ │ ├── __init__.py
│ │ ├── combat_engine.py # Combat calculations (TODO)
│ │ ├── damage_calculator.py # Damage formulas (TODO)
│ │ ├── effect_processor.py # Effect tick processing (TODO)
│ │ ├── skill_manager.py # Skill unlock logic (TODO)
│ │ └── loot_generator.py # Random loot generation (TODO)
│ ├── ai/ # AI integration
│ │ ├── __init__.py
│ │ ├── ai_client.py # Replicate + Anthropic clients (TODO)
│ │ ├── model_selector.py # Model tier selection (TODO)
│ │ ├── prompt_templates.py # Jinja2 prompt templates (TODO)
│ │ └── narrative_generator.py # AI narrative wrapper (TODO)
│ ├── tasks/ # Background jobs (RQ)
│ │ ├── __init__.py
│ │ ├── ai_tasks.py # RQ jobs for AI calls (TODO)
│ │ ├── combat_tasks.py # Async combat processing (TODO)
│ │ └── marketplace_tasks.py # Auction processing (TODO)
│ ├── services/ # Business logic & integrations
│ │ ├── __init__.py
│ │ ├── appwrite_service.py # Appwrite SDK wrapper
│ │ ├── database_service.py # Database operations
│ │ ├── database_init.py # Database initialization
│ │ ├── character_service.py # Character management
│ │ ├── class_loader.py # Load classes from YAML
│ │ └── origin_service.py # Load origins from YAML
│ ├── utils/ # Utilities
│ │ ├── __init__.py
│ │ ├── logging.py # Structlog setup
│ │ ├── response.py # Standardized API responses
│ │ └── auth.py # Auth decorators
│ └── data/ # Game data (YAML)
│ ├── abilities/ # Ability definitions
│ ├── classes/ # Character class definitions
│ ├── items/ # Item definitions (TODO)
│ └── origins.yaml # Origin definitions
├── config/ # Environment configs
│ ├── development.yaml # Dev environment settings
│ └── production.yaml # Production settings
├── tests/ # Pytest test suite
│ ├── __init__.py
│ ├── test_character.py
│ ├── test_stats.py
│ ├── test_effects.py
│ ├── test_combat_simulation.py
│ ├── test_class_loader.py
│ ├── test_origin_service.py
│ ├── test_character_service.py
│ └── test_api_characters_integration.py
├── scripts/ # Utility scripts
│ ├── init_database.py # Database initialization
│ ├── setup.sh # Project setup
│ └── README.md
├── logs/ # Application logs
│ └── app.log
├── docs/ # API documentation
│ ├── API_REFERENCE.md # API endpoint docs
│ ├── API_TESTING.md # API testing guide
│ ├── DATA_MODELS.md # Data model documentation
│ ├── GAME_SYSTEMS.md # Game mechanics docs
│ └── APPWRITE_SETUP.md # Database setup guide
├── requirements.txt # Python dependencies (full stack)
├── wsgi.py # WSGI entry point
├── docker-compose.yml # Redis service
├── .env.example # Environment variable template
└── README.md # API backend README
```
### Web Frontend (`/public_web`)
**Thin UI layer - Makes HTTP requests to API**
```
public_web/
├── app/
│ ├── __init__.py # Flask app factory
│ ├── config.py # Configuration loader
│ ├── views/ # View blueprints (Flask routes)
│ │ ├── __init__.py
│ │ ├── auth_views.py # Auth pages (login, register, etc.)
│ │ └── character_views.py # Character pages
│ ├── services/ # (Stub) API client services
│ │ ├── __init__.py # TODO: Refactor to HTTP client
│ │ ├── character_service.py # Stub (raises NotImplementedError)
│ │ ├── class_loader.py # Stub (raises NotImplementedError)
│ │ └── origin_service.py # Stub (raises NotImplementedError)
│ └── utils/ # Utilities
│ ├── __init__.py
│ ├── logging.py # Structlog setup
│ └── auth.py # Auth helpers (stubs, need refactor)
├── templates/ # Jinja2 HTML templates
│ ├── base.html # Base layout
│ ├── auth/ # Authentication pages
│ │ ├── login.html
│ │ ├── register.html
│ │ ├── forgot_password.html
│ │ ├── reset_password.html
│ │ └── verify_email.html
│ └── character/ # Character pages
│ ├── list.html # Character list
│ ├── detail.html # Character detail
│ ├── create_origin.html # Creation step 1
│ ├── create_class.html # Creation step 2
│ ├── create_customize.html # Creation step 3
│ └── create_confirm.html # Creation step 4
├── static/ # CSS, JS, images
│ └── css/
│ └── main.css # Main stylesheet
├── config/ # Web frontend configs
│ ├── development.yaml # Dev settings (API URL, etc.)
│ └── production.yaml # Production settings
├── logs/ # Application logs
├── docs/ # Frontend documentation
├── requirements.txt # Python dependencies (minimal)
├── wsgi.py # WSGI entry point
├── .env.example # Environment template
└── README.md # Web frontend README
```
**Known Technical Debt:**
- Views currently import stub services that raise `NotImplementedError`
- Need to refactor views to make HTTP requests to API backend
- Auth helpers need to validate sessions via API
- See `/public_web/README.md` for details
### Godot Client (`/godot_client`)
**Native cross-platform game client**
```
godot_client/
├── project.godot # Godot project configuration
├── scenes/ # Godot scene files (.tscn)
│ ├── main.tscn # Entry point
│ ├── auth/ # Authentication scenes
│ │ └── login.tscn
│ ├── character/ # Character scenes
│ ├── combat/ # Combat scenes
│ ├── world/ # World exploration scenes
│ └── components/ # Reusable UI components
├── scripts/ # GDScript code
│ ├── main.gd # Main scene controller
│ ├── services/ # Singleton autoloads
│ │ ├── settings.gd # Settings management
│ │ ├── http_client.gd # HTTP client for API calls
│ │ └── state_manager.gd # Global state management
│ ├── models/ # Data models
│ │ └── api_response.gd # API response wrapper
│ ├── components/ # Component scripts
│ │ ├── form_field.gd # Form input component
│ │ ├── card.gd # Card container
│ │ └── custom_button.gd # Styled button
│ └── utils/ # Helper utilities
│ └── theme_colors.gd # Color constants
├── assets/ # Game assets
│ ├── fonts/ # Cinzel + Lato fonts
│ ├── themes/ # UI theme files
│ └── ui/ # UI assets
├── docs/ # Godot client documentation
│ ├── ARCHITECTURE.md # Client architecture
│ ├── GETTING_STARTED.md # Setup guide
│ ├── EXPORT.md # Export instructions
│ └── THEME_SETUP.md # Theming guide
├── ARCHITECTURE.md # Architecture overview
├── README.md # Setup and usage
└── EXPORT.md # Platform export guide
```
---
## RQ Job Processing
### Job Types
| Queue | Job Function | Purpose |
|-------|--------------|---------|
| **ai_tasks** | `generate_dm_response()` | Generate narrative responses |
| | `generate_npc_dialogue()` | NPC conversations |
| | `narrate_combat_action()` | Combat descriptions |
| **combat_tasks** | `process_combat_round()` | Execute combat turn |
| | `finalize_combat()` | Handle combat end |
| **marketplace_tasks** | `process_ended_auctions()` | Periodic auction cleanup |
| | `cleanup_old_session_logs()` | Periodic log cleanup |
### Worker Configuration
**Start RQ workers:**
```bash
# Single worker for all queues
rq worker ai_tasks combat_tasks marketplace_tasks --url redis://localhost:6379
# Or separate workers
rq worker ai_tasks --url redis://localhost:6379
rq worker combat_tasks --url redis://localhost:6379
rq worker marketplace_tasks --url redis://localhost:6379
```
### Job Flow
1. User takes action in game
2. Action queued to RQ with job ID
3. API returns 202 Accepted with job ID
4. Worker processes job asynchronously
5. Worker updates Appwrite document
6. Appwrite Realtime notifies all clients
7. UI updates automatically
---
## Realtime Synchronization
**Use Appwrite Realtime for WebSocket connections:**
Frontend subscribes to session updates and receives automatic notifications when game state changes.
**Benefits:**
- No polling required
- Instant updates for all party members
- Built-in connection management
- Automatic reconnection
---
## Subscription Tiers
| Tier | Price | AI Calls/Day | AI Model | Marketplace | Log Retention | Max Chars | Party Size |
|------|-------|--------------|----------|-------------|---------------|-----------|------------|
| **FREE** | $0 | 50 | Replicate | ✗ | 7 days | 1 | Solo |
| **BASIC** | $4.99 | 200 | Haiku | ✗ | 14 days | 3 | 2 |
| **PREMIUM** | $9.99 | 1000 | Sonnet | ✓ | 30 days | 10 | 6 |
| **ELITE** | $19.99 | Unlimited | Sonnet | ✓+ | 90 days | Unlimited | 10 |
**ELITE Perks:**
- Priority marketplace listings
- Early access to new classes
- Exclusive items
---
## Security Architecture
### Authentication & Authorization
- Appwrite Auth handles user authentication
- HTTP-only cookies (`coc_session`) for session storage
- Prevents XSS attacks (JavaScript cannot access)
- HTTPS only in production (Secure flag)
- SameSite=Lax for CSRF protection
- 24-hour sessions (30 days with "remember me")
- Email verification required before login
- Password reset via email flow
- Auth decorators for protected routes:
- `@require_auth` - Enforce authentication
- `@require_tier(tier)` - Enforce minimum subscription tier
- `@require_email_verified` - Enforce verified email
- User tier system (Free/Basic/Premium/Elite)
- Session validation on every protected API call
- User ID verification (users can only access their own data)
### Input Validation
- Validate all JSON payloads against schemas
- Sanitize user inputs (character names, chat messages)
- Prevent injection attacks
### Rate Limiting
- AI endpoint limits based on subscription tier
- Marketplace actions (max listings per day)
- Combat actions (prevent spam/automation)
- Use Flask-Limiter with Redis backend
### API Security
- CORS properly configured (only allow frontend domain)
- API keys stored in environment variables
- Appwrite permissions set correctly on all collections
- HTTPS only in production
### Cost Control (AI)
- Daily limits on AI calls per tier
- Max tokens per request type
- Cost logging for analytics and alerts
- Graceful degradation if limits exceeded
### Data Protection
| Resource | Read Access | Write Access |
|----------|-------------|--------------|
| **Characters** | Owner only | Owner only |
| **Sessions** | Party members | Active player |
| **Marketplace** | All users | Listing owner |
| **Transactions** | Buyer + Seller | System only |
---
## Why These Technologies?
### Flask over FastAPI
- Team familiarity with Flask
- Async handled by RQ (don't need FastAPI's native async)
- Mature ecosystem for templates (Jinja2)
- Can migrate specific endpoints later if needed
### RQ over Celery
- Simpler setup and configuration
- Adequate for current scale
- Easier debugging
- Redis already required for caching
### Appwrite
- Reduces infrastructure overhead
- Built-in auth, database, storage, realtime
- Handles scaling of data layer
- Real-time WebSocket support out of box
- Self-hosted option available if needed later
### Dataclasses over ORM
- Flexibility in data structure (easy to change)
- No database migration headaches
- JSON storage in Appwrite is schema-flexible
- Easier to serialize/deserialize
- Performance (no ORM overhead)
### Turn-Based
- Simpler AI prompt construction
- Better for multiplayer coordination
- Classic D&D feel
- Easier to balance than real-time
- Less server load (no constant state updates)
### Microservices Architecture
- **Independent Deployment:** Each component can be updated/scaled separately
- **Technology Flexibility:** Can use different tech stacks per component (Flask + Godot)
- **Team Scalability:** Different teams can work on different components
- **Fault Isolation:** Failures in one component don't crash entire system
- **API as Contract:** Clear interface between frontend and backend
---
## Microservices Communication
### API-First Design
All frontends communicate with the API backend exclusively via HTTP/REST:
```
┌─────────────┐
│ Public Web │──┐
└─────────────┘ │
│ HTTP/REST
┌─────────────┐ │ (JSON)
│ Godot Client│──┼──────────► ┌──────────────┐
└─────────────┘ │ │ API Backend │
│ │ (Port 5000) │
│ └──────────────┘
Other │
Clients │
(Future) ────┘
```
### Communication Patterns
**1. Request/Response (Synchronous)**
- Standard CRUD operations
- Character creation, updates
- Authentication
- Data retrieval
**Example:**
```
POST /api/v1/characters
{
"name": "Aragorn",
"class_id": "vanguard",
"origin_id": "noble_exile"
}
→ API processes request
→ Returns character data
Response:
{
"app": "Code of Conquest",
"status": 200,
"result": { character_data },
"error": null
}
```
**2. Job Queue (Asynchronous)**
- AI narrative generation
- Combat processing
- Long-running operations
**Example:**
```
POST /api/v1/sessions/{id}/action
{
"action": "I search the ancient library"
}
→ API queues job to RQ
→ Returns job ID immediately
Response:
{
"status": 202,
"result": {
"job_id": "abc123",
"status": "queued"
}
}
→ Worker processes AI call
→ Updates Appwrite document
→ Appwrite Realtime notifies clients
```
**3. Real-Time (WebSocket via Appwrite)**
- Multiplayer session updates
- Combat state changes
- Party member actions
**Example:**
```javascript
// Subscribe to session updates
appwrite.subscribe('sessions.{sessionId}', callback);
// When another player acts:
Worker updates session in Appwrite
Appwrite broadcasts to all subscribers
All clients update UI automatically
```
### API Endpoints Structure
```
/api/v1/
├── health # Health check
├── auth/ # Authentication
│ ├── login
│ ├── register
│ ├── logout
│ └── reset-password
├── characters/ # Character management
│ ├── GET / # List characters
│ ├── POST / # Create character
│ ├── GET /{id} # Get character
│ ├── PUT /{id} # Update character
│ └── DELETE /{id} # Delete character
├── sessions/ # Game sessions (TODO)
│ ├── POST / # Create session
│ ├── GET /{id} # Get session
│ └── POST /{id}/action # Take action
├── combat/ # Combat system (TODO)
│ └── POST /sessions/{id}/combat/action
├── marketplace/ # Marketplace (TODO)
│ ├── GET /listings
│ └── POST /listings
└── shop/ # NPC shop (TODO)
└── GET /items
```
### Frontend Responsibilities
**API Backend (`/api`):**
- ✅ All business logic
- ✅ Data validation
- ✅ Database operations
- ✅ Authentication & authorization
- ✅ Game mechanics calculations
- ✅ AI orchestration
**Web Frontend (`/public_web`):**
- ❌ No business logic
- ✅ Render HTML templates
- ✅ Form validation (UI only)
- ✅ Make HTTP requests to API
- ✅ Display API responses
- ⚠️ **Current:** Has stub services (needs refactoring)
**Godot Client (`/godot_client`):**
- ❌ No business logic
- ✅ Render game UI
- ✅ Handle user input
- ✅ Make HTTP requests to API
- ✅ Display API responses
- ✅ Client-side animations/effects
---
## Deployment Architecture
### Development Environment
```
┌────────────────────┐
│ Developer Machine │
├────────────────────┤
│ │
│ API Backend │ ← Port 5000
│ (Flask dev server)│
│ │
│ Web Frontend │ ← Port 5001
│ (Flask dev server)│
│ │
│ Godot Editor │ ← F5 to test
│ │
│ Redis (Docker) │ ← Port 6379
│ │
└────────────────────┘
│ API calls
┌──────────────┐
│ Appwrite │
│ (Cloud) │
└──────────────┘
```
**Commands:**
```bash
# Terminal 1: API Backend
cd api
source venv/bin/activate
python wsgi.py # → http://localhost:5000
# Terminal 2: Web Frontend
cd public_web
source venv/bin/activate
python wsgi.py # → http://localhost:5001
# Terminal 3: Redis
cd api
docker-compose up
# Terminal 4: RQ Worker (optional)
cd api
source venv/bin/activate
rq worker ai_tasks --url redis://localhost:6379
# Godot: Open project and press F5
```
### Production Environment
```
┌──────────────────────────────────────┐
│ Load Balancer / CDN │
└────────────┬─────────────────────────┘
┌──────┴──────┐
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ Web │ │ Web │ ← Port 8080 (internal)
│ Frontend │ │ Frontend │
│(Gunicorn)│ │(Gunicorn)│
└────┬─────┘ └────┬─────┘
│ │
│ HTTP Requests
└──────┬──────┘
┌──────────┐
│ API │ ← Port 5000 (internal)
│ Backend │
│(Gunicorn)│
└────┬─────┘
┌────┴────┬──────────┬──────────┐
▼ ▼ ▼ ▼
┌──────────┐ ┌─────┐ ┌────────┐ ┌────────┐
│ Appwrite │ │Redis│ │ RQ │ │ AI │
│ │ │ │ │Workers │ │ APIs │
└──────────┘ └─────┘ └────────┘ └────────┘
```
**Deployment Strategy:**
- Each component containerized with Docker
- Independent scaling (more web servers if needed)
- API backend as single deployment (multiple workers via Gunicorn)
- Godot client exported to native apps (distributed separately)
### Environment Variables
**API Backend:**
```
FLASK_ENV=production
APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
APPWRITE_PROJECT_ID=...
APPWRITE_API_KEY=...
APPWRITE_DATABASE_ID=...
ANTHROPIC_API_KEY=...
REPLICATE_API_TOKEN=...
REDIS_URL=redis://redis:6379
SECRET_KEY=...
```
**Web Frontend:**
```
FLASK_ENV=production
SECRET_KEY=...
API_BASE_URL=https://api.codeofconquest.com
```
**Godot Client:**
```gdscript
# In settings.gd or environment config
var api_base_url = "https://api.codeofconquest.com"
```

580
docs/DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,580 @@
# Deployment & Operations
## Local Development Setup
### Prerequisites
| Tool | Version | Purpose |
|------|---------|---------|
| Python | 3.11+ | Backend runtime |
| Docker | Latest | Local services |
| Redis | 7.0+ | Job queue & caching |
| Git | Latest | Version control |
### Setup Steps
```bash
# 1. Clone repository
git clone <repo-url>
cd code_of_conquest
# 2. Create virtual environment
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Configure environment
cp .env.example .env
# Edit .env with your API keys and settings
# 5. Start local services
docker-compose up -d
# 6. Start RQ workers
rq worker ai_tasks combat_tasks marketplace_tasks &
# 7. Run Flask development server
flask run --debug
```
### Environment Variables
| Variable | Description | Required |
|----------|-------------|----------|
| `FLASK_ENV` | development/production | Yes |
| `SECRET_KEY` | Flask secret key | Yes |
| `REPLICATE_API_KEY` | Replicate API key | Yes |
| `ANTHROPIC_API_KEY` | Anthropic API key | Yes |
| `APPWRITE_ENDPOINT` | Appwrite server URL | Yes |
| `APPWRITE_PROJECT_ID` | Appwrite project ID | Yes |
| `APPWRITE_API_KEY` | Appwrite API key | Yes |
| `REDIS_URL` | Redis connection URL | Yes |
| `LOG_LEVEL` | Logging level (DEBUG/INFO/WARNING/ERROR) | No |
---
## Docker Compose (Local Development)
**docker-compose.yml:**
```yaml
version: '3.8'
services:
redis:
image: redis:alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
rq-worker:
build: .
command: rq worker ai_tasks combat_tasks marketplace_tasks --url redis://redis:6379
depends_on:
- redis
env_file:
- .env
environment:
- REDIS_URL=redis://redis:6379
volumes:
redis_data:
```
---
## Testing Strategy
### Manual Testing (Preferred)
**API Testing Document:** `docs/API_TESTING.md`
Contains:
- Endpoint examples
- Sample curl/httpie commands
- Expected responses
- Authentication setup
**Example API Test:**
```bash
# Login
curl -X POST http://localhost:5000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "password": "password123"}'
# Create character (with auth token)
curl -X POST http://localhost:5000/api/v1/characters \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{"name": "Aragorn", "class_id": "vanguard"}'
```
### Unit Tests (Optional)
**Framework:** pytest
**Test Categories:**
| Category | Location | Focus |
|----------|----------|-------|
| Combat | `tests/test_combat.py` | Damage calculations, effect processing |
| Skills | `tests/test_skills.py` | Skill unlock logic, prerequisites |
| Marketplace | `tests/test_marketplace.py` | Bidding logic, auction processing |
| Character | `tests/test_character.py` | Character creation, stats |
**Run Tests:**
```bash
# All tests
pytest
# Specific test file
pytest tests/test_combat.py
# With coverage
pytest --cov=app tests/
```
### Load Testing
**Tool:** Locust or Apache Bench
**Test Scenarios:**
| Scenario | Target | Success Criteria |
|----------|--------|------------------|
| Concurrent AI requests | 50 concurrent users | < 5s response time |
| Marketplace browsing | 100 concurrent users | < 1s response time |
| Session realtime updates | 10 players per session | < 100ms update latency |
---
## Production Deployment
### Deployment Checklist
**Pre-Deployment:**
- [ ] All environment variables configured
- [ ] Appwrite collections created with proper permissions
- [ ] Redis configured and accessible
- [ ] RQ workers running
- [ ] SSL certificates installed
- [ ] Rate limiting configured
- [ ] Error logging/monitoring set up (Sentry recommended)
- [ ] Backup strategy for Appwrite data
**Production Configuration:**
- [ ] `DEBUG = False` in Flask
- [ ] Secure session keys (random, long)
- [ ] CORS restricted to production domain
- [ ] Rate limits appropriate for production
- [ ] AI cost alerts configured
- [ ] CDN for static assets (optional)
### Dockerfile
```dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application
COPY . .
# Create non-root user
RUN useradd -m appuser && chown -R appuser:appuser /app
USER appuser
# Expose port
EXPOSE 5000
# Run application
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "4", "wsgi:app"]
```
### Build & Push Script
**scripts/build_and_push.sh:**
```bash
#!/bin/bash
# Get current git branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Ask for tag options
read -p "Tag as :latest? (y/n) " TAG_LATEST
read -p "Push to registry? (y/n) " PUSH_IMAGE
# Build image
docker build -t ai-dungeon-master:$BRANCH .
if [ "$TAG_LATEST" = "y" ]; then
docker tag ai-dungeon-master:$BRANCH ai-dungeon-master:latest
fi
if [ "$PUSH_IMAGE" = "y" ]; then
docker push ai-dungeon-master:$BRANCH
if [ "$TAG_LATEST" = "y" ]; then
docker push ai-dungeon-master:latest
fi
fi
```
### Production Environment
**Recommended Stack:**
- **Web Server:** Nginx (reverse proxy)
- **WSGI Server:** Gunicorn (4+ workers)
- **Process Manager:** Supervisor or systemd
- **Redis:** Standalone or Redis Cluster
- **RQ Workers:** Separate instances for each queue
**Scaling Strategy:**
| Component | Scaling Method | Trigger |
|-----------|----------------|---------|
| Flask API | Horizontal (add workers) | CPU > 70% |
| RQ Workers | Horizontal (add workers) | Queue length > 100 |
| Redis | Vertical (upgrade instance) | Memory > 80% |
| Appwrite | Managed by Appwrite | N/A |
---
## Monitoring & Logging
### Application Logging
**Logging Configuration:**
| Level | Use Case | Examples |
|-------|----------|----------|
| DEBUG | Development only | Variable values, function calls |
| INFO | Normal operations | User actions, API calls |
| WARNING | Potential issues | Rate limit approaching, slow queries |
| ERROR | Errors (recoverable) | Failed AI calls, validation errors |
| CRITICAL | Critical failures | Database connection lost, service down |
**Structured Logging with Structlog:**
```python
import structlog
logger = structlog.get_logger(__name__)
logger.info("Combat action executed",
session_id=session_id,
character_id=character_id,
action_type="attack",
damage=15
)
```
### Monitoring Tools
**Recommended Tools:**
| Tool | Purpose | Priority |
|------|---------|----------|
| **Sentry** | Error tracking and alerting | High |
| **Prometheus** | Metrics collection | Medium |
| **Grafana** | Metrics visualization | Medium |
| **Uptime Robot** | Uptime monitoring | High |
| **CloudWatch** | AWS logs/metrics (if using AWS) | Medium |
### Key Metrics to Monitor
| Metric | Alert Threshold | Action |
|--------|----------------|--------|
| API response time | > 3s average | Scale workers |
| Error rate | > 5% | Investigate logs |
| AI API errors | > 10% | Check API status |
| Queue length | > 500 | Add workers |
| Redis memory | > 80% | Upgrade instance |
| CPU usage | > 80% | Scale horizontally |
| AI cost per day | > budget × 1.2 | Investigate usage |
### AI Cost Tracking
**Log Structure:**
| Field | Type | Purpose |
|-------|------|---------|
| `user_id` | str | Track per-user usage |
| `model` | str | Which model used |
| `tier` | str | FREE/STANDARD/PREMIUM |
| `tokens_used` | int | Token count |
| `cost_estimate` | float | Estimated cost |
| `timestamp` | datetime | When called |
| `context_type` | str | What prompted the call |
**Daily Report:**
- Total AI calls per tier
- Total tokens used
- Estimated cost
- Top users by usage
- Anomaly detection (unusual spikes)
---
## Security
### Authentication & Authorization
**Implementation:**
| Layer | Method | Details |
|-------|--------|---------|
| **User Auth** | Appwrite Auth | Email/password, OAuth providers |
| **API Auth** | JWT tokens | Bearer token in Authorization header |
| **Session Validation** | Every API call | Verify token, check expiry |
| **Resource Access** | User ID check | Users can only access their own data |
### Input Validation
**Validation Strategy:**
| Input Type | Validation | Tools |
|------------|------------|-------|
| JSON payloads | Schema validation | Marshmallow or Pydantic |
| Character names | Sanitize, length limits | Bleach library |
| Chat messages | Sanitize, profanity filter | Custom validators |
| AI prompts | Template-based only | Jinja2 (no direct user input) |
**Example Validation:**
| Field | Rules |
|-------|-------|
| Character name | 3-20 chars, alphanumeric + spaces only |
| Gold amount | Positive integer, max 999,999,999 |
| Action text | Max 500 chars, sanitized HTML |
### Rate Limiting
**Implementation:** Flask-Limiter with Redis backend
**Limits by Tier:**
| Tier | API Calls/Min | AI Calls/Day | Marketplace Actions/Day |
|------|---------------|--------------|------------------------|
| FREE | 30 | 50 | N/A |
| BASIC | 60 | 200 | N/A |
| PREMIUM | 120 | 1000 | 50 |
| ELITE | 300 | Unlimited | 100 |
**Rate Limit Bypass:**
- Admin accounts
- Health check endpoints
- Static assets
### API Security
**Configuration:**
| Setting | Value | Reason |
|---------|-------|--------|
| **CORS** | Production domain only | Prevent unauthorized access |
| **HTTPS** | Required | Encrypt data in transit |
| **API Keys** | Environment variables | Never in code |
| **Appwrite Permissions** | Least privilege | Collection-level security |
| **SQL Injection** | N/A | Using Appwrite (NoSQL) |
| **XSS** | Sanitize all inputs | Prevent script injection |
| **CSRF** | CSRF tokens | For form submissions |
### Data Protection
**Access Control Matrix:**
| Resource | Owner | Party Member | Public | System |
|----------|-------|--------------|--------|--------|
| Characters | RW | R | - | RW |
| Sessions | R | RW (turn) | - | RW |
| Marketplace Listings | RW (own) | - | R | RW |
| Transactions | R (own) | - | - | RW |
**RW = Read/Write, R = Read only, - = No access**
### Secrets Management
**Never Commit:**
- API keys
- Database credentials
- Secret keys
- Tokens
**Best Practices:**
- Use `.env` for local development
- Use environment variables in production
- Use secrets manager (AWS Secrets Manager, HashiCorp Vault) in production
- Rotate keys regularly
- Different keys for dev/staging/prod
---
## Backup & Recovery
### Appwrite Data Backup
**Strategy:**
| Data Type | Backup Frequency | Retention | Method |
|-----------|------------------|-----------|--------|
| Characters | Daily | 30 days | Appwrite export |
| Sessions (active) | Hourly | 7 days | Appwrite export |
| Marketplace | Daily | 30 days | Appwrite export |
| Transactions | Daily | 90 days | Appwrite export |
**Backup Script:**
- Export collections to JSON
- Compress and encrypt
- Upload to S3 or object storage
- Verify backup integrity
### Disaster Recovery Plan
| Scenario | RTO | RPO | Steps |
|----------|-----|-----|-------|
| **Database corruption** | 4 hours | 24 hours | Restore from latest backup |
| **API server down** | 15 minutes | 0 | Restart/failover to standby |
| **Redis failure** | 5 minutes | Session data loss | Restart, users re-login |
| **Complete infrastructure loss** | 24 hours | 24 hours | Restore from backups to new infrastructure |
**RTO = Recovery Time Objective, RPO = Recovery Point Objective**
---
## CI/CD Pipeline
### Recommended Workflow
| Stage | Actions | Tools |
|-------|---------|-------|
| **1. Commit** | Developer pushes to `dev` branch | Git |
| **2. Build** | Run tests, lint code | GitHub Actions, pytest, flake8 |
| **3. Test** | Unit tests, integration tests | pytest |
| **4. Build Image** | Create Docker image | Docker |
| **5. Deploy to Staging** | Deploy to staging environment | Docker, SSH |
| **6. Manual Test** | QA testing on staging | Manual |
| **7. Merge to Beta** | Promote to beta branch | Git |
| **8. Deploy to Beta** | Deploy to beta environment | Docker, SSH |
| **9. Merge to Master** | Production promotion | Git |
| **10. Deploy to Prod** | Deploy to production | Docker, SSH |
| **11. Tag Release** | Create version tag | Git |
### GitHub Actions Example
```yaml
name: CI/CD
on:
push:
branches: [ dev, beta, master ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.11
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
run: pytest
- name: Lint
run: flake8 app/
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build Docker image
run: docker build -t ai-dungeon-master:${{ github.ref_name }} .
- name: Push to registry
run: docker push ai-dungeon-master:${{ github.ref_name }}
```
---
## Performance Optimization
### Caching Strategy
| Cache Type | What to Cache | TTL |
|------------|---------------|-----|
| **Redis Cache** | Session data | 30 minutes |
| | Character data (read-heavy) | 5 minutes |
| | Marketplace listings | 1 minute |
| | NPC shop items | 1 hour |
| **Browser Cache** | Static assets | 1 year |
| | API responses (GET) | 30 seconds |
### Database Optimization
**Appwrite Indexing:**
- Index `userId` on characters collection
- Index `status` on game_sessions collection
- Index `listing_type` + `status` on marketplace_listings
- Index `created_at` for time-based queries
### AI Call Optimization
**Strategies:**
| Strategy | Impact | Implementation |
|----------|--------|----------------|
| **Batch requests** | Reduce API calls | Combine multiple actions |
| **Cache common responses** | Reduce cost | Cache item descriptions |
| **Prompt optimization** | Reduce tokens | Shorter, more efficient prompts |
| **Model selection** | Reduce cost | Use cheaper models when appropriate |
---
## Troubleshooting
### Common Issues
| Issue | Symptoms | Solution |
|-------|----------|----------|
| **RQ workers not processing** | Jobs stuck in queue | Check Redis connection, restart workers |
| **AI calls failing** | 401/403 errors | Verify API keys, check rate limits |
| **Appwrite connection errors** | Database errors | Check Appwrite status, verify credentials |
| **Session not updating** | Stale data in UI | Check Appwrite Realtime connection |
| **High latency** | Slow API responses | Check RQ queue length, scale workers |
### Debug Mode
**Enable Debug Logging:**
```bash
export LOG_LEVEL=DEBUG
flask run --debug
```
**Debug Endpoints (development only):**
- `GET /debug/health` - Health check
- `GET /debug/redis` - Redis connection status
- `GET /debug/queues` - RQ queue status
---
## Resources
| Resource | URL |
|----------|-----|
| **Appwrite Docs** | https://appwrite.io/docs |
| **RQ Docs** | https://python-rq.org/ |
| **Flask Docs** | https://flask.palletsprojects.com/ |
| **Structlog Docs** | https://www.structlog.org/ |
| **HTMX Docs** | https://htmx.org/docs/ |
| **Anthropic API** | https://docs.anthropic.com/ |
| **Replicate API** | https://replicate.com/docs |

272
docs/PLAYSCREEN.md Normal file
View File

@@ -0,0 +1,272 @@
# Production Play Screen Implementation Plan
## Overview
Create a new production play screen at `templates/game/play.html` with a 3-column layout optimized for immersive gameplay, separate from the dev console.
## Layout Structure
```
+-------------+------------------------+------------------+
| LEFT | MIDDLE | RIGHT |
| (280px) | (1fr flex) | (320px) |
+-------------+------------------------+------------------+
| Character | Location Header | [History] |
| - Name/Lv | - Name, Type, Turn # | [Quests] |
| - HP/MP | Ambient Details | [NPCs] |
| - Stats | ---------------- | [Map] |
| ---------- | DM Response Area | |
| Actions | (main narrative) | Each accordion |
| [Free] | | independently |
| [Premium] | | refreshable |
| [Elite] | | |
| ---------- | | |
| [Talk NPC] | | |
| [Travel] | | |
+-------------+------------------------+------------------+
```
## Files to Create
### Templates
| File | Purpose |
|------|---------|
| `templates/game/play.html` | Main 3-column layout |
| `templates/game/partials/character_panel.html` | Left: actions + character stats |
| `templates/game/partials/narrative_panel.html` | Middle: DM response + location |
| `templates/game/partials/sidebar_history.html` | Right accordion: turn history |
| `templates/game/partials/sidebar_quests.html` | Right accordion: active quests |
| `templates/game/partials/sidebar_npcs.html` | Right accordion: NPCs at location |
| `templates/game/partials/sidebar_map.html` | Right accordion: discovered locations |
| `templates/game/partials/job_polling.html` | Job status polling partial |
| `templates/game/partials/travel_modal.html` | Travel destination modal |
| `templates/game/partials/npc_chat_modal.html` | NPC dialogue modal |
### CSS
| File | Purpose |
|------|---------|
| `static/css/play.css` | All play screen styles |
### Flask Views
| File | Purpose |
|------|---------|
| `app/views/game_views.py` | New blueprint for production game routes |
### Modify
| File | Change |
|------|--------|
| `app/__init__.py` | Register `game_bp` blueprint |
## Flask Routes
```python
# Main routes
GET /play/session/<session_id> # Main play screen
GET /play/session/<id>/character-panel # Refresh character stats
GET /play/session/<id>/narrative # Refresh narrative
GET /play/session/<id>/history # Refresh history accordion
GET /play/session/<id>/quests # Refresh quests accordion
GET /play/session/<id>/npcs # Refresh NPCs accordion
GET /play/session/<id>/map # Refresh map accordion
# Action routes
POST /play/session/<id>/action # Submit action -> job polling
GET /play/session/<id>/job/<job_id> # Poll job status
# Modal routes
GET /play/session/<id>/travel-modal # Get travel modal
POST /play/session/<id>/travel # Execute travel
GET /play/session/<id>/npc/<npc_id>/chat # Get NPC chat modal
POST /play/session/<id>/npc/<npc_id>/talk # Send message to NPC
```
## CSS Theme
```css
/* Dark fantasy theme matching existing */
--play-bg-primary: #1a1a2a;
--play-bg-secondary: #2a2a3a;
--play-border: #4a4a5a;
/* Action tiers */
--action-free: #3b82f6; /* Blue */
--action-premium: #8b5cf6; /* Purple */
--action-elite: #f59e0b; /* Gold */
/* Resource bars */
--hp-bar-fill: #ef4444;
--mp-bar-fill: #3b82f6;
```
## Action Button Organization
**Free Tier (Blue):**
1. Ask Locals for Information (town/tavern)
2. Explore the Area (wilderness/dungeon)
3. Search for Supplies (any) - 2 turn cooldown
4. Rest and Recover (town/tavern/safe) - 3 turn cooldown
**Premium Tier (Purple):**
5. Investigate Suspicious Activity (any)
6. Follow a Lead (any)
7. Make Camp (wilderness) - 5 turn cooldown
**Elite Tier (Gold):**
8. Consult Ancient Texts (library/town) - 3 turn cooldown
9. Commune with Nature (wilderness) - 4 turn cooldown
10. Seek Audience with Authorities (town) - 5 turn cooldown
## HTMX Patterns
### Action Submission
```html
<button hx-post="/play/session/{id}/action"
hx-vals='{"action_type":"button","prompt_id":"ask_locals"}'
hx-target="#narrative-content"
hx-indicator="#loading"
hx-disabled-elt="this">
```
### Job Polling (1s interval)
```html
<div hx-get="/play/session/{id}/job/{job_id}"
hx-trigger="load delay:1s"
hx-swap="innerHTML">
```
### Cascade Refresh (after action completes)
```html
<!-- Hidden triggers in dm_response.html -->
<div hx-get="/play/session/{id}/history" hx-target="#accordion-history" hx-trigger="load" hidden></div>
<div hx-get="/play/session/{id}/npcs" hx-target="#accordion-npcs" hx-trigger="load" hidden></div>
```
## Responsive Design
- **Desktop (>1024px):** 3-column grid
- **Tablet (768-1024px):** 2-column, left sidebar as slide-out drawer
- **Mobile (<768px):** Single column, right sidebar as bottom sheet
## Implementation Approach: Visual First
Build complete UI with mock/sample data first, then wire up real API calls. This allows rapid iteration on layout and styling before integrating backend.
### Phase 1: Complete Visual Layout with Mock Data
1. Create `game_views.py` with main route using hardcoded mock data
2. Create `play.html` base template with 3-column grid
3. Create `play.css` with all styles (theme, grid, components)
4. Register blueprint
5. Build all visual components with sample content:
- Left: Character panel with mock stats/actions
- Middle: Narrative panel with sample DM text
- Right: All 4 accordions with mock entries
### Phase 2: Interactive Components (No API)
1. Accordion toggle functionality (JavaScript)
2. Modal open/close (travel + NPC chat)
3. Action button states (hover, disabled, loading simulation)
4. Collapsible ambient details
5. Responsive breakpoints
### Phase 3: Wire Up API Integration ✅ COMPLETE (Nov 24, 2025)
1. ✅ Replace mock data with real API calls in Flask view
2. ✅ Implement job polling for actions
3. ✅ Wire up travel modal to `/api/v1/travel`
4. ✅ Wire up NPC chat to `/api/v1/npcs/{id}/talk`
5. ✅ Add HTMX refresh triggers for accordions
6. ✅ Wire up equipment modal with real character data
### Phase 4: Polish
- Error handling states
- Loading indicators
- Empty state messages
- Accessibility (ARIA labels, keyboard nav)
## Critical Reference Files
1. `public_web/templates/dev/story_session.html` - HTMX patterns, job polling
2. `public_web/app/views/dev.py` - Flask view patterns, API client usage
3. `public_web/static/css/main.css` - Theme variables, base styles
4. `api/app/data/action_prompts.yaml` - All 10 action definitions
5. `api/app/api/sessions.py` - Session API response formats
## API Endpoints Used
All endpoints already exist:
- `GET /api/v1/sessions/{id}` - Session state (updated to include `character_id`)
- `POST /api/v1/sessions/{id}/action` - Submit action
- `GET /api/v1/sessions/{id}/history` - Conversation history
- `GET /api/v1/jobs/{id}/status` - Poll job status
- `GET /api/v1/characters/{id}` - Character data
- `GET /api/v1/npcs/at-location/{id}` - NPCs at location
- `POST /api/v1/npcs/{id}/talk` - Talk to NPC
- `GET /api/v1/travel/available` - Available destinations
- `POST /api/v1/travel` - Travel to location
---
## Implementation Notes (Phase 3)
### Session Creation from Characters Page
Added the ability for players to create game sessions directly from `/characters`:
**Files Modified:**
- `public_web/app/views/character_views.py`
- Updated `list_characters()` to fetch user sessions via `GET /api/v1/sessions` and map them to characters
- Added new route `POST /characters/<character_id>/play` (`create_session`) that creates a session and redirects to play screen
- `public_web/templates/character/list.html`
- Added sessions section showing active sessions per character (up to 3 displayed)
- Added "Continue Playing" button (resumes latest session)
- Added "New Session" button (creates new session)
- Added "Start Adventure" button for characters without sessions
- Added CSS for session badges (turn number, status indicator)
### Play Screen API Integration
**Files Modified:**
- `public_web/app/views/game_views.py`
- Removed all mock data constants
- Added helper functions:
- `_get_user_tier(client)` - Gets user subscription tier
- `_build_location_from_game_state(game_state)` - Builds location dict from session
- `_build_character_from_api(char_data)` - Transforms API character response with robust defaults
- Updated all routes to use real API calls:
- `play_session` - Main play screen
- `character_panel` - Character stats refresh
- `narrative_panel` - Narrative content refresh
- `history_accordion`, `quests_accordion`, `npcs_accordion`, `map_accordion` - Sidebar refreshes
- `take_action` - Submit actions to API, return job polling partial
- `poll_job` - Poll job status, handle NPC dialogue vs story responses
- `equipment_modal`, `travel_modal`, `npc_chat_modal` - Modal data loading
- `do_travel`, `talk_to_npc` - Execute travel and NPC dialogue
**New Template:**
- `public_web/templates/game/partials/npc_dialogue_response.html` - Displays NPC dialogue from job polling results
### API Changes
**Files Modified:**
- `api/app/api/sessions.py`
- Updated `get_session_state()` to include `character_id` and `status` in response
- This was required because the play screen needs to know which character to load
### CSS Fixes
**Files Modified:**
- `public_web/static/css/play.css`
- Increased `max-width` from 1800px to 2400px for wider screens
- Changed middle column from `1fr` to `minmax(500px, 1fr)` to ensure minimum width
- Fixed NPC tags overflow:
- Added `flex-wrap: wrap` to `.npc-tags`
- Added `overflow: hidden` and `max-height: 3.5em`
- Added `white-space: nowrap` to `.npc-tag`
### Bug Fixes
1. **Character data showing "Unknown"** - Fixed `_build_character_from_api()` to always return complete dict with sensible defaults even when API data is empty or incomplete
2. **API not returning character_id** - Updated `api/app/api/sessions.py` to include `character_id` in session state response
3. **NPC tags overflow** - Fixed CSS to wrap tags and hide overflow

633
docs/ROADMAP.md Normal file
View File

@@ -0,0 +1,633 @@
# Code of Conquest - Implementation Roadmap
**Project:** Code of Conquest (AI Dungeon Master)
**Last Updated:** November 15, 2025
**Status:** Active Development
---
## Development Philosophy
**Workflow:** Brainstorm → Design → Code → Revise
**Principles:**
- Build incrementally (MVP first, then expand)
- Test each phase before moving forward
- Security and cost control from day one
- Manual testing preferred for most features
- Focus on core gameplay before polish
---
## Phase 0: Foundation (Week 1-2) ✅ COMPLETE
**Goal:** Set up development environment and project structure
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Initialize git repository | High | ✅ | Set up dev/beta/master branches |
| Create project structure | High | ✅ | `/app`, `/config`, `/tests`, `/static`, `/templates` |
| Set up virtual environment | High | ✅ | `python3 -m venv venv` |
| Create requirements.txt | High | ✅ | Pin version ranges for all dependencies |
| Configure .env and .env.example | High | ✅ | API keys, secrets, config |
| Set up Docker Compose (local) | High | ✅ | Redis container |
| Configure Appwrite project | High | ✅ | Create project, get credentials |
| Set up Appwrite collections | High | ✅ | users, characters, game_sessions, marketplace_listings, transactions |
| Configure logging (structlog) | Medium | ✅ | Centralized logging setup |
| Create config loader | Medium | ✅ | YAML config + typed dataclass |
| Write API response wrapper | Medium | ✅ | Standardized JSON response format |
| Set up Flask app factory | High | ✅ | `app/__init__.py` |
**Deliverable:** Fully configured development environment, ready for coding
---
## Phase 1: Core Data Models (Week 3) ✅ COMPLETE
**Goal:** Implement all core dataclasses and serialization
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Implement Stats dataclass | High | ✅ | Include computed properties (HP, MP) |
| Implement Item dataclass | High | ✅ | All item types |
| Implement Effect dataclass | High | ✅ | BUFF, DEBUFF, DOT, HOT, STUN, SHIELD |
| Implement SkillNode dataclass | High | ✅ | With prerequisite checking |
| Implement SkillTree dataclass | High | ✅ | With can_unlock() method |
| Implement PlayerClass dataclass | High | ✅ | Base stats + skill trees |
| Implement Character dataclass | High | ✅ | to_json(), from_json(), get_effective_stats() |
| Implement Combatant dataclass | High | ✅ | For combat encounters |
| Implement CombatEncounter dataclass | High | ✅ | Combat state management |
| Implement SessionConfig dataclass | High | ✅ | Session settings |
| Implement GameSession dataclass | High | ✅ | Full session state |
| Implement MarketplaceListing dataclass | Medium | ✅ | Auction + fixed price |
| Write unit tests for dataclasses | High | ✅ | 68 tests passing, >80% coverage |
**Deliverable:** ✅ Complete data model layer with tests - All 68 tests passing!
### Phase 1 Implementation Summary
**What Was Built:**
- **10 data model files** in `/app/models/`:
- `enums.py` - 9 enum types for type safety
- `stats.py` - Stats with computed properties (HP, MP, defense, resistance)
- `effects.py` - 6 effect types (BUFF, DEBUFF, DOT, HOT, STUN, SHIELD) with stacking
- `abilities.py` - Ability system with YAML loader (data-driven design)
- `items.py` - Items (weapons, armor, consumables, quest items)
- `skills.py` - SkillNode, SkillTree, PlayerClass
- `character.py` - Character with **get_effective_stats()** (single source of truth)
- `combat.py` - Combatant, CombatEncounter with turn-based flow
- `session.py` - GameSession, SessionConfig, GameState, ConversationEntry
- `marketplace.py` - MarketplaceListing, Bid, Transaction, ShopItem
**Test Coverage:**
- 68 tests across 4 test files, all passing
- `test_stats.py` - 12 tests for Stats dataclass
- `test_effects.py` - 17 tests for all effect types
- `test_character.py` - 20 tests including get_effective_stats()
- `test_combat_simulation.py` - 19 tests including full combat flow
**Key Design Decisions Made:**
| Decision | Rationale |
|----------|-----------|
| **Abilities from YAML** | Data-driven design for easy balancing without code changes |
| **Effect stacking capped at max_stacks** | Prevents infinite stacking abuse (default 5, configurable) |
| **Duration refreshes on re-application** | Simpler than cumulative duration, more predictable |
| **Shield damage absorption** | Fully implemented with partial/complete absorption logic |
| **Critical hits only** | No damage variance = deterministic damage except crits (JRPG-style) |
| **Stat minimum clamped at 1** | Debuffs can't reduce stats below 1 (prevents zero/negative stats) |
| **Single source of truth** | Character.get_effective_stats() combines all modifiers (base + equip + skills + effects) |
**Combat System Features:**
- Deterministic damage calculation with stat scaling
- 6 effect types with tick() processing
- Shield absorption before HP damage
- Effect stacking with configurable caps
- Turn-based initiative system
- Mana costs and ability cooldowns
- Full combat simulation tested
**Data Serialization:**
- All models have to_dict() / from_dict() methods
- Enums serialize to .value strings
- JSON-compatible for Appwrite storage
- Round-trip serialization tested
**Documentation Updated:**
- DATA_MODELS.md - Added Ability, AbilityLoader, Enums, expanded Effect/Character
- GAME_SYSTEMS.md - Added Ability System section, clarified effect stacking, shields, crits
- ARCHITECTURE.md - Updated models directory structure
---
## Phase 2: Authentication & User Management (Week 4) ✅ COMPLETE
**Goal:** Implement user authentication via Appwrite
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Set up Appwrite service wrapper | High | ✅ | `app/services/appwrite_service.py` |
| Implement login endpoint | High | ✅ | `POST /api/v1/auth/login` |
| Implement register endpoint | High | ✅ | `POST /api/v1/auth/register` |
| Implement logout endpoint | High | ✅ | `POST /api/v1/auth/logout` |
| Implement email verification | High | ✅ | `GET /api/v1/auth/verify-email` |
| Implement password reset | High | ✅ | `POST /api/v1/auth/forgot-password`, `POST /api/v1/auth/reset-password` |
| Create JWT token middleware | High | ✅ | Verify tokens on protected routes |
| Implement user tier/subscription check | High | ✅ | Free/Basic/Premium/Elite |
| Create auth decorators | High | ✅ | @require_auth, @require_tier(), @require_email_verified |
| Write auth tests | Medium | ✅ | Manual API testing with docs/API_TESTING.md |
| Create login page template | Medium | ✅ | `templates/auth/login.html` with HTMX |
| Create register page template | Medium | ✅ | `templates/auth/register.html` with password strength |
| Create password reset templates | Medium | ✅ | `templates/auth/forgot_password.html`, `reset_password.html` |
| Create base template | Medium | ✅ | `templates/base.html` with RPG/fantasy theme |
| Create main stylesheet | Medium | ✅ | `static/css/main.css` with approved dark slate theme |
**Deliverable:** ✅ Complete authentication system with email verification, password reset, and RPG-themed UI
---
## Phase 3: Character System (Week 5-6) ✅ COMPLETE
**Goal:** Character creation, management, and skill system
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Define all 8 player classes | High | ✅ | Using reference data from data files |
| Design skill trees (2 per class) | High | ✅ | Loaded from YAML data files |
| Implement character CRUD API | High | ✅ | 7 endpoints: create, get, list, delete, unlock skill, respec |
| Implement classes/origins API | High | ✅ | 3 endpoints: list classes, get class, list origins |
| Implement skill unlock endpoint | High | ✅ | `POST /api/v1/characters/<id>/skills/unlock` |
| Implement skill respec endpoint | Medium | ✅ | `POST /api/v1/characters/<id>/skills/respec` |
| Implement effective stats calculation | High | ✅ | In Character dataclass from Phase 1 |
| Write character system tests | Medium | ✅ | 18 integration tests in test_api_characters_integration.py |
| Create API testing doc | Medium | ✅ | `docs/API_TESTING.md` with character endpoints |
| Create character creation UI | High | ✅ | 4-step flow: origin → class → customize → confirm |
| Create character list UI | High | ✅ | Show all user's characters with tier limits |
| Create character detail UI | High | ✅ | Stats, inventory, equipment display |
**Deliverable:** ✅ Full character creation and management system (API + UI complete)
**Progress:** 12/12 tasks complete (100%)
**Note:** Skill tree visualization UI moved to Phase 5 (Combat System) where it will be implemented alongside combat abilities.
---
## Phase 4: AI Integration + Story Progression System (Week 7-9) 🎯 NEXT PHASE
**Goal:** Integrate AI narrative generation and implement turn-based story progression with quest system
**Total Tasks:** 45 tasks across 3 weeks (~126 hours)
**Implementation Details:** See [api/docs/PHASE4_IMPLEMENTATION.md](../api/docs/PHASE4_IMPLEMENTATION.md) for granular task breakdowns, code examples, and verification steps.
### Overview
Phase 4 delivers the core single-player gameplay experience where players interact with the AI Dungeon Master through button-based actions. This phase includes AI infrastructure, story progression, and the quest system.
### Week 7: AI Engine Foundation (15 tasks)
**Task Groups:**
- **Group 1: Redis & RQ Infrastructure** (4 tasks)
- **Group 2: AI API Clients** (4 tasks)
- **Group 3: Prompt Templates & Narrative Generation** (4 tasks)
- **Group 4: Usage Tracking & Cost Controls** (3 tasks)
| Task ID | Task | Status | Notes |
|---------|------|--------|-------|
| 7.1 | Set up Redis service wrapper | ⬜ | Connection pooling, TTL support |
| 7.2 | Configure RQ job queues | ⬜ | ai_tasks, combat_tasks, marketplace_tasks |
| 7.3 | Create base AI task job structure | ⬜ | Status tracking, retry logic |
| 7.4 | ✅ Checkpoint: Verify Redis/RQ | ⬜ | Integration test |
| 7.5 | Implement Replicate API client | ⬜ | Llama-3 8B for free tier |
| 7.6 | Implement Anthropic API client | ⬜ | Haiku/Sonnet/Opus support |
| 7.7 | Implement model selector | ⬜ | Tier-based routing |
| 7.8 | ✅ Checkpoint: Verify all models | ⬜ | Test each AI model |
| 7.9 | Create Jinja2 prompt templates | ⬜ | 4 core templates |
| 7.10 | Implement narrative generator | ⬜ | High-level generation API |
| 7.11 | Build AI task jobs | ⬜ | Async processing with Appwrite |
| 7.12 | ✅ Checkpoint: E2E AI flow | ⬜ | Full job lifecycle test |
| 7.13 | Implement AI usage tracking | ⬜ | Log tokens, costs to Appwrite |
| 7.14 | Implement daily limit checks | ⬜ | Per-tier rate limiting |
| 7.15 | Set up cost monitoring & alerts | ⬜ | Daily cost reports, email alerts |
**Deliverable:** Working AI narrative generation with tier-based models and cost controls
### Week 8: Story Progression System (16 tasks)
**Task Groups:**
- **Group 5: Action Prompts & Data Layer** (4 tasks)
- **Group 6: Session Management** (5 tasks)
- **Group 7: Story API Endpoints** (4 tasks)
- **Group 8: Story UI & Integration** (3 tasks)
| Task ID | Task | Status | Notes |
|---------|------|--------|-------|
| 8.16 | Create ActionPrompt dataclass | ⬜ | Tier/context filtering |
| 8.17 | Create 10 action prompts in YAML | ⬜ | Free(4), Premium(+3), Elite(+3) |
| 8.18 | Implement ActionPromptLoader | ⬜ | YAML loading and filtering |
| 8.19 | ✅ Checkpoint: Verify action filtering | ⬜ | Test tier/context logic |
| 8.20 | Extend GameSession for solo play | ⬜ | Add state tracking fields |
| 8.21 | Implement SessionService | ⬜ | Create/load/update sessions |
| 8.22 | Add conversation history management | ⬜ | History CRUD methods |
| 8.23 | Add game state tracking | ⬜ | Location, quests, events |
| 8.24 | ✅ Checkpoint: Verify persistence | ⬜ | Test Appwrite storage |
| 8.25 | Implement create session endpoint | ⬜ | POST /api/v1/sessions |
| 8.26 | Implement take action endpoint | ⬜ | POST /sessions/{id}/action (async) |
| 8.27 | Implement get session state endpoint | ⬜ | GET /api/v1/sessions/{id} |
| 8.28 | Implement get history endpoint | ⬜ | GET /sessions/{id}/history |
| 8.29 | Create story gameplay template | ⬜ | HTMX-powered UI |
| 8.30 | Build action button UI | ⬜ | Tier filtering, custom input |
| 8.31 | ✅ Checkpoint: Full integration test | ⬜ | Complete story turn flow |
**Deliverable:** Complete turn-based story progression with button-based actions
### Week 9: Quest System (14 tasks)
**Task Groups:**
- **Group 9: Quest Data Models** (3 tasks)
- **Group 10: Quest Content & Loading** (4 tasks)
- **Group 11: Quest Offering & Management** (4 tasks)
- **Group 12: Quest UI & Final Testing** (3 tasks)
| Task ID | Task | Status | Notes |
|---------|------|--------|-------|
| 9.32 | Create Quest dataclasses | ⬜ | Quest, Objective, Reward, Triggers |
| 9.33 | Create QuestTriggers with offering logic | ⬜ | Location/level-based eligibility |
| 9.34 | ✅ Checkpoint: Verify serialization | ⬜ | Test round-trip to JSON |
| 9.35 | Create quest YAML schema | ⬜ | Document in QUEST_SYSTEM.md |
| 9.36 | Write 10 example quests | ⬜ | 4 easy, 3 medium, 2 hard, 1 epic |
| 9.37 | Implement QuestService | ⬜ | YAML loading, filtering |
| 9.38 | ✅ Checkpoint: Verify quest loading | ⬜ | Test all 10 quests load |
| 9.39 | Implement context-aware offering | ⬜ | Probability + AI selection |
| 9.40 | Integrate offering into story turns | ⬜ | Check after each action |
| 9.41 | Implement quest accept endpoint | ⬜ | POST /api/v1/quests/accept |
| 9.42 | Implement quest complete endpoint | ⬜ | Rewards, level up check |
| 9.43 | Create quest tracker sidebar UI | ⬜ | Active quests display |
| 9.44 | Create quest offering modal UI | ⬜ | Accept/decline interface |
| 9.45 | ✅ Final Checkpoint: Full integration | ⬜ | Complete quest lifecycle |
**Deliverable:** YAML-driven quest system with context-aware offering
### Phase 4 Success Criteria
- [ ] AI clients for Anthropic and Replicate functional
- [ ] Tier-based model selection working (Free→Replicate, Premium→Sonnet, etc.)
- [ ] Cost tracking and daily limits enforced
- [ ] 10 action prompts defined and loadable from YAML
- [ ] Solo session creation and management working
- [ ] Story turn flow functional (action → AI response → state update)
- [ ] Conversation history persisted and displayed
- [ ] Tier restrictions enforced (Free: 4 buttons, Premium: 7 + free-form, Elite: 10 + free-form)
- [ ] 10 example quests defined in YAML
- [ ] Quest offering logic working (context-aware + location-based)
- [ ] Quest tracking and completion functional
- [ ] Max 2 active quests enforced
**Estimated Timeline:** ~126 hours (~16 days of focused work)
---
## Phase 5: Combat System + Skill Tree UI (Week 10-11)
**Goal:** Turn-based combat with AI narration + skill tree visualization
**Note:** Combat reuses the turn-based infrastructure built in Phase 4 (story progression). The main additions are damage calculation, effect processing, combat-specific UI, and the skill tree visualization deferred from Phase 3.
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Implement damage calculator | High | ⬜ | Physical, magical, critical |
| Implement effect processor | High | ⬜ | Tick effects, apply damage |
| Implement combat engine | High | ⬜ | Turn order, action processing |
| Implement initiative system | High | ⬜ | d20 + speed rolls |
| Implement combat API endpoints | High | ⬜ | Attack, cast, item, defend |
| Implement combat state management | High | ⬜ | Start, process, end combat |
| Implement AI combat narration | High | ⬜ | Generate descriptions for actions |
| Create loot generator | Medium | ⬜ | Random loot by tier |
| Implement XP/leveling | Medium | ⬜ | Award XP, level up characters |
| Create combat UI | High | ⬜ | `templates/game/combat.html` |
| Create combat action UI | High | ⬜ | Buttons for attack/spell/item |
| Create skill tree UI | High | ⬜ | `templates/character/skills.html` - Dual tree display (from Phase 3) |
| Implement skill node visualization | High | ⬜ | Show 5 tiers × 2 nodes per tree, locked/available/unlocked states |
| Implement skill unlock UI | High | ⬜ | Click to unlock with HTMX, prerequisite validation |
| Implement respec UI | Medium | ⬜ | Respec button with confirmation modal (costs gold) |
| Write combat tests | High | ⬜ | Test damage, effects, flow |
| Write skill tree UI tests | Medium | ⬜ | Test unlock flow, respec, validation |
**Deliverable:** Fully functional combat system + interactive skill tree UI
**Total Tasks:** 17 tasks (12 combat + 5 skill tree UI)
---
## Phase 6: Multiplayer Sessions (Week 12-13)
**Goal:** Invite-based, time-limited co-op sessions for Premium/Elite players
**Note:** Multiplayer is a paid-tier feature focused on short co-op adventures. Unlike solo story progression, multiplayer sessions are time-limited (2 hours), invite-based, and combat-focused.
**Key Features:**
- Premium/Elite tier only
- Shareable invite links
- 2-4 player parties
- 2-hour session duration
- AI-generated custom campaigns
- Realtime synchronization
- Character snapshots (doesn't affect solo campaigns)
**See:** [MULTIPLAYER.md](MULTIPLAYER.md) for complete specification
### Week 12: Core Multiplayer Infrastructure (Days 1-7)
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Create MultiplayerSession dataclass | High | ⬜ | Extends GameSession with time limits, invite codes |
| Create PartyMember dataclass | High | ⬜ | Player info, character snapshot |
| Create MultiplayerCampaign models | High | ⬜ | Campaign, CampaignEncounter, CampaignRewards |
| Implement invite code generation | High | ⬜ | 8-char alphanumeric, unique, 24hr expiration |
| Implement session creation API | High | ⬜ | `POST /api/v1/sessions/multiplayer/create` (Premium/Elite only) |
| Implement join via invite API | High | ⬜ | `GET/POST /api/v1/sessions/multiplayer/join/{invite_code}` |
| Implement lobby system | High | ⬜ | Ready status, player list, host controls |
| Implement 2-hour timer logic | High | ⬜ | Session expiration, warnings (10min, 5min, 1min), auto-end |
| Set up Appwrite Realtime | High | ⬜ | WebSocket subscriptions for live session updates |
| Write unit tests | Medium | ⬜ | Invite generation, join validation, timer logic |
### Week 13: Campaign Generation & Combat (Days 8-14)
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Implement AI campaign generator | High | ⬜ | Generate 3-5 encounters based on party composition |
| Create campaign templates | Medium | ⬜ | Pre-built campaign structures for AI to fill |
| Implement turn management | High | ⬜ | Initiative, turn order, action validation for multiplayer |
| Implement multiplayer combat flow | High | ⬜ | Reuse Phase 5 combat system, add multi-player support |
| Implement disconnect handling | High | ⬜ | Auto-defend mode, host promotion on disconnect |
| Implement reward distribution | High | ⬜ | Calculate and grant rewards at session end |
| Create lobby UI | High | ⬜ | `templates/multiplayer/lobby.html` - Player list, ready status, invite link |
| Create active session UI | High | ⬜ | `templates/multiplayer/session.html` - Timer, party status, combat, narrative |
| Create session complete UI | High | ⬜ | `templates/multiplayer/complete.html` - Rewards, stats, MVP badges |
| Write integration tests | High | ⬜ | Full session flow: create → join → play → complete |
| Test realtime synchronization | High | ⬜ | Multiple browsers simulating party gameplay |
| Test session expiration | Medium | ⬜ | Force expiration, verify cleanup and reward distribution |
**Deliverable:** Working invite-based multiplayer system with time-limited co-op campaigns
**Total Tasks:** 22 tasks across 2 weeks
---
## Phase 7: NPC Shop (Week 12)
**Goal:** Basic economy and item purchasing
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Define shop inventory | High | ⬜ | Items, prices, categories |
| Implement shop browse API | High | ⬜ | `GET /api/v1/shop/items` |
| Implement shop purchase API | High | ⬜ | `POST /api/v1/shop/purchase` |
| Implement transaction logging | Medium | ⬜ | Record all purchases |
| Create shop UI | High | ⬜ | `templates/shop/index.html` |
| Test shop purchases | Medium | ⬜ | Verify gold deduction, item add |
**Deliverable:** Working NPC shop system
---
## Phase 8: Marketplace (Week 13-14)
**Goal:** Player-to-player trading (Premium+ only)
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Implement marketplace browse API | High | ⬜ | Filtering, sorting, pagination |
| Implement listing creation API | High | ⬜ | Auction + fixed price |
| Implement bidding API | High | ⬜ | Validate bid amounts |
| Implement buyout API | High | ⬜ | Instant purchase |
| Implement listing cancellation | Medium | ⬜ | Return item to seller |
| Implement auction processing task | High | ⬜ | Periodic job to end auctions |
| Implement bid notifications | Medium | ⬜ | Realtime outbid alerts |
| Implement my listings/bids API | Medium | ⬜ | User's active listings/bids |
| Create marketplace browse UI | High | ⬜ | `templates/marketplace/browse.html` |
| Create listing detail UI | High | ⬜ | Show item, bids, auction timer |
| Create listing creation UI | High | ⬜ | Form for creating listings |
| Test auction flow | High | ⬜ | Full auction cycle |
| Test tier restrictions | High | ⬜ | Verify Premium+ only |
**Deliverable:** Working marketplace system
---
## Phase 9: Frontend Polish (Week 15-16)
**Goal:** Improve UI/UX, add HTMX interactivity
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Design CSS theme | High | ⬜ | Dark fantasy aesthetic |
| Implement responsive design | High | ⬜ | Mobile-friendly |
| Add HTMX for dynamic updates | High | ⬜ | No full page reloads |
| Create reusable components | Medium | ⬜ | Character cards, inventory, etc. |
| Add loading states | Medium | ⬜ | Spinners for AI calls |
| Add error messaging | High | ⬜ | User-friendly error displays |
| Implement dice roll animations | Low | ⬜ | `static/js/dice-roller.js` |
| Add combat animations | Low | ⬜ | Visual feedback for actions |
| Create base template | High | ⬜ | `templates/base.html` |
| Test UI across browsers | Medium | ⬜ | Chrome, Firefox, Safari |
**Deliverable:** Polished, interactive UI
---
## Phase 10: PWA & Deployment (Week 17-18)
**Goal:** Deploy to production as PWA
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Create PWA manifest | High | ⬜ | `static/manifest.json` |
| Create service worker | High | ⬜ | `sw.js` for offline support |
| Create PWA icons | High | ⬜ | Various sizes |
| Set up production environment | High | ⬜ | Server, domain, SSL |
| Configure Nginx | High | ⬜ | Reverse proxy |
| Configure Gunicorn | High | ⬜ | 4+ workers |
| Set up RQ workers (production) | High | ⬜ | Separate instances |
| Set up Redis (production) | High | ⬜ | Standalone or cluster |
| Configure monitoring | High | ⬜ | Sentry, uptime monitoring |
| Set up backup system | High | ⬜ | Daily Appwrite backups |
| Create deployment scripts | High | ⬜ | `scripts/deploy.sh` |
| Write deployment documentation | Medium | ⬜ | Update DEPLOYMENT.md |
| Perform security audit | High | ⬜ | Check all endpoints |
| Load testing | Medium | ⬜ | Test concurrent users |
| Deploy to production | High | ⬜ | Go live! |
**Deliverable:** Live production deployment
---
## Phase 11: Beta Testing & Iteration (Week 19-20)
**Goal:** Gather feedback and fix issues
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Recruit beta testers | High | ⬜ | 10-20 users |
| Create feedback form | High | ⬜ | Bug reports, suggestions |
| Monitor error logs | High | ⬜ | Daily Sentry review |
| Monitor AI costs | High | ⬜ | Track spending |
| Fix critical bugs | High | ⬜ | Priority: game-breaking issues |
| Balance combat | Medium | ⬜ | Adjust damage, HP, difficulty |
| Balance economy | Medium | ⬜ | Gold rates, item prices |
| Optimize performance | Medium | ⬜ | Reduce latency |
| Improve AI prompts | Medium | ⬜ | Better narrative quality |
| Update documentation | Medium | ⬜ | Based on learnings |
**Deliverable:** Stable, tested system ready for launch
---
## Phase 12: Launch Preparation (Week 21-22)
**Goal:** Marketing, final polish, and launch
### Tasks
| Task | Priority | Status | Notes |
|------|----------|--------|-------|
| Create landing page | High | ⬜ | Marketing site |
| Write user documentation | High | ⬜ | How to play guide |
| Set up payment system | High | ⬜ | Stripe integration for subscriptions |
| Implement subscription tiers | High | ⬜ | Free/Basic/Premium/Elite |
| Create privacy policy | High | ⬜ | Legal requirement |
| Create terms of service | High | ⬜ | Legal requirement |
| Set up analytics | Medium | ⬜ | Track user behavior |
| Create social media accounts | Medium | ⬜ | Twitter, Discord, etc. |
| Write launch announcement | Medium | ⬜ | Blog post, social media |
| Set up support system | Medium | ⬜ | Email, Discord, or ticketing |
| Final security review | High | ⬜ | Penetration testing |
| Final performance review | High | ⬜ | Load testing |
| Launch! | High | ⬜ | Public release |
**Deliverable:** Public launch of Code of Conquest
---
## Future Phases (Post-Launch)
### Phase 13: Content Expansion
- Additional player classes (Monk, Druid, Warlock, Artificer)
- New locations and quests
- More items and equipment
- Seasonal events
### Phase 14: Advanced Features
- Guild system
- PvP arena
- Crafting system
- Achievement system
- World events
### Phase 15: Mobile Apps
- Native iOS app
- Native Android app
- Mobile-specific UI optimizations
---
## Risk Management
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| **AI costs exceed budget** | High | Medium | Daily monitoring, strict tier limits, cost alerts |
| **Appwrite service issues** | High | Low | Backup plan to self-host, regular backups |
| **Low user adoption** | Medium | Medium | Beta testing, marketing, community building |
| **Performance issues** | Medium | Medium | Load testing, horizontal scaling, caching |
| **Security vulnerabilities** | High | Low | Regular audits, security-first development |
| **Feature creep** | Medium | High | Stick to roadmap, resist scope expansion |
---
## Success Metrics
### MVP Success (End of Phase 10)
- [ ] 50+ beta users
- [ ] < 3s average API response time
- [ ] < $500/month AI costs
- [ ] 99% uptime
- [ ] < 5% error rate
### Launch Success (End of Phase 12)
- [ ] 500+ registered users
- [ ] 100+ paying subscribers
- [ ] Positive user reviews
- [ ] Profitable (revenue > costs)
- [ ] Active community (Discord, etc.)
### Long-term Success (6 months post-launch)
- [ ] 5,000+ registered users
- [ ] 1,000+ paying subscribers
- [ ] Monthly content updates
- [ ] Growing user base
- [ ] Sustainable business model
---
## Notes
**Current Status:** Phase 3 ✅ COMPLETE (100%) | Phase 4 🎯 READY TO START
**Last Completed:** Phase 3 - Character System (creation, management, APIs, UI) - November 16, 2025
**Next Milestone:** Phase 4 - AI Integration + Story Progression + Quest System (Weeks 7-9, 21 days)
**Estimated MVP Completion:** End of Phase 10 (~20 weeks / 5 months)
**Estimated Launch:** End of Phase 12 (~24 weeks / 6 months)
**Important Notes:**
- Phase 3 is 100% complete. Skill tree UI deferred to Phase 5 (Combat System).
- Phase 4 is the next active development phase (AI engine + story progression + quests).
- Phase 4 expanded from 1 week to 3 weeks to include complete story gameplay loop.
- Overall timeline extended by 2 weeks from original estimate.
**Update Frequency:** Review and update roadmap weekly during development
---
## Changelog
| Date | Change | By |
|------|--------|-----|
| 2025-11-14 | Initial roadmap created | Claude |
| 2025-11-14 | Phase 2 (Authentication & User Management) completed | User/Claude |
| 2025-11-15 | Phase 3 Character API layer completed (10 endpoints) | Claude |
| 2025-11-15 | Documentation updated: API_REFERENCE.md, API_TESTING.md | Claude |
| 2025-11-16 | Phase 3 Integration tests completed (18 comprehensive tests) | Claude |
| 2025-11-16 | API_TESTING.md updated with correct endpoint paths and formats | Claude |
| 2025-11-16 | Database migrated from Documents API to TablesDB API | User/Claude |
| 2025-11-16 | Authentication flow fixed (session secrets, cookies, user model) | User/Claude |
| 2025-11-16 | Phase 3 Character Creation UI completed (4-step HTMX flow) | User/Claude |
| 2025-11-16 | Phase 3 Character Management UI completed (list, detail pages) | User/Claude |
| 2025-11-16 | Phase 3 COMPLETE ✅ - Character system fully functional | User/Claude |
| 2025-11-16 | Created STORY_PROGRESSION.md - Turn-based story gameplay system | Claude |
| 2025-11-16 | Created QUEST_SYSTEM.md - YAML-driven quest system with context-aware offering | Claude |
| 2025-11-16 | Expanded Phase 4 from 1 week to 3 weeks (AI + Story + Quests) | Claude |
| 2025-11-16 | Adjusted Phases 5-6 timeline (+2 weeks overall to MVP) | Claude |
| 2025-11-16 | Created MULTIPLAYER.md - Invite-based, time-limited co-op system specification | Claude |
| 2025-11-16 | Revised Phase 6: Multiplayer now paid-tier only, 2-hour sessions, AI campaigns | Claude |
| 2025-11-16 | Phase 3 marked as 100% complete - Skill tree UI moved to Phase 5 | User/Claude |
| 2025-11-16 | Phase 5 updated to include skill tree UI (5 additional tasks) | User/Claude |
| 2025-11-16 | Phase 4 set as next active development phase (READY TO START) | User/Claude |

View File

@@ -0,0 +1,926 @@
# Web vs Client Feature Distribution
**Version:** 1.0
**Last Updated:** November 17, 2025
**Status:** Architectural Decision Document
---
## Overview
This document defines the feature distribution strategy between **Public Web Frontend** (`/public_web`) and **Godot Game Client** (`/godot_client`). It outlines what features belong in each frontend, security considerations, and implementation priorities.
**Core Principle:** Both frontends are **thin clients** that make HTTP calls to the API backend. The API is the single source of truth for all business logic, data persistence, and validation.
---
## Architecture Pattern
```
┌─────────────────────────────────────────────────────────────┐
│ User Access │
├──────────────────────────┬──────────────────────────────────┤
│ │ │
│ Public Web Frontend │ Godot Game Client │
│ (Flask + Jinja2) │ (Godot 4.5) │
│ │ │
│ - Account Management │ - Gameplay Experience │
│ - Character Viewing │ - Combat & Quests │
│ - Marketplace │ - Real-time Multiplayer │
│ - Community │ - Inventory & Equipment │
│ │ │
└──────────────────────────┴──────────────────────────────────┘
┌────────────────────┐
│ API Backend │
│ (Flask REST) │
│ │
│ - Business Logic │
│ - Validation │
│ - Data Persistence │
│ - AI Integration │
└────────────────────┘
┌────────────────────┐
│ Appwrite DB │
│ + Redis Cache │
└────────────────────┘
```
**Key Points:**
- Both frontends are **untrusted clients** - API validates everything
- No business logic in frontends (only UI/UX)
- No direct database access from frontends
- API enforces permissions, rate limits, tier restrictions
---
## Feature Distribution Strategy
### Decision Framework
When deciding where a feature belongs, consider:
1. **Security Sensitivity** - Payment/account changes → Web only
2. **Gameplay Integration** - Combat/quests → Game only
3. **Accessibility** - Planning/browsing → Web preferred
4. **User Experience** - Visual/immersive → Game preferred
5. **Performance** - Real-time updates → Game preferred
6. **SEO/Marketing** - Public content → Web preferred
---
## Public Web Frontend Features
The web frontend serves as the **Management Plane** - where players manage their account, characters, and community presence outside of active gameplay.
### ✅ Core Account Management (Security-Critical)
**Authentication & Security:**
- User registration with email verification
- Login with session management
- Password reset flow (email-based)
- Change password (requires re-authentication)
- Change email address (with verification)
- Two-Factor Authentication (2FA) setup
- View active sessions (device management)
- Login history and security audit log
- Account deletion (GDPR compliance)
**Why Web?**
- Security-critical operations require robust email flows
- PCI/GDPR compliance easier on web
- Better audit trails with server logs
- Standard user expectation (manage accounts in browsers)
- HTTPS, CSP headers, secure cookie handling
### ✅ Subscription & Payment Management
**Billing Features:**
- View current subscription tier
- Upgrade/downgrade between tiers (Free, Basic, Premium, Elite)
- Payment method management (add/remove cards)
- Billing history and invoices
- Cancel subscription
- Gift code redemption
- Referral program tracking
**Why Web?**
- **PCI DSS compliance** - Never handle payments in game clients
- Standard payment gateways (Stripe, PayPal) are web-first
- Easier to secure against client-side tampering
- Legal/regulatory requirements (receipts, invoices)
- Integration with Stripe Customer Portal
**Security:**
- No payment data stored in database (Stripe handles)
- Webhook verification for subscription changes
- Transaction logging for audit compliance
### ✅ Character Management (Viewing & Light Editing)
**Character Features:**
- **Character Gallery** - View all characters with stats, equipment, level, achievements
- **Character Detail View** - Full character sheet (read-only)
- **Character Comparison** - Side-by-side stat comparison (useful for planning builds)
- **Character Renaming** - Simple text field edit
- **Character Deletion** - Soft delete with confirmation modal
- **Skill Tree Viewer** - Read-only interactive skill tree (planning builds)
**Why Web?**
- Accessible from anywhere (phone, work, tablet)
- Good for planning sessions while away from desktop
- Faster load times than booting game client
- Industry standard: WoW Armory, FFXIV Lodestone, D&D Beyond
**Note:** Character **creation** wizard can be on web OR game (see recommendations below)
### ✅ Marketplace (Full-Featured Trading Hub)
**Marketplace Features:**
- **Browse Listings** - Search, filter, sort with pagination
- **Advanced Search** - Filter by item type, rarity, level, price range
- **Place Bids** - Auction bidding system with bid history
- **Buyout** - Instant purchase at buyout price
- **Create Listing** - List items for auction or fixed price
- **My Listings** - View/cancel your active listings
- **My Bids** - View/manage your active bids
- **Transaction History** - Full audit trail of purchases/sales
- **Price Analytics** - Charts, market trends, price history
- **Watchlist** - Save listings to watch later
- **Notification Preferences** - Email/in-game alerts for auction wins/outbid
**Why Web?**
- Better for serious trading (multiple tabs, spreadsheets, price comparison)
- Data visualization for market trends (charts work better on web)
- Pagination-friendly (hundreds of listings)
- Can browse while at work/away from game
- SEO benefits (public listings can be indexed)
**Note:** Game client should have **light marketplace access** for convenience (quick browse/buy during gameplay)
### ✅ Community & Content
**Community Features:**
- **Dev Blog** - Patch notes, announcements, event schedules
- **Game News** - Latest updates, maintenance windows, new features
- **Forums** - Player discussions (or link to Discord/Reddit)
- **Leaderboards** - Global rankings, seasonal standings, category leaderboards
- **Guild Directory** - Browse guilds, recruitment listings, guild pages
- **Player Profiles** - Public character pages (if user enables)
- **Session Replays** - View past session logs (markdown export from API)
- **Knowledge Base** - Game wiki, guides, FAQs, tutorials
- **Feedback/Suggestions** - Submit feedback, vote on features
**Why Web?**
- **SEO benefits** - Google can index news, guides, wiki pages (marketing)
- Accessible to non-players (prospect research before signing up)
- Easier content updates (no client patches required)
- Standard for all MMOs/online games (WoW, FFXIV, GW2, etc.)
- Community engagement outside of gameplay
### ✅ Analytics & Progress Tracking
**Dashboard Features:**
- **Account Stats** - Total playtime, characters created, sessions played
- **Character Progress** - XP charts, gold history, level progression timeline
- **Combat Analytics** - Win/loss rate, damage dealt, kills, deaths
- **Achievement Tracker** - Progress toward achievements, completion percentage
- **Quest Log** - View active/completed quests across all characters
- **Collection Tracker** - Items collected, rare drops, completionist progress
**Why Web?**
- Always accessible (check progress on phone)
- Better for data visualization (charts, graphs, timelines)
- Doesn't clutter game UI
- Can share stats publicly (profile pages)
### ✅ Support & Help
**Support Features:**
- **Help Desk** - Submit support tickets, track status
- **FAQ / Knowledge Base** - Searchable help articles
- **Contact Form** - Direct contact with support team
- **Bug Reports** - Submit bug reports with screenshots
- **Email Preferences** - Newsletter subscriptions, notification settings
**Why Web?**
- Standard support workflow (ticket systems)
- Easier to attach screenshots/logs
- Can access while game is broken
- GDPR compliance (manage email consent)
### ✅ Guild Management Hub (Future Feature)
**Guild Features:**
- **Create Guild** - Setup guild with name, description, emblem
- **Manage Guild** - Edit details, set permissions, manage roster
- **Guild Bank** - View/manage shared resources
- **Guild Events** - Schedule raids, events with calendar integration
- **Guild Permissions** - Role-based access control
- **Recruitment** - Post recruitment listings to directory
**Why Web?**
- Guild management is administrative (not gameplay)
- Better UX for roster management (tables, sorting)
- Calendar integration works better on web
- Officers can manage guild without booting game
---
## Godot Game Client Features
The game client serves as the **Experience Plane** - where players engage with gameplay, combat, story, and real-time interactions.
### ✅ Core Gameplay
**Gameplay Features:**
- **Character Creation** - Full visual wizard with 3D character previews
- **Combat System** - Turn-based combat UI with animations, effects, sound
- **Quest System** - Quest tracking, objectives, turn-ins, rewards
- **Story Progression** - AI DM interactions, narrative choices, action prompts
- **Exploration** - World map navigation, location discovery, fast travel
- **NPC Interactions** - Dialogue trees, shop browsing, quest givers
- **Session Management** - Join/create sessions, invite players, session state
**Why Game?**
- Rich UI/UX (animations, particle effects, sound design)
- Immersive experience (3D environments, music, atmosphere)
- Real-time interactions with AI DM
- This is what players launch the game for
### ✅ Inventory & Equipment Management
**Inventory Features:**
- **Inventory UI** - Drag-drop interface, auto-sort, filtering
- **Equipment System** - Character sheet, equip/unequip with visual updates
- **Item Tooltips** - Detailed stats, stat comparisons (current vs new)
- **Item Usage** - Consume potions, activate items, combine items
- **Loot System** - Loot drops, auto-loot settings, loot rolling (multiplayer)
**Why Game?**
- Drag-drop is better in native UI than web
- Visual feedback (character model updates when equipped)
- Tight integration with combat/gameplay
- Real-time item usage during combat
### ✅ Social & Multiplayer
**Social Features:**
- **Party Formation** - Invite players to party, manage party composition
- **Chat System** - Party chat, global chat, whispers, guild chat
- **Multiplayer Sessions** - Real-time session joining, turn coordination
- **Emotes** - Character animations, quick messages
- **Friend List** - Add friends, see online status, invite to party
- **Voice Chat Integration** - Discord Rich Presence or in-game voice
**Why Game?**
- Real-time communication during gameplay
- WebSocket integration for live updates (Appwrite Realtime)
- Better performance for rapid message updates
- Social features enhance gameplay immersion
### ✅ Character Customization
**Customization Features:**
- **Appearance Editor** - Visual character customization (face, hair, body type)
- **Skill Tree** - Interactive skill unlocking with visual tree UI
- **Talent Respec** - Preview changes, confirm spend, visual feedback
- **Cosmetics** - Apply skins, mount cosmetics, visual effects
- **Character Sheet** - Live stat updates, equipment preview
**Why Game?**
- Visual feedback (see changes immediately on 3D model)
- Integrated with character rendering engine
- Better UX for complex skill trees (zoom, pan, tooltips)
- Drag-drop equipment for easy comparison
### ✅ Combat & Abilities
**Combat Features:**
- **Attack System** - Target selection, attack animations, damage numbers
- **Spell Casting** - Spell targeting, visual effects, cooldown tracking
- **Item Usage** - Combat items (potions, scrolls), inventory shortcuts
- **Defensive Actions** - Dodge, block, defend with animations
- **Combat Log** - Real-time combat text log with color coding
- **Status Effects** - Visual indicators for buffs/debuffs, duration tracking
**Why Game?**
- Animations, sound effects, particle systems
- Real-time feedback during combat
- Immersive combat experience
- Tight integration with game loop
### ✅ NPC Shops & Marketplace (Light Access)
**In-Game Commerce:**
- **NPC Shops** - Browse shop inventory, purchase items, sell loot
- **Marketplace (Quick Access)** - Simple search, quick buy, notifications
- **Auction Alerts** - Pop-up notifications for auction wins/outbid
- **Transaction Confirmation** - In-game purchase confirmations
**Why Game?**
- Convenience during gameplay (buy potions before dungeon)
- Quick transactions without alt-tabbing
- NPC shops are part of world immersion
**Note:** Serious trading should still happen on web (better UX for market analysis)
### ✅ Map & Navigation
**Navigation Features:**
- **World Map** - Interactive map with zoom, fog of war
- **Minimap** - Real-time position tracking during exploration
- **Waypoints** - Set custom waypoints, quest markers
- **Fast Travel** - Teleport to discovered locations
- **Location Discovery** - Reveal map as you explore
**Why Game?**
- Real-time position updates during movement
- Integration with 3D world rendering
- Better performance for map rendering
---
## Features That Should Be in BOTH (Different UX)
Some features benefit from being accessible in both frontends with different user experiences:
### 🔄 Marketplace
- **Web:** Full-featured trading hub (serious trading, market analysis, price charts)
- **Game:** Quick access (buy potions, check if auction won, browse while waiting)
### 🔄 Character Viewing
- **Web:** Planning builds (read-only skill trees, stat calculators, gear comparisons)
- **Game:** Active gameplay (equip items, unlock skills, use abilities)
### 🔄 News & Events
- **Web:** Read patch notes, browse dev blog, event calendars
- **Game:** In-game notifications (event starting soon, new patch available)
### 🔄 Achievements
- **Web:** Achievement tracker, progress bars, leaderboards, collection view
- **Game:** Achievement pop-ups, unlock notifications, sound effects
### 🔄 Friends & Social
- **Web:** Manage friend list, send friend requests, view profiles
- **Game:** See online status, invite to party, send messages
---
## Security Best Practices
### 🔒 Web-Only (High Security Operations)
These features MUST be web-only for security/compliance reasons:
1. **Payment Processing**
- PCI DSS compliance is easier on web
- Standard payment gateways (Stripe, PayPal) are web-first
- Easier to secure against client-side tampering
- Audit trails for regulatory compliance
- **NEVER handle payment info in game client**
2. **Password Management**
- Password reset flows require email verification
- Password change requires re-authentication
- Web is more secure (HTTPS, CSP headers, no client tampering)
- **NEVER allow password changes in game client**
3. **Email/Account Recovery**
- Email verification links (click to verify in browser)
- 2FA setup (QR codes for authenticator apps)
- Backup code generation and storage
- **Web-based flows are standard**
4. **Account Deletion / Critical Operations**
- Requires email confirmation (prevent accidental deletion)
- Legal compliance (GDPR right to deletion, data export)
- Audit trail requirements
- **Too risky for game client**
### 🎮 Game Client (Lower Security Risk)
These operations are safe in game client (with API validation):
- Gameplay actions (combat, quests, item usage)
- Character creation (not security-critical)
- Inventory management (server validates all transactions)
- Social features (chat, parties - API handles rate limits)
**Why Safe?**
- All validated server-side by API
- Game client is just a UI (thin client architecture)
- Cheating attempts fail at API validation layer
- API enforces permissions, tier limits, rate limits
### 🔐 Security Architecture Principle
```
[Untrusted Client] → [API Validates Everything] → [Database]
```
**Both frontends are untrusted:**
- Never trust client-side data
- API validates all inputs (sanitize, type check, permission check)
- API enforces business rules (tier limits, cooldowns, costs)
- Database transactions ensure data integrity
---
## Security Checklist for Web Frontend
When implementing web features, ensure:
### Authentication & Sessions
- [ ] HTTPS everywhere (Cloudflare, Let's Encrypt, SSL certificate)
- [ ] HTTP-only cookies for sessions (JavaScript cannot access)
- [ ] Secure flag on cookies (HTTPS only in production)
- [ ] SameSite: Lax or Strict (CSRF protection)
- [ ] Session expiration (24 hours normal, 30 days remember-me)
- [ ] Session regeneration after login (prevent session fixation)
### Input Validation & Protection
- [ ] CSRF protection on all forms (Flask-WTF)
- [ ] Input validation and sanitization (prevent XSS, SQLi)
- [ ] Content Security Policy (CSP) headers
- [ ] Rate limiting on sensitive endpoints (login, registration, password reset)
- [ ] CAPTCHA on registration/login (prevent bots)
### Payment Security
- [ ] Use Stripe/PayPal hosted checkout (no card data in your DB)
- [ ] Verify webhook signatures (prevent fake payment confirmations)
- [ ] PCI DSS compliance (use certified payment processors)
- [ ] Transaction logging for audit compliance
### Account Security
- [ ] Two-Factor Authentication (2FA) support (TOTP, backup codes)
- [ ] Email verification on registration
- [ ] Email confirmation for critical operations (password change, email change)
- [ ] Account lockout after N failed login attempts (5-10 attempts)
- [ ] Login history tracking (IP, device, timestamp)
- [ ] Security event notifications (new device login, password changed)
### Data Protection & Compliance
- [ ] GDPR compliance (data export, right to deletion)
- [ ] Privacy policy and terms of service
- [ ] Cookie consent banner (EU requirements)
- [ ] Data encryption at rest (database encryption)
- [ ] Data encryption in transit (TLS 1.2+ for API calls)
- [ ] Secure password storage (bcrypt, Argon2)
### HTTP Security Headers
- [ ] Strict-Transport-Security (HSTS)
- [ ] X-Content-Type-Options: nosniff
- [ ] X-Frame-Options: DENY (prevent clickjacking)
- [ ] X-XSS-Protection: 1; mode=block
- [ ] Referrer-Policy: strict-origin-when-cross-origin
### Logging & Monitoring
- [ ] Audit logging (who did what, when)
- [ ] Error tracking (Sentry, Rollbar)
- [ ] Security event alerts (failed logins, suspicious activity)
- [ ] Uptime monitoring (status page)
---
## Industry Examples & Best Practices
### World of Warcraft (Blizzard)
**Web (Battle.net):**
- Account management (register, login, 2FA, password reset)
- Shop (game time, expansions, mounts, pets)
- Armory (character profiles, gear, achievements)
- News (patch notes, events, hotfixes)
- Forums (community discussions)
- Guild finder
**Game Client:**
- All gameplay (quests, combat, exploration)
- Character customization (transmog, talents)
- Auction house (but also web armory for viewing)
- In-game shop (quick access to mounts/pets)
**Key Insight:** Players use web for planning (checking gear, reading news) and game for playing
---
### Final Fantasy XIV (Square Enix)
**Web (Lodestone + Mog Station):**
- Lodestone: News, character profiles, free company search, event calendar
- Mog Station: Account management, subscription, shop (mounts, cosmetics)
- Market board history and price trends
**Game Client:**
- All gameplay
- Retainer market board (player-driven economy)
- Glamour system (cosmetics)
- In-game shop access
**Key Insight:** Separate web properties for community (Lodestone) vs account (Mog Station)
---
### Path of Exile (Grinding Gear Games)
**Web:**
- Official trade marketplace (advanced search, price indexing)
- Account management (login, 2FA, linked accounts)
- News and patch notes
- Build guides and community wiki
- Passive skill tree planner
**Game Client:**
- All gameplay (combat, loot, skill gems)
- In-game item searching (but serious traders use web)
- Hideout customization
- MTX shop access
**Key Insight:** Community created trade tools before official web version (PoE.trade) - web is essential for complex economies
---
### EVE Online (CCP Games)
**Web:**
- Extensive market tools (price history, regional comparison)
- Killboards (combat logs, ship losses)
- Contract browsing (item contracts, courier contracts)
- Account management and subscription
- Skill planner
**Game Client:**
- Flying ships, combat, exploration
- Quick market trades (local market)
- Contract management
- Corporation (guild) management
**Key Insight:** EVE's complexity REQUIRES web tools - players use spreadsheets alongside web for market trading
---
### D&D Beyond (Wizards of the Coast)
**Web:**
- Character builder (digital character sheets)
- Campaign management (DM tools)
- Rules reference (searchable rules, spells, items)
- Marketplace (digital books, adventures)
- Dice roller
**In-Person Gameplay:**
- Players use tablets/phones to access web character sheets
- DM uses web for campaign notes
**Key Insight:** Tabletop RPG went digital - web is perfect for character management, rules lookup
---
### Common Patterns Across Industry
**Web = "Management Plane"**
- Account, billing, subscription
- Character planning and build theory
- Trading, market analysis, economics
- Community, news, forums
- Wiki, guides, knowledge base
**Game = "Experience Plane"**
- Gameplay, combat, quests, story
- Real-time multiplayer and chat
- Immersive visuals, sound, animations
- Social features during gameplay
---
## Recommended Implementation Phases
### Phase 1: Essential Web Features (MVP)
**Goal:** Fix technical debt, enable basic account/character management
1. **Refactor public_web to use API** (Technical Debt)
- Replace stub service calls with HTTP requests to API
- Update auth helpers to validate sessions via API
- Remove stub service modules
- Test all existing views
2. **Authentication Flows**
- User registration with email verification
- Login with session management
- Password reset flow
- Logout
3. **Character Gallery**
- View all characters (read-only)
- Character detail pages
- Basic stats and equipment display
4. **Account Settings**
- Change password (requires re-auth)
- Change email (with verification)
- View account info (registration date, tier)
5. **Dev Blog / News Feed**
- Simple blog posts (markdown-based)
- Announcement system
- RSS feed
**Deliverable:** Functional web frontend that complements game client
---
### Phase 2: Monetization (Revenue)
**Goal:** Enable subscription management and payment processing
6. **Subscription Management**
- View current tier (Free, Basic, Premium, Elite)
- Upgrade/downgrade flows
- Stripe integration (Customer Portal)
- Subscription confirmation emails
7. **Payment Processing**
- Stripe Checkout integration
- Webhook handling (subscription updates)
- Payment method management
8. **Billing History**
- View past invoices
- Download receipts (PDF)
- Transaction log
9. **Gift Code Redemption**
- Enter gift codes
- Apply promotional codes
- Track code usage
**Deliverable:** Monetization system to support ongoing development
---
### Phase 3: Community & Engagement
**Goal:** Build community, increase retention
10. **Marketplace (Web Version)**
- Browse listings (search, filter, sort, pagination)
- Place bids on auctions
- Create listings (auction or fixed price)
- My listings / My bids
- Transaction history
- Price analytics and charts
11. **Leaderboards**
- Global rankings (level, wealth, achievements)
- Seasonal leaderboards
- Category leaderboards (PvP, crafting, questing)
- Player profile links
12. **Session History Viewer**
- View past session logs (markdown export from API)
- Search sessions by date, characters, party members
- Share session links publicly (if enabled)
13. **Player Profiles**
- Public character pages (if user enables)
- Achievement showcase
- Stats and analytics
- Session history
**Deliverable:** Community features to keep players engaged
---
### Phase 4: Advanced Features
**Goal:** Expand platform, add convenience features
14. **Guild Management Hub**
- Create/manage guilds
- Guild roster management
- Guild bank (shared resources)
- Guild event scheduling
15. **Forums / Community**
- Discussion boards (or Discord/Reddit integration)
- Official announcements
- Player-to-player help
16. **Analytics Dashboard**
- Account stats (playtime, characters, sessions)
- Character progress charts (XP, gold, level timeline)
- Combat analytics (win rate, damage dealt)
17. **Support / Help Desk**
- Submit support tickets
- Track ticket status
- FAQ / knowledge base
- Bug report submission
**Deliverable:** Mature platform with advanced features
---
## Character Creation: Web vs Game Recommendation
**Character creation wizard can exist in BOTH, but prioritize based on your goals:**
### Option 1: Game Client Primary (Recommended)
**Pros:**
- Better UX (3D character preview, animations, music)
- Immersive first-time experience
- Visual customization (face, hair, body type)
- Immediate transition to gameplay after creation
**Cons:**
- Requires downloading game client before creating character
- Can't create characters on mobile (unless Godot exports to mobile)
**When to choose:** If you want character creation to be part of the game experience
---
### Option 2: Web Primary (Accessibility)
**Pros:**
- Accessible from anywhere (phone, tablet, any browser)
- Can create characters before downloading game
- Faster load times (no 3D assets)
- Good for planning builds (skill tree preview)
**Cons:**
- Less immersive (no 3D preview)
- Limited visual customization (no character model)
- Feels more administrative than experiential
**When to choose:** If you want to reduce friction (create character on phone, play on desktop later)
---
### Option 3: Both (Best of Both Worlds)
**Implementation:**
- Web: "Quick Create" - Name, class, origin (minimal wizard)
- Game: "Full Create" - Visual customization, 3D preview, full immersion
**When to choose:** If you want maximum flexibility
**Recommendation:** Start with game-only (better UX), add web later if needed
---
## Mobile Considerations
### Public Web (Mobile-Responsive)
The web frontend should be **fully mobile-responsive** for:
- Account management (on the go)
- Character viewing (check stats while away from PC)
- Marketplace browsing (trading from phone)
- News and community (read patch notes on commute)
**Implementation:**
- Responsive CSS (mobile-first design)
- Touch-friendly UI (large buttons, swipe gestures)
- Progressive Web App (PWA) support (installable on phone)
### Godot Client (Mobile Export - Future)
Godot supports mobile export (iOS, Android), but:
- Requires significant UI/UX changes (touch controls)
- Performance considerations (mobile GPUs)
- App store submission process
- Monetization changes (Apple/Google take 30% cut)
**Recommendation:** Start with desktop, add mobile export later if demand exists
---
## API Design Considerations
### Endpoint Organization
**Authentication:**
- `POST /api/v1/auth/register`
- `POST /api/v1/auth/login`
- `POST /api/v1/auth/logout`
- `POST /api/v1/auth/forgot-password`
- `POST /api/v1/auth/reset-password`
- `POST /api/v1/auth/verify-email`
**Account Management:**
- `GET /api/v1/account/profile`
- `PATCH /api/v1/account/profile`
- `POST /api/v1/account/change-password`
- `POST /api/v1/account/change-email`
- `DELETE /api/v1/account`
**Subscription:**
- `GET /api/v1/subscription/status`
- `POST /api/v1/subscription/create-checkout`
- `POST /api/v1/subscription/create-portal-session`
- `POST /api/v1/subscription/webhook` (Stripe)
**Marketplace:**
- `GET /api/v1/marketplace/listings`
- `GET /api/v1/marketplace/listings/:id`
- `POST /api/v1/marketplace/listings`
- `POST /api/v1/marketplace/listings/:id/bid`
- `POST /api/v1/marketplace/listings/:id/buyout`
- `DELETE /api/v1/marketplace/listings/:id`
**Leaderboards:**
- `GET /api/v1/leaderboards/:category`
- `GET /api/v1/leaderboards/player/:user_id`
**News:**
- `GET /api/v1/news` (public, no auth required)
- `GET /api/v1/news/:slug`
---
## Technology Stack Summary
### Public Web Frontend
**Core:**
- Flask (web framework)
- Jinja2 (templating)
- HTMX (dynamic interactions)
- Vanilla CSS (styling)
**Libraries:**
- Requests (HTTP client for API calls)
- Structlog (logging)
- Flask-WTF (CSRF protection)
**Deployment:**
- Gunicorn (WSGI server)
- Nginx (reverse proxy)
- Docker (containerization)
### Godot Game Client
**Core:**
- Godot 4.5 (game engine)
- GDScript (scripting language)
- HTTP client (API calls)
**Deployment:**
- Desktop exports (Windows, macOS, Linux)
- Web export (WebAssembly) - future
- Mobile exports (iOS, Android) - future
### API Backend
**Core:**
- Flask (REST API framework)
- Appwrite (database, auth, realtime)
- RQ + Redis (async task queue)
- Anthropic API (Claude AI for DM)
**Libraries:**
- Dataclasses (data modeling)
- PyYAML (config, game data)
- Structlog (logging)
- Requests (external API calls)
---
## Conclusion
**Public Web Frontend:**
- **Purpose:** Account management, character planning, community engagement
- **Features:** Authentication, subscriptions, marketplace, news, leaderboards, analytics
- **Security:** Payment processing, password management, 2FA, audit logs
- **Accessibility:** Mobile-responsive, SEO-friendly, fast load times
**Godot Game Client:**
- **Purpose:** Immersive gameplay experience
- **Features:** Combat, quests, story progression, real-time multiplayer, inventory
- **Experience:** 3D graphics, animations, sound design, music
- **Performance:** Real-time updates, WebSocket communication, optimized rendering
**Both frontends:**
- Thin clients (no business logic)
- Make HTTP requests to API backend
- API validates everything (security, permissions, business rules)
- Microservices architecture (independent deployment)
**Next Steps:**
1. Refactor public_web technical debt (remove stub services)
2. Implement Phase 1 web features (MVP)
3. Continue Godot client development (gameplay features)
4. Phase 2+ based on user feedback and revenue needs
---
**Document Version:** 1.0
**Last Updated:** November 17, 2025
**Next Review:** After Phase 1 completion