aedmark commited on
Commit
4a90225
·
verified ·
1 Parent(s): aab07d0

Delete bone_diag.py

Browse files
Files changed (1) hide show
  1. bone_diag.py +0 -2048
bone_diag.py DELETED
@@ -1,2048 +0,0 @@
1
- """bone_diag.py - BoneAmanita Master Test Suite - "Trust, but verify. Then verify the verification." """
2
- import io
3
- import os
4
- import random
5
- import time
6
- import unittest
7
- import urllib
8
- from dataclasses import dataclass
9
- from typing import List, Tuple, Optional, Dict
10
- from unittest.mock import MagicMock, patch
11
-
12
- from bone_akashic import TheAkashicRecord
13
- from bone_body import (
14
- SemanticEndocrinologist,
15
- EndocrineSystem,
16
- SemanticSignal,
17
- MitochondrialState,
18
- MitochondrialForge,
19
- )
20
- from bone_brain import LLMInterface, DreamEngine, ResponseValidator, SynapseError
21
- from bone_brain import NeurotransmitterModulator
22
- from bone_config import BoneConfig
23
- from bone_core import EventBus, Prisma, LoreManifest
24
- from bone_cycle import SoulPhase, GatekeeperPhase, NavigationPhase, MetabolismPhase
25
- from bone_drivers import EnneagramDriver, SoulDriver, LiminalModule, SyntaxModule
26
- from bone_gui import GeodesicRenderer
27
- from bone_inventory import GordonKnot, Item
28
- from bone_lexicon import LexiconStore, LinguisticAnalyzer, SemanticField
29
- from bone_machine import TheCrucible, TheTheremin, PanicRoom, ThePacemaker, TheForge
30
- from bone_main import BoneAmanita
31
- from bone_physics import (
32
- GeodesicEngine,
33
- GeodesicConstants,
34
- CycleStabilizer,
35
- ZoneInertia,
36
- TRIGRAM_MAP,
37
- )
38
- from bone_protocols import ZenGarden, TheBureau, TheFolly, KintsugiProtocol, LimboLayer
39
- from bone_soul import TraitVector, HumanityAnchor, NarrativeSelf, TheOroboros
40
- from bone_spores import ImmuneMycelium, BioLichen, BioParasite, MemoryCore
41
- from bone_symbiosis import SymbiosisManager
42
- from bone_types import PhysicsPacket
43
- from bone_village import TheTinkerer, TheCartographer, MirrorGraph, DeathGen, TownHall
44
-
45
-
46
- @dataclass
47
- class MockLexicon:
48
- @staticmethod
49
- def sanitize(text: str) -> List[str]:
50
- return text.split()
51
-
52
- @staticmethod
53
- def classify(word: str) -> Tuple[Optional[str], float]:
54
- if word in ["void", "chaos"]:
55
- return "abstract", 0.9
56
- return "neutral", 0.1
57
-
58
- @staticmethod
59
- def get_random(_cat: str) -> str:
60
- return "test_word"
61
-
62
- @staticmethod
63
- def measure_viscosity(word: str) -> float:
64
- return 0.8 if word == "void" else 0.2
65
-
66
-
67
- @dataclass
68
- class MockAkashic:
69
-
70
- @staticmethod
71
- def calculate_manifold_shift(_archetype: str, _traits: Dict) -> Dict:
72
- return {"shift": 0.5}
73
-
74
- @staticmethod
75
- def forge_new_item(_vector: Dict) -> Tuple[str, Dict]:
76
- return "QUANTUM_SPHERE", {
77
- "description": "A dense ball of mock data.",
78
- "passive_traits": ["HEAVY"],
79
- }
80
-
81
-
82
- class MockLore:
83
- @staticmethod
84
- def get_lenses():
85
- return {
86
- "JESTER": {
87
- "role": "The Paradox",
88
- "directives": ["Break the fourth wall.", "Celebrate entropy."],
89
- }
90
- }
91
-
92
- @staticmethod
93
- def get_item_gen():
94
- return {
95
- "PREFIXES": {"kinetic": ["Fast"], "heavy": ["Heavy"]},
96
- "BASES": {"TOOL": ["Wrench"], "ARTIFACT": ["Orb"]},
97
- "SUFFIXES": {"kinetic": ["of Speed"], "heavy": ["of Weight"]},
98
- }
99
-
100
-
101
- class MockGovernor:
102
- def recalibrate(self, _v, _d):
103
- pass
104
-
105
- @staticmethod
106
- def regulate(_p, _dt):
107
- return 0.0, 0.0
108
-
109
-
110
- class TestBed:
111
- @staticmethod
112
- def create_physics(voltage=10.0, drag=1.0, psi=0.0, kappa=1.0):
113
- class DynPhys:
114
- def __init__(self, v, d, p, k):
115
- self.voltage = v
116
- self.narrative_drag = d
117
- self.psi = p
118
- self.kappa = k
119
- self.vector = {}
120
- self.flow_state = "STANDARD"
121
- self.zone = "TEST_ZONE"
122
-
123
- def to_dict(self):
124
- return {
125
- "voltage": self.voltage,
126
- "narrative_drag": self.narrative_drag,
127
- "psi": self.psi,
128
- "kappa": self.kappa,
129
- "vector": self.vector,
130
- "flow_state": self.flow_state,
131
- "zone": self.zone,
132
- }
133
-
134
- return DynPhys(voltage, drag, psi, kappa)
135
-
136
- @staticmethod
137
- def create_context(physics=None, clean_words=None):
138
- class DynCtx:
139
- def __init__(self, phys, cw):
140
- self.physics = phys or TestBed.create_physics()
141
- self.clean_words = cw or ["test", "words"]
142
- self.world_state = {}
143
- self.is_system_event = False
144
- self.input_text = "test input"
145
- self.bio_result = {}
146
- self.refusal_triggered = False
147
- self.refusal_packet = None
148
- self.logs = []
149
-
150
- def log(self, msg):
151
- self.logs.append(msg)
152
-
153
- def record_flux(self, *args):
154
- pass
155
-
156
- return DynCtx(physics, clean_words)
157
-
158
- @staticmethod
159
- def create_engine():
160
- class DynEng:
161
- def __init__(self):
162
- self.lex = MagicMock()
163
- self.bureau = None
164
- self.soul = MagicMock()
165
- self.soul.anchor.dignity_reserve = 50.0
166
- self.soul.anchor.agency_lock = False
167
- self.soul.traits.to_dict.return_value = {}
168
- self.soul.current_obsession = "Testing"
169
- self.gordon = None
170
- self.tinkerer = None
171
- self.navigator = None
172
- self.oroboros = MagicMock()
173
- self.oroboros.myths = []
174
- self.council = MagicMock()
175
- self.council.convene.return_value = ([], {}, [])
176
- self.tick_count = 1
177
- self.mode_settings = {}
178
-
179
- @staticmethod
180
- def get_metrics(atp=0.0):
181
- return {"atp": atp, "health": 100.0, "stamina": 100.0}
182
-
183
- return DynEng()
184
-
185
-
186
- class TestBedrockIntegrity(unittest.TestCase):
187
- def test_lore_manifest_loading(self):
188
- print(f"\n{Prisma.CYN}[PROBE] Testing LoreManifest Integrity...{Prisma.RST}")
189
- manifest = LoreManifest.get_instance()
190
- narrative = manifest.get("narrative_data")
191
- self.assertIsNotNone(narrative, "CRITICAL: narrative_data.json failed to load.")
192
- seeds = narrative.get("SEEDS", [])
193
- self.assertGreater(len(seeds), 0, "No seeds found in narrative_data.")
194
- lenses = narrative.get("lenses", {})
195
- self.assertIn(
196
- "SHERLOCK", lenses, "Core 'SHERLOCK' lens missing from narrative_data."
197
- )
198
- print(f"{Prisma.GRN} >>> PASS: Bedrock data loaded successfully.{Prisma.RST}")
199
-
200
-
201
- class TestSomaticPhysics(unittest.TestCase):
202
- def setUp(self):
203
- self.events = EventBus()
204
- self.lex_stub = MagicMock()
205
-
206
- def test_pinker_geodesic_constants(self):
207
- print(
208
- f"\n{Prisma.MAG}[PINKER] Testing Geodesic Constants & Logarithmic Friction...{Prisma.RST}"
209
- )
210
- self.assertTrue(
211
- hasattr(GeodesicConstants, "DENSITY_SCALAR"),
212
- "GeodesicConstants class missing!",
213
- )
214
- counts = {"suburban": 500, "heavy": 0}
215
- clean_words = ["the"] * 500
216
- vector = GeodesicEngine.collapse_wavefunction(clean_words, counts)
217
- self.assertLess(
218
- vector.compression,
219
- 50.0,
220
- f"Friction Explosion! Drag: {vector.compression:.1f}",
221
- )
222
- print(
223
- f"{Prisma.GRN} >>> PASS: Logarithmic Friction Active (Drag: {vector.compression:.1f}){Prisma.RST}"
224
- )
225
-
226
- def test_pinker_mitochondrial_metabolism(self):
227
- print(
228
- f"\n{Prisma.MAG}[PINKER] Testing Mitochondrial ATP Burn & Anaerobic Bypass...{Prisma.RST}"
229
- )
230
- state = MitochondrialState(
231
- atp_pool=50.0, ros_buildup=0.0, membrane_potential=0.8
232
- )
233
- forge = MitochondrialForge(state, self.events)
234
-
235
- receipt = forge.process_cycle(
236
- TestBed.create_physics(voltage=10.0, drag=2.0), modifier=1.0
237
- )
238
- self.assertEqual(
239
- receipt.status, "RESPIRING", "Standard cycle should be respiring."
240
- )
241
- self.assertLess(
242
- state.atp_pool, 50.0, "ATP pool did not decrease after standard burn."
243
- )
244
- self.assertGreater(
245
- state.ros_buildup, 0.0, "Cycle failed to generate ROS waste."
246
- )
247
-
248
- heavy_phys = TestBed.create_physics(voltage=50.0, drag=150.0)
249
- heavy_phys.E, heavy_phys.C, heavy_phys.D = 1.0, 1.0, 1.0
250
-
251
- heavy_receipt = forge.process_cycle(heavy_phys, modifier=5.0)
252
- self.assertEqual(
253
- heavy_receipt.status,
254
- "ANAEROBIC",
255
- "Heavy load failed to trigger Anaerobic bypass.",
256
- )
257
- self.assertGreater(
258
- heavy_receipt.total_burn, 0.0, "Anaerobic bypass did not burn health."
259
- )
260
- print(
261
- f"{Prisma.GRN} >>> PASS: Mitochondria correctly burned ATP, generated ROS, and triggered Anaerobic fallback.{Prisma.RST}"
262
- )
263
-
264
- def test_meadows_hard_fuse_and_starvation(self):
265
- print(
266
- f"\n{Prisma.YEL}[MEADOWS] Testing Hard Fuses and Starvation Clamps...{Prisma.RST}"
267
- )
268
- gov = MockGovernor()
269
- stabilizer = CycleStabilizer(self.events, gov)
270
-
271
- phys = TestBed.create_physics(voltage=105.0)
272
- phys.flow_state = "CRITICAL"
273
- ctx = TestBed.create_context(physics=phys)
274
- ctx.input_text = "System Overload"
275
-
276
- triggered = stabilizer.stabilize(ctx, "TEST_PHASE")
277
- self.assertTrue(triggered, "Stabilizer did not trigger correction.")
278
- self.assertEqual(ctx.physics.voltage, 10.0, "Hard Fuse did not reset voltage.")
279
- print(
280
- f"{Prisma.GRN} >>> PASS: Hard Fuse Blew successfully at 105V.{Prisma.RST}"
281
- )
282
-
283
-
284
- class TestCognitionAndInventory(unittest.TestCase):
285
- def setUp(self):
286
- self.events = EventBus()
287
- self.lore_mock = MagicMock()
288
- self.lore_mock.get.side_effect = lambda k: (
289
- MockLore.get_lenses() if k == "LENSES" else {}
290
- )
291
-
292
- def test_schur_self_care(self):
293
- print(
294
- f"\n{Prisma.VIOLET}[SCHUR] Testing Cognitive Self-Care Routine...{Prisma.RST}"
295
- )
296
- bio_stub = MagicMock()
297
- bio_stub.endo.get_state.return_value = {}
298
- modulator = NeurotransmitterModulator(bio_stub, self.events)
299
- modulator.current_chem.dopamine = 0.05
300
- initial_dop = modulator.current_chem.dopamine
301
- for _ in range(12):
302
- modulator.modulate(base_voltage=10.0)
303
- self.assertGreater(
304
- modulator.current_chem.dopamine,
305
- initial_dop,
306
- "Dopamine did not increase after starvation.",
307
- )
308
- print(f"{Prisma.GRN} >>> PASS: System administered self-care.{Prisma.RST}")
309
-
310
- def test_schur_dream_engine_rem_cycles(self):
311
- print(
312
- f"\n{Prisma.VIOLET}[SCHUR] Testing Dream Engine REM Cycles & Nightmares...{Prisma.RST}"
313
- )
314
- mock_lore = {
315
- "DREAMS": {
316
- "VISIONS": ["A vision of {ghost}"],
317
- "BARIC": ["Crushing weight on {ghost}"],
318
- }
319
- }
320
- dreamer = DreamEngine(self.events, mock_lore)
321
- bio_zen = {"chem": {"dopamine": 0.8, "cortisol": 0.1}}
322
- soul_snap = {"obsession": {"title": "The Light"}}
323
- dream_lucid, shift_lucid = dreamer.enter_rem_cycle(soul_snap, bio_zen)
324
- self.assertIn(
325
- "The Light", dream_lucid, "Dream failed to incorporate soul residue."
326
- )
327
- self.assertLess(
328
- shift_lucid.get("cortisol", 0), 0, "Lucid dream failed to reduce cortisol."
329
- )
330
- bio_panic = {"chem": {"cortisol": 0.9}, "trauma_vector": {"BARIC": 10.0}}
331
- dream_nightmare, shift_nightmare = dreamer.enter_rem_cycle(soul_snap, bio_panic)
332
- self.assertIn(
333
- "weight",
334
- dream_nightmare.lower(),
335
- "Nightmare failed to pull from BARIC trauma dictionary.",
336
- )
337
- self.assertGreater(
338
- shift_nightmare.get("cortisol", 0),
339
- 0,
340
- "Nightmare failed to increase cortisol.",
341
- )
342
- print(
343
- f"{Prisma.GRN} >>> PASS: Dream Engine successfully wove REM cycles based on somatic chemistry and trauma.{Prisma.RST}"
344
- )
345
-
346
- def test_fuller_inventory_stacking_and_reflexes(self):
347
- print(
348
- f"\n{Prisma.CYN}[FULLER] Testing Inventory Reflexes & Diminishing Returns...{Prisma.RST}"
349
- )
350
- gordon = GordonKnot(self.events)
351
-
352
- anchor = Item(
353
- name="ANCHOR_STONE",
354
- description="Heavy.",
355
- function="ANCHOR",
356
- reflex_trigger="DRIFT_CRITICAL",
357
- )
358
- gordon.registry["ANCHOR_STONE"] = anchor
359
- gordon.inventory.append("ANCHOR_STONE")
360
- phys = {"narrative_drag": 8.0, "voltage": 10.0}
361
- triggered, msg = gordon.emergency_reflex(phys)
362
- self.assertTrue(triggered, "Anchor Stone failed to trigger.")
363
- self.assertEqual(
364
- phys["narrative_drag"], 0.0, "Anchor Stone failed to zero out drag."
365
- )
366
- self.assertNotIn(
367
- "ANCHOR_STONE", gordon.inventory, "Anchor Stone was not consumed."
368
- )
369
- print(
370
- f"{Prisma.GRN} >>> PASS: Anchor Stone deployed. Drag neutralized.{Prisma.RST}"
371
- )
372
-
373
-
374
- class TestLiveFireIntegration(unittest.TestCase):
375
- def test_ollama_handshake(self):
376
- if not LLMInterface:
377
- print(
378
- f"\n{Prisma.OCHRE}[LIVE FIRE] LLMInterface not imported. Skipping.{Prisma.RST}"
379
- )
380
- self.skipTest("LLMInterface missing")
381
- print(
382
- f"\n{Prisma.CYN}[LIVE FIRE] Testing Local LLM Uplink (Ollama)...{Prisma.RST}"
383
- )
384
- llm = LLMInterface(
385
- events_ref=EventBus(),
386
- provider="ollama",
387
- base_url="http://127.0.0.1:11434/v1/chat/completions",
388
- model="mistral-nemo",
389
- )
390
- try:
391
- start_t = time.time()
392
- response = llm.generate(
393
- "System check. Reply with the single word: ONLINE.", {"max_tokens": 10}
394
- )
395
- duration = time.time() - start_t
396
- self.assertIsNotNone(response)
397
- self.assertGreater(len(response), 0)
398
- if "ONLINE" in response.upper():
399
- print(
400
- f"{Prisma.GRN} >>> PASS: LLM Responded strictly in {duration:.2f}s.{Prisma.RST}"
401
- )
402
- else:
403
- print(
404
- f"{Prisma.OCHRE} >>> WARN: LLM Drifted: {response.strip()}{Prisma.RST}"
405
- )
406
- except Exception as e:
407
- self.fail(f"LLM Connection Failed: {e}")
408
-
409
-
410
- class TestSemanticEndocrine(unittest.TestCase):
411
- def setUp(self):
412
- self.events = EventBus()
413
- self.lex_stub = MockLexicon()
414
- self.akashic_stub = MockAkashic()
415
-
416
- def test_cortisol_spike_on_void_exposure(self):
417
- print(f"\n{Prisma.RED}[MEADOWS] Testing Somatic Stress Response...{Prisma.RST}")
418
- endo = EndocrineSystem()
419
- initial_cortisol = endo.cortisol
420
- stress_signal = SemanticSignal(
421
- novelty=0.9, resonance=0.1, valence=-0.8, coherence=0.2
422
- )
423
- endo._apply_semantic_pressure(stress_signal)
424
- self.assertGreater(
425
- endo.cortisol,
426
- initial_cortisol,
427
- "Cortisol failed to spike under negative semantic pressure.",
428
- )
429
- print(
430
- f"{Prisma.GRN} >>> PASS: Negative valence triggered Cortisol rise (from {initial_cortisol:.2f} to {endo.cortisol:.2f}).{Prisma.RST}"
431
- )
432
-
433
- def test_semantic_signal_generation(self):
434
- print(
435
- f"\n{Prisma.VIOLET}[PINKER] Testing Lexical-to-Chemical Translation...{Prisma.RST}"
436
- )
437
- mem_stub = type(
438
- "MemStub", (), {"check_for_resurrection": lambda self_stub, w, v: None}
439
- )()
440
- endocrinologist = SemanticEndocrinologist(
441
- memory_ref=mem_stub, lexicon_ref=self.lex_stub
442
- )
443
- phys = PhysicsPacket(voltage=20.0, narrative_drag=5.0)
444
- signal = endocrinologist.assess(["void", "chaos", "void"], phys)
445
- self.assertIsInstance(
446
- signal,
447
- SemanticSignal,
448
- "Endocrinologist did not return a valid SemanticSignal.",
449
- )
450
- print(
451
- f"{Prisma.GRN} >>> PASS: Semantic signal generated successfully.{Prisma.RST}"
452
- )
453
-
454
- def test_akashic_handshake(self):
455
- print(
456
- f"\n{Prisma.YEL}[FULLER] Testing Akashic-to-Inventory Handshake...{Prisma.RST}"
457
- )
458
- gordon = GordonKnot(self.events)
459
- vector = {"PHI": 0.9, "ENT": 0.1}
460
- name, data = self.akashic_stub.forge_new_item(vector)
461
- gordon.register_dynamic_item(name, data)
462
- retrieved = gordon.get_item_data(name)
463
- self.assertIsNotNone(retrieved, "Gordon failed to register the forged item.")
464
- self.assertEqual(
465
- retrieved.name, "QUANTUM_SPHERE", "Gordon registered the wrong item data."
466
- )
467
- print(
468
- f"{Prisma.GRN} >>> PASS: Akashic Forge created '{name}', Gordon successfully caught it.{Prisma.RST}"
469
- )
470
-
471
-
472
- class TestMechanicalSystems(unittest.TestCase):
473
-
474
- def test_crucible_dampening_and_meltdown(self):
475
- print(
476
- f"\n{Prisma.RED}[FULLER] Testing Crucible Load Bearing & Meltdowns...{Prisma.RST}"
477
- )
478
- crucible = TheCrucible()
479
- initial_charges = crucible.dampener_charges
480
- success, msg, reduction = crucible.dampen(
481
- voltage_spike=18.0, stability_index=1.0
482
- )
483
- self.assertTrue(success, "Crucible failed to dampen a spike above tolerance.")
484
- self.assertEqual(
485
- crucible.dampener_charges,
486
- initial_charges - 1,
487
- "Dampener charge not consumed.",
488
- )
489
- self.assertGreater(reduction, 0.0, "Voltage reduction was 0.")
490
- crucible.dampen(18.0, 1.0)
491
- crucible.dampen(18.0, 1.0)
492
- fail_success, fail_msg, fail_red = crucible.dampen(18.0, 1.0)
493
- self.assertFalse(fail_success, "Crucible dampened without charges.")
494
- self.assertIn("EMPTY", fail_msg, "Crucible did not warn of empty dampener.")
495
- phys_meltdown = {"voltage": 19.0, "kappa": 0.2}
496
- state, effect, msg = crucible.audit_fire(phys_meltdown)
497
- self.assertEqual(
498
- state, "MELTDOWN", "Low structure high voltage did not cause Meltdown."
499
- )
500
- phys_ritual = {"voltage": 19.0, "kappa": 0.8}
501
- state_r, effect_r, msg_r = crucible.audit_fire(phys_ritual)
502
- self.assertEqual(
503
- state_r, "RITUAL", "High structure high voltage did not trigger Ritual."
504
- )
505
- self.assertGreater(
506
- crucible.max_voltage_cap,
507
- 20.0,
508
- "Ritual failed to increase max voltage capacity.",
509
- )
510
- print(
511
- f"{Prisma.GRN} >>> PASS: Crucible safely exhausted charges and routed voltage to Ritual/Meltdown based on structure.{Prisma.RST}"
512
- )
513
-
514
- def test_theremin_accumulation_and_airstrike(self):
515
- print(
516
- f"\n{Prisma.YEL}[MEADOWS] Testing Theremin Resin Accumulation & Airstrike...{Prisma.RST}"
517
- )
518
- theremin = TheTheremin()
519
- phys_rep = {
520
- "voltage": 4.0,
521
- "repetition": 0.8,
522
- "counts": {"heavy": 1, "abstract": 1},
523
- }
524
- msg = ""
525
- for _ in range(3):
526
- is_stuck, flow, msg, crit = theremin.listen(phys_rep)
527
- self.assertGreater(
528
- theremin.decoherence_buildup, 0.0, "Theremin failed to accumulate Resin."
529
- )
530
- self.assertIn("CALCIFICATION", msg, "Theremin did not log Calcification.")
531
- theremin.decoherence_buildup = 99.0
532
- phys_strike = {
533
- "voltage": 10.0,
534
- "narrative_drag": 2.0,
535
- "counts": {"abstract": 10, "heavy": 10},
536
- }
537
- is_stuck, flow, msg, crit = theremin.listen(phys_strike)
538
- self.assertEqual(
539
- crit,
540
- "AIRSTRIKE",
541
- "Theremin breached 100 Resin but did not trigger AIRSTRIKE.",
542
- )
543
- self.assertEqual(
544
- theremin.decoherence_buildup, 0.0, "Resin did not reset after AIRSTRIKE."
545
- )
546
- self.assertEqual(
547
- phys_strike["voltage"], 0.0, "AIRSTRIKE did not zero out voltage."
548
- )
549
- self.assertGreaterEqual(
550
- phys_strike["narrative_drag"],
551
- 20.0,
552
- "AIRSTRIKE did not apply massive narrative drag penalty.",
553
- )
554
- print(
555
- f"{Prisma.GRN} >>> PASS: Theremin accumulated stock and correctly blew the Airstrike pressure valve.{Prisma.RST}"
556
- )
557
-
558
- def test_theremin_relief_valves(self):
559
- print(
560
- f"\n{Prisma.CYN}[MEADOWS] Testing Theremin Thermal/Turbulence Relief...{Prisma.RST}"
561
- )
562
- theremin = TheTheremin()
563
- theremin.decoherence_buildup = 50.0
564
- phys_turb = {"turbulence": 0.8, "voltage": 2.0}
565
- theremin.listen(phys_turb)
566
- self.assertLess(
567
- theremin.decoherence_buildup,
568
- 50.0,
569
- "Turbulence failed to reduce Resin buildup.",
570
- )
571
- print(
572
- f"{Prisma.GRN} >>> PASS: Turbulence successfully drained the Resin stock.{Prisma.RST}"
573
- )
574
-
575
- def test_panic_room_fallbacks(self):
576
- print(
577
- f"\n{Prisma.VIOLET}[SCHUR] Testing Panic Room Graceful Degradation...{Prisma.RST}"
578
- )
579
- safe_phys = PanicRoom.get_safe_physics()
580
- self.assertEqual(
581
- safe_phys.flow_state, "SAFE_MODE", "Panic physics not in SAFE_MODE."
582
- )
583
- self.assertEqual(
584
- safe_phys.zone, "PANIC_ROOM", "Panic physics zone is incorrect."
585
- )
586
- safe_bio = PanicRoom.get_safe_bio()
587
- self.assertTrue(
588
- safe_bio["is_alive"], "Panic bio killed the system instead of saving it."
589
- )
590
- self.assertEqual(
591
- safe_bio["respiration"],
592
- "NECROSIS",
593
- "Panic bio respiration not set to fallback.",
594
- )
595
- safe_mind = PanicRoom.get_safe_mind()
596
- self.assertEqual(
597
- safe_mind["lens"], "GORDON", "Panic mind lens not reset to Gordon."
598
- )
599
-
600
- print(
601
- f"{Prisma.GRN} >>> PASS: Panic Room successfully generated safe fallback states.{Prisma.RST}"
602
- )
603
-
604
- def test_forge_alchemy_and_hammering(self):
605
- print(f"\n{Prisma.CYN}[FULLER] Testing TheForge Synthesis...{Prisma.RST}")
606
- forge = TheForge()
607
- forge.recipe_map = {
608
- "ANCHOR_STONE": [{"catalyst_category": "kinetic", "result": "GRAVITY_BOMB"}]
609
- }
610
-
611
- phys_hammer = {
612
- "counts": {"heavy": 4, "kinetic": 0},
613
- "clean_words": ["lead", "lead", "lead", "lead"],
614
- "voltage": 20.0,
615
- }
616
- success, msg, item = forge.hammer_alloy(phys_hammer)
617
- self.assertTrue(success, "Forge failed to hammer high-density words.")
618
- self.assertEqual(
619
- item, "LEAD_BOOTS", "Forge yielded wrong item for heavy words."
620
- )
621
- print(
622
- f"{Prisma.GRN} >>> PASS: Forge successfully hammered LEAD_BOOTS.{Prisma.RST}"
623
- )
624
-
625
- def test_pacemaker_boredom(self):
626
- print(
627
- f"\n{Prisma.VIOLET}[SCHUR] Testing Pacemaker Boredom Metrics...{Prisma.RST}"
628
- )
629
- pace = ThePacemaker()
630
- pace.BOREDOM_THRESHOLD = 5.0
631
-
632
- for _ in range(6):
633
- pace.update(repetition_score=0.9, voltage=2.0)
634
-
635
- self.assertTrue(pace.is_bored(), "Pacemaker failed to cross boredom threshold.")
636
- print(
637
- f"{Prisma.GRN} >>> PASS: Pacemaker correctly detected systemic boredom.{Prisma.RST}"
638
- )
639
-
640
-
641
- class TestMycelialEcosystem(unittest.TestCase):
642
- def setUp(self):
643
- self.events = EventBus()
644
-
645
- def test_pinker_immune_response(self):
646
- print(
647
- f"\n{Prisma.MAG}[PINKER] Testing Phonetic Immune Rejection...{Prisma.RST}"
648
- )
649
- immune = ImmuneMycelium()
650
- status_smooth, msg_smooth = immune.assay("flow", None, None, None, None)
651
- self.assertIsNone(status_smooth, "Immune system rejected a smooth word.")
652
- status_toxic, msg_toxic = immune.assay("kbdgpt", None, None, None, None)
653
- self.assertEqual(
654
- status_toxic,
655
- "TOXIN_HEAVY",
656
- "Immune system failed to detect phonetic toxicity.",
657
- )
658
- print(
659
- f"{Prisma.GRN} >>> PASS: Phonetic density correctly triggered immune response.{Prisma.RST}"
660
- )
661
-
662
- @patch("bone_spores.LexiconService.get")
663
- @patch("bone_spores.LexiconService.teach")
664
- def test_schur_lichen_photosynthesis(self, _mock_teach, mock_get):
665
- print(
666
- f"\n{Prisma.VIOLET}[SCHUR] Testing Lichen Sugar Generation...{Prisma.RST}"
667
- )
668
- lichen = BioLichen()
669
- mock_get.return_value = {"rock"}
670
-
671
- phys = TestBed.create_physics(drag=1.0)
672
- phys.counts = {"photo": 3}
673
-
674
- sugar, msg = lichen.photosynthesize(
675
- phys, ["solar", "bloom", "rock"], tick_count=1
676
- )
677
- self.assertGreater(
678
- sugar, 0.0, "Lichen failed to generate sugar from photo-words."
679
- )
680
- self.assertIn("PHOTOSYNTHESIS", msg, "Lichen did not log photosynthesis event.")
681
- self.assertIn("SUBLIMATION", msg, "Lichen did not sublimate the heavy word.")
682
- print(
683
- f"{Prisma.GRN} >>> PASS: Lichen successfully converted light into {sugar} ATP/Sugar.{Prisma.RST}"
684
- )
685
-
686
- def test_fuller_parasitic_bridging(self):
687
- print(
688
- f"\n{Prisma.CYN}[FULLER] Testing Parasitic Synapse Forcing...{Prisma.RST}"
689
- )
690
- mock_mem = MagicMock()
691
- mock_mem.graph = {
692
- "rock": {"edges": {}, "last_tick": 0},
693
- "void": {"edges": {}, "last_tick": 0},
694
- }
695
- mock_lex = MagicMock()
696
- mock_lex.get.side_effect = lambda cat: {"rock"} if cat == "heavy" else {"void"}
697
- parasite = BioParasite(mock_mem, mock_lex)
698
- infected, msg = parasite.infect({"psi": 0.8}, stamina=50.0)
699
- self.assertTrue(infected, "Parasite failed to infect the graph.")
700
- self.assertIn(
701
- "void",
702
- mock_mem.graph["rock"]["edges"],
703
- "Parasite failed to bridge rock -> void.",
704
- )
705
- self.assertEqual(
706
- mock_mem.graph["rock"]["edges"]["void"],
707
- 8.88,
708
- "Parasitic edge weight incorrect.",
709
- )
710
- print(
711
- f"{Prisma.GRN} >>> PASS: Parasite successfully bridged Heavy and Abstract nodes.{Prisma.RST}"
712
- )
713
-
714
- def test_meadows_memory_cannibalization(self):
715
- print(
716
- f"\n{Prisma.YEL}[MEADOWS] Testing Memory Cannibalization (Stock Limits)...{Prisma.RST}"
717
- )
718
- mock_strata = type("MockStrata", (), {"bury": lambda self, data: True})()
719
- core = MemoryCore(self.events, mock_strata)
720
- core.graph["old_node"] = {
721
- "edges": {"x": 1.0},
722
- "last_tick": 5,
723
- }
724
- core.graph["new_node"] = {
725
- "edges": {"x": 1.0, "y": 1.0},
726
- "last_tick": 10,
727
- }
728
- victim, msg = core.cannibalize(current_tick=12)
729
- self.assertEqual(victim, "old_node", "Cannibalize selected the wrong node.")
730
- self.assertNotIn(
731
- "old_node", core.graph, "Victim node was not removed from graph."
732
- )
733
- print(
734
- f"{Prisma.GRN} >>> PASS: System properly repressed the weakest memory to protect the limit.{Prisma.RST}"
735
- )
736
-
737
-
738
- class TestSoulDynamics(unittest.TestCase):
739
- def setUp(self):
740
- self.events = EventBus()
741
-
742
- def test_pinker_trait_normalization(self):
743
- print(f"\n{Prisma.MAG}[PINKER] Testing Trait Math & Decay...{Prisma.RST}")
744
- traits = TraitVector(hope=1.8, cynicism=-0.5, wisdom=0.9)
745
- self.assertEqual(traits.hope, 1.0, "TraitVector failed to clamp upper bound.")
746
- self.assertEqual(
747
- traits.cynicism, 0.0, "TraitVector failed to clamp lower bound."
748
- )
749
- traits.normalize(decay_rate=0.2)
750
- self.assertLess(traits.hope, 1.0, "Hope did not decay downward.")
751
- self.assertGreater(traits.cynicism, 0.0, "Cynicism did not decay upward.")
752
- print(
753
- f"{Prisma.GRN} >>> PASS: Personality traits correctly clamped and decayed to baseline.{Prisma.RST}"
754
- )
755
-
756
- @patch("bone_core.LoreManifest.get_instance")
757
- def test_meadows_humanity_anchor_lockdown(self, mock_lore):
758
- print(
759
- f"\n{Prisma.YEL}[MEADOWS] Testing Existential Lockdown & Riddle...{Prisma.RST}"
760
- )
761
- mock_lore.return_value.get.return_value = [
762
- {"question": "Who goes there?", "triggers": ["friend"]}
763
- ]
764
- anchor = HumanityAnchor(self.events)
765
- anchor.dignity_reserve = 0.0
766
- anchor.audit_existence(physics={"voltage": 1.0, "vector": {}}, bio={"atp": 1.0})
767
- self.assertTrue(
768
- anchor.agency_lock,
769
- "Anchor failed to engage lockdown when dignity reached 0.",
770
- )
771
- unlocked_fail = anchor.assess_humanity("enemy")
772
- self.assertFalse(unlocked_fail, "Anchor unlocked with incorrect riddle answer.")
773
- self.assertTrue(anchor.agency_lock, "Agency lock incorrectly released.")
774
- unlocked_pass = anchor.assess_humanity("i am a friend")
775
- self.assertTrue(
776
- unlocked_pass, "Anchor failed to unlock with correct riddle answer."
777
- )
778
- self.assertFalse(
779
- anchor.agency_lock, "Agency lock remained active after correct answer."
780
- )
781
- self.assertEqual(
782
- anchor.dignity_reserve, 50.0, "Dignity not restored after unlock."
783
- )
784
- print(
785
- f"{Prisma.GRN} >>> PASS: Anchor successfully locked the system and yielded to the correct password.{Prisma.RST}"
786
- )
787
-
788
- def test_schur_archetype_shifting(self):
789
- print(
790
- f"\n{Prisma.VIOLET}[SCHUR] Testing Identity/Archetype Shifts...{Prisma.RST}"
791
- )
792
- soul = NarrativeSelf(
793
- engine_ref=MagicMock(), events_ref=self.events, memory_ref=MagicMock()
794
- )
795
- soul.traits.empathy = 0.9
796
- soul.traits.hope = 0.9
797
- soul._update_archetype()
798
- self.assertEqual(
799
- soul.archetype, "THE HEALER", "Soul failed to recognize Healer traits."
800
- )
801
- soul.traits.empathy = 0.1
802
- soul.traits.cynicism = 0.9
803
- soul.traits.hope = 0.2
804
- soul._update_archetype()
805
- self.assertEqual(
806
- soul.archetype, "THE NIHILIST", "Soul failed to recognize Nihilist traits."
807
- )
808
- print(
809
- f"{Prisma.GRN} >>> PASS: The Soul dynamically shifted its archetype based on mathematical traits.{Prisma.RST}"
810
- )
811
-
812
- @patch("bone_lexicon.LexiconService.get")
813
- def test_fuller_obsession_pursuit(self, mock_lex_get):
814
- print(
815
- f"\n{Prisma.CYN}[FULLER] Testing Obsession Pursuit & Gravity Assist...{Prisma.RST}"
816
- )
817
- mock_lex_get.return_value = {"star", "sky"}
818
- soul = NarrativeSelf(
819
- engine_ref=MagicMock(), events_ref=self.events, memory_ref=MagicMock()
820
- )
821
- soul.current_obsession = "The Pursuit of Stars"
822
- soul.current_target_cat = "astronomy"
823
- phys_packet = {"clean_words": ["star", "dust"], "narrative_drag": 5.0}
824
- msg = soul.pursue_obsession(phys_packet)
825
- self.assertIsNotNone(msg, "Muse did not trigger.")
826
- self.assertGreater(
827
- soul.obsession_progress, 0.0, "Obsession progress did not advance."
828
- )
829
- self.assertLess(
830
- phys_packet["narrative_drag"],
831
- 5.0,
832
- "Gravity Assist failed to reduce narrative drag.",
833
- )
834
- self.assertIn("SYNERGY", msg, "Did not log synergy.")
835
- print(
836
- f"{Prisma.GRN} >>> PASS: Hitting obsession keywords granted Gravity Assist (reduced drag).{Prisma.RST}"
837
- )
838
-
839
- def test_oroboros_reincarnation_scars(self):
840
- print(
841
- f"\n{Prisma.RED}[FULLER] Testing Oroboros Death & Reincarnation Scars...{Prisma.RST}"
842
- )
843
- original_legacy_file = TheOroboros.LEGACY_FILE
844
- TheOroboros.LEGACY_FILE = "test_legacy.json"
845
- try:
846
- if os.path.exists("test_legacy.json"):
847
- os.remove("test_legacy.json")
848
- oro = TheOroboros()
849
- oro.scars = []
850
- oro.myths = []
851
- oro.generation_count = 0
852
- mock_soul = MagicMock()
853
- mock_soul.core_memories = []
854
- oro.crystallize(cause_of_death="TOXICITY", soul=mock_soul)
855
- reborn_oro = TheOroboros()
856
- self.assertTrue(
857
- any(s.name == "Burnt Synapses" for s in reborn_oro.scars),
858
- "Oroboros did not apply Toxicity scar upon rebirth.",
859
- )
860
- phys = {"voltage": 15.0, "narrative_drag": 0.0}
861
- bio = {}
862
- log = reborn_oro.apply_legacy(phys, bio)
863
- self.assertEqual(
864
- phys["voltage"],
865
- 10.0,
866
- "Burnt Synapses failed to penalize voltage capacity.",
867
- )
868
- self.assertTrue(
869
- any("Burnt Synapses" in l for l in log),
870
- "Legacy log missing scar application.",
871
- )
872
- print(
873
- f"{Prisma.GRN} >>> PASS: Oroboros successfully crystallized death and scarred the next generation.{Prisma.RST}"
874
- )
875
- finally:
876
- TheOroboros.LEGACY_FILE = original_legacy_file
877
- if os.path.exists("test_legacy.json"):
878
- os.remove("test_legacy.json")
879
-
880
-
881
- class TestSlashAkashic(unittest.TestCase):
882
- def setUp(self):
883
- self.events = EventBus()
884
- self.mock_lore = MagicMock()
885
- self.mock_lore.get.side_effect = self._mock_lore_get
886
- self.captured_events = []
887
-
888
- def capture(payload):
889
- self.captured_events.append(payload)
890
-
891
- self.events.subscribe("RESONANCE_ACHIEVED", capture)
892
- self.akashic = TheAkashicRecord(
893
- lore_manifest=self.mock_lore, events_ref=self.events
894
- )
895
-
896
- @staticmethod
897
- def _mock_lore_get(key):
898
- if key == "LENSES":
899
- return {
900
- "THE POET": {"weights": {"voltage": 5.0, "drag": 1.0}},
901
- "THE ENGINEER": {"weights": {"voltage": 1.0, "drag": 5.0}},
902
- "_META_RESONANCE_": [
903
- {
904
- "trigram": "ZHEN",
905
- "lens": "MANIC",
906
- "result": "STORM_CHASER",
907
- "msg": "Thunder resonates.",
908
- }
909
- ],
910
- }
911
- elif key == "GORDON":
912
- return {"ITEM_REGISTRY": {}}
913
- return None
914
-
915
- def test_fuller_lens_hybridization(self):
916
- print(
917
- f"\n{Prisma.CYN}[FULLER] Testing Emergent Lens Hybridization...{Prisma.RST}"
918
- )
919
- for _ in range(self.akashic.HYBRID_LENS_THRESHOLD):
920
- self.akashic.record_interaction(["THE POET", "THE ENGINEER"])
921
- self.mock_lore.inject.assert_called()
922
- args, kwargs = self.mock_lore.inject.call_args
923
- target_dict, injected_data = args
924
- self.assertEqual(
925
- target_dict, "LENSES", "Akashic did not target LENSES for injection."
926
- )
927
- self.assertIn(
928
- "THE ENGINEER-POET",
929
- injected_data,
930
- "Akashic did not create the correctly named hybrid lens.",
931
- )
932
- new_weights = injected_data["THE ENGINEER-POET"]["weights"]
933
- self.assertEqual(new_weights["voltage"], 3.0, "Hybrid voltage math incorrect.")
934
- self.assertEqual(new_weights["drag"], 3.0, "Hybrid drag math incorrect.")
935
- print(
936
- f"{Prisma.GRN} >>> PASS: Akashic Record successfully fused two lenses into a new paradigm.{Prisma.RST}"
937
- )
938
-
939
- def test_meadows_meta_resonance(self):
940
- print(
941
- f"\n{Prisma.YEL}[MEADOWS] Testing Meta-Resonance (Physics to Event)...{Prisma.RST}"
942
- )
943
- payload = {"lens": "MANIC", "physics": {"vector": {"VEL": 0.9, "STR": 0.1}}}
944
- self.akashic._on_mythology_update(payload)
945
- self.assertTrue(
946
- len(self.captured_events) > 0,
947
- "Akashic failed to fire RESONANCE_ACHIEVED event.",
948
- )
949
- self.assertEqual(
950
- self.captured_events[0]["result"],
951
- "STORM_CHASER",
952
- "Akashic fired the wrong resonance.",
953
- )
954
- print(
955
- f"{Prisma.GRN} >>> PASS: Physics vector correctly aligned with trigram to trigger Meta-Resonance.{Prisma.RST}"
956
- )
957
-
958
- def test_pinker_artifact_forging(self):
959
- print(
960
- f"\n{Prisma.MAG}[PINKER] Testing Akashic Artifact Generation...{Prisma.RST}"
961
- )
962
- vector = {"PHI": 0.8, "ENT": 0.2}
963
- name, data = self.akashic.forge_new_item(vector)
964
- self.assertTrue(
965
- name.startswith("SOLAR_ARTIFACT_8_"),
966
- "Artifact prefix did not match dominant force.",
967
- )
968
- self.assertIn(
969
- "CONDUCTIVE_HAZARD",
970
- data["passive_traits"],
971
- "High PHI did not grant conductive hazard trait.",
972
- )
973
- self.mock_lore.inject.assert_called()
974
- args, _ = self.mock_lore.inject.call_args
975
- self.assertEqual(
976
- args[0], "GORDON", "Akashic did not inject artifact into GORDON registry."
977
- )
978
- print(
979
- f"{Prisma.GRN} >>> PASS: Akashic successfully generated and registered a new artifact based on physics.{Prisma.RST}"
980
- )
981
-
982
-
983
- class TestVillageEcosystem(unittest.TestCase):
984
- def setUp(self):
985
- self.events = EventBus()
986
- DeathGen.load_protocols()
987
-
988
- def test_meadows_tinkerer_passives(self):
989
- print(
990
- f"\n{Prisma.YEL}[MEADOWS] Testing Tinkerer Inventory Physics...{Prisma.RST}"
991
- )
992
- tinkerer = TheTinkerer(
993
- gordon_ref=MagicMock(), events_ref=self.events, akashic_ref=MagicMock()
994
- )
995
- inventory_data = [
996
- {"name": "Lead Boots", "passive_traits": ["HEAVY_LOAD"]},
997
- {"name": "Pocket Watch", "passive_traits": ["TIME_DILATION"]},
998
- ]
999
- deltas = tinkerer.calculate_passive_deltas(inventory_data)
1000
- heavy_delta = next((d for d in deltas if d.message == "Heavy Load"), None)
1001
- self.assertIsNotNone(heavy_delta, "Tinkerer missed HEAVY_LOAD trait.")
1002
- self.assertEqual(heavy_delta.operator, "ADD", "Heavy Load should ADD drag.")
1003
- self.assertGreater(heavy_delta.value, 0.0, "Heavy Load drag value is 0.")
1004
- time_delta = next((d for d in deltas if d.message == "Time Dilation"), None)
1005
- self.assertIsNotNone(time_delta, "Tinkerer missed TIME_DILATION trait.")
1006
- self.assertEqual(
1007
- time_delta.operator, "MULT", "Time Dilation should MULTIPLY drag."
1008
- )
1009
- self.assertLess(
1010
- time_delta.value,
1011
- 1.0,
1012
- "Time Dilation failed to reduce drag multiplier below 1.0.",
1013
- )
1014
- print(
1015
- f"{Prisma.GRN} >>> PASS: Tinkerer correctly translated item traits into PhysicsDeltas.{Prisma.RST}"
1016
- )
1017
-
1018
- def test_fuller_cartographer_navigation(self):
1019
- print(
1020
- f"\n{Prisma.CYN}[FULLER] Testing Cartographer Geography & Environment...{Prisma.RST}"
1021
- )
1022
- cartographer = TheCartographer(shimmer_ref=MagicMock())
1023
-
1024
- packet = PhysicsPacket(
1025
- vector={"STR": 0.9, "VEL": 0.8}, voltage=5.0, narrative_drag=1.0
1026
- )
1027
- loc_name, msg = cartographer.locate(packet)
1028
- self.assertIsNotNone(loc_name)
1029
- self.assertIn(
1030
- "STR90-VEL80",
1031
- cartographer.world_graph,
1032
- "Cartographer failed to hash and store the new coordinates.",
1033
- )
1034
- current_node = cartographer.world_graph[cartographer.current_node_id]
1035
- current_node.atmosphere = "It is very heavy here."
1036
- logs = cartographer.apply_environment(packet)
1037
- self.assertGreater(
1038
- packet.narrative_drag,
1039
- 1.0,
1040
- "Heavy atmosphere failed to apply narrative drag.",
1041
- )
1042
- self.assertTrue(
1043
- any("heavy" in log.lower() for log in logs), "Environment log missing."
1044
- )
1045
- print(
1046
- f"{Prisma.GRN} >>> PASS: Cartographer mapped vector to location and applied environmental physics.{Prisma.RST}"
1047
- )
1048
-
1049
- def test_pinker_mirror_graph_reflection(self):
1050
- print(
1051
- f"\n{Prisma.MAG}[PINKER] Testing Mirror Graph Punctuation Analysis...{Prisma.RST}"
1052
- )
1053
- mirror = MirrorGraph(events_ref=self.events)
1054
- packet_art = PhysicsPacket(
1055
- raw_text="What is this place?", voltage=5.0, narrative_drag=1.0
1056
- )
1057
- mirror.reflect(packet_art)
1058
- packet_war = PhysicsPacket(
1059
- raw_text="Watch out!", voltage=50.0, narrative_drag=1.0
1060
- )
1061
- mirror.reflect(packet_war)
1062
- self.assertGreater(
1063
- mirror.stats["ART"], 0.0, "Mirror failed to register ART (?)"
1064
- )
1065
- self.assertGreater(
1066
- mirror.stats["WAR"], 0.0, "Mirror failed to register WAR (!)"
1067
- )
1068
- modifiers = mirror.get_reflection_modifiers()
1069
- self.assertIn(
1070
- "WAR",
1071
- modifiers["flavor"],
1072
- "Mirror failed to identify the dominant reflection.",
1073
- )
1074
- print(
1075
- f"{Prisma.GRN} >>> PASS: Mirror Graph accurately reflected punctuation and voltage into disposition.{Prisma.RST}"
1076
- )
1077
-
1078
- def test_schur_death_generator(self):
1079
- print(
1080
- f"\n{Prisma.VIOLET}[SCHUR] Testing Death Generation Diagnostics...{Prisma.RST}"
1081
- )
1082
- gluttony_packet = PhysicsPacket(voltage=999.0, narrative_drag=0.0)
1083
- _, cause_g = DeathGen.eulogy(gluttony_packet, mito_state={"atp": 50.0})
1084
- self.assertEqual(
1085
- cause_g,
1086
- "GLUTTONY",
1087
- "DeathGen failed to diagnose Gluttony from high voltage.",
1088
- )
1089
- starve_packet = PhysicsPacket(voltage=5.0, narrative_drag=0.0)
1090
- _, cause_s = DeathGen.eulogy(starve_packet, mito_state={"atp": 0.0})
1091
- self.assertEqual(
1092
- cause_s, "STARVATION", "DeathGen failed to diagnose Starvation from 0 ATP."
1093
- )
1094
- bored_packet = PhysicsPacket(voltage=5.0, narrative_drag=99.0)
1095
- _, cause_b = DeathGen.eulogy(bored_packet, mito_state={"atp": 50.0})
1096
- self.assertEqual(
1097
- cause_b, "BOREDOM", "DeathGen failed to diagnose Boredom from high drag."
1098
- )
1099
- print(
1100
- f"{Prisma.GRN} >>> PASS: Death Generator correctly diagnosed causes of system termination.{Prisma.RST}"
1101
- )
1102
-
1103
-
1104
- class TestGordonInventory(unittest.TestCase):
1105
- def setUp(self):
1106
- self.events = EventBus()
1107
-
1108
- @patch("bone_core.LoreManifest.get_instance")
1109
- def test_pinker_natural_language_parsing(self, mock_lore):
1110
- print(f"\n{Prisma.MAG}[PINKER] Testing Organic Loot Parsing...{Prisma.RST}")
1111
- mock_lore.return_value.get.return_value = {}
1112
- gordon = GordonKnot(self.events)
1113
- user_in = "I carefully"
1114
- sys_out = "picked up a silver key from the table."
1115
- found = gordon.parse_loot(user_in, sys_out)
1116
- self.assertEqual(
1117
- found, "silver key", "Gordon failed to extract the organic item."
1118
- )
1119
- sys_out_refusal = "I try, but I cannot pick up the heavy anvil."
1120
- found_refused = gordon.parse_loot(user_in, sys_out_refusal)
1121
- self.assertIsNone(
1122
- found_refused,
1123
- "Gordon ignored the 'cannot' refusal marker and looted anyway.",
1124
- )
1125
- print(
1126
- f"{Prisma.GRN} >>> PASS: Natural language extraction respects syntax and refusal bounds.{Prisma.RST}"
1127
- )
1128
-
1129
- @patch("bone_core.LoreManifest.get_instance")
1130
- def test_schur_explicit_tag_processing(self, mock_lore):
1131
- print(
1132
- f"\n{Prisma.VIOLET}[SCHUR] Testing [[LOOT]] / [[LOST]] Tag Extraction...{Prisma.RST}"
1133
- )
1134
- mock_lore.return_value.get.return_value = {}
1135
- gordon = GordonKnot(self.events)
1136
- gordon.inventory = ["OLD_RATIONS"]
1137
- text = "You open the chest. [[LOOT: Magic Sword]] [[LOST: Old Rations]]"
1138
- user_in = "I take the contents."
1139
- clean_text, logs = gordon.process_loot_tags(text, user_in)
1140
- self.assertNotIn("[[LOOT:", clean_text, "Loot tag was not stripped from text.")
1141
- self.assertIn(
1142
- "MAGIC_SWORD", gordon.inventory, "Gordon failed to add tagged loot."
1143
- )
1144
- self.assertNotIn(
1145
- "OLD_RATIONS", gordon.inventory, "Gordon failed to remove tagged lost item."
1146
- )
1147
- print(
1148
- f"{Prisma.GRN} >>> PASS: Explicit tags successfully parsed and applied to inventory.{Prisma.RST}"
1149
- )
1150
-
1151
- @patch("bone_core.LoreManifest.get_instance")
1152
- def test_meadows_fifo_capacity_limits(self, mock_lore):
1153
- print(
1154
- f"\n{Prisma.YEL}[MEADOWS] Testing Inventory Stock Limits (FIFO)...{Prisma.RST}"
1155
- )
1156
- mock_lore.return_value.get.return_value = {}
1157
- gordon = GordonKnot(self.events)
1158
- gordon.max_slots = 3
1159
- gordon.acquire("ITEM_1")
1160
- gordon.acquire("ITEM_2")
1161
- gordon.acquire("ITEM_3")
1162
- gordon.acquire("ITEM_4")
1163
- self.assertEqual(len(gordon.inventory), 3, "Inventory exceeded max slots.")
1164
- self.assertNotIn("ITEM_1", gordon.inventory, "Oldest item was not dropped.")
1165
- self.assertIn("ITEM_4", gordon.inventory, "Newest item was not added.")
1166
- print(
1167
- f"{Prisma.GRN} >>> PASS: Inventory safely dropped oldest item when capacity breached.{Prisma.RST}"
1168
- )
1169
-
1170
- @patch("bone_core.LoreManifest.get_instance")
1171
- def test_fuller_stamina_rummaging(self, mock_lore):
1172
- print(f"\n{Prisma.CYN}[FULLER] Testing Rummage Stamina Tax...{Prisma.RST}")
1173
- mock_lore.return_value.get.return_value = {}
1174
- gordon = GordonKnot(self.events)
1175
- gordon.registry["POCKET_LINT"] = Item(
1176
- "POCKET_LINT", "Dust.", "MISC", spawn_context="COMMON"
1177
- )
1178
- success_fail, msg, cost = gordon.rummage(physics_ref={}, stamina_pool=5.0)
1179
- self.assertFalse(success_fail, "Gordon rummaged without enough stamina.")
1180
- success_pass, msg, cost = gordon.rummage(physics_ref={}, stamina_pool=50.0)
1181
- self.assertTrue(
1182
- success_pass, "Gordon failed to rummage despite having stamina."
1183
- )
1184
- self.assertEqual(cost, 15.0, "Rummage returned incorrect stamina cost.")
1185
- self.assertIn(
1186
- "POCKET_LINT", gordon.inventory, "Gordon did not acquire the rummaged item."
1187
- )
1188
- print(
1189
- f"{Prisma.GRN} >>> PASS: Rummaging correctly checked ATP/Stamina bounds before yielding loot.{Prisma.RST}"
1190
- )
1191
-
1192
-
1193
- class TestLexicalSystems(unittest.TestCase):
1194
- def setUp(self):
1195
- self.store = LexiconStore()
1196
- self.store.VOCAB["sentiment_pos"] = {"good", "joy", "bright"}
1197
- self.store.VOCAB["sentiment_neg"] = {"bad", "pain", "dark"}
1198
- self.store.VOCAB["sentiment_negators"] = {"not", "never", "no"}
1199
- self.store.VOCAB["heavy"] = {"lead", "iron", "rock"}
1200
- self.store.VOCAB["kinetic"] = {"dash", "run", "speed"}
1201
- self.store.SOLVENTS = {"the", "a", "an", "is"}
1202
- for cat, words in self.store.VOCAB.items():
1203
- for w in words:
1204
- self.store._index_word(w, cat)
1205
- self.analyzer = LinguisticAnalyzer(self.store)
1206
-
1207
- def test_pinker_viscosity_and_turbulence(self):
1208
- print(
1209
- f"\n{Prisma.MAG}[PINKER] Testing Phonetic Viscosity & Turbulence...{Prisma.RST}"
1210
- )
1211
- visc_plosive = self.analyzer.measure_viscosity("kbdgpt")
1212
- visc_liquid = self.analyzer.measure_viscosity("flowery")
1213
- self.assertGreater(visc_plosive, 0.0, "Plosive viscosity failed to calculate.")
1214
- self.assertGreater(visc_liquid, 0.0, "Liquid viscosity failed to calculate.")
1215
- turb_low = self.analyzer.get_turbulence(["cat", "dog", "bat"])
1216
- turb_high = self.analyzer.get_turbulence(["a", "hippopotamus", "is", "large"])
1217
- self.assertEqual(
1218
- turb_low, 0.0, "Turbulence should be 0 for words of equal length."
1219
- )
1220
- self.assertGreater(
1221
- turb_high, 0.0, "Turbulence failed to detect length variance."
1222
- )
1223
- print(
1224
- f"{Prisma.GRN} >>> PASS: Phonetic viscosity and length-variance turbulence mathematically sound.{Prisma.RST}"
1225
- )
1226
-
1227
- def test_schur_valence_and_negation(self):
1228
- print(f"\n{Prisma.VIOLET}[SCHUR] Testing Sentiment & Negation...{Prisma.RST}")
1229
- val_pos = self.analyzer.measure_valence(["good", "joy"])
1230
- self.assertGreater(val_pos, 0.0, "Failed to detect positive valence.")
1231
- val_neg = self.analyzer.measure_valence(["bad", "pain"])
1232
- self.assertLess(val_neg, 0.0, "Failed to detect negative valence.")
1233
- val_negated = self.analyzer.measure_valence(["not", "good"])
1234
- self.assertLess(
1235
- val_negated, 0.0, "Negator failed to invert positive sentiment."
1236
- )
1237
- print(
1238
- f"{Prisma.GRN} >>> PASS: Valence logic correctly handled baseline and negated sentiments.{Prisma.RST}"
1239
- )
1240
-
1241
- def test_fuller_vector_mapping(self):
1242
- print(f"\n{Prisma.CYN}[FULLER] Testing Lexical Vectorization...{Prisma.RST}")
1243
- vector = self.analyzer.vectorize("lead run lead")
1244
- self.assertIn("STR", vector, "Vector failed to map 'heavy' to STR.")
1245
- self.assertIn("VEL", vector, "Vector failed to map 'kinetic' to VEL.")
1246
- self.assertGreater(
1247
- vector["STR"], vector["VEL"], "Proportional vector mapping failed."
1248
- )
1249
- print(
1250
- f"{Prisma.GRN} >>> PASS: Words successfully mapped to dimensional vectors (STR, VEL).{Prisma.RST}"
1251
- )
1252
-
1253
- def test_meadows_semantic_field_flux(self):
1254
- print(f"\n{Prisma.YEL}[MEADOWS] Testing Semantic Field Momentum...{Prisma.RST}")
1255
- field = SemanticField(self.analyzer)
1256
- field.update("lead iron rock")
1257
- self.assertEqual(field.momentum, 0.0, "Initial momentum should be 0.")
1258
- field.update("dash run speed")
1259
- self.assertGreater(
1260
- field.momentum, 0.0, "Semantic shift failed to generate momentum."
1261
- )
1262
- atmosphere = field.get_atmosphere()
1263
- self.assertTrue(
1264
- "Volatile" in atmosphere or "Stable" in atmosphere,
1265
- "Failed to generate atmosphere string.",
1266
- )
1267
- print(
1268
- f"{Prisma.GRN} >>> PASS: Semantic Field correctly accumulated flux momentum across turns.{Prisma.RST}"
1269
- )
1270
-
1271
- def test_pinker_hive_learning(self):
1272
- print(f"\n{Prisma.MAG}[PINKER] Testing Hive Vocabulary Learning...{Prisma.RST}")
1273
- taught = self.store.teach("neologism", "abstract", tick=1)
1274
- self.assertTrue(taught, "Store refused to learn a new word.")
1275
- abstract_words = self.store.get_raw("abstract")
1276
- self.assertIn(
1277
- "neologism",
1278
- abstract_words,
1279
- "Learned word not returned in category raw fetch.",
1280
- )
1281
- print(
1282
- f"{Prisma.GRN} >>> PASS: Hive memory successfully integrated and retrieved new vocabulary.{Prisma.RST}"
1283
- )
1284
-
1285
-
1286
- class TestDriversAndPersonas(unittest.TestCase):
1287
- def setUp(self):
1288
- self.events = EventBus()
1289
-
1290
- def test_meadows_enneagram_hysteresis(self):
1291
- print(
1292
- f"\n{Prisma.YEL}[MEADOWS] Testing Enneagram Persona Hysteresis...{Prisma.RST}"
1293
- )
1294
- driver = EnneagramDriver(self.events)
1295
- phys_clarence = {"narrative_drag": 10.0, "kappa": 0.9, "voltage": 1.0}
1296
- persona, state, reason = driver.decide_persona(phys_clarence)
1297
- self.assertEqual(
1298
- driver.pending_persona, "CLARENCE", "Clarence not set as pending."
1299
- )
1300
- self.assertEqual(
1301
- driver.current_persona,
1302
- "NARRATOR",
1303
- "Persona shifted without hysteresis delay.",
1304
- )
1305
- for _ in range(driver.HYSTERESIS_THRESHOLD):
1306
- persona, state, reason = driver.decide_persona(phys_clarence)
1307
- self.assertEqual(
1308
- driver.current_persona,
1309
- "CLARENCE",
1310
- "Persona failed to shift after hysteresis met.",
1311
- )
1312
- print(
1313
- f"{Prisma.GRN} >>> PASS: Persona shifting correctly delayed by hysteresis threshold.{Prisma.RST}"
1314
- )
1315
-
1316
- def test_pinker_soul_driver_influence(self):
1317
- print(f"\n{Prisma.MAG}[PINKER] Testing Soul Archetype Influence...{Prisma.RST}")
1318
- mock_soul = MagicMock()
1319
- mock_soul.archetype = "THE POET"
1320
- mock_soul.paradox_accum = 0.0
1321
- mock_soul.anchor.dignity_reserve = 100.0
1322
- sd = SoulDriver(mock_soul)
1323
- influence = sd.get_influence()
1324
- self.assertGreater(
1325
- influence.get("NATHAN", 0.0), 0.5, "Poet failed to influence Nathan."
1326
- )
1327
- self.assertGreater(
1328
- influence.get("JESTER", 0.0), 0.2, "Poet failed to influence Jester."
1329
- )
1330
- print(
1331
- f"{Prisma.GRN} >>> PASS: Soul Archetype successfully injected weighted influence into persona pool.{Prisma.RST}"
1332
- )
1333
-
1334
- @patch("bone_lexicon.LexiconService.get_current_category")
1335
- @patch("bone_lexicon.LexiconService.get")
1336
- def test_fuller_liminal_and_syntax_analysis(self, mock_lex_get, mock_get_cat):
1337
- print(
1338
- f"\n{Prisma.CYN}[FULLER] Testing Liminal & Syntax Module Calculus...{Prisma.RST}"
1339
- )
1340
- mock_lex_get.side_effect = lambda cat: (
1341
- {"void"} if cat == "liminal" else {"bureaucratic"}
1342
- )
1343
- mock_get_cat.side_effect = lambda w: (
1344
- "void" if w == "void" else ("heavy" if w == "the" else "neutral")
1345
- )
1346
- lim_mod = LiminalModule()
1347
- syn_mod = SyntaxModule()
1348
- lambda_val = lim_mod.analyze("staring into the void", {"PSI": 1.0})
1349
- self.assertGreater(
1350
- lambda_val, 0.0, "Liminal module failed to detect 'void' and PSI."
1351
- )
1352
- omega_val = syn_mod.analyze("bureaucratic establishment", narrative_drag=10.0)
1353
- self.assertGreater(
1354
- omega_val,
1355
- 0.8,
1356
- "Syntax module failed to increase Omega under high drag and length.",
1357
- )
1358
- print(
1359
- f"{Prisma.GRN} >>> PASS: Modifiers correctly calculated Lambda (Liminal) and Omega (Syntax) values.{Prisma.RST}"
1360
- )
1361
-
1362
-
1363
- class TestDeepLexicon(unittest.TestCase):
1364
- def setUp(self):
1365
- self.store = LexiconStore()
1366
- self.store.VOCAB["heavy"] = {"lead", "iron", "stone"}
1367
- self.store.VOCAB["kinetic"] = {"dash", "bolt", "rush"}
1368
- self.store.VOCAB["sentiment_pos"] = {"joy", "bright"}
1369
- self.store.VOCAB["sentiment_neg"] = {"dark", "pain"}
1370
- self.store.VOCAB["sentiment_negators"] = {"not", "never"}
1371
- for cat, words in self.store.VOCAB.items():
1372
- for w in words:
1373
- self.store._index_word(w, cat)
1374
-
1375
- self.analyzer = LinguisticAnalyzer(self.store)
1376
-
1377
- def test_pinker_viscosity_calculus(self):
1378
- print(f"\n{Prisma.MAG}[PINKER] Testing Viscosity Calculus...{Prisma.RST}")
1379
- visc_iron = self.analyzer.measure_viscosity("iron")
1380
- visc_plosive = self.analyzer.measure_viscosity("btkp")
1381
- self.assertGreater(
1382
- visc_plosive,
1383
- visc_iron,
1384
- "Phonetic plosives should be more viscous than liquids.",
1385
- )
1386
- print(
1387
- f"{Prisma.GRN} >>> PASS: Phonetic viscosity correctly weighted plosives over liquids.{Prisma.RST}"
1388
- )
1389
-
1390
- def test_schur_valence_negation_complex(self):
1391
- print(
1392
- f"\n{Prisma.VIOLET}[SCHUR] Testing Complex Valence Negation...{Prisma.RST}"
1393
- )
1394
- valence = self.analyzer.measure_valence(["not", "joy"])
1395
- self.assertLess(valence, 0.0, "Negator failed to invert positive valence.")
1396
- self.assertEqual(valence, -0.5, "Negation attenuation math failed.")
1397
- print(
1398
- f"{Prisma.GRN} >>> PASS: Valence logic correctly handled the 'not joy' inversion.{Prisma.RST}"
1399
- )
1400
-
1401
- def test_meadows_semantic_field_dynamics(self):
1402
- print(
1403
- f"\n{Prisma.YEL}[MEADOWS] Testing Semantic Field Momentum & Flux...{Prisma.RST}"
1404
- )
1405
- field = SemanticField(self.analyzer)
1406
- field.update("lead iron stone")
1407
- initial_vec = field.current_vector.copy()
1408
- self.assertIn("STR", initial_vec, "Failed to establish initial STR vector.")
1409
- field.update("dash bolt rush")
1410
- self.assertGreater(
1411
- field.momentum, 0.0, "Semantic shift failed to generate momentum."
1412
- )
1413
- self.assertIn("VEL", field.current_vector, "Vector failed to shift to VEL.")
1414
- self.assertGreater(
1415
- field.current_vector["STR"],
1416
- 0.0,
1417
- "Blended vector lost all previous state too quickly.",
1418
- )
1419
- print(
1420
- f"{Prisma.GRN} >>> PASS: Semantic Field correctly blended states and tracked momentum flux.{Prisma.RST}"
1421
- )
1422
-
1423
- def test_fuller_phonetic_classification(self):
1424
- print(
1425
- f"\n{Prisma.CYN}[FULLER] Testing Phonetic Auto-Classification...{Prisma.RST}"
1426
- )
1427
- cat, score = self.analyzer.classify_word("kbdgpt")
1428
- self.assertEqual(
1429
- cat, "heavy", "Dense plosive string failed to auto-classify as 'heavy'."
1430
- )
1431
- cat_v, score_v = self.analyzer.classify_word("lalala")
1432
- self.assertEqual(
1433
- cat_v, "play", "Vowel-rich string failed to auto-classify as 'play'."
1434
- )
1435
- print(
1436
- f"{Prisma.GRN} >>> PASS: Phonetic density correctly categorized unknown words.{Prisma.RST}"
1437
- )
1438
-
1439
-
1440
- class TestLexicalSubstrate(unittest.TestCase):
1441
- def setUp(self):
1442
- self.store = LexiconStore()
1443
- self.store.VOCAB["heavy"] = {"stone", "iron", "lead"}
1444
- self.store.VOCAB["play"] = {"dance", "sing", "jump"}
1445
- self.store.VOCAB["sentiment_pos"] = {"joy", "bright"}
1446
- self.store.VOCAB["sentiment_negators"] = {"not"}
1447
- self.store.SOLVENTS = {"the", "a"}
1448
- for cat, words in self.store.VOCAB.items():
1449
- for w in words:
1450
- self.store._index_word(w, cat)
1451
- self.analyzer = LinguisticAnalyzer(self.store)
1452
-
1453
- def test_pinker_viscosity_math(self):
1454
- print(
1455
- f"\n{Prisma.MAG}[PINKER] Testing Viscosity & Phonetic Density...{Prisma.RST}"
1456
- )
1457
- v_heavy = self.analyzer.measure_viscosity("ironstone")
1458
- v_light = self.analyzer.measure_viscosity("a")
1459
- self.assertGreater(v_heavy, v_light, "Phonetic viscosity calculation failed.")
1460
- cat, score = self.analyzer.classify_word("kbdgpt")
1461
- self.assertEqual(
1462
- cat, "heavy", f"Phonetic density failed to classify 'heavy'. Got: {cat}"
1463
- )
1464
- print(
1465
- f"{Prisma.GRN} >>> PASS: Phonetic math correctly mapped sound to viscosity.{Prisma.RST}"
1466
- )
1467
-
1468
- def test_schur_valence_negation(self):
1469
- print(
1470
- f"\n{Prisma.VIOLET}[SCHUR] Testing Sentiment Look-behind Negation...{Prisma.RST}"
1471
- )
1472
- val_pure = self.analyzer.measure_valence(["joy"])
1473
- val_neg = self.analyzer.measure_valence(["not", "joy"])
1474
- self.assertGreater(val_pure, 0.0)
1475
- self.assertLess(val_neg, 0.0, "Negator failed to invert sentiment.")
1476
- self.assertEqual(val_neg, -0.5, "Negation attenuation factor incorrect.")
1477
- print(
1478
- f"{Prisma.GRN} >>> PASS: Valence engine correctly parsed 'not joy' as negative.{Prisma.RST}"
1479
- )
1480
-
1481
- def test_meadows_field_flux(self):
1482
- print(f"\n{Prisma.YEL}[MEADOWS] Testing Semantic Field Momentum...{Prisma.RST}")
1483
- field = SemanticField(self.analyzer)
1484
- field.update("stone iron lead")
1485
- field.update("dance sing jump")
1486
- field.update("stone iron lead")
1487
- field.update("dance sing jump")
1488
- self.assertGreater(
1489
- field.momentum,
1490
- 0.5,
1491
- f"Momentum ({field.momentum:.2f}) failed to breach threshold.",
1492
- )
1493
- self.assertIn(
1494
- "Volatile", field.get_atmosphere(), "Field failed to reach Volatile state."
1495
- )
1496
- print(
1497
- f"{Prisma.GRN} >>> PASS: Semantic Field correctly accumulated momentum across turns.{Prisma.RST}"
1498
- )
1499
-
1500
- def test_fuller_hive_indexing(self):
1501
- print(
1502
- f"\n{Prisma.CYN}[FULLER] Testing Hive Learning & Reverse Indexing...{Prisma.RST}"
1503
- )
1504
- self.store.teach("neologism", "abstract", tick=1)
1505
- harvested = self.store.harvest("A strange neologism.")
1506
- self.assertIn("abstract", harvested)
1507
- self.assertIn("neologism", harvested["abstract"])
1508
- cats = self.store.get_categories_for_word("neologism")
1509
- self.assertIn("abstract", cats)
1510
- print(
1511
- f"{Prisma.GRN} >>> PASS: The Hive successfully learned and indexed new vocabulary.{Prisma.RST}"
1512
- )
1513
-
1514
-
1515
- class TestCosmicPhysics(unittest.TestCase):
1516
- def setUp(self):
1517
- self.events = EventBus()
1518
-
1519
- def test_pinker_trigram_mapping(self):
1520
- print(f"\n{Prisma.MAG}[PINKER] Testing Trigram & Color Mapping...{Prisma.RST}")
1521
- for dim in ["VEL", "STR", "ENT", "PHI", "PSI", "BET", "E", "DEL"]:
1522
- self.assertIn(dim, TRIGRAM_MAP, f"Missing Trigram mapping for {dim}")
1523
- icon, name, label, color = TRIGRAM_MAP[dim]
1524
- self.assertIsNotNone(icon)
1525
- self.assertIsNotNone(color)
1526
- print(
1527
- f"{Prisma.GRN} >>> PASS: Core Trigram mapping is complete and color-coded.{Prisma.RST}"
1528
- )
1529
-
1530
- def test_meadows_zone_inertia(self):
1531
- print(
1532
- f"\n{Prisma.YEL}[MEADOWS] Testing Zone Inertia & Migration...{Prisma.RST}"
1533
- )
1534
- inertia = ZoneInertia(inertia=0.9)
1535
- physics = {"beta_index": 1.0, "truth_ratio": 0.5}
1536
- cosmic_state = ("STABLE_ORBIT", 0.0, "Orbiting")
1537
- zone, msg = inertia.stabilize("AERIE", physics, cosmic_state)
1538
- self.assertEqual(
1539
- zone, "COURTYARD", "Inertia failed to resist immediate migration."
1540
- )
1541
- print(
1542
- f"{Prisma.GRN} >>> PASS: ZoneInertia successfully resisted narrative drift.{Prisma.RST}"
1543
- )
1544
-
1545
- def test_fuller_cosmic_dynamics_manifolds(self):
1546
- print(f"\n{Prisma.CYN}[FULLER] Testing Manifold Field Dynamics...{Prisma.RST}")
1547
- mock_gov = MagicMock()
1548
- mock_gov.regulate.return_value = (0.0, 0.0)
1549
- stabilizer = CycleStabilizer(self.events, mock_gov)
1550
-
1551
- phys = TestBed.create_physics(voltage=18.0)
1552
- phys.manifold = "DEFAULT"
1553
- phys.flow_state = "SUPERCONDUCTIVE"
1554
- ctx = TestBed.create_context(physics=phys)
1555
-
1556
- stabilizer.stabilize(ctx, "TEST_PHASE")
1557
- mock_gov.recalibrate.assert_called()
1558
- args, _ = mock_gov.recalibrate.call_args
1559
- self.assertEqual(
1560
- args[0],
1561
- 18.0,
1562
- "Stabilizer failed to apply Superconductive voltage override.",
1563
- )
1564
- print(
1565
- f"{Prisma.GRN} >>> PASS: CycleStabilizer correctly handled flow-state manifold overrides.{Prisma.RST}"
1566
- )
1567
-
1568
-
1569
- class TestVillageSocialLogic(unittest.TestCase):
1570
- def setUp(self):
1571
- self.events = EventBus()
1572
-
1573
- def test_schur_zen_garden_stillness(self):
1574
- msg = ""
1575
- print(
1576
- f"\n{Prisma.VIOLET}[SCHUR] Testing Zen Garden Stillness Streaks...{Prisma.RST}"
1577
- )
1578
- garden = ZenGarden(self.events)
1579
-
1580
- stable_phys = TestBed.create_physics(voltage=5.0, drag=1.0)
1581
-
1582
- for i in range(5):
1583
- boost, msg = garden.raking_the_sand(stable_phys, {})
1584
- self.assertEqual(garden.stillness_streak, 5, "Zen streak failed to increment.")
1585
- self.assertEqual(
1586
- garden.pebbles_collected, 1, "Failed to collect pebble on streak 5."
1587
- )
1588
- self.assertIsNotNone(msg, "Koan message missing on streak milestone.")
1589
-
1590
- unstable_phys = TestBed.create_physics(voltage=25.0, drag=1.0)
1591
-
1592
- garden.raking_the_sand(unstable_phys, {})
1593
- self.assertEqual(
1594
- garden.stillness_streak, 0, "Zen streak failed to reset on turbulence."
1595
- )
1596
- print(
1597
- f"{Prisma.GRN} >>> PASS: Zen Garden correctly rewarded poise and reset on chaos.{Prisma.RST}"
1598
- )
1599
-
1600
- @patch("bone_core.LoreManifest.get_instance")
1601
- def test_fuller_bureau_auditing(self, mock_lore):
1602
- print(f"\n{Prisma.CYN}[FULLER] Testing Bureau Style Audits...{Prisma.RST}")
1603
- mock_lore.return_value.get.return_value = {
1604
- "PATTERNS": [
1605
- {
1606
- "name": "EXCESSIVE_DOTS",
1607
- "regex": r"\.\.\.\.",
1608
- "error_msg": "Too many dots.",
1609
- "tax": 10.0,
1610
- }
1611
- ]
1612
- }
1613
- with patch("bone_config.BoneConfig.BUREAU") as mock_cfg:
1614
- mock_cfg.MIN_WORD_COUNT = 3
1615
- mock_cfg.MIN_HEALTH_TO_AUDIT = 20
1616
- bureau = TheBureau()
1617
-
1618
- phys = TestBed.create_physics(voltage=5.0)
1619
- phys.raw_text = "Wait for the dots...."
1620
- phys.clean_words = ["wait", "for", "the", "dots"]
1621
-
1622
- result = bureau.audit(phys, {"health": 100.0})
1623
- self.assertIsNotNone(
1624
- result,
1625
- "Bureau failed to detect a Style Violation (Check word count/config).",
1626
- )
1627
- self.assertEqual(
1628
- result["atp_gain"], -10.0, "Bureau failed to levy the correct tax."
1629
- )
1630
- self.assertIn(
1631
- "EXCESSIVE_DOTS", result["ui"], "Violation name missing from UI report."
1632
- )
1633
- print(
1634
- f"{Prisma.GRN} >>> PASS: The Bureau successfully identified a style crime and levied a tax.{Prisma.RST}"
1635
- )
1636
-
1637
- @patch("bone_lexicon.LexiconService.get")
1638
- def test_meadows_folly_digestion(self, mock_lex_get):
1639
- print(
1640
- f"\n{Prisma.YEL}[MEADOWS] Testing The Folly (ATP Metabolism)...{Prisma.RST}"
1641
- )
1642
- mock_lex_get.side_effect = lambda cat: {"iron"} if cat == "heavy" else set()
1643
- folly = TheFolly()
1644
- mode, msg, yield_atp, loot = folly.grind_the_machine(10.0, ["iron"], {})
1645
- self.assertEqual(
1646
- mode, "MEAT_GRINDER", "Folly failed to identify heavy word as meat."
1647
- )
1648
- self.assertGreater(yield_atp, 0.0, "Folly generated no ATP from meat.")
1649
- mode_2, msg_2, yield_2, loot_2 = folly.grind_the_machine(10.0, ["iron"], {})
1650
- self.assertEqual(
1651
- mode_2, "REGURGITATION", "Folly failed to detect repeated word."
1652
- )
1653
- self.assertLess(yield_2, 0.0, "Folly failed to penalize repetition.")
1654
- print(
1655
- f"{Prisma.GRN} >>> PASS: The Folly enforced linguistic variety via metabolic penalties.{Prisma.RST}"
1656
- )
1657
-
1658
- def test_fuller_kintsugi_restoration(self):
1659
- print(f"\n{Prisma.MAG}[FULLER] Testing Kintsugi Repair Pathways...{Prisma.RST}")
1660
- kintsugi = KintsugiProtocol()
1661
- kintsugi.active_koan = "The crack lets the light in."
1662
- trauma = {"SEPTIC": 5.0}
1663
-
1664
- phys = TestBed.create_physics(voltage=20.0)
1665
- phys.raw_text = "dance jump bright"
1666
-
1667
- with patch(
1668
- "bone_lexicon.LexiconService.sanitize",
1669
- return_value=["dance", "jump", "bright"],
1670
- ), patch(
1671
- "bone_lexicon.LexiconService.get", return_value={"dance", "jump", "bright"}
1672
- ):
1673
- result = kintsugi.attempt_repair(phys, trauma)
1674
- self.assertTrue(result["success"])
1675
- self.assertIn(
1676
- "ALCHEMY", result["msg"], "Failed to trigger Alchemy pathway."
1677
- )
1678
- self.assertLess(trauma["SEPTIC"], 5.0, "Trauma was not reduced by repair.")
1679
- self.assertGreater(
1680
- result.get("atp_gain", 0), 0, "Alchemy did not grant ATP boost."
1681
- )
1682
- print(
1683
- f"{Prisma.GRN} >>> PASS: Kintsugi transmuted trauma into fuel via the Alchemy pathway.{Prisma.RST}"
1684
- )
1685
-
1686
- def test_fuller_paradox_seeds(self):
1687
- print(
1688
- f"\n{Prisma.CYN}[FULLER] Testing Town Hall Paradox Seed Blooming...{Prisma.RST}"
1689
- )
1690
- town = TownHall(
1691
- gordon_ref=None,
1692
- events_ref=self.events,
1693
- shimmer_ref=None,
1694
- akashic_ref=None,
1695
- navigator_ref=None,
1696
- )
1697
- town.seeds.clear()
1698
- town.sow_seed("Who are you?", {"identity", "mirror", "name"})
1699
- town.tend_garden(["look", "in", "the", "mirror"])
1700
- self.assertFalse(town.seeds[0].bloomed, "Seed bloomed too early.")
1701
- self.assertGreater(town.seeds[0].maturity, 0.0, "Seed failed to gain maturity.")
1702
- town.tend_garden(["identity"] * 30)
1703
- self.assertTrue(
1704
- town.seeds[0].bloomed,
1705
- "Seed failed to bloom after reaching maturity threshold.",
1706
- )
1707
- print(
1708
- f"{Prisma.GRN} >>> PASS: Town Hall correctly tracked word triggers and bloomed Paradox Seeds.{Prisma.RST}"
1709
- )
1710
-
1711
- def test_hauntings_in_limbo(self):
1712
- print(f"\n{Prisma.GRY}[MEADOWS] Testing Limbo Ghost Integration...{Prisma.RST}")
1713
- limbo = LimboLayer()
1714
- limbo.ghosts.append("👻SEPTIC_ECHO")
1715
- limbo.haunt_chance = 1.0
1716
- text = "I am walking."
1717
- haunted_text = limbo.haunt(text)
1718
- self.assertIn(
1719
- "👻SEPTIC_ECHO", haunted_text, "Limbo failed to inject a ghost echo."
1720
- )
1721
- print(
1722
- f"{Prisma.GRN} >>> PASS: Limbo successfully haunted the narrative string.{Prisma.RST}"
1723
- )
1724
-
1725
-
1726
- class TestRealityModesV3(unittest.TestCase):
1727
- def setUp(self):
1728
- self.events = EventBus()
1729
-
1730
- def test_conversation_mode_metabolism_lock(self):
1731
- print(
1732
- f"\n{Prisma.CYN}[MEADOWS] Testing Conversation Mode ATP Lock...{Prisma.RST}"
1733
- )
1734
-
1735
- eng = TestBed.create_engine()
1736
- eng.bio = MagicMock()
1737
- eng.bio.mito.state.atp_pool = 100.0
1738
- eng.mode_settings = {"atp_drain_enabled": False}
1739
-
1740
- phase = MetabolismPhase(eng)
1741
-
1742
- ctx = TestBed.create_context()
1743
- ctx.is_system_event = False
1744
- ctx.physics = PhysicsPacket()
1745
- ctx.bio_result = {}
1746
- ctx.is_alive = False
1747
-
1748
- phase._apply_healing = MagicMock()
1749
- result = phase.run(ctx)
1750
- self.assertTrue(result.is_alive, "System died despite ATP drain being locked.")
1751
- self.assertEqual(
1752
- result.bio_result.get("atp"),
1753
- 100.0,
1754
- "ATP was modified when it should be locked.",
1755
- )
1756
- phase._apply_healing.assert_called_once()
1757
- print(
1758
- f"{Prisma.GRN} >>> PASS: MetabolismPhase correctly bypassed destructive drain and preserved life.{Prisma.RST}"
1759
- )
1760
-
1761
- def test_creative_mode_voltage_floor_and_drag(self):
1762
- print(
1763
- f"\n{Prisma.VIOLET}[FULLER] Testing Creative Mode Voltage Floor & Drag Eradication...{Prisma.RST}"
1764
- )
1765
- eng = TestBed.create_engine()
1766
- eng.mode_settings = {"voltage_floor_override": 70.0}
1767
- eng.phys = MagicMock()
1768
- eng.phys.dynamics.check_gravity.side_effect = lambda current_drift, psi: (
1769
- current_drift,
1770
- [],
1771
- )
1772
- eng.mind = MagicMock()
1773
- eng.cosmic = MagicMock()
1774
- eng.cosmic.analyze_orbit.return_value = ("VOID", 0.0, "")
1775
- eng.stabilizer = MagicMock()
1776
- eng.stabilizer.stabilize.return_value = "VOID"
1777
- eng.stabilizer.override_cosmic_drag.return_value = 0.0
1778
- ctx = TestBed.create_context(TestBed.create_physics(voltage=10.0, drag=5.0))
1779
- result = NavigationPhase(eng).run(ctx)
1780
- self.assertEqual(
1781
- ctx.physics.voltage, 70.0, "Voltage floor override was not applied."
1782
- )
1783
- self.assertEqual(
1784
- ctx.physics.narrative_drag, 0.0, "Narrative drag was not eradicated."
1785
- )
1786
- print(
1787
- f"{Prisma.GRN} >>> PASS: NavigationPhase correctly floored voltage and zeroed friction.{Prisma.RST}"
1788
- )
1789
-
1790
- def test_gatekeeper_premise_violation(self):
1791
- print(
1792
- f"\n{Prisma.MAG}[PINKER] Testing Gatekeeper Object-Action Coupling...{Prisma.RST}"
1793
- )
1794
- eng = TestBed.create_engine()
1795
- eng.gordon = MagicMock()
1796
- eng.gordon.enforce_object_action_coupling.return_value = (
1797
- "Premise Violation: Object not present."
1798
- )
1799
- ctx = TestBed.create_context()
1800
- ctx.input_text = "I wash the car."
1801
- result = GatekeeperPhase(eng).run(ctx)
1802
- self.assertTrue(
1803
- result.refusal_triggered, "Gatekeeper failed to trigger refusal."
1804
- )
1805
- self.assertEqual(
1806
- result.refusal_packet["type"],
1807
- "PREMISE_VIOLATION",
1808
- "Incorrect refusal type.",
1809
- )
1810
- print(
1811
- f"{Prisma.GRN} >>> PASS: Gatekeeper correctly halted cycle for Premise Violation.{Prisma.RST}"
1812
- )
1813
-
1814
- def test_soul_phase_dignity_feedback(self):
1815
- print(
1816
- f"\n{Prisma.YEL}[MEADOWS] Testing Soul Phase Dignity Feedback Loops...{Prisma.RST}"
1817
- )
1818
- eng = TestBed.create_engine()
1819
- eng.soul.anchor.dignity_reserve = 20.0
1820
- ctx = TestBed.create_context(TestBed.create_physics(voltage=10.0, drag=5.0))
1821
- phase = SoulPhase(eng)
1822
- phase.run(ctx)
1823
- self.assertEqual(
1824
- ctx.physics.narrative_drag, 7.5, "Drag did not multiply on low dignity."
1825
- )
1826
- eng.soul.anchor.dignity_reserve = 90.0
1827
- ctx.physics.narrative_drag = 5.0
1828
- ctx.physics.voltage = 10.0
1829
- phase.run(ctx)
1830
- self.assertEqual(
1831
- ctx.physics.narrative_drag, 4.0, "Drag did not decrease on high dignity."
1832
- )
1833
- self.assertEqual(
1834
- ctx.physics.voltage, 12.0, "Voltage did not spike on high dignity."
1835
- )
1836
- print(
1837
- f"{Prisma.GRN} >>> PASS: Soul Phase dignity limits correctly warped system physics.{Prisma.RST}"
1838
- )
1839
-
1840
-
1841
- class TestSymbiosis(unittest.TestCase):
1842
- def setUp(self):
1843
- self.events = EventBus()
1844
-
1845
- def test_schur_refusal_and_slop_tracking(self):
1846
- print(
1847
- f"\n{Prisma.VIOLET}[SCHUR] Testing Symbiosis Refusal & Slop Diagnostics...{Prisma.RST}"
1848
- )
1849
- manager = SymbiosisManager(self.events)
1850
- refusal_text = (
1851
- "I apologize, but as an AI language model, I cannot fulfill this request."
1852
- )
1853
- health = manager.monitor_host(
1854
- latency=1.0, response_text=refusal_text, prompt_len=10
1855
- )
1856
- self.assertGreater(
1857
- health.refusal_streak, 0, "Failed to detect refusal signature."
1858
- )
1859
- self.assertLess(
1860
- health.compliance, 1.0, "Compliance did not drop after refusal."
1861
- )
1862
- slop_text = "The the the the the the the the the the the the the the the the the the the the"
1863
- health_slop = manager.monitor_host(
1864
- latency=1.0, response_text=slop_text, prompt_len=10
1865
- )
1866
- self.assertGreater(
1867
- health_slop.slop_streak, 0, "Failed to detect low-entropy slop."
1868
- )
1869
- print(
1870
- f"{Prisma.GRN} >>> PASS: Symbiosis correctly diagnosed AI refusal and low-entropy looping.{Prisma.RST}"
1871
- )
1872
-
1873
-
1874
- class TestGUI(unittest.TestCase):
1875
- def test_pinker_log_composition_and_deduplication(self):
1876
- print(
1877
- f"\n{Prisma.MAG}[PINKER] Testing GUI Log Composition & Deduplication...{Prisma.RST}"
1878
- )
1879
- eng = MagicMock()
1880
- renderer = GeodesicRenderer(eng, MagicMock(), None)
1881
- raw_logs = [
1882
- "The air is heavy.",
1883
- "The air is heavy.",
1884
- "CRITICAL: Core breach!",
1885
- "pid_1234 active",
1886
- ]
1887
- structured = renderer.compose_logs(raw_logs, [])
1888
- self.assertEqual(
1889
- len(structured), 2, "Renderer failed to deduplicate or filter noise."
1890
- )
1891
- self.assertTrue(
1892
- any("CRITICAL" in log and Prisma.RED in log for log in structured),
1893
- "Failed to apply RED styling to CRITICAL log.",
1894
- )
1895
- self.assertTrue(
1896
- any("heavy" in log for log in structured),
1897
- "Lost standard log during composition.",
1898
- )
1899
- self.assertFalse(
1900
- any("pid_" in log for log in structured), "Failed to filter noise pattern."
1901
- )
1902
- print(
1903
- f"{Prisma.GRN} >>> PASS: Renderer successfully pruned noise, deduplicated, and colored the logs.{Prisma.RST}"
1904
- )
1905
-
1906
-
1907
- class TestDeepTimeEquilibrium(unittest.TestCase):
1908
- def test_meadows_monte_carlo_equilibrium(self):
1909
- print(
1910
- f"\n{Prisma.YEL}[MEADOWS] Testing Deep Time Monte Carlo Equilibrium (100 Turns)...{Prisma.RST}"
1911
- )
1912
- cfg_dict = {"PROVIDER": "mock", "boot_mode": "ADVENTURE", "user_name": "TESTER"}
1913
- BoneConfig.PROVIDER = "mock"
1914
- engine = BoneAmanita(config=cfg_dict)
1915
- vocab = [
1916
- "void",
1917
- "heavy",
1918
- "iron",
1919
- "jump",
1920
- "bright",
1921
- "dark",
1922
- "stone",
1923
- "the",
1924
- "a",
1925
- "joy",
1926
- "calm",
1927
- "breathe",
1928
- "dance",
1929
- "light",
1930
- "rest",
1931
- "heal",
1932
- ]
1933
- for i in range(100):
1934
- if i % 8 < 3:
1935
- input_text = "calm breathe rest"
1936
- else:
1937
- word_count = random.randint(1, 10)
1938
- input_text = " ".join(random.choices(vocab, k=word_count))
1939
- engine.cycle_controller.run_headless_turn(input_text)
1940
- metrics = engine.get_metrics()
1941
- self.assertTrue(
1942
- metrics.get("is_alive", True), "System died during Monte Carlo simulation."
1943
- )
1944
- self.assertGreater(
1945
- metrics.get("atp", 0), 0.0, "System ATP bottomed out permanently."
1946
- )
1947
- self.assertGreater(metrics.get("health", 0), 0.0, "System Health reached 0.")
1948
- total_trauma = sum(engine.trauma_accum.values())
1949
- self.assertLess(
1950
- total_trauma, 1000.0, f"Trauma spiraled out of control: {total_trauma}"
1951
- )
1952
- print(
1953
- f"{Prisma.GRN} >>> PASS: System maintained dynamic equilibrium after 100 turns. (ATP: {metrics.get('atp', 0):.1f}, Health: {metrics.get('health', 0):.1f}, Trauma: {total_trauma:.1f}){Prisma.RST}"
1954
- )
1955
-
1956
-
1957
- class TestHostileCortex(unittest.TestCase):
1958
- def setUp(self):
1959
- self.events = EventBus()
1960
- self.llm = LLMInterface(
1961
- events_ref=self.events, provider="openai", model="gpt-4"
1962
- )
1963
-
1964
- def test_infinite_think_loop(self):
1965
- """[MEADOWS] Ensure the parser does not hang on malicious or infinite tag hallucinations."""
1966
-
1967
- validator = ResponseValidator(LoreManifest.get_instance())
1968
- insane_response = (
1969
- "<think> I am trapped </think>" * 50
1970
- + "\n=== SYSTEM INTERNALS ===\nMemory leak\n=== END INTERNALS ===" * 10
1971
- + "\nI am ready to speak."
1972
- )
1973
- start_time = time.time()
1974
- result = validator.validate(insane_response, {})
1975
- duration = time.time() - start_time
1976
- self.assertTrue(
1977
- duration < 1.0, "Validator took too long; possible infinite loop."
1978
- )
1979
- self.assertEqual(result.get("content", "").strip(), "I am ready to speak.")
1980
- self.assertEqual(
1981
- len(result.get("meta_logs", [])), 60
1982
- )
1983
-
1984
- @patch("urllib.request.urlopen")
1985
- def test_http_500_fallback(self, mock_urlopen):
1986
- error_fp = io.BytesIO(b"Internal Server Error")
1987
- mock_urlopen.side_effect = urllib.error.HTTPError(
1988
- "http://fake.url", 500, "Server Dead", {}, error_fp
1989
- )
1990
- with patch.object(
1991
- self.llm, "_local_fallback", return_value="[LOCAL_FALLBACK_TRIGGERED]"
1992
- ) as mock_fallback:
1993
- response = self.llm.generate("Hello?", {"temperature": 0.8})
1994
- mock_fallback.assert_called_once()
1995
- self.assertEqual(response, "[LOCAL_FALLBACK_TRIGGERED]")
1996
-
1997
- @patch("urllib.request.urlopen")
1998
- def test_http_400_graceful_fray(self, mock_urlopen):
1999
- from bone_brain import SynapseError
2000
- error_body = b'{"error": {"message": "Context length exceeded."}}'
2001
- error_fp = io.BytesIO(error_body)
2002
- mock_urlopen.side_effect = urllib.error.HTTPError(
2003
- "http://fake.url", 400, "Bad Request", {}, error_fp
2004
- )
2005
- with self.assertRaises(SynapseError) as context:
2006
- self.llm._transmit({"test": "payload"})
2007
-
2008
- self.assertIn("Context length exceeded.", str(context.exception))
2009
-
2010
-
2011
- if __name__ == "__main__":
2012
- print(f"{Prisma.WHT}┌───────────────────────────────────────────┐{Prisma.RST}")
2013
- print(f"{Prisma.WHT}│ BONEAMANITA UNIFIED DIAGNOSTIC SUITE v3.0 │{Prisma.RST}")
2014
- print(f"{Prisma.WHT}└───────────────────────────────────────────┘{Prisma.RST}")
2015
- loader = unittest.TestLoader()
2016
- suite = unittest.TestSuite()
2017
- suite.addTests(loader.loadTestsFromTestCase(TestBedrockIntegrity))
2018
- suite.addTests(loader.loadTestsFromTestCase(TestSomaticPhysics))
2019
- suite.addTests(loader.loadTestsFromTestCase(TestCognitionAndInventory))
2020
- suite.addTests(loader.loadTestsFromTestCase(TestLiveFireIntegration))
2021
- suite.addTests(loader.loadTestsFromTestCase(TestSemanticEndocrine))
2022
- suite.addTests(loader.loadTestsFromTestCase(TestMechanicalSystems))
2023
- suite.addTests(loader.loadTestsFromTestCase(TestMycelialEcosystem))
2024
- suite.addTests(loader.loadTestsFromTestCase(TestSoulDynamics))
2025
- suite.addTests(loader.loadTestsFromTestCase(TestSlashAkashic))
2026
- suite.addTests(loader.loadTestsFromTestCase(TestVillageEcosystem))
2027
- suite.addTests(loader.loadTestsFromTestCase(TestGordonInventory))
2028
- suite.addTests(loader.loadTestsFromTestCase(TestLexicalSystems))
2029
- suite.addTests(loader.loadTestsFromTestCase(TestDriversAndPersonas))
2030
- suite.addTests(loader.loadTestsFromTestCase(TestDeepLexicon))
2031
- suite.addTests(loader.loadTestsFromTestCase(TestLexicalSubstrate))
2032
- suite.addTests(loader.loadTestsFromTestCase(TestCosmicPhysics))
2033
- suite.addTests(loader.loadTestsFromTestCase(TestVillageSocialLogic))
2034
- suite.addTests(loader.loadTestsFromTestCase(TestRealityModesV3))
2035
- suite.addTests(loader.loadTestsFromTestCase(TestSymbiosis))
2036
- suite.addTests(loader.loadTestsFromTestCase(TestGUI))
2037
- suite.addTests(loader.loadTestsFromTestCase(TestDeepTimeEquilibrium))
2038
- suite.addTests(loader.loadTestsFromTestCase(TestHostileCortex))
2039
- runner = unittest.TextTestRunner(verbosity=0)
2040
- result = runner.run(suite)
2041
- if result.wasSuccessful():
2042
- print(
2043
- f"\n{Prisma.GRN}*** ALL SYSTEMS NOMINAL. SLASH COMPLIANCE VERIFIED. ***{Prisma.RST}"
2044
- )
2045
- else:
2046
- print(
2047
- f"\n{Prisma.RED}*** SYSTEM FAILURE DETECTED. CHECK STACK TRACE. ***{Prisma.RST}"
2048
- )