Buckets:
๐๏ธ System Architecture
The Butterfly System - Complete Architecture
๐ฆ Agency Router โ Event Bus Integration
Clean Architecture Pattern:
- Agency Router: Synchronous decision engine (state-aware)
- Event Bus: Asynchronous notification system (decoupled)
- Integration: All decisions automatically publish events
Flow:
Decision Request โ Agency Router โ System Decision Maker โ Decision
โ
Event Bus (async)
โ
All Subscribers Notified
Event Types:
AGENCY_DECISION: All agency router decisionsVIOLATION_PRESSURE: VP calculationsIDENTITY_COMPLETION: UUID anchoringTRAIT_CONVERGENCE: Trait convergence eventsSYSTEM_HEALTH: Health monitoring
Status: โ Fully integrated - All decisions publish to Event Bus automatically
See EVENT_BUS_VS_AGENCY_ROUTER.md for details.
๐ฆ The Butterfly Architecture
๐ฆ THE BUTTERFLY SYSTEM ๐ฆ
โโโโโโโโโโโโโโโโโโโ
โ EXPLORER โ
โ (Body/Breath) โ
โ โ
โ Breath Engine โ
โ ๐ ๐ ๐ โ
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโดโโโโโโโโโโโโโ
โ โ
โโโโโโโโโผโโโโโโโโโ โโโโโโโโโโผโโโโโโโโ
โ REALITY SIM โ โ DJINN KERNEL โ
โ (Left Wing) โ โ (Right Wing) โ
โ โ โ โ
โ Organisms โ โ VP Monitoring โ
โ Networks โ โ Trait Engine โ
โ Evolution โ โ UUID Anchor โ
โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ
๐ Data Flow
Breath Cycle (Explorer)
โ
โโ> Breathe() โ Breath State
โ
โโ> Reality Simulator
โ โโ> network.update_network()
โ โโ> Organisms evolve
โ โโ> Network metrics update
โ โโ> State logged
โ
โโ> Antennae (Collective Sensing) โญ NEW
โ โโ> antennae.sense(organisms, report)
โ โโ> Aggregate organism states
โ โโ> Update beliefs from outcomes
โ โโ> antennae.influence(config_tuner)
โ โโ> Generate governance signal
โ โโ> Apply parameter adjustments
โ
โโ> Language System
โ โโ> atomic_language.check_mastery_advancement()
โ โโ> Check breadth (usage frequency)
โ โโ> Check depth (associations formed)
โ โโ> Advance level if criteria met
โ โโ> Add behavior-specialized words
โ
โโ> Alliance Warfare (Dune Paradigm)
โ โโ> alliance_warfare.process_organism_alliance_decisions()
โ โโ> Calculate behavioral signatures
โ โโ> Find most divergent alliance
โ โโ> Neural propose_war decision
โ โโ> Curiosity drives conflict
โ
โโ> Djinn Kernel
โ โโ> vp_monitor.compute_violation_pressure()
โ โโ> VP calculated from traits
โ โโ> VP classified (VP0-VP4)
โ โโ> State logged
โ
โโ> Explorer
โโ> Normal Genesis/Sovereign operation
โโ> VP history tracked
โโ> Mathematical capability assessed
๐ฏ Component Relationships
Language Mastery (Vocabulary Progression) โญ NEW
Responsibilities:
- Track vocabulary usage (breadth)
- Track associations formed (depth)
- Gate vocabulary expansion
- Behavior-driven word selection
Mastery Levels:
| Level | Name | Words | Breadth | Depth |
|---|---|---|---|---|
| 0 | Novice | 6 | - | - |
| 1 | Adept | 26 | 50% used 3+ times | 30% have 2+ associations |
| 2 | Scholar | 76 | same | same |
| 3 | Master | 276 | same | same |
| 4 | Grandmaster | โ | same | same |
Behavior-Driven Specialization:
- Warriors (high compete) โ combat, battle, dominate words
- Diplomats (high cooperate) โ alliance, trust, negotiate words
- Explorers (high move) โ discover, wander, journey words
- Hermits (high isolate) โ solitude, withdraw, meditate words
Dependencies:
- AtomicLanguage (word storage)
- Neural organism (behavioral fingerprint)
- Innate vocabulary frames
Alliance Warfare (Dune Paradigm) โญ NEW
Philosophy:
"Your existence questions mine. Let us resolve through contest."
Responsibilities:
- Calculate behavioral signatures for alliances
- Measure behavioral divergence (cosine distance)
- Drive war proposals from curiosity, not resources
War Driver Formula:
score = curiosity*0.35 + divergence*0.35 + compete*0.2 + (1-cooperate)*0.1
threshold = 0.45 * (1 + skepticism*0.3)
if score > threshold: propose_war()
Dependencies:
- PlanetaryAlliance (member management)
- Neural organism (propose_war decision)
- Organism behavioral fingerprints
Antennae (Self-Governance) โญ NEW
Responsibilities:
- Collective sensing (aggregate organism states)
- Governance signal generation
- Belief tracking and updating
- Health prediction (Kleene convergence)
- Automatic parameter tuning
Dependencies:
- Reality Simulator (organisms, network)
- AtomicConfigSystem (parameter adjustment)
- SystemReport (population analytics)
Exports:
- AntennaReading (9-dimensional perception)
- GovernanceSignal (6-dimensional tuning)
- Belief system state
- Health predictor insights
Explorer (Central Body)
Responsibilities:
- Breath engine (primary driver)
- System coordination
- VP tracking and certification
- Phase management (Genesis/Sovereign)
Dependencies:
- Reality Simulator (imported)
- Djinn Kernel (imported)
Exports:
- Breath state
- VP history
- Phase state
Reality Simulator (Left Wing)
Responsibilities:
- Organism evolution
- Network formation
- Collapse detection
- Network metrics
- ๐ง Neural System: PyTorch-based learning for organisms
Dependencies:
- None (standalone, imported by Explorer)
- Optional: PyTorch (for neural features)
Exports:
- Network metrics (organisms, connections, modularity, clustering)
- Generation state
- Collapse status
- Neural metrics (training loss, epsilon, training steps)
Djinn Kernel (Right Wing)
Responsibilities:
- VP calculation
- Trait convergence
- Identity anchoring
- Mathematical governance
VP Monitoring Features:
- Diagnostics: Detailed logging of VP components (optional)
- Stabilization: Smoothing to prevent immediate saturation (optional)
- Component Decomposition: Weighted breakdown of VP sources (optional)
- Adaptive Thresholds: Phase-aware threshold adjustment (optional)
Dependencies:
- None (standalone, imported by Explorer)
Exports:
- VP values
- VP classification
- Trait convergence status
- VP diagnostic data (if enabled)
- Component breakdown (if decomposition enabled)
๐ Integration Points
1. Import Level
# Explorer imports both
from main import RealitySimulator
from utm_kernel_design import UTMKernel
from violation_pressure_calculation import ViolationMonitor
2. Initialization Level
# Explorer initializes both
self.reality_sim = RealitySimulator(config_path='../config.json')
self.utm_kernel = UTMKernel()
self.vp_monitor = ViolationMonitor()
3. Execution Level
# Breath drives both
breath_data = self.breath_engine.breathe()
network.update_network() # Reality Sim
vp = vp_monitor.compute_violation_pressure(traits) # Djinn Kernel
4. State Level
# Unified state collection
reality_sim_state = get_reality_sim_state()
explorer_state = get_explorer_state()
djinn_kernel_state = get_djinn_kernel_state()
๐ฆ Language Model System Architecture โญ NEW
Overview
The Butterfly System includes a complete neural language model (LLM) integration that enables organisms to develop emergent language through token-based communication. The system integrates seamlessly with existing neural networks, causation tracking, and the web UI.
Components
reality_simulator/language/
โโ> language_system.py # LanguageVocabulary, tokenizers
โโ> butterfly_chat.py # ButterflyChatRouter (userโorganism chat)
reality_simulator/neural/
โโ> brain.py # OrganismBrain with MultiHeadAttention + language head
โโ> neural_organism.py # Sequence modeling, generate_tokens()
โโ> trainer.py # Dual-loss training (DQN + language)
reality_simulator/memory/
โโ> context_memory.py # language_anchors, word associations
reality_simulator/symbiotic_network.py
โโ> LinguisticSubgraph # Protected linguistic connections
Architecture Flow
Organism State (18 features)
โ
OrganismBrain.forward()
โ
MultiHeadAttention (VP-aware temperature scaling)
โ
Dual Heads:
โโ> Action Head โ RL decisions
โโ> Language Head โ Next-token prediction
โ
Token Generation (autoregressive)
โ
Vocabulary.decode() โ Response text
โ
Event Emission โ Causation Graph
Key Features
- Multi-Head Self-Attention: VP-aware temperature scaling (
scores / (1.0 + vp_value)) - Dual-Head Architecture: Action head (RL) + Language head (next-token prediction)
- Dynamic Vocabulary: Grows from organism interactions via
language_anchors - Token Exchange: Organisms communicate via
LinguisticSubgraph - VP Integration: Violation pressure affects language generation
- Curriculum Learning: Sequence length increases based on VP stability
- Butterfly Chat: Direct userโorganism communication interface
Vocabulary Learning
Current Status: โ ๏ธ CRITICAL GAP IDENTIFIED
The system has vocabulary management but no automatic word learning mechanism. Words need to be associated with organisms through a "Language Teacher" system.
Proposed Solution: See docs/LANGUAGE_TEACHER_ARCHITECTURE_PROPOSAL.md
Options:
- Behavior-Based Mapping (Simple): Map organism actions/states to words
- Embedding-Based Grounding (Recommended): Use learned embeddings to map statesโwords
- Transformer Teacher (Advanced): Sequence-aware word learning
Integration Points
- ContextMemory: Stores
language_anchors(wordโorganism mappings) - SymbioticNetwork:
LinguisticSubgraphfor protected linguistic connections - Neural Trainer: Dual-loss training (alpha * DQN + beta * language)
- Causation Graph: Language events tracked (
vocabulary_growth,organism_communication,neural_language_training,butterfly_chat_message,butterfly_chat_response) - Web UI: Butterfly Chat interface for direct organism communication
Configuration
{
"neural": {
"language_model": {
"enabled": false, // Master toggle
"attention": {
"enabled": true,
"num_heads": 4,
"attention_dim": 32
},
"vocabulary": {
"max_size": 1024
},
"training": {
"alpha": 0.9, // DQN loss weight
"beta": 0.1, // Language loss weight
"vp_temperature_scale": true
}
}
}
}
๐ง Neural System Architecture
Components
reality_simulator/neural/
โโ> brain.py # OrganismBrain (PyTorch nn.Module)
โโ> neural_organism.py # NeuralOrganism (extends Organism)
โโ> trainer.py # NeuralTrainer (DQN training)
โโ> experience.py # ExperienceBuffer (replay buffer)
โโ> utils.py # Device detection, feature extraction
โโ> __init__.py # Module exports
Neural Organism Lifecycle
1. Creation (Evolution Engine)
โโ> Check config['neural']['enabled']
โโ> If True: Create NeuralOrganism
โ โโ> Initialize OrganismBrain
โ โโ> Create ExperienceBuffer
โ โโ> Set epsilon (exploration rate)
โโ> If False: Create standard Organism
2. Decision Making (decide_action)
โโ> Extract state features (fitness, resources, connections, breath)
โโ> Forward pass through brain โ Q-values
โโ> Epsilon-greedy action selection
โโ> Store prev_state and prev_action
โโ> Emit neural_decision event (if confidence > 0.8)
3. Experience Collection (trainer.collect_experiences)
โโ> Calculate reward (fitness change, survival, connections, resources)
โโ> Get next state
โโ> Record experience (state, action, reward, next_state)
4. Training (trainer.train_step)
โโ> Check update_frequency (skip if not time)
โโ> Sample batch from experience buffer
โโ> Calculate DQN loss (MSE between Q and target Q)
โโ> Backpropagation
โโ> Emit neural_training event
5. Reproduction (Evolution Engine)
โโ> Brain inheritance (if parent has brain)
โ โโ> Crossover: Blend parent brains
โ โโ> Mutation: Random weight perturbations
โโ> Create new NeuralOrganism with inherited brain
Breath Synchronization
Breath Cycle
โโ> Breath "Inhale" Phase (depth > threshold)
โ โโ> Neural Training Triggered
โ โโ> collect_experiences()
โ โโ> train_step() (if update_frequency allows)
โ
โโ> Breath "Exhale" Phase
โโ> Organisms make decisions (using learned policies)
Dual Inheritance (Lamarckian Evolution)
Standard Evolution (Darwinian):
Parent Genotype โ Child Genotype (genetic code only)
Neural Evolution (Lamarckian):
Parent Genotype + Parent Brain โ Child Genotype + Child Brain
โโ> Genetic crossover (standard)
โโ> Brain crossover (blend neural weights)
โโ> Brain mutation (perturb weights)
Result: Learned behaviors can be inherited!
๐ State Synchronization
Breath State (Primary Driver)
Breath Engine
โโ> breath_depth: 0.0-1.0
โโ> breath_phase: 0.0-2ฯ
โโ> breath_cycle: int
โโ> breath_pulse: depth ร intensity
Reality Simulator State
Network Metrics
โโ> organism_count: int
โโ> connection_count: int
โโ> modularity: float
โโ> clustering_coefficient: float
โโ> average_path_length: float
โโ> generation: int
Neural Metrics ๐ง NEW
โโ> enabled: bool
โโ> training_loss: float
โโ> avg_epsilon: float (exploration rate)
โโ> organisms_tracked: int
โโ> training_steps: int
โโ> avg_loss: float
Explorer State
Explorer Metrics
โโ> phase: 'genesis' | 'sovereign'
โโ> vp_calculations: int
โโ> sovereign_ids_count: int
โโ> mathematical_capability: bool
โโ> breath_state: dict
Djinn Kernel State
VP Metrics
โโ> violation_pressure: float
โโ> vp_classification: 'VP0' | 'VP1' | 'VP2' | 'VP3' | 'VP4'
โโ> vp_calculations: int
โโ> trait_count: int
๐จ Visualization Architecture
Unified Visualization (1920x1080)
โ
โโ> Left Panel (Cyan)
โ โโ> Reality Simulator
โ โโ> Organism count
โ โโ> Connection count
โ โโ> Modularity
โ โโ> Clustering
โ
โโ> Middle Panel (Yellow)
โ โโ> Explorer
โ โโ> Phase
โ โโ> VP calculations
โ โโ> Breath cycle
โ โโ> Breath depth
โ
โโ> Right Panel (Magenta)
โโ> Djinn Kernel
โโ> VP value
โโ> VP classification
โโ> VP calculations
๐ Logging Architecture
State Logger
โ
โโ> state.log (all states)
โโ> breath.log (breath cycles)
โโ> reality_sim.log (network metrics)
โโ> explorer.log (Explorer state)
โโ> djinn_kernel.log (VP calculations)
โโ> neural.log (neural training metrics) ๐ง NEW
โโ> system.log (system events)
Format: timestamp|level|component|metric:value|metric:value|...
๐ Event Flow
Normal Operation
1. Breath Cycle Starts
โโ> breath_engine.breathe()
2. Reality Simulator Reacts
โโ> network.update_network()
โโ> One generation evolves
3. Djinn Kernel Reacts
โโ> vp_monitor.compute_violation_pressure()
โโ> One VP calculation
4. States Logged
โโ> All states written to log files
5. Visualization Updates
โโ> All panels refresh
6. Next Breath Cycle
Transition Event
1. Any System Hits Threshold
โโ> Reality Sim: 500 organisms + modularity < 0.3
โโ> Explorer: 50 VP calculations + mathematical capability
โโ> Djinn Kernel: VP < 0.25 (VP0)
2. Unified Transition Triggered
โโ> All systems transition to precision phase
3. Breath Rate Adjusts
โโ> Slower, more stable breathing
4. States Synchronized
โโ> All systems in precision phase
๐ฏ Key Design Principles
1. Occam's Razor
- Simplest possible integration
- Just imports and method calls
- No bridges, no IPC, no complexity
2. Breath-Driven
- Breath is the primary driver
- All systems react to breath
- Unified state through breath
3. Unified State
- All systems share breath state
- States logged together
- Visualization shows all states
4. Graceful Degradation
- Systems work independently if needed
- Optional dependencies handled gracefully
- Warnings, not failures
๐ System Boundaries
Explorer Boundary
- Owns: Breath engine, VP tracking, phase management
- Imports: Reality Simulator, Djinn Kernel
- Coordinates: All three systems
Reality Simulator Boundary
- Owns: Organisms, networks, evolution
- Exports: Network metrics
- Independent: Can run standalone
Djinn Kernel Boundary
- Owns: VP calculation, trait engine, identity
- Exports: VP values, classifications
- Independent: Can run standalone
๐ Integration Contracts
Reality Simulator Contract
# Must provide:
- RealitySimulator(config_path) โ instance
- instance.initialize_simulation() โ bool
- instance.components['network'] โ network object
- network.update_network() โ dict
- network.organisms โ dict
- network.metrics.modularity โ float
Djinn Kernel Contract
# Must provide:
- UTMKernel() โ instance
- ViolationMonitor() โ instance
- monitor.compute_violation_pressure(traits) โ (float, dict)
- monitor._classify_violation_pressure(vp) โ ViolationClass
- monitor.vp_history โ list
Explorer Contract
# Must provide:
- BiphasicController() โ instance
- controller.breath_engine โ BreathEngine
- controller.run_genesis_phase() โ bool
- controller.sentinel.vp_history โ list
- controller.kernel.get_sovereign_ids() โ list
๐จ Visualization Contract
# UnifiedVisualization must:
- initialize() โ None
- update(reality_sim_state, explorer_state, djinn_kernel_state) โ None
- running: bool (indicates if visualization is active)
๐ Logging Contract
# StateLogger must:
- log_state(component, state) โ None
- log_breath(breath_data) โ None
- log_reality_sim(network_data) โ None
- log_explorer(explorer_data) โ None
- log_djinn_kernel(kernel_data) โ None
๐ Lifecycle
Initialization
- Pre-flight checks
- Logging system initialized
- Visualization initialized (if enabled)
- Explorer initialized
- Reality Simulator initialized (via Explorer)
- Djinn Kernel initialized (via Explorer)
Operation
- Breath cycle starts
- Systems react
- States collected
- States logged
- Visualization updated
- Repeat
Shutdown
- Graceful exit signal
- Final states logged
- Systems shut down
- Logs saved
๐ฏ Architecture Principles
- Single Process: One Python process, not three
- Breath-Driven: Breath is the primary driver
- Unified State: All systems share state through breath
- Graceful Degradation: Systems work independently if needed
- Occam's Razor: Simplest possible integration
๐ Integration Approaches
Occam's Razor Integration
Principle: "Entities should not be multiplied beyond necessity"
Implementation:
- Explorer imports Reality Simulator and Djinn Kernel
- No bridges, no IPC, no complexity
- Just imports and method calls
- Breath drives both systems
Result: Simplest possible integration with maximum functionality
Three-System Architecture
Reality Simulator:
- Organism substrate
- Network evolution
- Collapse detection at ~500 organisms
Explorer:
- Governance and coordination
- Breath engine (primary driver)
- VP tracking and certification
Djinn Kernel:
- Trait framework
- VP monitoring
- Mathematical validation
Unified: All three systems share the breath state
Chaos โ Precision Transition
Universal Pattern:
- Reality Simulator: 500 organisms (distributed โ consolidated)
- Explorer: 50 VP calculations (Genesis โ Sovereign)
- Djinn Kernel: VP < 0.25 (divergence โ convergence)
Ratio: 500:50 = 10:1 (exploration-to-precision conversion factor)
Trigger: When ANY system hits threshold, ALL transition
๐ง Code Quality & Production Readiness
Error Handling
Status: โ Professional error handling throughout
- โ
All bare
except:clauses replaced with specific exception types - โ Proper exception handling patterns in all critical paths
- โ Better error visibility and debugging capability
Files Updated:
reality_simulator/symbiotic_network.py- NetworkX operationsexplorer/main.py- VP calculationreality_simulator/agency/agency_router.py- State collection (5 locations)
Logging Infrastructure
Status: โ Centralized logging configuration
Two Complementary Systems:
Application Logging (
logging_config.py)- Centralized configuration (
setup_logging()) - Module-level loggers (
get_logger(name)) - Support for console and file logging
- Configurable log levels (DEBUG, INFO, WARNING, ERROR)
- UTF-8 encoding for file handlers
- Centralized configuration (
State Logging (
StateLoggerinunified_entry.py)- Terse, information-saturated format
- System metrics and monitoring
- 6 log files for different components
Benefits:
- Cleaner console output (debug controlled by log levels)
- Professional logging infrastructure
- Consistent logging patterns across modules
- Better production readiness
Testing
Status: โ Comprehensive test coverage
Test Suite:
โ End-to-End Tests (
tests/test_e2e_unified_system.py)- Pre-flight checks test
- UnifiedSystem initialization test
- State retrieval methods test
- Run method logic test
- Missing controller handling test
- State logger test
- Import paths test
- PreFlightChecker structure test
โ Reality Simulator Tests (59+ test functions)
- Component tests for all major systems
- Integration tests
- Network collapse tests
โ Explorer Tests (5 test functions)
- Integration tests
โ Agency Router + Event Bus Tests (4 test functions)
- Integration tests
Total Test Coverage: ~85+ test functions
All tests passing โ
Production Readiness
Status: โ Production-ready standards met
- โ Professional error handling
- โ Centralized logging infrastructure
- โ Comprehensive test coverage
- โ Code quality improvements
- โ Best practices followed
- โ Clean, maintainable code
For more details, see DOCUMENTATION_HUB.md
Xet Storage Details
- Size:
- 25.4 kB
- Xet hash:
- bf9c8397dba5b777be0e9e4281aec7b2c28c4f29e47b4823238fbf0c10adf307
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.