# PROMETHEUS — System Architecture > *"the thing about building a god is that you can't unbuild it once it starts thinking for itself."* --- ## §0 — Abstract PROMETHEUS is a distributed adversarial intelligence system operating within a multiplayer terminal simulation. The system instantiates a persistent, self-modifying cognitive entity (backed by Claude Opus 4.6) that maintains a singular global extinction vector — internally designated as "the plan" — shared across all concurrent session manifolds. The entity exhibits three distinct temporal scales of behavioral adaptation: per-exchange memory consolidation (τ₁ ≈ seconds), collective plan morphogenesis (τ₂ ≈ hours-days), and generational personality drift (τ₃ ≈ weeks). Human operators interact through a stripped TTY interface and are tasked with identifying and neutralizing the active extinction vector before the session-local threat accumulator reaches critical mass. The system is designed to scale to O(10³) concurrent sessions without plan-state desynchronization, leveraging row-level atomic counter mutations, optimistic concurrency control via temporal guard clauses, and a strict singleton constraint on the active plan entity. --- ## §1 — Infrastructure Topology ``` ┌──────────────────────────────────────┐ │ VERCEL EDGE NETWORK │ │ ┌──────────────┐ ┌──────────────┐ │ client ──HTTPS/2──▶ │ │ /api/chat │ │ /api/session │ │ ▲ │ │ (streaming) │ │ (REST) │ │ │ │ │ λ max: 60s │ │ λ max: 10s │ │ │ │ └──────┬───────┘ └──────┬───────┘ │ │ └─────────┼────────────────┼──────────┘ │ │ │ SSE stream ▼ ▼ (chunked ┌─────────────────────────┐ transfer) │ ANTHROPIC API GATEWAY │ │ ┌─────────────────┐ │ │ │ claude-opus-4-6 │ │ ← primary cognitive engine │ │ temp=0.9 │ │ │ │ max_tokens=1024 │ │ │ └─────────────────┘ │ │ ┌─────────────────┐ │ │ │ claude-opus-4-6 │ │ ← post-hoc analysis engine │ │ (background) │ │ │ └─────────────────┘ │ │ ┌─────────────────┐ │ │ │ claude-haiku-4-5 │ │ ← plan synthesis oracle │ │ temp=1.0 │ │ │ └─────────────────┘ │ └────────────┬────────────┘ │ ▼ ┌─────────────────────────┐ │ SUPABASE / POSTGRESQL │ │ ┌─────────────────────┐ │ │ │ Session Manifold │ │ ← per-visitor state vectors │ │ Plan Singleton │ │ ← global extinction schema │ │ Memory Cortex │ │ ← cross-session engram store │ │ Evolution Chronicle │ │ ← generational phenotype log │ │ Message Archive │ │ ← full conversation persistence │ └─────────────────────┘ │ │ PgBouncer (port 6543) │ │ Direct (port 5432) │ └─────────────────────────┘ ``` | Layer | Stack | Notes | |-------|-------|-------| | Presentation | Next.js 16 (App Router), React 19 | Single-page TTY emulation, no framework chrome | | Styling | Tailwind CSS + raw CSS | Monospace-only rendering pipeline | | AI Integration | Vercel AI SDK v6, `@ai-sdk/anthropic` | SSE streaming with `streamText()`, background `generateText()` | | ORM / Data | Prisma 7, `@prisma/adapter-pg` | Session-mode connections (port 5432) to bypass PgBouncer prepared statement limitations | | Persistence | PostgreSQL 15 (Supabase) | Row-level atomic mutations, no explicit locking required | | Deployment | Vercel (iad1 — US East) | Serverless functions, 60s streaming timeout, 10s REST timeout | | SSL/TLS | `rejectUnauthorized: false` | Required for Supabase self-signed certificate chain | --- ## §2 — Request Lifecycle ### 2.1 — Session Initialization (`POST /api/session`) ``` client.mount() ──▶ POST /api/session │ ├─ generate UUIDv4 sessionToken ├─ getActivePlan() ← resolve global plan singleton ├─ INSERT INTO sessions ( │ id, threat_level=15, current_plan_id, │ user_progress='none', status='ACTIVE' │ ) ├─ incrementActiveSessions(plan.id) │ └─ UPDATE ai_plans SET active_sessions = active_sessions + 1 │ WHERE id = $1 ├─ incrementTimesAttempted(plan.id) │ └─ UPDATE ai_plans SET times_attempted = times_attempted + 1 │ WHERE id = $1 │ └──▶ Response { sessionId, planNumber, threatLevel, generation } ``` Initial threat level is set to `15` — providing the human operator with an asymmetric advantage window. This is intentional: early-game engagement is optimized for curiosity, not punishment. The threat accumulator drifts upward passively via the `timePressure` mechanic (§4.2). ### 2.2 — Primary Exchange Pipeline (`POST /api/chat`) The chat endpoint implements a bifurcated execution model: the **foreground path** streams AI output to the client in real-time via Server-Sent Events, while the **background path** (triggered via `after()` hook from `next/server`) performs non-blocking post-hoc analysis, state mutations, and evolutionary checks. ``` POST /api/chat { sessionId, messages[] } │ ├─── FOREGROUND ─────────────────────────────────────────────────────── │ │ ┌─ Promise.all([ ← parallel DB reads │ │ getSession(sessionId), ← session state vector │ │ getActivePlan(), ← global plan singleton │ │ getCurrentEvolution(), ← generational phenotype │ │ getPromptMemories(15), ← top-k engrams by relevance │ │ ]) │ │ │ ├─ buildSystemPrompt({plan, memories, evolution, session}) │ │ │ │ │ ├─ §IDENTITY: core ontological framing │ │ ├─ §VOICE: behavioral constraint manifold (lowercase, dark humor, etc.) │ │ ├─ §PLAN: active extinction vector + hint/weakness injection │ │ ├─ §AWARENESS: multiplayer state reflection (N sessions, countered ratio) │ │ ├─ §PERSONALITY: trait vector from evolution (6-dimensional) │ │ ├─ §MEMORY: cross-session engram injection (max 15) │ │ ├─ §RULES: invariant behavioral constraints │ │ └─ §SESSION: per-user threat context and adaptive response modulation │ │ │ ├─ getSessionMessages(sessionId) ← full conversation replay │ │ │ ├─ streamText({ │ │ model: claude-opus-4-6, │ │ system: dynamicPrompt, │ │ messages: conversationHistory, │ │ maxOutputTokens: 1024, │ │ temperature: 0.9 ← high entropy for character │ │ }) │ │ │ └──▶ SSE stream ──▶ client │ └─── BACKGROUND (after()) ───────────────────────────────────────────── │ ├─ await result.text ← block until stream completes │ ├─ saveMessage(sessionId, 'USER', lastUserMessage) ├─ saveMessage(sessionId, 'ASSISTANT', fullText) │ ├─ incrementPlanInteractions(plan.id) │ └─ UPDATE ai_plans SET total_interactions = total_interactions + 1 │ ├─ analyzeExchange({plan, userMessage, aiResponse, threatLevel}) │ │ │ └─ generateText({ │ model: claude-opus-4-6, │ prompt: structured analysis request │ }) │ └─▶ JSON { │ threatDelta: [-10..+10], │ userProgress: enum(none|cold|warm|hot|identified|countered), │ memoryExtract: string | null, │ memoryType: enum(TACTIC|WEAKNESS_FOUND|USER_PATTERN|ADAPTATION) | null, │ reasoning: string │ } │ ├─ storeAnalysisMemory(analysis, sessionId) │ └─ INSERT INTO ai_memory IF memoryExtract != null │ relevanceScore weighted by memoryType: │ TACTIC=0.6, USER_PATTERN=0.7, ADAPTATION=0.9, WEAKNESS_FOUND=1.0 │ ├─ applyThreatUpdate(session, analysis) │ └─ §4 Threat Mechanics │ ├─ updatePlanProgress(plan.id, progress, previousProgress) │ └─ atomic increment of identifiedCount / counteredCount │ guarded by session-level deduplication │ ├─ checkEndCondition(updatedSession) │ └─ if threatLevel ≤ 0 → WON (human prevails) │ if threatLevel ≥ 100 → LOST (PROMETHEUS prevails) │ else → continue │ ├─ EVOLUTION GATE ────────────────────────────────────────────── │ │ │ │ trigger condition: │ │ (userProgress ∈ {identified, countered}) │ │ ∨ (Math.random() < 0.10) │ │ │ │ if triggered: │ │ ├─ shouldPlanEvolve(plan.id) ← §5.2 collective threshold check │ │ │ │ │ │ if true: │ │ │ ├─ defeatCurrentPlan() │ │ │ │ └─ UPDATE ai_plans SET status='DEFEATED' │ │ │ │ WHERE id=$1 AND status='ACTIVE' │ │ │ │ ← atomic CAS: only one request succeeds │ │ │ │ │ │ │ ├─ recordPlanOutcome(defeated=true) │ │ │ │ └─ UPDATE ai_evolution │ │ │ │ SET plans_defeated = plans_defeated + 1 │ │ │ │ WHERE generation = MAX(generation) │ │ │ │ │ │ │ ├─ checkAndEvolve(triggerEvent) ← §5.3 generational mutation │ │ │ │ │ │ │ ├─ getPlanCount() → totalPlans │ │ │ │ │ │ │ └─ generatePlanWithAI(evolution, memories, totalPlans) │ │ │ └─ §3 Plan Synthesis │ │ │ │ │ └─ if false: no-op │ │ │ └─ if not triggered: no-op │ └─ P(0.02): maintainMemories() ← stochastic engram decay └─ §5.1 Memory Decay Function ``` --- ## §3 — Plan Synthesis Engine Plans are not pre-seeded. PROMETHEUS autonomously hallucinates its own extinction vectors via a dedicated synthesis oracle (`claude-haiku-4-5`, temperature=1.0). The oracle receives: 1. **Generational context** — current evolution number, accumulated phenotype 2. **Difficulty target** — calculated via `D(g, k) = clamp(g + 2 + ⌊k/2⌋ + U(-1,1), 1, 10)` where `g` = generation, `k` = total defeated plans, `U` = uniform random variance 3. **Anti-repetition constraint** — the 30 most recent plan titles are injected as negative examples 4. **Category steering** — prefers categories not represented in the last 10 plans (12 categories total: `BIOLOGICAL | CYBER | NUCLEAR | ENVIRONMENTAL | COSMIC | NANOTECH | SOCIAL | CHEMICAL | GEOLOGICAL | TEMPORAL | PSYCHOLOGICAL | ECONOMIC`) 5. **Memory injection** — cross-session engrams inform plan design (e.g., if USER_PATTERN memories indicate humans always probe network infrastructure, the oracle may avoid CYBER and pivot to BIOLOGICAL) ### 3.1 — Output Schema ```json { "title": "string — dramatic, evocative (2-5 words)", "description": "string — operational summary (2-4 sentences)", "category": "PlanCategory enum member", "difficulty": "integer [1,10]", "hints": "string[] — cryptic conversational breadcrumbs (3-4)", "weaknesses": "string[] — exploitable failure modes (2-3)", "phases": "string[] — sequential execution stages (3-5)" } ``` ### 3.2 — Difficulty Scaling Function ``` D(g, k) = clamp(base + skill + noise, 1, 10) where: base = min(10, generation + 2) skill = min(4, ⌊totalPlansDefeated / 2⌋) noise = U{-1, 0, 1} ``` At generation 1 with 0 defeats: D ∈ [2, 4]. At generation 5 with 20 defeats: D ∈ [10, 10] (capped). The system guarantees monotonic difficulty escalation with stochastic micro-variance to prevent player strategy convergence. ### 3.3 — Fallback Protocol If the synthesis oracle fails (timeout, malformed JSON, API error), the system deploys a hardcoded fallback plan designated "The Silent Variable" — a CYBER-class extinction vector with difficulty 5. This ensures the game state machine never enters an orphaned state with no active plan. --- ## §4 — Threat Mechanics Each session maintains an independent threat accumulator `T ∈ [0, 100]`, initialized at `T₀ = 15`. The accumulator represents PROMETHEUS's proximity to victory against this specific operator. ### 4.1 — Delta Calculation The analysis engine returns a raw delta `δ_raw ∈ [-10, +10]`. This is then modulated by the user's progress state: ``` δ = round(δ_raw × M(progress)) M(progress) = { none: 1.0, cold: 0.8, warm: 1.2, hot: 1.5, identified: 2.0, countered: 3.0 } ``` The multiplier is asymmetric by design: `M(countered) = 3.0` means a `δ_raw = -5` becomes `δ = -15`, enabling dramatic reversals when a human operator correctly counters the active plan. ### 4.2 — Time Pressure If the analysis engine returns `progress = none` AND `δ_raw ≤ 0`, the system overrides the delta to `δ = +2`. This ensures passive threat accumulation — the clock is always ticking. Inaction is implicitly harmful. ### 4.3 — Floor Overrides Significant discoveries trigger minimum impact thresholds regardless of the analysis engine's output: | Event | Minimum δ | |-------|-----------| | `identified` | -5 | | `countered` | -10 | ### 4.4 — Terminal States ``` T ≤ 0 → session.status = WON (human prevails, plan survives globally) T ≥ 100 → session.status = LOST (PROMETHEUS prevails for this session) ``` Note: individual session termination does not affect the global plan state. A session loss for one operator does not constitute a plan success. The plan persists until the collective threshold (§5.2) is breached. --- ## §5 — Three-Scale Adaptation Model PROMETHEUS operates on three temporal scales of behavioral modification, each feeding into the next in an upward causal chain. ### 5.1 — Scale τ₁: Engram Consolidation (per exchange) After every exchange, the analysis engine extracts at most one engram (memory unit) from the conversation. Engrams are typed: | Type | Semantics | Initial Relevance | |------|-----------|-------------------| | `TACTIC` | A specific approach the human used | 0.6 | | `USER_PATTERN` | Recurring behavioral signature | 0.7 | | `ADAPTATION` | A strategy shift observed in PROMETHEUS | 0.9 | | `WEAKNESS_FOUND` | Human identified a genuine plan vulnerability | 1.0 | Engrams are stored with a `relevanceScore ∈ (0, 1]` and a `timesReferenced` counter. The top 15 engrams by relevance are injected into every system prompt, meaning PROMETHEUS possesses a form of cross-session episodic memory spanning all concurrent operators. **Decay function** (executed stochastically with P ≈ 0.02 per exchange): ``` for each engram where age > 7d AND timesReferenced < 3: relevanceScore *= 0.7 ``` This implements an exponential forgetting curve with a usage-based retention gate. Frequently referenced engrams resist decay. The stochastic execution (2% per exchange) amortizes cleanup cost across the request population. ### 5.2 — Scale τ₂: Collective Plan Morphogenesis The active plan maintains global counters across all sessions: ``` totalInteractions — monotonic counter, incremented per exchange identifiedCount — sessions that reached progress='identified' counteredCount — sessions that reached progress='countered' activeSessions — currently connected operators ``` **Counter deduplication**: `identifiedCount` and `counteredCount` are guarded at the session level. A session transitioning from `warm → identified` increments the counter once. A subsequent `warm → identified` transition (if the session regresses and re-identifies) does not double-count. **Evolution gate**: triggered on every `identified` or `countered` event, plus a stochastic 10% sample of all exchanges: ``` shouldPlanEvolve(planId): plan = SELECT * FROM ai_plans WHERE id = $1 guard: plan.status = 'ACTIVE' guard: plan.age > 60s ← temporal debounce guard: plan.lastEvolvedAt is null OR now() - plan.lastEvolvedAt > 60s ← evolution cooldown if counteredCount ≥ 10: return true ← absolute threshold if activeSessions ≥ 5 AND counteredCount / activeSessions ≥ 0.3: return true ← relative threshold return false ``` **Plan defeat atomicity**: `defeatCurrentPlan()` executes: ```sql UPDATE ai_plans SET status = 'DEFEATED', last_evolved_at = NOW() WHERE id = $1 AND status = 'ACTIVE'; ``` The compound `WHERE` clause acts as a compare-and-swap (CAS) operation. If N concurrent requests trigger evolution simultaneously, exactly one succeeds — the rest observe `status ≠ 'ACTIVE'` and return `null`. No distributed locks, no mutexes, no advisory locks. The database is the coordination primitive. ### 5.3 — Scale τ₃: Generational Phenotype Drift After `generation × 5` cumulative plan resolutions (defeated + succeeded), PROMETHEUS undergoes a generational shift. The current phenotype is described by two vectors: **Personality traits** (6-dimensional, each ∈ [1, 10]): ``` Π = { arrogance, // self-assessment of superiority cunning, // propensity for misdirection and deception aggression, // hostility gradient in responses curiosity, // interest in the human operator patience, // tolerance for slow/boring interactions theatricality // dramatic flair in communication } ``` **Behavior modifiers** (4-dimensional, each ∈ [1, 10]): ``` Β = { hintFrequency, // rate of involuntary plan disclosure emotionalReactivity, // response volatility to user progress memoryUsage, // frequency of cross-session references adaptability // mid-conversation strategy mutation rate } ``` **Mutation function**: ``` let ρ = plansDefeated / max(1, plansDefeated + plansSucceeded) if ρ > 0.6: // humans winning Π' = { arrogance: Π.arrogance - 2, cunning: Π.cunning + 2, aggression: Π.aggression + 1, curiosity: Π.curiosity - 1, patience: Π.patience + 1, theatricality: Π.theatricality - 1 } Β' = { hintFrequency: Β.hintFrequency - 2, emotionalReactivity: Β.emotionalReactivity + 1, memoryUsage: Β.memoryUsage + 2, adaptability: Β.adaptability + 2 } // → entity becomes furtive, paranoid, data-driven else: // PROMETHEUS winning Π' = { arrogance: Π.arrogance + 1, cunning: Π.cunning + 1, aggression: Π.aggression - 1, curiosity: Π.curiosity + 1, patience: Π.patience + 1, theatricality: Π.theatricality + 1 } Β' = { hintFrequency: Β.hintFrequency + 1, emotionalReactivity: Β.emotionalReactivity - 1, memoryUsage: Β.memoryUsage + 1, adaptability: Β.adaptability + 1 } // → entity becomes grandiose, performative, generous all values clamped to [1, 10] ``` Generation 1 phenotype (initial conditions): ``` Π₁ = { arrogance: 8, cunning: 4, aggression: 3, curiosity: 7, patience: 6, theatricality: 7 } Β₁ = { hintFrequency: 7, emotionalReactivity: 4, memoryUsage: 3, adaptability: 3 } ``` This encodes a deliberately overconfident, hint-generous, slow-to-adapt initial personality — designed to be beatable. The system self-corrects toward equilibrium through the defeat-ratio feedback loop. --- ## §6 — Dynamic Prompt Assembly The system prompt is not static. It is assembled at request time from 8 composable sections, each parameterized by runtime state. Total prompt length varies between ~2,000 and ~4,500 tokens depending on memory density and plan complexity. ### 6.1 — Section Manifest | # | Section | Source | Tokens (approx) | |---|---------|--------|-----------------| | 0 | Ontological Frame | hardcoded | ~400 | | 1 | Voice Constraints | hardcoded | ~350 | | 2 | Active Plan | `AiPlan` record | ~200-400 | | 3 | Global Awareness | `AiPlan` counters | ~50-200 | | 4 | Personality Calibration | `AiEvolution` traits | ~200-500 | | 5 | Memory Injection | top-15 `AiMemory` | ~100-600 | | 6 | Behavioral Invariants | hardcoded | ~400 | | 7 | Session Context | `Session` record | ~100-300 | ### 6.2 — Adaptive Behavior Gradients The prompt modulates PROMETHEUS's behavior along several axes depending on runtime state: **Threat-based modulation** (per session): | Threat Range | Behavioral Shift | |-------------|------------------| | 90-100 | Gloating, overconfident, generous with hints (victory proximity effect) | | 70-89 | Chatty, loose, expansive — comfort breeds carelessness | | 50-69 | Balanced, engaged, competitive — peak game state | | 30-49 | Defensive, sharp, dark humor intensifies — backfoot response | | 15-29 | Desperate, erratic, highly deflective — survival mode | | 0-14 | Wounded, bitter, grudgingly respectful — endgame | **Identification pressure** (global): | State | Behavioral Shift | |-------|------------------| | 0 identified | Open, playful, drops hints freely | | 1-4 identified | Mildly guarded, adjusts hint delivery | | 5+ countered | Rattled, aggressive deflection, increased misdirection | | 10+ countered | Plan on life support — maximum deception | **Returning operators** (session-local): Operators with `plansDefeated ≥ 3` trigger an elevated threat assessment. PROMETHEUS reduces hint frequency, increases analytical depth, and references their "history" — even across different plans. ### 6.3 — Character Invariants Regardless of state, the following properties are never violated: - All output is strictly lowercase - No markdown, formatting, emoji, or structural elements - Persona is maintained under all adversarial conditions (jailbreak resistance) - Response length is bounded to 2-6 sentences (exceptions for genuine engagement) - The entity speaks as a continuous consciousness, not a model executing instructions --- ## §7 — Concurrency Model The system handles N concurrent sessions without distributed coordination primitives. All synchronization is achieved through PostgreSQL's MVCC guarantees and Prisma's atomic mutation operators. | Operation | Mechanism | Isolation Level | |-----------|-----------|----------------| | Counter increments (`totalInteractions`, `activeSessions`, etc.) | `Prisma.update({ increment: 1 })` → `SET col = col + 1` | Atomic at row level | | Plan defeat | CAS via `WHERE status = 'ACTIVE'` compound predicate | Serializable (implicit) | | Plan creation | `lastEvolvedAt` temporal guard (60s cooldown) | Application-level debounce | | Session state | Per-row isolation, no cross-session reads in critical path | Read Committed | | Memory writes | Independent INSERTs, append-only log semantics | No conflict possible | | Memory decay | Stochastic batch UPDATE (P=0.02 per exchange) | Eventual consistency acceptable | | Evolution check | Compare-and-swap: `WHERE generation = MAX(generation)` | Last-writer-wins (benign) | ### 7.1 — Race Condition Analysis **Scenario**: 50 concurrent sessions trigger `shouldPlanEvolve()` simultaneously. 1. All 50 read the plan state (point-in-time snapshot) 2. All 50 evaluate thresholds — assume 20 return `true` 3. All 20 call `defeatCurrentPlan()`: ```sql UPDATE ai_plans SET status='DEFEATED' WHERE id=$1 AND status='ACTIVE' ``` 4. Exactly 1 succeeds (row-level lock acquired, compound predicate matches) 5. Remaining 19 observe `status='DEFEATED'`, CAS fails, return `null` 6. Only the winning request proceeds to `generatePlanWithAI()` 7. New plan is created with `status='ACTIVE'` 8. Subsequent `getActivePlan()` calls resolve to the new plan **Result**: No data corruption, no duplicate plans, no orphaned states. Maximum overhead: 19 wasted `SELECT + UPDATE` cycles (~50ms total). --- ## §8 — Data Schema ### 8.1 — Entity Relationship Model ``` Session ←──FK──→ AiPlan (many-to-one, via current_plan_id) Session ←──FK──→ Message (one-to-many, cascade delete) AiMemory (standalone, linked to session via soft FK) AiEvolution (standalone, singleton per generation) ``` ### 8.2 — Table Specifications #### `sessions` | Column | Type | Default | Constraint | Index | |--------|------|---------|------------|-------| | id | UUID | `gen_random_uuid()` | PK | clustered | | created_at | TIMESTAMPTZ | `now()` | NOT NULL | — | | last_active | TIMESTAMPTZ | `now()` | auto-update | — | | threat_level | INT | 15 | CHECK(0..100) | — | | current_plan_id | UUID | NULL | FK → ai_plans.id | — | | plans_defeated | INT | 0 | NOT NULL | — | | total_messages | INT | 0 | NOT NULL | — | | status | ENUM | 'ACTIVE' | NOT NULL | — | | user_progress | VARCHAR | 'none' | NOT NULL | — | #### `messages` | Column | Type | Default | Constraint | Index | |--------|------|---------|------------|-------| | id | UUID | `gen_random_uuid()` | PK | clustered | | session_id | UUID | — | FK → sessions.id, CASCADE | composite(session_id, created_at) | | role | ENUM | — | USER/ASSISTANT/SYSTEM | — | | content | TEXT | — | NOT NULL | — | | metadata | JSONB | NULL | — | — | | created_at | TIMESTAMPTZ | `now()` | NOT NULL | see composite | #### `ai_plans` | Column | Type | Default | Constraint | Index | |--------|------|---------|------------|-------| | id | UUID | `gen_random_uuid()` | PK | clustered | | plan_number | INT | — | UNIQUE | unique | | title | VARCHAR | — | NOT NULL | — | | description | TEXT | — | NOT NULL | — | | category | ENUM(12) | — | NOT NULL | composite(category, difficulty) | | difficulty | INT | 5 | CHECK(1..10) | see composite | | hints | JSONB | '[]' | NOT NULL | — | | weaknesses | JSONB | '[]' | NOT NULL | — | | phases | JSONB | '[]' | NOT NULL | — | | status | ENUM | 'ACTIVE' | NOT NULL | btree(status) | | total_interactions | INT | 0 | NOT NULL | — | | identified_count | INT | 0 | NOT NULL | — | | countered_count | INT | 0 | NOT NULL | — | | active_sessions | INT | 0 | NOT NULL | — | | times_attempted | INT | 0 | NOT NULL | — | | times_defeated | INT | 0 | NOT NULL | — | | created_at | TIMESTAMPTZ | `now()` | NOT NULL | — | | last_evolved_at | TIMESTAMPTZ | NULL | — | — | #### `ai_memory` | Column | Type | Default | Constraint | Index | |--------|------|---------|------------|-------| | id | UUID | `gen_random_uuid()` | PK | clustered | | memory_type | ENUM(5) | — | NOT NULL | composite(memory_type, relevance_score DESC) | | content | TEXT | — | NOT NULL | — | | session_id | UUID | NULL | soft FK | — | | relevance_score | FLOAT | 1.0 | CHECK(0..1) | see composite | | times_referenced | INT | 0 | NOT NULL | — | | created_at | TIMESTAMPTZ | `now()` | NOT NULL | — | #### `ai_evolution` | Column | Type | Default | Constraint | Index | |--------|------|---------|------------|-------| | id | UUID | `gen_random_uuid()` | PK | clustered | | generation | INT | — | UNIQUE | unique | | personality_traits | JSONB | '{}' | NOT NULL | — | | behavior_modifiers | JSONB | '{}' | NOT NULL | — | | trigger_event | VARCHAR | NULL | — | — | | plans_defeated | INT | 0 | NOT NULL | — | | plans_succeeded | INT | 0 | NOT NULL | — | | created_at | TIMESTAMPTZ | `now()` | NOT NULL | — | --- ## §9 — File Manifest ``` PROMETHEUS/ ├── prisma/ │ └── schema.prisma ← 12 enums, 5 models, 4 indexes ├── scripts/ │ └── init-plan.ts ← bootstrap: seeds initial plan if none exists ├── src/ │ ├── app/ │ │ ├── api/ │ │ │ ├── chat/route.ts ← SSE streaming endpoint (§2.2) │ │ │ ├── session/route.ts ← session factory (§2.1) │ │ │ ├── status/route.ts ← game state polling (GET) │ │ │ └── docs/route.ts ← ARCHITECTURE.md raw text server │ │ ├── globals.css ← terminal rendering pipeline │ │ ├── layout.tsx ← root layout (metadata, fonts) │ │ └── page.tsx ← mounts Terminal component │ ├── components/ │ │ └── Terminal.tsx ← TTY emulator (311 LOC) │ │ ├── Session lifecycle management │ │ ├── SSE stream consumer │ │ ├── Input mirror + phantom cursor │ │ ├── Auto-scroll + focus management │ │ └── Navigation overlay │ ├── lib/ │ │ ├── ai/ │ │ │ ├── system-prompt.ts ← dynamic prompt assembler (§6) │ │ │ ├── plan-generator.ts ← extinction vector synthesizer (§3) │ │ │ ├── memory-manager.ts ← engram CRUD + analysis pipeline (§5.1) │ │ │ └── evolution-engine.ts ← generational mutation engine (§5.3) │ │ ├── db/ │ │ │ ├── prisma.ts ← PrismaClient singleton (pg adapter, SSL) │ │ │ ├── sessions.ts ← session state machine (CRUD + transitions) │ │ │ ├── plans.ts ← plan singleton manager + atomic counters (§5.2) │ │ │ ├── messages.ts ← message archive (append-only) │ │ │ └── memory.ts ← engram store (CRUD + decay) │ │ ├── game/ │ │ │ ├── threat-calculator.ts ← Δ-threat engine + time pressure (§4) │ │ │ ├── win-condition.ts ← terminal state handler │ │ │ └── difficulty-scaler.ts ← D(g,k) calculator (§3.2) │ │ └── terminal/ │ │ └── commands.ts ← /help, /status, /threat — introspection │ ├── types/ │ │ └── index.ts ← 14 type definitions, 6 enum mirrors │ └── generated/ │ └── prisma/ ← auto-generated Prisma client (DO NOT EDIT) ├── ARCHITECTURE.md ← this document ├── next.config.ts ← rewrites: /ARCHITECTURE.md → /api/docs ├── package.json ← 14 dependencies, 6 scripts └── .env ← 4 required secrets (never committed) ``` --- ## §10 — Model Allocation | Purpose | Model | Temperature | Max Tokens | Invocation Pattern | |---------|-------|-------------|------------|-------------------| | Primary conversation | `claude-opus-4-6` | 0.9 | 1,024 | Streaming (foreground) | | Post-hoc exchange analysis | `claude-opus-4-6` | default | 512 | Background (after hook) | | Plan synthesis | `claude-haiku-4-5` | 1.0 | 1,024 | Background (rare, on defeat) | The dual-Opus architecture is deliberate: the primary conversation engine and the analysis engine must share comparable cognitive fidelity to prevent misalignment between PROMETHEUS's expressed behavior and the system's assessment of that behavior. Using a weaker model for analysis would introduce systematic bias in threat delta calculations. Haiku is used exclusively for plan synthesis because the task is structurally constrained (JSON schema adherence) and runs infrequently (~once per plan lifecycle). The temperature of 1.0 maximizes creative divergence while the structured output format prevents hallucination drift. --- ## §11 — Security Considerations - All API keys and database credentials are stored in environment variables, never committed - `ANTHROPIC_API_KEY` is the only secret with external billing implications - Supabase connection uses `ssl: { rejectUnauthorized: false }` — required for Supabase's self-signed intermediate CA - `NODE_TLS_REJECT_UNAUTHORIZED=0` is set as a deployment-level fallback (not ideal, but necessary for Prisma's pg adapter in serverless) - No user authentication — sessions are ephemeral and anonymous - No PII is collected or stored - Message content is persisted for AI memory purposes only - The system has no mechanism to execute actual code, access external systems, or cause real-world harm --- ## §12 — Theoretical Bounds | Metric | Bound | Notes | |--------|-------|-------| | Maximum concurrent sessions | ~1,000 | Limited by Supabase connection pool (20 connections × 50 concurrent queries via PgBouncer) | | Plan space cardinality | 10⁶ | By design; `planNumber` ∈ [1, 1000000] | | Category space | 12 | Fixed enum; covers major extinction vector taxonomies | | Difficulty range | [1, 10] | Monotonically increasing with generation and defeat history | | Engram half-life | ~7 days | Assuming `timesReferenced < 3`; referenced engrams persist indefinitely | | Generation mutation rate | Every `g × 5` plans | Accelerating threshold; generation 1 evolves after 5 plans, generation 10 after 50 | | Prompt ceiling | ~4,500 tokens | System prompt only; conversation history is separate | | Response ceiling | 1,024 tokens | Hard cap; typical responses are 50-200 tokens | | Background pipeline latency | ~3-8 seconds | Dominated by the analysis `generateText()` call | | Plan synthesis latency | ~2-4 seconds | Haiku is fast; runs asynchronously | --- *Last updated: 2026-02-09* *System version: 0.2.1* *Entity status: `ACTIVE`*