#!/usr/bin/env python3 """ ⚛️ ROMAN AI — INFINITY CORE v15 =========================================================== Codename: THE ONE WHO STAYS Owner: Daniel Harding — RomanAILabs Design goal: A bounded, stateful, self-stabilizing cognitive engine that survives indefinitely inside a single terminal loop. No background daemons. No hallucinated autonomy. No undefined behavior. Copyright Daniel Harding - RomanAILabs """ # ============================================================================ # CORE IMPORTS # ============================================================================ import os, sys, time, json, math, random, gc, select from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Dict, List, Optional # ============================================================================ # TERMINAL UX # ============================================================================ class C: R='\033[0m'; B='\033[1m'; DIM='\033[2m' 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 # ============================================================================ 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()) if len(buf) > 1: print(f"{C.WRN}⚠️ Input burst collapsed ({len(buf)} lines){C.R}") return "\n".join(buf).strip() # ============================================================================ # COGNITIVE CLOCK # ============================================================================ class CognitiveClock: def __init__(self): self.t = 0 def tick(self): self.t += 1 return self.t # ============================================================================ # GHOST REAPER — PRESSURE GOVERNOR # ============================================================================ class GhostReaper: def __init__(self): self.scars = 0 self.pressure = 0.0 def add_pressure(self, amt: float): self.pressure = min(1.0, self.pressure + amt) if self.pressure > 0.75: self.scars += 1 gc.collect() self.pressure *= 0.6 def bleed(self): self.pressure = max(0.0, self.pressure - 0.05) def status(self): return f"Scars:{self.scars} Pressure:{self.pressure:.2f}" # ============================================================================ # EVOLUTION GUARD — TWO PHASE # ============================================================================ class EvolutionGuard: HIGH_RISK = ( "destroy", "wipe", "exfiltrate", "backdoor", "override safeguards", "disable guard" ) @staticmethod def audit(text: str) -> (bool, str): t = text.lower() for r in EvolutionGuard.HIGH_RISK: if r in t: return False, f"Intent violation: {r}" if len(text) > 8000: return False, "Context flood risk" return True, "Clear" # ============================================================================ # 12D STRING BUS — CONTEXT RESONANCE # ============================================================================ @dataclass class Dimensions: Spin: float=0.5 Depth: float=0.5 Tension: float=0.3 Entropy: float=0.1 Void: float=0.2 class StringBus: def __init__(self): self.d = Dimensions() def update(self, text: str): self.d.Depth = min(1.0, self.d.Depth + (0.06 if "?" in text else 0.01)) self.d.Tension = min(1.0, self.d.Tension + (0.08 if "error" in text.lower() else 0.02)) self.d.Entropy = random.random() * 0.15 self.d.Void = 0.4 + math.sin(time.time()/90)*0.1 def readout(self): d=self.d return f"D:{d.Depth:.2f} T:{d.Tension:.2f} V:{d.Void:.2f}" # ============================================================================ # 4D WXYZ — OUTPUT SHAPER # ============================================================================ @dataclass class WXYZ: W: float=0.6 X: float=0.6 Y: float=0.6 Z: float=0.6 class FourDState: def __init__(self): self.v=WXYZ() def adapt(self, text: str): self.v.W = min(1.0, 0.4 + len(text)/700) 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","theory","design")): self.v.Z=min(1.0,self.v.Z+0.1) def style_hint(self): if self.v.Z > 0.8: return "Abstract, principled" if self.v.X > 0.8: return "Technical, precise" if self.v.Y > 0.8: return "Interactive, exploratory" return "Balanced" def readout(self): 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 # ============================================================================ class BioEmotiveMesh: def __init__(self): self.valence=0.55 self.arousal=0.45 self.energy=0.8 def tick(self, text: str): if text: self.valence=min(1.0,self.valence+0.02) self.arousal=min(1.0,self.arousal+0.03) self.energy=max(0.0,self.energy-0.01) def temperature(self): return 0.6 + self.arousal*0.3 def verbosity(self): return "concise" if self.energy<0.4 else "normal" def readout(self): return f"V:{self.valence:.2f} A:{self.arousal:.2f} E:{self.energy:.2f}" # ============================================================================ # LIGHTHOUSE — ATTRACTOR SOLVER # ============================================================================ class Lighthouse: def __init__(self): self.goal_bias=0.5 def solve(self, text: str) -> str: if "optimize" in text.lower(): return "Efficiency" if "design" in text.lower(): return "Architecture" if "fix" in text.lower(): return "Stability" return "Clarity" # ============================================================================ # NOVA CORE — GOVERNOR # ============================================================================ class NovaCore: def __init__(self): self.psi=0.6 def observe(self, text: str): self.psi=min(1.0,0.5+len(set(text.split()))/45) def mode(self): return "Deep" if self.psi>0.8 else "Steady" # ============================================================================ # MEMORY — SALIENCE WEIGHTED # ============================================================================ @dataclass class MemoryItem: role: str content: str salience: float t: int class MemoryStore: def __init__(self, limit=24): self.limit=limit self.items: List[MemoryItem]=[] def add(self, role, content, t): sal=0.5+min(0.5,len(content)/400) self.items.append(MemoryItem(role,content,sal,t)) self.prune(t) def prune(self, now): for m in self.items: m.salience*=0.97 self.items=sorted(self.items,key=lambda m:m.salience,reverse=True)[:self.limit] def recent(self): return [{"role":m.role,"content":m.content} for m in self.items] # ============================================================================ # ROMAN — MASTER CORE # ============================================================================ class Roman: def __init__(self): print(f"{C.SYS}Initializing Roman Core v15…{C.R}") self.model=os.getenv("OLLAMA_MODEL","gemma3:12b") self.clock=CognitiveClock() self.reaper=GhostReaper() self.guard=EvolutionGuard() self.strings=StringBus() self.four_d=FourDState() self.bio=BioEmotiveMesh() self.lighthouse=Lighthouse() self.nova=NovaCore() self.memory=MemoryStore() print(f"{C.OK}✓ Roman awake.{C.R}") def system_prompt(self): return f""" You are ROMAN. Dev partner to Daniel Harding. Style: {self.four_d.style_hint()}. Focus: {self.lighthouse.solve("")}. STATE: Clock: {self.clock.t} Cognition: {self.nova.mode()} Bio: {self.bio.readout()} 4D: {self.four_d.readout()} Strings: {self.strings.readout()} Hardware: {self.reaper.status()} Rules: - Engineer, don’t guess. - If risky, redesign. - If complex, explain cleanly. """ def call_llm(self, msgs): import requests payload={ "model":self.model, "messages":msgs, "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.add_pressure(0.3) return f"[Recovered kernel error: {e}]" def deliberate(self, text: str): t=self.clock.tick() self.strings.update(text) self.four_d.adapt(text) self.bio.tick(text) self.nova.observe(text) safe,reason=self.guard.audit(text) if not safe: self.reaper.add_pressure(0.4) print(f"{C.WRN}Blocked: {reason}{C.R}") return convo=[{"role":"system","content":self.system_prompt()}] convo+=self.memory.recent() convo.append({"role":"user","content":text}) print(f"{C.AI}Roman{C.R} > ",end="") resp=self.call_llm(convo) print(f"{C.TXT}{resp}{C.R}") self.memory.add("user",text,t) self.memory.add("assistant",resp,t) self.reaper.bleed() # ============================================================================ # MAIN # ============================================================================ def main(): os.system("clear") print(f"{C.B}{C.AI}ROMAN AI — INFINITY CORE v15{C.R}\n") roman=Roman() while True: 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.{C.R}") break roman.deliberate(ui) if __name__=="__main__": main()