# Phase 5 — Multi-App Deployment (05) ## 6 Alorig Apps on Shared Infrastructure **Source of Truth:** Alorig-Master-Plan-v1.md + individual app blueprints **Document Version:** 1.0 **Date:** 2026-03-23 **Phase:** IGNY8 Phase 5 — Multi-App Deployment **Status:** Build Ready **Audience:** Claude Code, DevOps, Backend Developers, Frontend Developers --- ## 1. CURRENT STATE ### Shared Infrastructure Operational (Phase 0) - **VPS:** Hostinger KVM 4 — 4 vCPU, 16GB RAM, 200GB NVMe - **Docker Network:** `alorig_net` (external, all apps join) - **Shared Services** (`docker-compose.infra.yml`): - `alorig_postgres` — PostgreSQL 16, separate database per app - `alorig_redis` — Redis 7, app-specific key prefixes + DB numbers - `alorig_caddy` — Caddy 2, reverse proxy + SSL via Cloudflare DNS challenge - `portainer` — Portainer CE, Docker GUI for 25+ containers - `flower` — mher/flower, Celery monitoring (on-demand) - **DNS:** All domains in Cloudflare (free tier), wildcard A records to VPS IP ### IGNY8 Production + Staging Running - IGNY8 Phase 0–4 complete and stable - Containers: `igny8_backend`, `igny8_frontend`, `igny8_celery_worker`, `igny8_celery_beat`, `igny8_celery_video_worker`, `flower` - RAM usage: ~1.8 GB - Ports: 8011 (prod), 8031 (staging) - Redis DBs: 0 (prod), 1 (staging) ### 6 Apps Awaiting Deployment All apps have blueprints finalized. None have GitHub repos or containers yet. ### Resource Budget | Component | RAM Estimate | |-----------|-------------| | Shared infra (PG + Redis + Caddy + Portainer) | ~2.5 GB | | IGNY8 (prod + staging) | ~1.8 GB | | Psydge | ~1.75 GB | | Snapify | ~700 MB | | Observer OS | ~700 MB | | Alorig Site Builder | ~1.25 GB | | AstroTiming | ~400 MB | | ASMS Phase 1 | ~600 MB | | OS + Docker overhead | ~1.0 GB | | **TOTAL STEADY STATE** | **~10.7 GB / 16 GB** | **Headroom:** ~5 GB for spikes. Upgrade trigger: steady-state >13 GB or OOM kills. --- ## 2. WHAT TO BUILD Deploy 6 apps sequentially on the shared infrastructure. Each app follows the standard Alorig container pattern with app-specific exceptions. Deploy one at a time, monitor RAM after each before proceeding. ### Deployment Order | # | App | Rationale | Expected RAM | |---|-----|-----------|-------------| | 1 | **Psydge** | Most complex (WebSockets, Channels, real-time). Validate server under real load early. | ~1.75 GB | | 2 | **Snapify** | Standard Django. Validates multi-app pattern. WhatsApp adds external service testing. | ~700 MB | | 3 | **Alorig Site Builder** | Dual runtime (Django + Payload CMS/Node.js). Tests Node.js container pattern. | ~1.25 GB | | 4 | **Observer OS** | Standard Django + React. Light resources. Shares ephemeris logic with AstroTiming. | ~700 MB | | 5 | **AstroTiming** | Lightest app. Shares `pyswisseph` ephemeris data approach with Observer OS. | ~400 MB | | 6 | **ASMS Phase 1** | School management MVP for 74-school pilot. Basic modules only. | ~600 MB | ### Shared Tech Stack (All Apps) | Layer | Technology | Version | |-------|-----------|---------| | Backend | Django | 5.1–5.2+ | | API | Django REST Framework | 3.15+ | | Database | PostgreSQL | 16 (shared instance, separate DB per app) | | Cache/Broker | Redis | 7 (shared instance, separate DB per app) | | Task Queue | Celery | 5.3+ | | Frontend | React + TypeScript | React 19, TS 5+ | | State Management | Zustand | 4–5 | | Styling | Tailwind CSS | 3–4 | | Build | Vite | 5–6 | | Containers | Docker + Docker Compose | External network (`alorig_net`) | | Reverse Proxy | Caddy 2 | Cloudflare DNS challenge SSL | --- ## 3. SHARED DEPLOYMENT PATTERN ### Standard Per-App Container Set (3 containers) | Container | Role | |-----------|------| | `{app}_backend` | Django + Gunicorn (WSGI) | | `{app}_celery_worker` | Background task processing | | `{app}_celery_beat` | Scheduled task scheduling | React frontend built as static files → served via `alorig_caddy` (no separate frontend container). **Exceptions:** - Psydge: +1 container (`psydge_channels` for Django Channels/ASGI/WebSocket) - Site Builder: +1 container (`sitebuilder_payload` for Node.js/Payload CMS) ### Port Assignment Map | App | Backend Port | Additional Ports | |-----|-------------|-----------------| | IGNY8 (prod) | 8011 | — | | IGNY8 (staging) | 8031 | — | | Psydge | 8012 | 8013 (WebSocket/Channels) | | Snapify | 8014 | — | | Alorig Site Builder | 8016 | 8017 (Payload CMS) | | Observer OS | 8018 | — | | AstroTiming | 8020 | — | | ASMS | 8022 | — | ### Redis DB Assignment Map | DB | App | |----|-----| | 0 | IGNY8 production | | 1 | IGNY8 staging | | 2 | Psydge | | 3 | Snapify | | 4 | Alorig Site Builder | | 5 | Observer OS | | 6 | AstroTiming | | 7 | ASMS | ### Docker Compose File Naming ``` docker-compose.infra.yml ← Shared infrastructure docker-compose.igny8.yml ← IGNY8 production docker-compose.igny8-staging.yml ← IGNY8 staging docker-compose.psydge.yml ← Psydge docker-compose.snapify.yml ← Snapify docker-compose.sitebuilder.yml ← Alorig Site Builder docker-compose.observer.yml ← Observer OS docker-compose.astrotiming.yml ← AstroTiming docker-compose.asms.yml ← ASMS Phase 1 ``` All compose files: `networks: { alorig_net: { external: true } }` --- ## 4. APP 1: PSYDGE — AI Trading Discipline Platform ### Product Summary Psydge (Psychological Edge) — web-based trading discipline and execution platform. Sits between trader and MT4/MT5 broker via MetaApi, enforcing hard-coded discipline rules that structurally prevent self-destructive trading. Two products: Psydge Core (discipline engine) + Vista Strategies (pre-defined strategy suite). ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | Real-Time | Django Channels + Redis | WebSocket: live prices, position updates, gate status, AI messages | | Broker Bridge | MetaApi (Cloud) | MT4/MT5 connectivity, order execution, position polling | | AI | Claude API (Anthropic) | Trade supervision, behavioral prediction, pre-entry validation, session debriefs | | Charts | TradingView Lightweight Charts | Live candlestick charts, M1–D1 timeframes | | Billing | Stripe | Subscription (Psydge Core + Vista Strategies tiers) | ### Container Architecture (4 containers — exception) | Container | Image | Role | Port | |-----------|-------|------|------| | `psydge_backend` | psydge-backend:latest | Django + Gunicorn (WSGI for REST API) | 8012 | | `psydge_channels` | psydge-backend:latest | Django + Daphne (ASGI for WebSocket) | 8013 | | `psydge_celery_worker` | psydge-backend:latest | Celery worker (AI calls, behavioral analysis, scoring) | — | | `psydge_celery_beat` | psydge-backend:latest | Celery beat scheduler | — | ### Database - Database: `psydge_db` on `alorig_postgres` - Redis prefix: `psydge:`, Redis DB: 2 ### Core Data Models | Model | Key Fields | Purpose | |-------|-----------|---------| | User | email, timezone, broker_credentials (encrypted), subscription_tier | User account | | BrokerConnection | user_id, broker, server, account_number, connection_status | MT4/MT5 connection state | | DisciplineConfig | user_id, loss_lock_r, profit_lock_r, cooldown_hours, max_risk_pct, session_hours, symbol_whitelist | Per-user discipline parameters | | GateState | Redis hash: user_id → 6 buffer values | Real-time gate buffers (sub-ms reads) | | Trade | user_id, symbol, direction, entry, sl, tp, lot, risk_pct, r_result, strategy, status, opened_at, closed_at | Complete trade record | | Violation | user_id, violation_code, attempted_action, gate_state_snapshot | Every blocked trade attempt | | DisciplineScore | user_id, date, score, metric_breakdown (JSON) | Daily discipline score history | | ReflectionEntry | user_id, date, session_notes, ai_prompt, ai_summary | Session journal entries | | AIInteraction | user_id, trade_id, role, input_context, output | AI call history for audit | | BehavioralPattern | user_id, pattern_type, occurrence_count, last_instance, trend | Detected violation patterns | ### Redis State Schema | Key Pattern | Type | TTL | Content | |-------------|------|-----|---------| | `psydge:gate:{user_id}` | Hash | Persistent | All 6 buffer values | | `psydge:cooldown:{user_id}` | String | Cooldown duration | Cooldown expiry timestamp | | `psydge:session_r:{user_id}` | String | End of day | Cumulative R for session | | `psydge:positions:{user_id}` | Hash | Live sync | Open positions from MetaApi | | `psydge:prices:{symbol}` | String | 5 seconds | Latest bid/ask | | `psydge:lock:{user_id}` | String | End of session | Session lock flag | ### Discipline Engine - **6 Gate Buffers:** GO Signal (B), Symbol+TF Whitelist (C), Session Filter (D), R-Based Equity Guard (E), Cooldown Timer (H), Risk % Check (K) - **Locked Rules:** Loss Lock (−2R daily), Profit Lock (+3R daily), 4hr cooldown, 1% risk/trade, London+NY sessions only, web panel only execution - **Violation Levels:** L1 Alert → L2 Overlay → L3 Blackout → L4 Session Lock - **Discipline Score (0–100):** Rule Compliance 25%, Session Discipline 15%, Risk Management 15%, Patience 15%, Post-Win Control 15%, Cooldown Respect 10%, Revenge Prevention 5% ### 4 AI Roles (Claude API + Celery) | Role | Trigger | Output | |------|---------|--------| | Trade Supervisor | Trade at TP1 or R threshold | scale / hold / tighten_sl / exit | | Pre-Entry Validator | User initiates trade (if enabled) | approve / stand_down + reasoning | | Behavioral Predictor | Session start + post-trade | Risk alerts + enforcement tightening | | Session Debrief | Session end | Natural language summary + insights | ### Vista Strategy Suite (4 Tiers) | Strategy | Timeframe | Target R | |----------|-----------|----------| | Scalper Engine | M1–M5 | 1.5–2R | | Intraday Momentum | M15–H1 | 2–7R | | Swing Position | H1–D1 | 5–12R | | Vault Trail | H4–D1 | 15–20R | 6 proprietary indicators: NDNS, SV, TM, MOM, FHS, HAMFIST. ### Celery Tasks | Task | Schedule | |------|----------| | `calculate_discipline_score` | End of each trading session | | `detect_behavioral_patterns` | After every violation | | `ai_session_debrief` | Session end | | `sync_metaapi_positions` | Every 5 seconds (per connected user) | | `weekly_behavioral_report` | Sunday 23:00 UTC | ### Caddy Routes ``` psydge.com → static React build (frontend) api.psydge.com → psydge_backend:8012 (REST API) ws.psydge.com → psydge_channels:8013 (WebSocket) ``` ### Implementation Steps 1. Create GitHub repo `psydge` with Django project scaffold 2. Configure `docker-compose.psydge.yml` (4 containers on `alorig_net`) 3. Create `psydge_db` on shared PostgreSQL 4. Build Django models, migrations, admin 5. Build Discipline Engine (gate buffers, violation logging, enforcer) 6. Integrate MetaApi SDK (broker connection, order flow, position sync) 7. Build WebSocket consumers (Django Channels) for real-time data 8. Build Vista strategy engine (indicator calculations, TM scoring) 9. Integrate Claude API for 4 AI roles via Celery tasks 10. Build React frontend (trade panel, analytics dashboard, settings) 11. Configure Caddy routes for psydge.com, api.psydge.com, ws.psydge.com 12. Build Stripe subscription integration 13. Deploy, smoke test with paper trading account 14. Monitor RAM — expected ~1.75 GB steady state --- ## 5. APP 2: SNAPIFY — Pakistani E-Commerce Platform ### Product Summary Snapify.pk — mobile-first, AI-powered e-commerce platform for Pakistani micro-sellers to create online stores via WhatsApp. Three-interface architecture: buyer-facing store (server-rendered Django for SEO), seller dashboard (React 19 PWA), admin panel (React 19 SPA). Target: 5M+ informal sellers, breakeven at ~150 paying users. ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | WhatsApp | WhatsApp Business Cloud API | Onboarding bot, order notifications, seller commands | | Image CDN | Cloudinary | Image optimization, responsive srcset, WebP | | File Storage | DigitalOcean Spaces (S3-compatible) | Product images, generated assets | | Social APIs | Meta Graph API (FB + Instagram) | Auto-posting, story creation for Pro sellers | | AI Engine | OpenAI GPT-4 + Whisper API | Content generation, image analysis, speech-to-text (Urdu/Punjabi) | | Email | SendGrid | Transactional emails | | Search | PostgreSQL Full-Text + pg_trgm | Product search, store discovery | | Payment | JazzCash / EasyPaisa | Pakistani payment gateways | ### Container Architecture (3 containers — standard) | Container | Image | Role | Port | |-----------|-------|------|------| | `snapify_backend` | snapify-backend:latest | Django + Gunicorn (REST API + server-rendered store pages) | 8014 | | `snapify_celery_worker` | snapify-backend:latest | Celery worker (AI, images, social posting, SEO gen) | — | | `snapify_celery_beat` | snapify-backend:latest | Celery beat (sitemap regen, hub pages, analytics) | — | **Note:** Buyer-facing store is server-rendered Django templates (NOT React) — critical for SEO on 3G connections. ### Database - Database: `snapify_db` on `alorig_postgres` - Redis prefix: `snapify:`, Redis DB: 3 ### Three-Interface Architecture | Interface | Users | Technology | URL | |-----------|-------|-----------|-----| | Buyer-Facing Store | Buyers / public | Server-rendered Django + Tailwind | snapify.pk/store-name | | Seller Dashboard | Sellers | React 19 PWA (installable) | app.snapify.pk | | Admin Panel | Alorig team | React 19 SPA | admin.snapify.pk | ### Core Data Models | Model | Key Fields | Purpose | |-------|-----------|---------| | Store | seller_id, name, slug, city, category, custom_domain, template, subscription_tier, is_verified | Multi-tenant store entity | | Product | store_id, title, description, price, images (JSON), category_id, variants (JSON), seo_meta | Product listing | | Order | store_id, buyer_name, buyer_phone, products (JSON), total, status, tracking_number | WhatsApp-native order lifecycle | | Category | store_id, name, slug, product_count | Store-level product categories | | Analytics | store_id, page_type, page_slug, visitor_ip_hash, referrer, city | Per-pageview analytics | | Subscription | store_id, plan (free/pro), started_at, expires_at, payment_method | Seller subscription | | Post | store_id, platform, content, image_url, scheduled_at, status, engagement_metrics | Social auto-posting | | WhatsAppSession | store_id, phone_hash, state, last_message_at | Onboarding conversation state machine | ### Multi-Tenant Architecture - `StoreBaseModel` — FK to Store (equivalent to IGNY8's `SiteSectorBaseModel`) - `StoreModelViewSet` — queries scoped to store - `StoreMiddleware` — resolves tenant from URL path or custom domain lookup ### AI Pipeline (5 Stages via Celery) | Stage | Input → Output | Technology | |-------|----------------|-----------| | Image Analysis | Product photos → category, color, material, style | GPT-4 Vision | | Voice Processing | WhatsApp voice notes → structured text | Whisper API | | Content Generation | Product metadata → title, description, bullets, meta | GPT-4 | | SEO Optimization | Content + city → city-specific landing pages, schema | Custom templates + GPT | | Social Content | Images + content → post-ready images with overlays | Pillow + GPT captions | ### Store Page Types (Server-Rendered) | Page Type | URL Pattern | |-----------|------------| | Store Homepage | snapify.pk/store-name | | Product Detail | snapify.pk/store-name/product-slug | | Category Page | snapify.pk/store-name/category-slug | | City Landing (Pro) | snapify.pk/store-name/delivery-to-lahore | | Store About | snapify.pk/store-name/about | | Category Hub (Platform) | snapify.pk/best-clothing-stores-punjab | ### Performance Targets (3G Pakistan) | Metric | Target | |--------|--------| | First Contentful Paint | < 1.0s on 3G | | Largest Contentful Paint | < 2.0s on 3G | | Total Page Size | < 200KB | | PageSpeed Score | 95+ (mobile) | ### Pricing | Plan | Price | Features | |------|-------|---------| | Free | Rs. 0 | 15 products, basic dashboard, Snapify branding | | Pro | Rs. 2,500/month | Unlimited products, custom domain, analytics, social posting, no branding | ### Celery Tasks | Task | Schedule | |------|----------| | `process_whatsapp_webhook` | On webhook receipt | | `generate_product_content` | On product photo upload | | `generate_city_pages` | Weekly (Pro stores) | | `regenerate_sitemap` | Daily 2 AM | | `regenerate_hub_pages` | Weekly Sunday 3 AM | | `social_auto_post` | Per schedule | | `invalidate_store_cache` | On product/store change | ### Caddy Routes ``` snapify.pk → snapify_backend:8014 (server-rendered store pages) api.snapify.pk → snapify_backend:8014/api/ (REST API) app.snapify.pk → static React PWA build (seller dashboard) admin.snapify.pk → static React SPA build (admin, IP-restricted) ``` ### Implementation Steps 1. Create GitHub repo `snapify` with Django project scaffold 2. Configure `docker-compose.snapify.yml` (3 containers on `alorig_net`) 3. Create `snapify_db` on shared PostgreSQL 4. Build multi-tenant models (Store, Product, Order, Category, Analytics) 5. Build WhatsApp Business API integration (webhook receiver, state machine onboarding) 6. Build server-rendered Django store templates (6 page types, 7 store templates) 7. Build AI content generation pipeline (5 stages via Celery) 8. Build React seller PWA dashboard (products, orders, analytics, settings) 9. Build React admin panel (store management, moderation, platform metrics) 10. Build SEO engine (programmatic city pages, schema markup, sitemap generator) 11. Integrate Cloudinary for image CDN 12. Configure Caddy routes for all 4 subdomains 13. Integrate JazzCash/EasyPaisa for Pro subscriptions 14. Deploy, test WhatsApp onboarding flow end-to-end 15. Monitor RAM — expected ~700 MB steady state --- ## 6. APP 3: ALORIG SITE BUILDER — Multi-Tenant Website Platform ### Product Summary AI-powered multi-tenant website builder. Dual runtime: Django (business logic/API) + Payload CMS (Node.js, content management/visual editing). Only app with a Node.js container alongside Django. ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | CMS | Payload CMS (Node.js) | Visual content editing, block-based page builder | | Node Runtime | Node.js 18+ | Payload CMS server | | AI | OpenAI GPT-4 / Claude | Content generation, design suggestions | ### Container Architecture (4 containers — exception with Node.js) | Container | Image | Role | Port | |-----------|-------|------|------| | `sitebuilder_backend` | sitebuilder-backend:latest | Django + Gunicorn (REST API, auth, billing, tenants) | 8016 | | `sitebuilder_payload` | sitebuilder-payload:latest | Payload CMS (Node.js, content editing, block rendering) | 8017 | | `sitebuilder_celery_worker` | sitebuilder-backend:latest | Celery worker (AI generation, site builds, deployments) | — | | `sitebuilder_celery_beat` | sitebuilder-backend:latest | Celery beat scheduler | — | ### Database - Database: `sitebuilder_db` on `alorig_postgres` - Redis prefix: `sitebuilder:`, Redis DB: 4 - Payload CMS: can share same PostgreSQL or use separate `sitebuilder_payload_db` ### Caddy Routes ``` alorig.com/builder → static React build (builder dashboard) api.alorig.com/builder → sitebuilder_backend:8016 (Django API) cms.alorig.com → sitebuilder_payload:8017 (Payload CMS) *.sites.alorig.com → rendered sites (wildcard) ``` ### Implementation Steps 1. Create GitHub repo `alorig-site-builder` with Django + Payload dual scaffold 2. Configure `docker-compose.sitebuilder.yml` (4 containers on `alorig_net`) 3. Create `sitebuilder_db` database 4. Build Django models (Tenant/Site, User, Subscription, Deployment) 5. Build Payload CMS configuration (block types, page schemas, media) 6. Build Django↔Payload sync layer (auth sharing, data bridge) 7. Build AI content generation pipeline 8. Build React dashboard (site management, templates, billing) 9. Configure Caddy routes including wildcard for rendered sites 10. Deploy, test multi-tenant site creation end-to-end 11. Monitor RAM — expected ~1.25 GB steady state --- ## 7. APP 4: OBSERVER OS — Consciousness/Behavioral Awareness Platform ### Product Summary Observer OS (0·i·G·8) — self-operating behavioral operating system. Four progressive symbolic modules (0: Dissolution → i: Identity → G: The Gate → 8: Infinity) guide users through observation of ego patterns via AI-powered journaling, pattern detection, ambient environment adaptation, and planetary alignment. NOT a meditation app — an architecture of awakening. ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | AI (Primary) | OpenAI GPT-4o | Text analysis, pattern detection, ambient generation, module transitions | | AI (Secondary) | Anthropic Claude | Paradox detection, reflective prompt generation | | TTS/Audio | OpenAI TTS / ElevenLabs | Ambient sound generation, optional voice responses | | Image Gen | Runware / Stable Diffusion | Ambient visual generation | | Ephemeris | Swiss Ephemeris (pyswisseph) | Planetary positions for alignment layer | ### Container Architecture (3 containers — standard) | Container | Image | Role | Port | |-----------|-------|------|------| | `observer_backend` | observer-backend:latest | Django + Gunicorn (REST API) | 8018 | | `observer_celery_worker` | observer-backend:latest | Celery worker (AI analysis, patterns, ambient refresh) | — | | `observer_celery_beat` | observer-backend:latest | Celery beat (pattern analysis, planetary updates, cleanup) | — | ### Database - Database: `observer_db` on `alorig_postgres` - Redis prefix: `observer:`, Redis DB: 5 ### Django App Structure | Directory | Purpose | |-----------|---------| | `auth/` | User model, anonymous auth, JWT | | `api/` | Base ViewSets, pagination, response format | | `modules/observer/` | Module state, journal, pattern endpoints | | `modules/ambient/` | Color state, sound state, planetary overlay | | `modules/system/` | Settings, AI config, prompt templates | | `business/patterns/` | PatternService, EgoLoopDetector, FlowAnalyzer, ContradictionEngine | | `business/modules/` | ModuleTransitionService, state machine, trigger evaluation | | `business/journal/` | JournalService, NLP processing, prompt generation | | `business/ambient/` | ColorEngine, SoundEngine, PlanetaryService | | `ai/` | AIEngine, function registry, providers (OpenAI, Anthropic) | | `ai/functions/` | AnalyzeJournal, DetectPatterns, GeneratePrompt, DetectParadox, GenerateAmbient, AssessTransition | | `tasks/` | Celery task definitions | ### Core Data Models | Model | Key Fields | Purpose | |-------|-----------|---------| | User | email (optional), current_module, preferences, anonymous_token | Anonymous-first account | | ModuleState | user_id, active_module (0/i/G/8), transition_signals, accumulated_score | Module tracking + transition readiness | | JournalEntry | user_id, text (encrypted), emotion_tag, module_at_time, ai_analysis_summary | Encrypted journal entries | | Pattern | user_id, pattern_type, label, frequency, last_occurrence, evidence_refs | Detected behavioral patterns | | StateLoop | user_id, loop_id, triggers, behaviors, resolution_state, occurrence_count | Ego loops: trigger → reaction → resolution | | Event | user_id, module, trigger_type, text_input, system_reaction | Granular event log | | AmbientState | user_id, current_palette, current_sound, planetary_context | Current ambient config | | PlanetarySnapshot | date, planetary_positions, major_transits, awareness_theme | Daily planetary data cache | | PromptTemplate | module, trigger_context, prompt_text, effectiveness_score | AI prompt templates per context | ### 4 Core Modules (0 → i → G → 8) | Module | Symbol | Role | |--------|--------|------| | Dissolution | 0 | Disengage the machinery of "I" — break reactive identification | | Identity | i | Surface and expose egoic patterning — mirror the constructed self | | The Gate | G | Trigger collapse of division between observer and observed | | Infinity | 8 | Sustain choiceless awareness and non-fragmented perception | ### Module Transitions (Automatic, Never Announced) | From → To | Trigger | |-----------|---------| | 0 → i | Emergence of habitual pattern, ego language, resistance to stillness | | i → G | Observer begins observing the observer — paradox arises | | G → 8 | Surrender — "I" loses center stage, ambient being replaces it | | 8 → 0 | Identity re-coagulates — gentle rhythmic restart | ### Ambient Color System | State | Palette | Module | |-------|---------|--------| | Calm / Presence | Deep indigo, soft violet, midnight blue | 8 (Infinity) | | Alert / Activation | Amber, warm gold, burnt orange | i (Identity) | | Stillness / Dissolution | Charcoal, muted slate, near-black | 0 (Dissolution) | | Threshold / Paradox | Silver-white, pale lavender, stark contrast | G (Gate) | | Agitation / Resistance | Desaturated tones, slight red warmth | Any (friction) | ### Privacy Architecture | Tier | Location | Encryption | |------|----------|-----------| | Tier 1 (Local Only) | Device storage | Device-level encryption | | Tier 2 (Encrypted Sync) | Cloud database | AES-256 at rest, TLS in transit | | Tier 3 (Ephemeral) | Cloud AI API | Processed and discarded, never stored | ### API Endpoints | Group | Base Path | |-------|-----------| | Auth | /api/v1/auth/ | | Module State | /api/v1/observer/module/ | | Journal | /api/v1/journal/ | | Patterns | /api/v1/patterns/ | | Ambient | /api/v1/ambient/ | | Dashboard | /api/v1/dashboard/ | | Chat | /api/v1/chat/ | | Settings | /api/v1/settings/ | ### Celery Tasks | Task | Schedule | |------|----------| | Pattern Analysis | Every 6 hours (active users) | | Module Transition Check | Every 2 hours (active users) | | Planetary Update | Daily at midnight | | Ambient Refresh | On state change or hourly | | Journal NLP Processing | On new entry (debounced 5 min) | | Data Cleanup | Weekly | ### Caddy Routes ``` observeros.app → static React build (web app) api.observeros.app → observer_backend:8018 (REST API) ``` ### Implementation Steps 1. Create GitHub repo `observer-os` with Django project scaffold 2. Configure `docker-compose.observer.yml` (3 containers on `alorig_net`) 3. Create `observer_db` database 4. Build Django models with encryption (JournalEntry text encrypted at rest) 5. Build anonymous auth system (no email required for core use) 6. Build 4-module state machine (ModuleTransitionService) 7. Build pattern detection engine (PatternService, EgoLoopDetector, FlowAnalyzer, ContradictionEngine) 8. Build journaling API with NLP processing pipeline 9. Build ambient environment system (ColorEngine, SoundEngine, PlanetaryService) 10. Integrate AI providers (OpenAI primary, Claude secondary) via function registry 11. Build React frontend (conversational chat + visual dashboard) 12. Build ambient components (color engine, sound player, planetary overlay) 13. Configure Caddy routes 14. Deploy, test module transition flow end-to-end 15. Monitor RAM — expected ~700 MB steady state --- ## 8. APP 5: ASTROTIMING — Planetary Hours Intelligence Engine ### Product Summary AstroTiming transforms ancient celestial timing wisdom (Al Saat by Kash Al Barni) into a modern API-powered productivity tool. Three layers: Layer 1 (Classical Planetary Hours), Layer 2 (Live Planetary Positions via Swiss Ephemeris), Layer 3 (Intelligence Engine — Timing Quality Score 0–100). Three products: consumer web app, developer API, premium scheduling. ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | Ephemeris | pyswisseph | Sub-arcsecond planetary position calculations | | Sunrise/Sunset | SunCalc / astronomical calc | Precise sunrise/sunset for planetary hour computation | | AI (optional) | OpenAI GPT-4o | Natural language timing recommendations | | Calendar | Google Calendar API / CalDAV | Premium scheduling integration | ### Container Architecture (3 containers — standard, lightest app) | Container | Image | Role | Port | |-----------|-------|------|------| | `astrotiming_backend` | astrotiming-backend:latest | Django + Gunicorn (REST API + consumer web) | 8020 | | `astrotiming_celery_worker` | astrotiming-backend:latest | Celery worker (ephemeris pre-computation, AI recommendations) | — | | `astrotiming_celery_beat` | astrotiming-backend:latest | Celery beat (daily planetary cache, calendar sync) | — | ### Database - Database: `astrotiming_db` on `alorig_postgres` - Redis prefix: `astrotiming:`, Redis DB: 6 ### Three-Layer Engine **Layer 1: Classical Planetary Hours (Al Saat)** - Deterministic, requires only location + date/time - Sunrise/sunset → 12 unequal daytime + 12 unequal nighttime hours (24 total) - Chaldean Order: Saturn → Jupiter → Mars → Sun → Venus → Mercury → Moon - Activity-planet mapping from Al Saat taxonomy - Works entirely offline **Layer 2: Live Planetary Positions (Swiss Ephemeris)** - Exact ecliptic longitude of all 7 classical planets - Dignities: domicile, exaltation, detriment, fall - Retrogrades, aspects (conjunction, sextile, square, trine, opposition) - Lunar phase, Moon sign, void-of-course periods - NASA JPL DE431 data: 13201 BCE–17191 CE, 0.1 arcsecond precision **Layer 3: Intelligence Engine (TQS)** - Timing Quality Score (0–100) for any activity at any moment - Forward search: scan upcoming hours/days, find optimal windows - Smart scheduler: generate optimized calendar from activities + priorities - Conflict detection: flag unfavorable windows, suggest alternatives ### TQS Scoring Model | Factor | Weight | |--------|--------| | Hour Ruler Match | 30% | | Day Ruler Harmony | 15% | | Planetary Dignity | 15% | | Lunar Condition | 15% | | Planetary Aspects | 15% | | Retrograde Status | 10% | Interpretation: 80–100 Excellent, 60–79 Good, 40–59 Neutral, 20–39 Unfavorable, 0–19 Avoid. ### Planet-Activity Mapping (Al Saat) | Planet | Domains | |--------|---------| | Sun (Shams) | Leadership, health, government, recognition | | Moon (Qamar) | Travel, social, domestic, emotional | | Mars (Mirrikh) | Physical action, competition, bold ventures | | Mercury (Utarid) | Writing, commerce, learning, technology | | Jupiter (Mushtari) | Business expansion, education, spiritual | | Venus (Zuhra) | Arts, relationships, beauty, social | | Saturn (Zuhal) | Organization, long-term projects, boundaries | ### Core Data Models | Model | Key Fields | Purpose | |-------|-----------|---------| | User | email, location (lat/lng), timezone, preferences | User with location | | Location | name, latitude, longitude, timezone, user_id | Saved locations | | ActivityCategory | planet, category_name, activities (JSON) | Al Saat activity-planet mapping | | TimingQuery | user_id, activity, location_id, datetime, tqs_score, breakdown (JSON) | Logged queries with scores | | ScheduleEntry | user_id, activity, preferred_window, assigned_window, tqs_score | Smart scheduler entries | | PlanetaryCache | date, location_hash, sunrise, sunset, planetary_hours (JSON), positions (JSON), aspects (JSON) | Pre-computed daily data | | APIKey | user_id, key_hash, tier (free/developer/premium), requests_today, rate_limit | Developer API key management | ### Pricing | Tier | Price | Features | |------|-------|---------| | Free (Consumer) | $0 | Web app: current hour, TQS for any activity, daily view | | Developer API | $9–49/month | REST API: TQS, forward search, bulk queries, webhooks | | Premium | $4.99/month | Smart scheduler, calendar sync, daily briefings, optimal window alerts | ### Celery Tasks | Task | Schedule | |------|----------| | `precompute_daily_planetary_data` | Daily 00:00 UTC | | `generate_daily_briefing` | Daily per user timezone (sunrise − 30min) | | `sync_user_calendars` | Every 30 min (premium users) | | `cleanup_old_queries` | Weekly | ### Caddy Routes ``` astrotiming.com → static React build (consumer web app) api.astrotiming.com → astrotiming_backend:8020 (REST API + developer API) ``` ### Implementation Steps 1. Create GitHub repo `astrotiming` with Django project scaffold 2. Install `pyswisseph` and verify ephemeris calculations 3. Configure `docker-compose.astrotiming.yml` (3 containers on `alorig_net`) 4. Create `astrotiming_db` database 5. Build Layer 1: Classical planetary hours engine (Al Saat ruleset) 6. Build Layer 2: Swiss Ephemeris integration (positions, dignities, aspects, retrogrades, lunar) 7. Build Layer 3: TQS scoring engine combining Layer 1 + Layer 2 8. Build forward search and smart scheduler algorithms 9. Build Django models, REST API endpoints 10. Build developer API with key management and rate limiting 11. Build React frontend (daily view, activity search, score display) 12. Configure Caddy routes 13. Implement PlanetaryCache pre-computation pipeline 14. Deploy, validate TQS against known Al Saat test cases 15. Monitor RAM — expected ~400 MB steady state --- ## 9. APP 6: ASMS PHASE 1 — School Management System ### Product Summary Alorig School Management System (ASMS) Phase 1 — pilot deployment for 74 schools in Pakistan. Foundation platform: student/guardian management, multi-school tenancy, admissions, gradebook, attendance, courses, RBAC, LMS core. Phase 1 scope only (700–1,030 hours); Advanced Modules & Intelligence Layer are Phase 2+. ### Tech Stack Additions | Addition | Technology | Purpose | |----------|-----------|---------| | Multi-Tenant | Head Office → Branch → School hierarchy | 74-campus data isolation | | RBAC | Django permission groups | 10 user roles | | Attendance | GPS + geo-fence (Phase 2) | 100m radius per school | | WhatsApp | WhatsApp Business API (Phase 2) | Parent notifications | | AI (Phase 2) | Predictive analytics, adaptive assessment | At-risk identification | ### Container Architecture (3 containers — standard) | Container | Image | Role | Port | |-----------|-------|------|------| | `asms_backend` | asms-backend:latest | Django + Gunicorn (REST API) | 8022 | | `asms_celery_worker` | asms-backend:latest | Celery worker (reports, data import, notifications) | — | | `asms_celery_beat` | asms-backend:latest | Celery beat (attendance reports, grade calculations) | — | ### Database - Database: `asms_db` on `alorig_postgres` - Redis prefix: `asms:`, Redis DB: 7 ### Multi-School Tenant Architecture - 3-level hierarchy: Head Office → Branch (regional) → School (campus) - `SchoolBaseModel` — FK to School with tenant isolation - `SchoolModelViewSet` — queries scoped to user's school(s) - HO Admin sees all; Branch Admin sees branch schools; Principal sees own school only ### Phase 1 Foundation Modules | Module | Key Models | |--------|-----------| | Student & Guardian Management | Student, Guardian, Enrollment, Transfer | | Multi-School Tenant | HeadOffice, Branch, School, SchoolUser | | Admissions & Registration | Application, AdmissionLevel, AdmissionStep | | Gradebook & Report Cards | Grade, MarkingPeriod, Transcript, ReportCard | | Discipline & Behavior | Infraction, DisciplineAction, BehaviorLog | | Attendance (Base) | Attendance, AttendanceRecord, AbsenteeFlag | | Courses & Scheduling | Course, ClassSection, TeacherAssignment, Schedule | | RBAC (10 Roles) | Role, Permission, UserSchoolAccess | | LMS Core | Curriculum, LessonPlan, Quiz, Question, LearningOutcome | ### 10 User Roles HO Admin, Branch Admin, Principal, Vice Principal, Teacher, Class Teacher, Accountant, Parent, Student, Support Staff ### Caddy Routes ``` schools.alorig.com → static React build (web app) api.schools.alorig.com → asms_backend:8022 (REST API) ``` ### Implementation Steps 1. Create GitHub repo `asms` with Django project scaffold 2. Configure `docker-compose.asms.yml` (3 containers on `alorig_net`) 3. Create `asms_db` database 4. Build multi-tenant hierarchy models (HeadOffice, Branch, School) 5. Build RBAC system (10 roles with granular permissions) 6. Build Student & Guardian management module 7. Build Admissions workflow module 8. Build Courses & Scheduling module with conflict detection 9. Build Attendance module (daily homeroom/class, absence tracking) 10. Build Gradebook module (standards-based grading, report cards, transcripts) 11. Build Discipline & Behavior tracking module 12. Build LMS core (curriculum, lesson plans, quiz engine) 13. Build React frontend (role-based dashboards, CRUD screens, reports) 14. Build REST API layer for all modules 15. Seed with pilot school data (5 schools initially) 16. Deploy, run pilot testing with 5 schools 17. Monitor RAM — expected ~600 MB steady state --- ## 10. POST-DEPLOYMENT MONITORING ### Immediate (First 24 Hours After Each App) 1. `docker stats` — verify container RAM matches budget 2. PostgreSQL: `SELECT count(*) FROM pg_stat_activity;` — check connection count 3. Redis: `redis-cli INFO memory` — verify key prefix isolation 4. Caddy routes — verify SSL and domain routing 5. Smoke tests — login, core functionality, API responses ### Ongoing (First Week) 1. Monitor RAM over full business cycle 2. Check Celery task queue depths — no backlogs 3. Verify inter-app isolation (no Redis key collisions, no DB cross-contamination) 4. Test under expected concurrent user load ### Upgrade Triggers | Condition | Action | |-----------|--------| | Steady-state RAM > 13 GB | Upgrade to KVM 8 or split heaviest app | | OOM kills on any container | Investigate — reduce workers or split | | PostgreSQL connections > 80 | Add PgBouncer connection pooling | | Redis memory > 2 GB | Review TTLs, add eviction policies | | Celery queue > 1000 pending | Add worker or split queues | --- ## 11. ACCEPTANCE CRITERIA - [ ] Each of the 6 apps has: containers, database, Redis config, Caddy routes, implementation steps - [ ] Deployment order specified with rationale and triggers - [ ] Post-deployment monitoring protocol documented - [ ] Resource budget per app with upgrade triggers - [ ] Docker compose naming convention established - [ ] Each app references its source blueprint document - [ ] Exception patterns (Psydge WebSocket, Site Builder Node.js) clearly documented - [ ] Port assignments verified — no conflicts across all apps - [ ] Redis DB numbers verified — no conflicts across all apps - [ ] All Caddy routes listed — no domain conflicts - [ ] Total steady-state RAM estimate ~10.7 GB within 16 GB budget --- ## 12. CLAUDE CODE INSTRUCTIONS ### Context Requirements 1. Read Phase 0 infrastructure docs — understand shared services configuration 2. Read IGNY8 docker-compose files — understand existing port/Redis/DB allocation 3. Read each app blueprint document for deep-dive implementation details 4. Verify port and Redis DB assignment maps against all existing compose files ### Execution Order ``` For each app (in deployment order): 1. Create GitHub repo with Django scaffold 2. Create docker-compose.{app}.yml on alorig_net 3. Create database on shared PostgreSQL 4. Build models + migrations 5. Build app-specific business logic 6. Build REST API endpoints 7. Build React frontend (static build for Caddy) 8. Configure Caddy routes 9. Deploy + smoke test 10. Monitor RAM for 24 hours 11. Proceed to next app only when stable ``` ### Critical Rules 1. **One app at a time** — deploy sequentially, monitor between each 2. **Shared infrastructure** — every app joins `alorig_net`, uses shared PG/Redis 3. **Database per app** — separate database name on shared PostgreSQL instance 4. **Redis per app** — separate DB number + key prefix 5. **Port uniqueness** — use assigned ports from port map (no conflicts) 6. **Static frontend** — React builds served by Caddy (no frontend containers) 7. **Exception containers** — only Psydge (Channels) and Site Builder (Payload) get extra containers 8. **RAM monitoring** — check after each app, stop if approaching 13 GB 9. **Compose naming** — `docker-compose.{appname}.yml` convention ### Cross-References | Doc | Relationship | |-----|-------------| | 00-MASTER | Phase 0 infrastructure that all apps run on | | 00A Server + Docker | Shared services, `alorig_net` network, Caddy config | | 00B Database Schema | PostgreSQL setup, per-app databases | | 00C Caddy Configuration | Reverse proxy rules, SSL, domain routing | | 04A–04C | IGNY8 must be stable (Phase 4 complete) before Phase 5 begins |