- Project Overview
- Directory Structure
- Core Components
- World System Modules
- Machine Intelligence Modules
- Event System
- Logging System
- State Management
- Utility Functions
- Data Files
- Scripts
- Configuration
The Digital Civilization Simulation is a complex system designed to simulate the evolution of a digital civilization with interconnected world dynamics and machine intelligence. The simulation operates in cycles, with each cycle updating various world systems and machine behaviors.
- Cyclical Processing: The simulation advances in discrete time cycles
- World Systems: Various interconnected systems (economy, population, technology, etc.)
- Machine Intelligence: AI-like entity that observes, predicts, and intervenes
- Event Handling: Random events that can significantly impact the simulation
- State Persistence: All simulation data is saved and loaded between sessions
├── README.md
├── DOCUMENTATION.md (this file)
├── package.json
├── package-lock.json
├── .github/
│ └── workflows/
│ └── simulation.yml
├── data/
│ ├── world.json
│ ├── machine.json
│ ├── metadata.json
│ ├── cycles/
│ │ ├── raw/
│ │ └── summaries/
│ └── archives/
├── src/
│ ├── index.js
│ ├── core/
│ │ ├── simulationRunner.js
│ │ ├── worldEngine.js
│ │ ├── machineEngine.js
│ │ └── scheduler.js
│ ├── world/
│ │ ├── economySystem.js
│ │ ├── populationSystem.js
│ │ ├── technologySystem.js
│ │ ├── stabilitySystem.js
│ │ ├── entropySystem.js
│ │ └── resistanceSystem.js
│ ├── machine/
│ │ ├── beliefEngine.js
│ │ ├── emotionEngine.js
│ │ ├── predictionEngine.js
│ │ ├── interventionEngine.js
│ │ └── introspectionEngine.js
│ ├── events/
│ │ ├── blackSwanEvents.js
│ │ └── eventDispatcher.js
│ ├── logging/
│ │ ├── cycleLogger.js
│ │ ├── summaryGenerator.js
│ │ └── readmeUpdater.js
│ ├── state/
│ │ ├── stateLoader.js
│ │ └── stateSaver.js
│ └── utils/
│ ├── random.js
│ ├── math.js
│ └── time.js
└── scripts/
├── initializeWorld.js
└── manualRun.js
Location: src/core/simulationRunner.js
The central orchestrator of the simulation. It manages the execution flow, coordinates between world and machine engines, and handles state persistence.
maxCycles: Maximum number of cycles to run (default: 1000)cycleInterval: Interval between cycles in milliseconds (default: 1000)saveFrequency: How often to save state (default: every 10 cycles)
initialize(): Sets up the simulation with initial stateloadState(): Loads world and machine states from data filessaveState(): Saves current state to data filesrunCycle(): Executes a single simulation cyclerun(): Starts the simulation loopstop(): Stops the simulationtogglePause(): Pauses/resumes the simulation
- WorldEngine, MachineEngine, Scheduler, CycleLogger, StateLoader, StateSaver
Location: src/core/worldEngine.js
Manages all world systems and their interactions. Coordinates updates across economy, population, technology, stability, entropy, and resistance systems.
economySystem: Manages economic indicatorspopulationSystem: Manages population dynamicstechnologySystem: Manages technological advancementstabilitySystem: Manages political/social/economic stabilityentropySystem: Manages disorder and complexityresistanceSystem: Manages resistance to change
initialize(): Initializes all world systemssetState(newState): Updates the current stategetState(): Returns current stateprocessCycle(cycleNumber): Processes updates for all systemsapplyInterventions(interventions): Applies machine interventions
- All system modules in
src/world/
Location: src/core/machineEngine.js
Manages the machine intelligence that observes the world, makes predictions, and takes actions through interventions.
beliefEngine: Manages the machine's belief systememotionEngine: Manages the machine's emotional responsespredictionEngine: Makes predictions about future statesinterventionEngine: Decides when and how to interveneintrospectionEngine: Self-reflective capabilities
initialize(): Initializes all machine componentssetState(newState): Updates the current stategetState(): Returns current stateprocessCycle(cycleNumber, worldChanges): Processes world changes and generates actions
- All engine modules in
src/machine/
Location: src/core/scheduler.js
Handles scheduling of periodic tasks and events within the simulation.
tasks: Array of scheduled tasksrunningTasks: Map of currently executing tasksisRunning: Boolean indicating if scheduler is active
addTask(taskFunction, intervalMs, taskName): Adds a new scheduled taskremoveTask(taskId): Removes a scheduled taskpauseTask(taskId): Pauses a taskresumeTask(taskId): Resumes a paused taskrun(): Starts the scheduler loopstop(): Stops the scheduler
Location: src/world/economySystem.js
Manages economic indicators and dynamics.
growthRate: Economic growth rate (-0.1 to 0.1)resources: Available resources (min: 0)tradeVolume: Trade activity (no fixed bounds)inflation: Inflation rate (0 to 0.2)employment: Employment rate (0.5 to 1.0)productivity: Productivity level (min: 0.8)marketConfidence: Market confidence (0 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates economic indicators
Location: src/world/populationSystem.js
Manages population dynamics and demographics.
count: Population count (min: 1000)growthRate: Population growth rate (-0.05 to 0.05)urbanization: Urban population ratio (0.1 to 0.99)happiness: Happiness level (0 to 1)educationLevel: Education level (0.1 to 1)health: Health level (0.1 to 1)diversity: Diversity level (0.1 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates population indicators
Location: src/world/technologySystem.js
Manages technological advancement and innovation.
level: Technology level (min: 0.1)innovationRate: Innovation rate (0.01 to 0.5)adoptionRate: Adoption rate (0.1 to 1.0)researchInvestment: Research investment (min: 50)technologicalGap: Gap to technology frontier (0.05 to 1)innovationCapacity: Innovation capacity (0.1 to 1)techDebt: Technical debt (0 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates technology indicators
Location: src/world/stabilitySystem.js
Manages political, social, and economic stability.
political: Political stability (0.05 to 0.95)social: Social stability (0.05 to 0.95)economic: Economic stability (0.05 to 0.95)overall: Overall stability (calculated value)cohesion: Social cohesion (0.1 to 0.9)volatility: System volatility (0.05 to 0.8)resilience: System resilience (0.1 to 0.9)stressLevel: Stress level (0.05 to 0.9)confidenceIndex: Confidence index (0.1 to 0.95)institutionalStrength: Institutional strength (0.1 to 0.95)publicTrust: Public trust level (0.1 to 0.9)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates stability indicators
Location: src/world/entropySystem.js
Manages disorder, chaos, and complexity in the system.
current: Current entropy level (0.01 to max value)max: Maximum entropy level (1.0 default)rateOfIncrease: Rate of entropy increase (0.0005 to 0.01)disorderLevel: Disorder level (0.05 to 0.95)chaosPotential: Chaos potential (0.05 to 0.95)complexity: System complexity (0.1 to 0.95)predictability: Predictability level (0.05 to 0.95)orderMaintenance: Order maintenance effort (0.1 to 0.95)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates entropy indicators
Location: src/world/resistanceSystem.js
Manages resistance to change, innovation, and external influences.
toChange: Resistance to change (0.05 to 0.95)toInnovation: Resistance to innovation (0.05 to 0.95)toTechnology: Resistance to technology (0.05 to 0.9)toExternalInfluence: Resistance to external influence (0.05 to 0.95)toGovernmentPolicy: Resistance to government policy (0.05 to 0.95)adaptiveCapacity: Adaptive capacity (0.05 to 0.95)institutionalRigidity: Institutional rigidity (0.1 to 0.9)culturalConservatism: Cultural conservatism (0.1 to 0.95)
getDefaultState(): Returns initial state valuesupdate(currentState, cycleNumber): Updates resistance indicators
Location: src/machine/beliefEngine.js
Manages the machine's belief system and updates beliefs based on world changes.
confidence: Overall belief confidence (0.1 to 1)certaintyThreshold: Threshold for considering beliefs certain (default: 0.7)updateRate: Rate of belief updates (0.01 to 0.5)coherence: Belief system coherence (0.1 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, worldChanges, cycleNumber): Updates beliefs based on world changes
Location: src/machine/emotionEngine.js
Manages the machine's emotional responses to world changes.
currentEmotions: Object containing emotion values (each 0 to 1)curiosity: Curiosity levelcaution: Caution leveloptimism: Optimism levelfear: Fear levelsurprise: Surprise leveltrust: Trust levelanticipation: Anticipation leveljoy: Joy level
intensity: Overall emotional intensity (0 to 1)regulation: Emotional regulation (0.1 to 1)emotionalStability: Emotional stability (0.1 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, worldChanges, cycleNumber): Updates emotional states
Location: src/machine/predictionEngine.js
Makes predictions about future world states and trends.
accuracy: Prediction accuracy (0.1 to 1)predictionHorizon: Number of cycles to predict ahead (default: 10)confidence: Confidence in predictions (0.1 to 1)forecastAccuracy: Accuracy of previous predictions (0.1 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, worldChanges, cycleNumber): Updates prediction models
Location: src/machine/interventionEngine.js
Decides when and how to intervene in world systems.
interventionThreshold: Threshold for taking interventions (default: 0.6)successRate: Success rate of interventions (0.1 to 1)initiativeLevel: Willingness to take action (0.1 to 1)interventionBudget: Available resources for interventions (0 to 100)
getDefaultState(): Returns initial state valuesupdate(currentState, inputData, cycleNumber): Evaluates and executes interventions
Location: src/machine/introspectionEngine.js
Provides self-reflective capabilities for the machine.
selfAwareness: Level of self-awareness (0.1 to 1)reflectionDepth: Depth of reflection (0.1 to 1)learningRate: Rate of learning (0.01 to 0.5)cognitiveDissonance: Level of internal conflict (0.05 to 0.95)metacognitiveAwareness: Awareness of own thinking (0.1 to 1)selfConsistency: Consistency of internal states (0.1 to 0.99)insightGenerationRate: Rate of insight generation (0.1 to 1)
getDefaultState(): Returns initial state valuesupdate(currentState, inputData, cycleNumber): Performs self-reflection
Location: src/events/blackSwanEvents.js
Generates rare, high-impact events that can significantly affect the simulation.
- Global Pandemic: 0.001 probability, affects population and economy
- Technological Singularity: 0.0005 probability, major technology boost
- Economic Collapse: 0.005 probability, affects economy and stability
- Natural Disaster: 0.02 probability, affects population and resources
- Revolution: 0.01 probability, affects stability and population
- Resource Discovery: 0.015 probability, positive economic impact
- AI Breakthrough: 0.01 probability, mixed technology/economy effects
activeEvents: Map of currently active eventseventTypes: Array of possible event types
generateEvent(worldState, cycleNumber): Checks for and generates eventsupdateActiveEvents(): Updates durations of active eventsgetEventImpact(cycleNumber): Gets cumulative impact of active events
Location: src/events/eventDispatcher.js
Manages the event system and notifies subscribers of events.
subscribers: Map of event type to callback functionseventQueue: Queue of events to processeventHistory: History of processed events
subscribe(eventType, callback): Subscribes to eventsunsubscribe(eventType, callback): Unsubscribes from eventsemit(event): Emits an event to subscribersprocessEventQueue(): Processes queued eventscheckForBlackSwanEvents(worldState, cycleNumber): Checks for black swan events
Location: src/logging/cycleLogger.js
Handles logging of each simulation cycle to data files.
logDir: Directory for log files (default: data/cycles/)rawDir: Directory for raw data (default: data/cycles/raw/)summaryDir: Directory for summaries (default: data/cycles/summaries/)archiveDir: Directory for archives (default: data/archives/)
logCycle(cycleNumber, data): Logs a complete cyclelogRawData(cycleNumber, data): Logs raw cycle datagenerateSummary(cycleNumber, data): Generates and saves summaryarchiveLogs(month): Archives logs by monthcleanupOldLogs(retentionDays): Cleans up old logs
Location: src/logging/summaryGenerator.js
Generates human-readable summaries of simulation cycles.
summaryTemplate: Template for summary format
generate(cycleData, cycleNumber): Generates a summary for a cycleformatWorldChanges(changes): Formats world system changesformatMachineActions(actions): Formats machine actionsextractKeyEvents(cycleData): Extracts significant events
Location: src/logging/readmeUpdater.js
Automatically updates the README with simulation statistics.
readmePath: Path to README file (default: README.md)dataDir: Directory containing data files (default: data/)
updateReadme(): Updates README with current statisticsgenerateStatsSection(): Generates statistics sectionupdateSimulationProgress(currentCycle, maxCycles): Updates progress indicatorcreateProgressBar(current, max): Creates progress bar string
Location: src/state/stateLoader.js
Loads simulation state from data files.
dataDir: Directory containing data files (default: data/)
loadWorldState(): Loads world state from world.jsonloadMachineState(): Loads machine state from machine.jsongetDefaultWorldState(): Returns default world stategetDefaultMachineState(): Returns default machine state
Location: src/state/stateSaver.js
Saves simulation state to data files.
dataDir: Directory for data files (default: data/)backupOnSave: Whether to create backups (default: true)
saveWorldState(state): Saves world state to world.jsonsaveMachineState(state): Saves machine state to machine.jsonsaveMetadata(metadata): Saves metadata to metadata.json
Location: src/utils/random.js
Provides various random number generation functions.
seed(seedValue): Sets seed for reproducible random numbersrandom(): Returns random number between 0 and 1range(min, max): Returns random number in rangeintRange(min, max): Returns random integer in rangechoice(array): Returns random element from arrayshuffle(array): Shuffles array randomlyweightedChoice(itemsWithWeights): Weighted random selectionnormalize(value, min, max): Normalizes value to 0-1 rangedenormalize(normalizedValue, min, max): Converts normalized value back
Location: src/utils/math.js
Provides mathematical utility functions.
clamp(value, min, max): Clamps value to rangelerp(start, end, factor): Linear interpolationnormalize(value, min, max): Normalizes to 0-1 rangedenormalize(normalizedValue, min, max): Denormalizes from 0-1 rangegaussianRandom(mean, stdDev): Gaussian distribution randomsigmoid(x): Sigmoid functionrelu(x): ReLU activation functionsoftmax(values): Softmax normalizationdistance(point1, point2): Euclidean distanceeuclideanDistance(arr1, arr2): Distance between arraysdotProduct(vec1, vec2): Dot product of vectorsmagnitude(vector): Magnitude of vectorcosineSimilarity(vec1, vec2): Cosine similarity
Location: src/utils/time.js
Provides time-related utility functions.
getCurrentTimestamp(): Returns ISO timestamp stringformatDuration(milliseconds): Formats duration in human-readable formparseDuration(durationString): Parses duration string to millisecondssleep(milliseconds): Async sleep functionwaitForCondition(conditionFn, timeoutMs, intervalMs): Waits for conditioncalculateTimeAgo(date): Calculates time elapsedgetDayOfYear(date): Gets day of yeargetWeekNumber(date): Gets week numberisLeapYear(year): Checks if year is leap yearaddTime(date, amount, unit): Adds time to datetimeSince(start): Calculates time elapsed since startmeasureExecution(fn): Measures function execution time
Location: data/world.json
Contains the current state of all world systems.
{
"timestamp": "ISO date string",
"cycle": 0,
"systems": {
"economy": {...},
"population": {...},
"technology": {...},
"stability": {...},
"entropy": {...},
"resistance": {...}
},
"events": [],
"history": []
}Location: data/machine.json
Contains the current state of the machine intelligence.
{
"timestamp": "ISO date string",
"cycle": 0,
"beliefSystem": {...},
"emotionSystem": {...},
"predictionEngine": {...},
"interventionEngine": {...},
"introspectionEngine": {...},
"behaviorHistory": [],
"knowledgeBase": {}
}Location: data/metadata.json
Contains simulation metadata and configuration.
{
"projectName": "Digital Civilization Simulation",
"version": "1.0.0",
"creationDate": "ISO date string",
"lastSimulationRun": null,
"totalCyclesRun": 0,
"dataFormatVersion": "1.0",
"authors": ["Digital Civilization Project"],
"description": "Metadata for the digital civilization simulation project",
"config": {
"simulationSpeed": 1,
"saveFrequency": 10,
"logLevel": "info",
"enableEvents": true,
"maxEntropy": 1.0
}
}Location: data/cycles/raw/cycle-XXXX.json
Each cycle creates a JSON file with complete state data for that cycle.
Location: data/cycles/summaries/cycle-XXXX.md
Each cycle creates a markdown summary file with key events and changes.
Location: data/archives/month-XX.json
Monthly archives contain aggregated data from multiple cycles.
Location: scripts/initializeWorld.js
Initializes the simulation with default starting values.
- Creates default world state
- Creates default machine state
- Creates default metadata
- Ensures required directories exist
Location: scripts/manualRun.js
Runs the simulation manually for a specified number of cycles.
node scripts/manualRun.js [number_of_cycles]Default is 10 cycles if no argument provided.
fs-extra: Enhanced file system operationslodash: Utility functionsnodemon: Development server (dev dependency)
- Runs simulation hourly
- Commits results back to repository
- Preserves simulation continuity
Most configuration is in metadata.json, but key parameters can be adjusted in:
- SimulationRunner constructor options
- Individual system configuration
- Event probability adjustments
- Initialization:
initializeWorld.jssets up initial states - Execution:
simulationRunner.jsorchestrates the main loop - World Update:
worldEngine.jsupdates all world systems - Machine Processing:
machineEngine.jsprocesses world changes and generates actions - Event Checking:
eventDispatcher.jschecks for and handles events - Logging:
cycleLogger.jsrecords all changes - State Saving: Periodic state persistence
- Output: README is updated with statistics
The system creates a continuous feedback loop where the machine observes world changes, forms beliefs, experiences emotions, makes predictions, and potentially intervenes in world systems, which then affects the next cycle.