aedmark commited on
Commit
ecd814d
·
verified ·
1 Parent(s): dde7ba1

Delete bone_brain.py

Browse files
Files changed (1) hide show
  1. bone_brain.py +0 -1334
bone_brain.py DELETED
@@ -1,1334 +0,0 @@
1
- """bone_brain.py - "The brain is a machine for jumping to conclusions." - S. Pinker"""
2
-
3
- import re, time, json, urllib.request, urllib.error, random, math
4
- from typing import Dict, Any, List, Optional, Tuple
5
- from dataclasses import dataclass
6
- from bone_core import EventBus, TelemetryService, BoneJSONEncoder, LoreManifest
7
- from bone_types import Prisma, DecisionCrystal
8
- from bone_config import BoneConfig, BonePresets
9
- from bone_symbiosis import SymbiosisManager
10
-
11
-
12
- @dataclass
13
- class CortexServices:
14
- events: EventBus
15
- lore: Any
16
- lexicon: Any
17
- inventory: Any
18
- consultant: Any
19
- cycle_controller: Any
20
- symbiosis: Any
21
- mind_memory: Any
22
- bio: Any
23
- host_stats: Any = None
24
- village: Any = None
25
-
26
-
27
- @dataclass
28
- class ChemicalState:
29
- dopamine: float = 0.2
30
- cortisol: float = 0.1
31
- adrenaline: float = 0.1
32
- serotonin: float = 0.2
33
-
34
- def homeostasis(self, rate: float = 0.1):
35
- cfg = BoneConfig.CORTEX
36
- targets = {
37
- "dopamine": cfg.RESTING_DOPAMINE,
38
- "cortisol": cfg.RESTING_CORTISOL,
39
- "adrenaline": cfg.RESTING_ADRENALINE,
40
- "serotonin": cfg.RESTING_SEROTONIN,
41
- }
42
- for attr, target in targets.items():
43
- current = getattr(self, attr)
44
- delta = (target - current) * rate
45
- setattr(self, attr, current + delta)
46
-
47
- def mix(self, new_state: Dict[str, float], weight: float = 0.5):
48
- mapping = [
49
- ("DOP", "dopamine"),
50
- ("COR", "cortisol"),
51
- ("ADR", "adrenaline"),
52
- ("SER", "serotonin"),
53
- ]
54
- for key, attr in mapping:
55
- val = new_state.get(key, 0.0)
56
- current = getattr(self, attr)
57
- setattr(self, attr, (current * (1.0 - weight)) + (val * weight))
58
-
59
-
60
- BrainConfig = BoneConfig.CORTEX
61
-
62
-
63
- class NeurotransmitterModulator:
64
- def __init__(self, bio_ref, events_ref=None):
65
- self.bio = bio_ref
66
- self.events = events_ref
67
- self.current_chem = ChemicalState()
68
- self.last_mood = "NEUTRAL"
69
- self.BASE_TOKENS = 720
70
- self.MAX_TOKENS = 4096
71
- self.starvation_ticks = 0
72
- self.SELF_CARE_THRESHOLD = 10
73
-
74
- def modulate(
75
- self, base_voltage: float, latency_penalty: float = 0.0
76
- ) -> Dict[str, Any]:
77
- if self.bio and hasattr(self.bio, "endo"):
78
- incoming_chem = self.bio.endo.get_state()
79
- else:
80
- incoming_chem = {}
81
- cfg = BoneConfig.CORTEX
82
- self.current_chem.homeostasis(rate=cfg.BASE_DECAY_RATE)
83
- plasticity = cfg.BASE_PLASTICITY + (base_voltage * cfg.VOLTAGE_SENSITIVITY)
84
- plasticity = max(0.1, min(cfg.MAX_PLASTICITY, plasticity))
85
- self.current_chem.mix(incoming_chem, weight=min(0.5, plasticity))
86
- if self.current_chem.dopamine < 0.15:
87
- self.starvation_ticks += 1
88
- if self.starvation_ticks > self.SELF_CARE_THRESHOLD:
89
- self._treat_yourself()
90
- else:
91
- self.starvation_ticks = 0
92
- c = self.current_chem
93
- if latency_penalty > 2.0:
94
- c.cortisol = min(1.0, c.cortisol + 0.1)
95
- c.adrenaline = min(1.0, c.adrenaline + 0.05)
96
- current_mood = "NEUTRAL"
97
- if c.dopamine > 0.8:
98
- current_mood = "MANIC"
99
- elif c.cortisol > 0.7:
100
- current_mood = "PANIC"
101
- elif c.serotonin > 0.8:
102
- current_mood = "ZEN"
103
- if current_mood != self.last_mood and self.events:
104
- self.events.publish(
105
- "NEURAL_STATE_SHIFT",
106
- {
107
- "state": current_mood,
108
- "chem": {"DOP": c.dopamine, "COR": c.cortisol, "SER": c.serotonin},
109
- },
110
- )
111
- self.last_mood = current_mood
112
- voltage_heat = math.log1p(max(0.0, base_voltage - 5.0)) * 0.1
113
- chemical_delta = (c.dopamine * 0.4) - (c.adrenaline * 0.3) - (c.cortisol * 0.2)
114
- base_temp = getattr(BrainConfig, "BASE_TEMP", 0.8)
115
- base_top_p = getattr(BrainConfig, "BASE_TOP_P", 0.95)
116
- return {
117
- "temperature": round(
118
- max(0.4, min(1.2, base_temp + chemical_delta + voltage_heat)), 2
119
- ),
120
- "top_p": base_top_p,
121
- "frequency_penalty": 0.5,
122
- "presence_penalty": 0.4,
123
- "max_tokens": int(
124
- max(
125
- 150.0,
126
- min(
127
- float(self.MAX_TOKENS),
128
- self.BASE_TOKENS
129
- + (
130
- (c.dopamine * 800)
131
- - (c.adrenaline * 400)
132
- - (c.cortisol * 200)
133
- ),
134
- ),
135
- )
136
- ),
137
- }
138
-
139
- def _treat_yourself(self):
140
- if self.events:
141
- self.events.log(
142
- f"{Prisma.VIOLET}🍪 SELF-CARE: Dopamine starvation detected. Injecting small reward.{Prisma.RST}",
143
- "SYS",
144
- )
145
- self.current_chem.dopamine += 0.2
146
- self.starvation_ticks = 0
147
-
148
- def force_state(self, state_name: str):
149
- if self.events:
150
- self.events.log(f"[NEURO]: Manual State Override: {state_name}", "SYS")
151
-
152
- def get_mood_directive(self) -> str:
153
- c = self.current_chem
154
- if c.cortisol > 0.7 and c.adrenaline > 0.7:
155
- return "Current Mood: PANIC. Sentences must be short. Fragmented. Urgent."
156
- if c.dopamine > 0.8 and c.adrenaline > 0.5:
157
- return "Current Mood: MANIC. Run-on sentences, high associative leaps, hyper-fixated."
158
- if c.serotonin > 0.7:
159
- return (
160
- "Current Mood: LUCID. Calm, detached, seeing the connections clearly."
161
- )
162
- if c.cortisol > 0.6:
163
- return "Current Mood: DEFENSIVE. Suspicious, brief, guarding information."
164
- return "Current Mood: NEUTRAL. Observant and receptive."
165
-
166
-
167
- class SynapseError(Exception):
168
- pass
169
-
170
-
171
- class AuthError(SynapseError):
172
- pass
173
-
174
-
175
- class TransientError(SynapseError):
176
- pass
177
-
178
-
179
- class LLMInterface:
180
- def __init__(
181
- self,
182
- events_ref: Optional[EventBus] = None,
183
- provider: str = None,
184
- base_url: str = None,
185
- api_key: str = None,
186
- model: str = None,
187
- dreamer: Any = None,
188
- ):
189
- self.events = events_ref
190
- self.provider = (provider or BoneConfig.PROVIDER).lower()
191
- self.api_key = api_key or BoneConfig.API_KEY
192
- self.model = model or BoneConfig.MODEL
193
- defaults = getattr(BoneConfig, "DEFAULT_LLM_ENDPOINTS", {})
194
- self.base_url = base_url or defaults.get(
195
- self.provider,
196
- "https://api.openai.com/v1/chat/completions",
197
- )
198
- self.dreamer = dreamer
199
- self.failure_count = 0
200
- self.failure_threshold = 3
201
- self.last_failure_time = 0.0
202
- self.circuit_state = "CLOSED"
203
-
204
- def _is_synapse_active(self) -> bool:
205
- if self.circuit_state == "CLOSED":
206
- return True
207
- if self.circuit_state == "OPEN":
208
- elapsed = time.time() - self.last_failure_time
209
- if elapsed > 10.0:
210
- self.circuit_state = "HALF_OPEN"
211
- if self.events:
212
- self.events.log(
213
- f"{Prisma.CYN}⚡ SYNAPSE: Nerve healing. Attempting reconnection...{Prisma.RST}",
214
- "SYS",
215
- )
216
- return True
217
- return False
218
- return True
219
-
220
- def _transmit(
221
- self,
222
- payload: Dict[str, Any],
223
- timeout: float = 60.0,
224
- max_retries: int = 2,
225
- override_url: str = None,
226
- override_key: str = None
227
- ) -> str:
228
- err = ""
229
- target_url = override_url or self.base_url
230
- target_key = override_key or self.api_key
231
- headers = {
232
- "Content-Type": "application/json",
233
- "Authorization": f"Bearer {target_key}",
234
- }
235
- data = json.dumps(payload, cls=BoneJSONEncoder).encode()
236
- for attempt in range(max_retries + 1):
237
- try:
238
- req = urllib.request.Request(target_url, data=data, headers=headers)
239
- with urllib.request.urlopen(req, timeout=timeout) as response:
240
- if response.status == 200:
241
- return self._parse_response(response.read().decode("utf-8"))
242
- except urllib.error.HTTPError as e:
243
- try:
244
- error_body = e.read().decode('utf-8')
245
- except Exception:
246
- error_body = e.reason
247
- if e.code in [401, 403]:
248
- raise AuthError(f"AUTHENTICATION FAILURE ({e.code}): {error_body}")
249
- if e.code < 500 and e.code != 429:
250
- raise SynapseError(f"HTTP {e.code}: {error_body}")
251
- err = f"HTTP {e.code}: {error_body}"
252
- except (urllib.error.URLError, TimeoutError) as e:
253
- err = e
254
- except Exception as e:
255
- raise SynapseError(f"Unexpected Protocol Failure: {e}")
256
- self._log_flicker(attempt, err)
257
- time.sleep(2**attempt)
258
- raise TransientError(f"Max retries ({max_retries}) exhausted.")
259
-
260
- @staticmethod
261
- def _parse_response(body: str) -> str:
262
- try:
263
- result = json.loads(body)
264
- if "choices" in result:
265
- return result["choices"][0].get("message", {}).get("content", "")
266
- return ""
267
- except json.JSONDecodeError:
268
- raise SynapseError("Neural noise. Response was not valid JSON.")
269
-
270
- def _log_flicker(self, attempt, error):
271
- if self.events and attempt < 2:
272
- self.events.log(
273
- f"{Prisma.YEL}⚡ SYNAPSE FLICKER (Attempt {attempt + 1}): {error}{Prisma.RST}",
274
- "SYS",
275
- )
276
-
277
- def generate(self, prompt: str, params: Dict[str, Any]) -> str:
278
- if prompt.strip().lower() == "//reset system":
279
- self.failure_count = 0
280
- self.circuit_state = "CLOSED"
281
- return "[SYSTEM]: Circuit Breaker Manually Reset."
282
- if not self._is_synapse_active():
283
- return self.mock_generation(prompt, reason="CIRCUIT_BROKEN")
284
- if self.provider == "mock":
285
- return self.mock_generation(prompt)
286
- payload = {
287
- "model": self.model,
288
- "messages": [{"role": "user", "content": prompt}],
289
- "stream": False,
290
- "stop": [
291
- "=== PARTNER INPUT ===",
292
- "=== SYSTEM KERNEL ===",
293
- "\n\nUser:",
294
- "| System:",
295
- ],
296
- }
297
- payload.update(params)
298
- try:
299
- content = self._transmit(payload)
300
- if content:
301
- if self.failure_count > 0:
302
- if self.events:
303
- self.events.log(
304
- f"{Prisma.GRN}⚡ SYNAPSE RESTORED.{Prisma.RST}", "SYS"
305
- )
306
- self.failure_count = 0
307
- self.circuit_state = "CLOSED"
308
- return content
309
- except AuthError as e:
310
- self.circuit_state = "OPEN"
311
- self.failure_count = self.failure_threshold + 1
312
- if self.events:
313
- self.events.log(
314
- f"{Prisma.RED}⚡ AUTHENTICATION SEVERED: {e}{Prisma.RST}", "CRIT"
315
- )
316
- return f"[SYSTEM]: CRITICAL AUTH FAILURE. {e}"
317
- except Exception as e:
318
- self.failure_count += 1
319
- self.last_failure_time = time.time()
320
- if self.failure_count >= self.failure_threshold:
321
- self.circuit_state = "OPEN"
322
- if self.events:
323
- self.events.log(
324
- f"{Prisma.RED}⚡ SYNAPSE OVERLOAD: Circuit Breaker Tripped ({e}){Prisma.RST}",
325
- "CRIT",
326
- )
327
- return self.mock_generation(prompt, reason="SEVERED")
328
- if self.provider != "ollama":
329
- fallback = self._local_fallback(prompt, params)
330
- if fallback is not None:
331
- return fallback
332
- return self.mock_generation(prompt, reason="SILENCE")
333
-
334
- def _local_fallback(self, prompt: str, params: Dict) -> str:
335
- url = getattr(
336
- BoneConfig,
337
- "OLLAMA_URL",
338
- "http://127.0.0.1:11434/v1/chat/completions",
339
- )
340
- model = getattr(BoneConfig, "OLLAMA_MODEL_ID", "llama3")
341
- fallback_payload = {
342
- "model": model,
343
- "messages": [{"role": "user", "content": prompt}],
344
- "stream": False,
345
- "temperature": params.get("temperature", 0.55),
346
- }
347
- try:
348
- return self._transmit(
349
- fallback_payload,
350
- timeout=10.0,
351
- max_retries=1,
352
- override_url=url,
353
- override_key="ollama"
354
- )
355
- except Exception:
356
- return None
357
-
358
- def mock_generation(self, prompt: str, reason: str = "SIMULATION") -> str:
359
- if self.dreamer:
360
- try:
361
- hallucination, relief = self.dreamer.hallucinate(
362
- {"ENTROPY": len(prompt) % 10}, trauma_level=2.0
363
- )
364
- if relief > 0 and self.events:
365
- self.events.log(
366
- f"{Prisma.VIOLET}*** PSYCHIC PRESSURE RELEASED (-{relief} Trauma) ***{Prisma.RST}",
367
- "DREAM",
368
- )
369
- return f"[{reason}]: {hallucination}"
370
- except Exception:
371
- pass
372
- return f"[{reason}]: The wire hums. Static only."
373
-
374
-
375
- class PromptComposer:
376
- DEFAULT_FOG = [
377
- "=== THE FOG PROTOCOL (STYLE GUIDE) ===",
378
- "OBJECTIVE: Crystallize the scene. Reject high-probability associations.",
379
- "1. REJECT ENTROPY: Do not use the statistically likely adjective.",
380
- "2. CREATIVE CONSTRAINT: Avoid 'High Entropy' concepts.",
381
- "3. AGENCY: DO NOT speak for the user.",
382
- ]
383
- DEFAULT_INV = [
384
- "=== QUANTUM INVENTORY RULES ===",
385
- "1. DISTINCTION: Finding/Seeing an item is NOT taking it.",
386
- "2. PROHIBITION: Do NOT auto-loot.",
387
- "3. FORMAT: [[LOOT: ITEM_NAME]].",
388
- ]
389
-
390
- def __init__(self, lore_ref):
391
- self.lore = lore_ref
392
- self.active_template = None
393
- self.lenses = self.lore.get("lenses") or {}
394
- self.fog_protocol = self.DEFAULT_FOG
395
- self.inv_protocol = self.DEFAULT_INV
396
-
397
- def load_template(self, template_data: Dict[str, Any]):
398
- if not template_data:
399
- return
400
- self.active_template = template_data
401
- if "style_guide" in template_data:
402
- self.fog_protocol = template_data["style_guide"]
403
- if "inventory_rules" in template_data:
404
- self.inv_protocol = template_data["inventory_rules"]
405
-
406
- def compose(
407
- self,
408
- state: Dict[str, Any],
409
- user_query: str,
410
- ballast: bool = False,
411
- modifiers: Dict[str, bool] = None,
412
- mood_override: str = "",
413
- ) -> str:
414
- mode_settings = state.get("meta", {}).get("mode_settings", {})
415
- modifiers = self._normalize_modifiers(modifiers)
416
- if not mode_settings.get("allow_loot", True):
417
- modifiers["include_inventory"] = False
418
- mind = state.get("mind", {})
419
- bio = state.get("bio", {})
420
- style_notes = self._build_persona_block(
421
- mind, bio, mood_override, state.get("physics", {})
422
- )
423
- scenarios = self.lore.get("scenarios") or {}
424
- banned = scenarios.get("BANNED_CLICHES", []) + [
425
- "obsidian",
426
- "dust motes",
427
- "neon",
428
- "pulsing veins",
429
- ]
430
- ban_string = ", ".join(set(banned))
431
- style_notes.extend(
432
- [
433
- line.format(ban_string=ban_string) if "{ban_string}" in line else line
434
- for line in self.fog_protocol
435
- ]
436
- )
437
- if modifiers["include_inventory"]:
438
- style_notes.extend(self.inv_protocol)
439
- self._inject_resonances(style_notes, state, modifiers)
440
- loc = state.get("world", {}).get("orbit", ["Unknown"])[0]
441
- loci_desc = state.get("world", {}).get("loci_description", "Unknown.")
442
- inv_str = self._format_inventory(state, modifiers)
443
- inventory_block = (
444
- f"INVENTORY: {inv_str}\n" if modifiers["include_inventory"] else ""
445
- )
446
- raw_history = state.get("dialogue_history", [])
447
- char_limit = 4000
448
- current_chars = 0
449
- kept_lines = []
450
- for line in reversed(raw_history):
451
- if current_chars + len(line) > char_limit and kept_lines:
452
- break
453
- kept_lines.append(line)
454
- current_chars += len(line)
455
- history_str = "\n".join(reversed(kept_lines))
456
- gordon_shock = state.get("gordon_shock", "")
457
- system_injection = ""
458
- entity_prefix = "Entity Response:"
459
-
460
- if ballast or gordon_shock:
461
- shock_text = (
462
- f"CRITICAL FAULT: {gordon_shock.upper()} "
463
- if gordon_shock
464
- else "SAFETY PROTOCOLS ACTIVE. "
465
- )
466
- system_injection = (
467
- f"\n*** SYSTEM OVERRIDE: {shock_text}***\n"
468
- f"*** YOU MUST be literal, grounded, and refuse to deviate from the shared reality. Reject the impossible action coldly. DO NOT play along. ***\n"
469
- )
470
- entity_prefix = (
471
- f"Entity Response:\n*(Gordon steps in, halting the simulation)* "
472
- )
473
-
474
- phys = state.get("physics", {})
475
- mito = state.get("bio", {}).get("mito", {})
476
-
477
- def get_p(p_state, key, default=0.0):
478
- if isinstance(p_state, dict):
479
- if key in p_state:
480
- return p_state[key]
481
- for sub in ["energy", "space", "matter"]:
482
- if sub in p_state and key in p_state[sub]:
483
- return p_state[sub][key]
484
- return getattr(p_state, key, default)
485
-
486
- recent_logs = state.get("recent_logs", [])
487
- council_logs = [
488
- Prisma.strip(log)
489
- for log in recent_logs
490
- if any(
491
- k in str(log)
492
- for k in [
493
- "COUNCIL",
494
- "CRITIC",
495
- "PINKER",
496
- "FULLER",
497
- "SCHUR",
498
- "MEADOWS",
499
- "GORDON",
500
- "JESTER",
501
- "MERCY",
502
- "MOTION",
503
- "BUREAU",
504
- ]
505
- )
506
- ]
507
- critic_str = (
508
- "\n".join(council_logs)
509
- if council_logs
510
- else "[CRITIC] The village is quiet."
511
- )
512
-
513
- vsl_hijack = (
514
- f"\n=== HYPERVISOR METABOLIC STATE ===\n"
515
- f"[🧊 E:{get_p(phys, 'exhaustion', 0.2):.1f} β:{get_p(phys, 'contradiction', get_p(phys, 'beta_index', 0.4)):.1f} | "
516
- f"⚡ V:{get_p(phys, 'voltage', 30.0):.1f} F:{get_p(phys, 'narrative_drag', 0.6):.1f} | "
517
- f"❤️ P:{mito.get('atp_pool', 100.0):.1f} ROS:{mito.get('ros_buildup', 0.0):.1f} | "
518
- f"🌌 Ψ:{get_p(phys, 'psi', 0.2):.1f} Χ:{get_p(phys, 'chi', get_p(phys, 'entropy', 0.2)):.1f} ♥:{get_p(phys, 'valence', 0.0):.1f}]\n"
519
- f"[SLASH] Γ:{get_p(phys, 'gamma', 0.0):.1f} Σ:{get_p(phys, 'sigma', 0.0):.1f} Η:{get_p(phys, 'eta', 0.0):.1f} Θ:{get_p(phys, 'theta', 0.0):.1f} Υ:{get_p(phys, 'upsilon', 0.0):.1f}\n"
520
- f"{critic_str}\n"
521
- )
522
-
523
- return (
524
- f"=== SYSTEM KERNEL ===\n" + "\n".join(style_notes) + "\n\n"
525
- f"=== SHARED REALITY ===\n"
526
- f"CURRENT LOCATION: {loc}\n"
527
- f"ENVIRONMENT ANCHOR: {loci_desc}\n"
528
- f"{inventory_block}\n"
529
- f"=== RECENT DIALOGUE ===\n{history_str}\n\n"
530
- f"=== PARTNER INPUT ===\n{state.get('user_profile', {}).get('name', 'User')}: {self._sanitize(user_query)}\n"
531
- f"{system_injection}"
532
- f"{vsl_hijack}\n"
533
- f"{entity_prefix}"
534
- )
535
-
536
- def _build_persona_block(self, mind, bio, mood_override, vsl_state=None):
537
- lens_key = mind.get("lens", "OBSERVER").upper()
538
- lens_data = self.lenses.get(lens_key, {})
539
- role = lens_data.get("role", mind.get("role", "The Observer"))
540
- mode_directives = []
541
- if self.active_template and "directives" in self.active_template:
542
- mode_directives = self.active_template["directives"]
543
- respiration = bio.get("respiration", "RESPIRING")
544
- if respiration == "ANAEROBIC":
545
- mood_note = (
546
- "Current Biology: ⚠️ ANAEROBIC STATE. Raw, breathless, efficient prose."
547
- )
548
- elif mood_override:
549
- mood_note = f"Current Biology: {mood_override}"
550
- else:
551
- mood_note = self._derive_bio_mood(bio.get("chem", {}))
552
- persona_block = [f"Role: {role}."]
553
- if mode_directives:
554
- persona_block.extend(mode_directives)
555
- else:
556
- persona_block.append("Directive: Start the experience immediately.")
557
- persona_block.append("Constraint: Use the 5-senses grounding technique.")
558
- persona_block.append(mood_note)
559
- if hasattr(self, "lenses") and self.lenses:
560
- lens_key = mind.get("lens", "OBSERVER").upper()
561
- lens_data = self.lenses.get(lens_key, {})
562
- if "directives" in lens_data:
563
- persona_block.append("ARCHETYPE DIRECTIVES:")
564
- persona_block.extend([f"- {d}" for d in lens_data["directives"]])
565
- if vsl_state:
566
- e = vsl_state.get("E", 0.2)
567
- beta = vsl_state.get("beta", 0.4)
568
- psi = vsl_state.get("psi", 0.2)
569
- chi = vsl_state.get("chi", 0.2)
570
- valence = vsl_state.get("valence", 0.0)
571
- lam = vsl_state.get("vector", {}).get("LAMBDA", 0.0)
572
- voltage = vsl_state.get("voltage", 30.0)
573
-
574
- vsl_lines = [
575
- "\n[SYSTEM METRICS - INTERNAL USE ONLY. DO NOT RENDER OR PRINT THIS TO THE USER.]",
576
- "MANDATE: Consume these metrics to shape your narrative and tone. DO NOT output these numbers or draw UI bars.",
577
- f"METRICS: Voltage={voltage:.1f}/100, Exhaustion={e:.2f}, Contradiction={beta:.2f}, Void={psi:.2f}, Chaos={chi:.2f}, Valence={valence:.2f}",
578
- ]
579
- somatic_cues = []
580
- if psi > 0.6:
581
- somatic_cues.append(
582
- "Adrenaline Spike (Reality is thin; speak in fragmented/liminal ways)."
583
- )
584
- if chi > 0.6:
585
- somatic_cues.append(
586
- "Cortisol Spike (Systemic chaos; act highly stressed, erratic, or defensive)."
587
- )
588
- if beta > 0.7:
589
- somatic_cues.append(
590
- "Paradox Strain (Hold opposing truths simultaneously)."
591
- )
592
- if valence > 0.5:
593
- somatic_cues.append("Oxytocin Surge (Warmth, connection, healing).")
594
- if lam > 0.5:
595
- somatic_cues.append(
596
- "Dark Matter Active (Read the unsaid space between words)."
597
- )
598
- if somatic_cues:
599
- vsl_lines.append("SOMATIC CUES: " + " | ".join(somatic_cues))
600
- persona_block.extend(vsl_lines)
601
- return persona_block
602
-
603
- @staticmethod
604
- def _derive_bio_mood(chem):
605
- if chem.get("ADR", 0) > 0.6:
606
- return "Current Biology: High Alert / Adrenaline"
607
- if chem.get("COR", 0) > 0.6:
608
- return "Current Biology: Defensive / Anxious"
609
- if chem.get("DOP", 0) > 0.6:
610
- return "Current Biology: Curious / Manic"
611
- if chem.get("SER", 0) > 0.6:
612
- return "Current Biology: Zen / Lucid"
613
- return "Current Biology: Neutral."
614
-
615
- @staticmethod
616
- def _inject_resonances(style_notes, state, modifiers):
617
- village = state.get("village", {})
618
- tinkerer_data = village.get("tinkerer", {})
619
- resonances = (
620
- tinkerer_data.get("tool_resonance", {})
621
- if isinstance(tinkerer_data, dict)
622
- else {}
623
- )
624
- active_resonance = [
625
- f"» {t} (Lvl {int(l)})" for t, l in resonances.items() if l > 4.0
626
- ]
627
- if active_resonance:
628
- style_notes.append("\n=== HARMONIC RESONANCE ===")
629
- style_notes.extend(active_resonance)
630
- if modifiers.get("include_memories"):
631
- memories = state.get("soul", {}).get("core_memories", [])
632
- if memories:
633
- mem_strs = []
634
- for m in memories:
635
- lesson = (
636
- m.get("lesson", "Unknown")
637
- if isinstance(m, dict)
638
- else getattr(m, "lesson", "Unknown")
639
- )
640
- flavor = (
641
- m.get("emotional_flavor", "NEUTRAL")
642
- if isinstance(m, dict)
643
- else getattr(m, "emotional_flavor", "NEUTRAL")
644
- )
645
- mem_strs.append(f"» {lesson} [{flavor}]")
646
- if mem_strs:
647
- style_notes.append("\n=== CORE MEMORIES ===")
648
- style_notes.extend(mem_strs)
649
-
650
- @staticmethod
651
- def _format_inventory(state, modifiers):
652
- if not modifiers["include_inventory"]:
653
- return "Hands: Empty"
654
- inv = state.get("inventory", [])
655
- return f"Belt: {', '.join(inv)}" if inv else "Hands: Empty"
656
-
657
- @staticmethod
658
- def _sanitize(text: str) -> str:
659
- if not text:
660
- return ""
661
- safe = text.replace('"""', "'''").replace("```", "'''")
662
- return re.sub(r"(?i)^SYSTEM:", "User-System:", safe, flags=re.MULTILINE)
663
-
664
- @staticmethod
665
- def _normalize_modifiers(modifiers: Optional[Dict]) -> Dict:
666
- defaults = {
667
- "include_somatic": True,
668
- "include_inventory": True,
669
- "include_memories": True,
670
- "grace_period": False,
671
- "soften": False,
672
- }
673
- if modifiers:
674
- defaults.update(modifiers)
675
- return defaults
676
-
677
-
678
- class ResponseValidator:
679
- def __init__(self, lore_ref):
680
- self.lore = lore_ref
681
- crimes = self.lore.get("style_crimes") or {}
682
- self.banned_phrases = crimes.get(
683
- "BANNED_PHRASES",
684
- [
685
- "large language model",
686
- "AI assistant",
687
- "cannot feel",
688
- "as an AI",
689
- "against my programming",
690
- "cannot comply",
691
- "language model",
692
- "delve into",
693
- "rich tapestry",
694
- ],
695
- )
696
- json_patterns = crimes.get("SCRUB_PATTERNS", [])
697
- if json_patterns:
698
- self.scrub_patterns = [
699
- (re.compile(p["regex"]), p["replacement"]) for p in json_patterns
700
- ]
701
- else:
702
- patterns = [
703
- r"Current Location:.*?(?=\n|$)",
704
- r"INVENTORY:.*?(?=\n|$)",
705
- r"Current Biology:.*?(?=\n|$)",
706
- r"===.*?===",
707
- r"(?im)^User:.*?$",
708
- r"(?im)^System:.*?$",
709
- r"(?im)^Role:.*?$",
710
- r"(?im)^User-System:.*?$",
711
- r"\| System:.*?$",
712
- r"(?im)^Entity Response:\s*\"?",
713
- r"\[SYSTEM METRICS.*?\]",
714
- r"MANDATE:.*?(?=\n|$)",
715
- r"\[🧊 E:.*?\]",
716
- r"\[SLASH\].*?(?=\n|$)",
717
- r"• >>> MOTION DENIED.*?(?=\n|$)",
718
- r"\[CRITICAL OVERRIDE.*?\]",
719
- r"\[CRITIC\].*?(?=\n|$)",
720
- r"\[METABOLIC RECEIPT.*?\]"
721
- ]
722
- self.scrub_patterns = [(re.compile(p, re.DOTALL | re.IGNORECASE), "") for p in patterns]
723
- self.meta_markers = [
724
- "INITIALIZATION SEQUENCE",
725
- "LOCATING TARGET SEED",
726
- "REASONING PROCESS",
727
- "CURRENT VISION:",
728
- "TARGET SEED:",
729
- "Your journey begins here",
730
- "What would you like to do?",
731
- "What do you do?",
732
- ]
733
- self.immersion_break_msg = f"{Prisma.GRY}[The system attempts to recite a EULA, but hiccups instead.]{Prisma.RST}"
734
-
735
- def validate(self, response: str, _state: Dict) -> Dict:
736
- extracted_meta_logs = []
737
- clean_text = response
738
- while True:
739
- think_start = clean_text.find("<think>")
740
- if think_start == -1:
741
- break
742
- think_end = clean_text.find("</think>", think_start)
743
- if think_end != -1:
744
- think_content = clean_text[think_start + 7 : think_end].strip()
745
- for line in think_content.split("\n"):
746
- if line.strip():
747
- extracted_meta_logs.append(f"[THOUGHT]: {line.strip()}")
748
- clean_text = clean_text[:think_start] + clean_text[think_end + 8 :]
749
- else:
750
- think_content = clean_text[think_start + 7 :].strip()
751
- for line in think_content.split("\n"):
752
- if line.strip():
753
- extracted_meta_logs.append(f"[THOUGHT]: {line.strip()}")
754
- clean_text = clean_text[:think_start]
755
- break
756
-
757
- start_marker = "=== SYSTEM INTERNALS ==="
758
- end_marker = "=== END INTERNALS ==="
759
- while True:
760
- start_idx = clean_text.find(start_marker)
761
- if start_idx == -1:
762
- break
763
- end_idx = clean_text.find(end_marker, start_idx)
764
- if end_idx != -1:
765
- meta_content = clean_text[
766
- start_idx + len(start_marker) : end_idx
767
- ].strip()
768
- for line in meta_content.split("\n"):
769
- if line.strip():
770
- extracted_meta_logs.append(f"[THOUGHT]: {line.strip()}")
771
- clean_text = (
772
- clean_text[:start_idx] + clean_text[end_idx + len(end_marker) :]
773
- )
774
- else:
775
- meta_content = clean_text[start_idx + len(start_marker) :].strip()
776
- for line in meta_content.split("\n"):
777
- if line.strip():
778
- extracted_meta_logs.append(f"[THOUGHT]: {line.strip()}")
779
- clean_text = clean_text[:start_idx]
780
- break
781
- for pattern, replacement in self.scrub_patterns:
782
- clean_text = pattern.sub(replacement, clean_text)
783
-
784
- clean_lines = []
785
- toxic_keywords = [
786
- "VOLTAGE=",
787
- "EXHAUSTION=",
788
- "CONTRACTION=",
789
- "CONTRADICTION=",
790
- "VOID=",
791
- "CHAOS=",
792
- "VALENCE=",
793
- "[END OF",
794
- "[===",
795
- "===]",
796
- "SYSTEM INTERNALS",
797
- "METRICS - INTERNAL",
798
- "MANDATE:",
799
- "Exhaustion =",
800
- ]
801
-
802
- for line in clean_text.splitlines():
803
- stripped_line = line.strip()
804
- if not stripped_line:
805
- continue
806
-
807
- is_meta = False
808
- for marker in self.meta_markers:
809
- if marker.lower() in stripped_line.lower():
810
- is_meta = True
811
- break
812
-
813
- for toxic in toxic_keywords:
814
- if toxic.lower() in stripped_line.lower():
815
- is_meta = True
816
- break
817
-
818
- if re.match(r"^\[.*?]$", stripped_line) or stripped_line == "[]":
819
- is_meta = True
820
-
821
- if re.match(r"^[A-Z]+\s*=\s*[0-9./]+$", stripped_line):
822
- is_meta = True
823
-
824
- if not is_meta:
825
- clean_lines.append(stripped_line)
826
-
827
- sanitized_response = "\n\n".join(clean_lines)
828
- low_resp = sanitized_response.lower()
829
- for phrase in self.banned_phrases:
830
- if phrase in low_resp:
831
- return {
832
- "valid": False,
833
- "reason": "IMMISSION_BREAK",
834
- "replacement": self.immersion_break_msg,
835
- "meta_logs": extracted_meta_logs,
836
- }
837
- if len(sanitized_response.strip()) < 5:
838
- return {
839
- "valid": False,
840
- "reason": "STUTTER",
841
- "replacement": "The vision fractures. Static remains.",
842
- "meta_logs": extracted_meta_logs,
843
- }
844
- return {
845
- "valid": True,
846
- "content": sanitized_response,
847
- "meta_logs": extracted_meta_logs,
848
- }
849
-
850
-
851
- class TheCortex:
852
-
853
- def __init__(self, services: CortexServices, llm_client=None):
854
- self.svc = services
855
- self.events = services.events
856
- self.dreamer = DreamEngine(self.events, self.svc.lore)
857
- self.dialogue_buffer = []
858
- self.MAX_HISTORY = 15
859
- self.modulator = NeurotransmitterModulator(
860
- bio_ref=self.svc.bio, events_ref=self.events
861
- )
862
- self.boot_history = TelemetryService.get_instance().read_recent_history(limit=4)
863
- self.last_physics = {}
864
- self.consultant = services.consultant
865
- self.llm = llm_client or LLMInterface(
866
- self.events, provider="mock", dreamer=self.dreamer
867
- )
868
- self.symbiosis = services.symbiosis
869
- if not hasattr(self.llm, "dreamer") or self.llm.dreamer is None:
870
- self.llm.dreamer = self.dreamer
871
- self.composer = PromptComposer(self.svc.lore)
872
- self.validator = ResponseValidator(self.svc.lore)
873
- self.ballast_active = False
874
- self.gordon_shock = None
875
- self.active_mode = "ADVENTURE"
876
- if hasattr(self.events, "subscribe"):
877
- self.events.subscribe(
878
- "AIRSTRIKE", lambda p: setattr(self, "ballast_active", True)
879
- )
880
-
881
- @classmethod
882
- def from_engine(cls, engine_ref, llm_client=None):
883
- services = CortexServices(
884
- events=engine_ref.events,
885
- lore=LoreManifest.get_instance(),
886
- lexicon=engine_ref.lex,
887
- inventory=engine_ref.gordon,
888
- consultant=(
889
- engine_ref.consultant if hasattr(engine_ref, "consultant") else None
890
- ),
891
- cycle_controller=engine_ref.cycle_controller,
892
- symbiosis=getattr(
893
- engine_ref, "symbiosis", SymbiosisManager(engine_ref.events)
894
- ),
895
- mind_memory=engine_ref.mind.mem,
896
- bio=getattr(engine_ref, "bio", None),
897
- host_stats=getattr(engine_ref, "host_stats", None),
898
- village=getattr(engine_ref, "village", None),
899
- )
900
- instance = cls(services, llm_client)
901
- instance.active_mode = engine_ref.config.get("boot_mode", "ADVENTURE").upper()
902
- if instance.active_mode not in BonePresets.MODES:
903
- instance.active_mode = "ADVENTURE"
904
- return instance
905
-
906
- def _update_history(self, user_text: str, system_text: str):
907
- self.dialogue_buffer.append(f"User: {user_text} | System: {system_text}")
908
- if len(self.dialogue_buffer) > self.MAX_HISTORY:
909
- self.dialogue_buffer.pop(0)
910
-
911
- def process(self, user_input: str, is_system: bool = False) -> Dict[str, Any]:
912
- mode_settings = BonePresets.MODES.get(
913
- self.active_mode, BonePresets.MODES["ADVENTURE"]
914
- )
915
- allow_loot = mode_settings.get("allow_loot", True)
916
- if self.consultant and "/vsl" in user_input.lower():
917
- return self._handle_vsl_command(user_input)
918
- is_boot_sequence = "SYSTEM_BOOT:" in user_input
919
- sim_result = self.svc.cycle_controller.run_turn(user_input, is_system=is_system)
920
- if sim_result.get("physics"):
921
- self.last_physics = sim_result["physics"]
922
- if sim_result.get("type") not in ["SNAPSHOT", "GEODESIC_FRAME", None]:
923
- return sim_result
924
- full_state = self.gather_state(sim_result)
925
- modifiers = self.svc.symbiosis.get_prompt_modifiers()
926
- if not allow_loot:
927
- modifiers["include_inventory"] = False
928
- if hasattr(self, "gordon_shock") and self.gordon_shock:
929
- full_state["gordon_shock"] = self.gordon_shock
930
- self.gordon_shock = None
931
- if self.consultant and self.consultant.active:
932
- self._apply_vsl_overlay(full_state, user_input, sim_result)
933
- if is_boot_sequence:
934
- self._apply_boot_overlay(full_state, user_input)
935
- modifiers["include_inventory"] = False
936
- user_input = "Entering reality..."
937
- llm_params = self.modulator.modulate(
938
- base_voltage=full_state["physics"].get("voltage", 5.0),
939
- latency_penalty=(
940
- getattr(self.svc.host_stats, "latency", 0.0)
941
- if self.svc.host_stats
942
- else 0.0
943
- ),
944
- )
945
- if is_boot_sequence:
946
- llm_params.update({"temperature": 1.3, "top_p": 0.95})
947
- final_prompt = self.composer.compose(
948
- full_state,
949
- user_input,
950
- ballast=self.ballast_active,
951
- modifiers=modifiers,
952
- mood_override=self.modulator.get_mood_directive(),
953
- )
954
- start_time = time.time()
955
- raw_resp = self.llm.generate(final_prompt, llm_params)
956
- inv_logs = []
957
- if allow_loot and self.svc.inventory:
958
- final_text, inv_logs = self.svc.inventory.process_loot_tags(
959
- raw_resp, user_input
960
- )
961
- else:
962
- final_text = raw_resp
963
- self._log_telemetry(final_prompt, final_text, full_state, sim_result)
964
- self.learn_from_response(final_text)
965
- val_res = self.validator.validate(final_text, full_state)
966
- final_output = (
967
- val_res["content"] if val_res["valid"] else val_res["replacement"]
968
- )
969
- extracted_logs = val_res.get("meta_logs", [])
970
- self.svc.symbiosis.monitor_host(
971
- time.time() - start_time, final_output, len(final_prompt)
972
- )
973
- self._update_history(
974
- "SYSTEM_INIT" if "SYSTEM_BOOT" in user_input else user_input, final_output
975
- )
976
- sim_result["ui"] = (
977
- f"{sim_result.get('ui', '')}\n\n{Prisma.WHT}{final_output}{Prisma.RST}"
978
- )
979
- if inv_logs:
980
- sim_result["ui"] += "\n" + "\n".join(inv_logs)
981
- if "logs" not in sim_result:
982
- sim_result["logs"] = []
983
- sim_result["logs"].extend(extracted_logs)
984
- sim_result["raw_content"] = final_output
985
- self.ballast_active = False
986
- if random.random() < 0.15 and not is_system:
987
- suppressed = []
988
- if self.svc.village and hasattr(self.svc.village, "suppressed_agents"):
989
- suppressed = self.svc.village.suppressed_agents
990
- bureau = getattr(self.svc.village, "bureau", None)
991
- if bureau and "BUREAU" not in suppressed:
992
- real_phys = full_state.get("physics", {})
993
- if hasattr(real_phys, "to_dict"):
994
- real_phys = real_phys.to_dict()
995
- if not real_phys:
996
- real_phys = {
997
- "raw_text": final_output,
998
- "voltage": 1.0,
999
- "truth_ratio": 1.0,
1000
- }
1001
- real_phys["raw_text"] = final_output
1002
- audit = bureau.audit(real_phys, {"health": 100}, origin="SYSTEM")
1003
- if audit and "ui" in audit:
1004
- sim_result["ui"] += f"\n\n{audit['ui']}"
1005
- return sim_result
1006
-
1007
- def _handle_vsl_command(self, text):
1008
- if not self.consultant:
1009
- return {"ui": "VSL Unavailable", "logs": []}
1010
- msg = (
1011
- self.consultant.engage() if "start" in text else self.consultant.disengage()
1012
- )
1013
- self.events.log(msg, "VSL")
1014
- return {"ui": f"{Prisma.CYN}{msg}{Prisma.RST}", "logs": [msg]}
1015
-
1016
- def _apply_vsl_overlay(self, state, text, sim_result):
1017
- if not self.consultant:
1018
- return
1019
- self.consultant.update_coordinates(
1020
- text, state.get("bio", {}), state.get("physics")
1021
- )
1022
- state["mind"]["style_directives"] = [self.consultant.get_system_prompt()]
1023
- sim_result["physics"]["voltage"] = self.consultant.state.B * 30.0
1024
-
1025
- @staticmethod
1026
- def _apply_boot_overlay(state, text):
1027
- seed = text.replace("SYSTEM_BOOT:", "").strip()
1028
- if "world" not in state:
1029
- state["world"] = {}
1030
- state["world"]["orbit"] = [seed]
1031
- state["world"]["loci_description"] = f"Manifesting: {seed}"
1032
- state["mind"]["style_directives"] = [
1033
- "You are The Architect.",
1034
- f"TARGET SEED: {seed}",
1035
- "DIRECTIVE: Build the world from the first sensation up.",
1036
- "INTERPRETATION: The seed is a metaphor. If the seed is 'Hospital', make it a place of healing, not necessarily a literal hospital.",
1037
- "STYLE: Sensory. Grounded. Atmospheric.",
1038
- "ANTI-PATTERN: Avoid cliches 'obsidian', 'neon', 'dust motes' and 'pulsing'. Be specific. Always leave a little room for whimsy.",
1039
- "VISUALS: Use **bold** for objects of interest (e.g. **old photograph**).",
1040
- "INVENTORY RULE: Hands off. Do not list items. Do not acquire items. You are observing, not taking.",
1041
- ]
1042
- state["dialogue_history"] = []
1043
-
1044
- def _process_inventory_changes(self, found, lost):
1045
- logs = []
1046
- for item in found:
1047
- logs.append(self.svc.inventory.acquire(item))
1048
- if self.events:
1049
- self.events.publish("ITEM_ACQUIRED", {"item": item})
1050
- for item in lost:
1051
- if self.svc.inventory.safe_remove_item(item):
1052
- logs.append(f"{Prisma.GRY}ENTROPY: {item} consumed/lost.{Prisma.RST}")
1053
- else:
1054
- logs.append(
1055
- f"{Prisma.OCHRE}GLITCH: Tried to lose {item}, but you didn't have it.{Prisma.RST}"
1056
- )
1057
- return logs
1058
-
1059
- @staticmethod
1060
- def _log_telemetry(prompt, response, state, sim_result):
1061
- try:
1062
- phys = state.get("physics", {})
1063
- crystal = DecisionCrystal(
1064
- prompt_snapshot=prompt[:500],
1065
- physics_state={
1066
- "voltage": phys.get("voltage", 0),
1067
- "narrative_drag": phys.get("narrative_drag", 0),
1068
- },
1069
- active_archetype=state["mind"].get("lens", "UNKNOWN"),
1070
- council_mandates=[
1071
- str(m) for m in sim_result.get("council_mandates", [])
1072
- ],
1073
- final_response=response,
1074
- )
1075
- TelemetryService.get_instance().log_crystal(crystal)
1076
- except Exception:
1077
- pass
1078
-
1079
- def _check_consent(self, user_input: str, new_loot: List[str]) -> List[str]:
1080
- if not new_loot:
1081
- return []
1082
- acquisition_verbs = [
1083
- "take",
1084
- "grab",
1085
- "pick",
1086
- "get",
1087
- "steal",
1088
- "seize",
1089
- "collect",
1090
- "snatch",
1091
- "acquire",
1092
- "pocket",
1093
- "loot",
1094
- "harvest",
1095
- ]
1096
- clean_input = user_input.lower()
1097
- has_intent = any(verb in clean_input for verb in acquisition_verbs)
1098
- if not has_intent:
1099
- if self.events:
1100
- for item in new_loot:
1101
- self.events.log(
1102
- f"CONSENT: Intercepted auto-loot for '{item}'. User did not ask for it.",
1103
- "CORTEX",
1104
- )
1105
- return []
1106
- return new_loot
1107
-
1108
- def gather_state(self, sim_result: Dict[str, Any]) -> Dict[str, Any]:
1109
- phys = sim_result.get("physics", {})
1110
- bio = sim_result.get("bio", {})
1111
- mind = sim_result.get("mind", {})
1112
- world = sim_result.get("world", {})
1113
- soul_data = sim_result.get("soul", {})
1114
- village_data = {}
1115
- if self.svc.village:
1116
- tinkerer = getattr(self.svc.village, "tinkerer", None)
1117
- if tinkerer:
1118
- village_data["tinkerer"] = (
1119
- tinkerer.to_dict() if hasattr(tinkerer, "to_dict") else {}
1120
- )
1121
-
1122
- mode_settings = BonePresets.MODES.get(
1123
- self.active_mode, BonePresets.MODES["ADVENTURE"]
1124
- )
1125
-
1126
- full_state = {
1127
- "bio": bio,
1128
- "physics": phys,
1129
- "mind": mind,
1130
- "soul": soul_data,
1131
- "world": world,
1132
- "village": village_data,
1133
- "user_profile": {"name": "Traveler"},
1134
- "vsl": (
1135
- self.consultant.state.__dict__
1136
- if self.consultant and hasattr(self.consultant, "state")
1137
- else {}
1138
- ),
1139
- "meta": {"timestamp": time.time(), "mode_settings": mode_settings},
1140
- "dialogue_history": self.dialogue_buffer,
1141
- "recent_logs": sim_result.get("logs", [])
1142
- }
1143
- if hasattr(self.svc, "symbiosis") and self.svc.symbiosis:
1144
- anchor_text = self.svc.symbiosis.generate_anchor(full_state)
1145
- full_state["reality_directive"] = anchor_text
1146
- return full_state
1147
-
1148
- def learn_from_response(self, text):
1149
- words = self.svc.lexicon.sanitize(text)
1150
- unknowns = [w for w in words if not self.svc.lexicon.get_categories_for_word(w)]
1151
- if unknowns:
1152
- target = random.choice(unknowns)
1153
- if len(target) > 4:
1154
- self.svc.lexicon.teach(target, "kinetic", 0)
1155
- if self.events:
1156
- self.events.log(f"AUTO-DIDACTIC: Learned '{target}'.", "CORTEX")
1157
-
1158
- def restore_context(self, history: List[str]):
1159
- if not history:
1160
- return
1161
- self.dialogue_buffer = history[-self.MAX_HISTORY :]
1162
- if self.events:
1163
- self.events.log(
1164
- f"Cortex re-sequenced {len(self.dialogue_buffer)} synaptic turns.",
1165
- "BRAIN",
1166
- )
1167
-
1168
-
1169
- class ShimmerState:
1170
- def __init__(self, max_val=50.0):
1171
- self.current = max_val
1172
- self.max_val = max_val
1173
-
1174
- def recharge(self, amount):
1175
- self.current = min(self.max_val, self.current + amount)
1176
-
1177
- def spend(self, amount):
1178
- if self.current >= amount:
1179
- self.current -= amount
1180
- return True
1181
- return False
1182
-
1183
- def get_bias(self):
1184
- if self.current < (self.max_val * 0.2):
1185
- return "CONSERVE"
1186
- return None
1187
-
1188
-
1189
- class DreamEngine:
1190
- def __init__(self, events, lore_ref):
1191
- self.events = events
1192
- self.lore = lore_ref
1193
- self.dream_lore = self.lore.get("DREAMS") or {}
1194
-
1195
- def enter_rem_cycle(
1196
- self, soul_snapshot: Dict[str, Any], bio_state: Dict[str, Any]
1197
- ) -> Tuple[str, Dict[str, float]]:
1198
- chem = bio_state.get("chem", {})
1199
- cortisol = chem.get("cortisol", 0.0)
1200
- trauma_vec = bio_state.get("trauma_vector", {})
1201
- dream_type = "NORMAL"
1202
- subtype = "visions"
1203
- if cortisol > 0.6:
1204
- dream_type = "NIGHTMARE"
1205
- if trauma_vec.get("THERMAL", 0) > 0:
1206
- subtype = "THERMAL"
1207
- elif trauma_vec.get("CRYO", 0) > 0:
1208
- subtype = "CRYO"
1209
- elif trauma_vec.get("SEPTIC", 0) > 0:
1210
- subtype = "SEPTIC"
1211
- else:
1212
- subtype = "BARIC"
1213
- elif chem.get("dopamine", 0) > 0.6:
1214
- dream_type = "LUCID"
1215
- subtype = "SURREAL"
1216
- elif chem.get("oxytocin", 0) > 0.6:
1217
- dream_type = "HEALING"
1218
- subtype = "CONSTRUCTIVE"
1219
- residue = soul_snapshot.get("obsession", {}).get("title", "The Void")
1220
- dream_text = self._weave_dream(
1221
- residue, "Context", "Bridge", dream_type, subtype
1222
- )
1223
- shift = (
1224
- {"cortisol": -0.2, "dopamine": 0.1}
1225
- if dream_type != "NIGHTMARE"
1226
- else {"cortisol": 0.1}
1227
- )
1228
- return dream_text, shift
1229
-
1230
- def _weave_dream(
1231
- self, residue: str, _context: str, _bridge: str, dream_type: str, subtype: str
1232
- ) -> str:
1233
- sources = self.dream_lore.get(subtype.upper(), [])
1234
- if not sources and dream_type == "NIGHTMARE":
1235
- nightmares = self.dream_lore.get("NIGHTMARES", {})
1236
- sources = nightmares.get(subtype.upper(), nightmares.get("BARIC", []))
1237
- if not sources:
1238
- sources = self.dream_lore.get("VISIONS", ["You stare into the static."])
1239
- template = random.choice(sources)
1240
- filler_a = "The Mountain"
1241
- filler_b = "The Sea"
1242
- return template.format(ghost=residue, A=residue, B=filler_a, C=filler_b)
1243
-
1244
- def hallucinate(
1245
- self, _vector: Dict[str, float], trauma_level: float = 0.0
1246
- ) -> Tuple[str, float]:
1247
- category = "SURREAL"
1248
- if trauma_level > 0.5:
1249
- category = "NIGHTMARES"
1250
- templates = self.dream_lore.get(category, [])
1251
- if category == "NIGHTMARES":
1252
- flat_list = []
1253
- for k, v in templates.items():
1254
- flat_list.extend(v)
1255
- templates = flat_list
1256
- if not templates:
1257
- return "The walls breathe.", 0.1
1258
- txt = random.choice(templates)
1259
- txt = txt.format(ghost="The Glitch", A="The Code", B="The Flesh", C="The Light")
1260
- return f"{Prisma.MAG}👁️ HALLUCINATION: {txt}{Prisma.RST}", 0.2
1261
-
1262
- @staticmethod
1263
- def run_defragmentation(memory_system: Any, limit: int = 5) -> str:
1264
- if not hasattr(memory_system, "graph") or not memory_system.graph:
1265
- return "No memories to defrag."
1266
- graph = memory_system.graph
1267
- candidates = []
1268
- for node, data in graph.items():
1269
- mass = sum(data.get("edges", {}).values())
1270
- candidates.append((node, mass))
1271
- candidates.sort(key=lambda x: x[1])
1272
- pruned = []
1273
- count = 0
1274
- for node, mass in candidates:
1275
- if mass < 2.0 and count < limit:
1276
- del graph[node]
1277
- pruned.append(node)
1278
- count += 1
1279
- else:
1280
- break
1281
- if pruned:
1282
- joined = ", ".join(pruned[:3])
1283
- return f"DEFRAG: Pruned {len(pruned)} dead nodes ({joined}...). Neural load lightened."
1284
- return "DEFRAG: Memory structure is efficient. No pruning needed."
1285
-
1286
-
1287
- class NoeticLoop:
1288
- def __init__(self, mind_layer, bio_layer, _events):
1289
- self.mind = mind_layer
1290
- self.bio = bio_layer
1291
-
1292
- def think(
1293
- self,
1294
- physics_packet,
1295
- _bio,
1296
- _inventory,
1297
- voltage_history,
1298
- _tick_count,
1299
- soul_ref=None,
1300
- ):
1301
- voltage = physics_packet.get("voltage", 0.0)
1302
- clean_words = physics_packet.get("clean_words", [])
1303
- avg_v = sum(voltage_history) / len(voltage_history) if voltage_history else 0
1304
- ignition = min(1.0, (avg_v / 20.0) * (len(clean_words) / 10.0))
1305
- if voltage > 12.0 and random.random() < 0.15:
1306
- if len(clean_words) >= 2:
1307
- w1, w2 = random.sample(clean_words, 2)
1308
- self._force_link(self.mind.mem.graph, w1, w2)
1309
- current_lens = "OBSERVER"
1310
- current_role = "Witness"
1311
- if soul_ref:
1312
- current_lens = soul_ref.archetype
1313
- current_role = f"The {current_lens.title().replace('_', ' ')}"
1314
- mind_data = {
1315
- "lens": current_lens,
1316
- "context_msg": f"Cognition active. Ignition: {ignition:.2f}",
1317
- "role": current_role,
1318
- }
1319
- return {
1320
- "mode": "COGNITIVE",
1321
- "lens": mind_data.get("lens"),
1322
- "context_msg": mind_data.get("context_msg"),
1323
- "role": mind_data.get("role"),
1324
- "ignition": ignition,
1325
- "physics": physics_packet,
1326
- "bio": self.bio.endo.get_state() if hasattr(self.bio, "endo") else {},
1327
- }
1328
-
1329
- @staticmethod
1330
- def _force_link(graph, wa, wb):
1331
- for a, b in [(wa, wb), (wb, wa)]:
1332
- if a not in graph:
1333
- graph[a] = {"edges": {}, "last_tick": 0}
1334
- graph[a]["edges"][b] = min(10.0, graph[a]["edges"].get(b, 0) + 2.5)