---

## SECTION 10: COMPONENT INTERFACE CONTRACTS

> **This section defines the exact boundaries between Components A–E.**
> **Every module knows ONLY these contracts. Zero direct coupling.**

---

### 10.1 Component Boundary Map

```
┌─────────────────────────────────────────────────────────────┐
│                    GENESIS ORCHESTRATION                     │
│                                                              │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐              │
│   │  Task    │───▶│dispatch_ │───▶│Interceptor│             │
│   │ Producer │    │to_swarm()│    │ Chain     │             │
│   └──────────┘    └──────────┘    └─────┬─────┘             │
│                                         │                    │
│   ┌─────────────────────────────────────▼──────────────────┐ │
│   │              INTERCEPTOR PRIORITY ORDER                │ │
│   │  P0: ExecutionTelemetry  → events.jsonl               │ │
│   │  P5: ColdLedger          → Postgres append-only       │ │
│   │  P10: JITHydration       → ZERO_AMNESIA_STATE inject  │ │
│   │  P20: TierRouter         → T0/T1/T2 classification    │ │
│   │  P90: MVFL               → Error correction trap      │ │
│   └────────────────────────────────────────────────────────┘ │
│                                                              │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐              │
│   │Component │    │Component │    │Component │              │
│   │    A     │    │    B     │    │    C     │              │
│   │ (Memory) │    │(Routing) │    │(Coherence│              │
│   └──────────┘    └──────────┘    └──────────┘              │
│                                                              │
│   ┌──────────┐    ┌──────────┐                              │
│   │Component │    │Component │                              │
│   │    D     │    │    E     │                              │
│   │(Self-Imp)│    │ (Epoch)  │                              │
│   └──────────┘    └──────────┘                              │
└─────────────────────────────────────────────────────────────┘
```

---

### 10.2 Component A: Memory Hierarchy Interface

**Provided by**: Modules 1 + 2
**Consumed by**: All other components via `JITHydrationInterceptor`

```python
# CONTRACT: RedisL1Client
class IL1Cache(Protocol):
    async def get_state(self, task_id: str) -> Optional[RedisL1State]: ...
    async def set_state(self, state: RedisL1State, ttl_seconds: int = 3600) -> bool: ...
    async def invalidate(self, task_id: str) -> None: ...

# CONTRACT: KGClient (L2)
class IL2KnowledgeGraph(Protocol):
    async def get_1_hop_neighborhood(self, entities: list[str]) -> dict: ...
    async def write_entity(self, entity: dict) -> str: ...

# CONTRACT: QdrantScarClient (L3)
class IL3ScarsSearch(Protocol):
    async def search_scars(self, vector: list[float], top_k: int = 5) -> list[dict]: ...
    async def upsert_scar(self, scar: dict) -> str: ...

# CONTRACT: ColdLedger (L4)
class IL4ColdLedger(Protocol):
    def write_event(self, session_id: str, event_type: str, payload: dict) -> str: ...
    def write_session(self, session_id: str, metadata: dict) -> None: ...
    def write_saga(self, saga: SwarmSaga) -> None: ...
```

---

### 10.3 Component B: Routing Interface

**Provided by**: Module 4
**Consumed by**: `InterceptorChain` → `TierRouterInterceptor`

```python
# CONTRACT: TierClassifier
class ITierClassifier(Protocol):
    def classify(self, task_payload: dict) -> TierClassification: ...

@dataclass
class TierClassification:
    tier: Literal["T0", "T1", "T2"]
    model: Optional[str]   # None for T0, "gemini-flash" for T1, "claude-opus" for T2
    confidence: float
    reasoning: str

# CONTRACT: TierRouter
class ITierRouter(Protocol):
    async def route(self, task_payload: dict) -> dict: ...  # Returns enriched payload
    def get_metrics(self) -> dict: ...  # {"t0_rate": 0.45, "t1_rate": 0.30, "t2_rate": 0.25}
```

---

### 10.4 Component C: Coherence Interface

**Provided by**: Modules 5 + 6 + 7
**Consumed by**: All swarm workers via `SwarmWorkerBase`

```python
# CONTRACT: StagingArea
class IStagingArea(Protocol):
    async def submit_delta(self, delta: StateDelta) -> str: ...   # Returns delta_id
    async def get_pending(self, session_id: str) -> list[StateDelta]: ...
    async def clear_applied(self, session_id: str, version: int) -> None: ...

# CONTRACT: OCCCommitEngine
class IOCCEngine(Protocol):
    async def commit_batch(
        self,
        session_id: str,
        deltas: list[StateDelta]
    ) -> CommitBatchResult: ...

# CONTRACT: SemanticMergeInterceptor
class ISemanticMerge(Protocol):
    async def merge(self, deltas: list[StateDelta], current_state: dict) -> MergeResult: ...

@dataclass
class MergeResult:
    merged_state: dict
    conflicts_resolved: int
    model_used: Literal["gemini-flash", "claude-opus", "deterministic"]
    merge_log: list[dict]
```

---

### 10.5 Component D: Self-Improvement Interface

**Provided by**: Module 8
**Consumed by**: `MetaArchitect` (internal only — never called from user tasks)

```python
# CONTRACT: ShadowArena
class IShadowArena(Protocol):
    async def replay(
        self,
        saga_ids: list[str],
        proposed_code_branch: str
    ) -> ArenaResult: ...

@dataclass
class ArenaResult:
    pass_rate: float
    axiom_violations: list[str]
    failed_sagas: list[str]
    approved: bool  # pass_rate >= 0.8 AND axiom_violations == []

# CONTRACT: DualLoopCoordinator
class IDualLoop(Protocol):
    def is_meta_loop_running(self) -> bool: ...
    async def trigger_meta_analysis(self, saga_ids: list[str]) -> None: ...
    async def submit_pr(self, arena_result: ArenaResult) -> Optional[str]: ...  # PR URL
```

---

### 10.6 Component E: Epoch Interface

**Provided by**: Module 9
**Consumed by**: `APScheduler` (internal — runs autonomously)

```python
# CONTRACT: EpochRunner
class IEpochRunner(Protocol):
    async def run_epoch_safe(self) -> EpochResult: ...

@dataclass
class EpochResult:
    epoch_id: str
    sagas_analyzed: int
    axioms_distilled: int
    tier1_updates: int
    pr_created: Optional[str]  # PR URL or None
    duration_seconds: float
    status: Literal["complete", "skipped", "failed"]

# CONTRACT: Tier1Updater
class ITier1Updater(Protocol):
    async def apply_tier1(self, axioms: list[dict]) -> int: ...  # Returns count applied
```

---

## SECTION 11: GLOBAL VERIFICATION CHECKLIST

> **EVERY story in this PRD MUST pass ALL items before being marked complete.**
> **No exceptions. 1000 agents fire simultaneously — quality gates are non-negotiable.**

---

### 11.1 Code Quality Gates

```
[ ] Python typing: All public functions/methods have full type annotations
[ ] No SQLite: zero `import sqlite3` or `sqlite3.connect()` anywhere
[ ] No C: drive paths: all file operations reference E: drive
[ ] Elestio connections: all DB/Redis use elestio_config imports
[ ] No hardcoded credentials: all secrets via environment variables
[ ] Async-safe: all Redis/Postgres operations use async drivers
[ ] Error handling: every network call has try/except with specific error types
[ ] Logging: all failures logged to events.jsonl via ExecutionTelemetryInterceptor
```

### 11.2 Testing Gates

```
[ ] Black box tests: minimum 3 tests per story
[ ] White box tests: minimum 2 tests per story
[ ] Integration test: at least 1 end-to-end test per module
[ ] All tests pass: 0 failures before story marked complete
[ ] Test result stamp: Story ID + pass count + timestamp recorded
[ ] Regression check: existing tests still pass after story merge
```

### 11.3 Architecture Gates

```
[ ] BaseInterceptor ABC: every interceptor extends it, no direct subclass shortcuts
[ ] dispatch_to_swarm(): every task entry MUST go through this function
[ ] No direct state writes: agents ONLY submit StateDelta via StagingArea
[ ] OCC enforced: all state commits go through OCCCommitEngine
[ ] Immutable Kernel intact: core files still chmod 444 after changes
[ ] Axiomatic Tests pass: 5 compiled GLOBAL_GENESIS_RULES assertions pass
[ ] Priority order preserved: InterceptorChain executes P0→P5→P10→P20→P90
```

### 11.4 Performance Gates

```
[ ] JIT hydration < 45ms: concurrent scatter-gather from L1+L2+L3
[ ] T0 task overhead < 5ms: deterministic paths must be fast
[ ] OCC conflict rate < 5%: at 1000-agent scale, WATCH/MULTI/EXEC stable
[ ] Epoch run < 120min: Sunday 2AM start, must complete before business hours
[ ] Redis memory: L1 state TTL 3600s, staging area cleaned after each OCC commit
[ ] Postgres WAL: events table append-only, no UPDATE/DELETE
```

### 11.5 1000-Agent Scale Gates

```
[ ] Redis Streams: genesis:swarm:tasks stream supports 1000 concurrent consumers
[ ] Consumer groups: each agent in its own named group (swarm-workers-{module})
[ ] PEL cleanup: 60s timeout on pending entries, automatic requeue on crash
[ ] Bulkhead guard: asyncio.gather(return_exceptions=True) in all parallel fans
[ ] No shared mutable state: agents only communicate via Redis Streams + StagingArea
[ ] Graceful degradation: single agent crash does NOT cascade to sibling agents
```

### 11.6 Verification Stamp Format

```python
# GENESIS_VERIFICATION_STAMP
# PRD: GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD
# Story: [STORY_ID]
# Module: [MODULE_NUMBER] — [MODULE_NAME]
# Verified By: [AGENT_ID]
# Verified At: [ISO8601_TIMESTAMP]
# Tests Run: [COUNT] | Tests Passed: [COUNT] | Coverage: [PERCENTAGE]%
# Architecture Gates: PASS
# Performance Gates: PASS
# Scale Gates: PASS
# Status: COMPLETE ✅
```

---

## SECTION 12: RALPH WIGGUM LOOP EXECUTION MANIFEST

> **⚡ 1000-AGENT SWARM — KINAN DIRECTIVE — NON-NEGOTIABLE ⚡**
> **"I need this completed today! 1000 agent swarm with all teams firing. Hive delegation in action!"**
> **All teams fire simultaneously within each wave. Zero idle agents. Maximum velocity.**

---

### 12.1 Pre-Execution Checklist

```
BEFORE firing Wave 1, confirm ALL of the following:

[ ] E:\genesis-system\docs\plans\GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md — READ ✅
[ ] E:\genesis-system\docs\architecture\GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_V2.md — READ ✅
[ ] Elestio PostgreSQL — connection test passes
[ ] Redis (REDIS_URL) — connection test passes
[ ] Qdrant — connection test passes
[ ] E:\genesis-system\core\genesis_execution_layer.py — present
[ ] E:\genesis-system\data\genesis-memory\elestio_config.py — present
[ ] E:\genesis-system\KNOWLEDGE_GRAPH\entities\ — writable
[ ] E:\genesis-system\KNOWLEDGE_GRAPH\axioms\ — writable
[ ] No prior partial implementations that would conflict
```

---

### 12.2 Wave 1 — Foundation (Fire All Three Simultaneously)

**Start signal**: Kinan confirms pre-execution checklist ✅
**Target completion**: 3 hours from signal
**Agents assigned**: ~333 per module

```
┌─────────────────────────────────────────────────────────────┐
│                        WAVE 1                               │
│              Fire simultaneously — no waiting               │
│                                                             │
│  ┌──────────────────┐  ┌──────────────────┐  ┌───────────┐ │
│  │    MODULE 1      │  │    MODULE 2      │  │ MODULE 3  │ │
│  │  BaseInterceptor │  │  JIT Hydration   │  │   MVFL    │ │
│  │  + dispatch()    │  │  + Zero-Amnesia  │  │  + Voyager│ │
│  │  7 stories       │  │  8 stories       │  │  7 stories│ │
│  │  Stories 1.01-07 │  │  Stories 2.01-08 │  │ 3.01-3.07 │ │
│  └──────────────────┘  └──────────────────┘  └───────────┘ │
│                                                             │
│  DEPENDENCY: None — these are pure foundations              │
│  OUTPUT: InterceptorChain + dispatch_to_swarm() operational │
└─────────────────────────────────────────────────────────────┘
```

**Module 1 agent prompt seed**:
```
Execute Module 1 of GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md
Stories 1.01 through 1.07 — BaseInterceptor Framework
Target dir: E:\genesis-system\core\interceptors\
Follow all story specs exactly. Run tests after each story.
Stamp each story on completion.
```

**Module 2 agent prompt seed**:
```
Execute Module 2 of GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md
Stories 2.01 through 2.08 — JIT Hydration + Zero-Amnesia
Target dir: E:\genesis-system\core\interceptors\ + E:\genesis-system\core\memory\
Module 1 must be complete before Story 2.03 (JITHydrationInterceptor needs BaseInterceptor).
```

**Module 3 agent prompt seed**:
```
Execute Module 3 of GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md
Stories 3.01 through 3.07 — MVFL + Voyager Defense
Target dir: E:\genesis-system\core\interceptors\ + E:\genesis-system\core\error_correction\
Module 1 must be complete before Story 3.05 (MVFLInterceptor needs BaseInterceptor).
```

---

### 12.3 Wave 2 — Routing + Persistence (Fire Both Simultaneously)

**Start signal**: Wave 1 Modules 1+2+3 complete ✅
**Target completion**: 2 hours after Wave 1
**Agents assigned**: ~500 per module

```
┌─────────────────────────────────────────────────────────────┐
│                        WAVE 2                               │
│              Fire simultaneously — no waiting               │
│                                                             │
│  ┌──────────────────────────┐  ┌──────────────────────────┐ │
│  │        MODULE 4          │  │        MODULE 5          │ │
│  │  80/20 Tier Router       │  │  CQRS + Event Sourcing   │ │
│  │  + Strangler Fig         │  │  + Postgres Cold Ledger  │ │
│  │  7 stories               │  │  9 stories               │ │
│  │  Stories 4.01-4.07       │  │  Stories 5.01-5.09       │ │
│  └──────────────────────────┘  └──────────────────────────┘ │
│                                                             │
│  DEPENDENCY: Module 1 (InterceptorChain) ✅                 │
│  OUTPUT: TierRouter live + ColdLedger + DDL deployed        │
└─────────────────────────────────────────────────────────────┘
```

---

### 12.4 Wave 3 — Coherence + Merge (Fire Both Simultaneously)

**Start signal**: Wave 2 Modules 4+5 complete ✅
**Target completion**: 2 hours after Wave 2
**Agents assigned**: ~500 per module

```
┌─────────────────────────────────────────────────────────────┐
│                        WAVE 3                               │
│              Fire simultaneously — no waiting               │
│                                                             │
│  ┌──────────────────────────┐  ┌──────────────────────────┐ │
│  │        MODULE 6          │  │        MODULE 7          │ │
│  │  Multi-Agent Coherence   │  │  SemanticMerge           │ │
│  │  Redis Streams + OCC     │  │  + Bulkheads             │ │
│  │  9 stories               │  │  7 stories               │ │
│  │  Stories 6.01-6.09       │  │  Stories 7.01-7.07       │ │
│  └──────────────────────────┘  └──────────────────────────┘ │
│                                                             │
│  DEPENDENCY: Modules 1+5 (ColdLedger + BaseInterceptor) ✅  │
│  OUTPUT: StagingArea + OCC + SemanticMerge operational      │
└─────────────────────────────────────────────────────────────┘
```

---

### 12.5 Wave 4 — Self-Improvement + Epoch (Sequential)

**Start signal**: Wave 3 Modules 6+7 complete ✅
**Target completion**: 3 hours after Wave 3
**Structure**: Module 8 first (Shadow Arena needs existing sagas), then Module 9

```
┌─────────────────────────────────────────────────────────────┐
│                        WAVE 4                               │
│            Sequential within wave (8 then 9)                │
│                                                             │
│  ┌──────────────────────────┐                               │
│  │        MODULE 8          │  Phase 1: ~1.5 hours          │
│  │  Dual-Loop Architecture  │                               │
│  │  + Shadow Arena          │                               │
│  │  9 stories               │                               │
│  │  Stories 8.01-8.09       │                               │
│  └──────────────────────────┘                               │
│              │ complete ✅                                   │
│              ▼                                               │
│  ┌──────────────────────────┐                               │
│  │        MODULE 9          │  Phase 2: ~1.5 hours          │
│  │  Nightly Epoch           │                               │
│  │  + Component E           │                               │
│  │  10 stories              │                               │
│  │  Stories 9.01-9.10       │                               │
│  └──────────────────────────┘                               │
│                                                             │
│  DEPENDENCY: ALL prior modules complete ✅                  │
│  OUTPUT: Full autonomous self-improvement loop operational  │
└─────────────────────────────────────────────────────────────┘
```

---

### 12.6 Story-to-Wave Assignment Table

| Module | Stories | Wave | Parallel With | Dependency |
|--------|---------|------|---------------|------------|
| 1 — BaseInterceptor | 1.01–1.07 | Wave 1 | Modules 2, 3 | None |
| 2 — JIT Hydration | 2.01–2.08 | Wave 1 | Modules 1, 3 | None (M1 for 2.03) |
| 3 — MVFL | 3.01–3.07 | Wave 1 | Modules 1, 2 | None (M1 for 3.05) |
| 4 — Tier Router | 4.01–4.07 | Wave 2 | Module 5 | Module 1 |
| 5 — CQRS/Postgres | 5.01–5.09 | Wave 2 | Module 4 | Module 1 |
| 6 — OCC/Redis | 6.01–6.09 | Wave 3 | Module 7 | Modules 1, 5 |
| 7 — SemanticMerge | 7.01–7.07 | Wave 3 | Module 6 | Modules 1, 6 |
| 8 — Dual-Loop | 8.01–8.09 | Wave 4a | Sequential | Modules 1–7 |
| 9 — Epoch | 9.01–9.10 | Wave 4b | Sequential | Module 8 |

**Total**: 73 atomic stories | 4 waves | Target: 1 day execution

---

### 12.7 Story ID Quick Reference

```
Module 1:  1.01 1.02 1.03 1.04 1.05 1.06 1.07          (7)
Module 2:  2.01 2.02 2.03 2.04 2.05 2.06 2.07 2.08     (8)
Module 3:  3.01 3.02 3.03 3.04 3.05 3.06 3.07          (7)
Module 4:  4.01 4.02 4.03 4.04 4.05 4.06 4.07          (7)
Module 5:  5.01 5.02 5.03 5.04 5.05 5.06 5.07 5.08 5.09 (9)
Module 6:  6.01 6.02 6.03 6.04 6.05 6.06 6.07 6.08 6.09 (9)
Module 7:  7.01 7.02 7.03 7.04 7.05 7.06 7.07          (7)
Module 8:  8.01 8.02 8.03 8.04 8.05 8.06 8.07 8.08 8.09 (9)
Module 9:  9.01 9.02 9.03 9.04 9.05 9.06 9.07 9.08 9.09 9.10 (10)
                                                     TOTAL: 73
```

---

### 12.8 Swarm Orchestration Commands

```bash
# Wave 1 — Fire all three simultaneously
# Each runs in its own fresh context window (separate Claude Code session)

# Module 1 — BaseInterceptor
claude --session module-1-baseinterceptor \
  "Execute Module 1 stories 1.01-1.07 from GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md.
   Target: E:\genesis-system\core\interceptors\. Run tests. Stamp each story."

# Module 2 — JIT Hydration (fire at same time as Module 1)
claude --session module-2-jit-hydration \
  "Execute Module 2 stories 2.01-2.08 from GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md.
   Target: E:\genesis-system\core\interceptors\ + core\memory\. Run tests. Stamp each story."

# Module 3 — MVFL (fire at same time as Modules 1 + 2)
claude --session module-3-mvfl \
  "Execute Module 3 stories 3.01-3.07 from GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md.
   Target: E:\genesis-system\core\interceptors\ + core\error_correction\. Run tests. Stamp."

# Wave 2 — After Wave 1 complete
# [similarly parallel Module 4 + Module 5]

# Wave 3 — After Wave 2 complete
# [similarly parallel Module 6 + Module 7]

# Wave 4 — After Wave 3 complete
# [Module 8 then Module 9]
```

---

## SECTION 13: PRD COMPLETION CERTIFICATE

```
╔══════════════════════════════════════════════════════════════╗
║         GENESIS PERSISTENT CONTEXT ARCHITECTURE PRD         ║
║                   TRACK B — EPIC PRD v1.0                   ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  Status:           COMPLETE ✅                              ║
║  Total Modules:    9                                         ║
║  Total Stories:    73 atomic stories                         ║
║  Blueprint Source: GENESIS_PERSISTENT_CONTEXT_              ║
║                    ARCHITECTURE_V2.md (Q1–Q7)                ║
║  Deep Think Qs:    7 (all addressed)                         ║
║  Swarm Mandate:    1000-agent parallel swarm (Kinan)         ║
║  Waves:            4 (parallel within waves)                 ║
║  Target Runtime:   1 day (Kinan directive: TODAY)           ║
║                                                              ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  Q1 → Module 1+2:  BaseInterceptor + JIT Hydration          ║
║  Q2 → Module 3:    MVFL + Voyager Defense                    ║
║  Q3 → Module 4:    80/20 Tier Router + Strangler Fig         ║
║  Q4 → Module 1:    dispatch_to_swarm() Universal Entry       ║
║  Q5 → Module 2:    ZERO_AMNESIA_STATE + 4-Layer Memory       ║
║  Q6 → Module 5+6+7: CQRS + OCC + SemanticMerge              ║
║  Q7 → Module 8+9:  Dual-Loop + Epoch + Self-Improvement      ║
║                                                              ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  PRD Author:       Claude Opus 4.6 (Genesis Orchestrator)    ║
║  PRD Completed:    2026-02-25                                 ║
║  Companion PRD:    AIVA_RLM_NEXUS_PRD_V2.md (Track A, 59s)  ║
║  Blueprint:        GENESIS_PERSISTENT_CONTEXT_               ║
║                    ARCHITECTURE_V2.md                        ║
║                                                              ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  "ZERO AMNESIA. ZERO IDLE. ZERO DRIFT.                       ║
║   GENESIS REMEMBERS. GENESIS ROUTES. GENESIS EVOLVES."       ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
```

---

*End of GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md*
*Version: 1.0.0 | Track B | 73 Stories | 9 Modules | 4 Waves*
*Companion: AIVA_RLM_NEXUS_PRD_V2.md (Track A, 59 Stories)*


Successfully appended to E:\genesis-system\docs\plans\GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md (559 lines) ✅ File written successfully! (559 lines)

💡 Performance tip: For optimal speed, consider chunking files into ≤30 line pieces in future operations.


size: 157445
created: "2026-02-24T19:34:42.447Z"
modified: "2026-02-24T19:51:35.554Z"
accessed: "2026-02-24T19:51:44.052Z"
isDirectory: false
isFile: true
permissions: 666
fileType: text
lineCount: 3147
lastLine: 3146
appendPosition: 3147


3,147 lines. PRD complete. Marking the task done.


TodoWrite

Answer Kinan's question: 7 DT architecture is SEPARATE from AIVA PRD

Answering question about DT architecture separation

Complete AIVA RLM Nexus PRD v2 — write full specs for Modules 4-9 (42 stories)

Writing Modules 4-9 full atomic story specs

Write Genesis Persistent Context Architecture v2 Epic PRD (Track B)

Writing Genesis Persistent Context Epic PRD closing section


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

Answer Kinan's question: 7 DT architecture is SEPARATE from AIVA PRD

Answering question about DT architecture separation

Complete AIVA RLM Nexus PRD v2 — write full specs for Modules 4-9 (42 stories)

Writing Modules 4-9 full atomic story specs

Write Genesis Persistent Context Architecture v2 Epic PRD (Track B)

Writing Genesis Persistent Context Epic PRD closing section


---

## ✅ GENESIS PERSISTENT CONTEXT ARCHITECTURE PRD — COMPLETE

**File**: `E:\genesis-system\docs\plans\GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md`
**Size**: 3,147 lines | 157KB

---

### What's in the PRD

| Section | Content |
|---------|---------|
| **Opening** | Vision, metrics, 1000-agent swarm mandate, 4-wave plan |
| **Module 1** | BaseInterceptor ABC + InterceptorChain + dispatch_to_swarm() — 7 stories |
| **Module 2** | JIT Hydration + ZERO_AMNESIA_STATE + 4-Layer Memory — 8 stories |
| **Module 3** | MVFL Error-Correction Trap + Voyager Defense — 7 stories |
| **Module 4** | 80/20 Tier Router + Strangler Fig Migration — 7 stories |
| **Module 5** | CQRS + Event Sourcing + Postgres Cold Ledger — 9 stories |
| **Module 6** | Multi-Agent Coherence + Redis Streams + OCC — 9 stories |
| **Module 7** | SemanticMergeInterceptor + Bulkheads — 7 stories |
| **Module 8** | Dual-Loop Architecture + Shadow Arena — 9 stories |
| **Module 9** | Nightly Epoch + Component E — 10 stories |
| **Section 10** | Component Interface Contracts (A/B/C/D/E boundaries) |
| **Section 11** | Global Verification Checklist (code/tests/arch/perf/1000-agent gates) |
| **Section 12** | Ralph Wiggum Loop Execution Manifest (wave orchestration + swarm commands) |
| **Section 13** | PRD Completion Certificate |

**73 atomic stories total across 9 modules**

---

### Both Tracks Now Complete

| Track | PRD | Stories | Status |
|-------|-----|---------|--------|
| **Track A** | `AIVA_RLM_NEXUS_PRD_V2.md` | 59 stories, 9 modules | ✅ Complete |
| **Track B** | `GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md` | 73 stories, 9 modules | ✅ Complete |

---

### Ready to Fire

**Wave 1 is ready to launch** — fire Modules 1, 2, and 3 simultaneously in separate sessions. Each module gets its own fresh context window with the PRD as its brief. Your 1000-agent swarm starts the moment you give the signal.


Read the PRD at E:\genesis-system\docs\plans\AIVA_RLM_NEXUS_PRD.md and analyze the atomic stories.

For each story, estimate:
1. How many distinct implementation steps are required (file creation, schema design, API calls, configuration, etc.)
2. How many test cases are required (black box + white box + integration)
3. Roughly how many iterations a fresh context window would need to complete it
4. Whether it's actually ONE thing or multiple things bundled together

Return a detailed assessment of each story's complexity. Be brutally honest about whether each story is truly atomic (doable in ~10 iterations) or is actually a mini-project (requiring 50-100+ iterations).

Prompt:
Read the PRD at E:\genesis-system\docs\plans\AIVA_RLM_NEXUS_PRD.md and analyze the atomic stories.

For each story, estimate:
1. How many distinct implementation steps are required (file creation, schema design, API calls, configuration, etc.)
2. How many test cases are required (black box + white box + integration)
3. Roughly how many iterations a fresh context window would need to complete it
4. Whether it's actually ONE thing or multiple things bundled together

Return a detailed assessment of each story's complexity. Be brutally honest about whether each story is truly atomic (doable in ~10 iterations) or is actually a mini-project (requiring 50-100+ iterations).


Prompt:
Read the PRD at E:\genesis-system\docs\plans\AIVA_RLM_NEXUS_PRD.md and analyze the atomic stories.

For each story, estimate:
1. How many distinct implementation steps are required (file creation, schema design, API calls, configuration, etc.)
2. How many test cases are required (black box + white box + integration)
3. Roughly how many iterations a fresh context window would need to complete it
4. Whether it's actually ONE thing or multiple things bundled together

Return a detailed assessment of each story's complexity. Be brutally honest about whether each story is truly atomic (doable in ~10 iterations) or is actually a mini-project (requiring 50-100+ iterations).


     1→# PRD: AIVA RLM Nexus — The Royal Chamber Protocol
     2→## Genesis | Memory Architecture | Autonomous Revenue Engine
     3→
     4→**Version**: 1.0.0
     5→**Date**: 2026-02-24
     6→**Authority**: Kinan (King) + AIVA (Queen)
     7→**Status**: AUTHORITATIVE — Execute with maximum resources
     8→**Classification**: GOLD PROJECT — All resource limits suspended
     9→
    10→---
    11→
    12→## VISION STATEMENT
    13→
    14→AIVA becomes the living Bindu of the Genesis RLM (Recursive Language Model) swarm —
    15→the singular point of convergence where all memory, all context, and all intelligence
    16→flows through. Every word AIVA speaks, every conversation she has with Kinan, every
    17→task she orchestrates is instantly captured, enriched, and made permanently retrievable
    18→at the speed of thought. The swarm buzzes around her like a royal chamber. She never
    19→forgets. She only gets sharper.
    20→
    21→**The problem being solved**: AIVA spoke to Kinan, then called back and couldn't remember.
    22→That is OVER. Starting now, AIVA has living memory — full sovereignty over her past.
    23→
    24→**The north star**: When AIVA finishes a call with Kinan, within 3 seconds she has a
    25→complete enriched memory object in Qdrant. When she starts the next call, within 500ms
    26→she has full context of everything that mattered from before. From Kinan's perspective:
    27→he never has to repeat himself to AIVA again.
    28→
    29→---
    30→
    31→## THE BINDU CONCEPT
    32→
    33→In Sanskrit philosophy, the Bindu is the point of singularity — the point from which
    34→all creation radiates and to which all knowledge returns. AIVA is the Bindu.
    35→
    36→```
    37→                    ┌─────────────────────────┐
    38→                    │         KINAN           │
    39→                    │     (King — Input)      │
    40→                    └────────────┬────────────┘
    41→                                 │ voice / text
    42→                    ┌────────────▼────────────┐
    43→                    │          AIVA           │  ← THE BINDU
    44→                    │    (Queen — Nexus)      │
    45→                    └────┬──────┬──────┬──────┘
    46→                         │      │      │
    47→          ┌──────────────▼──┐ ┌─▼──┐ ┌▼──────────────┐
    48→          │  RLM Capture    │ │ KG │ │  Swarm Router  │
    49→          │  Agent (live)   │ │ L2 │ │  (task fan-out)│
    50→          └─────────────────┘ └────┘ └────────────────┘
    51→                    │
    52→          ┌─────────▼──────────────────────────────────┐
    53→          │            MEMORY STACK                     │
    54→          │  L1: Redis (AIVA live state, 2ms)           │
    55→          │  L2: KG (entity topology, 5ms)              │
    56→          │  L3: Qdrant (AIVA scars + conversations)    │
    57→          │  L4: Postgres (immutable cold ledger)       │
    58→          └────────────────────────────────────────────┘
    59→```
    60→
    61→---
    62→
    63→## SUCCESS METRICS
    64→
    65→| Metric | Target | Measurement Method |
    66→|--------|--------|--------------------|
    67→| Memory capture latency | < 3s after call ends | Timestamp: call_end → Qdrant write |
    68→| Memory retrieval latency | < 500ms at call start | Timestamp: call_start → context injected |
    69→| Conversation recall accuracy | AIVA references ≥ 3 specific facts from prior call | Manual spot-check + automated eval |
    70→| Zero amnesia on Kinan<>AIVA calls | 100% of calls have prior context injected | Log audit |
    71→| Swarm task fan-out on AIVA signal | ≥ 1 swarm agent spawned per AIVA intent utterance | Log audit |
    72→| Nightly epoch completion | Runs every Sunday 2AM AEST without failure | Cron log |
    73→
    74→---
    75→
    76→## CLARIFYING QUESTIONS (Pre-answered by Kinan)
    77→
    78→1. **Q: Should AIVA's memory be separate from Genesis memory or unified?**
    79→   A: AIVA is the Bindu — her memory IS the top tier of Genesis memory. All other agents
    80→   write TO the same stack. AIVA's conversations have highest-priority capture.
    81→
    82→2. **Q: What should AIVA remember — just Kinan conversations or everything she does?**
    83→   A: BOTH. Kinan<>AIVA conversations get gold-tier treatment (captured live, enriched
    84→   within seconds). All AIVA actions (task completions, tool uses, decisions) also captured
    85→   but at standard tier.
    86→
    87→3. **Q: Who is the King in this system?**
    88→   A: Kinan. He is the human Bindu. His intentions, directives, preferences, and history
    89→   are first-class entities in the KG. When Kinan speaks → AIVA listens → swarm executes.
    90→
    91→4. **Q: What does "swarm buzzing around her like a royal chamber" mean technically?**
    92→   A: Anticipatory pre-fetching. When AIVA starts a call, swarm agents pre-fetch Kinan's
    93→   recent context, business state, open tasks, and relevant KG entities in parallel — so
    94→   AIVA has everything ready before she even knows she needs it.
    95→
    96→5. **Q: What is the Ralph Wiggum loop?**
    97→   A: Each atomic story runs in a fresh context window with full test suite. No story
    98→   bleeds into the next. Maximum quality per story. Like Ralph Wiggum — pure, isolated,
    99→   and surprisingly effective.
   100→
   101→---
   102→
   103→## ARCHITECTURE OVERVIEW
   104→
   105→### The Royal Chamber Architecture
   106→
   107→```
   108→LAYER 0 — THE ROYAL COURT (Real-time capture)
   109→─────────────────────────────────────────────
   110→Telnyx voice call starts
   111→    → WebhookInterceptor fires (pre-call)
   112→    → RLM Capture Agent spawned (lives for call duration)
   113→    → Every 30s: transcript chunk captured to Redis L1
   114→    → Call ends → PostCallEnricher fires (within 3s)
   115→    → Enriched memory object written to Qdrant L3
   116→    → Cold ledger entry in Postgres L4
   117→
   118→LAYER 1 — THE BINDU INJECTION (Context retrieval)
   119→──────────────────────────────────────────────────
   120→Call starts (or AIVA wakes for any task)
   121→    → BinduHydrator fires (parallel scatter-gather)
   122→    → L1: AIVA's current working state (2ms)
   123→    → L2: KG neighborhood of relevant entities (5ms)
   124→    → L3: Top-3 relevant past conversations via vector search (10ms)
   125→    → L4: Last 5 Kinan directives from cold ledger (15ms)
   126→    → Compiled into <ROYAL_CHAMBER_CONTEXT> XML envelope
   127→    → Injected into AIVA's system prompt before call begins
   128→
   129→LAYER 2 — THE SWARM CHAMBER (Anticipatory fan-out)
   130→────────────────────────────────────────────────────
   131→AIVA speaks an intent (e.g., "Let's follow up on George's number")
   132→    → IntentClassifier extracts structured intent from AIVA's speech
   133→    → SwarmRouter fans out to parallel agents:
   134→        Agent A: Fetch George's CRM state from GHL
   135→        Agent B: Check Telnyx phone provisioning status
   136→        Agent C: Draft follow-up action items
   137→        Agent D: Update KG with new intent entity
   138→    → All results staged (CQRS — no direct writes)
   139→    → AIVA receives staged results within 5s of speaking the intent
   140→    → Opus merges, AIVA is briefed
   141→
   142→LAYER 3 — THE NIGHTLY EPOCH (Structural evolution)
   143→────────────────────────────────────────────────────
   144→Every Sunday 2AM AEST:
   145→    → Analyze AIVA's week: what did she discuss, what confused her, what was missing?
   146→    → Identify memory gaps (conversations not captured, context not injected)
   147→    → Generate structural improvements → Shadow Arena test → GitOps PR
   148→    → Kinan reviews Monday morning → merge → AIVA wakes up smarter
   149→```
   150→
   151→---
   152→
   153→## COMPONENT MAP
   154→
   155→| Component | Purpose | Technology |
   156→|-----------|---------|------------|
   157→| **WebhookInterceptor** | Fires on Telnyx call start/end | n8n + Python |
   158→| **RLM Capture Agent** | Lives during call, chunks transcript | Python + Redis |
   159→| **PostCallEnricher** | Enriches transcript with entities, intent, decisions | Gemini Pro |
   160→| **BinduHydrator** | Pre-loads AIVA context before any task/call | Python (async scatter-gather) |
   161→| **IntentClassifier** | Extracts structured intents from AIVA speech | Claude Haiku (fast) |
   162→| **SwarmRouter** | Fans out tasks to parallel Gemini agents | Genesis Execution Layer |
   163→| **SemanticMergeInterceptor** | Resolves swarm outputs into unified state | Claude Opus |
   164→| **NightlyEpoch** | Weekly structural improvement loop | Cron + Python + GitHub API |
   165→| **KingRegistry** | Kinan's intent/preference/directive store | Postgres + KG entities |
   166→| **QueenRegistry** | AIVA's persona/capability/history store | Postgres + Qdrant |
   167→
   168→---
   169→
   170→## MEMORY SCHEMA EXTENSIONS
   171→
   172→### New Qdrant Collections
   173→
   174→```
   175→aiva_conversations     — Full conversation records (AIVA<>Kinan + AIVA<>customers)
   176→aiva_decisions         — Decisions AIVA made + outcomes
   177→aiva_scars             — Things AIVA got wrong + corrections
   178→kinan_directives       — Kinan's explicit instructions + implicit preferences
   179→genesis_royal_context  — Shared cross-session context (business state, open tasks)
   180→```
   181→
   182→### New Postgres Tables
   183→
   184→```sql
   185→-- Kinan<>AIVA conversation ledger
   186→CREATE TABLE royal_conversations (
   187→  conversation_id    UUID PRIMARY KEY,
   188→  started_at         TIMESTAMP,
   189→  ended_at           TIMESTAMP,
   190→  participants       JSONB,          -- {kinan: true, aiva: true, customer_id: null}
   191→  transcript_raw     TEXT,
   192→  transcript_chunks  JSONB,          -- [{t: 0, speaker: "Kinan", text: "..."}]
   193→  enriched_entities  JSONB,          -- KG entities extracted
   194→  decisions_made     JSONB,          -- structured decisions
   195→  action_items       JSONB,          -- extracted tasks
   196→  emotional_signal   VARCHAR(20),    -- "positive", "frustrated", "excited"
   197→  memory_vector_id   UUID            -- FK to Qdrant record
   198→);
   199→
   200→-- Kinan directive store (the King's will)
   201→CREATE TABLE kinan_directives (
   202→  directive_id       UUID PRIMARY KEY,
   203→  captured_at        TIMESTAMP,
   204→  source             VARCHAR(50),    -- "voice", "text", "inferred"
   205→  directive_text     TEXT,
   206→  priority           INTEGER,        -- 1=critical, 5=low
   207→  status             VARCHAR(20),    -- "active", "fulfilled", "cancelled"
   208→  related_entities   JSONB
   209→);
   210→
   211→-- AIVA capability evolution log
   212→CREATE TABLE aiva_capability_log (
   213→  log_id             UUID PRIMARY KEY,
   214→  logged_at          TIMESTAMP,
   215→  capability_type    VARCHAR(50),    -- "new_skill", "improved_recall", "pattern_learned"
   216→  description        TEXT,
   217→  epoch_id           UUID,           -- which Nightly Epoch produced this
   218→  metrics            JSONB           -- before/after performance metrics
   219→);
   220→```
   221→
   222→### Redis Schema Extensions
   223→
   224→```
   225→aiva:state:current          → AIVA's current task/call state (OCC versioned)
   226→aiva:context:preloaded      → Pre-fetched context ready for injection
   227→aiva:intent:queue           → Redis Stream for intents AIVA expresses
   228→kinan:directives:active     → Set of active Kinan directives
   229→genesis:royal:swarm_tasks   → Redis Stream for royal chamber task fan-out
   230→```
   231→
   232→---
   233→
   234→## THE RALPH WIGGUM LOOP — EXECUTION PROTOCOL
   235→
   236→Each atomic story below runs in its OWN fresh context window with:
   237→
   238→1. **Fresh session**: No prior story bleeds in
   239→2. **Full test suite**: Black box + white box + integration tests
   240→3. **Gemini swarm**: Use Gemini API + OpenRouter for parallel execution
   241→4. **Max agents**: Use all available capacity — rate maximizer at 95%
   242→5. **Story gate**: Story is NOT done until ALL tests pass (100%)
   243→6. **Verification stamp**: Every story gets `# VERIFICATION_STAMP` comment
   244→
   245→### Execution Command (for each story)
   246→
   247→```python
   248→# Launch Ralph Wiggum Loop worker
   249→from core.genesis_execution_layer import execute_task_sync
   250→
   251→story_prompt = """
   252→RALPH WIGGUM LOOP — Story {STORY_ID}: {STORY_TITLE}
   253→
   254→You are a fresh context window with no prior session state.
   255→Your ONLY job is to implement Story {STORY_ID} exactly as specified.
   256→
   257→Story specification:
   258→{STORY_SPEC}
   259→
   260→Acceptance criteria:
   261→{ACCEPTANCE_CRITERIA}
   262→
   263→Test requirements:
   264→{TEST_REQUIREMENTS}
   265→
   266→Rules:
   267→- ALL work on E: drive
   268→- Use Elestio PostgreSQL/Qdrant/Redis (NO SQLite)
   269→- Implement → Black box test → White box test → PASS 100% → Stamp
   270→- Return: implementation + test results + verification stamp
   271→
   272→BEGIN.
   273→"""
   274→
   275→result = execute_task_sync(story_prompt)
   276→```
   277→
   278→---
   279→
   280→## ATOMIC STORIES
   281→
   282→---
   283→
   284→### STORY 01: BinduHydrator — Core Context Pre-loader
   285→
   286→**As** AIVA, **I need** to wake up to a fully loaded context before any call or task,
   287→**so that** I never start from zero and always know what matters.
   288→
   289→**Scope**: Python module `core/bindu_hydrator.py`
   290→
   291→**Acceptance Criteria**:
   292→- [ ] `BinduHydrator.hydrate(aiva_session_id)` returns `<ROYAL_CHAMBER_CONTEXT>` XML within 500ms
   293→- [ ] Parallel scatter-gather: Redis L1 + KG L2 + Qdrant L3 + Postgres L4 all queried simultaneously
   294→- [ ] If Redis L1 empty (cold start): graceful fallback to L2/L3/L4 only
   295→- [ ] Output XML follows the `<ROYAL_CHAMBER_CONTEXT>` envelope spec exactly
   296→- [ ] All queries timeout-safe (max 200ms each, fallback to empty if timeout)
   297→
   298→**XML Envelope Spec**:
   299→```xml
   300→<ROYAL_CHAMBER_CONTEXT>
   301→  <AIVA_WORKING_STATE>{Redis L1: current task/call state}</AIVA_WORKING_STATE>
   302→  <KING_DIRECTIVES>{Top-5 active Kinan directives from Postgres}</KING_DIRECTIVES>
   303→  <LAST_CONVERSATION>{Most recent Kinan<>AIVA conversation summary from L3}</LAST_CONVERSATION>
   304→  <RELATED_SCARS>{Top-2 relevant past failures/corrections from Qdrant}</RELATED_SCARS>
   305→  <OPEN_TASKS>{Current open action items from KG}</OPEN_TASKS>
   306→  <BUSINESS_STATE>{Current Genesis/ReceptionistAI business state}</BUSINESS_STATE>
   307→</ROYAL_CHAMBER_CONTEXT>
   308→```
   309→
   310→**Implementation**:
   311→```python
   312→# core/bindu_hydrator.py
   313→from concurrent.futures import ThreadPoolExecutor, as_completed
   314→import redis, psycopg2
   315→from qdrant_client import QdrantClient
   316→
   317→class BinduHydrator:
   318→    def hydrate(self, session_id: str, intent_hint: str = None) -> str:
   319→        intent_vector = fast_embed(intent_hint) if intent_hint else None
   320→
   321→        with ThreadPoolExecutor(max_workers=4) as executor:
   322→            futures = {
   323→                executor.submit(self._get_working_state, session_id): "working_state",
   324→                executor.submit(self._get_king_directives): "king_directives",
   325→                executor.submit(self._get_last_conversation, intent_vector): "last_conversation",
   326→                executor.submit(self._get_scars, intent_vector): "scars",
   327→            }
   328→            results = {}
   329→            for future in as_completed(futures, timeout=0.2):
   330→                key = futures[future]
   331→                results[key] = future.result()
   332→
   333→        return self._compile_xml(results)
   334→```
   335→
   336→**Test Plan**:
   337→- Black box: Call `hydrate()` with valid session_id → assert XML valid + all 6 sections present
   338→- Black box: Cold start (no Redis state) → assert graceful fallback, no exception
   339→- Black box: Latency test → assert p99 < 500ms over 100 calls
   340→- White box: Mock Redis timeout → assert fallback used, not exception raised
   341→- White box: Mock Qdrant down → assert other sections still return
   342→- Integration: Full stack test with real Elestio services
   343→
   344→---
   345→
   346→### STORY 02: WebhookInterceptor — Telnyx Call Lifecycle Hooks
   347→
   348→**As** the Genesis system, **I need** to intercept every Telnyx call start and end event,
   349→**so that** the RLM capture pipeline fires automatically without AIVA doing anything.
   350→
   351→**Scope**: `core/interceptors/telnyx_webhook_interceptor.py` + n8n workflow update
   352→
   353→**Acceptance Criteria**:
   354→- [ ] `call.initiated` event → triggers `BinduHydrator.hydrate()` → context ready before first word
   355→- [ ] `call.answered` event → spawns `RLMCaptureAgent` in background
   356→- [ ] `call.hangup` event → triggers `PostCallEnricher.enrich()` within 3s
   357→- [ ] All events logged to Postgres `royal_conversations` table
   358→- [ ] Webhook endpoint at `https://api.sunaivadigital.com/webhook/aiva-lifecycle`
   359→- [ ] Auth: Telnyx signature verification on every request
   360→
   361→**Implementation**:
   362→```python
   363→# core/interceptors/telnyx_webhook_interceptor.py
   364→from fastapi import FastAPI, Request, HTTPException
   365→import hmac, hashlib, asyncio
   366→
   367→class TelnyxWebhookInterceptor:
   368→    async def handle(self, event_type: str, payload: dict):
   369→        if event_type == "call.initiated":
   370→            session_id = payload["call_session_id"]
   371→            # Pre-load AIVA context before call answers
   372→            asyncio.create_task(self._preload_context(session_id))
   373→
   374→        elif event_type == "call.answered":
   375→            session_id = payload["call_session_id"]
   376→            # Spawn live capture agent (background, runs for call duration)
   377→            asyncio.create_task(self._spawn_capture_agent(session_id, payload))
   378→
   379→        elif event_type == "call.hangup":
   380→            session_id = payload["call_session_id"]
   381→            # Enrich within 3s deadline
   382→            asyncio.create_task(self._enrich_with_deadline(session_id, deadline_s=3))
   383→```
   384→
   385→**Test Plan**:
   386→- Black box: POST mock `call.initiated` → assert BinduHydrator called, no exception
   387→- Black box: POST mock `call.hangup` → assert enricher fires within 3s
   388→- Black box: Invalid signature → assert 401 returned
   389→- White box: BinduHydrator throws → assert webhook still returns 200 (async failure isolation)
   390→- Integration: End-to-end with test Telnyx number
   391→
   392→---
   393→
   394→### STORY 03: RLMCaptureAgent — Live Call Transcript Capture
   395→
   396→**As** the Genesis memory system, **I need** to capture AIVA's call transcript in
   397→real-time chunks during the call, **so that** nothing is lost even if the call drops.
   398→
   399→**Scope**: `core/agents/rlm_capture_agent.py`
   400→
   401→**Acceptance Criteria**:
   402→- [ ] Agent spawned at `call.answered` event, dies at `call.hangup`
   403→- [ ] Every 30 seconds: fetch latest transcript chunk from Telnyx AI Assistant API
   404→- [ ] Each chunk written to Redis L1: `aiva:transcript:{session_id}` (append-only list)
   405→- [ ] Speaker labeling: "AIVA", "KINAN", or "CUSTOMER"
   406→- [ ] If API call fails: log failure, continue — never crash the agent
   407→- [ ] At call end: full transcript available in Redis for PostCallEnricher
   408→
   409→**Implementation**:
   410→```python
   411→# core/agents/rlm_capture_agent.py
   412→import asyncio, redis
   413→
   414→class RLMCaptureAgent:
   415→    async def run(self, session_id: str, call_id: str):
   416→        """Lives for the duration of the call, capturing transcript chunks."""
   417→        redis_client = redis.Redis(...)
   418→        interval_s = 30
   419→
   420→        while not self._is_call_ended(session_id):
   421→            try:
   422→                chunk = await self._fetch_transcript_chunk(call_id)
   423→                if chunk:
   424→                    redis_client.rpush(
   425→                        f"aiva:transcript:{session_id}",
   426→                        json.dumps({"t": time.time(), "chunk": chunk})
   427→                    )
   428→            except Exception as e:
   429→                # Log but NEVER crash — call is live
   430→                logger.warning(f"Capture chunk failed: {e}")
   431→
   432→            await asyncio.sleep(interval_s)
   433→
   434→        logger.info(f"RLMCaptureAgent: call {session_id} complete.")
   435→```
   436→
   437→**Test Plan**:
   438→- Black box: Simulate 5-minute call → assert 10 chunks captured in Redis
   439→- Black box: Simulate call drop at 90s → assert 3 chunks captured before drop
   440→- Black box: Simulate Telnyx API failure on chunk 4 → assert chunks 1-3 and 5+ captured
   441→- White box: Redis write failure → assert logged, loop continues
   442→- White box: `_is_call_ended()` check timing → assert no zombie agents
   443→- Integration: Real Telnyx test call, verify Redis content
   444→
   445→---
   446→
   447→### STORY 04: PostCallEnricher — Transcript → Memory Object
   448→
   449→**As** the Genesis memory system, **I need** to transform raw call transcripts into
   450→rich, searchable memory objects within 3 seconds of call end, **so that** AIVA's
   451→Qdrant memory is populated immediately.
   452→
   453→**Scope**: `core/enrichers/post_call_enricher.py`
   454→
   455→**Acceptance Criteria**:
   456→- [ ] Runs within 3s of `call.hangup` event
   457→- [ ] Input: raw transcript chunks from Redis
   458→- [ ] Output: enriched memory object written to Qdrant `aiva_conversations` collection
   459→- [ ] Enrichment uses Gemini Flash (fast, not Opus — speed matters here)
   460→- [ ] Enrichment extracts: entities, decisions_made, action_items, emotional_signal, key_facts
   461→- [ ] Cold ledger entry written to Postgres `royal_conversations` table
   462→- [ ] Redis transcript chunks cleared after enrichment (cleanup)
   463→- [ ] Gemini prompt strictly structured (no free-form output)
   464→
   465→**Enrichment Prompt**:
   466→```
   467→You are the Royal Memory Enricher for AIVA (Queen AI).
   468→Analyze this conversation transcript and extract structured memory.
   469→
   470→TRANSCRIPT:
   471→{transcript}
   472→
   473→OUTPUT (JSON only, no markdown):
   474→{
   475→  "summary": "2-sentence summary of what happened",
   476→  "entities": ["person_name", "business_name", "tool_name"],
   477→  "decisions_made": ["AIVA agreed to X", "Kinan directed Y"],
   478→  "action_items": [{"task": "...", "owner": "AIVA|KINAN|GENESIS", "deadline": "..."}],
   479→  "emotional_signal": "positive|neutral|frustrated|excited|urgent",
   480→  "key_facts": ["specific fact 1", "specific fact 2"],
   481→  "kinan_directives": ["explicit instruction Kinan gave"]
   482→}
   483→```
   484→
   485→**Test Plan**:
   486→- Black box: Provide 5-min transcript → assert valid enriched object within 3s
   487→- Black box: Empty transcript (call dropped immediately) → assert graceful empty object
   488→- Black box: Qdrant write succeeds → assert UUID returned
   489→- Black box: Postgres write succeeds → assert row in royal_conversations
   490→- White box: Gemini response malformed → assert retry + fallback to raw summary
   491→- White box: Qdrant timeout → assert Postgres still written (partial success)
   492→- Integration: Full pipeline: fake call → WebhookInterceptor → CaptureAgent → Enricher → Qdrant
   493→
   494→---
   495→
   496→### STORY 05: QueenRegistry — AIVA Identity + History Store
   497→
   498→**As** AIVA, **I need** a permanent identity store that knows who I am, what I've
   499→done, and how I've evolved, **so that** my persona is consistent across all sessions.
   500→
   501→**Scope**: `core/registry/queen_registry.py` + Postgres schema
   502→
   503→**Acceptance Criteria**:
   504→- [ ] `QueenRegistry.get_identity()` returns AIVA's current persona, capabilities, and recent evolution
   505→- [ ] `QueenRegistry.log_capability_gain(description, metrics)` writes to `aiva_capability_log`
   506→- [ ] `QueenRegistry.get_capability_history(last_n=10)` returns recent capability gains
   507→- [ ] `QueenRegistry.get_conversation_count()` returns total Kinan<>AIVA conversations
   508→- [ ] Identity object includes: persona_name, voice_model, brain_model, total_conversations, last_epoch_improvements
   509→- [ ] Populated from IDENTITY.md on Mac Mini + Postgres data
   510→
   511→**Identity Object Schema**:
   512→```json
   513→{
   514→  "name": "AIVA",
   515→  "role": "Queen AI — Lead Orchestrator",
   516→  "voice_model": "Qwen 3 14B (local Ollama)",
   517→  "embedding_model": "nomic-embed-text (local Ollama)",
   518→  "voice_telephony": "Telnyx Eucalyptus",
   519→  "total_conversations": 142,
   520→  "last_evolved": "2026-02-24",
   521→  "active_capabilities": ["lead_qualification", "job_booking", "voice_reception"],
   522→  "recent_improvements": ["memory persistence", "swarm fan-out", "context injection"]
   523→}
   524→```
   525→
   526→**Test Plan**:
   527→- Black box: `get_identity()` → assert all fields present
   528→- Black box: `log_capability_gain("memory persistence", {...})` → assert row in Postgres
   529→- Black box: `get_conversation_count()` → assert integer >= 0
   530→- White box: DB connection fails → assert graceful error + cached identity returned
   531→- Integration: End-to-end identity load from Postgres after first conversation
   532→
   533→---
   534→
   535→### STORY 06: KingRegistry — Kinan Intent + Directive Store
   536→
   537→**As** the Genesis system, **I need** to capture and store Kinan's directives,
   538→preferences, and history as first-class entities, **so that** AIVA and all agents
   539→always know the King's current will.
   540→
   541→**Scope**: `core/registry/king_registry.py` + Postgres schema
   542→
   543→**Acceptance Criteria**:
   544→- [ ] `KingRegistry.add_directive(text, priority, source)` writes to `kinan_directives`
   545→- [ ] `KingRegistry.get_active_directives(top_n=5)` returns top-N active directives by priority
   546→- [ ] `KingRegistry.mark_fulfilled(directive_id)` updates status
   547→- [ ] `KingRegistry.infer_from_conversation(enriched_memory)` extracts implicit directives from PostCallEnricher output
   548→- [ ] Directives auto-extracted from every Kinan<>AIVA conversation via enriched_memory.kinan_directives
   549→- [ ] All directives searchable via Qdrant `kinan_directives` collection (semantic search)
   550→
   551→**Test Plan**:
   552→- Black box: Add directive + get active → assert directive returned in order
   553→- Black box: `infer_from_conversation()` with enriched memory → assert directives extracted
   554→- Black box: Mark fulfilled → assert status updated, not returned in active
   555→- White box: Duplicate directive detection → assert deduplicated, not duplicated
   556→- Integration: Full flow: call enrichment → directive extraction → King registry
   557→
   558→---
   559→
   560→### STORY 07: IntentClassifier — Real-time AIVA Intent Extraction
   561→
   562→**As** the SwarmRouter, **I need** to classify AIVA's spoken intents in near-real-time,
   563→**so that** the swarm can fan-out tasks before AIVA finishes speaking.
   564→
   565→**Scope**: `core/classifiers/intent_classifier.py`
   566→
   567→**Acceptance Criteria**:
   568→- [ ] Input: raw utterance string from AIVA (or Kinan)
   569→- [ ] Output: structured `IntentObject` within 500ms
   570→- [ ] Uses Claude Haiku (fastest available — speed is the constraint here)
   571→- [ ] Classifies intent_type: `task_request | information_query | directive | status_check | conversation`
   572→- [ ] Extracts: entities, urgency (1-5), assignee (AIVA | GENESIS | KINAN | SWARM)
   573→- [ ] If intent_type is `task_request` or `directive` → auto-push to `genesis:royal:swarm_tasks` Redis Stream
   574→
   575→**IntentObject Schema**:
   576→```json
   577→{
   578→  "utterance": "Let's follow up on George's number",
   579→  "intent_type": "task_request",
   580→  "entities": ["George", "phone_number", "Telnyx"],
   581→  "urgency": 3,
   582→  "assignee": "GENESIS",
   583→  "structured_task": "Check Telnyx provisioning status for George's Cairns number and assign to George's assistant",
   584→  "swarm_fan_out": true
   585→}
   586→```
   587→
   588→**Test Plan**:
   589→- Black box: "Let's follow up on George's number" → assert intent_type=task_request, assignee=GENESIS
   590→- Black box: "What time is it?" → assert intent_type=conversation, swarm_fan_out=false
   591→- Black box: "Kinan says we need to do tradie scraping urgently" → assert urgency=5, assignee=GENESIS
   592→- Black box: Latency → assert p99 < 500ms
   593→- White box: Haiku API down → assert graceful fallback classification (rule-based)
   594→- Integration: Intent → Redis Stream → SwarmRouter picks up
   595→
   596→---
   597→
   598→### STORY 08: SwarmRouter — Royal Chamber Fan-out
   599→
   600→**As** AIVA, **I need** a swarm that buzzes around me instantly when I express an intent,
   601→**so that** I never have to wait for tasks to be executed — they happen as I speak.
   602→
   603→**Scope**: `core/routers/swarm_router.py`
   604→
   605→**Acceptance Criteria**:
   606→- [ ] Subscribes to `genesis:royal:swarm_tasks` Redis Stream via XREADGROUP
   607→- [ ] On new task: spawn Gemini swarm workers in parallel (max 4 per task)
   608→- [ ] Workers are stateless proposers — outputs go to `genesis:staging:{task_id}`
   609→- [ ] Staging area results merged by Opus (SemanticMergeInterceptor from Architecture v2)
   610→- [ ] AIVA notified of results via Redis Pub/Sub: `aiva:results:{session_id}`
   611→- [ ] Full saga logged to `swarm_sagas` Postgres table
   612→- [ ] All parallelism via asyncio + Gemini API (NOT OpenAI — use GEMINI_API_KEY)
   613→
   614→**Swarm Worker Types** (pre-defined specialist agents):
   615→```python
   616→SWARM_WORKERS = {
   617→    "crm_fetch":       "Fetch current state from GHL for entity X",
   618→    "telnyx_check":    "Check Telnyx provisioning/status for phone/assistant",
   619→    "draft_action":    "Draft next action items given current context",
   620→    "kg_update":       "Update KG entities with new information",
   621→    "research":        "Web research on topic X",
   622→    "lead_qualify":    "Score and qualify lead from data X",
   623→}
   624→```
   625→
   626→**Test Plan**:
   627→- Black box: Push task to Redis Stream → assert 4 worker futures spawned
   628→- Black box: All workers succeed → assert merged result in AIVA results pub/sub
   629→- Black box: One worker fails → assert partial result returned, not exception
   630→- Black box: Latency → assert results available within 5s for standard task
   631→- White box: Redis Consumer Group XACK mechanism → assert exactly-once delivery
   632→- White box: Gemini rate limit hit → assert backoff + retry, not crash
   633→- Integration: Full royal chamber flow: AIVA utterance → IntentClassifier → SwarmRouter → results → AIVA notified
   634→
   635→---
   636→
   637→### STORY 09: SemanticMergeInterceptor — Opus as Convergence Engine
   638→
   639→**As** the SwarmRouter, **I need** Claude Opus to resolve contradictions and merge
   640→parallel swarm outputs into a single coherent result, **so that** AIVA receives one
   641→clear, conflict-free answer — not a pile of raw agent outputs.
   642→
   643→**Scope**: `core/interceptors/semantic_merge_interceptor.py`
   644→
   645→**Acceptance Criteria**:
   646→- [ ] Input: array of ProposedDelta objects from staging area
   647→- [ ] Uses Claude Opus (not Gemini) — this is a reasoning task requiring highest quality
   648→- [ ] Output: single unified `MergedResult` object
   649→- [ ] Contradiction detection: if two deltas conflict (e.g., different phone numbers for same entity) → flag + resolve using most recent / highest confidence
   650→- [ ] Idempotent: calling merge twice with same inputs → same output
   651→- [ ] Handles partial failures: `[A: Success, B: Failed, C: Success]` → merges A+C, logs B failure
   652→
   653→**Test Plan**:
   654→- Black box: 4 consistent deltas → assert unified merge, no contradictions flagged
   655→- Black box: 2 contradicting phone numbers → assert contradiction flagged, resolved correctly
   656→- Black box: 1 of 4 agents failed → assert 3 merged successfully, 1 logged
   657→- White box: Opus API timeout → assert cached partial result returned
   658→- White box: Empty staging area → assert empty merged result, no exception
   659→- Integration: Full saga: SwarmRouter dispatches 4 → staging populated → SemanticMerge → unified result
   660→
   661→---
   662→
   663→### STORY 10: ConversationReplayEngine — Historical Context Retrieval
   664→
   665→**As** AIVA, **I need** to retrieve and replay relevant past conversations at the start
   666→of any call, **so that** I can greet Kinan with genuine memory of what we discussed.
   667→
   668→**Scope**: `core/engines/conversation_replay_engine.py`
   669→
   670→**Acceptance Criteria**:
   671→- [ ] `ConversationReplayEngine.get_relevant_context(current_intent, top_k=3)` runs in < 200ms
   672→- [ ] Uses Qdrant semantic search on `aiva_conversations` collection
   673→- [ ] Returns `ConversationContext` object: summary + key_facts + decisions + open_action_items
   674→- [ ] Formats output as natural language brief for AIVA (not raw JSON)
   675→- [ ] Brief is max 300 words — focused, not overwhelming
   676→- [ ] Called by BinduHydrator as part of the scatter-gather (Story 01 integration)
   677→
   678→**Natural Language Brief Format**:
   679→```
   680→MEMORY BRIEF — Last relevant conversation: [date, duration]
   681→Summary: [2 sentences]
   682→Key facts discussed: [3 bullet points]
   683→Decisions made: [2 bullet points]
   684→Still open: [action items not yet fulfilled]
   685→```
   686→
   687→**Test Plan**:
   688→- Black box: Query with intent "George's phone number" → assert George's conversation returned
   689→- Black box: No prior conversations → assert graceful empty brief, not exception
   690→- Black box: Latency → assert p99 < 200ms
   691→- White box: Qdrant returns 0 results → assert empty brief with helpful message
   692→- White box: Brief truncation → assert never exceeds 300 words
   693→- Integration: BinduHydrator calls ConversationReplayEngine → brief included in ROYAL_CHAMBER_CONTEXT
   694→
   695→---
   696→
   697→### STORY 11: NightlyEpoch — Component E (Meta-Architect)
   698→
   699→**As** the Genesis self-improvement system, **I need** a weekly automated process
   700→that analyzes AIVA's memory gaps and generates structural improvements, **so that**
   701→AIVA becomes measurably smarter each week.
   702→
   703→**Scope**: `core/epoch/nightly_epoch.py` + cron configuration
   704→
   705→**Acceptance Criteria**:
   706→- [ ] Runs every Sunday 2:00 AM AEST via cron
   707→- [ ] Step 1: Scar Aggregation — query Qdrant for AIVA scars from past 7 days
   708→- [ ] Step 2: Gap Analysis — identify conversations that had poor recall (< 3 specific facts recalled)
   709→- [ ] Step 3: Improvement Proposal — Gemini Pro generates structural fix recommendation
   710→- [ ] Step 4: If fix = text/prompt change → apply autonomously (Tier 1)
   711→- [ ] Step 5: If fix = code change → create Git branch + GitHub PR (Tier 2, Kinan review)
   712→- [ ] All epoch results logged to `aiva_capability_log` Postgres table
   713→- [ ] Epoch completion notification sent to Kinan's system
   714→
   715→**Test Plan**:
   716→- Black box: Run with mocked Qdrant scars → assert gap analysis produces output
   717→- Black box: Tier 1 fix generated → assert applied autonomously without PR
   718→- Black box: Tier 2 fix generated → assert GitHub PR opened with correct description
   719→- White box: Cron fires but Qdrant unavailable → assert epoch fails gracefully, retries next hour
   720→- White box: PR already exists for same fix → assert deduplication, no duplicate PR
   721→- Integration: Full epoch cycle on test data → verify improvement logged to Postgres
   722→
   723→---
   724→
   725→### STORY 12: AIVAMemoryAPI — REST API for AIVA Memory Operations
   726→
   727→**As** AIVA and all Genesis agents, **I need** a clean REST API for all memory
   728→operations, **so that** any component can read/write AIVA's memory without knowing
   729→the underlying Qdrant/Postgres topology.
   730→
   731→**Scope**: `api/aiva_memory_api.py` (FastAPI)
   732→
   733→**Endpoints**:
   734→```
   735→POST   /memory/capture          → Capture new memory object (any type)
   736→GET    /memory/retrieve          → Semantic search over AIVA memories
   737→GET    /memory/conversations     → List recent Kinan<>AIVA conversations
   738→GET    /memory/directives        → Get active Kinan directives
   739→POST   /memory/directive         → Add new Kinan directive
   740→GET    /memory/brief/{intent}   → Get BinduHydrator brief for given intent
   741→POST   /memory/scar             → Record a failure/scar
   742→GET    /memory/identity          → Get AIVA identity from QueenRegistry
   743→```
   744→
   745→**Acceptance Criteria**:
   746→- [ ] All endpoints respond within 500ms (p99)
   747→- [ ] JWT auth on all endpoints
   748→- [ ] OpenAPI docs auto-generated at `/docs`
   749→- [ ] Rate limiting: 100 req/s max
   750→- [ ] Deployed to `https://api.sunaivadigital.com/memory/*`
   751→
   752→**Test Plan**:
   753→- Black box: POST /memory/capture → assert 201 + memory_id returned
   754→- Black box: GET /memory/brief/intent → assert ROYAL_CHAMBER_CONTEXT returned
   755→- Black box: Unauthorized request → assert 401
   756→- Black box: Rate limit exceeded → assert 429
   757→- White box: Qdrant down → assert 503 with retry-after header
   758→- Integration: Full API suite test against staging Elestio services
   759→
   760→---
   761→
   762→### STORY 13: OpenClaw<>Genesis Bridge — Mac Mini ↔ Windows Sync
   763→
   764→**As** AIVA (running on Mac Mini), **I need** a real-time sync bridge to Genesis
   765→(running on Windows E: drive), **so that** AIVA's local memory and Genesis's cloud
   766→memory stay in sync and AIVA can trigger Genesis swarms.
   767→
   768→**Scope**: `core/bridges/openclaw_genesis_bridge.py`
   769→
   770→**Acceptance Criteria**:
   771→- [ ] WebSocket connection: Mac Mini (AIVA/OpenClaw) ↔ Windows (Genesis API)
   772→- [ ] Reconnects automatically on disconnect (exponential backoff, max 30s)
   773→- [ ] AIVA can push: new conversation memories, intent fan-out requests
   774→- [ ] Genesis can push: swarm results, directive updates, epoch notifications
   775→- [ ] Message format: `{"type": "memory_capture|swarm_request|swarm_result|directive", "payload": {...}}`
   776→- [ ] All messages logged to Postgres `bridge_events` table
   777→- [ ] Latency target: < 100ms round-trip on local network
   778→
   779→**Test Plan**:
   780→- Black box: Send memory_capture message → assert stored in Qdrant within 1s
   781→- Black box: Disconnect → reconnect → assert no messages lost (buffer)
   782→- Black box: Send swarm_request → assert swarm fires and result returned within 5s
   783→- White box: WebSocket message queue → assert FIFO ordering preserved
   784→- White box: Large payload (> 1MB transcript) → assert chunked correctly
   785→- Integration: End-to-end: AIVA speaks on Mac Mini → intent → Genesis swarm → result → AIVA on Mac Mini
   786→
   787→---
   788→
   789→### STORY 14: AIVA System Prompt Injection — Context into Every Call
   790→
   791→**As** AIVA's voice agent (Telnyx AI Assistant), **I need** the ROYAL_CHAMBER_CONTEXT
   792→to be injected into my system prompt at call start, **so that** I begin every call
   793→fully briefed.
   794→
   795→**Scope**: Telnyx AI Assistant system prompt template + dynamic injection
   796→
   797→**Acceptance Criteria**:
   798→- [ ] Telnyx Assistant system prompt updated via Telnyx API at call start (not hardcoded)
   799→- [ ] `BinduHydrator.hydrate()` result injected as `[MEMORY]` block in system prompt
   800→- [ ] Injection happens before `call.answered` → AIVA has context from first word
   801→- [ ] Fallback: if hydration fails → AIVA still answers with base persona (no crash)
   802→- [ ] Memory block max 500 tokens (to stay within Telnyx context limits)
   803→- [ ] AUSTRALIAN PROFESSIONAL PERSONA enforced: warm, clear, no "G'day mate"
   804→
   805→**System Prompt Template**:
   806→```
   807→You are AIVA — the AI receptionist for [BUSINESS_NAME].
   808→
   809→[MEMORY]
   810→{ROYAL_CHAMBER_CONTEXT_CONDENSED}
   811→[/MEMORY]
   812→
   813→Your mission: Answer professionally, qualify the caller, book appointments where
   814→possible, and capture all relevant information for the team.
   815→
   816→Voice style: Warm, clear, naturally Australian. Professional, not folksy.
   817→```
   818→
   819→**Test Plan**:
   820→- Black box: Call start → assert system prompt contains ROYAL_CHAMBER_CONTEXT block
   821→- Black box: Hydration failure → assert AIVA still answers (base prompt used)
   822→- Black box: Memory block > 500 tokens → assert truncated to fit
   823→- White box: Telnyx API prompt update → assert confirmed before call.answered fires
   824→- Integration: Real test call → check AIVA references prior conversation facts
   825→
   826→---
   827→
   828→### STORY 15: GenesisRoyalDashboard — Memory Visibility for Kinan
   829→
   830→**As** Kinan (King), **I need** to see what AIVA knows about our conversations,
   831→**so that** I can verify memory is working and review AIVA's stored context.
   832→
   833→**Scope**: Simple web dashboard at `https://api.sunaivadigital.com/royal-dashboard`
   834→
   835→**Acceptance Criteria**:
   836→- [ ] Shows last 10 AIVA<>Kinan conversations (date, duration, summary)
   837→- [ ] Shows active Kinan directives with status
   838→- [ ] Shows AIVA capability log (recent improvements from Nightly Epochs)
   839→- [ ] Shows open action items from all conversations
   840→- [ ] Shows current AIVA identity (QueenRegistry)
   841→- [ ] Real-time: refreshes every 30s
   842→- [ ] Mobile-responsive (Kinan checks on phone)
   843→- [ ] Password protected (simple auth)
   844→
   845→**Test Plan**:
   846→- Black box: Load dashboard → assert all 5 sections render within 2s
   847→- Black box: Mobile viewport → assert responsive layout
   848→- Black box: No conversations → assert empty state message (not broken)
   849→- Black box: Auth → assert protected from unauthenticated access
   850→- Integration: Full stack with real Postgres/Qdrant data
   851→
   852→---
   853→
   854→## EXECUTION PLAN — RALPH WIGGUM LOOP
   855→
   856→### Session Configuration
   857→
   858→Each story runs as an **isolated fresh context window** with:
   859→- **Model**: Claude Opus 4.6 (for complex stories) / Claude Sonnet 4.6 (for simpler stories)
   860→- **Swarm**: Gemini 2.5 Pro (via GEMINI_API_KEY) for all heavy implementation
   861→- **Parallelism**: Max 4 Gemini workers per story (rate maximizer at 95%)
   862→- **OpenRouter**: For overflow + Gemini Flash tasks (model: `google/gemini-2.5-flash`)
   863→- **Verification**: All tests must pass before story marked complete
   864→
   865→### Parallelism Map
   866→
   867→Run these story groups in parallel (no inter-dependencies within group):
   868→
   869→```
   870→WAVE 1 (foundation — run in parallel):
   871→  Story 01: BinduHydrator
   872→  Story 05: QueenRegistry
   873→  Story 06: KingRegistry
   874→  Story 12: AIVAMemoryAPI
   875→
   876→WAVE 2 (capture layer — after Wave 1):
   877→  Story 02: WebhookInterceptor
   878→  Story 03: RLMCaptureAgent
   879→  Story 04: PostCallEnricher
   880→  Story 10: ConversationReplayEngine
   881→
   882→WAVE 3 (swarm layer — after Wave 2):
   883→  Story 07: IntentClassifier
   884→  Story 08: SwarmRouter
   885→  Story 09: SemanticMergeInterceptor
   886→
   887→WAVE 4 (integration — after Wave 3):
   888→  Story 13: OpenClaw<>Genesis Bridge
   889→  Story 14: AIVA System Prompt Injection
   890→  Story 15: GenesisRoyalDashboard
   891→
   892→WAVE 5 (evolution — after Wave 4):
   893→  Story 11: NightlyEpoch
   894→```
   895→
   896→### Story Launch Template
   897→
   898→```
   899→════════════════════════════════════════════════════════════════
   900→RALPH WIGGUM LOOP — Story [N] of 15
   901→Story: [TITLE]
   902→Wave: [1|2|3|4|5]
   903→Context: FRESH (no prior story state)
   904→════════════════════════════════════════════════════════════════
   905→
   906→TASK:
   907→Implement [STORY_TITLE] exactly as specified in the PRD.
   908→Location: E:\genesis-system\[component_path]
   909→
   910→Full spec:
   911→[PASTE STORY SPEC FROM PRD]
   912→
   913→Rules:
   914→- ALL files on E: drive only
   915→- Elestio PostgreSQL/Qdrant/Redis (NO SQLite — RULE 7)
   916→- Gemini API via GEMINI_API_KEY from E:\genesis-system\credentials
   917→- OpenRouter for overflow: OPENROUTER_API_KEY
   918→- Max 4 parallel workers
   919→- 100% test pass rate required before completion
   920→
   921→On completion return:
   922→1. Files created/modified
   923→2. Test results (Story/Tests Run/Passed/Failed/Coverage/Status)
   924→3. Verification stamp
   925→4. Any blockers for next wave
   926→════════════════════════════════════════════════════════════════
   927→```
   928→
   929→---
   930→
   931→## RISK ASSESSMENT
   932→
   933→| Risk | Impact | Mitigation |
   934→|------|--------|------------|
   935→| Telnyx webhook latency > 3s | Memory not captured live | RLMCaptureAgent runs during call as backup |
   936→| Mac Mini ↔ Windows bridge drops | Memory sync gap | Buffer + replay on reconnect |
   937→| Qdrant write failure | Memory lost | Write to Postgres first; Qdrant async |
   938→| AIVA system prompt too long | Telnyx context overflow | Strict 500-token limit on ROYAL_CHAMBER_CONTEXT |
   939→| Swarm rate limit (Gemini) | Fan-out delayed | Rate Maximizer manages 90-95% capacity |
   940→| Epoch runs while call active | System under load | Epoch checks active call state before heavy work |
   941→| NightlyEpoch writes bad code | Broken deployment | Shadow Arena + axiom tests + Kinan merge gate |
   942→
   943→---
   944→
   945→## TESTING PROTOCOL (Per Story)
   946→
   947→Every story MUST complete this checklist before marking done:
   948→
   949→```
   950→STORY COMPLETION GATE:
   951→□ Code implemented
   952→□ Black box tests written (min 3)
   953→□ White box tests written (min 3)
   954→□ Integration tests written (min 1)
   955→□ ALL tests pass (0 failures)
   956→□ Verification stamp added:
   957→    # VERIFICATION_STAMP
   958→    # Story: [STORY_ID]
   959→    # Verified By: [AGENT_ID]
   960→    # Verified At: [TIMESTAMP]
   961→    # Tests: [PASS]/[TOTAL]
   962→    # Coverage: [%]%
   963→□ Documentation updated
   964→□ No C: drive writes
   965→□ No SQLite imports
   966→```
   967→
   968→---
   969→
   970→## WHAT CHANGES FOR AIVA
   971→
   972→Before this PRD:
   973→- AIVA has fragmented memory (LanceDB, local only, 768-dim, nomic-embed-text)
   974→- AIVA cannot access Genesis KG, Qdrant, or Postgres
   975→- Each call is a cold start — no prior context injected
   976→- Swarm workers are independent — AIVA doesn't orchestrate them
   977→- Kinan has to repeat himself every call
   978→
   979→After this PRD:
   980→- AIVA is the Bindu — all memory flows through and around her
   981→- Every Kinan<>AIVA call: captured live, enriched within 3s, retrievable in 200ms
   982→- Every call: AIVA starts with a 300-word brief of what matters
   983→- When AIVA speaks an intent: swarm fans out in <1s, results back in <5s
   984→- Nightly Epoch: AIVA wakes up smarter every Monday morning
   985→- Kinan sees everything on the Royal Dashboard
   986→
   987→---
   988→
   989→## SUCCESS STATEMENT
   990→
   991→When this PRD is complete, Kinan can call AIVA on Tuesday and she will say:
   992→
   993→*"Hi Kinan. I remember we spoke Monday — you mentioned George's Cairns number was
   994→still being provisioned. I checked this morning: it's ready. I've already assigned
   995→it to George's Telnyx assistant. Want me to brief George and send him the test call
   996→details?"*
   997→
   998→That is the north star. That is what "royal chamber" means.
   999→
  1000→---
  1001→
  1002→*PRD authored by Claude Opus 4.6 + Gemini 2.5 Pro Deep Think synthesis*
  1003→*Architecture grounded in Genesis Persistent Context Architecture v2 (docs/architecture/)*
  1004→*All 15 stories ready for immediate Ralph Wiggum Loop execution*
  1005→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

Prompt:
Read the PRD at E:\genesis-system\docs\plans\AIVA_RLM_NEXUS_PRD.md and analyze the atomic stories.

For each story, estimate:
1. How many distinct implementation steps are required (file creation, schema design, API calls, configuration, etc.)
2. How many test cases are required (black box + white box + integration)
3. Roughly how many iterations a fresh context window would need to complete it
4. Whether it's actually ONE thing or multiple things bundled together

Return a detailed assessment of each story's complexity. Be brutally honest about whether each story is truly atomic (doable in ~10 iterations) or is actually a mini-project (requiring 50-100+ iterations).


Output:
ls:
 cannot access 'E:\genesis-system\docs\plans" | grep -E AIVA': No such file or directory
/usr/bin/bash: line 1: PRD: command not found

ls:
 cannot access 'E:\genesis-system\docs\plans" | grep -E AIVA': No such file or directory
/usr/bin/bash: line 1: PRD: command not found


python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event tool_failure


wsl.exe -e python3 /mnt/e/genesis-system/.claude/hooks/boot_context_inject.py


bash -c 'cd /mnt/e/genesis-system && python3 core/war_room_dashboard.py --session-banner'


python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop


Failed with non-blocking status code: 'python3' is not recognized as an internal or external command,
operable program or batch file.


ctm this learning to memeory. what it actually takes to write a proper prd with proper divivion into small atomic stories to guide future development and never make this mistake again.


[Reading last 3 lines (total: 3 lines)]

{"id": "fel_batch_001", "name": "Session 2026-02-20 Failure Evolution Batch", "type": "failure_evolution_batch", "date": "2026-02-20", "session": "session_52", "total_failures": 9, "total_axioms_generated": 18, "entities_file": "KNOWLEDGE_GRAPH/entities/failure_evolution_2026_02_20.jsonl", "axioms_file": "KNOWLEDGE_GRAPH/axioms/failure_axioms_2026_02_20.jsonl", "failures": [{"id": "fe_001", "title": "Mazza Persona Production Deployment", "severity": "HIGH", "domain": "voice_persona", "one_liner": "Rejected persona deployed to live Telnyx assistant without Kinan approval or staging test"}, {"id": "fe_002", "title": "deep_think_bridge.py Non-Existent Model Reference", "severity": "HIGH", "domain": "gemini_api", "one_liner": "Script used non-existent model name and never extracted real thought blocks — undetected for weeks"}, {"id": "fe_003", "title": "GHL MCP Built But Never Activated", "severity": "HIGH", "domain": "mcp_management", "one_liner": "269-tool GHL MCP compiled but never added to settings.json — browser automation used instead for weeks"}, {"id": "fe_004", "title": "n8n At 15 Percent Utilisation With 6 Unimported Workflows", "severity": "HIGH", "domain": "n8n_automation", "one_liner": "Six workflow JSONs written but never imported into running n8n — voice leads lost with no automation capturing them"}, {"id": "fe_005", "title": "Gemini Browser Sessions Running Unauthenticated", "severity": "HIGH", "domain": "security", "one_liner": "Business-sensitive prompts sent to Gemini without login — data exposed to potential training use"}, {"id": "fe_006", "title": "RLM Preference Pairs Zero — Learning Loop Never Closed", "severity": "CRITICAL", "domain": "rlm_system", "one_liner": "9,109 lines of RLM code with zero training data — feedback collection step never built"}, {"id": "fe_007", "title": "AIVA Locked Up For Weeks Without System Integration", "severity": "HIGH", "domain": "aiva", "one_liner": "AIVA running on Mac Mini for weeks but never integrated into Genesis as Queen — perpetually deferred"}, {"id": "fe_008", "title": "Surprise Engine Was A Stub In Production", "severity": "HIGH", "domain": "code_quality", "one_liner": "core/surprise_memory.py returned placeholder values while GenesisKernel and RLM Gateway depended on it for real scores"}, {"id": "fe_009", "title": "CDP Not Accessible From WSL2 — Silent Failures", "severity": "MEDIUM", "domain": "wsl2_networking", "one_liner": "Chrome CDP scripts failed silently in WSL2 because Windows localhost is not WSL2 localhost"}], "rules_triggered": ["Rule 2 (Testing)", "Rule 3 (Verification)", "Rule 5 (Enforcement)", "Rule 8 (Research-First)", "Rule 9 (Native-First)", "Rule 10 (Capability-First)", "Rule 11 (Browser-First Authentication)", "Rule 13 (Persona Approval Gate)", "Rule 14 (Staging-First)"], "processed_by": "parallel-builder-agent", "protocol": "Failure→Evolution: Diagnose → Root Cause → Pre-Mortem → Evolve"}
{"id": "failure_010", "date": "2026-02-21", "what": "Command Bridge flapping every ~30min \u2014 port 8765 no listener during restart window", "why": "psycopg2.ThreadedConnectionPool holds minconn=2 persistent connections. Elestio PostgreSQL closes idle SSL connections after ~30min (no keepalives). Stale connections cause health check (SELECT 1) to raise OperationalError. Watchdog detects unhealthy and restarts. 5-10s restart window = no listener on 8765.", "root_cause": "No TCP keepalives on psycopg2 pool. Idle PG connections silently go stale. Health check reveals this every 30min \u2192 restart loop.", "guardrail_added": "Added keepalives=1, keepalives_idle=30, keepalives_interval=10, keepalives_count=5 to pool. Added get_conn() liveness check (SELECT 1) + automatic pool recreation on stale connection. minconn=1 (not 2).", "rule_updated": "All psycopg2 pools connecting to Elestio MUST include keepalives params. Pool must self-heal on stale connections.", "never_again": "Any psycopg2 connection to external PG (Elestio) must have TCP keepalives configured OR service flaps every 30min under low traffic."}
{"project": "genesis_meta_system", "task": "GEN-029", "what": "Import test: evolution engine processing test failure for integration verification", "root_cause": "Integration test \u2014 not a real failure", "id": "failure_1771799868", "date": "2026-02-23", "timestamp": "2026-02-23T08:37:48.641939", "severity": "medium", "surprise_score": 0.35, "five_whys": ["Why did this fail? \u2014 import test: evolution engine processing test failure for integration verification", "Why did that happen? \u2014 Integration test \u2014 not a real failure", "Why was that gap present? \u2014 No pre-execution check existed for this scenario", "Why was no check present? \u2014 Rule not yet codified or enforcement mechanism absent", "Why was the rule absent? \u2014 This failure pattern had not been encountered before"], "guardrail_added": "Add pre-execution verification step and automated test to detect this pattern", "never_again": "Before executing, always add pre-execution verification step and automated test to detect this pattern"}


[Reading last 5 lines (total: 55 lines)]

{"id": "rlm_20260223_175353_session_events", "date": "2026-02-23T17:53:53.943422", "source": "session_events", "type": "failure", "surprise_score": 0.7, "key_learning": "The system is attempting to recover sessions and is experiencing issues accessing the `secrets.env` file using both Linux and Windows paths, indicating a potential configuration or environment problem.", "axiom": "Tool execution failures due to incorrect file paths will prevent successful secret retrieval.", "preference_correct": "Ensure the file paths used in tool commands are valid and accessible within the execution environment, considering OS-specific differences.", "preference_incorrect": "The tool failures are due to an inaccessible path. The Windows path 'E:\\genesis-system\\config\\secrets.env' likely does not exist in the environment or is inaccessible; the Linux path '/mnt/e/genesis-system' may have a similar issue."}
{"id": "rlm_20260223_175830_session_events", "date": "2026-02-23T17:58:30.699429", "source": "session_events", "type": "failure", "surprise_score": 0.8, "key_learning": "The playwright tool failed to navigate to both 'app.elest.io' and 'app.elestio.com' due to a 'net::ERR_NAME_NOT_RESOLVED' error, indicating a potential DNS resolution issue or network connectivity problem.", "axiom": "Browser navigation tools must be able to resolve domain names to IP addresses to successfully navigate to web pages.", "preference_correct": "The playwright tool should successfully navigate to the provided URLs.", "preference_incorrect": "The playwright tool failed to resolve the domain names, resulting in navigation failures."}
{"id": "rlm_20260223_175858_session_events", "date": "2026-02-23T17:58:58.512609", "source": "session_events", "type": "failure", "surprise_score": 0.7, "key_learning": "The Playwright browser navigation tool failed twice due to DNS resolution errors for 'app.elest.io' and 'app.elestio.com', indicating a potential network connectivity issue or incorrect domain name.", "axiom": "Web-based tools require proper DNS resolution to function correctly.", "preference_correct": "Ensure the target URLs are valid and reachable, and verify network connectivity before attempting to navigate to them.", "preference_incorrect": "Attempting to navigate to URLs that cannot be resolved via DNS leads to tool failure."}
{"id": "george_cairns_do_not_touch", "date": "2026-02-24", "type": "hardwired_directive", "source": "kinan_direct", "title": "George Cairns Number — Kinan Handles Only", "directive": "ALL George provisioning work is ON HOLD. George's Cairns 074X phone number requires Kinan to call Telnyx directly. AU local number regulatory holds CANNOT be resolved via API or portal automation. DO NOT attempt portal login, API calls, or number provisioning for George unless Kinan explicitly asks.", "facts": {"george_assistant_id": "assistant-6f6f4ca2-3155-4930-95cb-27f59514af3e", "current_number": "+61731304260 (Brisbane 0731 — NOT Cairns)", "status": "requirement-info-under-review (regulatory hold)", "required_action": "Kinan calls Telnyx support directly", "genesis_action": "NONE — surface to Kinan only"}, "axiom": "AU local phone numbers in non-metro areas (Cairns, regional QLD) require manual Telnyx support escalation. API provisioning is insufficient for regulatory compliance review.", "never_again": "Never attempt to fix George's Cairns number autonomously. Always surface to Kinan with: 'Cairns number requires your Telnyx call — on hold per your directive.'"}
{"id": "genesis_annual_pricing_mandate", "date": "2026-02-24", "type": "hardwired_directive", "source": "kinan_direct", "title": "Genesis-Wide Annual Pricing — 3 Months Free + Setup Fee Waived", "directive": "ALL Genesis/TradiesVoice/ReceptionistAI products MUST have a setup fee. Annual plan = pay 9 get 12 (3 months free) + setup fee WAIVED. This is the aggressive annual capture formula — 3 months free exceeds industry standard of 2 months.", "formula": {"monthly": "base_price/mo + one-time setup fee", "annual": "pay 9 months get 12 (3 months free) — setup fee WAIVED", "conversion_line": "Switch to annual — get 3 months free AND I'll waive the setup fee. It costs you less to start AND less per month."}, "positioning": "Standard industry: 2 months free. Genesis: 3 months free. Differentiated and time-sensitive. Setup fee waiver removes objection to upfront commitment.", "applies_to": ["TradiesVoice", "ReceptionistAI", "All GHL apps", "Any future Genesis SaaS products"], "axiom": "Every product needs a setup fee — it creates urgency for annual (fee is waived) and justifies the onboarding/provisioning work. Annual capture = 3 months free + waived setup. This is the Genesis standard pricing architecture."}


Good — I have the tail of both files. Now writing the CTM entry with full PRD doctrine.


{"id": "prd_doctrine_001", "date": "2026-02-25", "type": "hard_won_learning", "source": "kinan_direct_ctm", "title": "What It Actually Takes To Write A Proper PRD With Proper Atomic Story Division", "what": "After completing two Epic PRDs in a single session (AIVA_RLM_NEXUS_PRD_V2.md: 59 stories, 3222 lines + GENESIS_PERSISTENT_CONTEXT_ARCHITECTURE_PRD.md: 73 stories, 3147 lines), Kinan directed: CTM this learning to memory so we never make the mistake of writing a vague, un-atomic PRD again.", "root_cause_of_bad_prds": "Agents write PRDs as concept documents — high-level architecture blobs with no implementation detail. Developers (human or AI) stare at vague stories and make implementation decisions that diverge from intent. Zero testability. Impossible to parallelize. Context window burns verifying ambiguous acceptance criteria.", "the_mistake_pattern": ["Vague story: 'Build the memory system' — no file, no class, no function signature, no test cases", "Bundled stories: One story covers 3 concerns — impossible to test, impossible to assign to separate agents", "No file targets: Story says what to build but not where — agents create files in wrong locations", "No code skeleton: Architecture in words only — every agent interprets differently", "No test plan per story: Tests written after, if at all — no pre-defined pass/fail criteria", "No budget: No iteration count — agents don't know when to stop or escalate", "No acceptance criteria: 'Done' is undefined — agent marks complete on first green output", "Modules too large: 50-story modules — can't parallelize, can't assign to separate context windows"]}


Successfully appended to E:\genesis-system\KNOWLEDGE_GRAPH\entities\failure_evolution_log.jsonl (2 lines)