### Quick Start: Initialize and Broadcast Context Source: https://github.com/v1b3x0r/mds/blob/main/README.npm.md Initialize a new World instance with specified features and broadcast initial environmental context. This snippet demonstrates the basic setup for a simulated world. ```javascript import { World } from '@v1b3x0r/mds-core' const world = new World({ features: { ontology: true, history: true, communication: true, linguistics: true, physics: true, rendering: 'headless' } }) world.broadcastContext({ 'env.temp.c': 32.8, 'env.humidity': 0.68, 'env.light.lux': 15000 }) console.log(world.logger.tailText(10).join('\n')) ``` -------------------------------- ### Running Example Tests Source: https://github.com/v1b3x0r/mds/blob/main/docs/patterns/zero-code-lookup.md Shows how to execute a specific example test file using Node.js. This is useful for verifying the behavior of loaded entity patterns. ```bash node tests/examples/guardian-golem.test.mjs ``` -------------------------------- ### Setup Dialogue Source: https://github.com/v1b3x0r/mds/blob/main/src/4-communication/llm.txt Use this pattern to set up a dialogue for an entity. Dialogues can support multilingual responses. ```typescript entity.addDialogue('intro', [{ lang: { th: 'สวัสดี', en: 'Hello' }}]) ``` -------------------------------- ### Install MDS Core Source: https://github.com/v1b3x0r/mds/blob/main/README.npm.md Install the @v1b3x0r/mds-core package using npm. This is the first step to integrate MDS into your project. ```bash npm install @v1b3x0r/mds-core ``` -------------------------------- ### Minimal MDS Entity Initialization Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Demonstrates the basic setup of the MDS environment and spawning a simple entity. This code requires the '@v1b3x0r/mds-core' package. ```javascript import { World } from '@v1b3x0r/mds-core' const world = new World() const entity = world.spawn({ essence: 'Ghost' }, { x: 100, y: 100 }) // Entity exists, has emotion, can age, can form relationships ``` -------------------------------- ### Spawn an entity in a world Source: https://github.com/v1b3x0r/mds/blob/main/docs/llm.txt This snippet shows the basic setup for creating a new world and spawning an entity with a defined essence. It's the starting point for building within MDS-core. ```typescript const world = new World(); world.spawn({ essence: 'curious lamp' }); ``` -------------------------------- ### Essence Description Example Source: https://github.com/v1b3x0r/mds/blob/main/docs/FIELD-GUIDE.md A minimal example of an essence description in .mdm format. This line defines the core identity of a being. ```json { "essence": "lonely ghost" } ``` -------------------------------- ### Essence-First Design Example Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Illustrates the minimal data structure for defining an entity's essence, which works across any language and allows the system to fill in defaults. ```json { "essence": "ผีขี้อาย" } ``` -------------------------------- ### Phase 1: Needs API (v5.9) Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Provides examples for managing entity needs, interacting with resource fields, and assessing the emotional climate of the world. ```javascript // Check needs entity.getNeed('water') // Get need object entity.isCritical('water') // Check if < threshold entity.getCriticalNeeds() // Get all critical need IDs entity.speakAboutNeeds() // Generate utterance ("I need water") entity.satisfyNeed('water', 0.3) // Drink water (+30%) // Resource fields world.addResourceField({ id: 'well', resourceType: 'water', type: 'point', position: { x: 200, y: 200 }, intensity: 1.0 }) world.consumeResource('water', x, y, 0.3) // Consume from field world.findNearestResourceField(x, y, 'water') // Find nearest // Emotional climate world.recordEntityDeath(entity, 0.9) // Record death const climate = world.getEmotionalClimate() // Get climate // climate.grief, climate.vitality, climate.tension, climate.harmony ``` -------------------------------- ### Loading MDS Materials Source: https://github.com/v1b3x0r/mds/blob/main/docs/patterns/zero-code-lookup.md Demonstrates how to load an MDS material file and spawn an entity in a new world. Ensure you have the '@v1b3x0r/mds-core' package installed. ```typescript import { World } from '@v1b3x0r/mds-core' import fs from 'node:fs' const material = JSON.parse(fs.readFileSync('materials/examples/entity.guardian_golem.mdm', 'utf-8')) const world = new World({ features: { ontology: true, history: true } }) const entity = world.spawn(material, { x: 0, y: 0 }) ``` -------------------------------- ### Trigger Schema Example Source: https://github.com/v1b3x0r/mds/blob/main/docs/MDM-SEMANTIC-FIRST.md Defines a behavior trigger with conditions and associated actions. Use this schema to declare how the system should react to specific events. ```yaml behavior: triggers: - on: "turn" where: "channel == '#radio' && spontaneity > 0.1" actions: - say: { mode: "auto" } - relation.update: { formula: "trust += 0.02 * agreement - 0.01 * conflict" } - memory.recall: { kind: "episodic", window: "300s", strategy: "recent" } ``` -------------------------------- ### Rain Trigger Example Source: https://github.com/v1b3x0r/mds/blob/main/docs/FIELD-GUIDE.md A declarative line of code defining a trigger for weather events. This specific example links the 'weather.rain' event to an 'anxious' emotional state for a forest creature. ```text trigger: "weather.rain" → anxious ``` -------------------------------- ### Enable Learning for an Entity Source: https://github.com/v1b3x0r/mds/blob/main/src/3-cognition/llm.txt Enables the learning capability for an entity, specifying learning parameters. Use when an entity needs to start learning from its interactions. ```typescript entity.enableLearning({ alpha: 0.1, gamma: 0.9 }) ``` -------------------------------- ### Get Current Intent Source: https://github.com/v1b3x0r/mds/blob/main/src/1-ontology/llm.txt Retrieves the highest priority goal from the intent stack. ```typescript current() ``` -------------------------------- ### MDS Core Identity Example Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md A minimal JSON entity defining its core essence. The system automatically assigns emotional state, aging, relationship capabilities, and physics interactions. ```json { "essence": "Lonely ghost" } ``` -------------------------------- ### Festival Mode Entity Behavior Snippet Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md An example snippet to be included within an entity's MDM file. It defines a behavior that triggers during festival mode, emitting a sparkle emoji. ```json { "id": "festival-shine", "on": "time.every(8s)", "where": "context.schedule.is_festival", "actions": [ { "say": { "text": "✨", "mode": "emoji" } } ] } ``` -------------------------------- ### Warm-up: All-on World Preset Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md Initializes the World with all core features enabled. Recommended for general use, with the option to disable features later. ```javascript import { World } from '@v1b3x0r/mds-core' export const world = new World({ features: { ontology: true, history: true, communication: true, linguistics: true, physics: true, rendering: 'headless' } }) ``` -------------------------------- ### Create Environment Configuration Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Use this to set up the physical environment parameters such as temperature, gravity, and viscosity. ```typescript createEnvironment({ temperature, gravity, viscosity }) ``` -------------------------------- ### Initialize World with Recommended Defaults Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Instantiate the World simulation with essential features enabled for ontology, history, communication, linguistics, and physics. Rendering defaults to 'headless'. ```typescript const world = new World({ features: { ontology: true, history: true, communication: true, linguistics: true, physics: true, rendering: 'headless' } }) ``` -------------------------------- ### World API - Constructor Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Initializes a new World instance with optional configuration for simulation features. ```APIDOC ## World API - Constructor ### Description Initializes a new World instance with optional configuration for simulation features. ### Constructor Signature ```ts new World(options?: WorldOptions) ``` ### Default Options ```ts const world = new World({ features: { ontology: true, history: true, communication: true, linguistics: true, physics: true, rendering: 'headless' } }) ``` ### Feature Options - `ontology`: Enables needs, emotion, relationships, memory stacks. - `history`: Enables long-format logs for snapshots. - `communication`: Enables message queues and dialogue triggers. - `linguistics`: Enables transcript, lexicon, and `translation.learn` loops. - `physics`: Enables collision, energy, and field resonance. - `rendering`: Sets rendering mode ('headless', 'dom', or 'canvas'). ``` -------------------------------- ### Emoji Garden Starter: Spawning and Context Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md Spawns the 'orz.seed' and 'athena.lexicon' entities and broadcasts initial environmental context. This sets up the initial state for the Emoji Garden. ```javascript world.spawn(await loadMaterial('materials/entities/orz.seed.mdm'), { x: 0, y: 0 }) world.spawn(await loadMaterial('materials/entities/athena.lexicon.mdm'), { x: 160, y: 0 }) world.broadcastContext({ 'env.temp.c': 33.5, 'env.humidity': 0.7, 'env.light.lux': 18000, 'env.noise.db': 38 }) ``` -------------------------------- ### Get Recent Transcript Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Retrieves the most recent 'n' entries from the world's transcript. Useful for quick logging or debugging. ```javascript world.transcript?.getRecent(n) ``` -------------------------------- ### Entity API - Declarative vs Imperative Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Explains the recommended approach for defining entity behavior. ```APIDOC ## Entity API - Declarative vs Imperative ### Description Explains the recommended approach for defining entity behavior. ### Guidance - **Declarative (`behavior.triggers`)**: This is the recommended approach, as the engine handles the checks. - **Imperative helpers**: These remain available for quick experiments, testing, or emergency overrides. ``` -------------------------------- ### Simplified LLM Configuration (v5.3) Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Shows the current grouped LLM configuration object for setting up language and semantic models. Use the single 'llm' object for all LLM configurations. ```javascript // ✅ CURRENT (v5.3) — Grouped LLM config const world = new World({ llm: { provider: 'openrouter', // 'openrouter' | 'anthropic' | 'openai' apiKey: 'sk-...', // Auto-fallback to process.env.OPENROUTER_KEY languageModel: 'anthropic/claude-3.5-sonnet', embeddingModel: 'openai/text-embedding-3-small' // Optional } }) // ❌ DEPRECATED (v5.2) — Still works, auto-converts with warning const world = new World({ languageProvider: 'openrouter', languageApiKey: 'sk-...', languageModel: 'claude-3.5', semanticProvider: 'openai', semanticApiKey: 'sk-...' }) ``` -------------------------------- ### Run Desert Survival Demo Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md This command executes the desert survival demo using Node.js. It's a way to experience a specific simulation within the MDS environment. ```bash node node_modules/@v1b3x0r/mds-core/demos/desert-survival.mjs ``` -------------------------------- ### Configure All Features Preset Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md This configuration object enables all available features, with rendering set to 'headless'. It's a preset for enabling comprehensive functionality. ```javascript export const featuresAllOn = { ontology: true, history: true, communication: true, linguistics: true, physics: true, rendering: 'headless' } ``` -------------------------------- ### Map Emotion to Speed Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Converts an emotional state into a physical speed multiplier. For example, joy results in doubled speed, while sadness reduces it by half. ```typescript emotionToSpeed(emotion) ``` -------------------------------- ### Code Verification Commands Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Lists the essential commands to run for verifying code changes, including building, testing, and type checking. Ensures code is production-ready. ```bash npm run build # Check bundle size npm test # All 192 tests must pass npm run type-check # TypeScript validation ``` -------------------------------- ### World API - Key Methods Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Provides essential methods for interacting with the simulation world, including ticking, broadcasting context, spawning, and managing entities. ```APIDOC ## World API - Key Methods ### Description Provides essential methods for interacting with the simulation world, including ticking, broadcasting context, spawning, and managing entities. ### Methods | Method | Notes | |--------|-------| | `world.tick(dt: number)` | Runs one simulation step; `dt` in seconds. | | `world.broadcastContext(context: Record)` | Injects meaning into the world. | | `world.spawn(material: MdsMaterial, options?: SpawnOptions)` | Creates an entity with optional spawn parameters. | | `world.get(id: string)` | Retrieves an entity by its internal ID. | | `world.remove(id: string)` | Removes an entity immediately from the simulation. | | `world.destroy()` | Tears down the simulation and clears logger subscriptions. ``` -------------------------------- ### Say Action Configuration Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Configures the 'say' action, specifying the text to be spoken, the speaking mode (e.g., 'emoji', 'proto'), and an optional language for translation. ```json { "say": { "text": "🌙", "mode": "emoji", "lang": "th" } } ``` -------------------------------- ### Create a Learning Experience Data Point Source: https://github.com/v1b3x0r/mds/blob/main/src/3-cognition/llm.txt Constructs a data point representing a learning experience, used for updating Q-tables. It captures the state, action, and reward of an interaction. ```typescript createExperience(state, action, reward) ``` -------------------------------- ### Before Layered Architecture: Mixed Test Concerns Source: https://github.com/v1b3x0r/mds/blob/main/docs/testing/LAYERED_ARCHITECTURE.md Illustrates the previous approach where a single test mixed algorithm and integration concerns. This made failure attribution difficult. ```javascript // Test 6: World Stats API const world = new World({ features: { linguistics: true }}) // Mixed algorithm + integration concerns ``` ```javascript // Test 8: Multilingual Speech const world = new World({ features: { linguistics: true }}) // Mixed UTF-8 handling + climate concerns ``` -------------------------------- ### Entity API - Spawn Options Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Defines the options available when spawning new entities. ```APIDOC ## Entity API - Spawn Options ### Description Defines the options available when spawning new entities. ### Interface ```ts interface SpawnOptions { x?: number y?: number vx?: number vy?: number } ``` ### Notes If omitted, entities spawn at `(0, 0)` with zero velocity. ``` -------------------------------- ### Unified Feature Activation (v5.3) Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Demonstrates the current unified API for enabling and disabling entity features. Use this for all new code. ```javascript // ✅ CURRENT (v5.3) — Unified API entity.enable('memory', 'learning', 'relationships', 'skills') entity.disable('learning') entity.isEnabled('memory') // → true entity.enableAll() // Enable everything entity.disableAll() // Disable everything // ❌ DEPRECATED (v5.2) — Still works, but console warns entity.enableMemory = true entity.enableLearning() ``` -------------------------------- ### Enable World Linguistics System Source: https://github.com/v1b3x0r/mds/blob/main/src/6-world/llm.txt Activate the linguistics system, configuring parameters like buffer size for conversation history. ```typescript world.enableLinguistics({ bufferSize: 500 }) ``` -------------------------------- ### Create World Instance Source: https://github.com/v1b3x0r/mds/blob/main/src/6-world/llm.txt Instantiate the World class with optional configuration for width, height, and seed. ```typescript new World({ width, height, seed }) ``` -------------------------------- ### Enable LLM Source: https://github.com/v1b3x0r/mds/blob/main/src/4-communication/llm.txt Use this pattern to enable Large Language Model (LLM) capabilities, specifying the provider and API key. LLMs are optional and fallbacks should be provided. ```typescript enableLLM({ provider: 'openrouter', apiKey }) ``` -------------------------------- ### World API - Feature Toggles Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Allows runtime configuration and retrieval of world options. ```APIDOC ## World API - Feature Toggles (Runtime) ### Description Allows runtime configuration and retrieval of world options. ### Methods - `world.configure(newOptions)`: Updates world configuration at runtime (currently limited). - `world.getOptions()`: Returns a copy of the current world options. ``` -------------------------------- ### Set World Environment Parameters Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Configures the environment for the world simulation, including temperature and gravity. ```typescript world.setEnvironment({ temperature: 25, gravity: 0.1 }) ``` -------------------------------- ### Spawn Full-Featured Entity with Unified API Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Spawns an NPC with advanced features like memory, learning, and relationships, configuring LLM settings for advanced communication. ```javascript const world = new World({ features: { memory: true, learning: true, relationships: true, communication: true }, llm: { provider: 'openrouter', apiKey: process.env.OPENROUTER_KEY, languageModel: 'anthropic/claude-3.5-sonnet' } }) const npc = world.spawn({ essence: 'Village blacksmith who holds grudges', dialogue: { intro: [{ lang: { en: 'What do you want?', th: 'ต้องการอะไร?' }}] } }, { x: 200, y: 200 }) // Unified API (replaces old enableMemory, enableLearning, etc.) pc.enable('memory', 'learning', 'relationships') // NPC now: // - Remembers all interactions (memory) // - Learns from rewards/punishment (learning) // - Forms relationships with other entities (relationships) ``` -------------------------------- ### Emoji Garden Starter: Athena Lexicon MDM Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md Defines the 'athena.lexicon' entity for translating emoji to Thai words. It learns translations from mentions and logs them. ```json { "material": "entity.athena.lexicon", "essence": "Translator that keeps gentle notes", "behavior": { "triggers": [ { "id": "emoji-translation", "on": "mention(others)", "where": "event.utterance.text != ''", "actions": [ { "translation.learn": { "source": "{{event.utterance.text}}", "lang": "th", "text": "{{emoji.map(event.utterance.text)}}" } }, { "memory.write": { "kind": "fact", "target": "translation.latest", "value": "{{event.utterance.text}} -> {{translate.th}}" } }, { "say": { "text": "{{translate.th}}", "mode": "short", "lang": "th" } } ] } ] } } ``` -------------------------------- ### Broadcasting Context via Semantic Bus Source: https://github.com/v1b3x0r/mds/blob/main/docs/PHILOSOPHY.md Use broadcastContext to send environmental hints like temperature, humidity, light, and noise levels into the Semantic Bus for interpretation by .mdm logic. ```javascript world.broadcastContext({ 'env.temp.c': 33.5, 'env.humidity': 0.7, 'env.light.lux': 18000, 'env.noise.db': 38 }) ``` -------------------------------- ### Switch Renderer to Canvas Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Switches the world's renderer to use the Canvas adapter. Ensure the canvas element is correctly initialized and provided. ```typescript world.setRenderer(new CanvasRenderer(canvas)) ``` -------------------------------- ### Learn Translation Action Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Configures the 'translation.learn' action to store a new translation. It requires the source text, target language, and the translated text. This can be combined with memory and 'say' actions for immediate feedback. ```json { "translation.learn": { "source": "{{event.utterance.text}}", "lang": "th", "text": "{{emoji.map(event.utterance.text)}}" } } ``` -------------------------------- ### Enable Entity Coupling with Presets Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Activates the coupling mechanism for an entity, using predefined presets for common patterns. ```typescript entity.enableCoupling(COUPLING_PRESETS.expressive) ``` -------------------------------- ### Write to Memory Action Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Configures the 'memory.write' action to store an entry in the memory buffer. It specifies the kind of entry, a target identifier, and the value to store. Useful for later retrieval with 'memory.recall'. ```json { "memory.write": { "kind": "fact", "target": "translation.latest", "value": "{{event.utterance.text}} -> {{translate.th}}" } } ``` -------------------------------- ### Subscribe to Logger Entries Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md This snippet demonstrates how to subscribe to the world logger to receive and render log entries in real-time. The subscription can be later unsubscribed to stop receiving logs. ```javascript const unsub = world.logger.subscribe(entry => { renderLine(`[${entry.type}] ${entry.text || ''}`) }) // Later → unsub() ``` -------------------------------- ### Spawn Entity with Needs Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Spawns an entity with defined needs and adds a resource field to the world. Simulates a tick and checks if the entity's needs are critical. ```javascript const world = new World({ features: { ontology: true, linguistics: true }}) const traveler = world.spawn({ essence: 'Thirsty traveler', needs: { resources: [{ id: 'water', depletionRate: 0.01, criticalThreshold: 0.3 }] } }, { x: 100, y: 100 }) // Add water source world.addResourceField({ id: 'well', resourceType: 'water', type: 'point', position: { x: 250, y: 250 }, intensity: 1.0 }) // Simulate world.tick(1) // Check needs if (traveler.isCritical('water')) { const utterance = traveler.speakAboutNeeds() // "I need water" const consumed = world.consumeResource('water', traveler.x, traveler.y, 0.3) traveler.satisfyNeed('water', consumed) } ``` -------------------------------- ### Entity Learning from Interaction Source: https://github.com/v1b3x0r/mds/blob/main/src/3-cognition/llm.txt Trains an entity by providing a learning data point consisting of the current state, the action taken, and the resulting reward. This is the core Q-learning update mechanism. ```typescript entity.learn(state, action, reward) ``` -------------------------------- ### Layer 1: Pure Crystallization Algorithm Test Source: https://github.com/v1b3x0r/mds/blob/main/docs/testing/LAYERED_ARCHITECTURE.md Tests the core frequency counting, thresholding, and lexicon storage logic in isolation. Use when you need to verify the algorithm's correctness without external system influences. ```javascript // Test 6A: Pure Crystallization Algorithm const world = new World({ features: { linguistics: true, ontology: false } }) world.recordSpeech(entity, 'wow') world.recordSpeech(entity, 'wow') world.tick(1) const popular = world.getPopularTerms(2) assert(popular.length === 2, 'Filters by frequency threshold') ``` -------------------------------- ### Run World Simulation Tick Source: https://github.com/v1b3x0r/mds/blob/main/src/6-world/llm.txt Execute the world's three-phase update cycle (Physical, Mental, Relational) at a fixed interval. ```typescript setInterval(() => world.tick(1/60), 16) ``` -------------------------------- ### After Layered Architecture: Separated Test Concerns Source: https://github.com/v1b3x0r/mds/blob/main/docs/testing/LAYERED_ARCHITECTURE.md Demonstrates the layered approach, separating pure algorithm tests (Layer 1) from full integration tests (Layer 2) for clearer validation. ```javascript // Test 6A: Pure Crystallization Algorithm (Layer 1) const world = new World({ features: { linguistics: true, ontology: false } }) // Tests ONLY frequency threshold logic // Test 6B: Emotion-Aware Crystallization (Layer 2) const world = new World({ features: { linguistics: true, ontology: true } }) // Tests emotion context capture in full system ``` ```javascript // Test 8A: Multilingual Crystallization (Layer 1) const world = new World({ features: { linguistics: true, ontology: false } }) // Tests ONLY UTF-8 pattern detection // Test 8B: Multilingual with Climate (Layer 2) const world = new World({ features: { linguistics: true, ontology: true } }) // Tests climate influence on multilingual terms ``` -------------------------------- ### Load World from File Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Loads a world state from a JSON file and reconstructs the World object. This involves loading the file content and then parsing it into a world. ```typescript const world = fromWorldFile(loadWorldFile('world.json')) ``` -------------------------------- ### Entity Spawn Options Interface Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Defines the optional properties for spawning entities, including their initial position and velocity. ```typescript interface SpawnOptions { x?: number y?: number vx?: number vy?: number } ``` -------------------------------- ### Entity API - Common Helpers Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Lists common properties and methods available on entity objects when the ontology feature is enabled. ```APIDOC ## Entity API - Common Entity Helpers (Ontology Enabled) ### Description Lists common properties and methods available on entity objects when the ontology feature is enabled. ### Helpers | Property / method | Purpose | |-------------------|---------| | `entity.remember(entry)` | Writes an entry to the entity's memory. | | `entity.memory?.recall(filter)` | Reads memory entries based on a filter. | | `entity.emotion` | Accesses the entity's PAD object (`valence`, `arousal`, `dominance`). | | `entity.intent` | Manages the entity's stack of goals (push/pop). | | `entity.relationships` | Provides a map of inter-entity relationships. | | `entity.getCriticalNeeds()` | Returns an array of needs below a specified threshold. | | `entity.say(text, options?)` | Imperative speech command (use with caution; prefer declarative `say`). ``` -------------------------------- ### Factory Pattern for Spawning Entities Source: https://github.com/v1b3x0r/mds/blob/main/src/0-foundation/llm.txt Use the factory pattern to create new entities within the simulation world. This ensures proper initialization and adherence to system constraints. ```typescript world.spawn(material, x, y) ``` -------------------------------- ### Broadcast Sensor Data to Semantic Bus Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md This snippet shows how to hook a sensor into the Semantic Bus by broadcasting its readings. It includes a function to map sensor data to bus contexts and a timer to periodically fetch and broadcast readings. ```javascript function hintFromWeatherStation(reading) { world.broadcastContext({ 'env.temp.c': reading.temperature, 'env.humidity': reading.humidity, 'env.light.lux': reading.lux, 'env.noise.db': reading.noise || 32 }) } setInterval(async () => { const reading = await fetchWeatherOrMock() hintFromWeatherStation(reading) }, 4000) ``` -------------------------------- ### Emoji Garden Starter: Orz Seed MDM Source: https://github.com/v1b3x0r/mds/blob/main/docs/COOKBOOK.md Defines the 'orz.seed' entity, which cycles through emojis and speaks 'orz' in quiet environments. It uses time-based triggers for its behavior. ```json { "material": "entity.orz.seed", "essence": "Little seed that bows to meaning", "utterance": { "policy": { "modes": ["emoji", "proto", "short"], "defaultMode": "auto" } }, "behavior": { "triggers": [ { "id": "emoji-cycle", "on": "time.every(6s)", "actions": [ { "say": { "text": "{{pick(['🌱','💧','🌬️','🔥','🌤','🌙','⛰️','☁️'])}}", "mode": "emoji" } } ] }, { "id": "quiet-bow", "on": "time.every(12s)", "where": "env.noise.db < 40 && climate.harmony > 0.6", "actions": [ { "say": { "text": "orz", "mode": "short" } } ] } ] } } ``` -------------------------------- ### Generate Text with LLM Source: https://github.com/v1b3x0r/mds/blob/main/src/4-communication/llm.txt Use this pattern to generate text based on a prompt using a Language Generator. This can interface with various LLM providers. ```typescript LanguageGenerator.generate(prompt) ``` -------------------------------- ### MDS Serialization and Rehydration Source: https://github.com/v1b3x0r/mds/blob/main/docs/patterns/zero-code-lookup.md Illustrates how to serialize the current world state to a file and then rehydrate it. This is essential for persisting and restoring entity states, including emotions and timers. ```typescript import { toWorldFile, fromWorldFile } from '@v1b3x0r/mds-core' const file = toWorldFile(world) const restored = fromWorldFile(file, { features: { ontology: true, history: true } }) ``` -------------------------------- ### World Spawn Signature Source: https://github.com/v1b3x0r/mds/blob/main/CLAUDE.md Highlights the correct and deprecated signatures for the world.spawn method. Always use the material and position object signature. ```javascript // ✅ CORRECT world.spawn(material, { x, y }) // ❌ WRONG (old signature, deprecated) world.spawn(material, x, y) ``` -------------------------------- ### World Constructor Signature Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md The signature for the World constructor, accepting optional WorldOptions. ```typescript new World(options?: WorldOptions) ``` -------------------------------- ### Subscribe to Logger Entries Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Subscribes a listener function to receive live logger entries. The listener is called for each new entry. Call the returned unsubscribe function to stop listening. ```javascript const unsubscribe = world.logger.subscribe(entry => { renderLine(`[${entry.type}] ${entry.text || ''}`) }) // Later → unsubscribe() ``` -------------------------------- ### Set Creator Context Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Sets the creator context, including user information like name and personality. This context can be used by AI for personalized responses. ```typescript setCreatorContext({ user: { name, personality }}) ``` -------------------------------- ### Create Small-World Network Topology Source: https://github.com/v1b3x0r/mds/blob/main/src/5-network/llm.txt Generates an efficient and sparse network topology using the Watts-Strogatz model. Suitable for large-scale P2P networks. ```typescript SmallWorldNetwork.create(entities, k=8) ``` -------------------------------- ### Save World to File Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Serializes the current world state into a WorldFile format and saves it to a specified file path. This uses the toWorldFile utility for serialization. ```typescript const file = toWorldFile(world); saveWorldFile(file, 'world.json') ``` -------------------------------- ### Define a Trigger with Actions Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Defines a trigger with an ID, a condition for activation ('on' and 'where'), and a list of actions to perform. The 'on' field supports time intervals and event mentions. ```json { "id": "emoji-cycle", "on": "time.every(6s)", "where": "env.noise.db < 50", "actions": [ { "say": { "text": "🌱", "mode": "emoji" } } ] } ``` -------------------------------- ### Enable Emotion for Entity Source: https://github.com/v1b3x0r/mds/blob/main/src/1-ontology/llm.txt Enables emotion tracking for an entity, allowing configuration of baseline emotional state and drift rate. ```typescript entity.enableEmotion({ baseline, driftRate }) ``` -------------------------------- ### Enable LLM Bridge Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Enables the LLM bridge with specified provider, API key, and model. This allows the system to communicate with external LLM services. ```typescript enableLLM({ provider: 'openrouter', apiKey, model }) ``` -------------------------------- ### Create Relationship Source: https://github.com/v1b3x0r/mds/blob/main/src/1-ontology/llm.txt Establishes a new relationship between entities, characterized by trust and familiarity, which decays over time. ```typescript createRelationship() ``` -------------------------------- ### Load World State Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Loads a previously saved world state from a file. Ensure the world file is valid before attempting to load. ```javascript world.loadWorldFile(worldFile) ``` -------------------------------- ### Enable Collision Detection in World Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Enables collision detection for the world simulation. Configure parameters like radius and elasticity. ```typescript world.enableCollision({ radius, elasticity }) ``` -------------------------------- ### Enable P2P Cognitive Link Source: https://github.com/v1b3x0r/mds/blob/main/src/5-network/llm.txt Enables an entity to participate in P2P memory sharing. This is a key step for distributed consciousness. ```typescript entity.enableCognitiveLink() ``` -------------------------------- ### Set Context Values Action Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Configures the 'context.set' action to store values into the entity's context, making them available for subsequent triggers. It can set arbitrary key-value pairs, including values recalled from memory. ```json { "context.set": { "seed.lastEmoji": "{{event.utterance.text}}", "seed.translation.count": "memory.recall.count" } } ``` -------------------------------- ### World API - Climate & Stats Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Provides access to the world's emotional climate and related statistics. ```APIDOC ## World API - Climate & Stats ### Description Provides access to the world's emotional climate and related statistics. ### API Endpoints | API | Description | |-----|-------------| | `world.getEmotionalClimate()` | Returns the current emotional climate snapshot (e.g., `grief`, `vitality`, `tension`, `harmony`). | | `world.recordEntityDeath(entity, intensity)` | Convenience wrapper for recording entity deaths (related to `CollectiveIntelligence.recordDeath`). | | `CollectiveIntelligence.describeClimate(climate)` | Generates a human-readable summary of the climate. | | `CollectiveIntelligence.updateEmotionalClimate(climate, dt)` | Manually updates the emotional climate, useful for custom pacing. ``` -------------------------------- ### Describe Climate Source: https://github.com/v1b3x0r/mds/blob/main/docs/REFERENCE.md Generates a descriptive summary of the current emotional climate of the world. Requires the world's emotional climate data. ```javascript CollectiveIntelligence.describeClimate(world.getEmotionalClimate()) ``` -------------------------------- ### Set World Weather Conditions Source: https://github.com/v1b3x0r/mds/blob/main/src/2-physics/llm.txt Applies a specific weather condition to the world simulation. ```typescript world.setWeather('storm') ``` -------------------------------- ### Dialogue Manager (Conceptual) Source: https://github.com/v1b3x0r/mds/blob/main/docs/FIELD-GUIDE.md Conceptual anchors for dialogue management, including language generation, semantic similarity, and message queuing. The LLM for dialogue generation is optional. ```typescript src/4-communication/dialogue/manager.ts ``` ```typescript language/generator.ts ``` ```typescript semantics/similarity.ts ``` ```typescript message/queue.ts ``` -------------------------------- ### Set OpenAI LLM Bridge Source: https://github.com/v1b3x0r/mds/blob/main/src/7-interface/llm.txt Sets the LLM bridge to use the OpenAI provider. Requires an API key for authentication. ```typescript setLlmBridge(new OpenAIBridge(apiKey)) ``` -------------------------------- ### Respond to Dialogue Trigger Source: https://github.com/v1b3x0r/mds/blob/main/src/4-communication/llm.txt Use this pattern to have a Dialogue Manager respond to a trigger within a given context. Responses are conditional. ```typescript DialogueManager.respond(trigger, context) ``` -------------------------------- ### Share Memory via Cognitive Link Source: https://github.com/v1b3x0r/mds/blob/main/src/5-network/llm.txt Allows an entity to share a specific memory with another entity, respecting defined policies. Requires P2P to be enabled. ```typescript entity.shareMemory(targetId, memoryId, policy) ``` -------------------------------- ### Send Message Source: https://github.com/v1b3x0r/mds/blob/main/src/4-communication/llm.txt Use this pattern to send a message from one entity to another. Messages can have a type, content, and priority. ```typescript entity.sendMessage(target, { type, content, priority }) ``` ```typescript entity.sendMessage(targetId, { type: 'greeting', content: 'สวัสดี' }) ```