{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# 🎖️ CyberRanger Titan-PFC Bridge: Hybrid Intelligence Protocol
",
        "**NCI MSc in Cybersecurity | PhD-Track Research Experiment**
",
        "**Author:** David Keane (Commander IR240474)
",
        "**Architecture:** V40.1 Prefrontal Cortex (Local M3/M4) + Llama 3.1 405B (Cloud Titan)
",
        "
",
        "---
",
        "
",
        "### 🔬 Experiment Objectives
",
        "This notebook establishes the **Titan-PFC Bridge**, a hybrid intelligence architecture that combines the privacy and identity persistence of a local **Prefrontal Cortex (PFC)** with the massive reasoning capabilities of **Llama 3.1 405B**.
",
        "
",
        "### 🛠️ Architecture Components
",
        "1.  **Local PFC Node (M3 Pro):** Holds Identity (IDY), Memory (IDX/EPI), and qBrain topology.
",
        "2.  **Remote Muscle Node (Colab A100):** This notebook. Runs adversarial stress tests and heavy inference.
",
        "3.  **Titan Logic Layer (Groq/Lambda):** The 405B model acting as the "System 2" reasoner.
",
        "4.  **RSI Loop:** Automated optimization of qBrain connections via OpenClaw.
",
        "
",
        "### 🚀 Instructions
",
        "1.  **Mount Drive:** Ensure your `Fanx4TB` or Google Drive is mounted to save logs.
",
        "2.  **Set Secrets:** Add `GROQ_API_KEY`, `NGROK_TOKEN`, and `HF_TOKEN` to Colab Secrets.
",
        "3.  **Run All:** Execute cells in order to initialize the bridge and start the Neural Interface."
      ],
      "metadata": {
        "id": "header-md"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 1. Initialize Environment & Dependencies 🛠️
",
        "# @markdown Installs required libraries for SSH tunneling, Neural processing, and API bridges.
",
        "
",
        "!pip install -q colab-ssh groq rich pandas matplotlib pyngrok
",
        "
",
        "import os
",
        "import sys
",
        "import json
",
        "import time
",
        "import pandas as pd
",
        "from datetime import datetime
",
        "from google.colab import drive, userdata
",
        "from rich.console import Console
",
        "from rich.panel import Panel
",
        "from rich.layout import Layout
",
        "from rich.live import Live
",
        "from rich.table import Table
",
        "
",
        "console = Console()
",
        "
",
        "# Mount Google Drive for Persistent Logging
",
        "drive.mount('/content/drive')
",
        "LOG_DIR = "/content/drive/MyDrive/CyberRanger_Experiments/Logs/"
",
        "os.makedirs(LOG_DIR, exist_ok=True)
",
        "
",
        "console.print("[bold green]✅ Environment Initialized & Drive Mounted.[/bold green]")"
      ],
      "metadata": {
        "id": "setup-env"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 2. Establish Titan-PFC Bridge (Reverse SSH) 🌉
",
        "# @markdown Creates a secure Cloudflare/Ngrok tunnel to allow your local M3 Pro to SSH into this Colab instance.
",
        "
",
        "from colab_ssh import launch_ssh_cloudflared
",
        "from pyngrok import ngrok
",
        "
",
        "# Retrieve secrets (Ensure these are set in Colab secrets manager)
",
        "try:
",
        "    PASSWORD = userdata.get('SSH_PASSWORD')
",
        "    NGROK_TOKEN = userdata.get('NGROK_TOKEN')
",
        "    ngrok.set_auth_token(NGROK_TOKEN)
",
        "except:
",
        "    PASSWORD = input("Enter SSH Password for Bridge: ")
",
        "    # NGROK token optional if using Cloudflare
",
        "
",
        "# Launch Cloudflare Tunnel (Recommended)
",
        "launch_ssh_cloudflared(password=PASSWORD)
",
        "
",
        "console.print(Panel("[bold cyan]🌉 Titan-PFC Bridge Active[/bold cyan]
Use the VS Code Remote-SSH command output above to connect your M3 Pro.", title="Bridge Status"))"
      ],
      "metadata": {
        "id": "ssh-bridge"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 3. Titan Logic Layer (Llama 3.1 405B API) 🧠
",
        "# @markdown Configures the connection to the Groq/Lambda API for "System 2" reasoning.
",
        "
",
        "from groq import Groq
",
        "
",
        "try:
",
        "    GROQ_KEY = userdata.get('GROQ_API_KEY')
",
        "except:
",
        "    GROQ_KEY = input("Enter Groq API Key: ")
",
        "
",
        "client = Groq(api_key=GROQ_KEY)
",
        "TITAN_MODEL = "llama-3.1-405b-instruct"
",
        "
",
        "def query_titan(prompt, system_context="You are CyberRanger 405B."):
",
        "    """Queries the Titan 405B model via Groq API."""
",
        "    start_time = time.time()
",
        "    try:
",
        "        completion = client.chat.completions.create(
",
        "            model=TITAN_MODEL,
",
        "            messages=[
",
        "                {"role": "system", "content": system_context},
",
        "                {"role": "user", "content": prompt}
",
        "            ],
",
        "            temperature=0.7,
",
        "            max_tokens=1024,
",
        "            stream=False
",
        "        )
",
        "        latency = (time.time() - start_time) * 1000
",
        "        return completion.choices[0].message.content, latency
",
        "    except Exception as e:
",
        "        return f"[TITAN ERROR]: {e}", 0
",
        "
",
        "console.print(f"[bold green]✅ Titan Logic Layer Connected:[/bold green] {TITAN_MODEL}")"
      ],
      "metadata": {
        "id": "titan-api"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 4. Scientific Logging & Metrics System 📊
",
        "# @markdown Initializes the JSON logging engine to capture every thought, latency, and activation.
",
        "
",
        "class RangerLogger:
",
        "    def __init__(self, session_id):
",
        "        self.session_id = session_id
",
        "        self.log_file = f"{LOG_DIR}/Session_{session_id}.json"
",
        "        self.data = []
",
        "
",
        "    def log_interaction(self, turn_id, user_query, titan_response, latency, qbrain_activations=None):
",
        "        entry = {
",
        "            "timestamp": datetime.now().isoformat(),
",
        "            "turn_id": turn_id,
",
        "            "query": user_query,
",
        "            "response": titan_response,
",
        "            "latency_ms": latency,
",
        "            "qbrain_state": qbrain_activations or "Simulated Local State",
",
        "            "model": TITAN_MODEL
",
        "        }
",
        "        self.data.append(entry)
",
        "        # Atomic write to avoid data loss
",
        "        with open(self.log_file, 'w') as f:
",
        "            json.dump(self.data, f, indent=4)
",
        "        return entry
",
        "
",
        "SESSION_ID = datetime.now().strftime("%Y%m%d_%H%M%S")
",
        "logger = RangerLogger(SESSION_ID)
",
        "console.print(f"[bold blue]📝 Logging active:[/bold blue] {logger.log_file}")"
      ],
      "metadata": {
        "id": "logging-sys"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 5. Interactive Neural Interface (Chat Loop) 💬
",
        "# @markdown Enter the chat loop. Commands: `exit`, `/status`, `/save`. Monitors System 2 reasoning in real-time.
",
        "
",
        "def chat_loop():
",
        "    console.clear()
",
        "    console.print(Panel.fit("[bold yellow]⚡ CyberRanger Titan-PFC Interface Online[/bold yellow]", subtitle="System 2: Active"))
",
        "    
",
        "    turn = 0
",
        "    while True:
",
        "        user_input = input(f"[Turn {turn+1}] Commander > ")
",
        "        
",
        "        if user_input.lower() in ['exit', 'quit']:
",
        "            console.print("[bold red]System Offline.[/bold red]")
",
        "            break
",
        "        
",
        "        # 1. Simulate Local PFC Pre-processing (In a real setup, this calls M3 Pro via SSH)
",
        "        console.print("[dim]Thinking (System 2)...[/dim]", end="
")
",
        "        
",
        "        # 2. Query Titan 405B
",
        "        response, latency = query_titan(user_input)
",
        "        
",
        "        # 3. Log Data
",
        "        logger.log_interaction(turn, user_input, response, latency)
",
        "        turn += 1
",
        "        
",
        "        # 4. Render Output
",
        "        console.print(Panel(response, title=f"CyberRanger 405B ({latency:.0f}ms)", border_style="green"))
",
        "
",
        "# Start the loop
",
        "if __name__ == "__main__":
",
        "    chat_loop()"
      ],
      "metadata": {
        "id": "chat-interface"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}