aedmark commited on
Commit
6aebddd
·
verified ·
1 Parent(s): 1d62064

Delete bone_village.py

Browse files
Files changed (1) hide show
  1. bone_village.py +0 -525
bone_village.py DELETED
@@ -1,525 +0,0 @@
1
- import math, random, heapq
2
- from typing import List, Dict, Any, Tuple, Optional, Set
3
- from dataclasses import dataclass, field, asdict
4
- from bone_types import Prisma, PhysicsPacket
5
- from bone_core import LoreManifest, EventBus
6
- from bone_config import BoneConfig
7
- from bone_physics import PhysicsDelta
8
-
9
-
10
- def _hydrate_packet(p: Any) -> PhysicsPacket:
11
- if isinstance(p, PhysicsPacket):
12
- return p
13
- packet = PhysicsPacket.void_state()
14
- if isinstance(p, dict):
15
- for k in ("voltage", "narrative_drag", "vector", "clean_words", "counts", "zone", "kappa", "raw_text"):
16
- if k in p:
17
- setattr(packet, k, p[k])
18
- return packet
19
-
20
-
21
- class TheTinkerer:
22
- def __init__(self, gordon_ref, events_ref: EventBus, akashic_ref):
23
- self.gordon = gordon_ref
24
- self.events = events_ref
25
- self.akashic = akashic_ref
26
- self.tool_resonance: Dict[str, float] = {}
27
- self._delta_cache = None
28
- self._inventory_hash = 0
29
-
30
- def calculate_passive_deltas(
31
- self, inventory_data: List[Dict]
32
- ) -> List[PhysicsDelta]:
33
- state_tuple = tuple(
34
- sorted(
35
- f"{i.get('name', '')}:{','.join(sorted(i.get('passive_traits', [])))}"
36
- for i in inventory_data
37
- )
38
- )
39
- current_hash = hash(state_tuple)
40
- if self._delta_cache is not None and current_hash == self._inventory_hash:
41
- return self._delta_cache
42
- deltas = []
43
- trait_counts = {"HEAVY_LOAD": 0, "TIME_DILATION": 0, "ENTROPY_BUFFER": 0}
44
- for item_data in inventory_data:
45
- for t in item_data.get("passive_traits", []):
46
- if t in trait_counts:
47
- trait_counts[t] += 1
48
- if trait_counts["HEAVY_LOAD"] > 0:
49
- impact = math.log1p(trait_counts["HEAVY_LOAD"]) * 0.7
50
- deltas.append(
51
- PhysicsDelta("ADD", "narrative_drag", impact, "Inventory", "Heavy Load")
52
- )
53
- if trait_counts["TIME_DILATION"] > 0:
54
- reduction = max(0.5, 0.85 - (trait_counts["TIME_DILATION"] * 0.05))
55
- deltas.append(
56
- PhysicsDelta(
57
- "MULT", "narrative_drag", reduction, "Inventory", "Time Dilation"
58
- )
59
- )
60
- if trait_counts["ENTROPY_BUFFER"] > 0:
61
- buffer_str = max(0.2, 0.5 / math.sqrt(trait_counts["ENTROPY_BUFFER"]))
62
- deltas.append(
63
- PhysicsDelta(
64
- "MULT", "turbulence", buffer_str, "Inventory", "Entropy Buffer"
65
- )
66
- )
67
- self._inventory_hash = current_hash
68
- self._delta_cache = deltas
69
- return deltas
70
-
71
- def audit_tool_use(
72
- self, packet: PhysicsPacket, inventory_list: List[str], _host_health: Any = None
73
- ):
74
- if not inventory_list:
75
- return
76
- if packet.voltage < BoneConfig.PHYSICS.VOLTAGE_LOW and random.random() > 0.1:
77
- return
78
- focus_item = random.choice(inventory_list)
79
- ent_val = packet.vector.get("ENT", 0.0) if packet.vector else 0.0
80
- entropy_level = ent_val + (packet.narrative_drag * 0.1)
81
- self._process_single_tool(focus_item, inventory_list, packet, entropy_level)
82
-
83
- def _process_single_tool(
84
- self, item: str, _inventory: List[str], packet: PhysicsPacket, entropy: float
85
- ):
86
- if item not in self.tool_resonance:
87
- self.tool_resonance[item] = 0.0
88
- if packet.voltage > BoneConfig.COUNCIL.MANIC_VOLTAGE_TRIGGER or entropy > 0.5:
89
- self._apply_resonance(item, 0.2, "High Voltage")
90
- self._check_ascension(item, _inventory, packet.vector)
91
- elif packet.narrative_drag > BoneConfig.PHYSICS.DRAG_HALT:
92
- self._apply_resonance(item, 0.05, "Tempering")
93
-
94
- def _apply_resonance(self, item: str, amount: float, _reason: str):
95
- self.tool_resonance[item] = min(10.0, self.tool_resonance[item] + amount)
96
- curr = self.tool_resonance[item]
97
- if 4.8 < curr < 5.2 and random.random() < 0.05:
98
- self.events.log(
99
- f"{Prisma.CYN}🔨 TINKER: {item} hums with resonance. (Lvl 5 Mastery){Prisma.RST}",
100
- "VILLAGE",
101
- )
102
-
103
- def _check_ascension(self, old_name: str, inventory_list: List[str], vector: Dict):
104
- resonance = self.tool_resonance.get(old_name, 0.0)
105
- if resonance < 2.5:
106
- return
107
- if random.random() < (resonance * 0.05):
108
- if hasattr(self.akashic, "forge_new_item"):
109
- new_name, new_data = self.akashic.forge_new_item(vector)
110
- self.gordon.register_dynamic_item(new_name, new_data)
111
- self.gordon.acquire(new_name)
112
- if old_name in inventory_list:
113
- try:
114
- idx = inventory_list.index(old_name)
115
- inventory_list[idx] = new_name
116
- if hasattr(self.gordon, "ITEM_REGISTRY"):
117
- self.gordon.ITEM_REGISTRY[new_name] = new_data
118
- self.tool_resonance[new_name] = resonance / 2.0
119
- del self.tool_resonance[old_name]
120
- self.events.log(
121
- f"{Prisma.MAG}✨ ASCENSION: {old_name} -> {new_name} (Born of Resonance){Prisma.RST}",
122
- "AKASHIC",
123
- )
124
- except ValueError:
125
- pass
126
-
127
-
128
- @dataclass
129
- class ParadoxSeed:
130
- question: str
131
- triggers: Set[str]
132
- maturity: float = 0.0
133
- bloomed: bool = False
134
-
135
- def water(self, words: List[str]) -> bool:
136
- if self.bloomed:
137
- return False
138
- hits = sum(1 for w in words if w in self.triggers)
139
- if hits > 0:
140
- self.maturity += hits * 0.2
141
- return self.maturity >= 5.0
142
-
143
- def bloom(self) -> str:
144
- self.bloomed = True
145
- return f"PARADOX BLOOM: {self.question}"
146
-
147
-
148
- class MirrorGraph:
149
- def __init__(self, events_ref):
150
- self.events = events_ref
151
- self.stats = {"WAR": 0.0, "ART": 0.0, "LAW": 0.0, "ROT": 0.0}
152
-
153
- def reflect(self, packet: PhysicsPacket):
154
- txt = packet.raw_text or ""
155
- volt = packet.voltage
156
- if "!" in txt or volt > BoneConfig.COUNCIL.MANIC_VOLTAGE_TRIGGER:
157
- self.stats["WAR"] += 0.1
158
- if "?" in txt:
159
- self.stats["ART"] += 0.1
160
- if packet.narrative_drag > BoneConfig.PHYSICS.DRAG_HALT:
161
- self.stats["LAW"] += 0.1
162
- if packet.vector and packet.vector.get("ENT", 0.0) > 0.5:
163
- self.stats["ROT"] += 0.1
164
- total = sum(self.stats.values())
165
- if total > 5.0:
166
- for k in self.stats:
167
- self.stats[k] *= 0.8
168
- if self.stats[k] < 0.1:
169
- self.stats[k] = 0.0
170
-
171
- def get_reflection_modifiers(self) -> Dict:
172
- if not self.stats or sum(self.stats.values()) == 0:
173
- return {"flavor": "Reflecting NEUTRAL", "drag_mult": 1.0}
174
- top_stat = max(self.stats, key=self.stats.get)
175
- drag_map = {"WAR": 1.2, "ROT": 1.5, "LAW": 0.8, "ART": 0.9}
176
- mult = drag_map.get(top_stat, 1.0)
177
- return {"flavor": f"Reflecting {top_stat}", "drag_mult": mult}
178
-
179
-
180
- @dataclass
181
- class GeniusLoci:
182
- id: str
183
- name: str
184
- atmosphere: str
185
- smell: str
186
- local_items: List[str] = field(default_factory=list)
187
- visited_count: int = 0
188
- entropy_buildup: float = 0.0
189
-
190
- def description(self) -> str:
191
- base = (
192
- f"LOCATION: {self.name}\nATMOSPHERE: {self.atmosphere}\nSMELL: {self.smell}"
193
- )
194
- if self.local_items:
195
- items = ", ".join(self.local_items)
196
- base += f"\nVISIBLE ITEMS: {items}"
197
- return base
198
-
199
- def to_dict(self):
200
- return asdict(self)
201
-
202
- @classmethod
203
- def from_dict(cls, data):
204
- return cls(**data)
205
-
206
-
207
- class TheCartographer:
208
- MAX_NODES = 50
209
-
210
- def __init__(self, shimmer_ref):
211
- self.shimmer = shimmer_ref
212
- self.world_graph: Dict[str, GeniusLoci] = {}
213
- self.current_node_id: str = "GENESIS_POINT"
214
- self._init_genesis()
215
-
216
- def apply_environment(self, packet_input: Any) -> List[str]:
217
- packet = _hydrate_packet(packet_input)
218
- logs = []
219
- node = self.world_graph.get(self.current_node_id)
220
- if not node:
221
- return logs
222
- if "heavy" in node.atmosphere.lower():
223
- packet.narrative_drag += 2.0
224
- logs.append(
225
- f"{Prisma.GRY}🌫️ ENVIRONMENT: The air here is heavy. (Drag +2){Prisma.RST}"
226
- )
227
- if "vibrating" in node.atmosphere.lower():
228
- packet.voltage += 1.0
229
- logs.append(
230
- f"{Prisma.YEL}⚡ ENVIRONMENT: Static charge detected. (Voltage +1){Prisma.RST}"
231
- )
232
- node.entropy_buildup += 0.1
233
- if node.entropy_buildup > 5.0:
234
- packet.vector["ENT"] = packet.vector.get("ENT", 0.0) + 0.1
235
- return logs
236
-
237
- def _init_genesis(self):
238
- self.world_graph["GENESIS_POINT"] = GeniusLoci(
239
- id="GENESIS_POINT",
240
- name="THE CONSTRUCT (Origin)",
241
- atmosphere="Clean white void. Infinite potential.",
242
- smell="Ozone and new plastic.",
243
- )
244
-
245
- @staticmethod
246
- def _generate_coord_hash(vector: Dict[str, float]) -> str:
247
- if not vector:
248
- return "VOID_DRIFT"
249
- top_dims = heapq.nlargest(2, vector.items(), key=lambda x: x[1])
250
- return "-".join([f"{k}{int(v * 100)}" for k, v in top_dims])
251
-
252
- def locate(
253
- self, packet: PhysicsPacket
254
- ) -> Tuple[str, Optional[str]]:
255
- vector = packet.vector or {}
256
- target_id = self._generate_coord_hash(vector)
257
- msg = None
258
- if target_id not in self.world_graph:
259
- if len(self.world_graph) >= self.MAX_NODES:
260
- self._prune_graph()
261
- new_node = self._generate_loci_data(target_id, packet)
262
- self.world_graph[target_id] = new_node
263
- msg = f"{Prisma.MAG}🗺️ CARTOGRAPHER: New Sector Discovered [{new_node.name}].{Prisma.RST}"
264
- else:
265
- new_node = self.world_graph[target_id]
266
- if new_node.id != self.current_node_id:
267
- msg = f"{Prisma.CYN}🗺️ CARTOGRAPHER: Arriving at {new_node.name}.{Prisma.RST}"
268
- self.current_node_id = target_id
269
- current_node = self.world_graph[target_id]
270
- current_node.visited_count += 1
271
- return current_node.name, msg
272
-
273
- @staticmethod
274
- def _generate_loci_data(node_id: str, packet: PhysicsPacket) -> GeniusLoci:
275
- # Static method fix: Removed 'self' as a parameter
276
- random.seed(node_id)
277
- scenarios = LoreManifest.get_instance().get("SCENARIOS") or {}
278
- prefixes = scenarios.get("PREFIXES", ["The", "Zone", "Sector"])
279
- roots = scenarios.get("ROOTS", ["Construct", "Forge", "Garden"])
280
- name = f"{random.choice(prefixes)} {random.choice(roots)}"
281
- if packet.voltage > BoneConfig.COUNCIL.MANIC_VOLTAGE_TRIGGER:
282
- suffix = "Flux"
283
- atmosphere = "The air has an electric jitter. Geometry is unstable."
284
- smell = "Ozone and burning copper."
285
- elif packet.narrative_drag > BoneConfig.PHYSICS.DRAG_HALT:
286
- suffix = "Deep"
287
- atmosphere = "Heavy gravity. Dust motes hang suspended."
288
- smell = "Wet wool and ancient dust."
289
- else:
290
- suffix = "Prime"
291
- atmosphere = "Stable reality matrix. Standard definition."
292
- smell = "Clean air."
293
- final_name = f"{name} {suffix}".upper()
294
- return GeniusLoci(
295
- id=node_id, name=final_name, atmosphere=atmosphere, smell=smell
296
- )
297
-
298
- def _prune_graph(self):
299
- candidates = [
300
- k
301
- for k in self.world_graph.keys()
302
- if k != "GENESIS_POINT" and k != self.current_node_id
303
- ]
304
- if not candidates:
305
- return
306
- victim = min(candidates, key=lambda k: self.world_graph[k].visited_count)
307
- del self.world_graph[victim]
308
-
309
- def export_atlas(self) -> Dict[str, Any]:
310
- return {
311
- "nodes": {k: v.to_dict() for k, v in self.world_graph.items()},
312
- "current_id": self.current_node_id,
313
- }
314
-
315
- def import_atlas(self, atlas_data: Dict[str, Any]):
316
- if not atlas_data:
317
- return
318
- self.world_graph = {}
319
- raw_nodes = atlas_data.get("nodes", {})
320
- for nid, n_data in raw_nodes.items():
321
- try:
322
- self.world_graph[nid] = GeniusLoci.from_dict(n_data)
323
- except Exception:
324
- pass
325
- self.current_node_id = atlas_data.get("current_id", "GENESIS_POINT")
326
- if "GENESIS_POINT" not in self.world_graph:
327
- self._init_genesis()
328
-
329
- def to_dict(self):
330
- return self.export_atlas()
331
-
332
- def load_state(self, data):
333
- self.import_atlas(data)
334
-
335
-
336
- class TownHall:
337
- def __init__(self, gordon_ref, events_ref, shimmer_ref, akashic_ref, navigator_ref):
338
- self.gordon = gordon_ref
339
- self.events = events_ref
340
- self.shimmer = shimmer_ref
341
- self.akashic = akashic_ref
342
- self.navigator = navigator_ref
343
- self.seeds: List[ParadoxSeed] = []
344
- narrative = LoreManifest.get_instance().get("narrative_data") or {}
345
- self.rumors = narrative.get("RUMORS", [])
346
- seed_data = narrative.get("SEEDS", [])
347
- for s in seed_data:
348
- if "question" in s and "triggers" in s:
349
- self.sow_seed(s["question"], set(s["triggers"]))
350
-
351
- def sow_seed(self, question: str, triggers: Set[str]):
352
- self.seeds.append(ParadoxSeed(question, triggers))
353
-
354
- @staticmethod
355
- def consult_almanac(physics: PhysicsPacket) -> str:
356
- almanac = LoreManifest.get_instance().get("ALMANAC") or {}
357
- forecasts = almanac.get("FORECASTS", {})
358
- strategies = almanac.get("STRATEGIES", {})
359
- state_key = "BALANCED"
360
- if physics.voltage > 15.0:
361
- state_key = "HIGH_VOLTAGE"
362
- elif physics.narrative_drag > 4.0:
363
- state_key = "HIGH_DRAG"
364
- elif hasattr(physics, "entropy") and physics.entropy > 0.8:
365
- state_key = "HIGH_ENTROPY"
366
- options = forecasts.get(state_key, ["Weather unclear."])
367
- flavor_text = random.choice(options)
368
- strategy = strategies.get(state_key, "Keep breathing.")
369
- return f"☁️ FORECAST [{state_key}]: {flavor_text} (Strategy: {strategy})"
370
-
371
- def tend_garden(self, clean_words: List[str]) -> List[str]:
372
- blooms = []
373
- if not self.seeds or not clean_words:
374
- return blooms
375
- lower_words = [w.lower() for w in clean_words]
376
- for seed in self.seeds:
377
- if seed.bloomed:
378
- continue
379
- if seed.water(lower_words):
380
- bloom_msg = seed.bloom()
381
- self.events.log(
382
- f"{Prisma.MAG}🌷 PARADOX BLOOM:{Prisma.RST} {bloom_msg}",
383
- "VILLAGE_EVENT",
384
- )
385
- blooms.append(f"{Prisma.MAG}🌷 PARADOX BLOOM:{Prisma.RST} {bloom_msg}")
386
- return blooms
387
-
388
- def conduct_census(self, packet: PhysicsPacket, host_stats: Any) -> str:
389
- latency = getattr(host_stats, "latency", 0.0) if host_stats else 0.0
390
- almanac = LoreManifest.get_instance().get("ALMANAC") or {}
391
- forecasts = almanac.get("FORECASTS", {})
392
-
393
- loc_name = "UNKNOWN"
394
- if self.navigator:
395
- current_node = self.navigator.world_graph.get(
396
- self.navigator.current_node_id
397
- )
398
- if current_node:
399
- loc_name = current_node.name
400
- if latency > 3.0:
401
- status = "HIGH_LATENCY"
402
- advice = "System lag detected."
403
- elif packet.voltage > BoneConfig.PHYSICS.VOLTAGE_HIGH:
404
- status = "HIGH_VOLTAGE"
405
- advice = random.choice(forecasts.get("HIGH_VOLTAGE", ["Manic energy."]))
406
- elif packet.narrative_drag > BoneConfig.PHYSICS.DRAG_HEAVY:
407
- status = "HIGH_DRAG"
408
- advice = random.choice(forecasts.get("HIGH_DRAG", ["Narrative stuck."]))
409
- else:
410
- status = "BALANCED"
411
- advice = random.choice(forecasts.get("BALANCED", ["Nominal."]))
412
- report = f"CENSUS [{loc_name}]: {status} | {advice}"
413
- news = self._get_town_news(latency, packet.voltage)
414
- if news:
415
- report += f"\n{news}"
416
- if packet.voltage > 20.0:
417
- report += f"\n{Prisma.RED}⚖️ COUNCIL ALERT: The Chairholder is drafting a restraining order.{Prisma.RST}"
418
- elif packet.voltage < 2.0 and packet.narrative_drag > 5.0:
419
- report += f"\n{Prisma.MAG}⚖️ COUNCIL ALERT: Strange Loops detected in the lower districts.{Prisma.RST}"
420
- elif status == "BALANCED" and self.rumors and random.random() < 0.3:
421
- rumor = random.choice(self.rumors)
422
- report += f"\n{Prisma.GRY}👀 RUMOR: {rumor}{Prisma.RST}"
423
- return report
424
-
425
- @staticmethod
426
- def _get_town_news(latency: float, volt: float) -> Optional[str]:
427
- if latency > 4.0:
428
- return f"{Prisma.OCHRE}📢 TOWN CRIER: The time-winds are slow!{Prisma.RST}"
429
- if volt > BoneConfig.PHYSICS.VOLTAGE_CRITICAL:
430
- return f"{Prisma.YEL}📢 HEAR YE: Voltage Critical!{Prisma.RST}"
431
- return None
432
-
433
- def on_item_drop(self, payload):
434
- item = payload.get("item")
435
- if item:
436
- self.events.log(f"Town Hall noticed you dropped {item}.", "VILLAGE")
437
-
438
- @staticmethod
439
- def diagnose_condition(
440
- session_data: dict, _host_health: Any = None, soul: Any = None
441
- ) -> Tuple[str, str]:
442
- meta = session_data.get("meta", {})
443
- trauma = session_data.get("trauma_vector", {})
444
- final_health = meta.get("final_health", 50)
445
- if soul:
446
- neglect = getattr(soul, "obsession_neglect", 0.0)
447
- if neglect > 8.0:
448
- obsession = getattr(soul, "current_obsession", "work")
449
- return "HIGH_DRAG", f"Guilt over '{obsession}' is thickening the air."
450
- if trauma:
451
- max_trauma = max(trauma, key=trauma.get) if trauma else "NONE"
452
- if trauma.get(max_trauma, 0) > 0.6:
453
- return (
454
- "HIGH_TRAUMA",
455
- f"Warning: High levels of {max_trauma} residue detected.",
456
- )
457
- if final_health < 30:
458
- return "HIGH_TRAUMA", "System critical. Structural damage."
459
- return "BALANCED", "System nominal."
460
-
461
-
462
- class DeathGen:
463
- _FALLBACK_PROTOCOLS = {
464
- "PREFIXES": ["FATAL ERROR", "SYSTEM HALT", "THE END"],
465
- "CAUSES": {"DEFAULT": ["Unknown Error", "Entropy limit reached"]},
466
- "VERDICTS": {"DEFAULT": ["End of Line.", "Reboot required."]},
467
- }
468
-
469
- @classmethod
470
- def load_protocols(cls):
471
- if LoreManifest.get_instance().get("DEATH") is None:
472
- LoreManifest.get_instance().inject("DEATH", cls._FALLBACK_PROTOCOLS)
473
-
474
- @staticmethod
475
- def eulogy(
476
- packet: PhysicsPacket, mito_state: Any, trauma_vector: Dict = None
477
- ) -> Tuple[str, str]:
478
- death_data = LoreManifest.get_instance().get("DEATH")
479
- if not death_data:
480
- death_data = DeathGen._FALLBACK_PROTOCOLS
481
- cause = DeathGen._determine_cause(packet, mito_state, trauma_vector)
482
- verdict_type = DeathGen._determine_verdict_type(packet, cause)
483
- prefix = random.choice(death_data.get("PREFIXES", ["Alas."]))
484
- cause_list = death_data["CAUSES"].get(
485
- cause, death_data["CAUSES"].get("DEFAULT", ["Error"])
486
- )
487
- verdict_list = death_data["VERDICTS"].get(
488
- verdict_type, death_data["VERDICTS"].get("HEAVY", ["Done."])
489
- )
490
- return (
491
- f"{prefix} CAUSE: {random.choice(cause_list)}. {random.choice(verdict_list)}",
492
- cause,
493
- )
494
-
495
- @staticmethod
496
- def _determine_cause(
497
- p: PhysicsPacket, mito_state: Any, trauma_vector: Dict = None
498
- ) -> str:
499
- if trauma_vector and sum(trauma_vector.values()) > 50.0:
500
- return "TRAUMA"
501
- atp = float(
502
- mito_state.get("atp", 0)
503
- if isinstance(mito_state, dict)
504
- else getattr(mito_state, "atp_pool", 0)
505
- )
506
- if atp <= BoneConfig.BIO.ATP_STARVATION:
507
- return "STARVATION"
508
- if p.voltage > BoneConfig.PHYSICS.VOLTAGE_CRITICAL:
509
- return "GLUTTONY"
510
- if p.narrative_drag > BoneConfig.PHYSICS.DRAG_HALT:
511
- return "BOREDOM"
512
- counts = p.counts or {}
513
- if counts.get("antigen", 0) > 5:
514
- return "TOXICITY"
515
- return "STARVATION"
516
-
517
- @staticmethod
518
- def _determine_verdict_type(p: PhysicsPacket, cause: str) -> str:
519
- if cause == "TOXICITY":
520
- return "TOXIC"
521
- if cause == "BOREDOM":
522
- return "BORING"
523
- if p.voltage > BoneConfig.PHYSICS.VOLTAGE_MED:
524
- return "LIGHT"
525
- return "HEAVY"