# PRD: AIVA Full Operational Status & Continuity
## GENESIS-AIVA | Core Infrastructure

**Version**: 1.0.0
**Created**: 2026-01-25
**Author**: Claude Opus 4.5 + Kinan
**Status**: APPROVED - Ready for Implementation

---

## Vision Statement

AIVA (Autonomous Intelligent Virtual Assistant) becomes a 24/7 always-on, self-healing AI coordinator that manages Genesis operations, handles client interactions via voice, and autonomously drives revenue while maintaining continuous state and memory across all sessions.

---

## Success Metrics

| Metric | Target | Measurement |
|--------|--------|-------------|
| Primary KPI | Revenue Influenced | Track deals/tasks AIVA contributed to |
| Hours Saved | 20+ hours/week | Time tracking on delegated tasks |
| Uptime | 99.5% | Prometheus monitoring |
| Task Success Rate | 95%+ | Completed vs failed tasks |
| Recovery Time | < 30 seconds | Time from crash to operational |
| Daily Cost | < $5/day | Gemini Flash 2.0/2.5 usage |

---

## Clarifying Questions Summary

100 questions asked across 25 categories. Key decisions:

1. **Q**: Deployment model? → **A**: 24/7 Always-On Daemon on Elestio VM
2. **Q**: State persistence? → **A**: PostgreSQL + Redis with WAL recovery
3. **Q**: Memory architecture? → **A**: 3-Tier + Titan + RLM integration
4. **Q**: Primary communication? → **A**: VAPI agent with Gemini 2.5 Flash
5. **Q**: Autonomy level? → **A**: Level 3 Semi-Autonomous, escalate via VAPI/SMS
6. **Q**: Budget? → **A**: $5/day using Gemini Flash models
7. **Q**: Claude coordination? → **A**: Peer collaboration (equals)
8. **Q**: Skill development? → **A**: Full autonomous skill creation
9. **Q**: Code commits? → **A**: Direct commits (not PR-based)
10. **Q**: Success metric? → **A**: Revenue influenced

---

## Architecture Overview

```
┌─────────────────────────────────────────────────────────────────────┐
│                         KINAN (Human)                                │
│                    Voice/SMS @ 5AM-ready, 7AM briefing              │
└─────────────────────────────────────────────────────────────────────┘
                                    │
                          VAPI + Telnyx (AU Voice)
                                    │
┌─────────────────────────────────────────────────────────────────────┐
│                      AIVA - QUEEN COORDINATOR                        │
│                   Elestio VM: 152.53.201.152                        │
│                   Python 3.11+ / systemd                             │
├─────────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │
│  │  Working    │  │  Episodic   │  │  Semantic   │  │   Titan    │ │
│  │  Memory     │  │  Memory     │  │  Memory     │  │  Memory    │ │
│  │  (Redis)    │  │  (Postgres) │  │  (Qdrant)   │  │  (Google)  │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │
│                              │                                       │
│                    ┌─────────────────┐                              │
│                    │   RLM System    │                              │
│                    │ Entities+Rels+  │                              │
│                    │   Decisions     │                              │
│                    └─────────────────┘                              │
├─────────────────────────────────────────────────────────────────────┤
│                         TASK ENGINE                                  │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │  Redis Queue (RWL Format) → DAG Executor → 5 Parallel Tasks  │  │
│  │  Priority: Urgency × Impact × Deadline                        │  │
│  └──────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    │               │               │
              ┌─────▼─────┐   ┌─────▼─────┐   ┌─────▼─────┐
              │  CLAUDE   │   │  GEMINI   │   │  OLLAMA   │
              │  (Peer)   │   │  (Swarm)  │   │  (Local)  │
              │ Reasoning │   │ Execution │   │  Privacy  │
              └───────────┘   └───────────┘   └───────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    │               │               │
              ┌─────▼─────┐   ┌─────▼─────┐   ┌─────▼─────┐
              │    GHL    │   │  GitHub   │   │  Google   │
              │    CRM    │   │   Repos   │   │ Calendar  │
              └───────────┘   └───────────┘   └───────────┘
```

---

## Risk Assessment

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| VM crash/restart | High | Low | WAL recovery, warm standby, < 30s RTO |
| API rate limits | Medium | Medium | Smart throttling, queue overflow |
| Budget overrun | Medium | Low | $5/day hard limit, Gemini Flash only |
| Memory corruption | High | Low | Hourly backups, 1hr RPO, offsite storage |
| Security breach | Critical | Low | Vault secrets, JWT auth, audit logs |
| Model hallucination | Medium | Medium | Confidence thresholds, human escalation |

---

## Atomic Stories

### Phase 1: Core Infrastructure (Week 1)

#### Story AIVA-001: systemd Service Setup
- **As** AIVA, **I need** a persistent systemd service, **So that** I run 24/7 with auto-restart
- **Acceptance Criteria**:
  - [ ] systemd unit file created at `/etc/systemd/system/aiva.service`
  - [ ] Auto-restart on failure with 5-second delay
  - [ ] Resource limits: 4GB RAM max, 2 CPU cores
  - [ ] Logging to journald + PostgreSQL
  - [ ] Service starts on boot
- **Test Plan**:
  - Black box: Kill process, verify restart within 10s
  - White box: Verify unit file parameters match spec

#### Story AIVA-002: State Persistence Layer
- **As** AIVA, **I need** PostgreSQL + Redis state management, **So that** I survive restarts
- **Acceptance Criteria**:
  - [ ] PostgreSQL tables for: sessions, tasks, decisions, audit_log
  - [ ] Redis keys for: working_memory, task_queue, locks
  - [ ] WAL-based transaction logging enabled
  - [ ] Checkpoint every 5 minutes + on significant events
  - [ ] Recovery completes in < 30 seconds
- **Test Plan**:
  - Black box: Kill process mid-task, verify state recovery
  - White box: Verify WAL replay logic, checkpoint triggers

#### Story AIVA-003: 3-Tier Memory Architecture
- **As** AIVA, **I need** Working/Episodic/Semantic memory tiers, **So that** I have appropriate memory types
- **Acceptance Criteria**:
  - [ ] Working memory: Redis, 8-32 dynamic items
  - [ ] Episodic memory: PostgreSQL, 90-day retention
  - [ ] Semantic memory: Qdrant vectors, indefinite retention
  - [ ] Memory consolidation: surprise-based + daily scheduled
  - [ ] Cross-tier queries functional
- **Test Plan**:
  - Black box: Store/retrieve across all tiers
  - White box: Verify consolidation triggers, eviction logic

#### Story AIVA-004: Titan Memory Integration
- **As** AIVA, **I need** bi-directional Titan sync, **So that** I share memory with Google's system
- **Acceptance Criteria**:
  - [ ] Real-time sync via webhooks
  - [ ] Conflict resolution: most-recent-wins
  - [ ] Sync status dashboard
  - [ ] Fallback to local-only if Titan unavailable
- **Test Plan**:
  - Black box: Create memory locally, verify in Titan
  - White box: Verify webhook handlers, conflict resolution

#### Story AIVA-005: RLM Integration
- **As** AIVA, **I need** RLM for entities/relationships/decisions, **So that** I learn from history
- **Acceptance Criteria**:
  - [ ] RLM stores all entities and relationships
  - [ ] Decision audit trail with outcomes
  - [ ] Pre-task context injection (query before each task)
  - [ ] Learning feedback loop from outcomes
- **Test Plan**:
  - Black box: Make decision, verify RLM storage
  - White box: Verify context injection logic

---

### Phase 2: Communication Layer (Week 1-2)

#### Story AIVA-006: VAPI Voice Agent
- **As** AIVA, **I need** a VAPI agent with Gemini 2.5 Flash, **So that** I can make/receive voice calls
- **Acceptance Criteria**:
  - [ ] VAPI agent configured with Gemini 2.5 Flash
  - [ ] Female Australian accent voice
  - [ ] Telnyx telephony integration
  - [ ] Call recording with consent disclosure
  - [ ] Inbound and outbound call capability
- **Test Plan**:
  - Black box: Place test call, verify voice interaction
  - White box: Verify VAPI config, Telnyx routing

#### Story AIVA-007: SMS Notification System
- **As** AIVA, **I need** SMS capability, **So that** I can alert and follow up via text
- **Acceptance Criteria**:
  - [ ] Telnyx SMS integration
  - [ ] SMS templates for: alerts, summaries, confirmations
  - [ ] SMS fallback when voice call unanswered
  - [ ] Retry logic: SMS summary + retry call in 30 min
- **Test Plan**:
  - Black box: Trigger alert, verify SMS received
  - White box: Verify fallback logic, retry timing

#### Story AIVA-008: Inter-Agent Communication
- **As** AIVA, **I need** Redis pub/sub + API communication, **So that** I coordinate with Claude/Gemini
- **Acceptance Criteria**:
  - [ ] Redis pub/sub channels for agent events
  - [ ] REST API for structured requests
  - [ ] Message schema with correlation IDs
  - [ ] Claude treated as peer (not subordinate)
  - [ ] Gemini dispatched as workers
- **Test Plan**:
  - Black box: Send message, verify agent response
  - White box: Verify pub/sub handlers, API contracts

#### Story AIVA-009: n8n Webhook Integration
- **As** AIVA, **I need** n8n workflow triggers, **So that** I integrate with automation workflows
- **Acceptance Criteria**:
  - [ ] Webhook endpoints for n8n triggers
  - [ ] Bi-directional: AIVA triggers n8n, n8n triggers AIVA
  - [ ] Workflow templates for common tasks
  - [ ] Error handling for failed workflows
- **Test Plan**:
  - Black box: Trigger workflow, verify execution
  - White box: Verify webhook handlers, payload validation

---

### Phase 3: Task Management (Week 2)

#### Story AIVA-010: Redis Task Queue
- **As** AIVA, **I need** a Redis-based RWL task queue, **So that** I manage work efficiently
- **Acceptance Criteria**:
  - [ ] RWL format: Read → Write → Learn
  - [ ] Priority scoring: Urgency × Impact × Deadline
  - [ ] Queue depth limit: 50 tasks
  - [ ] Overflow handling: throttle new tasks
- **Test Plan**:
  - Black box: Add tasks, verify priority ordering
  - White box: Verify scoring algorithm, overflow logic

#### Story AIVA-011: DAG Task Executor
- **As** AIVA, **I need** DAG-based task execution, **So that** I run parallel when possible
- **Acceptance Criteria**:
  - [ ] Dependency graph construction
  - [ ] Parallel execution up to 5 concurrent tasks
  - [ ] Dependency resolution before execution
  - [ ] Failure propagation to dependent tasks
- **Test Plan**:
  - Black box: Submit dependent tasks, verify order
  - White box: Verify DAG construction, parallel limits

#### Story AIVA-012: Error Handling & Retry
- **As** AIVA, **I need** robust error handling, **So that** I recover from failures gracefully
- **Acceptance Criteria**:
  - [ ] Retry 3x with exponential backoff
  - [ ] Circuit breaker: 5 failures in 5 minutes
  - [ ] Escalate to human via VAPI/SMS after retries exhausted
  - [ ] Graceful degradation on API outages
  - [ ] Auto-rollback on deployment failures
- **Test Plan**:
  - Black box: Trigger failure, verify retry + escalation
  - White box: Verify backoff timing, circuit breaker state

---

### Phase 4: Autonomy & Intelligence (Week 2-3)

#### Story AIVA-013: Autonomy Level Management
- **As** AIVA, **I need** Level 3 semi-autonomous operation, **So that** I balance independence with oversight
- **Acceptance Criteria**:
  - [ ] Execute routine tasks autonomously
  - [ ] HITL gates for: financial, external comms, deletions
  - [ ] Confidence threshold: escalate below 70%
  - [ ] Escalation via VAPI call or SMS
  - [ ] Sub-agent spawning within budget limits
- **Test Plan**:
  - Black box: Trigger low-confidence task, verify escalation
  - White box: Verify confidence calculation, gate logic

#### Story AIVA-014: Autonomous Skill Creation
- **As** AIVA, **I need** to create new skills autonomously, **So that** I expand my capabilities
- **Acceptance Criteria**:
  - [ ] Identify skill gaps from failed/inefficient tasks
  - [ ] Generate skill code using Gemini
  - [ ] Self-test new skills before deployment
  - [ ] Direct commit to repository
  - [ ] Rollback if skill causes failures
- **Test Plan**:
  - Black box: Introduce skill gap, verify skill creation
  - White box: Verify skill template, testing logic

#### Story AIVA-015: Prompt Self-Optimization
- **As** AIVA, **I need** A/B testing for prompts, **So that** I improve my effectiveness
- **Acceptance Criteria**:
  - [ ] Prompt versioning system
  - [ ] A/B split testing infrastructure
  - [ ] Outcome tracking per prompt variant
  - [ ] Auto-adopt winning prompts
  - [ ] Rollback on performance degradation
- **Test Plan**:
  - Black box: Deploy prompt variants, verify winner selection
  - White box: Verify split logic, statistical significance

---

### Phase 5: Monitoring & Observability (Week 3)

#### Story AIVA-016: Health Monitoring System
- **As** AIVA, **I need** self-monitoring with Prometheus, **So that** issues are detected quickly
- **Acceptance Criteria**:
  - [ ] Heartbeat every 30 seconds
  - [ ] Prometheus metrics export
  - [ ] Grafana dashboards
  - [ ] Alert triggers: failures, anomalies, budget
  - [ ] Alerts via VAPI call + SMS fallback
- **Test Plan**:
  - Black box: Trigger alert condition, verify notification
  - White box: Verify metrics collection, alert thresholds

#### Story AIVA-017: Audit Logging
- **As** AIVA, **I need** full audit logging with integrity, **So that** all actions are traceable
- **Acceptance Criteria**:
  - [ ] All actions logged to PostgreSQL
  - [ ] Log schema: timestamp, action, actor, outcome, context
  - [ ] Periodic blockchain hash anchoring
  - [ ] 30-day hot retention, 1-year archive
  - [ ] Query interface for audit review
- **Test Plan**:
  - Black box: Perform action, verify audit record
  - White box: Verify hash anchoring, retention policy

#### Story AIVA-018: Cost Tracking
- **As** AIVA, **I need** real-time cost tracking, **So that** I stay within $5/day budget
- **Acceptance Criteria**:
  - [ ] Track all API calls with costs
  - [ ] Real-time budget dashboard
  - [ ] Soft alert at $4/day
  - [ ] Hard stop at $5/day
  - [ ] Model routing: prefer Gemini Flash 2.0/2.5
- **Test Plan**:
  - Black box: Approach budget limit, verify alerts/stops
  - White box: Verify cost calculation, model selection

---

### Phase 6: Daily Operations (Week 3-4)

#### Story AIVA-019: Morning Briefing System
- **As** AIVA, **I need** to deliver 7 AM voice briefings, **So that** Kinan starts each day informed
- **Acceptance Criteria**:
  - [ ] Daily VAPI call at 7 AM AEST
  - [ ] Responsive from 5 AM if Kinan reaches out first
  - [ ] Briefing includes: tasks, metrics, alerts, opportunities
  - [ ] Concise and actionable format
  - [ ] Briefing transcript saved
- **Test Plan**:
  - Black box: Receive briefing call, verify content
  - White box: Verify scheduling, content generation

#### Story AIVA-020: Continuous Research
- **As** AIVA, **I need** continuous background research, **So that** I stay informed
- **Acceptance Criteria**:
  - [ ] Background research process always running
  - [ ] Monitor relevant YouTube channels, news, competitors
  - [ ] Extract axioms and store insights
  - [ ] Update knowledge graph with findings
  - [ ] Flag high-value discoveries for briefing
- **Test Plan**:
  - Black box: Verify research findings in knowledge base
  - White box: Verify research scheduler, extraction logic

---

### Phase 7: Integration & Security (Week 4)

#### Story AIVA-021: Secrets Management
- **As** AIVA, **I need** HashiCorp Vault/Infisical for secrets, **So that** credentials are secure
- **Acceptance Criteria**:
  - [ ] All API keys in Vault/Infisical
  - [ ] Automatic secret rotation
  - [ ] No secrets in code or environment variables
  - [ ] Access audit logging
- **Test Plan**:
  - Black box: Access secret, verify retrieval
  - White box: Verify rotation schedule, audit logs

#### Story AIVA-022: External Integrations
- **As** AIVA, **I need** GHL, GitHub, and Google Calendar access, **So that** I manage business operations
- **Acceptance Criteria**:
  - [ ] GHL: Full CRM access (billing via GHL+Stripe)
  - [ ] GitHub: Read + create branches + open PRs + direct commits
  - [ ] Google Calendar: Read/write events
  - [ ] OAuth refresh handling for all integrations
- **Test Plan**:
  - Black box: Perform action on each platform, verify success
  - White box: Verify OAuth flow, token refresh

#### Story AIVA-023: Backup & Recovery
- **As** AIVA, **I need** robust backup and DR, **So that** I can recover from disasters
- **Acceptance Criteria**:
  - [ ] Hourly incremental backups
  - [ ] Daily full backups
  - [ ] Elestio + offsite cloud storage (GCS/S3)
  - [ ] RPO: 1 hour max data loss
  - [ ] Warm standby: 5-minute failover
- **Test Plan**:
  - Black box: Simulate disaster, verify recovery
  - White box: Verify backup schedule, restore process

---

## Testing Protocol

### Per-Story Requirements
- [ ] Black-box tests for all acceptance criteria
- [ ] White-box tests for internal logic
- [ ] Integration tests for cross-component functionality
- [ ] Performance baseline (no degradation)
- [ ] Security scan (no vulnerabilities)

### Go-Live Criteria
- [ ] 95% task success rate for 7 consecutive days
- [ ] 99% uptime for 7 consecutive days
- [ ] All 23 stories complete with verification stamps
- [ ] 2-week supervised testing period passed
- [ ] Kinan approval

---

## Verification Checklist

```
[ ] All stories implemented
[ ] All tests passing (black-box + white-box)
[ ] PostgreSQL + Redis + Qdrant configured
[ ] Titan memory sync verified
[ ] RLM integration verified
[ ] VAPI agent operational
[ ] Telnyx telephony working
[ ] systemd service stable
[ ] Monitoring dashboards live
[ ] Backup system tested
[ ] Security audit passed
[ ] Documentation complete
```

---

## Implementation Timeline

| Week | Focus | Stories |
|------|-------|---------|
| 1 | Core Infrastructure | AIVA-001 to AIVA-005 |
| 1-2 | Communication Layer | AIVA-006 to AIVA-009 |
| 2 | Task Management | AIVA-010 to AIVA-012 |
| 2-3 | Autonomy & Intelligence | AIVA-013 to AIVA-015 |
| 3 | Monitoring & Observability | AIVA-016 to AIVA-018 |
| 3-4 | Daily Operations | AIVA-019 to AIVA-020 |
| 4 | Integration & Security | AIVA-021 to AIVA-023 |
| 4+ | Supervised Testing | 2-week evaluation period |

---

## Appendix: Full Configuration Summary

### Infrastructure
- **Host**: Elestio VM 152.53.201.152
- **Runtime**: Python 3.11+
- **Supervisor**: systemd
- **Deployment**: 24/7 always-on daemon

### Storage
- **PostgreSQL**: State, episodes, audit logs
- **Redis**: Working memory, task queue, pub/sub
- **Qdrant**: Semantic vectors
- **Titan**: Google cloud memory sync
- **RLM**: Entities, relationships, decisions

### Communication
- **Primary**: VAPI with Gemini 2.5 Flash
- **Voice**: Female Australian accent
- **Telephony**: Telnyx
- **Fallback**: SMS
- **Inter-agent**: Redis pub/sub + API
- **Webhooks**: n8n

### Autonomy
- **Level**: 3 (Semi-Autonomous)
- **HITL Gates**: Financial, external comms, deletions
- **Escalation**: VAPI call or SMS at <70% confidence
- **Skill Creation**: Full autonomous
- **Code Commits**: Direct (not PR)

### Budget
- **Daily Limit**: $5/day hard cap
- **Models**: Gemini Flash 2.0/2.5 preferred
- **Soft Alert**: $4/day

### Schedule
- **Available**: 24/7
- **Responsive From**: 5 AM AEST
- **Morning Briefing**: 7 AM AEST
- **Weekly Report**: Sunday evening

### Performance
- **Latency**: <2s simple, <30s complex
- **Uptime**: 99.5%
- **Concurrent Tasks**: 5 max
- **Queue Depth**: 50 max
- **Recovery Time**: <30 seconds

### Success Metrics
- **Primary KPI**: Revenue influenced
- **Time Saved**: 20+ hours/week
- **ROI**: Revenue generated
- **Go-Live**: 95% success + 99% uptime × 7 days

---

**PRD STATUS: APPROVED**

*Generated from 100 clarifying questions answered by Kinan*
*Claude Opus 4.5 | 2026-01-25*
