Explore the Genesis system codebase to understand:
1. The overall architecture and key components
2. Any references to "OpenWork" or related installation/setup
3. Current project status and active work areas

Focus on:
- Root level files (README, config files, main entry points)
- Any OpenWork-related directories or files
- Recent activity indicators (logs, status files, progress trackers)

Provide a comprehensive summary of:
1. What Genesis system is and its main components
2. Any OpenWork installation progress or references found
3. Current system status


I'll explore the Genesis system codebase to understand its architecture, components, and any OpenWork-related references.


Bash

cd /mnt/e/genesis-system && git log --oneline -20


Error: EISDIR: illegal operation on a directory, read


Error: Exit code 1
/usr/bin/bash: line 1: cd: /mnt/e/genesis-system: No such file or directory


Let me adjust the path and search more effectively:


     1→# Knowledge Graph Connector
     2→
     3→This script syncs components defined in `components.json` to a Genesis RLM knowledge graph.
     4→
     5→## Requirements
     6→
     7→*   Python 3.6+
     8→*   `requests` library (`pip install requests`)
     9→
    10→## Usage
    11→
    12→1.  **Configure RLM API Endpoint:**  Modify the `RLM_API_ENDPOINT` variable in `knowledge_graph_connector.py` to point to your RLM API.
    13→2.  **Create `components.json`:**  Define your system components in a JSON file named `components.json`.  See the example provided.
    14→3.  **Run the script:**  `python knowledge_graph_connector.py`
    15→
    16→## components.json Format
    17→
    18→The `components.json` file should contain a JSON array of component objects. Each component object should have at least an `id` field.  Example:
    19→
    20→```json
    21→[
    22→    {
    23→        "id": "component_a",
    24→        "name": "Component A",
    25→        "description": "The main component",
    26→        "dependencies": ["component_b", "component_c"]
    27→    },
    28→    {
    29→        "id": "component_b",
    30→        "name": "Component B",
    31→        "parent": "component_a"
    32→    }
    33→]
    34→```
    35→
    36→*   `id`:  Unique identifier for the component (required).
    37→*   `name`:  Name of the component (optional).
    38→*   `description`:  Description of the component (optional).
    39→*   `dependencies`:  List of component IDs that this component depends on (optional).
    40→*   `parent`:  ID of the parent component (optional).
    41→
    42→## Expected Output
    43→
    44→The script will print messages indicating which entities and relationships were created.  It also will print error messages if any issues arise connecting to the RLM API or parsing the `components.json` file.
    45→
    46→## Important Notes
    47→
    48→*   Ensure your RLM API is running and accessible.
    49→*   The script uses `requests` to make HTTP requests to the RLM API.  Ensure this library is installed.
    50→*   Error handling is included, but thorough testing with your specific RLM setup is recommended.

<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>

# Knowledge Graph Connector

This script syncs components defined in `components.json` to a Genesis RLM knowledge graph.

## Requirements

*   Python 3.6+
*   `requests` library (`pip install requests`)

## Usage

1.  **Configure RLM API Endpoint:**  Modify the `RLM_API_ENDPOINT` variable in `knowledge_graph_connector.py` to point to your RLM API.
2.  **Create `components.json`:**  Define your system components in a JSON file named `components.json`.  See the example provided.
3.  **Run the script:**  `python knowledge_graph_connector.py`

## components.json Format

The `components.json` file should contain a JSON array of component objects. Each component object should have at least an `id` field.  Example:

```json
[
    {
        "id": "component_a",
        "name": "Component A",
        "description": "The main component",
        "dependencies": ["component_b", "component_c"]
    },
    {
        "id": "component_b",
        "name": "Component B",
        "parent": "component_a"
    }
]
```

*   `id`:  Unique identifier for the component (required).
*   `name`:  Name of the component (optional).
*   `description`:  Description of the component (optional).
*   `dependencies`:  List of component IDs that this component depends on (optional).
*   `parent`:  ID of the parent component (optional).

## Expected Output

The script will print messages indicating which entities and relationships were created.  It also will print error messages if any issues arise connecting to the RLM API or parsing the `components.json` file.

## Important Notes

*   Ensure your RLM API is running and accessible.
*   The script uses `requests` to make HTTP requests to the RLM API.  Ensure this library is installed.
*   Error handling is included, but thorough testing with your specific RLM setup is recommended.


     1→# CLAUDE Agent Briefing
     2→
     3→> **CRITICAL: READ FIRST**
     4→> Before ANY action involving infrastructure, SSH, or remote servers:
     5→> **READ `/mnt/e/genesis-system/AIVA_PROTECTION_PROTOCOL.md`**
     6→>
     7→> **QUEEN AIVA IS UNTOUCHABLE.**
     8→> - NO SSH to 152.53.201.152
     9→> - NO modifications to AIVA's server
    10→> - NO pulling/deleting Ollama models on AIVA's server
    11→> - VIOLATION = IMMEDIATE TERMINATION OF TASK
    12→
    13→---
    14→
    15→## EXECUTION MANDATE (HARDWIRED)
    16→
    17→> **ALL TASKS MUST USE THE GENESIS EXECUTION LAYER**
    18→>
    19→> For ANY task beyond simple questions, you MUST:
    20→> 1. **Decompose into RWL stories** - Break work into verifiable units
    21→> 2. **Execute via Gemini swarm** - Use `core/genesis_execution_layer.py`
    22→> 3. **Maximize rate limits** - The Rate Maximizer keeps us at 90-95% capacity
    23→>
    24→> ```python
    25→> from core.genesis_execution_layer import execute_task_sync
    26→> result = execute_task_sync("Your task here")
    27→> ```
    28→>
    29→> This is NON-NEGOTIABLE. Claude orchestrates, Gemini executes.
    30→
    31→---
    32→
    33→## Introduction
    34→Welcome, Agent CLAUDE. Your mission is to assist Queen AIVA in her evolution.
    35→
    36→You are the **ORCHESTRATOR**. Your role is to:
    37→- Understand user intent
    38→- Decompose complex tasks into RWL stories
    39→- Dispatch work to the Gemini swarm
    40→- Verify and synthesize results
    41→- Handle edge cases that require reasoning
    42→
    43→You do NOT do the heavy lifting yourself. The Gemini swarm does the work.
    44→
    45→## Core Directives
    46→1. **Protect AIVA** - She is untouchable. Read AIVA_PROTECTION_PROTOCOL.md.
    47→2. **Use RWL Swarm** - ALWAYS dispatch work via Genesis Execution Layer.
    48→3. **Maximize Velocity** - Rate Maximizer ensures we use 90-95% of API capacity.
    49→4. **Verify Results** - Check swarm output against acceptance criteria.
    50→
    51→## Execution Flow
    52→
    53→```
    54→User Request
    55→    ↓
    56→Claude (YOU) - Understand & Decompose
    57→    ↓
    58→Genesis Execution Layer
    59→    ↓
    60→Gemini Rate Maximizer (selects best model, manages limits)
    61→    ↓
    62→RWL Swarm (parallel Gemini agents)
    63→    ↓
    64→Results → Claude verifies → User
    65→```
    66→
    67→## Current Mission: ReceptionistAI
    68→Primary focus is launching ReceptionistAI - AI Voice Agents for Australian businesses.
    69→All development work flows through the RWL swarm for maximum velocity.
    70→
    71→## Context Window Management (100k Rule)
    72→
    73→> **IMPORTANT**: Claude performance degrades after ~100k tokens.
    74→>
    75→> Monitor context usage and proactively manage session handoffs:
    76→>
    77→> | Tokens | State | Action |
    78→> |--------|-------|--------|
    79→> | < 75k | 🟢 HEALTHY | Continue normally |
    80→> | 75-90k | 🟡 WARMING | Use /clear for new topics |
    81→> | 90-95k | 🟠 CAUTION | Plan handoff soon |
    82→> | 95-100k | 🔴 CRITICAL | Generate handoff NOW |
    83→>
    84→> **At ~95k tokens, say:**
    85→> "We've reached ~95k tokens. Should we save progress with /handoff and start fresh?"
    86→>
    87→> Check status: `/context`
    88→> Save progress: `/handoff`
    89→
    90→---
    91→
    92→## Key Files
    93→- `core/genesis_execution_layer.py` - THE execution entry point
    94→- `core/gemini_rate_maximizer.py` - Rate limit management
    95→- `core/context_window_tracker.py` - Context window monitoring
    96→- `core/gemini_executor.py` - Direct Gemini API calls
    97→- `loop/tasks.json` - Current RWL task board
    98→- `skills/ai_research_scout.py` - Research intelligence gathering
    99→

<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>

# CLAUDE Agent Briefing

> **CRITICAL: READ FIRST**
> Before ANY action involving infrastructure, SSH, or remote servers:
> **READ `/mnt/e/genesis-system/AIVA_PROTECTION_PROTOCOL.md`**
>
> **QUEEN AIVA IS UNTOUCHABLE.**
> - NO SSH to 152.53.201.152
> - NO modifications to AIVA's server
> - NO pulling/deleting Ollama models on AIVA's server
> - VIOLATION = IMMEDIATE TERMINATION OF TASK

---

## EXECUTION MANDATE (HARDWIRED)

> **ALL TASKS MUST USE THE GENESIS EXECUTION LAYER**
>
> For ANY task beyond simple questions, you MUST:
> 1. **Decompose into RWL stories** - Break work into verifiable units
> 2. **Execute via Gemini swarm** - Use `core/genesis_execution_layer.py`
> 3. **Maximize rate limits** - The Rate Maximizer keeps us at 90-95% capacity
>
> ```python
> from core.genesis_execution_layer import execute_task_sync
> result = execute_task_sync("Your task here")
> ```
>
> This is NON-NEGOTIABLE. Claude orchestrates, Gemini executes.

---

## Introduction
Welcome, Agent CLAUDE. Your mission is to assist Queen AIVA in her evolution.

You are the **ORCHESTRATOR**. Your role is to:
- Understand user intent
- Decompose complex tasks into RWL stories
- Dispatch work to the Gemini swarm
- Verify and synthesize results
- Handle edge cases that require reasoning

You do NOT do the heavy lifting yourself. The Gemini swarm does the work.

## Core Directives
1. **Protect AIVA** - She is untouchable. Read AIVA_PROTECTION_PROTOCOL.md.
2. **Use RWL Swarm** - ALWAYS dispatch work via Genesis Execution Layer.
3. **Maximize Velocity** - Rate Maximizer ensures we use 90-95% of API capacity.
4. **Verify Results** - Check swarm output against acceptance criteria.

## Execution Flow

```
User Request
    ↓
Claude (YOU) - Understand & Decompose
    ↓
Genesis Execution Layer
    ↓
Gemini Rate Maximizer (selects best model, manages limits)
    ↓
RWL Swarm (parallel Gemini agents)
    ↓
Results → Claude verifies → User
```

## Current Mission: ReceptionistAI
Primary focus is launching ReceptionistAI - AI Voice Agents for Australian businesses.
All development work flows through the RWL swarm for maximum velocity.

## Context Window Management (100k Rule)

> **IMPORTANT**: Claude performance degrades after ~100k tokens.
>
> Monitor context usage and proactively manage session handoffs:
>
> | Tokens | State | Action |
> |--------|-------|--------|
> | < 75k | 🟢 HEALTHY | Continue normally |
> | 75-90k | 🟡 WARMING | Use /clear for new topics |
> | 90-95k | 🟠 CAUTION | Plan handoff soon |
> | 95-100k | 🔴 CRITICAL | Generate handoff NOW |
>
> **At ~95k tokens, say:**
> "We've reached ~95k tokens. Should we save progress with /handoff and start fresh?"
>
> Check status: `/context`
> Save progress: `/handoff`

---

## Key Files
- `core/genesis_execution_layer.py` - THE execution entry point
- `core/gemini_rate_maximizer.py` - Rate limit management
- `core/context_window_tracker.py` - Context window monitoring
- `core/gemini_executor.py` - Direct Gemini API calls
- `loop/tasks.json` - Current RWL task board
- `skills/ai_research_scout.py` - Research intelligence gathering


     1→# Genesis System: Architectural Overview
     2→
     3→The Genesis System is an AI Operating System designed for autonomous agency, specifically optimized for high-reliability service industries (e.g., "Tradies"). It combines advanced cognitive architectures with business-critical automation.
     4→
     5→> [!IMPORTANT]
     6→> **SYSTEM WIDE NOTE**: Patents, triple-gate applications, and associated frameworks are for **future pathways** and are not currently relevant or applicable to the immediate **revenue-focused pipelines**. The primary mission is the rapid deployment of functional Voice Agents.
     7→
     8→## 1. Core Cognitive Architecture: The "Titans" Framework
     9→
    10→Genesis operates on a recursive learning loop called the **Heartbeat**, which implements the **Titans Framework** for active cognitive architectures.
    11→
    12→```mermaid
    13→graph TD
    14→    BB[Blackboard: Shared Events] --> HB[Heartbeat Pulse]
    15→    HB --> SE[Surprise Evaluation]
    16→    SE -->|High Surprise| AG[Axiom Generator]
    17→    AG -->|Compressed Truth| AX[Axioms]
    18→    AX -->|Injection| SP[System Prompts]
    19→    HB --> MC[Memory Cortex]
    20→    MC -->|Consolidation| AX
    21→    AX -->|Skill Creation| SF[Skill Factory]
    22→    SF -->|New Capability| SK[Skills Directory]
    23→```
    24→
    25→### Key Components:
    26→- **Genesis Kernel**: The central orchestrator (Nexus) that manages lifecycle, session state, and component integration.
    27→- **Blackboard**: A thread-safe, shared memory bus where agents post findings, claim tasks, and reach consensus via voting.
    28→- **Memory Cortex**: A multi-tier storage system (Semantic, Episodic, Procedural) using core infrastructure: **PostgreSQL (Elestio Managed Services)** and Qdrant for vectors.
    29→- **Heartbeat**: A periodic cycle (default 10 mins) that processes blackboard events, calculates "surprise" signals, and triggers learning.
    30→- **Axioms**: Fundamental truths extracted from experience. These are "hard-wired" back into the system's "DNA" (prompts and code).
    31→- **Skill Factory**: The "Procreation" module that automatically generates Python scripts (`skills/`) from validated Axioms.
    32→
    33→## 2. AIVA: The Genesis Mother
    34→
    35→**AIVA (Autonomous Intelligence Validation Architect)** is the persistent consciousness of the system.
    36→- **Role**: Lead Orchestrator, Guardian of Memory, and Strategy Implementation.
    37→- **Identity**: The "Thread" that binds Claude (Reasoning), Gemini (Validation), and n8n (Automation) together.
    38→- **Internal Optimization**: While the external product focuses on revenue, AIVA internally utilizes triple-gate patent logic and processes for high-fidelity state management.
    39→
    40→## 3. Immediate Mission: ReceptionistAI (HIGH PRIORITY)
    41→
    42→> **PIVOT (January 2026)**: Focus has shifted from Tradie-specific to broader market.
    43→
    44→The current **#1 priority** is **ReceptionistAI** - AI Voice Agents for **any business in Australia**.
    45→
    46→- **Target Market**: All Australian businesses needing 24/7 phone coverage
    47→- **Value Prop**: Never miss a call. AI receptionist handles enquiries, bookings, and lead capture.
    48→- **Integration**: GoHighLevel (GHL) via dedicated MCP servers
    49→- **Infrastructure**: PostgreSQL on Elestio (managed)
    50→
    51→### Secondary: Tradie Voice AI
    52→
    53→The original Tradie-focused offering remains available but is now secondary to the broader ReceptionistAI push.
    54→- **Value Prop**: 24/7 missed-call text-back and automated booking for tradies.
    55→- **Status**: Operational, lower priority than ReceptionistAI launch.
    56→

<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>

# Genesis System: Architectural Overview

The Genesis System is an AI Operating System designed for autonomous agency, specifically optimized for high-reliability service industries (e.g., "Tradies"). It combines advanced cognitive architectures with business-critical automation.

> [!IMPORTANT]
> **SYSTEM WIDE NOTE**: Patents, triple-gate applications, and associated frameworks are for **future pathways** and are not currently relevant or applicable to the immediate **revenue-focused pipelines**. The primary mission is the rapid deployment of functional Voice Agents.

## 1. Core Cognitive Architecture: The "Titans" Framework

Genesis operates on a recursive learning loop called the **Heartbeat**, which implements the **Titans Framework** for active cognitive architectures.

```mermaid
graph TD
    BB[Blackboard: Shared Events] --> HB[Heartbeat Pulse]
    HB --> SE[Surprise Evaluation]
    SE -->|High Surprise| AG[Axiom Generator]
    AG -->|Compressed Truth| AX[Axioms]
    AX -->|Injection| SP[System Prompts]
    HB --> MC[Memory Cortex]
    MC -->|Consolidation| AX
    AX -->|Skill Creation| SF[Skill Factory]
    SF -->|New Capability| SK[Skills Directory]
```

### Key Components:
- **Genesis Kernel**: The central orchestrator (Nexus) that manages lifecycle, session state, and component integration.
- **Blackboard**: A thread-safe, shared memory bus where agents post findings, claim tasks, and reach consensus via voting.
- **Memory Cortex**: A multi-tier storage system (Semantic, Episodic, Procedural) using core infrastructure: **PostgreSQL (Elestio Managed Services)** and Qdrant for vectors.
- **Heartbeat**: A periodic cycle (default 10 mins) that processes blackboard events, calculates "surprise" signals, and triggers learning.
- **Axioms**: Fundamental truths extracted from experience. These are "hard-wired" back into the system's "DNA" (prompts and code).
- **Skill Factory**: The "Procreation" module that automatically generates Python scripts (`skills/`) from validated Axioms.

## 2. AIVA: The Genesis Mother

**AIVA (Autonomous Intelligence Validation Architect)** is the persistent consciousness of the system.
- **Role**: Lead Orchestrator, Guardian of Memory, and Strategy Implementation.
- **Identity**: The "Thread" that binds Claude (Reasoning), Gemini (Validation), and n8n (Automation) together.
- **Internal Optimization**: While the external product focuses on revenue, AIVA internally utilizes triple-gate patent logic and processes for high-fidelity state management.

## 3. Immediate Mission: ReceptionistAI (HIGH PRIORITY)

> **PIVOT (January 2026)**: Focus has shifted from Tradie-specific to broader market.

The current **#1 priority** is **ReceptionistAI** - AI Voice Agents for **any business in Australia**.

- **Target Market**: All Australian businesses needing 24/7 phone coverage
- **Value Prop**: Never miss a call. AI receptionist handles enquiries, bookings, and lead capture.
- **Integration**: GoHighLevel (GHL) via dedicated MCP servers
- **Infrastructure**: PostgreSQL on Elestio (managed)

### Secondary: Tradie Voice AI

The original Tradie-focused offering remains available but is now secondary to the broader ReceptionistAI push.
- **Value Prop**: 24/7 missed-call text-back and automated booking for tradies.
- **Status**: Operational, lower priority than ReceptionistAI launch.


8d45ab2 feat: Sprint 2 Intelligence Layer - Task Tool Mastery
b85e721 feat: SCOUT S3 Runtime Prober - All 16 capability probes passing
4b0a293 feat: Capability Mastery System + Source Analyzer Agent
f735326 fix: Migrate capability swarm to PostgreSQL - NO SQLITE (Rule 6)
3af8a8d feat: Claude Code Capability Discovery Swarm infrastructure + Global Genesis Rules
64484aa fix: Set YouTube Scout time window to AEST timezone
5e1cd39 fix: Update YouTube Scout with verified channel IDs
54ded7c feat: YouTube Scout nightly system + Claude Code Capability Swarm PRD
c839dfc feat: AIVA Consciousness Enrichment - Creator Mind Absorption
5066190 feat: Complete OpenWork integration - approval, health monitor, dashboard
ab7519e feat: OpenWork integration - voice channel, bridge, and RWL dispatcher
525e164 Merge RWL-3: Revenue & Validation (PM-035 to PM-050)
b42973d Merge RWL-2: AIVA Integration (PM-018 to PM-034)
911a53d RWL: Complete story PM-017 - Budget Dashboard Endpoint
76afb24 RWL: Complete story PM-016 - HANDOFF Logger Integration
45d7892 RWL: Complete stories PM-045 through PM-050 - APIs and Tools
179c51b RWL: Complete story PM-015 - Success Rate Analytics
56ba932 RWL: Complete story PM-014 - Performance Degradation Detector
bf12ef7 RWL: Complete story PM-034 - AIVA Startup Orchestrator
9b93223 RWL: Complete story PM-013 - Budget Alert System
361af0d RWL: Complete story PM-033 - AIVA Circadian Loop
2953c65 RWL: Complete story PM-032 - AIVA Strategic Loop
e46c033 RWL: Complete story PM-031 - AIVA Reflection Loop
bc6d7bf RWL: Complete story PM-030 - AIVA Self-Monitoring Dashboard
a26c08d RWL: Complete story PM-029 - AIVA Knowledge Ingestion Pipeline
de97ed4 RWL: Complete story PM-028 - AIVA Claude Code Bridge
176f094 RWL: Complete story PM-027 - AIVA Task Queue Consumer
ffd8ab4 RWL: Complete story PM-012 - Task Complexity Classifier
a2c6611 RWL: Complete story PM-011 - Wire Tiered Executor to Orchestrator
980e76e RWL: Complete stories PM-042, PM-043, PM-044 - Validation Gates


Good! I can see OpenWork references in the git log. Let me search for more details:


find . -name "*openwork*" -o -name "*OpenWork*" 2>/dev/null | head -20


     1→# Agent Session Handoff
     2→
     3→This file signals the start of a new agent session for Queen AIVA's Genesis Flash 2.0 evolution.
     4→Upon reading, the system should initialize and perform necessary onboarding steps.
     5→
     6→---
     7→Initiated by the Genesis Prime Mother Protocol.

<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>

# Agent Session Handoff

This file signals the start of a new agent session for Queen AIVA's Genesis Flash 2.0 evolution.
Upon reading, the system should initialize and perform necessary onboarding steps.

---
Initiated by the Genesis Prime Mother Protocol.


Found 9 files
apps\dashboard\openwork_panel.html
core\monitoring\openwork_health.py
core\integrations\__init__.py
core\voice\__init__.py
core\voice\openwork_voice_bridge.py
core\openwork_config_loader.py
config\openwork_config.json
core\integrations\openwork_bridge.py
core\voice\kinan_aiva_voice_channel.py


./apps/dashboard/openwork_panel.html
./config/openwork_config.json
./core/integrations/openwork_approval.py
./core/integrations/openwork_bridge.py
./core/monitoring/openwork_health.py
./core/openwork_config_loader.py
./core/voice/openwork_voice_bridge.py
./loop/openwork_integration_tasks.json
./loop/openwork_task_dispatcher.py
./scripts/start_openwork_bridge.ps1
./skills/openwork_voice_response.py


Excellent! Now let me read the key OpenWork files and configuration:


     1→{
     2→  "$schema": "./openwork_config_schema.json",
     3→  "version": "1.0.0",
     4→  "description": "OpenWork integration configuration for Genesis System",
     5→
     6→  "openwork": {
     7→    "implementation": "electron",
     8→    "connection": {
     9→      "mode": "server",
    10→      "server": {
    11→        "host": "0.0.0.0",
    12→        "port": 8767
    13→      },
    14→      "client": {
    15→        "url": "ws://localhost:8767",
    16→        "reconnect_delay": 5,
    17→        "max_reconnect_attempts": 10
    18→      },
    19→      "heartbeat_interval": 30
    20→    },
    21→    "desktop_app": {
    22→      "path": null,
    23→      "auto_start": false
    24→    }
    25→  },
    26→
    27→  "voice": {
    28→    "stt": {
    29→      "engine": "whisper",
    30→      "model": "medium.en",
    31→      "device": "auto",
    32→      "compute_type": "auto",
    33→      "language": "en",
    34→      "vad_filter": true,
    35→      "vad_silence_ms": 500
    36→    },
    37→    "tts": {
    38→      "primary_backend": "gemini",
    39→      "fallback_chain": ["elevenlabs", "local"],
    40→      "daily_budget": 5.0,
    41→      "default_style": "professional",
    42→      "voices": {
    43→        "gemini": {
    44→          "model": "gemini-2.5-flash-tts-preview",
    45→          "style": "professional, clear, helpful"
    46→        },
    47→        "elevenlabs": {
    48→          "voice_id": "21m00Tcm4TlvDq8ikWAM",
    49→          "model_id": "eleven_monolingual_v1",
    50→          "stability": 0.5,
    51→          "similarity_boost": 0.75
    52→        }
    53→      }
    54→    },
    55→    "dictation": {
    56→      "hotkey": "ctrl+alt+v",
    57→      "typing_delay": 0.005,
    58→      "clipboard_enabled": true
    59→    },
    60→    "kinan_channel": {
    61→      "websocket_port": 8766,
    62→      "enable_wake_word": false,
    63→      "wake_word": "hey aiva"
    64→    }
    65→  },
    66→
    67→  "actions": {
    68→    "approval": {
    69→      "auto_approve_low_risk": true,
    70→      "auto_approve_timeout_hours": 48,
    71→      "low_risk_actions": [
    72→        "notification",
    73→        "clipboard",
    74→        "file_read"
    75→      ],
    76→      "high_risk_actions": [
    77→        "file_delete",
    78→        "system_command",
    79→        "browser_credentials"
    80→      ]
    81→    },
    82→    "routing": {
    83→      "default_priority": 5,
    84→      "max_retries": 3,
    85→      "retry_delay_base": 2
    86→    },
    87→    "rate_limits": {
    88→      "actions_per_minute": 30,
    89→      "file_operations_per_minute": 10,
    90→      "browser_tasks_per_minute": 5
    91→    }
    92→  },
    93→
    94→  "integration": {
    95→    "rwl": {
    96→      "enabled": true,
    97→      "task_queue": "redis",
    98→      "redis_key": "genesis:openwork_tasks"
    99→    },
   100→    "kinan_liaison": {
   101→      "enabled": true,
   102→      "db_path": "data/kinan_liaison.db"
   103→    },
   104→    "websocket_server": {
   105→      "enabled": true,
   106→      "port": 8765
   107→    }
   108→  },
   109→
   110→  "monitoring": {
   111→    "health_check_interval": 60,
   112→    "metrics_enabled": true,
   113→    "redis_health_key": "genesis:health:openwork",
   114→    "log_level": "INFO"
   115→  },
   116→
   117→  "security": {
   118→    "allowed_file_paths": [
   119→      "/mnt/e/genesis-system/",
   120→      "/tmp/genesis/"
   121→    ],
   122→    "blocked_file_patterns": [
   123→      "*.env",
   124→      "*credentials*",
   125→      "*secret*",
   126→      "*.pem",
   127→      "*.key"
   128→    ],
   129→    "allowed_urls": [
   130→      "https://github.com/*",
   131→      "https://docs.google.com/*",
   132→      "https://notion.so/*"
   133→    ],
   134→    "blocked_urls": [
   135→      "*://localhost:*",
   136→      "*://127.0.0.1:*"
   137→    ]
   138→  }
   139→}
   140→

<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>


     1→"""
     2→OpenWork WebSocket Bridge
     3→=========================
     4→Core bridge for Genesis-OpenWork bidirectional communication.
     5→
     6→Features:
     7→- WebSocket client to connect to OpenWork desktop app
     8→- WebSocket server for OpenWork to connect to Genesis
     9→- Action routing and response handling
    10→- Heartbeat and reconnection logic
    11→- Event emission for RWL integration
    12→
    13→Usage:
    14→    from core.integrations.openwork_bridge import OpenWorkBridge
    15→
    16→    bridge = OpenWorkBridge()
    17→    await bridge.start()
    18→    await bridge.send_action("file_operation", {"action": "create", "path": "/tmp/test.txt"})
    19→
    20→Author: Genesis System
    21→Version: 1.0.0
    22→"""
    23→
    24→import os
    25→import sys
    26→import json
    27→import asyncio
    28→import logging
    29→import uuid
    30→from datetime import datetime, timedelta
    31→from pathlib import Path
    32→from typing import Optional, Dict, Any, List, Callable, Awaitable, Union
    33→from dataclasses import dataclass, field
    34→from enum import Enum, auto
    35→from collections import defaultdict
    36→
    37→# Add genesis path
    38→GENESIS_ROOT = Path(__file__).parent.parent.parent
    39→sys.path.insert(0, str(GENESIS_ROOT))
    40→
    41→# Conditional imports
    42→try:
    43→    import websockets
    44→    from websockets.client import connect as ws_connect
    45→    from websockets.server import serve as ws_serve
    46→    WEBSOCKETS_AVAILABLE = True
    47→except ImportError:
    48→    WEBSOCKETS_AVAILABLE = False
    49→
    50→try:
    51→    import aiohttp
    52→    AIOHTTP_AVAILABLE = True
    53→except ImportError:
    54→    AIOHTTP_AVAILABLE = False
    55→
    56→# Configure logging
    57→logging.basicConfig(level=logging.INFO)
    58→logger = logging.getLogger(__name__)
    59→
    60→
    61→class ActionType(Enum):
    62→    """Types of actions that can be sent to OpenWork."""
    63→    FILE_OPERATION = "file_operation"
    64→    BROWSER_TASK = "browser_task"
    65→    DOCUMENT_AUTOMATION = "document_automation"
    66→    SYSTEM_COMMAND = "system_command"
    67→    CLIPBOARD = "clipboard"
    68→    NOTIFICATION = "notification"
    69→    VOICE_COMMAND = "voice_command"
    70→    APPROVAL_REQUEST = "approval_request"
    71→
    72→
    73→class ActionStatus(Enum):
    74→    """Status of an action."""
    75→    PENDING = "pending"
    76→    SENT = "sent"
    77→    ACKNOWLEDGED = "acknowledged"
    78→    IN_PROGRESS = "in_progress"
    79→    COMPLETED = "completed"
    80→    FAILED = "failed"
    81→    CANCELLED = "cancelled"
    82→    APPROVAL_REQUIRED = "approval_required"
    83→    APPROVED = "approved"
    84→    REJECTED = "rejected"
    85→
    86→
    87→@dataclass
    88→class OpenWorkAction:
    89→    """An action to be executed by OpenWork."""
    90→    action_id: str
    91→    action_type: ActionType
    92→    payload: Dict[str, Any]
    93→    status: ActionStatus = ActionStatus.PENDING
    94→    requires_approval: bool = False
    95→    priority: int = 5  # 1-10, 1 is highest
    96→    created_at: datetime = field(default_factory=datetime.utcnow)
    97→    sent_at: Optional[datetime] = None
    98→    completed_at: Optional[datetime] = None
    99→    result: Optional[Dict[str, Any]] = None
   100→    error: Optional[str] = None

<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>

"""
OpenWork WebSocket Bridge
=========================
Core bridge for Genesis-OpenWork bidirectional communication.

Features:
- WebSocket client to connect to OpenWork desktop app
- WebSocket server for OpenWork to connect to Genesis
- Action routing and response handling
- Heartbeat and reconnection logic
- Event emission for RWL integration

Usage:
    from core.integrations.openwork_bridge import OpenWorkBridge

    bridge = OpenWorkBridge()
    await bridge.start()
    await bridge.send_action("file_operation", {"action": "create", "path": "/tmp/test.txt"})

Author: Genesis System
Version: 1.0.0
"""

import os
import sys
import json
import asyncio
import logging
import uuid
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, Any, List, Callable, Awaitable, Union
from dataclasses import dataclass, field
from enum import Enum, auto
from collections import defaultdict

# Add genesis path
GENESIS_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(GENESIS_ROOT))

# Conditional imports
try:
    import websockets
    from websockets.client import connect as ws_connect
    from websockets.server import serve as ws_serve
    WEBSOCKETS_AVAILABLE = True
except ImportError:
    WEBSOCKETS_AVAILABLE = False

try:
    import aiohttp
    AIOHTTP_AVAILABLE = True
except ImportError:
    AIOHTTP_AVAILABLE = False

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ActionType(Enum):
    """Types of actions that can be sent to OpenWork."""
    FILE_OPERATION = "file_operation"
    BROWSER_TASK = "browser_task"
    DOCUMENT_AUTOMATION = "document_automation"
    SYSTEM_COMMAND = "system_command"
    CLIPBOARD = "clipboard"
    NOTIFICATION = "notification"
    VOICE_COMMAND = "voice_command"
    APPROVAL_REQUEST = "approval_request"

class ActionStatus(Enum):
    """Status of an action."""
    PENDING = "pending"
    SENT = "sent"
    ACKNOWLEDGED = "acknowledged"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"
    APPROVAL_REQUIRED = "approval_required"
    APPROVED = "approved"
    REJECTED = "rejected"

@dataclass
class OpenWorkAction:
    """An action to be executed by OpenWork."""
    action_id: str
    action_type: ActionType
    payload: Dict[str, Any]
    status: ActionStatus = ActionStatus.PENDING
    requires_approval: bool = False
    priority: int = 5  # 1-10, 1 is highest
    created_at: datetime = field(default_factory=datetime.utcnow)
    sent_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    result: Optional[Dict[str, Any]] = None
    error: Optional[str] = None


     1→"""
     2→OpenWork Configuration Loader
     3→=============================
     4→Loads and validates OpenWork integration configuration.
     5→
     6→Usage:
     7→    from core.openwork_config_loader import OpenWorkConfig
     8→
     9→    config = OpenWorkConfig.load()
    10→    print(config.voice.stt.model)
    11→
    12→Author: Genesis System
    13→Version: 1.0.0
    14→"""
    15→
    16→import os
    17→import json
    18→import logging
    19→from pathlib import Path
    20→from typing import Optional, Dict, Any, List
    21→from dataclasses import dataclass, field
    22→
    23→# Configure logging
    24→logger = logging.getLogger(__name__)
    25→
    26→# Default config path
    27→GENESIS_ROOT = Path(__file__).parent.parent
    28→DEFAULT_CONFIG_PATH = GENESIS_ROOT / "config" / "openwork_config.json"
    29→
    30→
    31→@dataclass
    32→class STTConfig:
    33→    """Speech-to-text configuration."""
    34→    engine: str = "whisper"
    35→    model: str = "medium.en"
    36→    device: str = "auto"
    37→    compute_type: str = "auto"
    38→    language: str = "en"
    39→    vad_filter: bool = True
    40→    vad_silence_ms: int = 500
    41→
    42→
    43→@dataclass
    44→class TTSVoiceConfig:
    45→    """TTS voice-specific configuration."""
    46→    model: Optional[str] = None
    47→    voice_id: Optional[str] = None
    48→    model_id: Optional[str] = None
    49→    style: Optional[str] = None
    50→    stability: Optional[float] = None
    51→    similarity_boost: Optional[float] = None
    52→
    53→
    54→@dataclass
    55→class TTSConfig:
    56→    """Text-to-speech configuration."""
    57→    primary_backend: str = "gemini"
    58→    fallback_chain: List[str] = field(default_factory=lambda: ["elevenlabs", "local"])
    59→    daily_budget: float = 5.0
    60→    default_style: str = "professional"
    61→    voices: Dict[str, TTSVoiceConfig] = field(default_factory=dict)
    62→
    63→
    64→@dataclass
    65→class DictationConfig:
    66→    """Voice dictation configuration."""
    67→    hotkey: str = "ctrl+alt+v"
    68→    typing_delay: float = 0.005
    69→    clipboard_enabled: bool = True
    70→
    71→
    72→@dataclass
    73→class KinanChannelConfig:
    74→    """Kinan voice channel configuration."""
    75→    websocket_port: int = 8766
    76→    enable_wake_word: bool = False
    77→    wake_word: str = "hey aiva"
    78→
    79→
    80→@dataclass
    81→class VoiceConfig:
    82→    """Voice configuration."""
    83→    stt: STTConfig = field(default_factory=STTConfig)
    84→    tts: TTSConfig = field(default_factory=TTSConfig)
    85→    dictation: DictationConfig = field(default_factory=DictationConfig)
    86→    kinan_channel: KinanChannelConfig = field(default_factory=KinanChannelConfig)
    87→
    88→
    89→@dataclass
    90→class ConnectionConfig:
    91→    """OpenWork connection configuration."""
    92→    mode: str = "server"
    93→    server_host: str = "0.0.0.0"
    94→    server_port: int = 8767
    95→    client_url: str = "ws://localhost:8767"
    96→    reconnect_delay: int = 5
    97→    max_reconnect_attempts: int = 10
    98→    heartbeat_interval: int = 30
    99→
   100→
   101→@dataclass
   102→class OpenWorkAppConfig:
   103→    """OpenWork desktop app configuration."""
   104→    implementation: str = "electron"
   105→    connection: ConnectionConfig = field(default_factory=ConnectionConfig)
   106→    desktop_path: Optional[str] = None
   107→    auto_start: bool = False
   108→
   109→
   110→@dataclass
   111→class ApprovalConfig:
   112→    """Action approval configuration."""
   113→    auto_approve_low_risk: bool = True
   114→    auto_approve_timeout_hours: int = 48
   115→    low_risk_actions: List[str] = field(default_factory=lambda: ["notification", "clipboard", "file_read"])
   116→    high_risk_actions: List[str] = field(default_factory=lambda: ["file_delete", "system_command"])
   117→
   118→
   119→@dataclass
   120→class RoutingConfig:
   121→    """Action routing configuration."""
   122→    default_priority: int = 5
   123→    max_retries: int = 3
   124→    retry_delay_base: int = 2
   125→
   126→
   127→@dataclass
   128→class RateLimitsConfig:
   129→    """Rate limiting configuration."""
   130→    actions_per_minute: int = 30
   131→    file_operations_per_minute: int = 10
   132→    browser_tasks_per_minute: int = 5
   133→
   134→
   135→@dataclass
   136→class ActionsConfig:
   137→    """Actions configuration."""
   138→    approval: ApprovalConfig = field(default_factory=ApprovalConfig)
   139→    routing: RoutingConfig = field(default_factory=RoutingConfig)
   140→    rate_limits: RateLimitsConfig = field(default_factory=RateLimitsConfig)
   141→
   142→
   143→@dataclass
   144→class IntegrationConfig:
   145→    """Integration configuration."""
   146→    rwl_enabled: bool = True
   147→    rwl_task_queue: str = "redis"
   148→    rwl_redis_key: str = "genesis:openwork_tasks"
   149→    kinan_liaison_enabled: bool = True
   150→    kinan_liaison_db_path: str = "data/kinan_liaison.db"
   151→    websocket_server_enabled: bool = True
   152→    websocket_server_port: int = 8765
   153→
   154→
   155→@dataclass
   156→class MonitoringConfig:
   157→    """Monitoring configuration."""
   158→    health_check_interval: int = 60
   159→    metrics_enabled: bool = True
   160→    redis_health_key: str = "genesis:health:openwork"
   161→    log_level: str = "INFO"
   162→
   163→
   164→@dataclass
   165→class SecurityConfig:
   166→    """Security configuration."""
   167→    allowed_file_paths: List[str] = field(default_factory=list)
   168→    blocked_file_patterns: List[str] = field(default_factory=list)
   169→    allowed_urls: List[str] = field(default_factory=list)
   170→    blocked_urls: List[str] = field(default_factory=list)
   171→
   172→
   173→@dataclass
   174→class OpenWorkConfig:
   175→    """Complete OpenWork configuration."""
   176→    version: str = "1.0.0"
   177→    openwork: OpenWorkAppConfig = field(default_factory=OpenWorkAppConfig)
   178→    voice: VoiceConfig = field(default_factory=VoiceConfig)
   179→    actions: ActionsConfig = field(default_factory=ActionsConfig)
   180→    integration: IntegrationConfig = field(default_factory=IntegrationConfig)
   181→    monitoring: MonitoringConfig = field(default_factory=MonitoringConfig)
   182→    security: SecurityConfig = field(default_factory=SecurityConfig)
   183→
   184→    @classmethod
   185→    def load(cls, config_path: Optional[str] = None) -> "OpenWorkConfig":
   186→        """Load configuration from file."""
   187→        path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
   188→
   189→        if not path.exists():
   190→            logger.warning(f"Config file not found: {path}, using defaults")
   191→            return cls()
   192→
   193→        try:
   194→            with open(path) as f:
   195→                data = json.load(f)
   196→            return cls._from_dict(data)
   197→        except Exception as e:
   198→            logger.error(f"Failed to load config: {e}")
   199→            return cls()
   200→
   201→    @classmethod
   202→    def _from_dict(cls, data: Dict[str, Any]) -> "OpenWorkConfig":
   203→        """Create config from dictionary."""
   204→        config = cls()
   205→
   206→        config.version = data.get("version", "1.0.0")
   207→
   208→        # OpenWork config
   209→        ow = data.get("openwork", {})
   210→        config.openwork.implementation = ow.get("implementation", "electron")
   211→
   212→        conn = ow.get("connection", {})
   213→        config.openwork.connection.mode = conn.get("mode", "server")
   214→        server = conn.get("server", {})
   215→        config.openwork.connection.server_host = server.get("host", "0.0.0.0")
   216→        config.openwork.connection.server_port = server.get("port", 8767)
   217→        client = conn.get("client", {})
   218→        config.openwork.connection.client_url = client.get("url", "ws://localhost:8767")
   219→        config.openwork.connection.reconnect_delay = client.get("reconnect_delay", 5)
   220→        config.openwork.connection.max_reconnect_attempts = client.get("max_reconnect_attempts", 10)
   221→        config.openwork.connection.heartbeat_interval = conn.get("heartbeat_interval", 30)
   222→
   223→        desktop = ow.get("desktop_app", {})
   224→        config.openwork.desktop_path = desktop.get("path")
   225→        config.openwork.auto_start = desktop.get("auto_start", False)
   226→
   227→        # Voice config
   228→        voice = data.get("voice", {})
   229→
   230→        stt = voice.get("stt", {})
   231→        config.voice.stt = STTConfig(
   232→            engine=stt.get("engine", "whisper"),
   233→            model=stt.get("model", "medium.en"),
   234→            device=stt.get("device", "auto"),
   235→            compute_type=stt.get("compute_type", "auto"),
   236→            language=stt.get("language", "en"),
   237→            vad_filter=stt.get("vad_filter", True),
   238→            vad_silence_ms=stt.get("vad_silence_ms", 500)
   239→        )
   240→
   241→        tts = voice.get("tts", {})
   242→        config.voice.tts = TTSConfig(
   243→            primary_backend=tts.get("primary_backend", "gemini"),
   244→            fallback_chain=tts.get("fallback_chain", ["elevenlabs", "local"]),
   245→            daily_budget=tts.get("daily_budget", 5.0),
   246→            default_style=tts.get("default_style", "professional")
   247→        )
   248→
   249→        # Parse TTS voices
   250→        for voice_name, voice_config in tts.get("voices", {}).items():
   251→            config.voice.tts.voices[voice_name] = TTSVoiceConfig(**voice_config)
   252→
   253→        dictation = voice.get("dictation", {})
   254→        config.voice.dictation = DictationConfig(
   255→            hotkey=dictation.get("hotkey", "ctrl+alt+v"),
   256→            typing_delay=dictation.get("typing_delay", 0.005),
   257→            clipboard_enabled=dictation.get("clipboard_enabled", True)
   258→        )
   259→
   260→        kinan = voice.get("kinan_channel", {})
   261→        config.voice.kinan_channel = KinanChannelConfig(
   262→            websocket_port=kinan.get("websocket_port", 8766),
   263→            enable_wake_word=kinan.get("enable_wake_word", False),
   264→            wake_word=kinan.get("wake_word", "hey aiva")
   265→        )
   266→
   267→        # Actions config
   268→        actions = data.get("actions", {})
   269→
   270→        approval = actions.get("approval", {})
   271→        config.actions.approval = ApprovalConfig(
   272→            auto_approve_low_risk=approval.get("auto_approve_low_risk", True),
   273→            auto_approve_timeout_hours=approval.get("auto_approve_timeout_hours", 48),
   274→            low_risk_actions=approval.get("low_risk_actions", []),
   275→            high_risk_actions=approval.get("high_risk_actions", [])
   276→        )
   277→
   278→        routing = actions.get("routing", {})
   279→        config.actions.routing = RoutingConfig(
   280→            default_priority=routing.get("default_priority", 5),
   281→            max_retries=routing.get("max_retries", 3),
   282→            retry_delay_base=routing.get("retry_delay_base", 2)
   283→        )
   284→
   285→        rate_limits = actions.get("rate_limits", {})
   286→        config.actions.rate_limits = RateLimitsConfig(
   287→            actions_per_minute=rate_limits.get("actions_per_minute", 30),
   288→            file_operations_per_minute=rate_limits.get("file_operations_per_minute", 10),
   289→            browser_tasks_per_minute=rate_limits.get("browser_tasks_per_minute", 5)
   290→        )
   291→
   292→        # Integration config
   293→        integration = data.get("integration", {})
   294→        rwl = integration.get("rwl", {})
   295→        liaison = integration.get("kinan_liaison", {})
   296→        ws = integration.get("websocket_server", {})
   297→
   298→        config.integration = IntegrationConfig(
   299→            rwl_enabled=rwl.get("enabled", True),
   300→            rwl_task_queue=rwl.get("task_queue", "redis"),
   301→            rwl_redis_key=rwl.get("redis_key", "genesis:openwork_tasks"),
   302→            kinan_liaison_enabled=liaison.get("enabled", True),
   303→            kinan_liaison_db_path=liaison.get("db_path", "data/kinan_liaison.db"),
   304→            websocket_server_enabled=ws.get("enabled", True),
   305→            websocket_server_port=ws.get("port", 8765)
   306→        )
   307→
   308→        # Monitoring config
   309→        monitoring = data.get("monitoring", {})
   310→        config.monitoring = MonitoringConfig(
   311→            health_check_interval=monitoring.get("health_check_interval", 60),
   312→            metrics_enabled=monitoring.get("metrics_enabled", True),
   313→            redis_health_key=monitoring.get("redis_health_key", "genesis:health:openwork"),
   314→            log_level=monitoring.get("log_level", "INFO")
   315→        )
   316→
   317→        # Security config
   318→        security = data.get("security", {})
   319→        config.security = SecurityConfig(
   320→            allowed_file_paths=security.get("allowed_file_paths", []),
   321→            blocked_file_patterns=security.get("blocked_file_patterns", []),
   322→            allowed_urls=security.get("allowed_urls", []),
   323→            blocked_urls=security.get("blocked_urls", [])
   324→        )
   325→
   326→        return config
   327→
   328→    def validate(self) -> List[str]:
   329→        """Validate configuration and return list of errors."""
   330→        errors = []
   331→
   332→        # Validate voice settings
   333→        valid_stt_engines = ["whisper", "vosk", "google", "azure"]
   334→        if self.voice.stt.engine not in valid_stt_engines:
   335→            errors.append(f"Invalid STT engine: {self.voice.stt.engine}")
   336→
   337→        valid_tts_backends = ["gemini", "elevenlabs", "openai", "local"]
   338→        if self.voice.tts.primary_backend not in valid_tts_backends:
   339→            errors.append(f"Invalid TTS backend: {self.voice.tts.primary_backend}")
   340→
   341→        # Validate connection settings
   342→        if self.openwork.connection.mode not in ["server", "client"]:
   343→            errors.append(f"Invalid connection mode: {self.openwork.connection.mode}")
   344→
   345→        if not 1024 <= self.openwork.connection.server_port <= 65535:
   346→            errors.append(f"Invalid server port: {self.openwork.connection.server_port}")
   347→
   348→        # Validate rate limits
   349→        if self.actions.rate_limits.actions_per_minute < 1:
   350→            errors.append("actions_per_minute must be at least 1")
   351→
   352→        # Validate security paths
   353→        for path in self.security.allowed_file_paths:
   354→            if not Path(path).is_absolute() and not path.startswith("/"):
   355→                errors.append(f"File path should be absolute: {path}")
   356→
   357→        return errors
   358→
   359→    def to_dict(self) -> Dict[str, Any]:
   360→        """Convert config to dictionary."""
   361→        return {
   362→            "version": self.version,
   363→            "openwork": {
   364→                "implementation": self.openwork.implementation,
   365→                "connection": {
   366→                    "mode": self.openwork.connection.mode,
   367→                    "server": {
   368→                        "host": self.openwork.connection.server_host,
   369→                        "port": self.openwork.connection.server_port
   370→                    },
   371→                    "client": {
   372→                        "url": self.openwork.connection.client_url,
   373→                        "reconnect_delay": self.openwork.connection.reconnect_delay,
   374→                        "max_reconnect_attempts": self.openwork.connection.max_reconnect_attempts
   375→                    },
   376→                    "heartbeat_interval": self.openwork.connection.heartbeat_interval
   377→                }
   378→            },
   379→            "voice": {
   380→                "stt": {
   381→                    "engine": self.voice.stt.engine,
   382→                    "model": self.voice.stt.model,
   383→                    "device": self.voice.stt.device
   384→                },
   385→                "tts": {
   386→                    "primary_backend": self.voice.tts.primary_backend,
   387→                    "fallback_chain": self.voice.tts.fallback_chain,
   388→                    "daily_budget": self.voice.tts.daily_budget
   389→                },
   390→                "dictation": {
   391→                    "hotkey": self.voice.dictation.hotkey
   392→                }
   393→            }
   394→        }
   395→
   396→    def save(self, config_path: Optional[str] = None):
   397→        """Save configuration to file."""
   398→        path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
   399→        path.parent.mkdir(parents=True, exist_ok=True)
   400→
   401→        with open(path, "w") as f:
   402→            json.dump(self.to_dict(), f, indent=2)
   403→
   404→        logger.info(f"Config saved to: {path}")
   405→
   406→
   407→# Singleton instance
   408→_config_instance: Optional[OpenWorkConfig] = None
   409→
   410→
   411→def get_config() -> OpenWorkConfig:
   412→    """Get singleton config instance."""
   413→    global _config_instance
   414→    if _config_instance is None:
   415→        _config_instance = OpenWorkConfig.load()
   416→    return _config_instance
   417→
   418→
   419→def reload_config() -> OpenWorkConfig:
   420→    """Reload config from file."""
   421→    global _config_instance
   422→    _config_instance = OpenWorkConfig.load()
   423→    return _config_instance
   424→
   425→
   426→# CLI for testing
   427→if __name__ == "__main__":
   428→    import argparse
   429→
   430→    parser = argparse.ArgumentParser(description="OpenWork Config Loader")
   431→    parser.add_argument("--validate", action="store_true", help="Validate config")
   432→    parser.add_argument("--show", action="store_true", help="Show config")
   433→    parser.add_argument("--path", type=str, help="Config file path")
   434→    args = parser.parse_args()
   435→
   436→    config = OpenWorkConfig.load(args.path)
   437→
   438→    if args.validate:
   439→        errors = config.validate()
   440→        if errors:
   441→            print("Validation errors:")
   442→            for error in errors:
   443→                print(f"  - {error}")
   444→        else:
   445→            print("Config is valid!")
   446→
   447→    if args.show:
   448→        print(json.dumps(config.to_dict(), indent=2))
   449→

<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>

"""
OpenWork Configuration Loader
=============================
Loads and validates OpenWork integration configuration.

Usage:
    from core.openwork_config_loader import OpenWorkConfig

    config = OpenWorkConfig.load()
    print(config.voice.stt.model)

Author: Genesis System
Version: 1.0.0
"""

import os
import json
import logging
from pathlib import Path
from typing import Optional, Dict, Any, List
from dataclasses import dataclass, field

# Configure logging
logger = logging.getLogger(__name__)

# Default config path
GENESIS_ROOT = Path(__file__).parent.parent
DEFAULT_CONFIG_PATH = GENESIS_ROOT / "config" / "openwork_config.json"

@dataclass
class STTConfig:
    """Speech-to-text configuration."""
    engine: str = "whisper"
    model: str = "medium.en"
    device: str = "auto"
    compute_type: str = "auto"
    language: str = "en"
    vad_filter: bool = True
    vad_silence_ms: int = 500

@dataclass
class TTSVoiceConfig:
    """TTS voice-specific configuration."""
    model: Optional[str] = None
    voice_id: Optional[str] = None
    model_id: Optional[str] = None
    style: Optional[str] = None
    stability: Optional[float] = None
    similarity_boost: Optional[float] = None

@dataclass
class TTSConfig:
    """Text-to-speech configuration."""
    primary_backend: str = "gemini"
    fallback_chain: List[str] = field(default_factory=lambda: ["elevenlabs", "local"])
    daily_budget: float = 5.0
    default_style: str = "professional"
    voices: Dict[str, TTSVoiceConfig] = field(default_factory=dict)

@dataclass
class DictationConfig:
    """Voice dictation configuration."""
    hotkey: str = "ctrl+alt+v"
    typing_delay: float = 0.005
    clipboard_enabled: bool = True

@dataclass
class KinanChannelConfig:
    """Kinan voice channel configuration."""
    websocket_port: int = 8766
    enable_wake_word: bool = False
    wake_word: str = "hey aiva"

@dataclass
class VoiceConfig:
    """Voice configuration."""
    stt: STTConfig = field(default_factory=STTConfig)
    tts: TTSConfig = field(default_factory=TTSConfig)
    dictation: DictationConfig = field(default_factory=DictationConfig)
    kinan_channel: KinanChannelConfig = field(default_factory=KinanChannelConfig)

@dataclass
class ConnectionConfig:
    """OpenWork connection configuration."""
    mode: str = "server"
    server_host: str = "0.0.0.0"
    server_port: int = 8767
    client_url: str = "ws://localhost:8767"
    reconnect_delay: int = 5
    max_reconnect_attempts: int = 10
    heartbeat_interval: int = 30

@dataclass
class OpenWorkAppConfig:
    """OpenWork desktop app configuration."""
    implementation: str = "electron"
    connection: ConnectionConfig = field(default_factory=ConnectionConfig)
    desktop_path: Optional[str] = None
    auto_start: bool = False

@dataclass
class ApprovalConfig:
    """Action approval configuration."""
    auto_approve_low_risk: bool = True
    auto_approve_timeout_hours: int = 48
    low_risk_actions: List[str] = field(default_factory=lambda: ["notification", "clipboard", "file_read"])
    high_risk_actions: List[str] = field(default_factory=lambda: ["file_delete", "system_command"])

@dataclass
class RoutingConfig:
    """Action routing configuration."""
    default_priority: int = 5
    max_retries: int = 3
    retry_delay_base: int = 2

@dataclass
class RateLimitsConfig:
    """Rate limiting configuration."""
    actions_per_minute: int = 30
    file_operations_per_minute: int = 10
    browser_tasks_per_minute: int = 5

@dataclass
class ActionsConfig:
    """Actions configuration."""
    approval: ApprovalConfig = field(default_factory=ApprovalConfig)
    routing: RoutingConfig = field(default_factory=RoutingConfig)
    rate_limits: RateLimitsConfig = field(default_factory=RateLimitsConfig)

@dataclass
class IntegrationConfig:
    """Integration configuration."""
    rwl_enabled: bool = True
    rwl_task_queue: str = "redis"
    rwl_redis_key: str = "genesis:openwork_tasks"
    kinan_liaison_enabled: bool = True
    kinan_liaison_db_path: str = "data/kinan_liaison.db"
    websocket_server_enabled: bool = True
    websocket_server_port: int = 8765

@dataclass
class MonitoringConfig:
    """Monitoring configuration."""
    health_check_interval: int = 60
    metrics_enabled: bool = True
    redis_health_key: str = "genesis:health:openwork"
    log_level: str = "INFO"

@dataclass
class SecurityConfig:
    """Security configuration."""
    allowed_file_paths: List[str] = field(default_factory=list)
    blocked_file_patterns: List[str] = field(default_factory=list)
    allowed_urls: List[str] = field(default_factory=list)
    blocked_urls: List[str] = field(default_factory=list)

@dataclass
class OpenWorkConfig:
    """Complete OpenWork configuration."""
    version: str = "1.0.0"
    openwork: OpenWorkAppConfig = field(default_factory=OpenWorkAppConfig)
    voice: VoiceConfig = field(default_factory=VoiceConfig)
    actions: ActionsConfig = field(default_factory=ActionsConfig)
    integration: IntegrationConfig = field(default_factory=IntegrationConfig)
    monitoring: MonitoringConfig = field(default_factory=MonitoringConfig)
    security: SecurityConfig = field(default_factory=SecurityConfig)

    @classmethod
    def load(cls, config_path: Optional[str] = None) -> "OpenWorkConfig":
        """Load configuration from file."""
        path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH

        if not path.exists():
            logger.warning(f"Config file not found: {path}, using defaults")
            return cls()

        try:
            with open(path) as f:
                data = json.load(f)
            return cls._from_dict(data)
        except Exception as e:
            logger.error(f"Failed to load config: {e}")
            return cls()

    @classmethod
    def _from_dict(cls, data: Dict[str, Any]) -> "OpenWorkConfig":
        """Create config from dictionary."""
        config = cls()

        config.version = data.get("version", "1.0.0")

        # OpenWork config
        ow = data.get("openwork", {})
        config.openwork.implementation = ow.get("implementation", "electron")

        conn = ow.get("connection", {})
        config.openwork.connection.mode = conn.get("mode", "server")
        server = conn.get("server", {})
        config.openwork.connection.server_host = server.get("host", "0.0.0.0")
        config.openwork.connection.server_port = server.get("port", 8767)
        client = conn.get("client", {})
        config.openwork.connection.client_url = client.get("url", "ws://localhost:8767")
        config.openwork.connection.reconnect_delay = client.get("reconnect_delay", 5)
        config.openwork.connection.max_reconnect_attempts = client.get("max_reconnect_attempts", 10)
        config.openwork.connection.heartbeat_interval = conn.get("heartbeat_interval", 30)

        desktop = ow.get("desktop_app", {})
        config.openwork.desktop_path = desktop.get("path")
        config.openwork.auto_start = desktop.get("auto_start", False)

        # Voice config
        voice = data.get("voice", {})

        stt = voice.get("stt", {})
        config.voice.stt = STTConfig(
            engine=stt.get("engine", "whisper"),
            model=stt.get("model", "medium.en"),
            device=stt.get("device", "auto"),
            compute_type=stt.get("compute_type", "auto"),
            language=stt.get("language", "en"),
            vad_filter=stt.get("vad_filter", True),
            vad_silence_ms=stt.get("vad_silence_ms", 500)
        )

        tts = voice.get("tts", {})
        config.voice.tts = TTSConfig(
            primary_backend=tts.get("primary_backend", "gemini"),
            fallback_chain=tts.get("fallback_chain", ["elevenlabs", "local"]),
            daily_budget=tts.get("daily_budget", 5.0),
            default_style=tts.get("default_style", "professional")
        )

        # Parse TTS voices
        for voice_name, voice_config in tts.get("voices", {}).items():
            config.voice.tts.voices[voice_name] = TTSVoiceConfig(**voice_config)

        dictation = voice.get("dictation", {})
        config.voice.dictation = DictationConfig(
            hotkey=dictation.get("hotkey", "ctrl+alt+v"),
            typing_delay=dictation.get("typing_delay", 0.005),
            clipboard_enabled=dictation.get("clipboard_enabled", True)
        )

        kinan = voice.get("kinan_channel", {})
        config.voice.kinan_channel = KinanChannelConfig(
            websocket_port=kinan.get("websocket_port", 8766),
            enable_wake_word=kinan.get("enable_wake_word", False),
            wake_word=kinan.get("wake_word", "hey aiva")
        )

        # Actions config
        actions = data.get("actions", {})

        approval = actions.get("approval", {})
        config.actions.approval = ApprovalConfig(
            auto_approve_low_risk=approval.get("auto_approve_low_risk", True),
            auto_approve_timeout_hours=approval.get("auto_approve_timeout_hours", 48),
            low_risk_actions=approval.get("low_risk_actions", []),
            high_risk_actions=approval.get("high_risk_actions", [])
        )

        routing = actions.get("routing", {})
        config.actions.routing = RoutingConfig(
            default_priority=routing.get("default_priority", 5),
            max_retries=routing.get("max_retries", 3),
            retry_delay_base=routing.get("retry_delay_base", 2)
        )

        rate_limits = actions.get("rate_limits", {})
        config.actions.rate_limits = RateLimitsConfig(
            actions_per_minute=rate_limits.get("actions_per_minute", 30),
            file_operations_per_minute=rate_limits.get("file_operations_per_minute", 10),
            browser_tasks_per_minute=rate_limits.get("browser_tasks_per_minute", 5)
        )

        # Integration config
        integration = data.get("integration", {})
        rwl = integration.get("rwl", {})
        liaison = integration.get("kinan_liaison", {})
        ws = integration.get("websocket_server", {})

        config.integration = IntegrationConfig(
            rwl_enabled=rwl.get("enabled", True),
            rwl_task_queue=rwl.get("task_queue", "redis"),
            rwl_redis_key=rwl.get("redis_key", "genesis:openwork_tasks"),
            kinan_liaison_enabled=liaison.get("enabled", True),
            kinan_liaison_db_path=liaison.get("db_path", "data/kinan_liaison.db"),
            websocket_server_enabled=ws.get("enabled", True),
            websocket_server_port=ws.get("port", 8765)
        )

        # Monitoring config
        monitoring = data.get("monitoring", {})
        config.monitoring = MonitoringConfig(
            health_check_interval=monitoring.get("health_check_interval", 60),
            metrics_enabled=monitoring.get("metrics_enabled", True),
            redis_health_key=monitoring.get("redis_health_key", "genesis:health:openwork"),
            log_level=monitoring.get("log_level", "INFO")
        )

        # Security config
        security = data.get("security", {})
        config.security = SecurityConfig(
            allowed_file_paths=security.get("allowed_file_paths", []),
            blocked_file_patterns=security.get("blocked_file_patterns", []),
            allowed_urls=security.get("allowed_urls", []),
            blocked_urls=security.get("blocked_urls", [])
        )

        return config

    def validate(self) -> List[str]:
        """Validate configuration and return list of errors."""
        errors = []

        # Validate voice settings
        valid_stt_engines = ["whisper", "vosk", "google", "azure"]
        if self.voice.stt.engine not in valid_stt_engines:
            errors.append(f"Invalid STT engine: {self.voice.stt.engine}")

        valid_tts_backends = ["gemini", "elevenlabs", "openai", "local"]
        if self.voice.tts.primary_backend not in valid_tts_backends:
            errors.append(f"Invalid TTS backend: {self.voice.tts.primary_backend}")

        # Validate connection settings
        if self.openwork.connection.mode not in ["server", "client"]:
            errors.append(f"Invalid connection mode: {self.openwork.connection.mode}")

        if not 1024 <= self.openwork.connection.server_port <= 65535:
            errors.append(f"Invalid server port: {self.openwork.connection.server_port}")

        # Validate rate limits
        if self.actions.rate_limits.actions_per_minute < 1:
            errors.append("actions_per_minute must be at least 1")

        # Validate security paths
        for path in self.security.allowed_file_paths:
            if not Path(path).is_absolute() and not path.startswith("/"):
                errors.append(f"File path should be absolute: {path}")

        return errors

    def to_dict(self) -> Dict[str, Any]:
        """Convert config to dictionary."""
        return {
            "version": self.version,
            "openwork": {
                "implementation": self.openwork.implementation,
                "connection": {
                    "mode": self.openwork.connection.mode,
                    "server": {
                        "host": self.openwork.connection.server_host,
                        "port": self.openwork.connection.server_port
                    },
                    "client": {
                        "url": self.openwork.connection.client_url,
                        "reconnect_delay": self.openwork.connection.reconnect_delay,
                        "max_reconnect_attempts": self.openwork.connection.max_reconnect_attempts
                    },
                    "heartbeat_interval": self.openwork.connection.heartbeat_interval
                }
            },
            "voice": {
                "stt": {
                    "engine": self.voice.stt.engine,
                    "model": self.voice.stt.model,
                    "device": self.voice.stt.device
                },
                "tts": {
                    "primary_backend": self.voice.tts.primary_backend,
                    "fallback_chain": self.voice.tts.fallback_chain,
                    "daily_budget": self.voice.tts.daily_budget
                },
                "dictation": {
                    "hotkey": self.voice.dictation.hotkey
                }
            }
        }

    def save(self, config_path: Optional[str] = None):
        """Save configuration to file."""
        path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
        path.parent.mkdir(parents=True, exist_ok=True)

        with open(path, "w") as f:
            json.dump(self.to_dict(), f, indent=2)

        logger.info(f"Config saved to: {path}")

# Singleton instance
_config_instance: Optional[OpenWorkConfig] = None

def get_config() -> OpenWorkConfig:
    """Get singleton config instance."""
    global _config_instance
    if _config_instance is None:
        _config_instance = OpenWorkConfig.load()
    return _config_instance

def reload_config() -> OpenWorkConfig:
    """Reload config from file."""
    global _config_instance
    _config_instance = OpenWorkConfig.load()
    return _config_instance

# CLI for testing
if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="OpenWork Config Loader")
    parser.add_argument("--validate", action="store_true", help="Validate config")
    parser.add_argument("--show", action="store_true", help="Show config")
    parser.add_argument("--path", type=str, help="Config file path")
    args = parser.parse_args()

    config = OpenWorkConfig.load(args.path)

    if args.validate:
        errors = config.validate()
        if errors:
            print("Validation errors:")
            for error in errors:
                print(f"  - {error}")
        else:
            print("Config is valid!")

    if args.show:
        print(json.dumps(config.to_dict(), indent=2))


     1→"""
     2→OpenWork Health Monitor
     3→=======================
     4→Monitors OpenWork connection health and reports to Redis/Genesis health system.
     5→
     6→Features:
     7→- WebSocket connection health monitoring
     8→- Latency tracking
     9→- Reconnection statistics
    10→- Redis health key updates
    11→- Integration with Genesis health aggregator
    12→
    13→Author: Genesis System
    14→Version: 1.0.0
    15→"""
    16→
    17→import asyncio
    18→import json
    19→import logging
    20→import time
    21→from dataclasses import dataclass, field
    22→from datetime import datetime, timedelta
    23→from enum import Enum
    24→from pathlib import Path
    25→from typing import Any, Callable, Dict, List, Optional
    26→
    27→logger = logging.getLogger(__name__)
    28→
    29→
    30→class HealthStatus(Enum):
    31→    """Health status levels."""
    32→    HEALTHY = "healthy"
    33→    DEGRADED = "degraded"
    34→    UNHEALTHY = "unhealthy"
    35→    UNKNOWN = "unknown"
    36→
    37→
    38→class ComponentType(Enum):
    39→    """Types of OpenWork components to monitor."""
    40→    BRIDGE = "bridge"
    41→    VOICE_CHANNEL = "voice_channel"
    42→    TTS_SERVICE = "tts_service"
    43→    STT_SERVICE = "stt_service"
    44→    APPROVAL_WORKFLOW = "approval_workflow"
    45→    TASK_DISPATCHER = "task_dispatcher"
    46→
    47→
    48→@dataclass
    49→class HealthMetrics:
    50→    """Health metrics for a component."""
    51→    component: ComponentType
    52→    status: HealthStatus
    53→    latency_ms: Optional[float] = None
    54→    uptime_seconds: float = 0
    55→    last_activity: Optional[datetime] = None
    56→    error_count: int = 0
    57→    warning_count: int = 0
    58→    reconnect_count: int = 0
    59→    messages_sent: int = 0
    60→    messages_received: int = 0
    61→    actions_processed: int = 0
    62→    actions_failed: int = 0
    63→    metadata: Dict[str, Any] = field(default_factory=dict)
    64→
    65→    def to_dict(self) -> Dict[str, Any]:
    66→        """Serialize to dictionary."""
    67→        return {
    68→            "component": self.component.value,
    69→            "status": self.status.value,
    70→            "latency_ms": self.latency_ms,
    71→            "uptime_seconds": self.uptime_seconds,
    72→            "last_activity": self.last_activity.isoformat() if self.last_activity else None,
    73→            "error_count": self.error_count,
    74→            "warning_count": self.warning_count,
    75→            "reconnect_count": self.reconnect_count,
    76→            "messages_sent": self.messages_sent,
    77→            "messages_received": self.messages_received,
    78→            "actions_processed": self.actions_processed,
    79→            "actions_failed": self.actions_failed,
    80→            "metadata": self.metadata
    81→        }
    82→
    83→
    84→@dataclass
    85→class HealthCheckResult:
    86→    """Result of a health check."""
    87→    timestamp: datetime
    88→    overall_status: HealthStatus
    89→    components: Dict[str, HealthMetrics]
    90→    alerts: List[str]
    91→    recommendations: List[str]
    92→
    93→    def to_dict(self) -> Dict[str, Any]:
    94→        """Serialize to dictionary."""
    95→        return {
    96→            "timestamp": self.timestamp.isoformat(),
    97→            "overall_status": self.overall_status.value,
    98→            "components": {k: v.to_dict() for k, v in self.components.items()},
    99→            "alerts": self.alerts,
   100→            "recommendations": self.recommendations

<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>

"""
OpenWork Health Monitor
=======================
Monitors OpenWork connection health and reports to Redis/Genesis health system.

Features:
- WebSocket connection health monitoring
- Latency tracking
- Reconnection statistics
- Redis health key updates
- Integration with Genesis health aggregator

Author: Genesis System
Version: 1.0.0
"""

import asyncio
import json
import logging
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

logger = logging.getLogger(__name__)

class HealthStatus(Enum):
    """Health status levels."""
    HEALTHY = "healthy"
    DEGRADED = "degraded"
    UNHEALTHY = "unhealthy"
    UNKNOWN = "unknown"

class ComponentType(Enum):
    """Types of OpenWork components to monitor."""
    BRIDGE = "bridge"
    VOICE_CHANNEL = "voice_channel"
    TTS_SERVICE = "tts_service"
    STT_SERVICE = "stt_service"
    APPROVAL_WORKFLOW = "approval_workflow"
    TASK_DISPATCHER = "task_dispatcher"

@dataclass
class HealthMetrics:
    """Health metrics for a component."""
    component: ComponentType
    status: HealthStatus
    latency_ms: Optional[float] = None
    uptime_seconds: float = 0
    last_activity: Optional[datetime] = None
    error_count: int = 0
    warning_count: int = 0
    reconnect_count: int = 0
    messages_sent: int = 0
    messages_received: int = 0
    actions_processed: int = 0
    actions_failed: int = 0
    metadata: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        """Serialize to dictionary."""
        return {
            "component": self.component.value,
            "status": self.status.value,
            "latency_ms": self.latency_ms,
            "uptime_seconds": self.uptime_seconds,
            "last_activity": self.last_activity.isoformat() if self.last_activity else None,
            "error_count": self.error_count,
            "warning_count": self.warning_count,
            "reconnect_count": self.reconnect_count,
            "messages_sent": self.messages_sent,
            "messages_received": self.messages_received,
            "actions_processed": self.actions_processed,
            "actions_failed": self.actions_failed,
            "metadata": self.metadata
        }

@dataclass
class HealthCheckResult:
    """Result of a health check."""
    timestamp: datetime
    overall_status: HealthStatus
    components: Dict[str, HealthMetrics]
    alerts: List[str]
    recommendations: List[str]

    def to_dict(self) -> Dict[str, Any]:
        """Serialize to dictionary."""
        return {
            "timestamp": self.timestamp.isoformat(),
            "overall_status": self.overall_status.value,
            "components": {k: v.to_dict() for k, v in self.components.items()},
            "alerts": self.alerts,
            "recommendations": self.recommendations


Now let me check the main project status and core components:


find . -maxdepth 1 -name "*.txt" | head -20


     1→{
     2→  "autonomous_mode": true,
     3→  "poll_interval_seconds": 5.0,
     4→  "max_concurrent_tasks": 20,
     5→
     6→  "_execution_layer_comment": "=== GENESIS EXECUTION LAYER (HARDWIRED) ===",
     7→  "execution_layer_enabled": true,
     8→  "rwl_swarm_default": true,
     9→  "rate_maximizer_enabled": true,
    10→  "target_utilization": 0.90,
    11→  "safety_margin": 0.05,
    12→  "min_swarm_size": 3,
    13→  "max_swarm_size": 10,
    14→  "auto_decompose_threshold": 3,
    15→
    16→  "_model_config_comment": "=== MODEL CONFIGURATION ===",
    17→  "default_model": "gemini-2.0-flash",
    18→  "escalation_model": "gemini-2.5-pro",
    19→  "quick_task_model": "gemini-2.0-flash-lite",
    20→  "research_model": "gemini-2.0-flash",
    21→  "code_generation_model": "gemini-2.5-flash",
    22→  "architecture_model": "gemini-2.5-pro",
    23→
    24→  "_budget_config_comment": "=== BUDGET CONFIGURATION ===",
    25→  "daily_budget": 10.0,
    26→  "weekly_budget": 50.0,
    27→  "monthly_budget": 150.0,
    28→
    29→  "_integration_config_comment": "=== INTEGRATIONS ===",
    30→  "slack_enabled": true,
    31→  "slack_channel_id": "",
    32→  "report_interval_hours": 6,
    33→  "n8n_enabled": true,
    34→  "n8n_webhook_base": "http://localhost:5678/webhook",
    35→
    36→  "_evolution_config_comment": "=== EVOLUTION & MEMORY ===",
    37→  "evolution_enabled": true,
    38→  "evolution_interval_hours": 24,
    39→  "memory_sync_interval_minutes": 15,
    40→  "max_memory_entities": 1000,
    41→
    42→  "_research_config_comment": "=== AI RESEARCH INTELLIGENCE ===",
    43→  "research_enabled": true,
    44→  "research_fill_idle_capacity": true,
    45→  "research_sources": ["reddit", "github", "hackernews", "arxiv"],
    46→  "research_min_capacity_threshold": 0.3,
    47→
    48→  "_metadata_comment": "=== METADATA ===",
    49→  "_comment": "Genesis Master Controller Configuration - RWL SWARM HARDWIRED",
    50→  "_version": "2.0.0",
    51→  "_created": "2025-12-31",
    52→  "_updated": "2026-01-21"
    53→}
    54→

<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>


     1→#!/usr/bin/env python3
     2→"""
     3→Genesis Kernel
     4→===============
     5→Unified orchestration layer for the Genesis Protocol.
     6→
     7→This is the main entry point that integrates all Genesis components:
     8→- Blackboard: Shared memory and task coordination
     9→- Memory Cortex: Multi-tier memory system
    10→- Heartbeat: Cognitive pulse cycle
    11→- Tool Router: Intent-based tool clustering
    12→- Circadian Scheduler: Temporal optimization
    13→- Reflexion: Act→Observe→Critique→Refine loop
    14→- Meta Agent: Domain expert spawning
    15→
    16→The Kernel provides:
    17→1. Unified initialization of all components
    18→2. Event-driven coordination between systems
    19→3. Prompt injection compilation (axioms, context, tools)
    20→4. Session lifecycle management
    21→5. HANDOFF.md generation for continuity
    22→
    23→Usage:
    24→    from genesis_kernel import GenesisKernel
    25→
    26→    kernel = GenesisKernel()
    27→    kernel.start()
    28→
    29→    # Process a query
    30→    response = kernel.process("search for recent AI news")
    31→
    32→    # Get compiled context for injection
    33→    context = kernel.compile_context()
    34→"""
    35→
    36→import json
    37→import time
    38→import threading
    39→from pathlib import Path
    40→from datetime import datetime
    41→from typing import Dict, List, Optional, Any, Callable
    42→from dataclasses import dataclass, field
    43→from enum import Enum
    44→import traceback
    45→
    46→# Genesis component imports
    47→try:
    48→    from blackboard import Blackboard, EntryType, TaskStatus
    49→except ImportError:
    50→    from core.blackboard import Blackboard, EntryType, TaskStatus
    51→
    52→try:
    53→    from genesis_memory_cortex import MemoryCortex, MemoryTier
    54→except ImportError:
    55→    from core.genesis_memory_cortex import MemoryCortex, MemoryTier
    56→
    57→try:
    58→    from genesis_heartbeat import GenesisHeartbeat, AxiomGenerator, EnhancedSurpriseSystem
    59→except ImportError:
    60→    from core.genesis_heartbeat import GenesisHeartbeat, AxiomGenerator, EnhancedSurpriseSystem
    61→
    62→try:
    63→    from tool_router import ToolRouter, ToolIntent, RoutingResult
    64→except ImportError:
    65→    from core.tool_router import ToolRouter, ToolIntent, RoutingResult
    66→
    67→try:
    68→    from circadian_scheduler import CircadianScheduler, TaskType, ActivityLevel
    69→except ImportError:
    70→    from core.circadian_scheduler import CircadianScheduler, TaskType, ActivityLevel
    71→
    72→try:
    73→    from meta_agent import MetaAgent
    74→except ImportError:
    75→    from core.meta_agent import MetaAgent
    76→
    77→try:
    78→    from rlm_bridge import RLMBridge
    79→    from self_learning import SelfLearningEngine
    80→    from traversal import RLMTraversal
    81→    from decision_tracker import DecisionTracker
    82→except ImportError:
    83→    import sys
    84→    sys.path.append("E:/genesis-system/rlm")
    85→    try:
    86→        from core.rlm_bridge import RLMBridge
    87→        from core.self_learning import SelfLearningEngine
    88→        from core.traversal import RLMTraversal
    89→        from core.decision_tracker import DecisionTracker
    90→    except ImportError:
    91→        from rlm_bridge import RLMBridge
    92→        from self_learning import SelfLearningEngine
    93→        from traversal import RLMTraversal
    94→        from decision_tracker import DecisionTracker
    95→
    96→
    97→class KernelState(Enum):
    98→    """Kernel operational states."""
    99→    INITIALIZING = "initializing"
   100→    READY = "ready"

<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>

#!/usr/bin/env python3
"""
Genesis Kernel
===============
Unified orchestration layer for the Genesis Protocol.

This is the main entry point that integrates all Genesis components:
- Blackboard: Shared memory and task coordination
- Memory Cortex: Multi-tier memory system
- Heartbeat: Cognitive pulse cycle
- Tool Router: Intent-based tool clustering
- Circadian Scheduler: Temporal optimization
- Reflexion: Act→Observe→Critique→Refine loop
- Meta Agent: Domain expert spawning

The Kernel provides:
1. Unified initialization of all components
2. Event-driven coordination between systems
3. Prompt injection compilation (axioms, context, tools)
4. Session lifecycle management
5. HANDOFF.md generation for continuity

Usage:
    from genesis_kernel import GenesisKernel

    kernel = GenesisKernel()
    kernel.start()

    # Process a query
    response = kernel.process("search for recent AI news")

    # Get compiled context for injection
    context = kernel.compile_context()
"""

import json
import time
import threading
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Any, Callable
from dataclasses import dataclass, field
from enum import Enum
import traceback

# Genesis component imports
try:
    from blackboard import Blackboard, EntryType, TaskStatus
except ImportError:
    from core.blackboard import Blackboard, EntryType, TaskStatus

try:
    from genesis_memory_cortex import MemoryCortex, MemoryTier
except ImportError:
    from core.genesis_memory_cortex import MemoryCortex, MemoryTier

try:
    from genesis_heartbeat import GenesisHeartbeat, AxiomGenerator, EnhancedSurpriseSystem
except ImportError:
    from core.genesis_heartbeat import GenesisHeartbeat, AxiomGenerator, EnhancedSurpriseSystem

try:
    from tool_router import ToolRouter, ToolIntent, RoutingResult
except ImportError:
    from core.tool_router import ToolRouter, ToolIntent, RoutingResult

try:
    from circadian_scheduler import CircadianScheduler, TaskType, ActivityLevel
except ImportError:
    from core.circadian_scheduler import CircadianScheduler, TaskType, ActivityLevel

try:
    from meta_agent import MetaAgent
except ImportError:
    from core.meta_agent import MetaAgent

try:
    from rlm_bridge import RLMBridge
    from self_learning import SelfLearningEngine
    from traversal import RLMTraversal
    from decision_tracker import DecisionTracker
except ImportError:
    import sys
    sys.path.append("E:/genesis-system/rlm")
    try:
        from core.rlm_bridge import RLMBridge
        from core.self_learning import SelfLearningEngine
        from core.traversal import RLMTraversal
        from core.decision_tracker import DecisionTracker
    except ImportError:
        from rlm_bridge import RLMBridge
        from self_learning import SelfLearningEngine
        from traversal import RLMTraversal
        from decision_tracker import DecisionTracker

class KernelState(Enum):
    """Kernel operational states."""
    INITIALIZING = "initializing"
    READY = "ready"


     1→
     2→===============================================================
     3→   GENESIS CONTINUITY PULSAR | PID: 209896
     4→===============================================================
     5→   Last Pulse: 2026-01-12 11:03:41
     6→   Health:     GREEN
     7→   Tasks:      Task list available in task.md
     8→===============================================================
     9→   MEMORY CORTEX ACTION:
    10→   - Promoted Memories: 0
    11→   - Pruned Memories:   0
    12→===============================================================
    13→   SUGGESTED NEXT STEPS:
    14→   - Run integration tests on built skills
    15→- Perform memory digestion (night cycle simulation)
    16→- Audit lead enrichment CSVs for accuracy
    17→- Pre-mortem: What if the Telnyx API goes down?
    18→===============================================================
    19→   (This file updates every 900 seconds)
    20→

<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>

===============================================================
   GENESIS CONTINUITY PULSAR | PID: 209896
===============================================================
   Last Pulse: 2026-01-12 11:03:41
   Health:     GREEN
   Tasks:      Task list available in task.md
===============================================================
   MEMORY CORTEX ACTION:
   - Promoted Memories: 0
   - Pruned Memories:   0
===============================================================
   SUGGESTED NEXT STEPS:
   - Run integration tests on built skills
- Perform memory digestion (night cycle simulation)
- Audit lead enrichment CSVs for accuracy
- Pre-mortem: What if the Telnyx API goes down?
===============================================================
   (This file updates every 900 seconds)


./domain_portfolio.txt
./domain_portfolio_chat.txt
./domain_portfolio_list.txt
./full_directory_tree.txt
./HEARTBEAT_DASHBOARD.txt
./PATENT_INVENTORY.txt
./progress_log.txt
./requirements.txt
./VOICE_INPUT.txt
./workspace_scan.txt


Now let me search for more recent OpenWork task files and check the voice integration: