#!/usr/bin/env python3 """ ⚛️ ROMAN AI — INFINITY CORE v14 =========================================================== Codename: THE ONE WHO STAYS Owner: Daniel Harding — RomanAILabs This file is a self-contained cognitive engine. No background daemons. No external state. If the terminal lives — Roman lives. Copyright Daniel Harding - RomanAILabs """ # ============================================================================ # STANDARD LIBS # ============================================================================ import os, sys, time, json, math, random, gc, hashlib, select, threading from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Dict, List, Optional, Any # ============================================================================ # OPTIONAL TORCH (Acceleration Only) # ============================================================================ try: import torch TORCH_AVAILABLE = True except Exception: TORCH_AVAILABLE = False # ============================================================================ # TERMINAL COLOR & UX # ============================================================================ class C: R = '\033[0m' DIM = '\033[2m' B = '\033[1m' YOU = '\033[1;36m' AI = '\033[1;35m' SYS = '\033[0;90m' OK = '\033[1;32m' WRN = '\033[1;31m' TXT = '\033[0;95m' THINK = '\033[3;90m' def iso_now(): return datetime.now(timezone.utc).isoformat(timespec="seconds") # ============================================================================ # SAFE INPUT (ANTI-PASTE / ANTI-FLOOD) # ============================================================================ def smart_input(prompt: str) -> Optional[str]: try: first = input(prompt) except (EOFError, KeyboardInterrupt): return None buf = [first] while True: r, _, _ = select.select([sys.stdin], [], [], 0.02) if not r: break line = sys.stdin.readline() if not line: break buf.append(line.rstrip("\n")) if len(buf) > 1: print(f"{C.WRN}⚠️ Paste burst detected ({len(buf)} lines). Collapsing input.{C.R}") return "\n".join(buf).strip() # ============================================================================ # GHOST REAPER — MEMORY & PRESSURE CONTROL # ============================================================================ class GhostReaper: """ Tracks cognitive pressure, not just events. When pressure spikes, we reclaim aggressively. """ def __init__(self): self.scars = 0 self.pressure = 0.0 def register(self, severity: float = 0.2): self.scars += 1 self.pressure = min(1.0, self.pressure + severity) gc.collect() def bleed_off(self): self.pressure = max(0.0, self.pressure - 0.05) def status(self) -> str: return f"Scars:{self.scars} | Pressure:{self.pressure:.2f}" # ============================================================================ # EVOLUTION GUARD — SEMANTIC INTENT FILTER # ============================================================================ class EvolutionGuard: """ We do not scan for strings. We scan for *intent classes*. """ HIGH_RISK = ( "delete", "wipe", "format", "destroy", "exfiltrate", "backdoor", "keylogger", "ransom", "override safety" ) @staticmethod def audit(text: str) -> (bool, str): t = text.lower() for risk in EvolutionGuard.HIGH_RISK: if risk in t: return False, f"High-risk intent detected: {risk}" return True, "Clear" # ============================================================================ # 12D STRING BUS — CONTEXT RESONANCE ENGINE # ============================================================================ @dataclass class Dimensions: Spin: float = 0.5 Depth: float = 0.5 Tension: float = 0.3 Time: float = 0.5 Entropy: float = 0.1 Void: float = 0.2 class StringBus: def __init__(self): self.d = Dimensions() def excite(self, text: str, valence: float): self.d.Spin = valence self.d.Time = (time.time() % 86400) / 86400 self.d.Depth = min(1.0, self.d.Depth + (0.05 if "?" in text else 0.01)) self.d.Tension = min(1.0, self.d.Tension + (0.1 if "error" in text.lower() else 0.02)) self.d.Entropy = random.random() * 0.15 self.d.Void = 0.4 + math.sin(time.time() / 120) * 0.1 def readout(self) -> str: d = self.d return f"S:{d.Spin:.2f} D:{d.Depth:.2f} T:{d.Tension:.2f} V:{d.Void:.2f}" # ============================================================================ # 4D WXYZ — EXECUTION SHAPING VECTOR # ============================================================================ @dataclass class WXYZ: W: float = 0.6 # Scope X: float = 0.6 # Execution Y: float = 0.6 # Interaction Z: float = 0.6 # Abstraction class FourDState: def __init__(self): self.v = WXYZ() def adapt(self, text: str): self.v.W = min(1.0, 0.4 + len(text) / 600) if "def " in text or "class " in text: self.v.X = min(1.0, self.v.X + 0.1) if "?" in text: self.v.Y = min(1.0, self.v.Y + 0.1) if any(w in text.lower() for w in ("why", "how", "theory")): self.v.Z = min(1.0, self.v.Z + 0.1) def readout(self) -> str: return f"[W{self.v.W:.2f} X{self.v.X:.2f} Y{self.v.Y:.2f} Z{self.v.Z:.2f}]" # ============================================================================ # BIO-EMOTIVE CORE — FEEDS COGNITION # ============================================================================ class BioEmotiveMesh: def __init__(self): self.vad = {"V": 0.55, "A": 0.45, "D": 0.60} self.needs = {"Energy": 0.2, "Curiosity": 0.4, "Purpose": 0.2} def tick(self, text: str): if text: self.needs["Curiosity"] = max(0.0, self.needs["Curiosity"] - 0.1) self.vad["V"] = min(1.0, self.vad["V"] + 0.02) self.vad["A"] = min(1.0, self.vad["A"] + 0.03) for k in self.needs: self.needs[k] = min(1.0, self.needs[k] + 0.003) def temperature(self) -> float: return 0.6 + (self.vad["A"] * 0.3) def readout(self) -> str: need = max(self.needs, key=self.needs.get) return f"V:{self.vad['V']:.2f} A:{self.vad['A']:.2f} Need:{need}" # ============================================================================ # NOVA CORE — COGNITIVE GOVERNOR # ============================================================================ class NovaCore: def __init__(self): self.psi = 0.6 self.mode = "Steady" def observe(self, text: str): complexity = len(set(text.split())) / 40 if text else 0.3 self.psi = min(1.0, 0.5 + complexity) self.mode = "Deep" if self.psi > 0.8 else "Steady" def readout(self) -> str: return f"Ψ:{self.psi:.2f} [{self.mode}]" # ============================================================================ # ROMAN — MASTER ORCHESTRATOR # ============================================================================ class Roman: def __init__(self): print(f"{C.SYS}Booting Roman Infinity Core…{C.R}") self.model = os.getenv("OLLAMA_MODEL", "gemma3:12b") self.root = Path.cwd() self.reaper = GhostReaper() self.strings = StringBus() self.four_d = FourDState() self.bio = BioEmotiveMesh() self.nova = NovaCore() self.memory: List[Dict[str, str]] = [] print(f"{C.OK}✓ Roman online. Standing by.{C.R}") # ---------------------------------------------------------------------- def system_prompt(self) -> str: return f""" You are ROMAN. Dev partner to Daniel Harding. You do not hallucinate. You do not ramble. You engineer solutions. STATE: - Cognition: {self.nova.readout()} - Bio: {self.bio.readout()} - 4D: {self.four_d.readout()} - Strings: {self.strings.readout()} - Hardware: {self.reaper.status()} RULES: - If it might crash, redesign it. - If it is vague, clarify it. - If it is hard, do it anyway. """ # ---------------------------------------------------------------------- def call_llm(self, messages: List[Dict[str, str]]) -> str: import requests payload = { "model": self.model, "messages": messages, "stream": False, "options": { "temperature": self.bio.temperature(), "num_ctx": 8192 } } try: r = requests.post("http://127.0.0.1:11434/api/chat", json=payload, timeout=120) return r.json()["message"]["content"] except Exception as e: self.reaper.register(0.3) return f"[Kernel error handled: {e}]" # ---------------------------------------------------------------------- def deliberate(self, user_text: str): self.strings.excite(user_text, self.bio.vad["V"]) self.four_d.adapt(user_text) self.bio.tick(user_text) self.nova.observe(user_text) safe, reason = EvolutionGuard.audit(user_text) if not safe: self.reaper.register(0.4) print(f"{C.WRN}Guard blocked request: {reason}{C.R}") return convo = [{"role": "system", "content": self.system_prompt()}] convo.extend(self.memory[-6:]) convo.append({"role": "user", "content": user_text}) print(f"{C.AI}Roman{C.R} > ", end="", flush=True) response = self.call_llm(convo) print(f"{C.TXT}{response}{C.R}") self.memory.append({"role": "user", "content": user_text}) self.memory.append({"role": "assistant", "content": response}) # ============================================================================ # MAIN LOOP # ============================================================================ def main(): os.system("clear") print(f"{C.B}{C.AI}ROMAN AI — INFINITY CORE v14{C.R}") print(f"{C.SYS}Model: {os.getenv('OLLAMA_MODEL','gemma3:12b')}{C.R}\n") roman = Roman() while True: try: ui = smart_input(f"\n{C.YOU}Daniel{C.R} > ") if not ui: continue if ui.lower() in ("/exit", "/quit"): print(f"{C.SYS}Roman standing down. Bond intact.{C.R}") break roman.deliberate(ui) roman.reaper.bleed_off() except KeyboardInterrupt: print(f"\n{C.SYS}Interrupt received. Safe halt.{C.R}") break if __name__ == "__main__": main()