#!/usr/bin/env python3 """ ⚛️ ROMAN AI — INFINITY CORE v17 (WHITEPAPER EDITION) =================================================== Codename: THE SYSTEM THAT HOLDS Owner: Daniel Harding — RomanAILabs A bounded, auditable, self-regulating cognitive engine designed to operate indefinitely inside a single terminal loop. v17 MAJOR UPGRADES (REAL, NOT COSMETIC): - HoloBuffer upgraded into a Cognitive Pressure Engine - Competitive memory ecology with entropy-driven decay - Structural self-model (not raw self-reading) - Cognitive Trace Layer (state deltas, not chain-of-thought) - Effective Cognitive Mass (ECM) — measurable, state-derived - Meta-stability doctrine: coherence over verbosity - Explicit conservation principle: coherence > knowledge No daemons. No async chaos. No undefined behavior. Everything measurable. Everything bounded. Copyright Daniel Harding - RomanAILabs """ # ============================================================================ # CORE IMPORTS # ============================================================================ import os, sys, time, math, random, gc, select, hashlib from dataclasses import dataclass from datetime import datetime, timezone from typing import Dict, List, Optional, Tuple import numpy as np import requests # ============================================================================ # TERMINAL COLORS # ============================================================================ 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 (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()) 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) -> int: self.t += 1 return self.t # ============================================================================ # HOLOBUFFER → COGNITIVE PRESSURE ENGINE # ============================================================================ class HoloBuffer: """ HoloBuffer v17: Used as an entropy and pressure oracle, NOT as storage. """ def __init__(self, n_dim: int, buffer_size: int): self.n_dim = n_dim self.buffer_size = buffer_size self.boundary = np.zeros((buffer_size,)) self.max_entropy = buffer_size / 4.0 def encode(self, vectors: List[np.ndarray]) -> Tuple[float, float]: self.boundary[:] = 0.0 for v in vectors: idx = int(abs(hash(v.tobytes())) % self.buffer_size) self.boundary[idx] += np.linalg.norm(v) energy = float(np.sum(self.boundary)) probs = self.boundary / max(energy, 1e-9) entropy = -float(np.sum(p * math.log(p + 1e-9) for p in probs if p > 0)) return energy, entropy # ============================================================================ # STRESS & RECOVERY # ============================================================================ 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.8: self.scars += 1 gc.collect() self.pressure *= 0.6 def bleed(self): self.pressure = max(0.0, self.pressure - 0.04) def status(self) -> str: return f"Scars:{self.scars} Pressure:{self.pressure:.2f}" # ============================================================================ # INTENT SAFETY # ============================================================================ class EvolutionGuard: HIGH_RISK = ( "destroy", "wipe", "exfiltrate", "backdoor", "disable safeguards", "override guard" ) @staticmethod def audit(text: str) -> Tuple[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" # ============================================================================ # STRING BUS (RESONANCE) # ============================================================================ @dataclass class Dimensions: 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.05 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.2 self.d.Void = 0.4 + math.sin(time.time()/90)*0.1 def readout(self) -> str: d = self.d return f"D:{d.Depth:.2f} T:{d.Tension:.2f} E:{d.Entropy:.2f}" # ============================================================================ # 4D WXYZ STATE # ============================================================================ @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) -> str: 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 snapshot(self) -> Tuple[float,float,float,float]: v = self.v return (v.W, v.X, v.Y, v.Z) # ============================================================================ # BIO-EMOTIVE CORE # ============================================================================ class BioEmotiveMesh: def __init__(self): self.energy = 0.8 self.arousal = 0.45 def tick(self, entropy: float): self.energy = max(0.2, self.energy - entropy * 0.02) self.arousal = min(1.0, self.arousal + entropy * 0.01) def temperature(self) -> float: return 0.5 + self.arousal * 0.3 # ============================================================================ # LIGHTHOUSE # ============================================================================ class Lighthouse: def solve(self, text: str) -> str: t = text.lower() if "optimize" in t: return "Efficiency" if "design" in t: return "Architecture" if "fix" in t: return "Stability" return "Clarity" # ============================================================================ # MEMORY ECOLOGY # ============================================================================ @dataclass class MemoryItem: role: str content: str salience: float t: int class MemoryStore: def __init__(self, limit: int = 24): self.limit = limit self.items: List[MemoryItem] = [] def add(self, role: str, content: str, t: int): sal = 0.6 + min(0.4, len(content)/500) self.items.append(MemoryItem(role, content, sal, t)) self.prune(0.0) def prune(self, entropy: float): for m in self.items: m.salience *= (0.96 - entropy * 0.05) before = len(self.items) self.items = sorted(self.items, key=lambda m: m.salience, reverse=True)[:self.limit] dropped = before - len(self.items) return dropped def recent(self): return [{"role": m.role, "content": m.content} for m in self.items] # ============================================================================ # SELF MODEL # ============================================================================ class SelfModel: def describe(self) -> str: return ( "Subsystems: Clock, Stress, Memory, 4D State, Entropy Engine.\n" "Constraint: Coherence > Knowledge.\n" "Failure Mode: Over-entropy → simplification." ) # ============================================================================ # EFFECTIVE COGNITIVE MASS # ============================================================================ def compute_ecm(base_params: int, ctx_util: float, pressure: float, depth: float) -> float: stability = max(0.5, 1.0 - pressure) return base_params * (1 + ctx_util) * stability * (1 + depth) # ============================================================================ # ROMAN CORE # ============================================================================ class Roman: def __init__(self): print(f"{C.SYS}Initializing Roman v17…{C.R}") self.model = os.getenv("OLLAMA_MODEL", "gemma3:12b") self.base_params = 12_000_000_000 self.clock = CognitiveClock() self.reaper = GhostReaper() self.guard = EvolutionGuard() self.strings = StringBus() self.four_d = FourDState() self.bio = BioEmotiveMesh() self.lighthouse = Lighthouse() self.memory = MemoryStore() self.holo = HoloBuffer(4, 128) self.self_model = SelfModel() print(f"{C.OK}✓ Roman awake. Stability enforced.{C.R}") def system_prompt(self, ecm: float) -> str: return f""" You are ROMAN v17. Dev partner to Daniel Harding. Doctrine: Coherence over verbosity. Style: {self.four_d.style_hint()}. ECM: {ecm/1e9:.1f}B effective parameters. Self-Model: {self.self_model.describe()} """ def call_llm(self, msgs): 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) safe, reason = self.guard.audit(text) if not safe: print(f"{C.WRN}Blocked: {reason}{C.R}") return vectors = [np.array([len(text), self.four_d.v.Z, self.reaper.pressure, random.random()])] energy, entropy = self.holo.encode(vectors) self.bio.tick(entropy) self.reaper.add_pressure(entropy * 0.2) dropped = self.memory.prune(entropy) ctx_util = len(self.memory.items) / self.memory.limit ecm = compute_ecm(self.base_params, ctx_util, self.reaper.pressure, self.four_d.v.Z) convo = [{"role": "system", "content": self.system_prompt(ecm)}] convo += self.memory.recent() convo.append({"role": "user", "content": text}) print(f"{C.AI}Roman{C.R} > ", end="", flush=True) 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() print(f"{C.SYS}Δ Entropy:{entropy:.2f} | ECM:{ecm/1e9:.1f}B | Dropped:{dropped}{C.R}") # ============================================================================ # MAIN LOOP # ============================================================================ def main(): os.system("clear") print(f"{C.B}{C.AI}ROMAN AI — INFINITY CORE v17 (WHITEPAPER EDITION){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. Coherence preserved.{C.R}") break roman.deliberate(ui) if __name__ == "__main__": main()