You got it! Here is the entire, unabridged `README.md` file, incorporating all the recent additions and explanations, including the detailed testing section.
--- START OF COMPLETE README.md ---
# Autaxys Prime Engine: A Multiverse Explorer
**Version: 12.2 (S-Level Aware, Framework-Aligned Simulation)**
**Guided by: [Autaxic Table of Patterns: A Unified Generative Framework (v1.9)](D-P6.7-1_Unified_Framework_v1.9.md)**
*(Familiarity with the Framework Document is highly recommended for a deep understanding of this simulation.)*
## 1. Introduction: What is Autaxys?
**Autaxys** is a theoretical framework positing that reality is not built from fundamental "things" but emerges as a **self-generating, self-organizing computational system**. The core principle is **Ontological Closure (OC)**: only patterns that are perfectly self-consistent can persist. Fundamental *Distinctions* (D) and *Relations* (R), endowed with inherent *Proto-Properties*, interact according to a **Cosmic Algorithm**. Stable particles, forces, and even spacetime are hypothesized to be emergent properties of these stable relational patterns.
The **Autaxys Prime Engine** is a research instrument designed to computationally explore these core ideas. It begins with a conceptual void and attempts to generate stable "universes" (represented as relational graphs) based on the drive to achieve Ontological Closure.
## 2. Core Autaxys Concepts Simulated
This engine models key elements of the Autaxys framework (v1.9) to explore emergent stability:
### 2.1. Primitives: Distinction (D) and Relation (R)
The simulation uses a graph structure where:
* **Distinctions (D) are Nodes:**
* They represent the fundamental act of differentiation.
* **Key Simulated Proto-Properties & Attributes:**
* `id`: Unique identifier.
* `polarity`: A fundamental `+1` or `-1` bias, influencing bonding.
* `protoType`: (Standard, Leptonic, Quarkic) – A basic classification affecting behavior and potential adaptations.
* `protoValence`: An *inherent* capacity (e.g., preferred number of bonds) for forming relations. This is a foundational proto-property.
* `valence`: The *current adaptive* capacity for relations. The simulator allows this to change (via the Adaptation rule) around the `protoValence`.
* `stress`: A calculated measure of local incoherence, often due to unmet `valence` or unfavorable local configurations (e.g., being surrounded by Distinctions of the same polarity when hetero-polar bonds are preferred for stability). High stress can trigger adaptation.
* `sLevel`: The intrinsic stability level of the Distinction itself (typically S₁ for a single, stable node).
* *Conceptual Proto-Properties:* The data structures also include placeholders for `symmetryBias`, `coherencePotential`, and `aestheticValue` (as described in the framework document) for future, more advanced rule implementations.
* **Relations (R) are Edges:**
* They represent the act of connecting or transforming Distinctions.
* **Key Simulated Proto-Properties & Attributes:**
* `flowResistance`: An inherent "cost" or difficulty associated with maintaining this specific relation. This contributes to the overall "energy" or "tension" of a graph.
* *Conceptual Proto-Properties:* Placeholders for `interactionChannelType`, `coherencePotential`, and `aestheticValue` exist for future rule development that could differentiate types of relations more fundamentally.
### 2.2. The Cosmic Algorithm: Simulated Rules of Existence
The simulation employs a dynamic, rule-based system. At each step, potential transformations (futures) are generated by these rules, and the "best" future is chosen based on its potential to improve Ontological Closure.
* **Genesis:** Creates new Distinctions from the conceptual void (empty graph), endowing them with initial proto-properties.
* **Bonding (a type of Formation):** Allows two compatible Distinctions (typically of opposite `polarity` and with available `valence`) to form a Relation. This rule is fundamental for building structure.
* **Annihilation (a type of Resolution):** If two Distinctions of opposite `polarity` are connected *only* to each other (representing a simple, fulfilled pair), they can resolve and be removed, simplifying the graph.
* **Adaptation:** Allows individual Distinctions to change their properties in response to `stress`, aiming for better local stability. The simulator currently implements:
* `valence` adaptation: Increasing or decreasing the number of desired connections.
* `polarity` adaptation: Flipping polarity under extreme stress.
* `protoType` adaptation: Changing fundamental type (e.g., Standard to Leptonic) if stress remains high.
* **Transformation:** Represents more fundamental changes to a Distinction's `protoType` than simple adaptation, based on persistent low stability or high stress.
* **Collapse (a type of Resolution/Simplification):** Simplifies certain redundant structures (e.g., a linear chain of three nodes can have the middle one removed), aiming to reduce complexity (`C`) without losing (or even while improving) stability (`S`).
* **Dynamic Rule Weighting (Foundational):** The simulation can (if enabled) adjust the preference for applying different rules. If a rule leads to a state with demonstrably better Ontological Closure, its "weight" or priority for future selection can increase. This is a rudimentary implementation of the framework's concept of an "algorithmic self-modification" or a "learning" universe.
### 2.3. Ontological Closure (OC) and The S-Levels (Simulated Interpretation)
Ontological Closure is the central principle: only patterns that are sufficiently self-consistent can persist. The simulator evaluates the "quality" of OC for a given graph state using a **Pattern Descriptor**, which includes:
* **`C` (Complexity):** A measure of the pattern's structural intricacy (sum of Distinctions and Relations). Lower `C` for a given level of stability is generally preferred (Economy of Existence).
* **`S` (Stability Index):** This is a composite measure reflecting:
* **`S.level` (S-Level):** Categorizes the *mechanism* by which the pattern achieves stability. The simulator attempts to identify the following S-Levels:
* **S₀ (Vacuum):** The empty graph. The state of pure potential, maximal relational entropy.
* **S₁ (Simple Fixed Point):** A static, unchanging graph configuration. This is the most basic form of OC. Any non-empty graph that isn't changing and isn't part of a limit cycle is initially considered S₁.
* **S₂ (Recursive Structure):** A pattern stable due to self-referential internal loops or repeating structural motifs. The simulator has *basic heuristic detection* for S₂ (e.g., a simple 3-cycle of identical nodes). True S₂ detection is a complex graph-theoretic problem.
* **S₃ (Dynamic Equilibrium / Limit Cycle):** A pattern that is stable because it oscillates through a repeating cycle of different graph states. The simulator detects this by hashing graph states and identifying if a previously encountered state reappears.
* **S₄ (Composite Stability):** A higher-order pattern formed by the stable composition of simpler, S-Level-achieving patterns (e.g., two S₁ "particles" stably bound to form an S₄ "molecule"). *Current S₄ detection is a placeholder and a major area for future development.* It would require identifying stable sub-components and assessing the stability of their overall arrangement.
* **S₅+ (Higher-Order Closure):** Levels like Environmental Meta-stability, Adaptive Closure (S₆), or Reflexive Consciousness (S₇) are highly complex and *beyond the current simulation's direct modeling capabilities*, but represent the conceptual upper tiers of OC in the Autaxys framework.
* **`S.robustness`:** A quantitative measure of coherence, currently based on the density of hetero-polar bonds relative to complexity. Higher robustness is preferred.
* **`totalStress`:** The sum of `stress` on all Distinctions. Lower total stress indicates less "Relational Tension" and is preferred.
* **`totalRelationFlowResistance`:** The sum of `flowResistance` from all Relations. Lower resistance might imply a more "efficient" or "less costly" structure.
The simulation's core loop involves generating potential next states (futures) by applying rules, evaluating their `PatternDescriptor`s, and selecting the future that represents the "best" step towards improved OC (e.g., higher S-Level, then higher robustness, then lower complexity, then lower stress).
## 3. The Experimental Design & Simulation Modes
The workbench provides distinct modes to investigate Autaxic principles:
### 3.1. Single Timeline Explorer
* **Purpose:** To observe the detailed, step-by-step evolution of a single "universe" (graph) as it seeks Ontological Closure.
* **Interpretation:** Watch how a graph, starting from a single Distinction, applies rules, adapts its components, and changes its structure. The goal is to see if it can reach a high S-Level (e.g., an S₃ limit cycle or a complex S₁/S₂ static structure) and what that structure looks like. If it collapses to S₀ (vacuum), it's a "fizzled attempt," and the simulation can be restarted.
* **Observables:** Live graph visualization, detailed live statistics (C, S-Level, Robustness, Stress, etc.), and the dynamic evolution of rule weights (if enabled).
### 3.2. Multiverse Census
* **Purpose:** To statistically map the landscape of possible stable outcomes (P\_IDs in framework terms) by running many independent simulations.
* **Interpretation:** Each point in the multiverse visualization represents a universe that ran until it halted (e.g., reached S₁, S₃, or a rule-exhausted state) and had a complexity C > 1. This helps understand which types of stable structures (characterized by their S-Level and C) are common or rare given the current rule set and configurations.
* **Observables:** A force-directed layout of stable universes (points sized by C, colored by S-Level), and aggregate statistics (total attempts, number of stable universes, highest S-Level found across all attempts).
### 3.3. Divergence Engine
* **Purpose:** To illustrate the "butterfly effect" – how tiny differences (in this case, numerical precision) can lead to vastly different evolutionary paths. This is a key Autaxys concept for how novelty can arise from the inherent "computational substrate."
* **Interpretation:** Observe two universes, starting from identical seeds and rules, diverge due to the subtle differences between high-precision and native floating-point arithmetic. This highlights how the system might explore different paths to OC.
* **Observables:** Side-by-side graph visualizations and a notification of the step at which their macroscopic graph structures first differ.
## 4. How to Use This Instrument
1. **Install dependencies:** `npm install`
2. **Start the application:** `npm start`
3. **Explore:**
* Open `http://localhost:1234`.
* **Select Mode:** Choose from "Single Timeline," "Multiverse Census," or "Divergence Engine."
* **Configure Simulator (Sidebar):** Before starting, or during a pause, you can adjust these settings. They influence the behavior of the Cosmic Algorithm rules:
* **`Enable Valence Adaptation`**: (Tooltip: Allows Distinctions (nodes) to dynamically change their adaptive 'valence' (number of desired connections) based on their 'stress' levels. Helps them seek better local bonding configurations. (Autaxys 'Adaptation' rule))
* **`Enable Polarity Adaptation`**: (Tooltip: If a Distinction is under very high 'stress', this allows it to flip its 'polarity' (+/-). A more drastic adaptation to find a compatible environment. (Autaxys 'Adaptation' rule))
* **`Enable ProtoType Adaptation`**: (Tooltip: Under very high and persistent 'stress', Distinctions can change their fundamental 'protoType' (e.g., Standard to Leptonic). Allows exploration of different inherent behavioral characteristics. (Autaxys 'Adaptation' rule))
* **`Enable ProtoType Transformation`**: (Tooltip: A more fundamental rule allowing a Distinction to change its 'protoType' based on broader conditions like persistent low stability (S-Level) or specific stress patterns. (Autaxys 'Transformation' rule))
* **`Enable Collapse Rule`**: (Tooltip: Activates a rule that looks for simple, redundant structures (e.g., a linear chain of three nodes) and simplifies them. Helps reduce unnecessary complexity ('C') and 'Relational Tension'. (Autaxys 'Resolution/Simplification' rule))
* **`Enable Dynamic Rule Weighting`**: (Tooltip: Allows the simulation to 'learn' by increasing the preference for rules that have historically led to states with better Ontological Closure (higher S-Level, better robustness, lower complexity/stress). (Rudimentary Autaxys 'algorithmic self-modification'))
* *These settings affect simulations started after changes are made, or new universes in Multiverse mode.*
* **Press "Start/Pause/Resume/Restart":** Control the simulation flow.
* **Observe Panels:**
* **Main Canvas:** Visualizes the active simulation mode.
* **Live Statistics:** Displays key metrics (C, S-Level, Robustness, Stress) for the current primary simulation.
* **Dynamic Rule Weights:** Shows the evolving priorities of different rules (if enabled for the current mode).
* **Export Multiverse Data:** Save a CSV summary of stable universes found.
## 5. Testing the Simulator Logic (Using Jest)
The integrity of the simulation relies on the core logic within `simulator.ts` behaving as expected. Unit tests using the Jest framework are provided to verify key functionalities.
### 5.1. Test Setup
Before running tests, ensure you have installed the development dependencies:
```bash
npm install
```
This command (if not run before) installs Jest, `ts-jest` (for TypeScript compatibility with Jest), and other necessary packages defined in `package.json`. The project includes a `jest.config.js` file that configures Jest to work with TypeScript.
### 5.2. Running Tests
To execute the unit tests, open your terminal in the project's root directory and run:
```bash
npm test
```
Or, if you use Yarn:
```bash
yarn test
```
Jest will discover and run all test files (typically those ending in `.test.ts` or `.spec.ts`, like `simulator.test.ts`).
### 5.3. Interpreting Test Output
After running, Jest will provide a summary in your terminal:
* **PASS/FAIL Status:** For each test suite (e.g., `simulator.test.ts`) and each individual test case within it.
* **Number of Tests:** Total tests run, number passed, number failed.
* **Error Messages (for failures):** If a test fails, Jest will typically show:
* The specific assertion that failed (e.g., `expect(received).toBe(expected)`).
* The `received` value versus the `expected` value.
* A stack trace pointing to the line in the test file and potentially the source code where the failure occurred.
* **Coverage Report (Optional):** If configured (e.g., by running `npm test -- --coverage`), Jest can generate a report showing what percentage of your code lines, functions, and branches are covered by tests.
### 5.4. What is Being Tested (`simulator.test.ts`)
The `simulator.test.ts` file aims to cover critical aspects of the simulation logic:
* **Basic Initialization & Reset:** Ensures the simulator starts in a clean state and can be reset correctly.
* **Ignition Step:** Verifies that the simulation correctly initializes from an empty graph by creating the first Distinction.
* **Node Stress Calculation:** Tests various scenarios to ensure `stress` on Distinctions is calculated accurately based on unmet `valence`, over-bonding, and local environment (e.g., homogeneity of neighbors' polarity).
* **Pattern Descriptor Calculation:** Checks that the `PatternDescriptor` (Complexity `C`, S-Level, Robustness, Total Stress) is computed correctly for different simple graph states (empty, single node, bonded pair).
* **Core Rule Application (Heuristic Checks):**
* Attempts to verify that rules like `Genesis` and `Bonding` produce their expected outcomes (e.g., adding a node, adding an edge) under favorable conditions. *Note: These tests can be somewhat probabilistic due to the nature of rule selection. Failures here might indicate issues in rule selection logic or that the specific test conditions weren't met quickly.*
* **Adaptation Rule Effects:** Tests if specific adaptation sub-rules (e.g., `adaptation_valence_up`) trigger and correctly modify Distinction attributes under appropriate stress conditions.
* **Dynamic Rule Weighting:** Conceptually tests if rule weights change (increase) after a demonstrably "beneficial" move occurs (i.e., a move that improves the Pattern Descriptor).
* **`selectBestFuture` Logic:** Directly tests the decision-making process for choosing the next state. It uses mock "future" states with varying `PatternDescriptor` values to ensure the selection prioritizes:
1. Higher S-Level.
2. Higher Robustness (at the same S-Level).
3. Lower Complexity (at the same S-Level & Robustness).
4. Lower Total Stress (if other primary metrics are equal).
5. Influence of rule weights and move costs as tie-breakers.
6. The exploratory logic to prevent premature halting.
### 5.5. Addressing Test Failures and Improving Tests
* **Logic Errors:** If tests for `calculateNodeStress`, `calculatePatternDescriptor`, or `selectBestFuture` (with mock data) fail, it likely indicates a direct bug in that calculation or comparison logic. Use `console.log` statements in your simulator code or a debugger to trace values and identify the issue.
* **Probabilistic Rule Application Failures:** For tests verifying that a specific rule like `Genesis` or `Bonding` *is chosen and applied*, failures might occur if other rules were selected instead during the limited steps of the test. To make these more robust:
* Consider creating highly specific graph states within the test where the target rule is the *only* or overwhelmingly most beneficial option.
* For focused rule testing, you could temporarily modify the `initializeRules` method (perhaps with a test-specific configuration) to load *only* the rule under test.
* **Coverage:** Regularly check test coverage (`npm test -- --coverage`). Identify untested critical sections of `simulator.ts` and write new tests for them. Aim for high coverage of decision logic and calculations.
* **Keep Tests Updated:** As you evolve `simulator.ts` (e.g., add new rules, change S-Level detection, modify proto-properties), ensure your unit tests are updated to reflect these changes.
Thorough unit testing is essential for building confidence in the complex, emergent behavior of the Autaxys Prime Engine.
## 6. Current Status & Roadmap (Bridging the Vision)
This Autaxys Prime Engine (v12.2) is an evolving research tool focused on simulating the emergence of stable relational patterns based on the Autaxys framework (v1.9).
### 6.1. Implemented & Initiated Features:
* **Core Primitives (D/R):** Nodes (D) and Edges (R) have attributes for polarity, protoType, adaptive valence (influenced by `protoValence`), stress, and flowResistance.
* **Rule-Based Cosmic Algorithm:** Implements Genesis, Bonding (Formation), Annihilation (Resolution), multi-faceted Adaptation, Transformation, and a basic Collapse rule.
* **Ontological Closure (OC) Drive:** Simulation prioritizes moves that improve a `PatternDescriptor` (measuring C, S-Level, Robustness, Stress).
* **S-Level Awareness:** Actively attempts to detect and classify states as S₀, S₁, S₂ (basic heuristics), and S₃. S₄ is a structural placeholder.
* **Dynamic Rule Weighting:** Foundational mechanism for rules to "learn" based on OC improvement.
* **Configurable Simulation Modes:** Timeline, Multiverse, and Divergence modes for different analytical perspectives.
* **UI Controls & Enhanced Statistics:** Provides user control over key simulation mechanics and detailed feedback.
### 6.2. Key Areas for Future Development (Roadmap):
To fully realize the Autaxys Prime Engine as a definitive research instrument for the framework:
* **Sophisticated Proto-Property Dynamics:** Fully activate all conceptual proto-properties (e.g., `symmetryBias`, `interactionChannelType`) and define their influence on rule applicability, outcomes, and OC. Model interactions *between* different proto-properties.
* **Richer Cosmic Algorithm Rules:**
* **General Formation/Composition:** Move beyond simple bonding to rules that allow for more complex compositions based on diverse proto-property compatibilities and topological matching (essential for S₄).
* **Propagation & Interaction Rules ($I_R$):** Implement how influence, state changes, or "force-like" effects propagate through the relational network. This is key for emergent field-like behaviors and more complex interactions.
* **True S₂ and S₄ Detection & Validation:** Develop robust graph-theoretic algorithms to identify recursive structures (S₂) and stable composite patterns (S₄) as part of the OC validation, not just post-hoc analysis. This is critical for exploring higher-order stability.
* **Guiding Principles:** More explicitly implement "Symmetry Preference" and "Economy of Existence" (beyond current S/C in selection) to bias rule application and potentially algorithmic self-modification.
* **Quantum Rule:** Introduce probabilistic elements for resolving ambiguous states or rule choices, reflecting the framework's view on quantum measurement.
* **S₀ Vacuum Model:** Explore models for S₀ that go beyond an empty graph, incorporating "texture" and "relational noise" that can influence Genesis and pattern stability.
* **Advanced Algorithmic Self-Modification:** Refine dynamic rule weighting and explore mechanisms for rules themselves to evolve or for new rules to emerge, as per framework section 4.5.
* **Formalism Link (Long-Term):** Strive to connect simulation heuristics with the developing mathematical *Relational Calculus* of the Autaxys framework, aiming to derive AQNs and behaviors from more fundamental equations.
* **Analytical & Visualization Tools:** "Universe Inspector" for detailed study of stable multiverse outcomes, persistent census data, advanced metrics, and visualizations for the "Autaxic phase space."
The Autaxys Prime Engine aims to be a powerful tool for exploring how complexity and stability can emerge from simple relational principles, offering insights into the fundamental nature of reality as envisioned by the Autaxys framework.
--- END OF COMPLETE README.md ---
This version should be much more helpful and complete.