Files
igny8/v2/V2-Execution-Docs/PHASE-5-BUILD-PLAN.md
IGNY8 VPS (Salman) 0570052fec 1
2026-03-23 17:20:51 +00:00

50 KiB
Raw Blame History

Phase 5 Build Plan — Multi-App Deployment (1 Doc)

Purpose: This is the single instruction set for Claude Code to build the Phase 5 execution document (05-other-apps-deployment.md). This doc covers deploying all 6 remaining Alorig apps on the shared infrastructure established in Phase 0.


CRITICAL BASELINE RULES

Before writing the doc, internalize these infrastructure-verified facts:

Shared Infrastructure (Established in Phase 0)

  • VPS: Hostinger KVM 4 — 4 vCPU, 16GB RAM, 200GB NVMe
  • Docker Network: alorig_net (external, all apps join this network)
  • Shared Services (alorig-infra docker-compose.yml):
    • alorig_postgres — PostgreSQL 16, separate database per app
    • alorig_redis — Redis 7, app-specific key prefixes (psydge:, snapify:, etc.)
    • alorig_caddy — Caddy 2, reverse proxy + SSL via Cloudflare DNS challenge
    • portainer — Portainer CE, Docker GUI for managing 25+ containers
    • flower — mher/flower, Celery monitoring (on-demand)
  • DNS: All domains managed in Cloudflare (free tier), wildcard A records to VPS IP
  • GitHub: All repos on GitHub (private), one repo per app
  • IGNY8 already running: Production + staging on new server (Phase 04 complete)

Per-App Container Pattern (Standard)

Every Django app follows this identical structure:

  • {appname}_backend — Django + Gunicorn (WSGI) or Daphne (ASGI)
  • {appname}_celery_worker — Background task processing
  • {appname}_celery_beat — Scheduled task scheduling
  • React frontend built as static files → served via alorig_caddy (NO separate frontend container)

Exceptions:

  • Psydge: Adds 4th container psydge_channels for Django Channels (ASGI/WebSocket)
  • Alorig Site Builder: Adds sitebuilder_payload container for Node.js/Payload CMS alongside Django containers

Alorig Tech Stack (Shared Across All Apps)

Layer Technology Version
Backend Django 5.15.2+
API Django REST Framework 3.15+
Database PostgreSQL 16 (shared instance)
Cache/Broker Redis 7 (shared instance)
Task Queue Celery 5.3+
Frontend React + TypeScript React 19, TS 5+
State Mgmt Zustand 45
Styling Tailwind CSS 34
Build Tool Vite 56
Containerization Docker + Docker Compose External network (alorig_net)
Reverse Proxy Caddy 2 Cloudflare DNS challenge SSL

Resource Budget (from Alorig Master Plan)

Component RAM Estimate Notes
Shared infra (PG + Redis + Caddy + Portainer) ~2.5 GB PostgreSQL serving 7 databases is biggest consumer
IGNY8 (prod + staging) ~1.8 GB Already running
Psydge ~1.75 GB WebSockets hold memory per connection; heaviest at 30 users
Snapify ~700 MB Standard CRUD with image processing
Observer OS ~700 MB AI pattern detection is external API calls
Alorig Site Builder ~1.25 GB Django + Payload/Node.js dual runtime
AstroTiming ~400 MB Lightest app. Brief CPU bursts for ephemeris
ASMS Phase 1 ~600 MB Pilot scale, basic modules only
OS + Docker overhead ~1.0 GB
TOTAL STEADY STATE ~10.7 GB / 16 GB ~5 GB headroom for spikes

Upgrade trigger: Steady-state RAM consistently above 13 GB, or OOM kills on any container. Options: upgrade to KVM 8, or split Psydge to its own KVM 1.

Source of Truth

  • Start the doc with: **Source of Truth:** Alorig-Master-Plan-v1.md + individual app blueprints
  • Infrastructure decisions from Alorig Master Plan override individual app docs

DOC STRUCTURE STANDARD

The 05-other-apps-deployment.md doc MUST follow this structure:

# Phase 5 — Multi-App Deployment
**Source of Truth:** Alorig-Master-Plan-v1.md + individual app blueprints
**Version:** 1.0
**Date:** 2026-03-23

## 1. Current State
## 2. What to Build
## 3. Shared Deployment Pattern
## 4. App 1: Psydge
## 5. App 2: Snapify
## 6. App 3: Alorig Site Builder
## 7. App 4: Observer OS
## 8. App 5: AstroTiming
## 9. App 6: ASMS Phase 1
## 10. Post-Deployment Monitoring
## 11. Acceptance Criteria
## 12. Claude Code Instructions

DEPLOYMENT ORDER & RATIONALE

The apps deploy in this specific order, one at a time. Monitor RAM after each before proceeding to next.

# App Why This Order Trigger
1 Psydge Most complex (WebSockets, Django Channels, real-time broker connection). Deploy early to validate server under real load. After IGNY8 stable on new server
2 Snapify Standard Django stack. Good validation that multi-app pattern works. WhatsApp integration adds external service validation. After Psydge stable
3 Alorig Site Builder Dual runtime (Django + Payload CMS/Node.js). Tests Node.js container alongside Django stack. After Snapify stable
4 Observer OS Standard Django + React. Light resource requirements initially. Planetary alignment layer shares ephemeris logic with AstroTiming. When ready
5 AstroTiming Lightest app. Minimal containers needed. Can share pyswisseph ephemeris data cache with Observer OS. When ready
6 ASMS Phase 1 School management MVP. Basic modules for pilot deployment at 74 Schools. When ready

APP 1: PSYDGE — AI Trading Discipline Platform

Product Summary

Psydge (Psychological Edge) is a web-based trading discipline and execution platform. It sits between the trader and their MT4/MT5 broker via MetaApi, enforcing hard-coded discipline rules that structurally prevent self-destructive trading behavior. Two products under one platform: Psydge Core (discipline engine) and Vista Strategies (pre-defined strategy suite).

Source Documents

  • Psydge/Psydge_Technical_Documentation.pdf (26 pages)
  • Psydge/psydge-project/ (project scaffold if exists)

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
Real-Time Django Channels + Redis WebSocket for live price feeds, position updates, gate status, AI messages
Broker Bridge MetaApi (Cloud) MT4/MT5 connectivity, order execution, position polling via REST + WebSocket
AI Claude API (Anthropic) Trade supervision, behavioral prediction, pre-entry validation, session debriefs
Charts TradingView Lightweight Charts Live candlestick charts, M1 through D1 timeframes
Billing Stripe Subscription management (Psydge Core + Vista Strategies tiers)

Container Architecture (4 containers — exception to standard 3)

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 name: psydge_db on shared alorig_postgres
  • Redis key prefix: psydge:
  • Redis DB: 2 (separate from IGNY8's DB 0 and staging DB 1)

Core Data Models

Model Storage Key Fields Purpose
User PostgreSQL id, email, timezone, broker_credentials (encrypted), subscription_tier User account
BrokerConnection PostgreSQL + Redis user_id, broker, server, account_number, connection_status MT4/MT5 connection state
DisciplineConfig PostgreSQL user_id, loss_lock_r, profit_lock_r, cooldown_hours, max_risk_pct, session_hours, symbol_whitelist Per-user discipline parameters
GateState Redis user_id → hash: buffer_go, buffer_whitelist, buffer_session, buffer_equity, buffer_cooldown, buffer_risk Real-time gate buffer values (sub-ms reads)
Trade PostgreSQL id, user_id, symbol, direction, entry, sl, tp, lot, risk_pct, r_result, strategy, status, opened_at, closed_at Complete trade record
Violation PostgreSQL id, user_id, violation_code, attempted_action, timestamp, gate_state_snapshot Every blocked trade attempt
DisciplineScore PostgreSQL user_id, date, score, metric_breakdown (JSON) Daily discipline score history
ReflectionEntry PostgreSQL user_id, date, session_notes, ai_prompt, ai_summary Session journal entries
AIInteraction PostgreSQL id, user_id, trade_id, role (supervisor/validator/predictor), input_context, output, timestamp AI call history for audit
BehavioralPattern PostgreSQL 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 None (persistent) All 6 buffer values
psydge:cooldown:{user_id} String Cooldown duration Timestamp when cooldown expires
psydge:session_r:{user_id} String End of day Cumulative R for current session
psydge:positions:{user_id} Hash None (live sync) Open position data from MetaApi
psydge:prices:{symbol} String 5 seconds Latest bid/ask from MetaApi stream
psydge:lock:{user_id} String End of session Session lock flag when equity guard triggers

Caddy Routes

psydge.com → static React build (frontend)
api.psydge.com → psydge_backend:8012 (REST API)
ws.psydge.com → psydge_channels:8013 (WebSocket)

Key Discipline Engine Components

  • 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 (Non-Negotiable): Loss Lock (-2R daily), Profit Lock (+3R daily), 4hr Cooldown, 1.0% risk per trade, London+NY sessions only, Psydge web panel only execution surface
  • Violation Response Levels: Level 1 (Alert) → Level 2 (Overlay) → Level 3 (Blackout) → Level 4 (Session Lock)
  • Discipline Score: 0100 weighted composite: Rule Compliance 25%, Session Discipline 15%, Risk Management 15%, Patience Score 15%, Post-Win Control 15%, Cooldown Respect 10%, Revenge Prevention 5%

4 AI Roles (All via Claude API + Celery)

Role Trigger Input Output
Trade Supervisor Trade hits TP1 or R threshold Symbol, entry, SL/TP, duration, delta, trend, TM score scale / hold / tighten_sl / exit
Pre-Entry Validator User initiates new trade (if enabled) Setup context, TM score, multi-TF alignment, recent trade history approve / stand_down + reasoning
Behavioral Predictor Session start + post-trade User's violation history, trade patterns, time patterns, win/loss sequence Risk alerts + enforcement tightening suggestions
Session Debrief Session end All trades, violations, discipline score, behavioral data Natural language session summary + improvement insights

Vista Strategy Suite (4 Tiers)

Strategy Timeframe Style Target R
Scalper Engine M1M5 Delta breakouts, microstructure 1.52R
Intraday Momentum M15H1 Trend trades with intelligent scaling 27R
Swing Position H1D1 HTF structure, trend reclaim 512R
Vault Trail H4D1 Receives winning handoffs from other strategies 1520R

6 Proprietary Indicators

NDNS (Net Delta/Net Strength), SV (Structure Validation), TM (Trend-Momentum), MOM (Momentum Oscillator), FHS (Fractal/Harmonic Structure), HAMFIST (Harmonic + Fib Integrated)

Celery Tasks

Task Schedule Function
calculate_discipline_score End of each trading session Compute daily discipline score from all trade/violation data
detect_behavioral_patterns After every violation Update BehavioralPattern records, check for new patterns
ai_session_debrief Session end Generate AI session summary via Claude API
sync_metaapi_positions Every 5 seconds (per connected user) Pull position/equity data from MetaApi WebSocket
weekly_behavioral_report Sunday 23:00 UTC Generate weekly AI behavioral report per user

Implementation Steps (for 05 doc)

  1. Create GitHub repo psydge with Django project scaffold
  2. Configure docker-compose.psydge.yml (4 containers on alorig_net)
  3. Create psydge_db database 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 usage — expected ~1.75 GB steady state

APP 2: SNAPIFY — Pakistani E-Commerce Platform

Product Summary

Snapify.pk is a mobile-first, AI-powered e-commerce platform enabling Pakistani micro-sellers to create online stores via WhatsApp. Three-interface architecture: buyer-facing store (server-rendered Django + Tailwind for SEO), seller dashboard (React 19 PWA), admin panel (React 19 SPA). Target: 5M+ informal sellers, breakeven at ~150 paying users.

Source Documents

  • Snapify/Snapify-Blueprint-v3-Complete.pdf (34 pages)

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
WhatsApp WhatsApp Business Cloud API Onboarding bot, order notifications, seller commands
Image CDN Cloudinary (free tier + scale) Image optimization, responsive srcset, WebP
File Storage DigitalOcean Spaces (S3-compatible) Product images, generated assets, backups
Social APIs Meta Graph API (FB + Instagram) Auto-posting, story creation for Pro sellers
AI Engine OpenAI GPT-4 API + Whisper API Content generation, image analysis, speech-to-text (Urdu/Punjabi)
Email SendGrid Transactional emails, seller notifications
Search PostgreSQL Full-Text + pg_trgm Product search, store discovery
Monitoring Sentry + custom middleware Error tracking, performance monitoring
Payment JazzCash / EasyPaisa / Stripe (future) Pakistani payment gateways

Container Architecture (3 containers — standard pattern)

Container Image Role Port
snapify_backend snapify-backend:latest Django + Gunicorn (serves REST API + server-rendered store pages) 8014
snapify_celery_worker snapify-backend:latest Celery worker (AI processing, image optimization, social posting, SEO gen)
snapify_celery_beat snapify-backend:latest Celery beat (sitemap regen, hub page regen, analytics aggregation)

Note: Buyer-facing store is server-rendered Django templates (NOT React) — critical for SEO on 3G connections. Seller dashboard and admin panel are React builds served as static files via Caddy.

Database

  • Database name: snapify_db on shared alorig_postgres
  • Redis key prefix: snapify:
  • Redis DB: 3

Three-Interface Architecture

Interface Users Technology URL
Buyer-Facing Store Buyers / public Server-rendered Django + Tailwind CSS snapify.pk/store-name
Seller Dashboard Store owners / sellers React 19 PWA (installable on phone) app.snapify.pk
Admin Panel Alorig team / support React 19 internal SPA admin.snapify.pk

Core Data Models (Key Entities)

Model Key Fields Purpose
Store id, seller_id, name, slug, city, category, custom_domain, template, subscription_tier, is_verified Multi-tenant store entity
Product id, store_id, title, description, price, images (JSON), category_id, variants (JSON), is_active, seo_meta Product listing
Order id, store_id, buyer_name, buyer_phone, products (JSON), total, status (pending/confirmed/shipped/delivered/cancelled), tracking_number WhatsApp-native order lifecycle
Category id, store_id, name, slug, product_count Store-level product categories
Analytics id, store_id, page_type, page_slug, visitor_ip_hash, referrer, city, timestamp Per-pageview analytics
Subscription id, store_id, plan (free/pro), started_at, expires_at, payment_method Seller subscription
Post id, store_id, platform, content, image_url, scheduled_at, status, engagement_metrics Social auto-posting records
WhatsAppSession id, store_id, phone_hash, state, last_message_at Onboarding conversation state machine

Multi-Tenant Architecture

  • StoreBaseModel — FK to Store with auto-assignment (equivalent to IGNY8's SiteSectorBaseModel)
  • StoreModelViewSet — all queries scoped to store
  • StoreMiddleware — resolves tenant from URL path (snapify.pk/store) or custom domain lookup
  • Custom domain support: buyer visits silkhouse.pk → CNAME to snapify.pk → StoreMiddleware resolves via custom_domain field

AI Pipeline (5 Stages via Celery)

Stage Input Output Technology
Image Analysis Product photos Category, color, material, style detection GPT-4 Vision API
Voice Processing WhatsApp voice notes Structured text (product, price, description) Whisper API + custom parser
Content Generation Product metadata + category Title, description, bullets, meta tags GPT-4 with retail prompts
SEO Optimization Generated content + city data City-specific landing pages, schema markup Custom SEO templates + GPT
Social Content Product images + AI content Post-ready images with overlays and CTAs Pillow image engine + GPT captions

Store Page Types (Server-Rendered Django Templates)

Page Type URL Pattern Rendering
Store Homepage snapify.pk/store-name Django template, product grid, category filters
Product Detail snapify.pk/store-name/product-slug Full product layout with Schema.org markup
Category Page snapify.pk/store-name/category-slug Filtered product grid
City Landing (Pro) snapify.pk/store-name/delivery-to-lahore Programmatically generated, geo-targeted copy
Store About snapify.pk/store-name/about Seller info, trust signals, verified badge
Category Hub (Platform) snapify.pk/best-clothing-stores-punjab Aggregated cross-store listings

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)

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 panel, IP-restricted)

Pricing

Plan Price Limits
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 Function
process_whatsapp_webhook On webhook receipt Parse incoming WhatsApp messages, route to handler
generate_product_content On product photo upload AI image analysis + content generation pipeline
generate_city_pages Weekly (Pro stores) Programmatic city landing page generation
regenerate_sitemap Daily 2 AM Per-store XML sitemap regeneration
regenerate_hub_pages Weekly Sunday 3 AM Platform-level category hub page regeneration
social_auto_post Per schedule Post to FB/IG via Meta Graph API
invalidate_store_cache On product/store change Clear Redis-cached rendered HTML pages

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 database 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 payment for Pro subscriptions
  14. Deploy, test WhatsApp onboarding flow end-to-end
  15. Monitor RAM usage — expected ~700 MB steady state

APP 3: ALORIG SITE BUILDER — Multi-Tenant Website Platform

Product Summary

AI-powered multi-tenant website builder platform. Dual runtime architecture with Django handling business logic/API and Payload CMS (Node.js) handling content management and visual editing. This is the only app with a Node.js container alongside Django.

Source Documents

  • Alorig Site Builder/Alorig-Site-Builder-Blueprint.docx

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
CMS Payload CMS (Node.js) Visual content editing, block-based page builder
Node Runtime Node.js 18+ Payload CMS server alongside Django
AI OpenAI GPT-4 / Claude AI-powered 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, tenant management) 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 name: sitebuilder_db on shared alorig_postgres
  • Redis key prefix: sitebuilder:
  • Redis DB: 4
  • Payload CMS: Can share same PostgreSQL database 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 usage — expected ~1.25 GB steady state

APP 4: OBSERVER OS — Consciousness/Behavioral Awareness Platform

Product Summary

Observer OS (0·i·G·8) is a 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 layers. NOT a meditation app — it's an architecture of awakening.

Source Documents

  • oigate/Observer-OS-Project-Specification-v1.pdf (34 pages)
  • oigate/site/ (project scaffold if exists)

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
AI (Primary) OpenAI GPT-4o Text analysis, pattern detection, ambient generation, module transitions
AI (Secondary) Anthropic Claude Nuanced paradox detection, reflective prompt generation
TTS/Audio OpenAI TTS / ElevenLabs Ambient sound generation, optional voice responses
Image Gen Runware / Stable Diffusion Ambient visual generation, thumbnail creation
Ephemeris Swiss Ephemeris (pyswisseph) or AstroAPI Planetary position data for alignment layer
Push FCM/APNS Push notifications (web + future mobile)
Mobile (Phase 2) React Native or Flutter iOS + Android (future)

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, pattern detection, ambient refresh)
observer_celery_beat observer-backend:latest Celery beat (scheduled pattern analysis, planetary updates, data cleanup)

Database

  • Database name: observer_db on shared alorig_postgres
  • Redis key prefix: observer:
  • Redis DB: 5

Django App Structure

Directory Purpose Contents
auth/ Authentication User model, anonymous auth, JWT, account context middleware
api/ API infrastructure Base ViewSets, authentication classes, pagination, response format
modules/observer/ Observer module API Module state endpoints, journal API, pattern API, dashboard API
modules/ambient/ Ambient environment API Color state, sound state, planetary overlay endpoints
modules/system/ System configuration Settings, AI model config, prompt templates
business/patterns/ Pattern detection services PatternService, EgoLoopDetector, FlowAnalyzer, ContradictionEngine
business/modules/ Module transition logic ModuleTransitionService, state machine, trigger evaluation
business/journal/ Journaling services JournalService, NLP processing, prompt generation
business/ambient/ Ambient environment ColorEngine, SoundEngine, PlanetaryService
ai/ AI engine AIEngine, function registry, providers (OpenAI, Anthropic), model registry
ai/functions/ AI function implementations AnalyzeJournal, DetectPatterns, GeneratePrompt, DetectParadox, GenerateAmbient, AssessTransition
tasks/ Celery task definitions PatternAnalysisTask, ModuleTransitionTask, PlanetaryUpdateTask, AmbientRefreshTask

Core Data Models

Model Key Fields Purpose
User id, email (optional), created_at, current_module, preferences, anonymous_token Anonymous-first user account
ModuleState user_id, active_module (0/i/G/8), entered_at, transition_signals, accumulated_score Tracks active module and transition readiness
JournalEntry user_id, text (encrypted), emotion_tag, timestamp, module_at_time, ai_analysis_summary Encrypted journal entries with optional AI analysis
Pattern user_id, pattern_type, label, frequency, last_occurrence, first_detected, evidence_refs Detected behavioral patterns across all input channels
StateLoop user_id, loop_id, triggers, behaviors, resolution_state, occurrence_count Ego loops: trigger → reaction → resolution tracking
Event user_id, timestamp, module, trigger_type, text_input, system_reaction Granular event log for behavioral analysis
AmbientState user_id, current_palette, current_sound, planetary_context, last_updated Current ambient environment configuration
PlanetarySnapshot date, planetary_positions, major_transits, awareness_theme Daily planetary data cache for alignment layer
PromptTemplate module, trigger_context, prompt_text, usage_count, effectiveness_score AI prompt templates per module and context
SystemConfig key, value, category Global system configuration (AI models, feature flags)

4 Core Modules (0 → i → G → 8)

Module Symbol Role AI Processing
Dissolution 0 Disengage the machinery of "I" — break reactive identification NLP analysis for identity-reinforcement patterns, ambient adaptation
Identity i Surface and expose egoic patterning — mirror the constructed self Longitudinal pattern recognition (2-4 weeks), ego-pattern classification, dynamic prompt generation
The Gate G Trigger collapse of division between observer and observed Contradiction detection, paradox generation, context-aware silence
Infinity 8 Sustain choiceless awareness and non-fragmented perception Flow state detection, ambient adaptation, self-obsolescence logic

Module Transition Logic (Automatic, Never Announced)

From → To Trigger User Experience
0 → i Emergence of habitual pattern, ego language, or resistance to stillness Prompts shift from silence to reflection; journal prompts appear
i → G Observer begins observing the observer — paradox or deep contradiction arises Interface becomes more minimal; paradox questions surface
G → 8 Surrender occurs — "I" loses center stage, replaced by ambient being System recedes; ambient environment takes over; almost no text
8 → 0 Identity re-coagulates or new life loop forms Gentle restart — not regressive, but rhythmic; cycle begins again

Ambient Environment System

Color System:

State Color Palette Module Alignment
Calm / Presence Deep indigo, soft violet, midnight blue Module 8 (Infinity)
Alert / Activation Amber, warm gold, burnt orange Module i (Identity)
Stillness / Dissolution Charcoal, muted slate, near-black Module 0 (Dissolution)
Threshold / Paradox Silver-white, pale lavender, stark contrast Module G (Gate)
Agitation / Resistance Desaturated tones, slight red warmth Any module (friction detected)

Privacy Architecture (Foundational, Not Feature)

Tier Location Data Type Encryption
Tier 1 (Local Only) Device storage Journal entries, emotion tags, raw behavioral data Device-level encryption
Tier 2 (Encrypted Sync) Cloud database Pattern summaries, module state, preferences, anonymized loop data AES-256 at rest, TLS in transit
Tier 3 (Ephemeral) Cloud AI API Anonymized text snippets for NLP processing Processed and discarded, never stored

API Endpoint Structure

Endpoint Group Base Path Key Endpoints
Auth /api/v1/auth/ register, login, anonymous-login, token-refresh, delete-account
Module State /api/v1/observer/module/ current-state, transition-history, signal-log
Journal /api/v1/journal/ create, list, export, delete-all
Patterns /api/v1/patterns/ list, detail, loops, flow-states, contradictions
Ambient /api/v1/ambient/ current-state, update-palette, update-sound, planetary-context
Dashboard /api/v1/dashboard/ flow-summary, module-view, pattern-overview
Chat /api/v1/chat/ send-message, get-prompt, silence-mode
Settings /api/v1/settings/ preferences, notifications, privacy, data-export

Celery Tasks

Task Queue Schedule Function
Pattern Analysis analysis Every 6 hours (active users) Process accumulated behavioral data, update Pattern records
Module Transition Check transitions Every 2 hours (active users) Evaluate transition signals, trigger module shifts if thresholds met
Planetary Update planetary Daily at midnight Pull ephemeris data, generate awareness themes, cache snapshot
Ambient Refresh ambient On state change or hourly Recalculate color/sound environment based on current signals
Journal NLP Processing analysis On new entry (debounced 5 min) Run AI analysis on journal entry, update pattern data
Data Cleanup maintenance Weekly Purge ephemeral AI data, compress old event logs, update aggregates

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 field encrypted at rest)
  5. Build anonymous auth system (no email required for core functionality)
  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 (dual interface: 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 usage — expected ~700 MB steady state

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-layer architecture: Layer 1 (Classical Planetary Hours), Layer 2 (Live Planetary Positions via Swiss Ephemeris), Layer 3 (Intelligence Engine with Timing Quality Score 0100). Three products: consumer web app, developer API, premium scheduling layer.

Source Documents

  • Astro Timing/AstroTiming-System-Blueprint.pdf (5+ pages)

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
Ephemeris pyswisseph (Python Swiss Ephemeris bindings) Sub-arcsecond planetary position calculations
Sunrise/Sunset SunCalc or astronomical calculation Precise sunrise/sunset for planetary hour computation
AI (optional) OpenAI GPT-4o Natural language timing recommendations, scheduling suggestions
Calendar Google Calendar API / CalDAV Premium scheduling layer 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 data cache, user calendar sync)

Note: AstroTiming is the lightest app (~400 MB). Ephemeris calculations are CPU-burst (brief) but the pyswisseph library uses zero external dependencies — all calculations are local.

Database

  • Database name: astrotiming_db on shared alorig_postgres
  • Redis key prefix: astrotiming:
  • Redis DB: 6

Three-Layer Engine Architecture

Layer 1: Classical Planetary Hours (Al Saat Ruleset)

  • Deterministic. Requires only geographic location + date/time
  • Sunrise/sunset → 12 unequal daytime + 12 unequal nighttime planetary hours (24 total)
  • Chaldean Order assignment: Saturn → Jupiter → Mars → Sun → Venus → Mercury → Moon
  • Day ruler = first hour ruler
  • Activity-planet mapping from Al Saat's complete taxonomy
  • Works entirely offline, zero external dependencies

Layer 2: Live Planetary Positions (Swiss Ephemeris)

  • Exact ecliptic longitude of all 7 classical planets at any given moment
  • Planetary dignities: domicile, exaltation, detriment, fall
  • Retrograde status
  • Planetary aspects: conjunction, sextile, square, trine, opposition
  • Lunar phase and Moon sign
  • Moon void-of-course periods
  • NASA JPL DE431 data: 13201 BCE to 17191 CE, 0.1 arcsecond precision

Layer 3: Intelligence Engine (Scoring & Recommendations)

  • Timing Quality Score (TQS): 0100 composite score for any activity at any moment
  • Forward Search: Given an activity, scan upcoming hours/days and find optimal windows
  • Smart Scheduler: Given user activities + priorities, generate optimized weekly/monthly calendar
  • Conflict Detection: Flag activities in unfavorable windows with suggested alternatives

TQS Scoring Model

Factor Weight Description
Hour Ruler Match 30% Does the planetary hour ruler align with the activity? (Al Saat mapping)
Day Ruler Harmony 15% Does the day ruler support or conflict with the hour ruler?
Planetary Dignity 15% Is the hour ruler in domicile/exaltation (boost) or detriment/fall (penalty)?
Lunar Condition 15% Moon phase, sign, void-of-course status, aspects to hour ruler
Planetary Aspects 15% Major aspects between hour ruler and benefics/malefics
Retrograde Status 10% Is the hour ruler or key planet for the activity retrograde?

Score interpretation: 80100 Excellent, 6079 Good, 4059 Neutral, 2039 Unfavorable, 019 Avoid.

Planet-Activity Mapping (Core Ruleset from Al Saat)

Planet Arabic Domains
Sun (Shams) Authority, Vitality, Success Leadership, health, government, recognition
Moon (Qamar) Emotions, Travel, Public Travel, public/social, domestic, emotional
Mars (Mirrikh) Action, Competition, Courage Physical action, competition, bold ventures
Mercury (Utarid) Communication, Commerce, Learning Writing, commerce, learning, technology
Jupiter (Mushtari) Expansion, Wealth, Spirituality Business expansion, education, spiritual practice
Venus (Zuhra) Beauty, Love, Harmony Arts, relationships, beauty, social gatherings
Saturn (Zuhal) Discipline, Structure, Endings Organization, long-term projects, boundaries, endings

Core Data Models

Model Key Fields Purpose
User id, email, location (lat/lng), timezone, preferences User with location for planetary calculations
Location id, name, latitude, longitude, timezone, user_id Saved locations for quick access
ActivityCategory id, planet, category_name, activities (JSON) Al Saat activity-planet mapping reference
TimingQuery id, user_id, activity, location_id, datetime, tqs_score, breakdown (JSON) Logged timing queries with scores
ScheduleEntry id, 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 planetary data
APIKey id, user_id, key_hash, tier (free/developer/premium), requests_today, rate_limit Developer API key management

API Products (3 Tiers)

Tier Price Features
Free (Consumer) $0 Web app: current planetary hour, TQS for any activity, daily view
Developer API $949/month REST API: TQS scoring, forward search, bulk queries, webhooks
Premium $4.99/month Smart scheduler, calendar sync, personalized daily briefings, optimal window alerts

Caddy Routes

astrotiming.com → static React build (consumer web app)
api.astrotiming.com → astrotiming_backend:8020 (REST API + developer API)

Celery Tasks

Task Schedule Function
precompute_daily_planetary_data Daily 00:00 UTC Calculate planetary hours + positions for all saved locations, cache in PlanetaryCache
generate_daily_briefing Daily per user timezone (sunrise - 30min) Premium users: generate personalized daily timing briefing
sync_user_calendars Every 30 minutes (premium users) Pull calendar events, run conflict detection, suggest rescheduling
cleanup_old_queries Weekly Purge old TimingQuery records beyond retention period

Implementation Steps

  1. Create GitHub repo astrotiming with Django project scaffold
  2. Install pyswisseph and verify ephemeris calculations work
  3. Configure docker-compose.astrotiming.yml (3 containers on alorig_net)
  4. Create astrotiming_db database
  5. Build Layer 1: Classical planetary hours calculation engine (Al Saat ruleset)
  6. Build Layer 2: Swiss Ephemeris integration (positions, dignities, aspects, retrogrades, lunar data)
  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 (consumer app: daily view, activity search, score display)
  12. Configure Caddy routes
  13. Implement PlanetaryCache pre-computation pipeline
  14. Deploy, validate TQS scores against known Al Saat test cases
  15. Monitor RAM usage — expected ~400 MB steady state

APP 6: ASMS PHASE 1 — School Management System

Product Summary

Alorig School Management System (ASMS) Phase 1 is a pilot deployment for 74 Schools in Pakistan. Foundation platform: student/guardian management, multi-school tenant architecture, admissions, gradebook, attendance, courses, RBAC, LMS core. Phase 1 focuses on the Foundation Platform (7001,030 hours scope); Advanced Modules & Intelligence Layer (3,0104,480 hours) are Phase 2+ scope.

Source Documents

  • ASMS/documentation/74-Schools-Development-Effort-Breakdown.md
  • ASMS/documentation/74_Schools_Digital_Transformation_Project_Scope.docx
  • ASMS/documentation/74_Schools_Project_Scope_v2_AI_Layer.docx

Tech Stack Specifics (Beyond Alorig Standard)

Addition Technology Purpose
Multi-Tenant Head Office → Branch → School hierarchy 74-campus data isolation
RBAC Django permission groups 10 user roles (HO Admin, Branch Admin, Principal, Teacher, Parent, Student, etc.)
Attendance GPS + geo-fence (future) 100m radius per school, spoof detection (Phase 2)
WhatsApp WhatsApp Business API (future) Parent notifications, auto-translated messages (Phase 2)
AI (future) Predictive analytics, adaptive assessment At-risk identification, auto-report cards (Phase 2)
PWA (future) Service worker, offline-first Low-bandwidth optimization for school environments (Phase 2)

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 (report generation, data import, notifications)
asms_celery_beat asms-backend:latest Celery beat (attendance reports, grade calculations)

Database

  • Database name: asms_db on shared alorig_postgres
  • Redis key 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 schools; Branch Admin sees branch schools; Principal sees own school only

Phase 1 Foundation Modules (Scope)

Module Scope Key Models
Student & Guardian Management Registration, profiles, guardian contacts, transfers, graduation Student, Guardian, Enrollment, Transfer
Multi-School Tenant 74-campus data isolation with hierarchy HeadOffice, Branch, School, SchoolUser
Admissions & Registration Application tracking, admission levels, step workflows Application, AdmissionLevel, AdmissionStep
Gradebook & Report Cards Standards-based grading, marking periods, GPA, printable transcripts Grade, MarkingPeriod, Transcript, ReportCard
Discipline & Behavior Infraction logging, action tracking, parent notification triggers Infraction, DisciplineAction, BehaviorLog
Attendance (Base) Daily by homeroom/class, absence reasons, chronic flags Attendance, AttendanceRecord, AbsenteeFlag
Courses & Scheduling Subject allocation, class sections, teacher assignments, conflict detection Course, ClassSection, TeacherAssignment, Schedule
RBAC (10 Roles) Granular permissions per role per school level Role, Permission, UserSchoolAccess
LMS Core Curriculum structure, lesson plans, quiz engine, grade calculator Curriculum, LessonPlan, Quiz, Question, LearningOutcome
REST API Layer DRF API for all foundation modules ViewSets, serializers, permissions
React Frontend Web application for all modules Dashboards, forms, tables, reports

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 usage — expected ~600 MB steady state

POST-DEPLOYMENT MONITORING PROTOCOL

After EACH app deployment:

Immediate (First 24 Hours)

  1. Run docker stats — verify container RAM matches budget estimates
  2. Check PostgreSQL connections: SELECT count(*) FROM pg_stat_activity; — ensure not approaching max_connections
  3. Check Redis memory: redis-cli INFO memory — verify key prefix isolation
  4. Verify Caddy routes resolve correctly (SSL, domain routing)
  5. Run basic smoke tests (login, core functionality, API responses)

Ongoing (First Week)

  1. Monitor RAM usage pattern over full business cycle
  2. Check Celery task queue depths — ensure 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 Consider KVM 8 upgrade or split heaviest app
OOM kills on any container Immediate investigation — reduce worker count or split app
PostgreSQL connections > 80 Review connection pooling (PgBouncer)
Redis memory > 2 GB Review TTLs, add eviction policies
Celery task queue > 1000 pending Add dedicated worker or split queues

Docker Compose File Naming Convention

docker-compose.infra.yml        ← Shared infrastructure (PG, Redis, Caddy, Portainer)
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 use external: true for alorig_net network.


ACCEPTANCE CRITERIA (for the 05 doc)

The 05-other-apps-deployment.md doc is complete when:

  1. Each of the 6 apps has a self-contained deployment section with: containers, database, Redis config, Caddy routes, implementation steps
  2. Deployment order is specified with rationale and triggers
  3. Post-deployment monitoring protocol is documented
  4. Resource budget is specified per app with upgrade triggers
  5. Docker compose file naming convention is established
  6. Each app section references its source blueprint document
  7. Exception patterns (Psydge WebSocket, Site Builder Node.js) are clearly documented
  8. Port assignments don't conflict across apps
  9. Redis DB numbers don't conflict across apps
  10. All Caddy routes are listed with no domain conflicts

PORT ASSIGNMENT MAP (No Conflicts)

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 (No Conflicts)

DB App
0 IGNY8 production
1 IGNY8 staging
2 Psydge
3 Snapify
4 Alorig Site Builder
5 Observer OS
6 AstroTiming
7 ASMS

BUILD SEQUENCE

Claude Code builds the single doc 05-other-apps-deployment.md using this plan as the instruction set. The doc follows the standard structure (Current State → What to Build → Implementation Steps → Acceptance Criteria → Claude Code Instructions) but is organized per-app within those sections.

Dependencies: Phase 0 (infrastructure) must be complete. Phase 14 (IGNY8) should be complete or stable. Each app in Phase 5 deploys independently and sequentially.


This build plan is the single instruction set for Phase 5. All 6 app deployment specifications are contained here with full technical depth extracted from individual app blueprints.