""" GlyphForge — Recursive Glyph Production Engine ============================================== Seed → Grammar → Mutation → Receipt → Score → Archive → New Seed A glyph is not just a symbol. It is a compressed executable concept. The engine generates infinite descendants from a master glyph, scoring each by compression, meaning density, executability, proof strength, transferability, novelty, and commercial usefulness. Master glyph: ⧉◇@L → H@L Æ R Æ λ⁻¹ = ◎ → $ """ import json import time import hashlib import random import os from dataclasses import dataclass, field, asdict from typing import Optional from pathlib import Path # --- Glyph Alphabet --- ALPHABET = { "□": "file", "◇": "artifact", "⧉": "stationary_object", "H": "hash_identity", "L": "location_anchor", "R": "receipt", "λ": "friction", "λ⁻¹": "transferability_force", "T": "time_anchor", "Σ": "shard_set", "M": "merkle_root", "ZK": "zero_knowledge_proof", "Æ": "bind", "→": "derive_transfer", "Δ": "change_delta", "◎": "verified", "✕": "invalid", "$": "financeable_value", "Ω": "canonical_source", "⟲": "recursive_loop", } # --- Grammar Rules --- GRAMMAR = [ {"pattern": "{obj}@{loc}", "expansion": "object anchored at location", "produces": ["□@L", "◇@L"]}, {"pattern": "{obj}@{loc} → {id}@{loc}", "expansion": "anchored object derives identity", "produces": ["□@L → H@L"]}, {"pattern": "{id} Æ {rec}", "expansion": "identity binds to receipt", "produces": ["H Æ R", "H@L Æ R"]}, {"pattern": "{rec} Æ {trans}", "expansion": "receipt binds to transferability", "produces": ["R Æ λ⁻¹"]}, {"pattern": "{bound} = {ver}", "expansion": "binding achieves verification", "produces": ["H@L Æ R Æ λ⁻¹ = ◎"]}, {"pattern": "{ver} → {val}", "expansion": "verified becomes financeable", "produces": ["◎ → $"]}, {"pattern": "{shards} → {merkle}", "expansion": "shards aggregate to merkle root", "produces": ["ΣH → M"]}, {"pattern": "{merkle} Æ {zk}", "expansion": "merkle root binds to ZK proof", "produces": ["M Æ ZK"]}, {"pattern": "{time} Æ {delta}", "expansion": "time binds to file delta", "produces": ["T₀→T₁ Æ Δ□"]}, {"pattern": "{art} Æ {val}", "expansion": "artifact becomes financeable", "produces": ["◇ Æ $"]}, {"pattern": "{file} stays @ {loc} ; {rec} travels →", "expansion": "zero-copy transfer", "produces": ["□ stays @L ; R travels →"]}, {"pattern": "{lambda}↓ → {trans}↑", "expansion": "lower friction increases transferability", "produces": ["λ↓ → T↑"]}, {"pattern": "{art} = {id}@{loc} Æ {rec} Æ {trans} Æ {val}", "expansion": "full financeable artifact", "produces": ["◇ = H@L Æ R Æ λ⁻¹ Æ $"]}, {"pattern": "{delta_file} → {delta_hash} Æ {time}", "expansion": "file change produces delta hash bound to time", "produces": ["Δ□ → HΔ Æ T"]}, {"pattern": "{build} → {rec} Æ {ver}", "expansion": "build passes and receipt verifies", "produces": ["Build ✓ → R Æ ◎"]}, ] MASTER_GLYPH = "⧉◇@L → H@L Æ R Æ λ⁻¹ = ◎ → $" MUTATION_OPS = [ "bind_two", "split_shards", "invert_lambda", "attach_time", "attach_location", "attach_receipt", "attach_value", "replace_copy_with_zerocopy", "compress_to_symbol", "expand_to_schema", ] @dataclass class ForgedGlyph: glyph_id: str = "" symbol: str = "" plain_english: str = "" role: str = "" parents: list = field(default_factory=list) mutation: str = "" hash: str = "" score: float = 0.0 score_breakdown: dict = field(default_factory=dict) created_at: float = 0.0 machine_payload: dict = field(default_factory=dict) generation: int = 0 def to_dict(self) -> dict: return asdict(self) def score_glyph(symbol: str, plain_english: str, role: str, machine_payload: dict) -> tuple[float, dict]: """Score a glyph by compression, meaning, executability, proof, transferability, novelty.""" breakdown = { "compression": 0.0, "meaning_density": 0.0, "machine_executability": 0.0, "proof_strength": 0.0, "transferability": 0.0, "novelty": 0.0, "commercial_usefulness": 0.0, "ambiguity_penalty": 0.0, "decorative_noise_penalty": 0.0, } token_count = len(symbol.replace(" ", "").split("Æ")) + symbol.count("→") + 1 meaning_tokens = sum(1 for t in ALPHABET if t in symbol) breakdown["compression"] = min(10, meaning_tokens / max(token_count, 1) * 5) breakdown["meaning_density"] = min(10, meaning_tokens * 1.5) if machine_payload: executable_keys = sum(1 for k in machine_payload if k in ("object", "anchor", "proof", "state", "metric")) breakdown["machine_executability"] = min(10, executable_keys * 2) proof_tokens = sum(1 for t in ["H", "R", "M", "ZK", "◎"] if t in symbol) breakdown["proof_strength"] = min(10, proof_tokens * 2.5) if "λ⁻¹" in symbol or "λ↓" in symbol: breakdown["transferability"] = 8.0 elif "λ" in symbol: breakdown["transferability"] = 4.0 if "$" in symbol: breakdown["commercial_usefulness"] = 9.0 elif "◎" in symbol: breakdown["commercial_usefulness"] = 6.0 unique_chars = len(set(symbol.replace(" ", ""))) breakdown["novelty"] = min(10, unique_chars / 3) decorative = sum(1 for c in symbol if c in "✦⟁☍⌁✧✩✪") breakdown["decorative_noise_penalty"] = decorative * 2 if meaning_tokens < 2: breakdown["ambiguity_penalty"] = 5.0 total = sum(v for k, v in breakdown.items() if not k.endswith("penalty")) total -= sum(v for k, v in breakdown.items() if k.endswith("penalty")) return round(total, 2), breakdown def mutate_glyph(parent_symbol: str, parent_english: str, mutation: str) -> tuple[str, str, str, dict]: """Apply a mutation operation to a parent glyph.""" mutations = { "bind_two": lambda s, e: (s + " Æ R", e + " bound to receipt", "receipt_binding", {"object": "file", "proof": "receipt"}), "split_shards": lambda s, e: ("Σ" + s.replace("◇", "").replace("□", ""), e + " sharded into pieces", "shard_split", {"shards": True, "merkle": True}), "invert_lambda": lambda s, e: (s.replace("λ", "λ⁻¹") if "λ" in s and "λ⁻¹" not in s else s + " Æ λ⁻¹", e + " with transferability force", "lambda_inversion", {"metric": "inverse_lambda"}), "attach_time": lambda s, e: (s + " Æ T", e + " anchored in time", "time_anchor", {"time": True}), "attach_location": lambda s, e: (s + " @L" if "@L" not in s else s, e + " anchored at location", "location_anchor", {"anchor": "location"}), "attach_receipt": lambda s, e: (s + " Æ R" if "R" not in s else s, e + " with receipt proof", "receipt_attach", {"proof": "receipt"}), "attach_value": lambda s, e: (s + " → $", e + " becomes financeable", "value_attach", {"economic_target": "paid"}), "replace_copy_with_zerocopy": lambda s, e: (s.replace("→ □", "→ R") if "→ □" in s else "□ stays @L ; R travels →", e + " (zero-copy: file stays, receipt travels)", "zero_copy", {"zero_copy": True}), "compress_to_symbol": lambda s, e: ("◇=H@LÆRÆλ⁻¹=◎→$" if len(s) > 20 else s, "compressed: " + e, "compression", {"compressed": True}), "expand_to_schema": lambda s, e: (s, e + " expanded to machine schema", "schema_expansion", {"object": "artifact", "anchor": "location", "proof": "receipt", "metric": "lambda", "state": "verified"}), } op = mutations.get(mutation, mutations["bind_two"]) new_symbol, new_english, role, payload = op(parent_symbol, parent_english) return new_symbol, new_english, role, payload class GlyphForge: """Recursive glyph production engine.""" def __init__(self, max_generations: int = 10, min_score: float = 20.0): self.max_generations = max_generations self.min_score = min_score self.ledger: list[ForgedGlyph] = [] self.archive: dict[str, ForgedGlyph] = {} self.seed_glyph = MASTER_GLYPH self.seed_english = "A stationary artifact at location becomes hash-bound, receipt-bound, transferable, verified, and financeable." def forge(self, seed_symbol: str = None, seed_english: str = None, generations: int = None) -> list[ForgedGlyph]: """Run the forge loop: seed → mutate → score → archive → new seed.""" gens = generations or self.max_generations current_symbol = seed_symbol or self.seed_glyph current_english = seed_english or self.seed_english # Seed glyph seed = self._create_glyph(current_symbol, current_english, "master_seed", [], "seed", {}, gen=0) self.ledger.append(seed) self.archive[seed.glyph_id] = seed frontier = [seed] all_glyphs = [seed] for gen in range(1, gens + 1): next_frontier = [] for parent in frontier: for mutation in MUTATION_OPS: new_symbol, new_english, role, payload = mutate_glyph( parent.symbol, parent.plain_english, mutation ) if new_symbol == parent.symbol and new_english == parent.plain_english: continue child = self._create_glyph( new_symbol, new_english, role, [parent.glyph_id], mutation, payload, gen ) if child.score >= self.min_score: self.ledger.append(child) self.archive[child.glyph_id] = child all_glyphs.append(child) next_frontier.append(child) if not next_frontier: break # Keep top 5 per generation to prevent explosion next_frontier.sort(key=lambda g: g.score, reverse=True) frontier = next_frontier[:5] return all_glyphs def _create_glyph(self, symbol: str, english: str, role: str, parents: list, mutation: str, payload: dict, gen: int) -> ForgedGlyph: score, breakdown = score_glyph(symbol, english, role, payload) glyph_id = hashlib.sha256((symbol + str(time.time()) + str(gen)).encode()).hexdigest()[:12] return ForgedGlyph( glyph_id=glyph_id, symbol=symbol, plain_english=english, role=role, parents=parents, mutation=mutation, hash=hashlib.sha256(symbol.encode()).hexdigest(), score=score, score_breakdown=breakdown, created_at=time.time(), machine_payload=payload, generation=gen, ) def top_glyphs(self, n: int = 10) -> list[dict]: """Get the top N glyphs by score.""" sorted_glyphs = sorted(self.ledger, key=lambda g: g.score, reverse=True) return [g.to_dict() for g in sorted_glyphs[:n]] def by_generation(self) -> dict[int, list[dict]]: """Group glyphs by generation.""" gens: dict[int, list[dict]] = {} for g in self.ledger: gens.setdefault(g.generation, []).append(g.to_dict()) return gens def stream(self, n: int = 20) -> list[dict]: """Simulate a live production ticker.""" results = [] t = time.time() for i, g in enumerate(sorted(self.ledger, key=lambda x: x.created_at)[:n]): results.append({ "timestamp": time.strftime("%H:%M:%S", time.localtime(g.created_at)), "symbol": g.symbol, "score": g.score, "role": g.role, "gen": g.generation, }) return results def to_json(self) -> str: return json.dumps({ "master_glyph": self.seed_glyph, "total_glyphs": len(self.ledger), "generations": max(g.generation for g in self.ledger) if self.ledger else 0, "top": self.top_glyphs(10), "ledger": [g.to_dict() for g in self.ledger], }, indent=2)