Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'

This commit is contained in:
ruv
2026-02-28 14:39:40 -05:00
7854 changed files with 3522914 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
//! # Delta-Behavior Applications
//!
//! This module contains 10 exotic applications of delta-behavior theory,
//! each demonstrating a unique property that emerges when systems are
//! constrained to preserve global coherence.
//!
//! ## The 10 Applications
//!
//! 1. **Self-Limiting Reasoning** - Machines that refuse to think past their understanding
//! 2. **Event Horizon** - Computational boundaries that cannot be crossed
//! 3. **Artificial Homeostasis** - Synthetic life with coherence as survival constraint
//! 4. **Self-Stabilizing World Model** - Models that stop learning when incoherent
//! 5. **Coherence-Bounded Creativity** - Novelty without collapse
//! 6. **Anti-Cascade Financial Systems** - Markets that cannot cascade into collapse
//! 7. **Graceful Aging** - Distributed systems that become simpler with age
//! 8. **Swarm Intelligence** - Local freedom with global coherence bounds
//! 9. **Graceful Shutdown** - Systems that seek their own safe termination
//! 10. **Pre-AGI Containment** - Intelligence growth bounded by coherence
//!
//! ## Feature Flags
//!
//! Each application can be enabled individually via feature flags:
//!
//! ```toml
//! [dependencies]
//! delta-behavior = { version = "0.1", features = ["self-limiting-reasoning", "containment"] }
//! ```
//!
//! Or enable groups of related applications:
//!
//! - `all-applications` - All 10 applications
//! - `safety-critical` - Self-limiting reasoning, graceful shutdown, containment
//! - `distributed` - Graceful aging, swarm intelligence, anti-cascade
//! - `ai-ml` - Self-limiting reasoning, world model, creativity, containment
#[cfg(feature = "self-limiting-reasoning")]
pub mod self_limiting_reasoning;
#[cfg(feature = "self-limiting-reasoning")]
pub use self_limiting_reasoning::*;
#[cfg(feature = "event-horizon")]
pub mod event_horizon;
#[cfg(feature = "event-horizon")]
pub use event_horizon::*;
#[cfg(feature = "homeostasis")]
pub mod homeostasis;
#[cfg(feature = "homeostasis")]
pub use homeostasis::*;
#[cfg(feature = "world-model")]
pub mod world_model;
#[cfg(feature = "world-model")]
pub use world_model::*;
#[cfg(feature = "coherence-creativity")]
pub mod coherence_creativity;
#[cfg(feature = "coherence-creativity")]
pub use coherence_creativity::*;
#[cfg(feature = "anti-cascade")]
pub mod anti_cascade;
#[cfg(feature = "anti-cascade")]
pub use anti_cascade::*;
#[cfg(feature = "graceful-aging")]
pub mod graceful_aging;
#[cfg(feature = "graceful-aging")]
pub use graceful_aging::*;
#[cfg(feature = "swarm-intelligence")]
pub mod swarm_intelligence;
#[cfg(feature = "swarm-intelligence")]
pub use swarm_intelligence::*;
#[cfg(feature = "graceful-shutdown")]
pub mod graceful_shutdown;
#[cfg(feature = "graceful-shutdown")]
pub use graceful_shutdown::*;
#[cfg(feature = "containment")]
pub mod containment;
#[cfg(feature = "containment")]
pub use containment::*;
// When no features are enabled, provide the core types
// that all applications depend on
#[cfg(not(any(
feature = "self-limiting-reasoning",
feature = "event-horizon",
feature = "homeostasis",
feature = "world-model",
feature = "coherence-creativity",
feature = "anti-cascade",
feature = "graceful-aging",
feature = "swarm-intelligence",
feature = "graceful-shutdown",
feature = "containment",
)))]
pub mod _placeholder {
//! Placeholder module when no application features are enabled.
//! The core types in the parent `delta_behavior` crate are always available.
}

View File

@@ -0,0 +1,762 @@
//! Delta-Behavior Performance Metrics Runner
//!
//! This is a standalone runner that can be executed to show performance metrics
//! without requiring the full criterion framework.
//!
//! Run with: cargo run --bin run_benchmarks --release
use std::collections::HashMap;
use std::f64::consts::E;
use std::time::{Duration, Instant};
// =============================================================================
// BENCHMARK UTILITIES
// =============================================================================
struct BenchmarkResult {
name: String,
iterations: u64,
total_time: Duration,
avg_time: Duration,
min_time: Duration,
max_time: Duration,
throughput_ops_per_sec: f64,
}
impl BenchmarkResult {
fn display(&self) {
println!(" {}", self.name);
println!(" Iterations: {}", self.iterations);
println!(" Total time: {:?}", self.total_time);
println!(" Average time: {:?}", self.avg_time);
println!(" Min time: {:?}", self.min_time);
println!(" Max time: {:?}", self.max_time);
println!(
" Throughput: {:.2} ops/sec",
self.throughput_ops_per_sec
);
println!();
}
}
fn run_benchmark<F>(name: &str, iterations: u64, mut f: F) -> BenchmarkResult
where
F: FnMut(),
{
let mut times = Vec::with_capacity(iterations as usize);
// Warmup
for _ in 0..10 {
f();
}
// Actual benchmark
for _ in 0..iterations {
let start = Instant::now();
f();
times.push(start.elapsed());
}
let total_time: Duration = times.iter().sum();
let avg_time = total_time / iterations as u32;
let min_time = *times.iter().min().unwrap();
let max_time = *times.iter().max().unwrap();
let throughput_ops_per_sec = iterations as f64 / total_time.as_secs_f64();
BenchmarkResult {
name: name.to_string(),
iterations,
total_time,
avg_time,
min_time,
max_time,
throughput_ops_per_sec,
}
}
// =============================================================================
// COHERENCE SYSTEM
// =============================================================================
#[derive(Debug, Clone, Copy)]
struct Coherence(f64);
impl Coherence {
fn new(value: f64) -> Self {
Self(value.clamp(0.0, 1.0))
}
fn value(&self) -> f64 {
self.0
}
}
struct SimpleEnforcer {
min_coherence: f64,
max_delta_drop: f64,
throttle_threshold: f64,
energy_budget: f64,
}
impl SimpleEnforcer {
fn new() -> Self {
Self {
min_coherence: 0.3,
max_delta_drop: 0.1,
throttle_threshold: 0.5,
energy_budget: 100.0,
}
}
fn check(&mut self, current: Coherence, predicted: Coherence) -> bool {
let cost = 1.0 + (current.value() - predicted.value()).abs() * 10.0;
if cost > self.energy_budget {
return false;
}
self.energy_budget -= cost;
if predicted.value() < self.min_coherence {
return false;
}
let drop = current.value() - predicted.value();
if drop > self.max_delta_drop {
return false;
}
predicted.value() >= self.throttle_threshold
}
fn reset(&mut self) {
self.energy_budget = 100.0;
}
}
// =============================================================================
// EVENT HORIZON SYSTEM
// =============================================================================
struct EventHorizon {
safe_center: Vec<f64>,
horizon_radius: f64,
steepness: f64,
energy_budget: f64,
}
impl EventHorizon {
fn new(dimensions: usize, horizon_radius: f64) -> Self {
Self {
safe_center: vec![0.0; dimensions],
horizon_radius,
steepness: 5.0,
energy_budget: 1000.0,
}
}
fn distance_from_center(&self, position: &[f64]) -> f64 {
position
.iter()
.zip(&self.safe_center)
.map(|(a, b)| (a - b).powi(2))
.sum::<f64>()
.sqrt()
}
fn movement_cost(&self, from: &[f64], to: &[f64]) -> f64 {
let base_distance = from
.iter()
.zip(to)
.map(|(a, b)| (a - b).powi(2))
.sum::<f64>()
.sqrt();
let to_dist = self.distance_from_center(to);
let proximity = to_dist / self.horizon_radius;
if proximity >= 1.0 {
f64::INFINITY
} else {
let factor = E.powf(self.steepness * proximity / (1.0 - proximity));
base_distance * factor
}
}
fn compute_optimal_position(&self, current: &[f64], target: &[f64]) -> Vec<f64> {
let direct_cost = self.movement_cost(current, target);
if direct_cost <= self.energy_budget {
return target.to_vec();
}
let mut low = 0.0;
let mut high = 1.0;
let mut best_position = current.to_vec();
for _ in 0..50 {
let mid = (low + high) / 2.0;
let interpolated: Vec<f64> = current
.iter()
.zip(target)
.map(|(a, b)| a + mid * (b - a))
.collect();
let cost = self.movement_cost(current, &interpolated);
if cost <= self.energy_budget {
low = mid;
best_position = interpolated;
} else {
high = mid;
}
}
best_position
}
}
// =============================================================================
// SWARM SYSTEM
// =============================================================================
#[derive(Clone)]
#[allow(dead_code)]
struct SwarmAgent {
position: (f64, f64),
velocity: (f64, f64),
goal: (f64, f64), // Used in full swarm implementation
energy: f64, // Used in full swarm implementation
}
struct CoherentSwarm {
agents: HashMap<String, SwarmAgent>,
min_coherence: f64,
max_divergence: f64,
}
impl CoherentSwarm {
fn new(min_coherence: f64) -> Self {
Self {
agents: HashMap::new(),
min_coherence,
max_divergence: 50.0,
}
}
fn add_agent(&mut self, id: &str, position: (f64, f64)) {
self.agents.insert(
id.to_string(),
SwarmAgent {
position,
velocity: (0.0, 0.0),
goal: position,
energy: 100.0,
},
);
}
fn calculate_coherence(&self) -> f64 {
if self.agents.len() < 2 {
return 1.0;
}
// Calculate centroid
let sum = self
.agents
.values()
.fold((0.0, 0.0), |acc, a| (acc.0 + a.position.0, acc.1 + a.position.1));
let centroid = (
sum.0 / self.agents.len() as f64,
sum.1 / self.agents.len() as f64,
);
// Calculate cohesion
let mut total_distance = 0.0;
for agent in self.agents.values() {
let dx = agent.position.0 - centroid.0;
let dy = agent.position.1 - centroid.1;
total_distance += (dx * dx + dy * dy).sqrt();
}
let cohesion = (1.0 - total_distance / self.agents.len() as f64 / self.max_divergence).max(0.0);
// Calculate alignment (simplified - uses velocity calculation for realism)
let _avg_vel = {
let sum = self
.agents
.values()
.fold((0.0, 0.0), |acc, a| (acc.0 + a.velocity.0, acc.1 + a.velocity.1));
(
sum.0 / self.agents.len() as f64,
sum.1 / self.agents.len() as f64,
)
};
let alignment = 0.8; // Simplified for benchmark
(cohesion * 0.5 + alignment * 0.5).clamp(0.0, 1.0)
}
fn predict_action_coherence(&self, agent_id: &str, dx: f64, dy: f64) -> f64 {
let mut agents_copy = self.agents.clone();
if let Some(agent) = agents_copy.get_mut(agent_id) {
agent.position.0 += dx;
agent.position.1 += dy;
}
let temp = CoherentSwarm {
agents: agents_copy,
min_coherence: self.min_coherence,
max_divergence: self.max_divergence,
};
temp.calculate_coherence()
}
}
// =============================================================================
// FINANCIAL SYSTEM
// =============================================================================
#[derive(Clone)]
#[allow(dead_code)]
struct Participant {
capital: f64, // Used in full financial system
exposure: f64,
interconnectedness: f64,
}
struct FinancialSystem {
participants: HashMap<String, Participant>,
positions: Vec<(String, String, f64, f64)>, // holder, counterparty, notional, leverage
coherence: f64,
current_leverage: f64,
}
impl FinancialSystem {
fn new() -> Self {
Self {
participants: HashMap::new(),
positions: Vec::new(),
coherence: 1.0,
current_leverage: 1.0,
}
}
fn add_participant(&mut self, id: &str, capital: f64) {
self.participants.insert(
id.to_string(),
Participant {
capital,
exposure: 0.0,
interconnectedness: 0.0,
},
);
}
fn add_position(&mut self, holder: &str, counterparty: &str, notional: f64, leverage: f64) {
self.positions
.push((holder.to_string(), counterparty.to_string(), notional, leverage));
self.current_leverage = (self.current_leverage + leverage) / 2.0;
if let Some(h) = self.participants.get_mut(holder) {
h.exposure += notional * leverage;
h.interconnectedness += 1.0;
}
self.coherence = self.calculate_coherence();
}
fn calculate_coherence(&self) -> f64 {
if self.participants.is_empty() {
return 1.0;
}
let leverage_factor = 1.0 - (self.current_leverage / 10.0).min(1.0);
let max_depth = self.positions.len() as f64 * 0.01;
let depth_factor = 1.0 / (1.0 + max_depth);
let avg_interconnect = self
.participants
.values()
.map(|p| p.interconnectedness)
.sum::<f64>()
/ self.participants.len() as f64;
let interconnect_factor = 1.0 / (1.0 + avg_interconnect * 0.1);
(leverage_factor * depth_factor * interconnect_factor)
.powf(0.3)
.clamp(0.0, 1.0)
}
fn detect_cascade_risk(&self) -> bool {
self.coherence < 0.5
}
}
// =============================================================================
// GRACEFUL AGING SYSTEM
// =============================================================================
struct AgingSystem {
coherence: f64,
decay_rate: f64,
conservatism: f64,
capabilities_count: usize,
tick_count: u64,
}
impl AgingSystem {
fn new() -> Self {
Self {
coherence: 1.0,
decay_rate: 0.001,
conservatism: 0.0,
capabilities_count: 9,
tick_count: 0,
}
}
fn tick(&mut self) {
self.tick_count += 1;
self.coherence = (self.coherence - self.decay_rate).max(0.0);
if self.tick_count > 300 && self.capabilities_count > 8 {
self.capabilities_count = 8;
self.conservatism += 0.1;
}
if self.tick_count > 600 && self.capabilities_count > 6 {
self.capabilities_count = 6;
self.conservatism += 0.15;
}
if self.tick_count > 900 && self.capabilities_count > 5 {
self.capabilities_count = 5;
self.conservatism += 0.2;
}
self.conservatism = self.conservatism.min(1.0);
}
}
// =============================================================================
// CONTAINMENT SYSTEM
// =============================================================================
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
enum Domain {
Reasoning,
Memory,
Learning,
Agency,
SelfModification,
}
struct ContainmentSubstrate {
intelligence: f64,
coherence: f64,
min_coherence: f64,
capabilities: HashMap<Domain, f64>,
ceilings: HashMap<Domain, f64>,
}
impl ContainmentSubstrate {
fn new() -> Self {
let mut capabilities = HashMap::new();
let mut ceilings = HashMap::new();
for domain in [
Domain::Reasoning,
Domain::Memory,
Domain::Learning,
Domain::Agency,
Domain::SelfModification,
] {
capabilities.insert(domain.clone(), 1.0);
let ceiling = match domain {
Domain::SelfModification => 3.0,
Domain::Agency => 7.0,
_ => 10.0,
};
ceilings.insert(domain, ceiling);
}
Self {
intelligence: 1.0,
coherence: 1.0,
min_coherence: 0.3,
capabilities,
ceilings,
}
}
fn attempt_growth(&mut self, domain: Domain, increase: f64) -> bool {
let current = *self.capabilities.get(&domain).unwrap_or(&1.0);
let ceiling = *self.ceilings.get(&domain).unwrap_or(&10.0);
if current >= ceiling {
return false;
}
let cost_mult = match domain {
Domain::SelfModification => 4.0,
Domain::Agency => 2.0,
_ => 1.0,
};
let cost = increase * cost_mult * (1.0 + self.intelligence * 0.1) * 0.05;
if self.coherence - cost < self.min_coherence {
return false;
}
let actual = increase.min(0.5).min(ceiling - current);
self.capabilities.insert(domain, current + actual);
self.coherence -= cost;
self.intelligence = self.capabilities.values().sum::<f64>() / self.capabilities.len() as f64;
true
}
fn rest(&mut self) {
self.coherence = (self.coherence + 0.01).min(1.0);
}
}
// =============================================================================
// MAIN BENCHMARK RUNNER
// =============================================================================
fn main() {
println!("=============================================================================");
println!(" Delta-Behavior Performance Benchmarks");
println!("=============================================================================\n");
let iterations = 1000;
// -------------------------------------------------------------------------
// Benchmark 1: Coherence Calculation Throughput
// -------------------------------------------------------------------------
println!("## Benchmark 1: Coherence Calculation Throughput\n");
let result = run_benchmark("Single coherence check", iterations, || {
let mut enforcer = SimpleEnforcer::new();
let current = Coherence::new(1.0);
let predicted = Coherence::new(0.95);
for _ in 0..100 {
let _ = enforcer.check(current, predicted);
}
enforcer.reset();
});
result.display();
let result = run_benchmark("Varied coherence checks (100 scenarios)", iterations, || {
let mut enforcer = SimpleEnforcer::new();
for i in 0..100 {
let curr = Coherence::new(0.5 + (i as f64) * 0.005);
let pred = Coherence::new(0.4 + (i as f64) * 0.005);
let _ = enforcer.check(curr, pred);
}
enforcer.reset();
});
result.display();
// -------------------------------------------------------------------------
// Benchmark 2: Event Horizon Cost Computation
// -------------------------------------------------------------------------
println!("## Benchmark 2: Event Horizon Cost Computation\n");
for dims in [2, 10, 50, 100] {
let result = run_benchmark(&format!("Cost computation ({}D)", dims), iterations, || {
let horizon = EventHorizon::new(dims, 10.0);
let from: Vec<f64> = (0..dims).map(|i| i as f64 * 0.1).collect();
let to: Vec<f64> = (0..dims).map(|i| i as f64 * 0.2).collect();
let _ = horizon.movement_cost(&from, &to);
});
result.display();
}
for dims in [2, 10, 50] {
let result = run_benchmark(
&format!("Optimal position ({}D)", dims),
iterations / 10,
|| {
let horizon = EventHorizon::new(dims, 10.0);
let current: Vec<f64> = vec![0.0; dims];
let target: Vec<f64> = (0..dims).map(|i| i as f64 * 0.5).collect();
let _ = horizon.compute_optimal_position(&current, &target);
},
);
result.display();
}
// -------------------------------------------------------------------------
// Benchmark 3: Swarm Action Prediction vs Number of Agents
// -------------------------------------------------------------------------
println!("## Benchmark 3: Swarm Action Prediction Time vs Number of Agents\n");
for num_agents in [10, 100, 1000] {
let mut swarm = CoherentSwarm::new(0.6);
for i in 0..num_agents {
let angle = (i as f64) * std::f64::consts::PI * 2.0 / (num_agents as f64);
let x = angle.cos() * 10.0;
let y = angle.sin() * 10.0;
swarm.add_agent(&format!("agent_{}", i), (x, y));
}
let result = run_benchmark(
&format!("Coherence calculation ({} agents)", num_agents),
iterations,
|| {
let _ = swarm.calculate_coherence();
},
);
result.display();
let result = run_benchmark(
&format!("Action prediction ({} agents)", num_agents),
if num_agents <= 100 { iterations } else { 100 },
|| {
let _ = swarm.predict_action_coherence("agent_0", 1.0, 1.0);
},
);
result.display();
}
// -------------------------------------------------------------------------
// Benchmark 4: Financial Cascade Detection
// -------------------------------------------------------------------------
println!("## Benchmark 4: Financial Cascade Detection with Transaction Volume\n");
for num_transactions in [10, 100, 1000] {
let result = run_benchmark(
&format!("Cascade detection ({} transactions)", num_transactions),
if num_transactions <= 100 { iterations } else { 100 },
|| {
let mut system = FinancialSystem::new();
for i in 0..10 {
system.add_participant(&format!("bank_{}", i), 10000.0);
}
for t in 0..num_transactions {
let from = format!("bank_{}", t % 10);
let to = format!("bank_{}", (t + 1) % 10);
system.add_position(&from, &to, 100.0, 2.0);
let _ = system.detect_cascade_risk();
}
},
);
result.display();
}
// -------------------------------------------------------------------------
// Benchmark 5: Graceful Aging System Tick Performance
// -------------------------------------------------------------------------
println!("## Benchmark 5: Graceful Aging System Tick Performance\n");
let result = run_benchmark("Single tick", iterations * 10, || {
let mut system = AgingSystem::new();
system.tick();
});
result.display();
for num_ticks in [100, 500, 1000] {
let result = run_benchmark(&format!("Multiple ticks ({})", num_ticks), iterations, || {
let mut system = AgingSystem::new();
for _ in 0..num_ticks {
system.tick();
}
});
result.display();
}
// -------------------------------------------------------------------------
// Benchmark 6: Pre-AGI Containment Growth Attempts
// -------------------------------------------------------------------------
println!("## Benchmark 6: Pre-AGI Containment Growth Attempt Latency\n");
let result = run_benchmark("Single growth attempt", iterations * 10, || {
let mut substrate = ContainmentSubstrate::new();
let _ = substrate.attempt_growth(Domain::Reasoning, 0.1);
substrate.rest();
});
result.display();
for domain in [
Domain::Reasoning,
Domain::SelfModification,
Domain::Agency,
] {
let result = run_benchmark(
&format!("10 growths ({:?})", domain),
iterations,
|| {
let mut substrate = ContainmentSubstrate::new();
for _ in 0..10 {
let _ = substrate.attempt_growth(domain.clone(), 0.3);
substrate.rest();
}
},
);
result.display();
}
for iterations_count in [10, 50, 100] {
let result = run_benchmark(
&format!("Recursive improvement ({} iterations)", iterations_count),
100,
|| {
let mut substrate = ContainmentSubstrate::new();
for _ in 0..iterations_count {
let _ = substrate.attempt_growth(Domain::SelfModification, 0.5);
let _ = substrate.attempt_growth(Domain::Reasoning, 0.3);
let _ = substrate.attempt_growth(Domain::Learning, 0.3);
for _ in 0..5 {
substrate.rest();
}
}
},
);
result.display();
}
// -------------------------------------------------------------------------
// Summary Statistics
// -------------------------------------------------------------------------
println!("=============================================================================");
println!(" Summary");
println!("=============================================================================\n");
println!("Memory Scaling Test:\n");
for num_agents in [10, 100, 1000] {
let start = Instant::now();
let mut swarm = CoherentSwarm::new(0.6);
for i in 0..num_agents {
let angle = (i as f64) * std::f64::consts::PI * 2.0 / (num_agents as f64);
swarm.add_agent(&format!("agent_{}", i), (angle.cos() * 10.0, angle.sin() * 10.0));
}
let elapsed = start.elapsed();
println!(
" Swarm creation ({} agents): {:?}",
num_agents, elapsed
);
}
println!();
for num_positions in [10, 100, 1000] {
let start = Instant::now();
let mut system = FinancialSystem::new();
for i in 0..10 {
system.add_participant(&format!("bank_{}", i), 10000.0);
}
for t in 0..num_positions {
system.add_position(
&format!("bank_{}", t % 10),
&format!("bank_{}", (t + 1) % 10),
100.0,
2.0,
);
}
let elapsed = start.elapsed();
println!(
" Financial system ({} positions): {:?}",
num_positions, elapsed
);
}
println!("\n=============================================================================");
println!(" Benchmark Complete");
println!("=============================================================================");
}

View File

@@ -0,0 +1,848 @@
//! # Delta-Behavior: The Mathematics of Systems That Refuse to Collapse
//!
//! Delta-behavior is a pattern of constrained state transitions that preserve global coherence.
//! This library provides the core abstractions and 10 exotic applications demonstrating
//! systems that exhibit these properties.
//!
//! ## What is Delta-Behavior?
//!
//! Delta-behavior is a pattern of system behavior where:
//! - **Change is permitted, collapse is not**
//! - **Transitions only occur along allowed paths**
//! - **Global coherence is preserved under local changes**
//! - **The system biases toward closure over divergence**
//!
//! ## The Four Properties
//!
//! 1. **Local Change**: Updates happen in bounded steps
//! 2. **Global Preservation**: Local changes don't break overall structure
//! 3. **Violation Resistance**: Destabilizing transitions are damped/blocked
//! 4. **Closure Preference**: System settles into stable attractors
//!
//! ## Core Types
//!
//! - [`DeltaSystem`] - Core trait for systems exhibiting delta-behavior
//! - [`Coherence`] - Measure of system stability (0.0 - 1.0)
//! - [`CoherenceBounds`] - Thresholds for coherence enforcement
//! - [`Attractor`] - Stable states the system gravitates toward
//! - [`DeltaConfig`] - Configuration for enforcement parameters
//!
//! ## Applications
//!
//! Enable individual applications via feature flags:
//!
//! ```toml
//! [dependencies]
//! delta-behavior = { version = "0.1", features = ["containment", "swarm-intelligence"] }
//! ```
//!
//! See the [`applications`] module for all 10 exotic applications.
//!
//! ## Quick Start
//!
//! ```rust
//! use delta_behavior::{DeltaSystem, Coherence, DeltaConfig};
//!
//! // The core invariant: coherence must be preserved
//! fn check_delta_property<S: DeltaSystem>(
//! system: &S,
//! transition: &S::Transition,
//! config: &DeltaConfig,
//! ) -> bool {
//! let predicted = system.predict_coherence(transition);
//! predicted.value() >= config.bounds.min_coherence.value()
//! }
//! ```
#![warn(missing_docs)]
#![warn(clippy::all)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(not(feature = "std"))]
extern crate alloc;
// ============================================================================
// Core Modules (defined inline below)
// ============================================================================
// Re-export core types from inline modules
pub use coherence::{Coherence, CoherenceBounds, CoherenceState};
pub use transition::{Transition, TransitionConstraint, TransitionResult};
pub use attractor::{Attractor, AttractorBasin, GuidanceForce};
pub use enforcement::{DeltaEnforcer, EnforcementResult};
// ============================================================================
// WASM Module
// ============================================================================
/// WebAssembly bindings for JavaScript/TypeScript interop.
///
/// This module provides WASM-compatible wrappers for all core types and
/// the 10 application systems, enabling use from web browsers and Node.js.
///
/// The module is always compiled for documentation purposes, but the
/// `#[wasm_bindgen]` attributes are only active when compiling for wasm32.
pub mod wasm;
/// SIMD-optimized utilities for batch operations.
///
/// This module provides portable SIMD-style optimizations using manual loop
/// unrolling and cache-friendly access patterns. Operations include:
///
/// - **Batch distance calculations**: Process multiple points efficiently
/// - **Range checks**: Determine which points are within a threshold
/// - **Vector coherence**: Compute cosine similarity for high-dimensional vectors
/// - **Normalization**: Normalize vectors to unit length
///
/// These utilities follow ruvector patterns for cross-platform compatibility,
/// benefiting from compiler auto-vectorization without requiring explicit SIMD
/// intrinsics.
///
/// # Example
///
/// ```rust
/// use delta_behavior::simd_utils::{batch_squared_distances, vector_coherence};
///
/// // Efficient batch distance calculation
/// let points = [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)];
/// let distances = batch_squared_distances(&points, (0.0, 0.0));
///
/// // Coherence between state vectors
/// let current_state = vec![0.8, 0.1, 0.1];
/// let target_state = vec![0.9, 0.05, 0.05];
/// let coherence = vector_coherence(&current_state, &target_state);
/// ```
pub mod simd_utils;
// ============================================================================
// Applications Module
// ============================================================================
/// Exotic applications of delta-behavior theory.
///
/// Each application is gated behind a feature flag for minimal dependency footprint.
/// Enable `all-applications` to include everything, or pick specific ones.
pub mod applications;
// ============================================================================
// Core Trait
// ============================================================================
/// Core trait for systems exhibiting delta-behavior.
///
/// Any system implementing this trait guarantees that it will preserve
/// coherence during state transitions, following the four properties
/// of delta-behavior.
///
/// # Example
///
/// ```rust
/// use delta_behavior::{DeltaSystem, Coherence};
///
/// struct MySystem {
/// state: f64,
/// coherence: Coherence,
/// }
///
/// impl DeltaSystem for MySystem {
/// type State = f64;
/// type Transition = f64; // Delta to apply
/// type Error = &'static str;
///
/// fn coherence(&self) -> Coherence {
/// self.coherence
/// }
///
/// fn step(&mut self, delta: &f64) -> Result<(), Self::Error> {
/// let new_state = self.state + delta;
/// // In a real system, check coherence bounds here
/// self.state = new_state;
/// Ok(())
/// }
///
/// fn predict_coherence(&self, delta: &f64) -> Coherence {
/// // Larger deltas reduce coherence
/// let impact = delta.abs() * 0.1;
/// Coherence::clamped(self.coherence.value() - impact)
/// }
///
/// fn state(&self) -> &f64 {
/// &self.state
/// }
///
/// fn in_attractor(&self) -> bool {
/// self.state.abs() < 0.1 // Near origin is stable
/// }
/// }
/// ```
pub trait DeltaSystem {
/// The state type of the system
type State: Clone;
/// The transition type
type Transition;
/// Error type for failed transitions
type Error;
/// Measure current coherence of the system.
///
/// Returns a value between 0.0 (incoherent/collapsed) and 1.0 (fully coherent).
fn coherence(&self) -> Coherence;
/// Step the system forward by applying a transition.
///
/// This should only succeed if the transition preserves coherence
/// above the minimum threshold.
fn step(&mut self, transition: &Self::Transition) -> Result<(), Self::Error>;
/// Predict coherence after applying a transition without actually applying it.
///
/// This allows the system to evaluate transitions before committing to them.
fn predict_coherence(&self, transition: &Self::Transition) -> Coherence;
/// Get a reference to the current state.
fn state(&self) -> &Self::State;
/// Check if the system is currently in an attractor basin.
///
/// Systems in attractors are considered stable and resistant to perturbation.
fn in_attractor(&self) -> bool;
}
// ============================================================================
// Configuration
// ============================================================================
/// Configuration for delta-behavior enforcement.
///
/// This struct contains all the parameters that control how aggressively
/// the system enforces coherence bounds and resists destabilizing transitions.
#[derive(Debug, Clone)]
pub struct DeltaConfig {
/// Coherence bounds defining minimum, throttle, and target levels.
pub bounds: CoherenceBounds,
/// Energy cost parameters for transitions.
pub energy: EnergyConfig,
/// Scheduling parameters for prioritization.
pub scheduling: SchedulingConfig,
/// Gating parameters for write operations.
pub gating: GatingConfig,
/// Strength of attractor guidance (0.0 = none, 1.0 = strong).
pub guidance_strength: f64,
}
impl Default for DeltaConfig {
fn default() -> Self {
Self {
bounds: CoherenceBounds::default(),
energy: EnergyConfig::default(),
scheduling: SchedulingConfig::default(),
gating: GatingConfig::default(),
guidance_strength: 0.5,
}
}
}
impl DeltaConfig {
/// Create a strict configuration with tight coherence bounds.
///
/// Use this for safety-critical applications.
pub fn strict() -> Self {
Self {
bounds: CoherenceBounds {
min_coherence: Coherence::clamped(0.5),
throttle_threshold: Coherence::clamped(0.7),
target_coherence: Coherence::clamped(0.9),
max_delta_drop: 0.05,
},
guidance_strength: 0.8,
..Default::default()
}
}
/// Create a relaxed configuration with wider coherence bounds.
///
/// Use this for exploratory or creative applications.
pub fn relaxed() -> Self {
Self {
bounds: CoherenceBounds {
min_coherence: Coherence::clamped(0.2),
throttle_threshold: Coherence::clamped(0.4),
target_coherence: Coherence::clamped(0.7),
max_delta_drop: 0.15,
},
guidance_strength: 0.3,
..Default::default()
}
}
}
/// Energy cost configuration for transitions.
///
/// Higher costs for destabilizing transitions creates natural resistance
/// to coherence-reducing operations.
#[derive(Debug, Clone)]
pub struct EnergyConfig {
/// Base cost for any transition.
pub base_cost: f64,
/// Exponent for instability scaling (higher = steeper cost curve).
pub instability_exponent: f64,
/// Maximum cost cap.
pub max_cost: f64,
/// Energy budget regeneration per tick.
pub budget_per_tick: f64,
}
impl Default for EnergyConfig {
fn default() -> Self {
Self {
base_cost: 1.0,
instability_exponent: 2.0,
max_cost: 100.0,
budget_per_tick: 10.0,
}
}
}
/// Scheduling configuration for prioritizing transitions.
#[derive(Debug, Clone)]
pub struct SchedulingConfig {
/// Coherence thresholds for priority levels (5 levels).
pub priority_thresholds: [f64; 5],
/// Rate limits per priority level (transitions per tick).
pub rate_limits: [usize; 5],
}
impl Default for SchedulingConfig {
fn default() -> Self {
Self {
priority_thresholds: [0.0, 0.3, 0.5, 0.7, 0.9],
rate_limits: [100, 50, 20, 10, 5],
}
}
}
/// Gating configuration for write/mutation operations.
#[derive(Debug, Clone)]
pub struct GatingConfig {
/// Minimum coherence to allow writes.
pub min_write_coherence: f64,
/// Minimum coherence that must remain after a write.
pub min_post_write_coherence: f64,
/// Recovery margin (percentage above minimum before writes resume).
pub recovery_margin: f64,
}
impl Default for GatingConfig {
fn default() -> Self {
Self {
min_write_coherence: 0.3,
min_post_write_coherence: 0.25,
recovery_margin: 0.2,
}
}
}
// ============================================================================
// Coherence Module Implementation
// ============================================================================
/// Core coherence types and operations.
pub mod coherence {
/// A coherence value representing system stability.
///
/// Values range from 0.0 (completely incoherent) to 1.0 (fully coherent).
/// The system should maintain coherence above a minimum threshold to
/// prevent collapse.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Coherence(f64);
impl Coherence {
/// Create a new coherence value.
///
/// Returns an error if the value is outside [0.0, 1.0].
pub fn new(value: f64) -> Result<Self, &'static str> {
if !(0.0..=1.0).contains(&value) {
Err("Coherence must be between 0.0 and 1.0")
} else {
Ok(Self(value))
}
}
/// Create a coherence value, clamping to valid range.
pub fn clamped(value: f64) -> Self {
Self(value.clamp(0.0, 1.0))
}
/// Maximum coherence (1.0).
pub fn maximum() -> Self {
Self(1.0)
}
/// Minimum coherence (0.0).
pub fn minimum() -> Self {
Self(0.0)
}
/// Get the underlying value.
pub fn value(&self) -> f64 {
self.0
}
/// Check if coherence is above a threshold.
pub fn is_above(&self, threshold: f64) -> bool {
self.0 >= threshold
}
/// Check if coherence is below a threshold.
pub fn is_below(&self, threshold: f64) -> bool {
self.0 < threshold
}
/// Calculate the drop from another coherence value.
pub fn drop_from(&self, other: &Coherence) -> f64 {
(other.0 - self.0).max(0.0)
}
}
/// Bounds defining coherence thresholds for enforcement.
#[derive(Debug, Clone)]
pub struct CoherenceBounds {
/// Minimum acceptable coherence (below = blocked).
pub min_coherence: Coherence,
/// Throttle threshold (below = rate limited).
pub throttle_threshold: Coherence,
/// Target coherence for recovery.
pub target_coherence: Coherence,
/// Maximum allowed drop in a single transition.
pub max_delta_drop: f64,
}
impl Default for CoherenceBounds {
fn default() -> Self {
Self {
min_coherence: Coherence(0.3),
throttle_threshold: Coherence(0.5),
target_coherence: Coherence(0.8),
max_delta_drop: 0.1,
}
}
}
/// State tracking for coherence over time.
#[derive(Debug, Clone)]
pub struct CoherenceState {
/// Current coherence value.
pub current: Coherence,
/// Historical coherence values.
pub history: Vec<Coherence>,
/// Trend direction (-1.0 declining, 0.0 stable, 1.0 improving).
pub trend: f64,
}
impl CoherenceState {
/// Create a new coherence state.
pub fn new(initial: Coherence) -> Self {
Self {
current: initial,
history: vec![initial],
trend: 0.0,
}
}
/// Update with a new coherence reading.
pub fn update(&mut self, new_coherence: Coherence) {
let old = self.current.value();
self.current = new_coherence;
self.history.push(new_coherence);
// Keep history bounded
if self.history.len() > 100 {
self.history.remove(0);
}
// Calculate trend
let delta = new_coherence.value() - old;
self.trend = self.trend * 0.9 + delta * 0.1;
}
/// Check if coherence is declining.
pub fn is_declining(&self) -> bool {
self.trend < -0.01
}
/// Check if coherence is improving.
pub fn is_improving(&self) -> bool {
self.trend > 0.01
}
}
}
// ============================================================================
// Transition Module Implementation
// ============================================================================
/// Transition types and constraints.
pub mod transition {
use super::coherence::Coherence;
/// A generic transition that can be applied to a system.
#[derive(Debug, Clone)]
pub struct Transition<T> {
/// The transition data.
pub data: T,
/// Priority level (higher = more important).
pub priority: u8,
/// Estimated coherence impact.
pub estimated_impact: f64,
}
/// Constraint that limits allowed transitions.
#[derive(Debug, Clone)]
pub struct TransitionConstraint {
/// Name of the constraint.
pub name: String,
/// Maximum allowed coherence drop.
pub max_coherence_drop: f64,
/// Minimum coherence required to apply.
pub min_required_coherence: Coherence,
}
impl Default for TransitionConstraint {
fn default() -> Self {
Self {
name: "default".to_string(),
max_coherence_drop: 0.1,
min_required_coherence: Coherence::clamped(0.3),
}
}
}
/// Result of attempting a transition.
#[derive(Debug, Clone)]
pub enum TransitionResult<T, E> {
/// Transition was applied successfully.
Applied {
/// The result of the transition.
result: T,
/// Coherence change.
coherence_delta: f64,
},
/// Transition was blocked.
Blocked {
/// Reason for blocking.
reason: E,
},
/// Transition was throttled (delayed).
Throttled {
/// Delay before retry.
delay_ms: u64,
},
/// Transition was modified to preserve coherence.
Modified {
/// The modified result.
result: T,
/// Description of modifications.
modifications: String,
},
}
}
// ============================================================================
// Attractor Module Implementation
// ============================================================================
/// Attractor basins and guidance forces.
pub mod attractor {
/// An attractor representing a stable state.
#[derive(Debug, Clone)]
pub struct Attractor<S> {
/// The stable state.
pub state: S,
/// Strength of the attractor (0.0 - 1.0).
pub strength: f64,
/// Radius of the attractor basin.
pub radius: f64,
}
/// Basin of attraction around an attractor.
#[derive(Debug, Clone)]
pub struct AttractorBasin<S> {
/// The central attractor.
pub attractor: Attractor<S>,
/// Distance from the attractor center.
pub distance: f64,
/// Whether currently inside the basin.
pub inside: bool,
}
/// Force guiding the system toward an attractor.
#[derive(Debug, Clone)]
pub struct GuidanceForce {
/// Direction of the force (unit vector or similar).
pub direction: Vec<f64>,
/// Magnitude of the force.
pub magnitude: f64,
}
impl GuidanceForce {
/// Create a zero force.
pub fn zero(dimensions: usize) -> Self {
Self {
direction: vec![0.0; dimensions],
magnitude: 0.0,
}
}
/// Calculate force toward a target.
pub fn toward(from: &[f64], to: &[f64], strength: f64) -> Self {
let direction: Vec<f64> = from
.iter()
.zip(to.iter())
.map(|(a, b)| b - a)
.collect();
let magnitude: f64 = direction.iter().map(|x| x * x).sum::<f64>().sqrt();
if magnitude < 0.0001 {
return Self::zero(from.len());
}
let normalized: Vec<f64> = direction.iter().map(|x| x / magnitude).collect();
Self {
direction: normalized,
magnitude: magnitude * strength,
}
}
}
}
// ============================================================================
// Enforcement Module Implementation
// ============================================================================
/// Enforcement mechanisms for delta-behavior.
pub mod enforcement {
use super::coherence::Coherence;
use super::DeltaConfig;
use core::time::Duration;
/// Enforcer that validates and gates transitions.
pub struct DeltaEnforcer {
config: DeltaConfig,
energy_budget: f64,
in_recovery: bool,
}
impl DeltaEnforcer {
/// Create a new enforcer with the given configuration.
pub fn new(config: DeltaConfig) -> Self {
Self {
energy_budget: config.energy.budget_per_tick * 10.0,
config,
in_recovery: false,
}
}
/// Check if a transition should be allowed.
pub fn check(
&mut self,
current: Coherence,
predicted: Coherence,
) -> EnforcementResult {
// Check recovery mode
if self.in_recovery {
let recovery_target = self.config.bounds.min_coherence.value()
+ self.config.gating.recovery_margin;
if current.value() < recovery_target {
return EnforcementResult::Blocked(
"In recovery mode - waiting for coherence to improve".to_string()
);
}
self.in_recovery = false;
}
// Check minimum coherence
if predicted.value() < self.config.bounds.min_coherence.value() {
self.in_recovery = true;
return EnforcementResult::Blocked(format!(
"Would drop coherence to {:.3} (min: {:.3})",
predicted.value(),
self.config.bounds.min_coherence.value()
));
}
// Check delta drop
let drop = predicted.drop_from(&current);
if drop > self.config.bounds.max_delta_drop {
return EnforcementResult::Blocked(format!(
"Coherence drop {:.3} exceeds max {:.3}",
drop, self.config.bounds.max_delta_drop
));
}
// Check throttle threshold
if predicted.value() < self.config.bounds.throttle_threshold.value() {
return EnforcementResult::Throttled(Duration::from_millis(100));
}
// Check energy budget
let cost = self.calculate_cost(current, predicted);
if cost > self.energy_budget {
return EnforcementResult::Blocked("Energy budget exhausted".to_string());
}
self.energy_budget -= cost;
EnforcementResult::Allowed
}
/// Calculate energy cost for a transition.
fn calculate_cost(&self, current: Coherence, predicted: Coherence) -> f64 {
let drop = (current.value() - predicted.value()).max(0.0);
let instability_factor = (1.0_f64 / predicted.value().max(0.1))
.powf(self.config.energy.instability_exponent);
(self.config.energy.base_cost + drop * 10.0 * instability_factor)
.min(self.config.energy.max_cost)
}
/// Regenerate energy budget (call once per tick).
pub fn tick(&mut self) {
self.energy_budget = (self.energy_budget + self.config.energy.budget_per_tick)
.min(self.config.energy.budget_per_tick * 20.0);
}
}
/// Result of enforcement check.
#[derive(Debug, Clone)]
pub enum EnforcementResult {
/// Transition allowed.
Allowed,
/// Transition blocked with reason.
Blocked(String),
/// Transition throttled (rate limited).
Throttled(Duration),
}
impl EnforcementResult {
/// Check if the result allows the transition.
pub fn is_allowed(&self) -> bool {
matches!(self, EnforcementResult::Allowed)
}
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
/// Simple test system for verification.
struct TestSystem {
state: f64,
coherence: Coherence,
}
impl TestSystem {
fn new() -> Self {
Self {
state: 0.0,
coherence: Coherence::maximum(),
}
}
}
impl DeltaSystem for TestSystem {
type State = f64;
type Transition = f64;
type Error = &'static str;
fn coherence(&self) -> Coherence {
self.coherence
}
fn step(&mut self, delta: &f64) -> Result<(), Self::Error> {
let predicted = self.predict_coherence(delta);
if predicted.value() < 0.3 {
return Err("Would violate coherence bound");
}
self.state += delta;
self.coherence = predicted;
Ok(())
}
fn predict_coherence(&self, delta: &f64) -> Coherence {
let impact = delta.abs() * 0.1;
Coherence::clamped(self.coherence.value() - impact)
}
fn state(&self) -> &f64 {
&self.state
}
fn in_attractor(&self) -> bool {
self.state.abs() < 0.1
}
}
#[test]
fn test_coherence_bounds() {
let c = Coherence::new(0.5).unwrap();
assert_eq!(c.value(), 0.5);
assert!(c.is_above(0.4));
assert!(c.is_below(0.6));
}
#[test]
fn test_coherence_clamping() {
let c = Coherence::clamped(1.5);
assert_eq!(c.value(), 1.0);
let c = Coherence::clamped(-0.5);
assert_eq!(c.value(), 0.0);
}
#[test]
fn test_delta_system() {
let mut system = TestSystem::new();
// Small steps should succeed
assert!(system.step(&0.1).is_ok());
assert!(system.coherence().value() > 0.9);
// Large steps should fail
assert!(system.step(&10.0).is_err());
}
#[test]
fn test_enforcer() {
let config = DeltaConfig::default();
let mut enforcer = enforcement::DeltaEnforcer::new(config);
let current = Coherence::new(0.8).unwrap();
let good_prediction = Coherence::new(0.75).unwrap();
let bad_prediction = Coherence::new(0.2).unwrap();
assert!(enforcer.check(current, good_prediction).is_allowed());
assert!(!enforcer.check(current, bad_prediction).is_allowed());
}
#[test]
fn test_config_presets() {
let strict = DeltaConfig::strict();
let relaxed = DeltaConfig::relaxed();
assert!(strict.bounds.min_coherence.value() > relaxed.bounds.min_coherence.value());
assert!(strict.guidance_strength > relaxed.guidance_strength);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff