From cd63596316a8e6565d82a4dd2dbabb4e7dcd0892 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 30 Dec 2025 13:10:33 +0000 Subject: [PATCH] docs(dag): add README documentation for examples Add comprehensive documentation for all 13 DAG examples: examples/README.md: - Quick start guide with cargo commands - Core examples: basic_usage, attention_demo, attention_selection, learning_workflow, self_healing - Exotic examples: synthetic_haptic, synthetic_reflex_organism, timing_synchronization, coherence_safety, artificial_instincts, living_simulation, thought_integrity, federated_coherence - Architecture diagram showing component relationships - Key concepts: Tension, Coherence, Reflex Modes - Performance notes and testing instructions examples/exotic/README.md: - Philosophy of coherence-sensing substrates - Detailed explanation of each exotic example - Core insight: intelligence as homeostasis - Key metrics table (tension, coherence, cut value, criticality) - References to related concepts (free energy principle, autopoiesis) --- crates/ruvector-dag/examples/README.md | 294 ++++++++++++++++++ crates/ruvector-dag/examples/exotic/README.md | 148 +++++++++ 2 files changed, 442 insertions(+) create mode 100644 crates/ruvector-dag/examples/README.md create mode 100644 crates/ruvector-dag/examples/exotic/README.md diff --git a/crates/ruvector-dag/examples/README.md b/crates/ruvector-dag/examples/README.md new file mode 100644 index 00000000..7aef34ff --- /dev/null +++ b/crates/ruvector-dag/examples/README.md @@ -0,0 +1,294 @@ +# RuVector DAG Examples + +Comprehensive examples demonstrating the Neural Self-Learning DAG system. + +## Quick Start + +```bash +# Run any example +cargo run -p ruvector-dag --example + +# Run with release optimizations +cargo run -p ruvector-dag --example --release + +# Run tests for an example +cargo test -p ruvector-dag --example +``` + +## Core Examples + +### basic_usage +Fundamental DAG operations: creating nodes, adding edges, topological sort. + +```bash +cargo run -p ruvector-dag --example basic_usage +``` + +**Demonstrates:** +- `QueryDag::new()`, `add_node()`, `add_edge()` +- `OperatorNode` types: SeqScan, Filter, Sort, Aggregate +- Topological iteration and depth computation + +### attention_demo +All 7 attention mechanisms with visual output. + +```bash +cargo run -p ruvector-dag --example attention_demo +``` + +**Demonstrates:** +- `TopologicalAttention` - DAG layer-based scoring +- `CriticalPathAttention` - Longest path weighting +- `CausalConeAttention` - Ancestor/descendant influence +- `MinCutGatedAttention` - Bottleneck-aware attention +- `HierarchicalLorentzAttention` - Hyperbolic embeddings +- `ParallelBranchAttention` - Branch parallelism scoring +- `TemporalBTSPAttention` - Time-aware plasticity + +### attention_selection +UCB bandit algorithm for dynamic mechanism selection. + +```bash +cargo run -p ruvector-dag --example attention_selection +``` + +**Demonstrates:** +- `AttentionSelector` with UCB1 exploration/exploitation +- Automatic mechanism performance tracking +- Adaptive selection based on observed rewards + +### learning_workflow +Complete SONA learning pipeline with trajectory recording. + +```bash +cargo run -p ruvector-dag --example learning_workflow +``` + +**Demonstrates:** +- `DagSonaEngine` initialization and training +- `DagTrajectoryBuffer` for lock-free trajectory collection +- `DagReasoningBank` for pattern storage +- MicroLoRA fast adaptation +- EWC++ continual learning + +### self_healing +Autonomous anomaly detection and repair system. + +```bash +cargo run -p ruvector-dag --example self_healing +``` + +**Demonstrates:** +- `HealingOrchestrator` configuration +- `AnomalyDetector` with statistical thresholds +- `LearningDriftDetector` for performance degradation +- Custom `RepairStrategy` implementations +- Health score computation + +## Exotic Examples + +These examples explore unconventional applications of coherence-sensing substrates—systems that respond to internal tension rather than external commands. + +### synthetic_haptic ⭐ NEW +Complete nervous system for machines: sensor → reflex → actuator with memory and learning. + +```bash +cargo run -p ruvector-dag --example synthetic_haptic +``` + +**Architecture:** +| Layer | Component | Purpose | +|-------|-----------|---------| +| 1 | Event Sensing | Microsecond timestamps, 6-channel input | +| 2 | Reflex Arc | DAG tension + MinCut → ReflexMode | +| 3 | HDC Memory | 256-dim hypervector associative memory | +| 4 | SONA Learning | Coherence-gated adaptation | +| 5 | Actuation | Energy-budgeted force + vibro output | + +**Key Concepts:** +- Intelligence as homeostasis, not goal-seeking +- Tension drives immediate response +- Coherence gates learning (only when stable) +- ReflexModes: Calm → Active → Spike → Protect + +**Performance:** 192 μs avg loop @ 1000 Hz + +### synthetic_reflex_organism +Intelligence as homeostasis—organisms that minimize stress without explicit goals. + +```bash +cargo run -p ruvector-dag --example synthetic_reflex_organism +``` + +**Demonstrates:** +- `ReflexOrganism` with metabolic rate and tension tracking +- `OrganismResponse`: Rest, Contract, Expand, Partition, Rebalance +- Learning only when instability crosses thresholds +- No objectives, only stress minimization + +### timing_synchronization +Machines that "feel" timing through phase alignment. + +```bash +cargo run -p ruvector-dag --example timing_synchronization +``` + +**Demonstrates:** +- Phase-locked loops using DAG coherence +- Biological rhythm synchronization +- Timing deviation as tension signal +- Self-correcting temporal alignment + +### coherence_safety +Safety as structural property—systems that shut down when coherence drops. + +```bash +cargo run -p ruvector-dag --example coherence_safety +``` + +**Demonstrates:** +- `SafetyEnvelope` with coherence thresholds +- Automatic graceful degradation +- No external safety monitors needed +- Structural shutdown mechanisms + +### artificial_instincts +Hardwired biases via MinCut boundaries and attention patterns. + +```bash +cargo run -p ruvector-dag --example artificial_instincts +``` + +**Demonstrates:** +- Instinct encoding via graph structure +- MinCut-enforced behavioral boundaries +- Attention-weighted decision biases +- Healing as instinct restoration + +### living_simulation +Simulations that model fragility, not just outcomes. + +```bash +cargo run -p ruvector-dag --example living_simulation +``` + +**Demonstrates:** +- Coherence as simulation health metric +- Fragility-aware state evolution +- Self-healing simulation repair +- Tension-driven adaptation + +### thought_integrity +Reasoning monitored like electrical voltage—coherence as correctness signal. + +```bash +cargo run -p ruvector-dag --example thought_integrity +``` + +**Demonstrates:** +- Reasoning chain as DAG structure +- Coherence drops indicate logical errors +- Self-correcting inference +- Integrity verification without external validation + +### federated_coherence +Distributed consensus through coherence, not voting. + +```bash +cargo run -p ruvector-dag --example federated_coherence +``` + +**Demonstrates:** +- `FederatedNode` with peer coherence tracking +- 7 message types for distributed coordination +- Pattern propagation via coherence alignment +- Consensus emerges from structural agreement + +## Architecture Overview + +``` +┌─────────────────────────────────────────────────────────┐ +│ QueryDag │ +│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ +│ │Scan │──▶│Filter│──▶│Agg │──▶│Sort │──▶│Result│ │ +│ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ +└─────────────────────────────────────────────────────────┘ + │ │ │ + ▼ ▼ ▼ +┌───────────────┐ ┌───────────────┐ ┌───────────────┐ +│ Attention │ │ MinCut │ │ SONA │ +│ Mechanisms │ │ Engine │ │ Learning │ +│ (7 types) │ │ (tension) │ │ (coherence) │ +└───────────────┘ └───────────────┘ └───────────────┘ + │ │ │ + └───────────────────┴───────────────────┘ + │ + ▼ + ┌───────────────┐ + │ Healing │ + │ Orchestrator │ + └───────────────┘ +``` + +## Key Concepts + +### Tension +How far the current state is from homeostasis. Computed from: +- MinCut flow capacity stress +- Node criticality deviation +- Sensor/input anomalies + +**Usage:** Drives immediate reflex-level responses. + +### Coherence +How consistent the internal state is over time. Drops when: +- Tension changes rapidly +- Partitioning becomes unstable +- Learning causes drift + +**Usage:** Gates learning and safety decisions. + +### Reflex Modes +| Mode | Tension | Behavior | +|------|---------|----------| +| Calm | < 0.20 | Minimal response, learning allowed | +| Active | 0.20-0.55 | Proportional response | +| Spike | 0.55-0.85 | Heightened response, haptic feedback | +| Protect | > 0.85 | Protective shutdown, no output | + +## Running All Examples + +```bash +# Quick verification +for ex in basic_usage attention_demo attention_selection \ + learning_workflow self_healing synthetic_haptic; do + echo "=== $ex ===" && cargo run -p ruvector-dag --example $ex 2>/dev/null | head -20 +done + +# Exotic examples +for ex in synthetic_reflex_organism timing_synchronization coherence_safety \ + artificial_instincts living_simulation thought_integrity federated_coherence; do + echo "=== $ex ===" && cargo run -p ruvector-dag --example $ex 2>/dev/null | head -20 +done +``` + +## Testing + +```bash +# Run all example tests +cargo test -p ruvector-dag --examples + +# Test specific example +cargo test -p ruvector-dag --example synthetic_haptic +``` + +## Performance Notes + +- **Attention**: O(V+E) for topological, O(V²) for causal cone +- **MinCut**: O(n^0.12) amortized with caching +- **SONA Learning**: Background thread, non-blocking +- **Haptic Loop**: Target <1ms, achieved ~200μs average + +## License + +MIT - See repository root for details. diff --git a/crates/ruvector-dag/examples/exotic/README.md b/crates/ruvector-dag/examples/exotic/README.md new file mode 100644 index 00000000..86e401f0 --- /dev/null +++ b/crates/ruvector-dag/examples/exotic/README.md @@ -0,0 +1,148 @@ +# Exotic Examples: Coherence-Sensing Substrates + +These examples explore systems that respond to internal tension rather than external commands—where intelligence emerges as homeostasis. + +## Philosophy + +Traditional AI systems are goal-directed: they receive objectives and optimize toward them. These examples flip that model: + +> **Intelligence as maintaining coherence under perturbation.** + +A system doesn't need goals if it can feel when it's "out of tune" and naturally moves toward equilibrium. + +## The Examples + +### 1. synthetic_reflex_organism.rs +**Intelligence as Homeostasis** + +No goals, only stress minimization. The organism responds to tension by adjusting its internal state, learning only when instability crosses thresholds. + +```rust +pub enum OrganismResponse { + Rest, // Low tension: do nothing + Contract, // Rising tension: consolidate + Expand, // Stable low tension: explore + Partition, // High tension: segment + Rebalance, // Oscillating: redistribute +} +``` + +### 2. timing_synchronization.rs +**Machines That Feel Timing** + +Phase-locked loops using DAG coherence. The system "feels" when its internal rhythms drift from external signals and self-corrects. + +```rust +// Timing is not measured, it's felt +let phase_error = self.measure_phase_deviation(); +let tension = self.dag.compute_tension_from_timing(phase_error); +self.adjust_internal_clock(tension); +``` + +### 3. coherence_safety.rs +**Structural Safety** + +Safety isn't a monitor checking outputs—it's a structural property. When coherence drops below threshold, the system naturally enters a safe state. + +```rust +// No safety rules, just coherence +if coherence < 0.3 { + // System structurally cannot produce dangerous output + // because the pathways become disconnected +} +``` + +### 4. artificial_instincts.rs +**Hardwired Biases** + +Instincts encoded via MinCut boundaries and attention patterns. These aren't learned—they're structural constraints that shape behavior. + +```rust +// Fear isn't learned, it's architectural +let fear_boundary = mincut.compute(threat_region, action_region); +if fear_boundary.cut_value < threshold { + // Action pathway is structurally blocked +} +``` + +### 5. living_simulation.rs +**Fragility-Aware Modeling** + +Simulations that model not just outcomes, but structural health. The simulation knows when it's "sick" and can heal itself. + +```rust +// Simulation health = structural coherence +let health = simulation.dag.coherence(); +if health < 0.5 { + simulation.trigger_healing(); +} +``` + +### 6. thought_integrity.rs +**Reasoning Monitored Like Voltage** + +Logical inference as a DAG where coherence indicates correctness. Errors show up as tension in the reasoning graph. + +```rust +// Contradiction creates structural tension +let reasoning = build_inference_dag(premises, conclusion); +let integrity = reasoning.coherence(); +// Low integrity = likely logical error +``` + +### 7. federated_coherence.rs +**Consensus Through Coherence** + +Distributed systems that agree not by voting, but by structural alignment. Nodes synchronize patterns when their coherence matrices align. + +```rust +pub enum FederationMessage { + Heartbeat { coherence: f32 }, + ProposePattern { pattern: DagPattern }, + ValidatePattern { id: String, local_coherence: f32 }, + RejectPattern { id: String, tension_source: String }, + TensionAlert { severity: f32, region: Vec }, + SyncRequest { since_round: u64 }, + SyncResponse { patterns: Vec }, +} +``` + +## Core Insight + +These systems demonstrate that: + +1. **Intelligence doesn't require goals** — maintaining structure is sufficient +2. **Safety can be architectural** — not a bolt-on monitor +3. **Learning should be gated** — only update when stable +4. **Consensus can emerge** — from structural agreement, not voting + +## Running + +```bash +# Run all exotic examples +for ex in synthetic_reflex_organism timing_synchronization \ + coherence_safety artificial_instincts living_simulation \ + thought_integrity federated_coherence; do + cargo run -p ruvector-dag --example $ex +done +``` + +## Key Metrics + +| Metric | Meaning | Healthy Range | +|--------|---------|---------------| +| Tension | Deviation from equilibrium | < 0.3 | +| Coherence | Structural consistency | > 0.8 | +| Cut Value | Flow capacity stress | < 100 | +| Criticality | Node importance | 0.0-1.0 | + +## Further Reading + +These concepts draw from: +- Homeostatic regulation in biological systems +- Free energy principle (Friston) +- Autopoiesis (Maturana & Varela) +- Active inference +- Predictive processing + +The key shift: from "what should I do?" to "how do I stay coherent?"