---
name: AIVA Integration Mastery
description: |
  Complete guide for integrating AIVA (Queen AI) voice assistant with the
  Genesis orchestration system. Covers the 4-phase integration roadmap,
  genesis-voice-bridge MCP tools, Telnyx webhook pipeline, and real-time
  context injection.

  WHEN TO USE:
  - "How do I give AIVA access to Genesis memory?"
  - "Build Telnyx webhook pipeline for call transcripts"
  - "AIVA integration" or "voice bridge"
  - "How does AIVA know what Genesis is working on?"
  - "Inject context into live AIVA call"
  - "Phase 2/3/4 AIVA build"
  - Any task that bridges AIVA voice layer and Genesis KG

  CAPABILITIES:
  - genesis-voice-bridge MCP server (Phase 1, DONE)
  - Telnyx webhook → Genesis KG pipeline (Phase 2, TODO)
  - Real-time context injection during calls (Phase 3, TODO)
  - Full bidirectional command channel (Phase 4, TODO)

allowed-tools:
  - Read
  - Write
  - Bash
  - Edit
---

# AIVA Integration Mastery

## Purpose

AIVA (the Queen AI) is Genesis's voice layer. She answers calls, talks to
leads, and operates autonomously on a Mac Mini M4. Genesis is the orchestration
brain that holds all knowledge, memory, and mission state. This skill guides
the full integration between these two systems across four phases.

**Core problem**: AIVA and Genesis are two separate worlds. AIVA needs to know
what Genesis knows, and Genesis needs to learn from every call AIVA has. This
skill documents how to build that bridge — fully, bidirectionally, in production.

---

## AIVA System Map

```
┌─────────────────────────────────────────────────────────────┐
│                     AIVA (Queen AI)                         │
│                                                             │
│  Hardware:  Mac Mini M4 @ 192.168.1.57 (LAN)               │
│  Framework: OpenClaw (AI orchestration, Mac Mini)           │
│  Brain:     Ollama → Qwen 3 14B (local inference)           │
│  Voice:     Telnyx AI Assistant (handles live calls)        │
│  Memory:    LanceDB + nomic-embed-text (vector, local)      │
│  Phone:     +61 7 3130 4377 (eucalyptus, Australian Female) │
│                                                             │
│  Telnyx AI Assistant IDs:                                   │
│  - Main (AIVA):   assistant-9c42d3ce-e05a-4e34-8083-...    │
│  - George:        assistant-6f6f4ca2-3155-4930-95cb-...    │
└─────────────────────────────────────────────────────────────┘
                            │
                     4-Phase Bridge
                            │
┌─────────────────────────────────────────────────────────────┐
│                  GENESIS (Orchestration Brain)               │
│                                                             │
│  Hardware:  Windows 10 workstation + Elestio cloud          │
│  Brain:     Claude Opus 4.6 (orchestrator)                  │
│  Execution: Gemini swarm via Rate Maximizer                 │
│  Memory:    PostgreSQL + Qdrant + Redis + FalkorDB +        │
│             Supermemory (5-system unified stack)            │
│  KG:        FalkorDB (952 nodes, 285 edges, genesis graph)  │
└─────────────────────────────────────────────────────────────┘
```

**Critical safety rule**: NEVER SSH to 152.53.201.152 (AIVA's remote server).
The Mac Mini local IP (192.168.1.57) is the only valid AIVA access point on LAN.

---

## 4-Phase Integration Roadmap

### Phase 1: Genesis → AIVA (COMPLETE)

**What**: genesis-voice-bridge MCP server exposes Genesis KG to Telnyx AI
Assistant system prompts. AIVA can query Genesis memory when she needs context
during a call.

**Status**: PRODUCTION. Running at port 8900 on genesis workstation.

**Data flow**:
```
Telnyx AI Assistant System Prompt
    → genesis-voice-bridge MCP (port 8900, SSE/HTTP)
    → PostgreSQL + Qdrant + Redis + FalkorDB + Supermemory
    → Returns: project status, decisions, agent state, KG entities
```

**Server location**: `/mnt/e/genesis-system/mcp-servers/genesis-voice-bridge/server.py`

---

### Phase 2: AIVA → Genesis (TODO — BUILD THIS NEXT)

**What**: Every call AIVA has generates data. Call events, transcripts, and
extracted intents should flow back into the Genesis KG automatically via n8n.

**Data flow**:
```
Telnyx call event (webhook)
    → https://api.sunaivadigital.com/webhook/telnyx-lead
    → n8n workflow (parse + enrich)
    → PostgreSQL (episodes table) + Supermemory + FalkorDB
    → Genesis KG updated with call transcript, lead entity, intent
```

**Build guide**: See "Phase 2 Build Guide" section below.

---

### Phase 3: Real-Time Context Injection (TODO)

**What**: When AIVA is mid-call, Genesis can inject fresh context — new lead
data, updated project status, corrected facts — without the call dropping.

**Mechanism**: Redis pub/sub channel. Genesis writes context to
`genesis:aiva:live_context:{call_sid}`. AIVA's system prompt fetcher polls
or subscribes and injects mid-conversation.

**Build guide**: See "Phase 3 Build Guide" section below.

---

### Phase 4: Full Bidirectional (TODO)

**What**: Claude can initiate outbound calls via AIVA, update AIVA's Telnyx
knowledge base remotely, retrain voice prompts, and receive AIVA's local
LanceDB memory as searchable context in Genesis.

**Mechanisms**:
- Outbound calls: Telnyx API `POST /calls` from Genesis
- KB updates: Telnyx AI Assistant API `PATCH /ai/assistants/{id}`
- AIVA local memory sync: SFTP/rsync LanceDB index to Elestio, then index in Qdrant

---

## Phase 1 — genesis-voice-bridge MCP Tools

The server exposes 10 tools to Telnyx AI Assistants via SSE or HTTP.

### Authentication

All requests must include:
```
Authorization: Bearer genesis-voice-bridge-2026-production-key
```

Health check (no auth required):
```
GET http://<host>:8900/health
```

### Tool Reference

#### `get_project_status(project: str = "all")`

Returns current status of Genesis projects.

Arguments:
- `project`: One of `receptionistai`, `clawdtalk`, `sunaiva`, `aiva`, `all`

Usage pattern:
```
When caller asks "what is Genesis working on?" → get_project_status("all")
When caller asks about ReceptionistAI → get_project_status("receptionistai")
```

---

#### `get_war_room()`

Returns active war room state: current missions, completed items, blockers,
running agents, phase status, and key metrics.

Usage pattern:
```
When caller asks "what's happening right now?" → get_war_room()
Session context for daily briefings → get_war_room()
```

---

#### `search_memory(query: str, limit: int = 5)`

Semantic search across Supermemory for any topic. Uses natural language.

Arguments:
- `query`: Natural language search query
- `limit`: Max results (default 5)

Usage pattern:
```
When caller asks about a specific topic → search_memory("telnyx voice pricing")
When caller asks about recent events → search_memory("ReceptionistAI launch", 3)
```

Backend: Supermemory API (`https://api.supermemory.ai/v3/search`), container
tag `genesis-kinan`. Results cached in Redis for 120 seconds.

---

#### `query_knowledge_graph(query: str, query_type: str = "search")`

Queries the FalkorDB knowledge graph.

Arguments:
- `query`: Search term or entity name
- `query_type`: One of `search` (entity lookup), `axioms` (find axioms),
  `relationships` (find graph edges), `stats` (graph statistics)

Usage pattern:
```
Find what Genesis knows about a topic → query_knowledge_graph("ReceptionistAI", "search")
Find proven principles → query_knowledge_graph("velocity", "axioms")
Graph overview → query_knowledge_graph("", "stats")
```

Backend: FalkorDB on Elestio (host configured via `FALKORDB_HOST` env var).
Graph name: `genesis`. Cached 300 seconds.

---

#### `get_recent_decisions(days: int = 7)`

Pulls recent strategic decisions from both PostgreSQL episodes table and
Supermemory. Returns decisions sorted by importance score.

Arguments:
- `days`: Look-back window in days (default 7)

Usage pattern:
```
Morning briefing → get_recent_decisions(1)
Weekly review → get_recent_decisions(7)
```

Backend: Dual-source (PG episodes table + Supermemory semantic search).
Cached 180 seconds.

---

#### `get_agent_status()`

Returns all registered Genesis agents, their roles, and live Redis agent count.

Usage pattern:
```
When caller asks "who is working on what?" → get_agent_status()
Agent availability check → get_agent_status()
```

Agents covered: research-scout, builder, tester, reviewer, documenter,
deployer, alpha-evolve, orchestrator. Cached 600 seconds.

---

#### `get_memory_context()`

Returns the contents of `MEMORY.md` — Genesis's persistent session state.
Truncates intelligently, prioritising sections containing PRIME DIRECTIVE,
WAR ROOM, COMMAND CENTRE, Sunaiva, AIVA.

Usage pattern:
```
Full session context → get_memory_context()
When caller needs comprehensive Genesis state → get_memory_context()
```

Reads from `/mnt/e/genesis-system/MEMORY.md`. Cached 300 seconds.

---

#### `get_session_progress()`

Returns the 5 most recent session progress reports from `hive/progress/`.
These are `.md` files written by dispatched agents during execution.

Usage pattern:
```
"What did agents accomplish today?" → get_session_progress()
Progress update during briefing → get_session_progress()
```

Reads: `/mnt/e/genesis-system/hive/progress/*.md`. Cached 120 seconds.

---

#### `get_architecture_summary()`

Returns a structured summary of Genesis infrastructure: Elestio services,
voice architecture (Telnyx lines, costs), AI model stack, core patterns
(Core Four, Alpha Evolve, Three Pillars), and cost structure.

Usage pattern:
```
Technical briefing → get_architecture_summary()
"How is Genesis built?" → get_architecture_summary()
```

Static content with Redis cache of 900 seconds.

---

#### `get_revenue_status()`

Returns revenue targets, cost structure, product pricing, and financial
pipeline status across all Genesis products.

Usage pattern:
```
"Where are we financially?" → get_revenue_status()
Investor/partner call → get_revenue_status()
```

Static content updated periodically. Cache 600 seconds.

---

### Using genesis-voice-bridge in Telnyx System Prompts

To connect an AI assistant to the bridge, configure the Telnyx AI Assistant
with an MCP server pointing to the voice bridge:

```json
{
  "mcp_servers": [
    {
      "url": "http://<genesis-host>:8900/sse",
      "headers": {
        "Authorization": "Bearer genesis-voice-bridge-2026-production-key"
      }
    }
  ]
}
```

Then instruct the assistant in its system prompt:

```
You have access to Genesis memory tools. Before answering questions about
current projects, decisions, or Genesis status, always call the appropriate
tool to get live data. Do not fabricate project status from memory.

Key tools:
- get_project_status("all") → current project overview
- get_war_room() → active missions and blockers
- search_memory(query) → semantic search across all Genesis knowledge
- get_recent_decisions(7) → strategic decisions this week
```

---

## Phase 2 Build Guide — Telnyx Webhook → Genesis Pipeline

### Goal

Every Telnyx call event (call.answered, call.recording.saved,
call.transcription.ready, call.hangup) triggers an n8n workflow that parses
the payload, extracts entities and intent, and writes structured data back
into the Genesis KG (PostgreSQL episodes + Supermemory + FalkorDB).

### Existing Webhook Endpoint

The Sunaiva lead capture webhook is already live:
```
POST https://api.sunaivadigital.com/webhook/telnyx-lead
```

This endpoint currently handles lead capture. Phase 2 extends it (or creates
a parallel endpoint) to handle call transcription and event data.

### n8n Workflow Architecture

```
Telnyx Webhook Event
    │
    ▼
[Webhook Node] POST /webhook/telnyx-call-event
    │
    ├── event_type == "call.recording.saved"
    │       → [HTTP Request] GET recording URL from Telnyx
    │       → [Whisper/Deepgram Node] Transcribe audio
    │       → [AI Node] Extract: intent, entities, lead_data, sentiment
    │       → [PG Node] INSERT INTO episodes (call_transcript)
    │       → [HTTP Request] POST to Supermemory
    │       → [HTTP Request] POST to FalkorDB (create Lead entity)
    │
    ├── event_type == "call.transcription.ready"
    │       → [AI Node] Parse Telnyx real-time transcript
    │       → [AI Node] Extract intent + entities
    │       → [PG Node] INSERT INTO episodes
    │       → [HTTP Request] POST to Supermemory
    │
    └── event_type == "call.hangup"
            → [AI Node] Generate call summary
            → [PG Node] UPDATE lead record with outcome
            → [HTTP Request] Update FalkorDB lead node
```

### Telnyx Webhook Configuration

Configure the Telnyx messaging profile (or TeXML app) to send events to:
```
POST https://api.sunaivadigital.com/webhook/telnyx-call-event
```

Telnyx signs webhooks with HMAC-SHA256. Validate the `telnyx-signature-ed25519`
header using the public key from the Telnyx portal.

### n8n Workflow: Call Transcript Ingestion

Create this n8n workflow (use n8n MCP tools to build it):

1. **Webhook Trigger**: `POST /webhook/telnyx-call-event`

2. **Switch Node** on `body.data.event_type`:
   - `call.transcription.ready` → transcript branch
   - `call.recording.saved` → recording branch
   - `call.hangup` → summary branch

3. **Transcript Branch**:
   ```javascript
   // Extract from Telnyx transcription payload
   const transcript = $json.data.payload.transcription_data.transcript;
   const call_sid = $json.data.payload.call_control_id;
   const from = $json.data.payload.from;
   const to = $json.data.payload.to;
   const duration = $json.data.payload.call_duration_secs;
   ```

4. **AI Extraction Node** (Claude Haiku via OpenRouter):
   ```
   Prompt: Extract from this call transcript:
   1. Primary intent (lead_inquiry, booking_request, complaint, existing_customer)
   2. Lead name if mentioned
   3. Business name if mentioned
   4. Key pain points (list)
   5. Next action required
   6. Outcome (booked, interested, not_interested, wrong_number)

   Transcript: {transcript}

   Respond in JSON.
   ```

5. **PostgreSQL Insert Node**:
   ```sql
   INSERT INTO episodes (
     content, source_type, importance_score, created_at, metadata
   ) VALUES (
     $transcript, 'telnyx_call', $importance, NOW(),
     '{"call_sid": $call_sid, "from": $from, "intent": $intent}'::jsonb
   )
   ```

6. **Supermemory Add Node**:
   ```
   POST https://api.supermemory.ai/v3/memories
   {
     "content": "Call from {from} on {date}: {transcript_summary}",
     "containerTags": ["genesis-kinan", "aiva-calls"],
     "metadata": { "call_sid": ..., "intent": ..., "outcome": ... }
   }
   ```

7. **FalkorDB Lead Entity** (HTTP Request to FalkorDB REST or via Python):
   ```cypher
   MERGE (l:Lead {phone: $from})
   SET l.last_call = datetime(), l.intent = $intent, l.status = $outcome
   MERGE (l)-[:HAD_CALL]->(c:Call {sid: $call_sid, date: datetime()})
   ```

### PostgreSQL Schema Extension

Add to the existing genesis memory schema:

```sql
-- Extend episodes table (already exists) with call-specific fields
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_sid VARCHAR(100);
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_from VARCHAR(50);
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_to VARCHAR(50);
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_duration_secs INTEGER;
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_intent VARCHAR(100);
ALTER TABLE episodes ADD COLUMN IF NOT EXISTS call_outcome VARCHAR(50);

-- Create dedicated call_logs table for structured call data
CREATE TABLE IF NOT EXISTS call_logs (
    id SERIAL PRIMARY KEY,
    call_sid VARCHAR(100) UNIQUE NOT NULL,
    assistant_id VARCHAR(100),
    from_number VARCHAR(50),
    to_number VARCHAR(50),
    duration_secs INTEGER,
    transcript TEXT,
    intent VARCHAR(100),
    lead_name VARCHAR(200),
    business_name VARCHAR(200),
    pain_points TEXT[],
    outcome VARCHAR(50),
    summary TEXT,
    created_at TIMESTAMP DEFAULT NOW(),
    metadata JSONB DEFAULT '{}'
);
```

---

## Phase 3 Build Guide — Real-Time Context Injection

### Goal

When AIVA is in a live call, Genesis can push updated context into the
conversation without interrupting it. This enables:
- Pushing a fresh lead profile after CRM lookup mid-call
- Correcting outdated information AIVA is about to state
- Injecting a special offer or pricing update
- Flagging that the caller is a known VIP

### Mechanism: Redis Pub/Sub + Telnyx Call Control

```
Genesis writes context update
    → Redis PUBLISH "genesis:aiva:context:{call_sid}" "{json_context}"
    → Voice bridge subscriber receives update
    → Telnyx Call Control API: inject text-to-speech prompt
         POST /v2/calls/{call_control_id}/actions/speak
```

### Implementation

**Step 1**: Extend genesis-voice-bridge with a Redis subscriber thread.

In `server.py`, add after server init:

```python
import threading
import redis as redis_lib
from elestio_config import RedisConfig

def _start_call_context_subscriber():
    """Background thread: subscribe to AIVA live context updates."""
    client = redis_lib.Redis(**RedisConfig.get_connection_params())
    pubsub = client.pubsub()
    pubsub.psubscribe("genesis:aiva:context:*")

    for message in pubsub.listen():
        if message["type"] != "pmessage":
            continue
        try:
            channel = message["channel"].decode()
            call_sid = channel.split(":")[-1]
            data = json.loads(message["data"])
            _inject_context_into_call(call_sid, data)
        except Exception as e:
            logger.error("Context injection failed: %s", e)

def _inject_context_into_call(call_control_id: str, context: dict):
    """Use Telnyx Call Control to speak injected context."""
    import requests as req
    telnyx_key = os.environ.get("TELNYX_API_KEY")
    resp = req.post(
        f"https://api.telnyx.com/v2/calls/{call_control_id}/actions/speak",
        headers={"Authorization": f"Bearer {telnyx_key}"},
        json={
            "payload": context.get("message", ""),
            "voice": "eucalyptus",
            "language": "en-AU",
        },
        timeout=5,
    )
    logger.info("Context injection: %s -> %s", call_control_id, resp.status_code)

# Start subscriber at module load
threading.Thread(target=_start_call_context_subscriber, daemon=True).start()
```

**Step 2**: Genesis publishes context updates.

From Claude/Genesis during an active call:
```python
import redis
from data.genesis_memory.elestio_config import RedisConfig

r = redis.Redis(**RedisConfig.get_connection_params())
r.publish(
    f"genesis:aiva:context:{call_control_id}",
    json.dumps({
        "message": "The caller has just been identified as a VIP client. Offer them the premium tier.",
        "type": "context_update",
        "priority": "high"
    })
)
```

**Step 3**: Add a new MCP tool to genesis-voice-bridge for Genesis to track
active calls.

```python
@mcp.tool
def get_active_calls() -> str:
    """
    Get list of currently active AIVA calls from Redis.
    Returns call_control_ids and metadata for live calls.
    """
    client = _get_cache()
    if not client:
        return "Redis unavailable."

    keys = client.keys("genesis:aiva:active_call:*")
    if not keys:
        return "No active AIVA calls."

    output = f"Active AIVA Calls: {len(keys)}\n\n"
    for key in keys:
        data = json.loads(client.get(key) or "{}")
        output += f"  {key.decode()}: {data}\n"
    return output
```

### Telnyx: Tracking Active Calls

Use Telnyx webhooks (`call.answered`) to register active calls in Redis:

```python
# In n8n or the webhook handler:
# On call.answered event:
r.setex(
    f"genesis:aiva:active_call:{call_control_id}",
    3600,  # 1 hour TTL
    json.dumps({
        "from": from_number,
        "started_at": datetime.utcnow().isoformat(),
        "assistant_id": assistant_id,
    })
)

# On call.hangup event:
r.delete(f"genesis:aiva:active_call:{call_control_id}")
```

---

## Telnyx AI Assistant Integration Details

### Key Assistant IDs

| Assistant | ID | Phone | Voice |
|-----------|-----|-------|-------|
| Main (AIVA) | `assistant-9c42d3ce-e05a-4e34-8083-c91081917637` | +61 7 3130 4377 | eucalyptus (AU Female) |
| George | `assistant-6f6f4ca2-3155-4930-95cb-27f59514af3e` | +61 7 3130 4226 | marlu (AU Male) |

### Configuring MCP on an Assistant

Via Telnyx API:
```bash
curl -X PATCH https://api.telnyx.com/v2/ai/assistants/assistant-9c42d3ce-e05a-4e34-8083-c91081917637 \
  -H "Authorization: Bearer $TELNYX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "context_data": {
      "mcp_servers": [{
        "url": "http://<genesis-workstation-ip>:8900/sse",
        "headers": {
          "Authorization": "Bearer genesis-voice-bridge-2026-production-key"
        }
      }]
    }
  }'
```

Note: `<genesis-workstation-ip>` must be reachable from Telnyx's servers. If
the workstation is behind a home NAT, use ngrok or Cloudflare Tunnel to expose
port 8900.

### Exposing genesis-voice-bridge via Cloudflare Tunnel

Permanent production-grade exposure (free, no ngrok rate limits):

```bash
# Install cloudflared on the genesis workstation
# Then create a named tunnel:
cloudflared tunnel create genesis-voice-bridge
cloudflared tunnel route dns genesis-voice-bridge voice-bridge.agileadapt.com

# Config (~/.cloudflared/config.yml):
tunnel: <tunnel-id>
credentials-file: /root/.cloudflared/<tunnel-id>.json
ingress:
  - hostname: voice-bridge.agileadapt.com
    service: http://localhost:8900
  - service: http_status:404
```

Public URL: `https://voice-bridge.agileadapt.com/sse`

### Telnyx Knowledge Base (for static context)

The Telnyx AI Assistant KB provides static context injected into every call.
For dynamic context, the MCP tools are preferred. Use the KB for:
- Company profile, services, pricing (stable data)
- FAQ answers (changes rarely)
- Script guidance (call flow structure)

Update KB via Telnyx portal or API:
```bash
curl -X PATCH https://api.telnyx.com/v2/ai/knowledge_bases/{kb_id} \
  -H "Authorization: Bearer $TELNYX_API_KEY" \
  -d '{ "entries": [{ "content": "...", "title": "..." }] }'
```

---

## Failure Modes and Recovery

### Phase 1 Failures

| Failure | Symptom | Recovery |
|---------|---------|----------|
| Voice bridge not running | AIVA tools return no data | `cd /mnt/e/genesis-system/mcp-servers/genesis-voice-bridge && python server.py` |
| Redis down | Cache misses, slow responses | Fallback to direct DB queries (handled in code). Restart Elestio Redis. |
| FalkorDB unreachable | KG queries return "FalkorDB connection failed" | Check Elestio FalkorDB status. Bridge continues without KG (graceful degradation). |
| Telnyx can't reach bridge | 0 tool calls in conversation | Check firewall/Cloudflare tunnel. Test: `curl https://voice-bridge.agileadapt.com/health` |
| Auth token mismatch | 401/403 errors in Telnyx | Verify `GENESIS_MCP_AUTH_TOKEN` env var matches Telnyx assistant config |
| Port 8900 conflict | Bridge fails to start | `netstat -ano | findstr :8900` then kill conflicting process |

### Phase 2 Failures

| Failure | Symptom | Recovery |
|---------|---------|----------|
| Webhook not receiving events | Call data never appears in PG | Check Telnyx portal → Messaging Profiles → Event Destinations. Verify URL reachable. |
| n8n workflow inactive | Events received but not processed | Check n8n workflow is active. Re-activate via n8n MCP or portal. |
| Transcript extraction fails | Episodes inserted without intent/entities | Check AI node prompt. Review model availability (OpenRouter balance). |
| PG insert fails | n8n execution errors on DB node | Check Elestio PG connectivity. Verify schema has required columns. |
| Supermemory quota | 429 from Supermemory API | Check plan limits. Add retry with backoff in n8n HTTP node. |

### Phase 3 Failures

| Failure | Symptom | Recovery |
|---------|---------|----------|
| Redis pub/sub dead | Injections not received | Restart Redis subscriber thread in voice bridge. Check Redis connectivity. |
| Telnyx speak action 422 | Context injection rejected | Call may have ended. Check `get_active_calls()` before publishing. |
| Injection too late | AIVA already said wrong info | For time-sensitive data, use pre-call context enrichment instead of mid-call injection. |

### General Voice Bridge Monitoring

Health check (add to monitoring/cron):
```bash
curl -sf https://voice-bridge.agileadapt.com/health || echo "VOICE BRIDGE DOWN"
```

Log monitoring (when running locally):
```bash
# On genesis workstation:
python /mnt/e/genesis-system/mcp-servers/genesis-voice-bridge/server.py 2>&1 | tee /tmp/voice-bridge.log
```

---

## Key Environment Variables

| Variable | Purpose | Default |
|----------|---------|---------|
| `GENESIS_MCP_AUTH_TOKEN` | Bearer token for MCP auth | `genesis-voice-bridge-2026-production-key` |
| `GENESIS_MCP_HOST` | Bind host | `0.0.0.0` |
| `GENESIS_MCP_PORT` | Bind port | `8900` |
| `GENESIS_MCP_TRANSPORT` | `sse` or `http` | `sse` |
| `GENESIS_ROOT` | Path to genesis-system | `/mnt/e/genesis-system` |
| `TELNYX_API_KEY` | Telnyx API key for Call Control | Required for Phase 3 |
| `FALKORDB_HOST` | FalkorDB server host | `152.53.201.152` |
| `FALKORDB_PORT` | FalkorDB port | `6380` |
| `SUPERMEMORY_API_KEY` | Supermemory API key | Set in server.py |
| `SUPERMEMORY_CONTAINER_TAG` | Supermemory container | `genesis-kinan` |

---

## Integration Status Checklist

### Phase 1 (DONE)
- [x] genesis-voice-bridge MCP server implemented
- [x] 10 tools covering all Genesis memory systems
- [x] Bearer token auth + CORS middleware
- [x] Redis response cache (120-600s TTL per tool)
- [x] SSE transport for Telnyx compatibility
- [x] Graceful degradation on individual service failure
- [x] Health check endpoint

### Phase 2 (TODO)
- [ ] n8n webhook receiver for Telnyx call events
- [ ] Call transcription ingestion pipeline
- [ ] Intent/entity extraction via AI node
- [ ] PostgreSQL `call_logs` table schema
- [ ] Supermemory ingestion for call transcripts
- [ ] FalkorDB Lead entity creation/update
- [ ] Telnyx webhook signature validation
- [ ] End-to-end test: make test call → verify data in PG + KG

### Phase 3 (TODO)
- [ ] Redis pub/sub subscriber thread in voice bridge
- [ ] `_inject_context_into_call()` Telnyx Call Control integration
- [ ] `get_active_calls()` MCP tool
- [ ] Active call tracking (Redis, set on call.answered, del on call.hangup)
- [ ] Genesis-side publisher utility function
- [ ] Integration test: publish update → verify AIVA speaks it

### Phase 4 (TODO)
- [ ] Outbound call initiation from Genesis via Telnyx API
- [ ] AIVA Telnyx KB remote update (Telnyx API PATCH)
- [ ] AIVA local LanceDB sync to Elestio Qdrant
- [ ] Claude MCP tool: `initiate_aiva_call(number, context)`
- [ ] Claude MCP tool: `update_aiva_knowledge_base(content)`

---

## Related Skills

- **session-persistence**: How Genesis maintains context across sessions.
  AIVA integration data (call logs, lead entities) should survive session resets.

- **multi-agent-orchestration**: Phase 4 uses agent teams to process calls
  in parallel — research agent enriches lead data while build agent updates KB.

- **n8n-nervous-system**: Phase 2 is an n8n workflow. Use the n8n MCP tools
  (`mcp__n8n__*`) to create and activate the call ingestion workflow.

- **closed-loop-verification**: After building Phase 2, verify end-to-end
  by making a test call and confirming the transcript appears in PostgreSQL
  and Supermemory within 60 seconds.

---

## Quick Reference Commands

```bash
# Start voice bridge (development)
cd /mnt/e/genesis-system/mcp-servers/genesis-voice-bridge
python server.py

# Test health
curl http://localhost:8900/health

# Test authenticated tool call
curl -X POST http://localhost:8900/mcp \
  -H "Authorization: Bearer genesis-voice-bridge-2026-production-key" \
  -H "Content-Type: application/json" \
  -d '{"method": "tools/call", "params": {"name": "get_project_status", "arguments": {"project": "all"}}}'

# Check active Telnyx assistants
curl https://api.telnyx.com/v2/ai/assistants \
  -H "Authorization: Bearer $TELNYX_API_KEY"

# Publish test context injection (Phase 3)
python -c "
import redis, json, sys
sys.path.insert(0, '/mnt/e/genesis-system/data/genesis-memory')
from elestio_config import RedisConfig
r = redis.Redis(**RedisConfig.get_connection_params())
r.publish('genesis:aiva:context:TEST_CALL_SID', json.dumps({'message': 'Test injection', 'type': 'test'}))
print('Published')
"
```

---

## Titan Memory — AIVA Integration Learnings

- **Phase 1 transport**: Telnyx AI Assistants require SSE (not HTTP) for MCP.
  Set `GENESIS_MCP_TRANSPORT=sse` and ensure `/sse` endpoint is accessible.

- **Cloudflare buffering**: SSE through Cloudflare requires `X-Accel-Buffering: no`
  and `Cache-Control: no-cache, no-transform` headers. The middleware in
  `server.py` handles this automatically for the `/sse` path.

- **Voice truncation**: All tool responses must be readable aloud. Keep
  individual results under 500 characters. The bridge truncates automatically
  but tool prompt design should target 100-200 words max per response.

- **Call SID vs Call Control ID**: Telnyx uses two IDs. `call_sid` is the
  unique call identifier. `call_control_id` is the API handle for real-time
  actions (speak, hangup, transfer). Phase 3 injection uses `call_control_id`.

- **AIVA phone boundary**: AIVA's voice is on Telnyx (+61 7 3130 4377).
  Genesis cannot call AIVA's phone number to test — use the Telnyx portal
  "Test Call" feature or call from a real phone.
