BeastJS Project - Implementation of a Homeostatic Creature

Chapter 1: Introduction and Fundamental Principles

BEAST (Browser-based Embodied Agent Simulation and Testing) is a browser application that models individual adaptability. The goal is not to create a "working creature", but to formalize and implement the theory of adaptive systems as software code. The project acts as a tool for learning and debugging the architecture, where every detail of behavior follows strict, documented, and executable algorithms.

In the /demos/ folder there are demos that illustrate the implemented principles.

1.1 Purpose

BEAST is positioned as the most adequate way to implement the theory of individual adaptability. Just as mathematics formalizes physical laws, BEAST serves as a formalization layer for adaptive systems theory. The code is not only a product: it is also a specification and a "working diagram" of how the system works, enabling testing, modification, and debugging of adaptive behavior.

Complex verbal interfaces (phrase recognition, symbols, tone of messages) are intentionally excluded. The focus stays on core layers: homeostasis, basic contexts, stimuli, reflexes, an evidence/condition tree, semantic and episodic memory, the consciousness (awareness) process, and automatisms.

1.2 Architecture Core: From Organism to Consciousness

BEAST is built around a hierarchical model: each new layer abstracts and makes behavior more capable than the layer below.

  1. Homeostasis (body): the base level is represented by vitals (_1_Genetic_vitals). It is a set of parameters (wounds, hunger, stress, etc.) whose values change dynamically (via shift) every pulse. The vitals state determines the integral condition importance (IntergalConditionImportance) and the base condition: Poor (1), Normal (2), Well (3) (BadNormWell).
  2. Context (emotion): based on vitals output relative to the norm, the system activates basic contexts (_2_Genetic_basic_styles) - behavioral/emotional patterns (Fear, Aggression, Play, Curiosity, Calm, etc.). Their combination forms an emotion (an EmotionId), which together with the base state and the current stimulus defines the perception tree branch (_7_perception_tree). That branch (branchId) is a key identifier of the current situation.
  3. Stimuli and reflexes (input-output): the operator interacts through stimulus buttons (_3_perception). The combination of active stimuli forms the final image (FinalImageId). In response, genetic reflexes (_5_Genetic__reflexes) fire and trigger base actions (e.g. Cry, Eat). These actions are registered as action images (an ActionImageId). The system can also form conditional reflexes (_5_2_synonyms_reflexes) by linking the final image to an action under specific context conditions.
  4. Memory (experience): each interaction leaves traces.
  5. Consciousness (awareness): a central process that manages behavior. It is organized as consciousness cycles registry (ConsciousnessCycles) and an iterative dispatcher (consciousness_dispatcher.js).

1.3 Time: Discrete Pulse

The fundamental unit of time in BEAST is the pulse (puls.js). It is an artificial, discrete timeline used to run most system processes.

1.4 Key Concepts

Chapter 2: Pulse Flow: From Stimulus to Action (Corrected Version)

2.1 Pulse Lifecycle

The central loop is implemented in beast/puls.js via a recursive function sep_of_puls() that simulates a ˜heartbeat˜.

Each pulse follows a fixed sequence of steps:

# Step Description
1Fix ˜zero˜ importance markerCall getDiffImportance() to store current state in PrevDiffForEpisode for future episodic effect calculation.
2Save to IndexedDBCall runIndexedDBSavesForPulse(): all modules marked dirty persist their state.
3Increment pulse counterCur_puls_val++, update UI and localStorage.
4Episodic memory tickEpisodicMemory_onPulse(): waiting counter, close frame by timeout.
5Update vitalsperformSensorOperations(): apply shifts, account for active stimuli.
6Update contextsgetActiveBasicContexts(): compute BadVitalsValue, choose active BasicContexts, update BadNormWell.
7Update UIUpdate contexts, perception tree branch, and info panel (Info_updateFromPerceptionTree).
8Start consciousness cycle (pulse 3)If no main cycle exists, create an initial awareness cycle with stimulus 0.
9Consciousness dispatcherdispetchConsciousnessThinking(): a main-step plus background steps (every 5 pulses).
10ReflexesprocessGeneticReflexes(): deferred, conditional, genetic reflexes.
11Reset UR gateEpisodicMemory_skipConditionalReflexFormation = false.
12Pulse visualizationBlink the green circle in the UI.

2.2 Orientation Reflex (OR) as a Trigger

OR (orientation_reflex.js) starts on any change in the set of active stimuli (operator click). It is the central mechanism for deciding what the system should pay attention to.

2.2.1 Winner Selection Algorithm

2.3 Consciousness Process: From Input to Action

stimuls_consciousness (conscious_attention_channel.js) is a gate that decides whether the system should interrupt the current thought with a new stimulus.

2.3.1 Interrupt Threshold (˜Thinking Silence˜)

If there is an active main consciousness cycle and it is not marked expired, the new stimulus competes with it. The base condition compares effective stimulus significance with the current thinkingImportance and an interrupt ratio (INTERRUPT_THRESHOLD_ATTENTION_RATIO with a default of 1.5). Additional modifiers apply depending on situation/theme mismatch, important problem state, priority chains, or the orientation reflex winner.

2.3.2 Create an Episodic Consciousness Cycle

2.3.3 Elementary Pass (Levels 1˜2)

2.4 Reflexes on the Pulse: Genetic and Conditional

Reflex processing (processGeneticReflexes) occurs on each pulse after the consciousness dispatcher. This ensures that if awareness already started an automatism, a reflex for the same branch does not fire in the same pulse.

2.4.1 Processing Order

2.4.2 Forming Conditional Reflexes

A conditional reflex is created when synonyms_onGeneticActionFired is called (from startAction), provided:

Core structure:

2.5 Action and Memory Registration

startAction (genetic_reflexes_engine.js) is the final point where an action becomes a fact.

Typical effects:

2.6 Closing the Episodic Frame and Evaluating Effect

Closing the episodic frame is the moment when feedback is obtained. It can happen in three ways:

TriggerWhen it happensResult
Operator answer Stimulus appears while waiting closeLastFrame(stimulus_answer) closes the frame with the answer stimulus
Timeout Waiting period ends closeLastFrame(null) records 0/˜no action˜ marker into the frame
New OR winner OR is triggered while a frame is open Close the previous frame with answer = new winner

Inside closeLastFrame, the effect is computed (conceptually): effect = clamp(diffAfter - diffBefore, -10, +10), missing parts of the rule are filled with 0 markers, and the effect is passed to automatisms as usefulness updates. It then notifies modules (gestalt, abstractions cloning, semantic/mental rules updates).

Important: This manual page is a semantic English rewrite of the original Word-export. It keeps the architecture and key identifiers, but uses a simplified presentation for readability.

Chapter 3: Memory Models and Abstractions (Episode ? Knowledge)

3.1 Three Memory Levels

LevelStored inWhat it storesKey
Semantic SemanticMemory, SemanticMemoryIndex Stimulus significance (meanImportance) in conditions (well, emotionId, finalImageId)
Episodic Episodes Rules: condition ? stimulus ? action ? effect ? operator response Index in array (order matters)
Abstractions (clones) AbstractPerceptionImages, AbstractActionImages Clones of hard images; their semanticStructure contains rules by branch+context (perceptionNodeId, stimulusImageId) or (perceptionNodeId, actionImageId)

3.2 Semantic Memory: Importance of an Image

Semantic memory answers: ˜How important is this stimulus in these circumstances?˜. A semantic record stores a running average of effect-based usefulness.

Semantic record (structure):

{
  wellNormaBad: 1|2|3,   // Poor/Normal/Well
  emotionId: number,    // Emotion (combination of basic contexts)
  finalImageId: number,// Stimulus image ID
  meanImportance: number, // average importance (smoothed effect)
  samplesCount: number,   // number of observations
  lastImportance: number   // last stored value
}

Semantic records are updated in two places:

3.3 Episodic Memory: Rules and Their Closure

Episodic memory stores frames describing what happened: in which conditions, what stimulus, what action, what effect, and how the operator responded.

Episodic frame (structure):

{
  perceptionNodeId: number,      // perception tree branch ID (conditions)
  stimulusImageId: number,      // stimulus image ID
  situationId: number,          // situation ID (from situations tree)
  actionImageId: number|null,  // action image ID (null until executed)
  effect: number|null,         // effect (-10..+10, null while open)
  responseStimulusImageId: number|null, // operator answer image ID
  diffBefore: number,          // importance before activation (for effect calculation)
  createdAt: number            // timestamp
}

A frame has a lifecycle: created after OR threshold passes (waiting starts), filled with actions during startAction, and closed by operator response, timeout, or a new OR winner.

3.4 Abstractions: Clones of Hard Images

Abstractions are ˜clones˜ of hard perception/action images. Unlike their hard prototypes, they can be freely combined and exist as long-lived structures. Abstractions maintain a semanticStructure, a set of rules bound to specific conditions (branch + situation).

3.4.1 Two clone types

TypeArrayKeyCreated when
Perception clone AbstractPerceptionImages perceptionNodeId + stimulusImageId When the episodic frame closes (always)
Action clone AbstractActionImages perceptionNodeId + actionImageId When the episodic frame closes (only if actionImageId > 0)

3.4.2 Rule priorities inside semanticStructure

3.5 Mental Automatisms and ˜Symbols˜

Over abstractions, an additional mental layer is built: symbols (abstractions) and mental automatisms (MentalAutomatizms). Mental rules are created from episodic feedback and link the semantic abstraction to a mental action. After operator feedback with positive effect, mental automatisms can be created from semanticStructure rules.

Chapter 4: Gestalts, Dominants, and Insights

4.1 What is a Gestalt in BEAST

A gestalt is a long-lived dominant: a record about an unsolved task. Unlike an episodic frame (˜what happened˜ within one cycle), a gestalt lives across many cycles and can accumulate information about attempts to solve the problem.

4.4 Gestalt Resonance Buffer

A gestalt has a FIFO resonance buffer containing signatures of closed episodic frames. Each signature is an ˜experience snapshot˜ that can later support analogy-based reasoning.

Resonance buffer rules (summary)

4.5 Insights and Analogies

Insights link a gestalt˜s goal-image representation to a concrete candidate solution (an automatism/analogy), changing how the system understands the problem.

4.10 Current Implementation Limits

  1. No gestalt re-opening: if a gestalt is closed successfully (status=3), a new record for the same goal is not created.
  2. No full ˜gestalt building˜: analogyPool accumulates analogies, but does not necessarily synthesize a new rule from them yet.
  3. Gestalts do not directly influence goal selection: they provide context for level 3 but do not initiate a goal switch by themselves.
  4. No ˜forgetting˜: archived gestalts (status=4) are not deleted/cleaned.

Chapter 5: Persistence and State Saving

5.1 Two Persistence Strategies

StrategyMechanismPurposeFrequency
Automatic IndexedDB Save system state between page reloads On every data change (dirty flags)
Manual File System Access API Export/import a full ˜memory snapshot˜ On operator command (Save/Load buttons)

5.2 IndexedDB: Automatic Background Saving

The wrapper and saver registration mechanism are implemented in sys/IndexedDB/indexeddb.js. Each module registers a function via registerIndexedDBSaver.

5.2.3 Optimization: dirty flag + state signature

Modules use a combination of:

If the signature did not change, the system avoids writing again even if some metadata changed ˜semantically˜.

5.3 Saving to File: Full Memory Snapshot

In date/saving_ui.js there is a registry of BEAST.persistentModules. Each module registers:

Examples of registered modules:

KeyModuleWhat is saved
Cur_puls_valpuls.jsPulse counter
VitalsValuesvitals.jsVitals values
SemanticStatesemantic_memory.jsAll semantic memory
ConditionalReflexesStatesynonyms_reflexes.jsConditional reflexes
PerceptionTreeStateperception_tree.jsPerception tree
ActionImagesStateactions_image.jsAction images
EpisodesStateepisodic_memory.jsEpisodic frames (episodes)
AutomatizmsStateautomatizms.jsAutomatisms
GoalImagesStategoals.jsGoal images (life goals)
Abstractionsabstract_images.jsAbstract clones
Gestaltsgestalt.jsGestalt state
SituationsAndThemessituations treeSituations/themes

End of manual.