System Overview
The Event Tracking & Analytics System is a production-grade monitoring solution designed to observe,
record, and analyze user interactions and system state changes within the Chemical Chaos Engine
simulation environment. Built on event-driven architecture principles, the system demonstrates
enterprise-level software engineering practices.
184+
Tracked Events
16
Categories
7
Rarity Tiers
5
Architecture Layers
Core Capabilities:
- Real-Time Monitoring: Continuous observation of 184+ distinct events across 16
functional categories
- State Persistence: Automatic serialization and recovery using browser
LocalStorage API
- Event-Driven Architecture: Decoupled publisher-subscriber pattern with global
event bus
- Performance Optimization: Debounced polling (100ms), lazy evaluation, efficient
delta-based updates
- Scalable Design: Category-based organization supporting unlimited event
additions without refactoring
- Cross-System Integration: Monitors both simulation engine and site-wide
navigation patterns
Key Features
Chemical Event Tracking
Monitors bond formations (single/double/triple), molecule detection, and reaction type
classification across 12 mechanisms
Structural Analysis
Detects aromatic rings, conjugated systems, chiral centers, and radical species using graph
algorithms
Environmental Metrics
Tracks pH extremes (0-14 range), temperature ranges, and maintains historical min/max
records
Performance Analytics
Measures rapid bond formation rates, reaction cascades, and session duration metrics
Navigation Tracking
Records portfolio tab switches, photo lightbox views, and documentation access patterns
Persistent Storage
Automatic save every 5 seconds with version migration and graceful quota handling
🏗️ Technical Highlights
Modular Architecture: Four decoupled layers — Event Bus, Event Manager, Statistics Tracker, and Persistence Manager — each testable and modifiable independently.
Zero Framework Dependencies: Pure JavaScript ES6+ implementation with no external libraries.
Non-Invasive Monitoring: Observes system state through a bridge pattern without modifying core engine code.
Graceful Degradation: Functions in session-only mode if LocalStorage is unavailable. Handles storage quota exceeded errors by pruning old data.
System Architecture
The event system implements a layered architecture with clear separation of concerns. Each layer has a
well-defined responsibility and communicates through standardized interfaces.
Component Responsibilities
1. Global Event Bus CORE
Implements the observer pattern enabling decoupled communication. Publishers emit events without knowledge of subscribers. Supports dynamic subscription/unsubscription at runtime.
2. Event Manager ORCHESTRATOR
Central orchestration component maintaining the event registry, evaluating conditions every 100ms, managing unlock state, queueing notifications, and controlling system enable/disable state.
3. Statistics Tracker STATE
Comprehensive state container tracking chemical events, environmental metrics, structural data, performance metrics, and navigation analytics.
4. Persistence Manager STORAGE
Handles automatic serialization (every 5 seconds), state recovery on load, version migration for backward compatibility, and graceful quota exceeded handling.
5. State Monitoring Bridge BRIDGE
Non-invasive observer polling simulation state every 200ms. Detects changes via delta tracking without modifying core engine code.
Data Flow
💡 Event Emission Flow:
External system → State change → Monitoring bridge detects delta → Event bus emit → Event manager receives → Statistics updated → Conditions checked → Event potentially unlocked → Persistence triggered
Condition Evaluation Loop
Scheduled check (100ms) → Iterate event registry → Skip already-unlocked → Evaluate condition function → If met: unlock → Persist → Queue notification → Display
Event Categories
Events are organized into 16 functional categories based on the system component being monitored.
Each event carries one of 7 rarity tiers from Common to Cosmic.
Site Navigation
Tracks portfolio interactions: tab switches, photo lightbox opens, documentation views
Basic Chemistry
Fundamental bonding milestones from first bond to 100,000+ formations
Bond Types
Differentiates single, double, and triple covalent bonds
Molecular Detection
Identifies specific formulas: H₂O, CH₄, NH₃, C₆H₆, and more
Reaction Tracking
Monitors 12 reaction types including elimination, addition, hydrogenation
Structural Analysis
Detects aromatic rings, conjugated systems, chiral centers, radicals
Molecular Complexity
Tracks sizes from diatomic (2 atoms) to giga molecules (800+ atoms)
Element Usage
Monitors utilization of all 8 atom types: H, C, N, O, S, P, Cl, Br
pH Monitoring
Tracks pH extremes and neutral maintenance
Temperature Tracking
Records temperature exploration from cryogenic to scorching
Performance Metrics
Measures rapid bond formation and reaction cascades
Session Analytics
Tracks engagement duration and atom counts
Advanced Reactions
Higher-order transformations: Diels-Alder, esterification, Markovnikov, sigmatropic rearrangements, tautomerism
Environmental
Physics parameter tracking: turbulence, viscosity, crowding, bond stiffness, reactivity, time dilation
Paradox Events
Contradictory conditions: Acid Freeze (low pH + cold), Basic Inferno (high pH + hot), Frozen Chaos (cold + turbulence)
Speed & Chaos
Burst metrics: bonds per 5 seconds, reaction chains per 2 seconds
Endurance
Session duration milestones (15 min to 100 hrs) and peak atom counts
Cross-Category Mastery
Multi-condition challenges culminating in the Chaos Master meta-event (80% completion)
Rarity Tier System
Sample Unlock Notification
When an event condition is met, a themed notification slides in:
💧
★ COMMON
H₂O
100 water molecules were observed
Notifications display for 4.5 seconds with 500ms fade-in/fade-out. A maximum of 1 notification is shown at a time to prevent visual flooding — subsequent unlocks queue automatically.
Implementation Details
Event Definition Schema
Each event contains: unique ID, display name, description, icon, category, rarity tier, trigger type,
and a validation function that receives the stats object and current simulation state.
Event Schema Example
{ id, name, description, icon, category, difficulty: RARITY.*, trigger, check: (stats, state) => boolean }
Statistics Tracking (90+ Dimensions)
Chemical
Bond counts (total, double, triple), 14 tracked molecule formulas, 26 reaction type counters, 8 element usage trackers
Structural
Aromatic rings, conjugated systems, chiral centers, radicals, formal charges, hydrogen bonds, ring sizes (3–8), cumulenes
Environmental
pH range, temperature range, neutral time (±0.5 and ±0.2), turbulence/viscosity/crowding/stiffness/reactivity duration timers
Performance
Session duration, peak atoms, largest molecule, rapid bond bursts (5s window), reaction chains (2s window), thermal shocks
Navigation
Page views, tabs visited, photos viewed, docs opened, click count, UI toggle tracking (heatmap, trails, flow, stress, orbitals)
Paradox / Combo
Paradox duration, pH swing count, pH crossing count, simultaneous visualization tracking, all-viz-active detection
Key Strategies:
- Debounced Polling: Checks limited to 100ms intervals
- Skip Unlocked: Already-achieved events excluded from evaluation
- Delta Tracking: Only process state changes, not entire state
- Batched Persistence: Saves every 5 seconds, not per change
- Efficient Lookups: Hash maps for O(1) access
- Notification Queue: Sequential display prevents flooding (max stack: 1)
Advanced Features
Warmup Period SAFETY
All record*() calls are blocked during engine warmup to prevent false positives from initial state. The flag is exposed on the API via _isWarmingUp().
Cross-Tab Sync SYNC
Listens to the storage event to sync enabled/disabled state across browser tabs in real-time.
Data Freeze SECURITY
Event bus data is passed through Object.freeze() to prevent subscribers from mutating shared state.
Double-Init Guard GUARD
Global window.CHAOS_EVENT_SYSTEM_LOADED flag prevents re-initialization if the script is loaded multiple times.
26 Tracked Reaction Types
The system independently tracks each reaction mechanism:
Full reaction registry: elimination, addition, hydrogenation, ringClosure, aromaticSub, dielsAlder, esterification, markovnikov, nucleophilic, peroxide, acidbase, autoionize, propagation, initiation, termination, aldol, hydrolysis, sigmatropic, tautomerism, sn2, sn1, oxidation, reduction, dehydration, isomerization, amideBond
Tracked formulas: H₂O, CH₄, NH₃, C₂H₆, C₂H₄, C₂H₂, C₆H₆, HCl, HBr, H₂, O₂, N₂, CO₂, C₃H₈
State Monitoring Bridge
Non-invasive observer running every 200ms. Counts bonds via particle inspection, detects molecules from
state map, tracks structures from rings/conjugation arrays, monitors pH/temperature continuously.
Persistence Layer
Auto-Save
Every 5 seconds to LocalStorage with version tag v4
Recovery
Automatic state restoration on page load with version migration
Quota Handling
Graceful degradation with data pruning on storage errors
API Reference
The event system exposes a comprehensive JavaScript API accessible via
window.CHAOS_API.events
Core API Methods
toggle(enabled)
Enable/disable entire tracking system
getProgress()
Returns: { unlocked, total, percentage }
getByCategory()
Returns events grouped by category with tracking status
list()
Returns complete event registry (184+ definitions)
trackCustomEvent(name, data)
Emit custom events to global bus
reset()
Clear all progress with confirmation
Usage Examples
Query Progress:
const p = window.CHAOS_API.events.getProgress();
console.log(`${p.tracked}/${p.total} (${p.percentage}%)`)
Access Statistics:
const s = window.CHAOS_API.events.stats;
console.log(`Bonds: ${s.totalBondsFormed}`);
Enable Tracking:
window.CHAOS_API.events.toggle(true);
Emit Custom Event:
window.CHAOS_EVENTS.emit('custom', {data: 'value'});
Integration
Requirements: ES6+ JavaScript, LocalStorage API, No framework dependencies
Load Order: chaos-engine-core → chaos-engine-ui → chaos-events-org →
chaos-events-monitor
Compatibility: Chrome 60+, Firefox 55+, Safari 11+, Edge 79+