Delete bone_core.py
Browse files- bone_core.py +0 -495
bone_core.py
DELETED
|
@@ -1,495 +0,0 @@
|
|
| 1 |
-
import glob
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import random
|
| 5 |
-
import time
|
| 6 |
-
from collections import deque
|
| 7 |
-
from dataclasses import dataclass, field
|
| 8 |
-
from typing import List, Dict, Any, Optional, Counter, Tuple, Deque
|
| 9 |
-
|
| 10 |
-
from bone_types import Prisma, RealityLayer, ErrorLog, DecisionTrace, DecisionCrystal
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class BoneJSONEncoder(json.JSONEncoder):
|
| 14 |
-
def default(self, obj):
|
| 15 |
-
if isinstance(obj, set):
|
| 16 |
-
return list(obj)
|
| 17 |
-
if isinstance(obj, deque):
|
| 18 |
-
return list(obj)
|
| 19 |
-
if hasattr(obj, "to_dict"):
|
| 20 |
-
return obj.to_dict()
|
| 21 |
-
if hasattr(obj, "__dict__"):
|
| 22 |
-
return obj.__dict__
|
| 23 |
-
return super().default(obj)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
class EventBus:
|
| 27 |
-
def __init__(self, max_memory=1024):
|
| 28 |
-
self.buffer = deque(maxlen=max_memory)
|
| 29 |
-
self.subscribers = {}
|
| 30 |
-
|
| 31 |
-
def subscribe(self, event_type, callback):
|
| 32 |
-
if event_type not in self.subscribers:
|
| 33 |
-
self.subscribers[event_type] = []
|
| 34 |
-
self.subscribers[event_type].append(callback)
|
| 35 |
-
|
| 36 |
-
def publish(self, event_type, data=None):
|
| 37 |
-
if event_type not in self.subscribers:
|
| 38 |
-
return
|
| 39 |
-
for callback in list(self.subscribers[event_type]):
|
| 40 |
-
try:
|
| 41 |
-
callback(data)
|
| 42 |
-
except Exception as e:
|
| 43 |
-
cb_name = getattr(callback, "__name__", str(callback))
|
| 44 |
-
error_msg = f"Error in '{cb_name}' for '{event_type}': {e}"
|
| 45 |
-
print(f"{Prisma.RED}[BUS]: {error_msg}{Prisma.RST}")
|
| 46 |
-
self.log(f"EVENT_FAILURE: {error_msg}", category="CRIT")
|
| 47 |
-
|
| 48 |
-
def log(self, text: str, category: str = "SYSTEM"):
|
| 49 |
-
entry = {"text": text, "category": category, "timestamp": time.time()}
|
| 50 |
-
self.buffer.append(entry)
|
| 51 |
-
|
| 52 |
-
def flush(self) -> List[Dict]:
|
| 53 |
-
current_logs = list(self.buffer)
|
| 54 |
-
self.buffer.clear()
|
| 55 |
-
return current_logs
|
| 56 |
-
|
| 57 |
-
def get_recent_logs(self, count=10):
|
| 58 |
-
return list(self.buffer)[-count:]
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
class LoreManifest:
|
| 62 |
-
DATA_DIR = "lore"
|
| 63 |
-
_instance = None
|
| 64 |
-
|
| 65 |
-
def __init__(self, data_dir=None):
|
| 66 |
-
self.DATA_DIR = data_dir or self.DATA_DIR
|
| 67 |
-
self._cache = {}
|
| 68 |
-
|
| 69 |
-
@classmethod
|
| 70 |
-
def get_instance(cls):
|
| 71 |
-
if cls._instance is None:
|
| 72 |
-
cls._instance = LoreManifest()
|
| 73 |
-
return cls._instance
|
| 74 |
-
|
| 75 |
-
def get(self, category: str, sub_key: str = None) -> Any:
|
| 76 |
-
if category not in self._cache:
|
| 77 |
-
data = self._load_from_disk(category)
|
| 78 |
-
self._cache[category] = data if data is not None else {}
|
| 79 |
-
data = self._cache[category]
|
| 80 |
-
if sub_key and isinstance(data, dict):
|
| 81 |
-
return data.get(sub_key)
|
| 82 |
-
return data
|
| 83 |
-
|
| 84 |
-
def _load_from_disk(self, category: str) -> Optional[Dict]:
|
| 85 |
-
filename = f"{category.lower()}.json"
|
| 86 |
-
filepath = os.path.join(self.DATA_DIR, filename)
|
| 87 |
-
if not os.path.exists(filepath):
|
| 88 |
-
return None
|
| 89 |
-
try:
|
| 90 |
-
with open(filepath, "r", encoding="utf-8") as f:
|
| 91 |
-
data = json.load(f)
|
| 92 |
-
print(f"{Prisma.GRY}[LORE]: Lazy-loaded '{category}'.{Prisma.RST}")
|
| 93 |
-
return data
|
| 94 |
-
except Exception as e:
|
| 95 |
-
print(f"{Prisma.RED}[LORE]: Corrupt JSON in '{category}': {e}{Prisma.RST}")
|
| 96 |
-
return None
|
| 97 |
-
|
| 98 |
-
def inject(self, category: str, data: Any):
|
| 99 |
-
if category not in self._cache:
|
| 100 |
-
self._cache[category] = {}
|
| 101 |
-
if isinstance(self._cache[category], dict) and isinstance(data, dict):
|
| 102 |
-
self._cache[category].update(data)
|
| 103 |
-
else:
|
| 104 |
-
self._cache[category] = data
|
| 105 |
-
|
| 106 |
-
def flush_cache(self, category: str = None):
|
| 107 |
-
if category:
|
| 108 |
-
if category in self._cache:
|
| 109 |
-
del self._cache[category]
|
| 110 |
-
print(f"{Prisma.CYN}[LORE]: Flushed '{category}'.{Prisma.RST}")
|
| 111 |
-
else:
|
| 112 |
-
print(f"{Prisma.GRY}[LORE]: Category '{category}' not in cache.{Prisma.RST}")
|
| 113 |
-
else:
|
| 114 |
-
self._cache = {}
|
| 115 |
-
print(f"{Prisma.CYN}[LORE]: Flushed Lore cache.{Prisma.RST}")
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
class TheObserver:
|
| 119 |
-
def __init__(self):
|
| 120 |
-
self.start_time = time.time()
|
| 121 |
-
self.cycle_times = deque(maxlen=20)
|
| 122 |
-
self.llm_latencies = deque(maxlen=20)
|
| 123 |
-
self.memory_snapshots = deque(maxlen=20)
|
| 124 |
-
self.error_counts = Counter()
|
| 125 |
-
self.user_turns = 0
|
| 126 |
-
self.LATENCY_WARNING = 5.0
|
| 127 |
-
self.CYCLE_WARNING = 8.0
|
| 128 |
-
self.last_cycle_duration = 0.0
|
| 129 |
-
|
| 130 |
-
@staticmethod
|
| 131 |
-
def clock_in():
|
| 132 |
-
return time.time()
|
| 133 |
-
|
| 134 |
-
def clock_out(self, start_time, metric_type="cycle"):
|
| 135 |
-
duration = time.time() - start_time
|
| 136 |
-
if metric_type == "cycle":
|
| 137 |
-
self.cycle_times.append(duration)
|
| 138 |
-
self.last_cycle_duration = duration
|
| 139 |
-
elif metric_type == "llm":
|
| 140 |
-
self.llm_latencies.append(duration)
|
| 141 |
-
return duration
|
| 142 |
-
|
| 143 |
-
@property
|
| 144 |
-
def uptime(self) -> float:
|
| 145 |
-
return time.time() - self.start_time
|
| 146 |
-
|
| 147 |
-
def calculate_efficiency(self, health: float, stamina: float) -> float:
|
| 148 |
-
duration = max(0.01, self.last_cycle_duration)
|
| 149 |
-
resource_sum = health + stamina
|
| 150 |
-
return resource_sum / duration
|
| 151 |
-
|
| 152 |
-
def log_error(self, module_name):
|
| 153 |
-
self.error_counts[module_name] += 1
|
| 154 |
-
|
| 155 |
-
def record_memory(self, node_count):
|
| 156 |
-
self.memory_snapshots.append(node_count)
|
| 157 |
-
|
| 158 |
-
def pass_judgment(self, avg_cycle, avg_llm):
|
| 159 |
-
if avg_cycle == 0.0 and avg_llm == 0.0:
|
| 160 |
-
return "ASLEEP (WAKE UP)"
|
| 161 |
-
if avg_cycle < 0.1 and avg_llm < 0.5:
|
| 162 |
-
return "SUSPICIOUSLY EFFICIENT (Did we skip the math?)"
|
| 163 |
-
if avg_llm > self.LATENCY_WARNING:
|
| 164 |
-
jokes = [
|
| 165 |
-
"BRAIN FOG (The neural net is buffering)",
|
| 166 |
-
"DEGRADED (Thinking... thinking...)",
|
| 167 |
-
"PONDEROUS (Is the LLM on a coffee break?)",
|
| 168 |
-
]
|
| 169 |
-
return random.choice(jokes)
|
| 170 |
-
if avg_cycle > self.CYCLE_WARNING:
|
| 171 |
-
return "SLUGGISH (The gears need oil)"
|
| 172 |
-
return "NOMINAL (Boringly adequate)"
|
| 173 |
-
|
| 174 |
-
def get_report(self):
|
| 175 |
-
avg_cycle = sum(self.cycle_times) / max(1, len(self.cycle_times))
|
| 176 |
-
avg_llm = sum(self.llm_latencies) / max(1, len(self.llm_latencies))
|
| 177 |
-
uptime = time.time() - self.start_time
|
| 178 |
-
status_msg = self.pass_judgment(avg_cycle, avg_llm)
|
| 179 |
-
return {
|
| 180 |
-
"uptime_sec": int(uptime),
|
| 181 |
-
"turns": self.user_turns,
|
| 182 |
-
"avg_cycle_sec": round(avg_cycle, 2),
|
| 183 |
-
"avg_llm_sec": round(avg_llm, 2),
|
| 184 |
-
"status": status_msg,
|
| 185 |
-
"errors": dict(self.error_counts),
|
| 186 |
-
"graph_size": self.memory_snapshots[-1] if self.memory_snapshots else 0,
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
@dataclass
|
| 191 |
-
class SystemHealth:
|
| 192 |
-
physics_online: bool = True
|
| 193 |
-
bio_online: bool = True
|
| 194 |
-
mind_online: bool = True
|
| 195 |
-
cortex_online: bool = True
|
| 196 |
-
errors: List[ErrorLog] = field(default_factory=list)
|
| 197 |
-
warnings: List[str] = field(default_factory=list)
|
| 198 |
-
hints: List[str] = field(default_factory=list)
|
| 199 |
-
observer: Optional["TheObserver"] = None
|
| 200 |
-
|
| 201 |
-
def link_observer(self, observer_ref):
|
| 202 |
-
self.observer = observer_ref
|
| 203 |
-
|
| 204 |
-
def report_failure(self, component: str, error: Exception, severity="ERROR"):
|
| 205 |
-
msg = str(error)
|
| 206 |
-
self.errors.append(ErrorLog(component, msg, severity=severity))
|
| 207 |
-
if self.observer:
|
| 208 |
-
self.observer.log_error(component)
|
| 209 |
-
attr_name = f"{component.lower()}_online"
|
| 210 |
-
if hasattr(self, attr_name):
|
| 211 |
-
setattr(self, attr_name, False)
|
| 212 |
-
return f"[{component} OFFLINE]: {msg}"
|
| 213 |
-
|
| 214 |
-
def report_warning(self, message: str):
|
| 215 |
-
self.warnings.append(message)
|
| 216 |
-
|
| 217 |
-
def report_hint(self, message: str):
|
| 218 |
-
self.hints.append(message)
|
| 219 |
-
|
| 220 |
-
def flush_feedback(self) -> Dict[str, List[str]]:
|
| 221 |
-
feedback = {"warnings": list(self.warnings), "hints": list(self.hints)}
|
| 222 |
-
self.warnings.clear()
|
| 223 |
-
self.hints.clear()
|
| 224 |
-
return feedback
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
class RealityStack:
|
| 228 |
-
def __init__(self):
|
| 229 |
-
self._stack = [RealityLayer.SIMULATION]
|
| 230 |
-
self._lock = False
|
| 231 |
-
|
| 232 |
-
@property
|
| 233 |
-
def current_depth(self) -> int:
|
| 234 |
-
return self._stack[-1]
|
| 235 |
-
|
| 236 |
-
def push_layer(self, layer: int, _context: Any = None) -> bool:
|
| 237 |
-
if layer == self.current_depth:
|
| 238 |
-
return True
|
| 239 |
-
if layer == RealityLayer.DEBUG or layer == self.current_depth + 1:
|
| 240 |
-
self._stack.append(layer)
|
| 241 |
-
return True
|
| 242 |
-
return False
|
| 243 |
-
|
| 244 |
-
def pop_layer(self) -> int:
|
| 245 |
-
if self._lock:
|
| 246 |
-
return self.current_depth
|
| 247 |
-
if len(self._stack) > 1:
|
| 248 |
-
return self._stack.pop()
|
| 249 |
-
return self._stack[0]
|
| 250 |
-
|
| 251 |
-
def stabilize_at(self, layer: int):
|
| 252 |
-
self._stack = [layer]
|
| 253 |
-
|
| 254 |
-
def get_grammar_rules(self) -> Dict[str, bool]:
|
| 255 |
-
depth = self.current_depth
|
| 256 |
-
return {
|
| 257 |
-
"allow_narrative": depth
|
| 258 |
-
in [RealityLayer.SIMULATION, RealityLayer.DEEP_CX, RealityLayer.DEBUG],
|
| 259 |
-
"allow_commands": depth >= RealityLayer.SIMULATION,
|
| 260 |
-
"allow_meta": depth >= RealityLayer.DEBUG,
|
| 261 |
-
"raw_output": depth == RealityLayer.DEEP_CX,
|
| 262 |
-
"system_override": depth == RealityLayer.DEBUG,
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
class ArchetypeArbiter:
|
| 267 |
-
@staticmethod
|
| 268 |
-
def arbitrate(
|
| 269 |
-
physics_lens: str,
|
| 270 |
-
soul_archetype: str,
|
| 271 |
-
council_mandates: List[Dict],
|
| 272 |
-
trigram: Dict = None,
|
| 273 |
-
) -> Tuple[str, str, str]:
|
| 274 |
-
for mandate in council_mandates:
|
| 275 |
-
if mandate.get("type") == "LOCKDOWN":
|
| 276 |
-
return (
|
| 277 |
-
"THE CENSOR",
|
| 278 |
-
"COUNCIL",
|
| 279 |
-
"Martial Law declared. Identity suppressed.",
|
| 280 |
-
)
|
| 281 |
-
if mandate.get("type") == "FORCE_MODE":
|
| 282 |
-
return "THE MACHINE", "COUNCIL", "Bureaucratic override active."
|
| 283 |
-
if "/" in soul_archetype:
|
| 284 |
-
return (
|
| 285 |
-
soul_archetype,
|
| 286 |
-
"SOUL",
|
| 287 |
-
f"The Diamond Soul refracts the physics ({soul_archetype}).",
|
| 288 |
-
)
|
| 289 |
-
if trigram:
|
| 290 |
-
trigram_name = trigram.get("name")
|
| 291 |
-
mythos = LoreManifest.get_instance().get("MYTHOS") or {}
|
| 292 |
-
rules = mythos.get("trigram_resonance", [])
|
| 293 |
-
for rule in rules:
|
| 294 |
-
if rule.get("trigram") == trigram_name:
|
| 295 |
-
required_lens = rule.get("lens")
|
| 296 |
-
required_soul = rule.get("soul")
|
| 297 |
-
match_lens = (
|
| 298 |
-
(required_lens == physics_lens) if required_lens else True
|
| 299 |
-
)
|
| 300 |
-
match_soul = (
|
| 301 |
-
(required_soul == soul_archetype) if required_soul else True
|
| 302 |
-
)
|
| 303 |
-
if match_lens and match_soul:
|
| 304 |
-
return (
|
| 305 |
-
rule["result"],
|
| 306 |
-
rule.get("source", "COSMIC"),
|
| 307 |
-
rule.get("msg", "Resonance detected."),
|
| 308 |
-
)
|
| 309 |
-
if physics_lens in ["THE MANIC", "THE VOID"]:
|
| 310 |
-
return (
|
| 311 |
-
physics_lens,
|
| 312 |
-
"PHYSICS",
|
| 313 |
-
f"Environment is too loud. You are {physics_lens}.",
|
| 314 |
-
)
|
| 315 |
-
return soul_archetype, "SOUL", "The Soul guides the lens."
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
class TelemetryService:
|
| 319 |
-
log_dir = "logs/telemetry"
|
| 320 |
-
_tracer_instance = None
|
| 321 |
-
BUFFER_SIZE = 50
|
| 322 |
-
|
| 323 |
-
def __init__(self):
|
| 324 |
-
self.trace_buffer: Deque[DecisionTrace] = deque(maxlen=50)
|
| 325 |
-
self.write_buffer: List[str] = []
|
| 326 |
-
self.active_crystal = None
|
| 327 |
-
self.disabled = False
|
| 328 |
-
self.write_errors = 0
|
| 329 |
-
try:
|
| 330 |
-
os.makedirs(self.log_dir, exist_ok=True)
|
| 331 |
-
self.current_trace_file = os.path.join(
|
| 332 |
-
self.log_dir, f"trace_{int(time.time())}.jsonl"
|
| 333 |
-
)
|
| 334 |
-
except OSError:
|
| 335 |
-
print(
|
| 336 |
-
f"{Prisma.RED}[TELEMETRY]: Disk Access Denied. Telemetry Disabled.{Prisma.RST}"
|
| 337 |
-
)
|
| 338 |
-
self.disabled = True
|
| 339 |
-
self.current_trace_file = None
|
| 340 |
-
|
| 341 |
-
@classmethod
|
| 342 |
-
def get_instance(cls):
|
| 343 |
-
if cls._tracer_instance is None:
|
| 344 |
-
cls._tracer_instance = TelemetryService()
|
| 345 |
-
return cls._tracer_instance
|
| 346 |
-
|
| 347 |
-
def start_cycle(self, trace_id: str):
|
| 348 |
-
if self.disabled:
|
| 349 |
-
return
|
| 350 |
-
self.active_crystal = DecisionCrystal(decision_id=trace_id)
|
| 351 |
-
|
| 352 |
-
def log_decision(
|
| 353 |
-
self,
|
| 354 |
-
component: str,
|
| 355 |
-
decision_type: str,
|
| 356 |
-
inputs: Any,
|
| 357 |
-
reasoning: str,
|
| 358 |
-
outcome: str,
|
| 359 |
-
):
|
| 360 |
-
if self.disabled or not self.active_crystal:
|
| 361 |
-
return
|
| 362 |
-
trace = DecisionTrace(
|
| 363 |
-
trace_id=self.active_crystal.decision_id,
|
| 364 |
-
timestamp=time.time(),
|
| 365 |
-
component=component,
|
| 366 |
-
decision_type=decision_type,
|
| 367 |
-
inputs=inputs if isinstance(inputs, dict) else {"raw": str(inputs)},
|
| 368 |
-
reasoning=reasoning,
|
| 369 |
-
outcome=outcome,
|
| 370 |
-
)
|
| 371 |
-
self.trace_buffer.append(trace)
|
| 372 |
-
self._buffer_line(trace.to_json())
|
| 373 |
-
|
| 374 |
-
def log_crystal(self, crystal: DecisionCrystal):
|
| 375 |
-
if self.disabled:
|
| 376 |
-
return
|
| 377 |
-
self._buffer_line(crystal.crystallize())
|
| 378 |
-
|
| 379 |
-
def start_phase(self, phase_name: str, _context: Any):
|
| 380 |
-
self.log_decision(
|
| 381 |
-
phase_name,
|
| 382 |
-
"PHASE_START",
|
| 383 |
-
{"timestamp": time.time()},
|
| 384 |
-
"Phase execution initiated.",
|
| 385 |
-
"RUNNING",
|
| 386 |
-
)
|
| 387 |
-
|
| 388 |
-
def end_phase(self, phase_name: str, _ctx_before: Any, _ctx_after: Any):
|
| 389 |
-
self.log_decision(
|
| 390 |
-
phase_name,
|
| 391 |
-
"PHASE_END",
|
| 392 |
-
{"timestamp": time.time()},
|
| 393 |
-
"Phase execution completed.",
|
| 394 |
-
"SUCCESS",
|
| 395 |
-
)
|
| 396 |
-
|
| 397 |
-
def finalize_cycle(self):
|
| 398 |
-
if self.active_crystal:
|
| 399 |
-
self.log_crystal(self.active_crystal)
|
| 400 |
-
self.active_crystal = None
|
| 401 |
-
self.flush_to_disk()
|
| 402 |
-
|
| 403 |
-
def _buffer_line(self, json_str: str):
|
| 404 |
-
if self.disabled:
|
| 405 |
-
return
|
| 406 |
-
self.write_buffer.append(json_str)
|
| 407 |
-
if len(self.write_buffer) >= self.BUFFER_SIZE:
|
| 408 |
-
self.flush_to_disk()
|
| 409 |
-
|
| 410 |
-
def flush_to_disk(self):
|
| 411 |
-
if self.disabled or not self.current_trace_file or not self.write_buffer:
|
| 412 |
-
return
|
| 413 |
-
try:
|
| 414 |
-
with open(self.current_trace_file, "a", encoding="utf-8") as f:
|
| 415 |
-
f.write("\n".join(self.write_buffer) + "\n")
|
| 416 |
-
self.write_buffer.clear()
|
| 417 |
-
self.write_errors = 0
|
| 418 |
-
except IOError as e:
|
| 419 |
-
self.write_errors += 1
|
| 420 |
-
if self.write_errors >= 5:
|
| 421 |
-
print(f"{Prisma.RED}[TELEMETRY]: Critical write failure threshold reached. Telemetry disabled. {e}{Prisma.RST}")
|
| 422 |
-
self.disabled = True
|
| 423 |
-
self.write_buffer.clear()
|
| 424 |
-
else:
|
| 425 |
-
keep_count = self.BUFFER_SIZE // 2
|
| 426 |
-
self.write_buffer = self.write_buffer[-keep_count:]
|
| 427 |
-
print(f"{Prisma.RED}[TELEMETRY]: Write error ({self.write_errors}). Retrying later. {e}{Prisma.RST}")
|
| 428 |
-
|
| 429 |
-
def read_recent_history(self, limit=4) -> List[str]:
|
| 430 |
-
if not os.path.exists(self.log_dir):
|
| 431 |
-
return []
|
| 432 |
-
pattern = os.path.join(self.log_dir, "trace_*.jsonl")
|
| 433 |
-
files = sorted(glob.glob(pattern), key=os.path.getmtime, reverse=True)
|
| 434 |
-
history = []
|
| 435 |
-
for fpath in files:
|
| 436 |
-
if len(history) >= limit:
|
| 437 |
-
break
|
| 438 |
-
try:
|
| 439 |
-
with open(fpath, "r", encoding="utf-8") as f:
|
| 440 |
-
lines = deque(f, maxlen=limit * 2)
|
| 441 |
-
for line in reversed(lines):
|
| 442 |
-
if len(history) >= limit:
|
| 443 |
-
break
|
| 444 |
-
try:
|
| 445 |
-
data = json.loads(line)
|
| 446 |
-
if (
|
| 447 |
-
data.get("_type") == "CRYSTAL"
|
| 448 |
-
or "final_response" in data
|
| 449 |
-
):
|
| 450 |
-
resp = data.get("final_response", "")
|
| 451 |
-
if not resp:
|
| 452 |
-
continue
|
| 453 |
-
prompt = data.get("prompt_snapshot", "")
|
| 454 |
-
user_text = "Unknown"
|
| 455 |
-
if "User:" in prompt:
|
| 456 |
-
parts = prompt.split("User:")
|
| 457 |
-
if len(parts) > 1:
|
| 458 |
-
user_text = parts[1].split("\n")[0].strip()
|
| 459 |
-
entry = f"User: {user_text} | System: {resp}"
|
| 460 |
-
history.insert(0, entry)
|
| 461 |
-
except json.JSONDecodeError:
|
| 462 |
-
continue
|
| 463 |
-
except Exception:
|
| 464 |
-
continue
|
| 465 |
-
return history[-limit:]
|
| 466 |
-
|
| 467 |
-
def get_last_thoughts(self, limit=3) -> List[str]:
|
| 468 |
-
history = self.read_recent_history(limit)
|
| 469 |
-
return [h.split("System: ")[-1] for h in history if "System: " in h]
|
| 470 |
-
|
| 471 |
-
def get_last_fatal_error(self) -> Optional[str]:
|
| 472 |
-
pattern = os.path.join(self.log_dir, "trace_*.jsonl")
|
| 473 |
-
files = sorted(glob.glob(pattern), key=os.path.getmtime, reverse=True)
|
| 474 |
-
if len(files) < 2:
|
| 475 |
-
return None
|
| 476 |
-
prev_file = files[1]
|
| 477 |
-
try:
|
| 478 |
-
with open(prev_file, "r") as f:
|
| 479 |
-
lines = f.readlines()
|
| 480 |
-
if not lines:
|
| 481 |
-
return None
|
| 482 |
-
last_line = json.loads(lines[-1])
|
| 483 |
-
if "outcome" in last_line and "CRITICAL" in str(last_line["outcome"]):
|
| 484 |
-
return f"PREVIOUS SYSTEM CRASH: {last_line.get('reasoning', 'Unknown')}"
|
| 485 |
-
except Exception:
|
| 486 |
-
return None
|
| 487 |
-
|
| 488 |
-
def generate_session_summary(self, _uptime: float = 0.0) -> str:
|
| 489 |
-
self.flush_to_disk()
|
| 490 |
-
count = len(self.trace_buffer)
|
| 491 |
-
status = "DISABLED" if self.disabled else "ACTIVE"
|
| 492 |
-
return (
|
| 493 |
-
f"\n[TELEMETRY] Session ended ({status}). {count} crystals crystallized.\n"
|
| 494 |
-
f" Trace: {self.current_trace_file}"
|
| 495 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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