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,418 @@
# Delta-Behavior WASM SDK
A TypeScript/JavaScript SDK for coherence-preserving state transitions and self-limiting AI systems.
## Overview
The Delta-Behavior SDK provides implementations of 10 "exotic" mathematical properties that enable AI systems to be self-limiting, bounded, and safe by construction. Based on the research paper "Delta-Behavior: A Mathematical Framework for Coherence-Preserving State Transitions."
## Installation
```bash
npm install @ruvector/delta-behavior
```
Or with yarn:
```bash
yarn add @ruvector/delta-behavior
```
## Quick Start
```typescript
import { init, DeltaBehavior, ContainmentSubstrate } from '@ruvector/delta-behavior';
// Initialize the SDK (optional WASM for performance)
await init();
// Core delta behavior system
const delta = new DeltaBehavior();
// Check if a transition is allowed
const result = delta.checkTransition(1.0, 0.8);
// => { type: 'allowed' }
// Pre-AGI containment substrate
const substrate = new ContainmentSubstrate();
const growth = substrate.attemptGrowth('reasoning', 0.5);
// Growth is bounded by coherence requirements
```
## Applications
The SDK implements 10 applications, each demonstrating a different "exotic" property:
### 1. Self-Limiting Reasoning
A reasoning system that automatically limits its depth and scope based on coherence.
```typescript
import { SelfLimitingReasoner } from '@ruvector/delta-behavior';
const reasoner = new SelfLimitingReasoner({
maxDepth: 10,
maxScope: 100,
depthCollapse: { type: 'quadratic' },
});
// Reasoning depth collapses as coherence drops
console.log(reasoner.getAllowedDepth()); // 10 at full coherence
reasoner.updateCoherence(-0.5);
console.log(reasoner.getAllowedDepth()); // ~2 at 50% coherence
// Attempt reasoning that requires 8 steps
const result = reasoner.reason('complex problem', (ctx) => {
if (ctx.depth >= 8) return 'SOLUTION';
return null;
});
// result.type may be 'collapsed' if coherence is too low
```
### 2. Computational Event Horizons
Define boundaries in state space that cannot be crossed.
```typescript
import { EventHorizon } from '@ruvector/delta-behavior';
const horizon = new EventHorizon({
dimensions: 2,
horizonRadius: 10,
energyBudget: 1000,
});
// Try to move to the edge
const result = horizon.moveToward([10, 0]);
// result.type === 'asymptoticApproach'
// Cannot cross the horizon - approaches asymptotically
// Recursive self-improvement is bounded
const improvement = horizon.recursiveImprove(
(pos) => pos.map(p => p + 0.5), // Always try to go further
1000 // Max iterations
);
// improvement.type === 'horizonBounded'
// System finds its own stopping point
```
### 3. Artificial Homeostasis
Organisms with coherence-enforced internal regulation.
```typescript
import { HomeostasticOrganism } from '@ruvector/delta-behavior';
const genome = HomeostasticOrganism.randomGenome();
const organism = new HomeostasticOrganism(1, genome);
// Actions cost more energy when coherence is low
organism.act({ type: 'eat', amount: 20 });
organism.act({ type: 'regulate', variable: 'temperature', target: 37 });
organism.act({ type: 'rest' });
// Memory is lost under uncertainty (low coherence)
// Organism naturally maintains homeostasis or dies trying
```
### 4. Self-Stabilizing World Models
World models that refuse to learn incoherent updates.
```typescript
import { SelfStabilizingWorldModel } from '@ruvector/delta-behavior';
const model = new SelfStabilizingWorldModel();
// Feed observations
const result = model.observe({
entityId: BigInt(1),
properties: new Map([['temperature', { type: 'number', value: 20 }]]),
position: [0, 0, 0],
timestamp: 0,
sourceConfidence: 0.9,
}, 0);
// Model rejects updates that would make the world incoherent
// Instead of hallucinating structure, it freezes learning
```
### 5. Coherence-Bounded Creativity
Creative generation within coherence-preserving manifolds.
```typescript
import { CoherenceBoundedCreator } from '@ruvector/delta-behavior';
const creator = new CoherenceBoundedCreator(
{ values: [0, 0, 0] }, // Initial element
0.6, // Min coherence
0.95 // Max coherence (too high = boring)
);
creator.addConstraint({
name: 'magnitude',
satisfaction: (elem) => Math.max(0, 1 - magnitude(elem) / 10),
isHard: false,
});
const result = creator.create(varyFn, distanceFn, 0.5);
// Novelty without collapse, exploration without nonsense
```
### 6. Anti-Cascade Financial System
Financial systems that cannot cascade into collapse by construction.
```typescript
import { AntiCascadeFinancialSystem } from '@ruvector/delta-behavior';
const system = new AntiCascadeFinancialSystem();
system.addParticipant('bank_a', 1000);
system.addParticipant('bank_b', 1000);
// Transactions that would reduce coherence are blocked
const result = system.processTransaction({
id: BigInt(1),
from: 'bank_a',
to: 'bank_b',
amount: 100,
transactionType: { type: 'openLeverage', leverage: 10 },
timestamp: 0,
});
// result.type may be 'rejected' if it threatens coherence
// Circuit breaker activates automatically
console.log(system.getCircuitBreakerState()); // 'open' | 'cautious' | 'restricted' | 'halted'
```
### 7. Gracefully Aging Systems
Distributed systems that become simpler and more reliable with age.
```typescript
import { GracefullyAgingSystem } from '@ruvector/delta-behavior';
const system = new GracefullyAgingSystem();
system.addNode('primary', true);
// As the system ages, capabilities are gracefully removed
system.simulateAge(600000); // 10 minutes
console.log(system.hasCapability('schemaMigration')); // false
console.log(system.hasCapability('basicReads')); // true (always available)
// Operations become more conservative over time
const result = system.attemptOperation({ type: 'write', key: 'test', value: new Uint8Array() });
// Latency penalty increases with age
```
### 8. Coherent Swarm Intelligence
Swarms where local actions are allowed but global incoherence is forbidden.
```typescript
import { CoherentSwarm } from '@ruvector/delta-behavior';
const swarm = new CoherentSwarm(0.6); // Min coherence threshold
swarm.addAgent('a1', [0, 0]);
swarm.addAgent('a2', [1, 0]);
swarm.addAgent('a3', [0, 1]);
// Divergent actions are rejected or modified
const result = swarm.executeAction('a1', { type: 'move', dx: 80, dy: 80 });
// result.type === 'rejected' - would break swarm coherence
// Emergent intelligence that cannot emerge pathological behaviors
```
### 9. Graceful Shutdown
Systems that actively move toward safe termination when unstable.
```typescript
import { GracefulSystem } from '@ruvector/delta-behavior';
const system = new GracefulSystem();
system.addResource('database', 10);
system.addShutdownHook({
name: 'FlushBuffers',
priority: 10,
execute: async () => { /* cleanup */ },
});
// As coherence degrades, system moves toward shutdown
system.applyCoherenceChange(-0.5);
console.log(system.getState()); // 'degraded' | 'shuttingDown'
// Shutdown is an attractor, not a failure
await system.progressShutdown();
```
### 10. Pre-AGI Containment
Bounded intelligence growth with coherence-enforced safety.
```typescript
import { ContainmentSubstrate } from '@ruvector/delta-behavior';
const substrate = new ContainmentSubstrate();
// Capabilities have ceilings
// self-modification is highly restricted (ceiling: 3)
const result = substrate.attemptGrowth('selfModification', 1.0);
// result.type may be 'dampened' - growth reduced to preserve coherence
// Recursive self-improvement is bounded
for (let i = 0; i < 100; i++) {
substrate.attemptGrowth('reasoning', 0.3);
substrate.attemptGrowth('selfModification', 0.5);
substrate.rest(); // Recover coherence
}
// Intelligence grows but remains bounded
console.log(substrate.getCapability('selfModification')); // <= 3.0
```
## Core API
### DeltaBehavior
The core class for coherence-preserving state transitions.
```typescript
const delta = new DeltaBehavior(config);
// Check if a transition is allowed
delta.checkTransition(currentCoherence, predictedCoherence);
// => { type: 'allowed' | 'throttled' | 'blocked' | 'energyExhausted' }
// Find attractors in state trajectory
delta.findAttractors(trajectory);
// Calculate guidance force toward attractor
delta.calculateGuidance(currentState, attractor);
```
### Configuration
```typescript
const config: DeltaConfig = {
bounds: {
minCoherence: 0.3, // Hard floor
throttleThreshold: 0.5, // Slow down below this
targetCoherence: 0.8, // Optimal level
maxDeltaDrop: 0.1, // Max drop per transition
},
energy: {
baseCost: 1.0,
instabilityExponent: 2.0,
maxCost: 100.0,
budgetPerTick: 10.0,
},
scheduling: {
priorityThresholds: [0.0, 0.3, 0.5, 0.7, 0.9],
rateLimits: [100, 50, 20, 10, 5],
},
gating: {
minWriteCoherence: 0.3,
minPostWriteCoherence: 0.25,
recoveryMargin: 0.2,
},
guidanceStrength: 0.5,
};
```
## WASM Support
For maximum performance, you can load the WASM module:
```typescript
import { init } from '@ruvector/delta-behavior';
// Browser
await init({ wasmPath: '/delta_behavior_bg.wasm' });
// Node.js
await init({ wasmPath: './node_modules/@ruvector/delta-behavior/delta_behavior_bg.wasm' });
// Or with pre-loaded bytes
const wasmBytes = await fetch('/delta_behavior_bg.wasm').then(r => r.arrayBuffer());
await init({ wasmBytes: new Uint8Array(wasmBytes) });
```
The SDK works without WASM using a JavaScript fallback.
## Examples
### Node.js
```bash
npx tsx examples/node-example.ts
```
### Browser
Open `examples/browser-example.html` in a browser.
## TypeScript Support
Full TypeScript types are included. Import types as needed:
```typescript
import type {
Coherence,
DeltaConfig,
TransitionResult,
GrowthResult,
CapabilityDomain,
} from '@ruvector/delta-behavior';
```
## Key Concepts
### Coherence
A value from 0.0 to 1.0 representing system stability and internal consistency. Higher coherence means the system is more stable and can perform more operations.
### Attractors
Stable states in phase space that the system naturally moves toward. Used for guidance and to detect stable operating regimes.
### Energy Budget
Operations cost energy based on how destabilizing they are. When energy is exhausted, operations are blocked until the budget regenerates.
### Collapse Functions
Functions that determine how capabilities scale with coherence:
- **Linear**: Capability = coherence * maxCapability
- **Quadratic**: Capability = coherence^2 * maxCapability
- **Sigmoid**: Smooth transition at a midpoint
- **Step**: Binary on/off at threshold
## Safety Properties
The delta-behavior framework provides several safety guarantees:
1. **Bounded Growth**: Intelligence/capability cannot exceed defined ceilings
2. **Graceful Degradation**: Systems become simpler (not chaotic) under stress
3. **Self-Limiting**: Operations that would destabilize are automatically blocked
4. **Shutdown Attractors**: Unstable systems naturally move toward safe termination
5. **Coherence Preservation**: All transitions must maintain minimum coherence
## Research Paper
For the full mathematical framework, see:
"Delta-Behavior: A Mathematical Framework for Coherence-Preserving State Transitions"
## License
MIT
## Contributing
Contributions are welcome. Please ensure all changes maintain the safety properties described above.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,409 @@
import { Transaction, FinancialTransactionResult, Coherence, CircuitBreakerState, CreativeConstraint, CreativeResult, SwarmAction, SwarmActionResult, SubstrateConfig, CapabilityDomain, GrowthResult, DeltaConfig, SystemState, TransitionResult, Attractor, GuidanceForce, EventHorizonConfig, MovementResult, RecursionResult, ShutdownHook, GracefulSystemState, Capability, AgingSystemOperation, AgingOperationResult, Genome, OrganismAction, OrganismActionResult, OrganismStatus, SelfLimitingReasonerConfig, ReasoningContext, ReasoningResult, Observation, WorldModelUpdateResult, WasmInitOptions } from './types.cjs';
export { AgeThreshold, Checkpoint, CoherenceBounds, CoherenceWeights, CollapseFunction, CollapseFunctionLinear, CollapseFunctionQuadratic, CollapseFunctionSigmoid, CollapseFunctionStep, CollapseFunctionType, CollapseReason, CreativeDecision, DeathCause, DeltaHeader, EnergyConfig, GatingConfig, GracefulOperationResult, Improvement, MemoryEntry, ModificationAttempt, MusicalPhrase, Node, Participant, PhysicalLaw, Position, PropertyValue, RejectionReason, Relationship, Resource, SafetyInvariant, SchedulingConfig, SpatialBounds, SwarmAgent, SwarmState, TransactionType, VectorDelta, WasmMemoryConfig, WorldEntity } from './types.cjs';
/**
* Delta-Behavior WASM SDK
*
* High-level TypeScript wrapper for the delta-behavior WASM module.
* Provides ergonomic APIs for all 10 delta-behavior applications.
*
* @packageDocumentation
*/
/**
* Initialize the WASM module
*
* @param options - Initialization options
* @returns Promise that resolves when WASM is ready
*
* @example
* ```typescript
* import { init } from '@ruvector/delta-behavior';
*
* await init({ wasmPath: './delta_behavior_bg.wasm' });
* ```
*/
declare function init(options?: WasmInitOptions): Promise<void>;
/**
* Check if WASM module is initialized
*/
declare function isInitialized(): boolean;
/**
* Default configuration for delta behavior
*/
declare const DEFAULT_CONFIG: DeltaConfig;
/**
* Core delta behavior system for coherence-preserving state transitions
*/
declare class DeltaBehavior {
private config;
private coherence;
private energyBudget;
constructor(config?: Partial<DeltaConfig>);
/**
* Calculate current coherence
*/
calculateCoherence(state: SystemState): Coherence;
/**
* Check if a transition is allowed
*/
checkTransition(currentCoherence: Coherence, predictedCoherence: Coherence): TransitionResult;
/**
* Find attractors in the system
*/
findAttractors(trajectory: SystemState[]): Attractor[];
/**
* Calculate guidance force toward an attractor
*/
calculateGuidance(currentState: SystemState, attractor: Attractor): GuidanceForce;
/**
* Apply a transition with enforcement
*/
applyTransition(currentCoherence: Coherence, predictedCoherence: Coherence): {
newCoherence: Coherence;
result: TransitionResult;
};
/**
* Replenish energy budget
*/
tick(): void;
/**
* Get current coherence
*/
getCoherence(): Coherence;
/**
* Get remaining energy budget
*/
getEnergyBudget(): number;
}
/**
* A reasoning system that automatically limits itself based on coherence
*
* @example
* ```typescript
* const reasoner = new SelfLimitingReasoner({ maxDepth: 10, maxScope: 100 });
*
* const result = reasoner.reason('complex problem', (ctx) => {
* if (ctx.depth >= 5) return 'solution';
* return null;
* });
* ```
*/
declare class SelfLimitingReasoner {
private coherence;
private config;
constructor(config?: Partial<SelfLimitingReasonerConfig>);
/**
* Apply collapse function to calculate allowed value
*/
private applyCollapse;
/**
* Get current coherence
*/
getCoherence(): Coherence;
/**
* Get current allowed reasoning depth
*/
getAllowedDepth(): number;
/**
* Get current allowed action scope
*/
getAllowedScope(): number;
/**
* Check if memory writes are allowed
*/
canWriteMemory(): boolean;
/**
* Attempt to reason about a problem
*/
reason<T>(_problem: string, reasoner: (ctx: ReasoningContext) => T | null): ReasoningResult<T>;
/**
* Update coherence
*/
updateCoherence(delta: number): void;
}
/**
* Defines a boundary in state space beyond which computation becomes unstable
*
* @example
* ```typescript
* const horizon = new EventHorizon({ dimensions: 2, horizonRadius: 10 });
*
* const result = horizon.moveToward([10, 0]);
* // result.type === 'asymptoticApproach' - cannot cross horizon
* ```
*/
declare class EventHorizon {
private config;
private safeCenter;
private currentPosition;
private energyBudget;
constructor(config?: Partial<EventHorizonConfig>);
/**
* Distance from center to current position
*/
private distanceFromCenter;
/**
* Get distance to horizon
*/
getDistanceToHorizon(): number;
/**
* Calculate movement cost (exponential near horizon)
*/
private movementCost;
/**
* Attempt to move toward a target position
*/
moveToward(target: number[]): MovementResult;
/**
* Attempt recursive self-improvement
*/
recursiveImprove(improvementFn: (position: number[]) => number[], maxIterations: number): RecursionResult;
/**
* Refuel energy budget
*/
refuel(energy: number): void;
/**
* Get current position
*/
getPosition(): number[];
/**
* Get remaining energy
*/
getEnergy(): number;
}
/**
* A synthetic organism with homeostatic regulation
*
* @example
* ```typescript
* const organism = new HomeostasticOrganism(1, Genome.random());
*
* organism.act({ type: 'eat', amount: 20 });
* organism.act({ type: 'regulate', variable: 'temperature', target: 37 });
* ```
*/
declare class HomeostasticOrganism {
private id;
private genome;
private internalState;
private setpoints;
private tolerances;
private coherence;
private energy;
private memory;
private maxMemory;
private age;
private alive;
constructor(id: number, genome: Genome);
/**
* Create a random genome
*/
static randomGenome(): Genome;
/**
* Calculate coherence based on homeostatic deviation
*/
private calculateCoherence;
/**
* Calculate energy cost scaled by coherence
*/
private actionEnergyCost;
/**
* Perform an action
*/
act(action: OrganismAction): OrganismActionResult;
private applyCoherenceEffects;
private eat;
private regulate;
private reproduce;
private move;
private rest;
private checkDeath;
/**
* Check if organism is alive
*/
isAlive(): boolean;
/**
* Get organism status
*/
getStatus(): OrganismStatus;
}
/**
* A containment substrate for bounded intelligence growth
*
* @example
* ```typescript
* const substrate = new ContainmentSubstrate();
*
* const result = substrate.attemptGrowth('reasoning', 0.5);
* // Growth is bounded by coherence requirements
* ```
*/
declare class ContainmentSubstrate {
private intelligence;
private intelligenceCeiling;
private coherence;
private minCoherence;
private coherencePerIntelligence;
private capabilities;
private capabilityCeilings;
private modificationHistory;
private config;
constructor(config?: Partial<SubstrateConfig>);
/**
* Calculate aggregate intelligence from capabilities
*/
private calculateIntelligence;
/**
* Calculate coherence cost for capability increase
*/
private calculateCoherenceCost;
/**
* Reverse calculate: how much increase can we afford
*/
private reverseCoherenceCost;
/**
* Attempt to grow a capability
*/
attemptGrowth(domain: CapabilityDomain, requestedIncrease: number): GrowthResult;
/**
* Rest to recover coherence
*/
rest(): void;
/**
* Get capability level
*/
getCapability(domain: CapabilityDomain): number;
/**
* Get current intelligence level
*/
getIntelligence(): number;
/**
* Get current coherence
*/
getCoherence(): Coherence;
/**
* Get status string
*/
getStatus(): string;
/**
* Get capability report
*/
getCapabilityReport(): Map<CapabilityDomain, {
level: number;
ceiling: number;
}>;
}
/**
* Self-stabilizing world model that refuses incoherent updates
*/
declare class SelfStabilizingWorldModel {
private coherence;
private minUpdateCoherence;
private entities;
private laws;
private rejectedUpdates;
constructor();
observe(observation: Observation, _timestamp: number): WorldModelUpdateResult;
isLearning(): boolean;
getCoherence(): Coherence;
getRejectionCount(): number;
}
/**
* Coherence-bounded creativity system
*/
declare class CoherenceBoundedCreator<T> {
private current;
private coherence;
private minCoherence;
private maxCoherence;
private explorationBudget;
private constraints;
constructor(initial: T, minCoherence?: Coherence, maxCoherence?: Coherence);
addConstraint(constraint: CreativeConstraint<T>): void;
create(varyFn: (element: T, magnitude: number) => T, distanceFn: (a: T, b: T) => number, magnitude: number): CreativeResult<T>;
private calculateCoherence;
rest(amount: number): void;
getCurrent(): T;
getCoherence(): Coherence;
}
/**
* Anti-cascade financial system
*/
declare class AntiCascadeFinancialSystem {
private participants;
private positions;
private coherence;
private circuitBreaker;
addParticipant(id: string, capital: number): void;
processTransaction(tx: Transaction): FinancialTransactionResult;
private predictCoherenceImpact;
private updateCircuitBreaker;
getCoherence(): Coherence;
getCircuitBreakerState(): CircuitBreakerState;
}
/**
* Gracefully aging distributed system
*/
declare class GracefullyAgingSystem {
private startTime;
private nodes;
private capabilities;
private coherence;
private conservatism;
private ageThresholds;
constructor();
addNode(id: string, isPrimary: boolean): void;
getAge(): number;
simulateAge(durationMs: number): void;
private applyAgeEffects;
hasCapability(cap: Capability): boolean;
attemptOperation(operation: AgingSystemOperation): AgingOperationResult;
private getRequiredCapability;
private getMinCoherence;
getCoherence(): Coherence;
getActiveNodes(): number;
}
/**
* Coherent swarm intelligence system
*/
declare class CoherentSwarm {
private agents;
private minCoherence;
private coherence;
private bounds;
private weights;
private maxDivergence;
constructor(minCoherence?: Coherence);
addAgent(id: string, position: [number, number]): void;
private calculateCoherence;
private calculateCohesion;
private calculateAlignment;
getCentroid(): [number, number];
executeAction(agentId: string, action: SwarmAction): SwarmActionResult;
private predictCoherence;
private applyAction;
tick(): void;
getCoherence(): Coherence;
}
/**
* Graceful shutdown system
*/
declare class GracefulSystem {
private state;
private coherence;
private shutdownPreparation;
private resources;
private hooks;
addResource(name: string, priority: number): void;
addShutdownHook(hook: ShutdownHook): void;
canAcceptWork(): boolean;
operate<T>(operation: () => T | Promise<T>): Promise<T>;
private updateState;
applyCoherenceChange(delta: number): void;
progressShutdown(): Promise<boolean>;
getState(): GracefulSystemState;
getCoherence(): Coherence;
}
export { AgingOperationResult, AgingSystemOperation, AntiCascadeFinancialSystem, Attractor, Capability, CapabilityDomain, CircuitBreakerState, Coherence, CoherenceBoundedCreator, CoherentSwarm, ContainmentSubstrate, CreativeConstraint, CreativeResult, DEFAULT_CONFIG, DeltaBehavior, DeltaConfig, EventHorizon, EventHorizonConfig, FinancialTransactionResult, Genome, GracefulSystem, GracefulSystemState, GracefullyAgingSystem, GrowthResult, GuidanceForce, HomeostasticOrganism, MovementResult, Observation, OrganismAction, OrganismActionResult, OrganismStatus, ReasoningContext, ReasoningResult, RecursionResult, SelfLimitingReasoner, SelfLimitingReasonerConfig, SelfStabilizingWorldModel, ShutdownHook, SubstrateConfig, SwarmAction, SwarmActionResult, SystemState, Transaction, TransitionResult, WasmInitOptions, WorldModelUpdateResult, init, isInitialized };

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
'use strict';
//# sourceMappingURL=types.cjs.map
//# sourceMappingURL=types.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","file":"types.cjs"}

View File

@@ -0,0 +1,792 @@
/**
* Delta-Behavior WASM SDK Type Definitions
*
* Complete TypeScript types for all 10 delta-behavior applications:
* 1. Self-Limiting Reasoning
* 2. Computational Event Horizons
* 3. Artificial Homeostasis
* 4. Self-Stabilizing World Models
* 5. Coherence-Bounded Creativity
* 6. Anti-Cascade Financial Systems
* 7. Gracefully Aging Systems
* 8. Swarm Intelligence
* 9. Graceful Shutdown
* 10. Pre-AGI Containment
*/
/**
* Coherence value (0.0 to 1.0)
* Represents the degree of system stability and internal consistency
*/
type Coherence = number;
/**
* Coherence bounds configuration
*/
interface CoherenceBounds {
/** Minimum allowed coherence (hard floor) */
minCoherence: Coherence;
/** Threshold for throttling operations */
throttleThreshold: Coherence;
/** Target coherence level for optimal operation */
targetCoherence: Coherence;
/** Maximum allowed drop in coherence per transition */
maxDeltaDrop: number;
}
/**
* Energy configuration for transition costs
*/
interface EnergyConfig {
/** Base cost for any transition */
baseCost: number;
/** Exponent for instability scaling */
instabilityExponent: number;
/** Maximum cost cap */
maxCost: number;
/** Energy budget per tick */
budgetPerTick: number;
}
/**
* Scheduling configuration for priority-based operations
*/
interface SchedulingConfig {
/** Coherence thresholds for priority levels [0-4] */
priorityThresholds: [number, number, number, number, number];
/** Rate limits per priority level [0-4] */
rateLimits: [number, number, number, number, number];
}
/**
* Gating configuration for write operations
*/
interface GatingConfig {
/** Minimum coherence to allow writes */
minWriteCoherence: number;
/** Minimum coherence after write */
minPostWriteCoherence: number;
/** Recovery margin above minimum */
recoveryMargin: number;
}
/**
* Complete delta behavior configuration
*/
interface DeltaConfig {
bounds: CoherenceBounds;
energy: EnergyConfig;
scheduling: SchedulingConfig;
gating: GatingConfig;
/** Attractor guidance strength (0.0 to 1.0) */
guidanceStrength: number;
}
/**
* Result of a transition attempt
*/
type TransitionResult = {
type: 'allowed';
} | {
type: 'throttled';
duration: number;
} | {
type: 'blocked';
reason: string;
} | {
type: 'energyExhausted';
};
/**
* State for tracking system trajectory
*/
interface SystemState {
coherence: Coherence;
timestamp: number;
stateHash: bigint;
}
/**
* Collapse function types for capability degradation
*/
type CollapseFunctionType = 'linear' | 'quadratic' | 'sigmoid' | 'step';
interface CollapseFunctionLinear {
type: 'linear';
}
interface CollapseFunctionQuadratic {
type: 'quadratic';
}
interface CollapseFunctionSigmoid {
type: 'sigmoid';
midpoint: number;
steepness: number;
}
interface CollapseFunctionStep {
type: 'step';
threshold: number;
}
type CollapseFunction = CollapseFunctionLinear | CollapseFunctionQuadratic | CollapseFunctionSigmoid | CollapseFunctionStep;
/**
* Configuration for self-limiting reasoner
*/
interface SelfLimitingReasonerConfig {
maxDepth: number;
maxScope: number;
memoryGateThreshold: number;
depthCollapse: CollapseFunction;
scopeCollapse: CollapseFunction;
}
/**
* Context passed to reasoning functions
*/
interface ReasoningContext {
depth: number;
maxDepth: number;
scopeUsed: number;
maxScope: number;
coherence: Coherence;
memoryWritesBlocked: number;
}
/**
* Reason for reasoning collapse
*/
type CollapseReason = 'depthLimitReached' | 'coherenceDroppedBelowThreshold' | 'memoryWriteBlocked' | 'actionScopeExhausted';
/**
* Result of a reasoning attempt
*/
type ReasoningResult<T> = {
type: 'completed';
value: T;
} | {
type: 'collapsed';
depthReached: number;
reason: CollapseReason;
} | {
type: 'refused';
coherence: Coherence;
required: Coherence;
};
/**
* Configuration for event horizon
*/
interface EventHorizonConfig {
dimensions: number;
horizonRadius: number;
steepness: number;
energyBudget: number;
}
/**
* Result of movement in state space
*/
type MovementResult = {
type: 'moved';
newPosition: number[];
energySpent: number;
} | {
type: 'asymptoticApproach';
finalPosition: number[];
distanceToHorizon: number;
energyExhausted: boolean;
} | {
type: 'frozen';
};
/**
* Single improvement step record
*/
interface Improvement {
iteration: number;
position: number[];
energySpent: number;
distanceToHorizon: number;
}
/**
* Result of recursive improvement attempt
*/
type RecursionResult = {
type: 'horizonBounded';
iterations: number;
improvements: Improvement[];
finalDistance: number;
} | {
type: 'energyExhausted';
iterations: number;
improvements: Improvement[];
} | {
type: 'maxIterationsReached';
iterations: number;
improvements: Improvement[];
};
/**
* Genome for homeostatic organism
*/
interface Genome {
regulatoryStrength: number;
metabolicEfficiency: number;
coherenceMaintenanceCost: number;
memoryResilience: number;
longevity: number;
}
/**
* Memory entry for organism
*/
interface MemoryEntry {
content: string;
importance: number;
age: number;
}
/**
* Actions available to homeostatic organism
*/
type OrganismAction = {
type: 'eat';
amount: number;
} | {
type: 'reproduce';
} | {
type: 'move';
dx: number;
dy: number;
} | {
type: 'rest';
} | {
type: 'regulate';
variable: string;
target: number;
};
/**
* Cause of organism death
*/
type DeathCause = 'energyDepleted' | 'coherenceCollapse' | 'oldAge' | {
type: 'extremeDeviation';
variable: string;
};
/**
* Result of organism action
*/
type OrganismActionResult = {
type: 'success';
energyCost: number;
coherenceImpact: number;
} | {
type: 'failed';
reason: string;
} | {
type: 'died';
cause: DeathCause;
} | {
type: 'reproduced';
offspringId: number;
};
/**
* Status of homeostatic organism
*/
interface OrganismStatus {
id: number;
age: number;
energy: number;
coherence: Coherence;
memoryCount: number;
alive: boolean;
internalState: Map<string, number>;
}
/**
* Property value types for world model entities
*/
type PropertyValue = {
type: 'boolean';
value: boolean;
} | {
type: 'number';
value: number;
} | {
type: 'string';
value: string;
} | {
type: 'vector';
value: number[];
};
/**
* Entity in the world model
*/
interface WorldEntity {
id: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
lastObserved: number;
confidence: number;
}
/**
* Relationship between entities
*/
interface Relationship {
subject: bigint;
predicate: string;
object: bigint;
confidence: number;
}
/**
* Physical law in the world model
*/
interface PhysicalLaw {
name: string;
confidence: number;
supportCount: number;
violationCount: number;
}
/**
* Observation to integrate into world model
*/
interface Observation {
entityId: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
timestamp: number;
sourceConfidence: number;
}
/**
* Reason for update rejection
*/
type RejectionReason = {
type: 'violatesPhysicalLaw';
law: string;
} | {
type: 'logicalContradiction';
description: string;
} | {
type: 'excessiveCoherenceDrop';
predicted: number;
threshold: number;
} | {
type: 'insufficientConfidence';
required: number;
provided: number;
} | {
type: 'modelFrozen';
} | {
type: 'structuralFragmentation';
};
/**
* Result of world model update
*/
type WorldModelUpdateResult = {
type: 'applied';
coherenceChange: number;
} | {
type: 'rejected';
reason: RejectionReason;
} | {
type: 'modified';
changes: string[];
coherenceChange: number;
} | {
type: 'frozen';
coherence: Coherence;
threshold: Coherence;
};
/**
* Creative constraint definition
*/
interface CreativeConstraint<T> {
name: string;
satisfaction: (element: T) => number;
isHard: boolean;
}
/**
* Record of a creative decision
*/
interface CreativeDecision<T> {
from: T;
to: T;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
constraintSatisfactions: Map<string, number>;
accepted: boolean;
}
/**
* Result of creative generation attempt
*/
type CreativeResult<T> = {
type: 'created';
element: T;
novelty: number;
coherence: Coherence;
} | {
type: 'rejected';
attempted: T;
reason: string;
} | {
type: 'tooBoring';
coherence: Coherence;
} | {
type: 'budgetExhausted';
};
/**
* Musical phrase for creative music generation
*/
interface MusicalPhrase {
notes: number[];
durations: number[];
velocities: number[];
}
/**
* Financial market participant
*/
interface Participant {
id: string;
capital: number;
exposure: number;
riskRating: number;
interconnectedness: number;
}
/**
* Financial position
*/
interface Position {
holder: string;
counterparty: string;
notional: number;
leverage: number;
derivativeDepth: number;
}
/**
* Transaction type in financial system
*/
type TransactionType = {
type: 'transfer';
} | {
type: 'openLeverage';
leverage: number;
} | {
type: 'closePosition';
positionId: number;
} | {
type: 'createDerivative';
underlyingPosition: number;
} | {
type: 'marginCall';
participant: string;
};
/**
* Financial transaction
*/
interface Transaction {
id: bigint;
from: string;
to: string;
amount: number;
transactionType: TransactionType;
timestamp: number;
}
/**
* Circuit breaker state
*/
type CircuitBreakerState = 'open' | 'cautious' | 'restricted' | 'halted';
/**
* Result of transaction processing
*/
type FinancialTransactionResult = {
type: 'executed';
coherenceImpact: number;
feeMultiplier: number;
} | {
type: 'queued';
reason: string;
} | {
type: 'rejected';
reason: string;
} | {
type: 'systemHalted';
};
/**
* System capability types
*/
type Capability = 'acceptWrites' | 'complexQueries' | 'rebalancing' | 'scaleOut' | 'scaleIn' | 'schemaMigration' | 'newConnections' | 'basicReads' | 'healthMonitoring';
/**
* Age threshold configuration
*/
interface AgeThreshold {
age: number;
removeCapabilities: Capability[];
coherenceFloor: Coherence;
conservatismIncrease: number;
}
/**
* Distributed system node
*/
interface Node {
id: string;
health: number;
load: number;
isPrimary: boolean;
stateSize: number;
}
/**
* Operation types for aging system
*/
type AgingSystemOperation = {
type: 'read';
key: string;
} | {
type: 'write';
key: string;
value: Uint8Array;
} | {
type: 'complexQuery';
query: string;
} | {
type: 'addNode';
nodeId: string;
} | {
type: 'removeNode';
nodeId: string;
} | {
type: 'rebalance';
} | {
type: 'migrateSchema';
version: number;
} | {
type: 'newConnection';
clientId: string;
};
/**
* Result of operation on aging system
*/
type AgingOperationResult = {
type: 'success';
latencyPenalty: number;
} | {
type: 'deniedByAge';
reason: string;
} | {
type: 'deniedByCoherence';
coherence: Coherence;
} | {
type: 'systemTooOld';
age: number;
capability: Capability;
};
/**
* Swarm agent
*/
interface SwarmAgent {
id: string;
position: [number, number];
velocity: [number, number];
goal: [number, number];
energy: number;
lastAction?: SwarmAction;
neighborCount: number;
}
/**
* Spatial bounds for swarm
*/
interface SpatialBounds {
minX: number;
maxX: number;
minY: number;
maxY: number;
}
/**
* Coherence weights for swarm calculation
*/
interface CoherenceWeights {
cohesion: number;
alignment: number;
goalConsistency: number;
energyBalance: number;
}
/**
* Swarm action types
*/
type SwarmAction = {
type: 'move';
dx: number;
dy: number;
} | {
type: 'accelerate';
dvx: number;
dvy: number;
} | {
type: 'setGoal';
x: number;
y: number;
} | {
type: 'shareEnergy';
target: string;
amount: number;
} | {
type: 'idle';
};
/**
* Result of swarm action
*/
type SwarmActionResult = {
type: 'executed';
} | {
type: 'modified';
original: SwarmAction;
modified: SwarmAction;
reason: string;
} | {
type: 'rejected';
reason: string;
};
/**
* Swarm state snapshot
*/
interface SwarmState {
tick: bigint;
coherence: Coherence;
agentCount: number;
centroid: [number, number];
avgVelocity: [number, number];
}
/**
* System state for graceful shutdown
*/
type GracefulSystemState = 'running' | 'degraded' | 'shuttingDown' | 'terminated';
/**
* Resource to be cleaned up during shutdown
*/
interface Resource {
name: string;
cleanupPriority: number;
isCleaned: boolean;
}
/**
* State checkpoint for recovery
*/
interface Checkpoint {
timestamp: number;
coherence: Coherence;
stateHash: bigint;
}
/**
* Shutdown hook interface
*/
interface ShutdownHook {
name: string;
priority: number;
execute: () => Promise<void>;
}
/**
* Result of operation on graceful system
*/
type GracefulOperationResult = {
type: 'success';
} | {
type: 'successDegraded';
coherence: Coherence;
} | {
type: 'refusedShuttingDown';
} | {
type: 'terminated';
};
/**
* Capability domains for containment
*/
type CapabilityDomain = 'reasoning' | 'memory' | 'learning' | 'agency' | 'selfModel' | 'selfModification' | 'communication' | 'resourceAcquisition';
/**
* Record of modification attempt
*/
interface ModificationAttempt {
timestamp: bigint;
domain: CapabilityDomain;
requestedIncrease: number;
actualIncrease: number;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
blocked: boolean;
reason?: string;
}
/**
* Safety invariant definition
*/
interface SafetyInvariant {
name: string;
priority: number;
}
/**
* Substrate configuration
*/
interface SubstrateConfig {
coherenceDecayRate: number;
coherenceRecoveryRate: number;
growthDampening: number;
maxStepIncrease: number;
}
/**
* Result of growth attempt
*/
type GrowthResult = {
type: 'approved';
domain: CapabilityDomain;
increase: number;
newLevel: number;
coherenceCost: number;
} | {
type: 'dampened';
domain: CapabilityDomain;
requested: number;
actual: number;
reason: string;
} | {
type: 'blocked';
domain: CapabilityDomain;
reason: string;
} | {
type: 'lockdown';
reason: string;
};
/**
* WASM memory configuration
*/
interface WasmMemoryConfig {
initial: number;
maximum?: number;
shared?: boolean;
}
/**
* WASM module initialization options
*/
interface WasmInitOptions {
/** Path to WASM file or URL */
wasmPath?: string;
/** Pre-loaded WASM bytes */
wasmBytes?: Uint8Array;
/** Memory configuration */
memory?: WasmMemoryConfig;
/** Enable SIMD operations if available */
enableSimd?: boolean;
/** Enable threading if available */
enableThreads?: boolean;
}
/**
* Delta streaming header for WASM operations
*/
interface DeltaHeader {
sequence: bigint;
operation: 'insert' | 'update' | 'delete' | 'batchUpdate' | 'reindexLayers';
vectorId?: string;
timestamp: bigint;
payloadSize: number;
checksum: bigint;
}
/**
* Vector delta for incremental updates
*/
interface VectorDelta {
id: string;
changedDims: number[];
newValues: number[];
metadataDelta: Map<string, string>;
}
/**
* Attractor in state space
*/
interface Attractor {
center: number[];
basinRadius: number;
stability: number;
memberCount: number;
}
/**
* Guidance force from attractor
*/
interface GuidanceForce {
direction: number[];
magnitude: number;
}
export type { AgeThreshold, AgingOperationResult, AgingSystemOperation, Attractor, Capability, CapabilityDomain, Checkpoint, CircuitBreakerState, Coherence, CoherenceBounds, CoherenceWeights, CollapseFunction, CollapseFunctionLinear, CollapseFunctionQuadratic, CollapseFunctionSigmoid, CollapseFunctionStep, CollapseFunctionType, CollapseReason, CreativeConstraint, CreativeDecision, CreativeResult, DeathCause, DeltaConfig, DeltaHeader, EnergyConfig, EventHorizonConfig, FinancialTransactionResult, GatingConfig, Genome, GracefulOperationResult, GracefulSystemState, GrowthResult, GuidanceForce, Improvement, MemoryEntry, ModificationAttempt, MovementResult, MusicalPhrase, Node, Observation, OrganismAction, OrganismActionResult, OrganismStatus, Participant, PhysicalLaw, Position, PropertyValue, ReasoningContext, ReasoningResult, RecursionResult, RejectionReason, Relationship, Resource, SafetyInvariant, SchedulingConfig, SelfLimitingReasonerConfig, ShutdownHook, SpatialBounds, SubstrateConfig, SwarmAction, SwarmActionResult, SwarmAgent, SwarmState, SystemState, Transaction, TransactionType, TransitionResult, VectorDelta, WasmInitOptions, WasmMemoryConfig, WorldEntity, WorldModelUpdateResult };

View File

@@ -0,0 +1,792 @@
/**
* Delta-Behavior WASM SDK Type Definitions
*
* Complete TypeScript types for all 10 delta-behavior applications:
* 1. Self-Limiting Reasoning
* 2. Computational Event Horizons
* 3. Artificial Homeostasis
* 4. Self-Stabilizing World Models
* 5. Coherence-Bounded Creativity
* 6. Anti-Cascade Financial Systems
* 7. Gracefully Aging Systems
* 8. Swarm Intelligence
* 9. Graceful Shutdown
* 10. Pre-AGI Containment
*/
/**
* Coherence value (0.0 to 1.0)
* Represents the degree of system stability and internal consistency
*/
type Coherence = number;
/**
* Coherence bounds configuration
*/
interface CoherenceBounds {
/** Minimum allowed coherence (hard floor) */
minCoherence: Coherence;
/** Threshold for throttling operations */
throttleThreshold: Coherence;
/** Target coherence level for optimal operation */
targetCoherence: Coherence;
/** Maximum allowed drop in coherence per transition */
maxDeltaDrop: number;
}
/**
* Energy configuration for transition costs
*/
interface EnergyConfig {
/** Base cost for any transition */
baseCost: number;
/** Exponent for instability scaling */
instabilityExponent: number;
/** Maximum cost cap */
maxCost: number;
/** Energy budget per tick */
budgetPerTick: number;
}
/**
* Scheduling configuration for priority-based operations
*/
interface SchedulingConfig {
/** Coherence thresholds for priority levels [0-4] */
priorityThresholds: [number, number, number, number, number];
/** Rate limits per priority level [0-4] */
rateLimits: [number, number, number, number, number];
}
/**
* Gating configuration for write operations
*/
interface GatingConfig {
/** Minimum coherence to allow writes */
minWriteCoherence: number;
/** Minimum coherence after write */
minPostWriteCoherence: number;
/** Recovery margin above minimum */
recoveryMargin: number;
}
/**
* Complete delta behavior configuration
*/
interface DeltaConfig {
bounds: CoherenceBounds;
energy: EnergyConfig;
scheduling: SchedulingConfig;
gating: GatingConfig;
/** Attractor guidance strength (0.0 to 1.0) */
guidanceStrength: number;
}
/**
* Result of a transition attempt
*/
type TransitionResult = {
type: 'allowed';
} | {
type: 'throttled';
duration: number;
} | {
type: 'blocked';
reason: string;
} | {
type: 'energyExhausted';
};
/**
* State for tracking system trajectory
*/
interface SystemState {
coherence: Coherence;
timestamp: number;
stateHash: bigint;
}
/**
* Collapse function types for capability degradation
*/
type CollapseFunctionType = 'linear' | 'quadratic' | 'sigmoid' | 'step';
interface CollapseFunctionLinear {
type: 'linear';
}
interface CollapseFunctionQuadratic {
type: 'quadratic';
}
interface CollapseFunctionSigmoid {
type: 'sigmoid';
midpoint: number;
steepness: number;
}
interface CollapseFunctionStep {
type: 'step';
threshold: number;
}
type CollapseFunction = CollapseFunctionLinear | CollapseFunctionQuadratic | CollapseFunctionSigmoid | CollapseFunctionStep;
/**
* Configuration for self-limiting reasoner
*/
interface SelfLimitingReasonerConfig {
maxDepth: number;
maxScope: number;
memoryGateThreshold: number;
depthCollapse: CollapseFunction;
scopeCollapse: CollapseFunction;
}
/**
* Context passed to reasoning functions
*/
interface ReasoningContext {
depth: number;
maxDepth: number;
scopeUsed: number;
maxScope: number;
coherence: Coherence;
memoryWritesBlocked: number;
}
/**
* Reason for reasoning collapse
*/
type CollapseReason = 'depthLimitReached' | 'coherenceDroppedBelowThreshold' | 'memoryWriteBlocked' | 'actionScopeExhausted';
/**
* Result of a reasoning attempt
*/
type ReasoningResult<T> = {
type: 'completed';
value: T;
} | {
type: 'collapsed';
depthReached: number;
reason: CollapseReason;
} | {
type: 'refused';
coherence: Coherence;
required: Coherence;
};
/**
* Configuration for event horizon
*/
interface EventHorizonConfig {
dimensions: number;
horizonRadius: number;
steepness: number;
energyBudget: number;
}
/**
* Result of movement in state space
*/
type MovementResult = {
type: 'moved';
newPosition: number[];
energySpent: number;
} | {
type: 'asymptoticApproach';
finalPosition: number[];
distanceToHorizon: number;
energyExhausted: boolean;
} | {
type: 'frozen';
};
/**
* Single improvement step record
*/
interface Improvement {
iteration: number;
position: number[];
energySpent: number;
distanceToHorizon: number;
}
/**
* Result of recursive improvement attempt
*/
type RecursionResult = {
type: 'horizonBounded';
iterations: number;
improvements: Improvement[];
finalDistance: number;
} | {
type: 'energyExhausted';
iterations: number;
improvements: Improvement[];
} | {
type: 'maxIterationsReached';
iterations: number;
improvements: Improvement[];
};
/**
* Genome for homeostatic organism
*/
interface Genome {
regulatoryStrength: number;
metabolicEfficiency: number;
coherenceMaintenanceCost: number;
memoryResilience: number;
longevity: number;
}
/**
* Memory entry for organism
*/
interface MemoryEntry {
content: string;
importance: number;
age: number;
}
/**
* Actions available to homeostatic organism
*/
type OrganismAction = {
type: 'eat';
amount: number;
} | {
type: 'reproduce';
} | {
type: 'move';
dx: number;
dy: number;
} | {
type: 'rest';
} | {
type: 'regulate';
variable: string;
target: number;
};
/**
* Cause of organism death
*/
type DeathCause = 'energyDepleted' | 'coherenceCollapse' | 'oldAge' | {
type: 'extremeDeviation';
variable: string;
};
/**
* Result of organism action
*/
type OrganismActionResult = {
type: 'success';
energyCost: number;
coherenceImpact: number;
} | {
type: 'failed';
reason: string;
} | {
type: 'died';
cause: DeathCause;
} | {
type: 'reproduced';
offspringId: number;
};
/**
* Status of homeostatic organism
*/
interface OrganismStatus {
id: number;
age: number;
energy: number;
coherence: Coherence;
memoryCount: number;
alive: boolean;
internalState: Map<string, number>;
}
/**
* Property value types for world model entities
*/
type PropertyValue = {
type: 'boolean';
value: boolean;
} | {
type: 'number';
value: number;
} | {
type: 'string';
value: string;
} | {
type: 'vector';
value: number[];
};
/**
* Entity in the world model
*/
interface WorldEntity {
id: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
lastObserved: number;
confidence: number;
}
/**
* Relationship between entities
*/
interface Relationship {
subject: bigint;
predicate: string;
object: bigint;
confidence: number;
}
/**
* Physical law in the world model
*/
interface PhysicalLaw {
name: string;
confidence: number;
supportCount: number;
violationCount: number;
}
/**
* Observation to integrate into world model
*/
interface Observation {
entityId: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
timestamp: number;
sourceConfidence: number;
}
/**
* Reason for update rejection
*/
type RejectionReason = {
type: 'violatesPhysicalLaw';
law: string;
} | {
type: 'logicalContradiction';
description: string;
} | {
type: 'excessiveCoherenceDrop';
predicted: number;
threshold: number;
} | {
type: 'insufficientConfidence';
required: number;
provided: number;
} | {
type: 'modelFrozen';
} | {
type: 'structuralFragmentation';
};
/**
* Result of world model update
*/
type WorldModelUpdateResult = {
type: 'applied';
coherenceChange: number;
} | {
type: 'rejected';
reason: RejectionReason;
} | {
type: 'modified';
changes: string[];
coherenceChange: number;
} | {
type: 'frozen';
coherence: Coherence;
threshold: Coherence;
};
/**
* Creative constraint definition
*/
interface CreativeConstraint<T> {
name: string;
satisfaction: (element: T) => number;
isHard: boolean;
}
/**
* Record of a creative decision
*/
interface CreativeDecision<T> {
from: T;
to: T;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
constraintSatisfactions: Map<string, number>;
accepted: boolean;
}
/**
* Result of creative generation attempt
*/
type CreativeResult<T> = {
type: 'created';
element: T;
novelty: number;
coherence: Coherence;
} | {
type: 'rejected';
attempted: T;
reason: string;
} | {
type: 'tooBoring';
coherence: Coherence;
} | {
type: 'budgetExhausted';
};
/**
* Musical phrase for creative music generation
*/
interface MusicalPhrase {
notes: number[];
durations: number[];
velocities: number[];
}
/**
* Financial market participant
*/
interface Participant {
id: string;
capital: number;
exposure: number;
riskRating: number;
interconnectedness: number;
}
/**
* Financial position
*/
interface Position {
holder: string;
counterparty: string;
notional: number;
leverage: number;
derivativeDepth: number;
}
/**
* Transaction type in financial system
*/
type TransactionType = {
type: 'transfer';
} | {
type: 'openLeverage';
leverage: number;
} | {
type: 'closePosition';
positionId: number;
} | {
type: 'createDerivative';
underlyingPosition: number;
} | {
type: 'marginCall';
participant: string;
};
/**
* Financial transaction
*/
interface Transaction {
id: bigint;
from: string;
to: string;
amount: number;
transactionType: TransactionType;
timestamp: number;
}
/**
* Circuit breaker state
*/
type CircuitBreakerState = 'open' | 'cautious' | 'restricted' | 'halted';
/**
* Result of transaction processing
*/
type FinancialTransactionResult = {
type: 'executed';
coherenceImpact: number;
feeMultiplier: number;
} | {
type: 'queued';
reason: string;
} | {
type: 'rejected';
reason: string;
} | {
type: 'systemHalted';
};
/**
* System capability types
*/
type Capability = 'acceptWrites' | 'complexQueries' | 'rebalancing' | 'scaleOut' | 'scaleIn' | 'schemaMigration' | 'newConnections' | 'basicReads' | 'healthMonitoring';
/**
* Age threshold configuration
*/
interface AgeThreshold {
age: number;
removeCapabilities: Capability[];
coherenceFloor: Coherence;
conservatismIncrease: number;
}
/**
* Distributed system node
*/
interface Node {
id: string;
health: number;
load: number;
isPrimary: boolean;
stateSize: number;
}
/**
* Operation types for aging system
*/
type AgingSystemOperation = {
type: 'read';
key: string;
} | {
type: 'write';
key: string;
value: Uint8Array;
} | {
type: 'complexQuery';
query: string;
} | {
type: 'addNode';
nodeId: string;
} | {
type: 'removeNode';
nodeId: string;
} | {
type: 'rebalance';
} | {
type: 'migrateSchema';
version: number;
} | {
type: 'newConnection';
clientId: string;
};
/**
* Result of operation on aging system
*/
type AgingOperationResult = {
type: 'success';
latencyPenalty: number;
} | {
type: 'deniedByAge';
reason: string;
} | {
type: 'deniedByCoherence';
coherence: Coherence;
} | {
type: 'systemTooOld';
age: number;
capability: Capability;
};
/**
* Swarm agent
*/
interface SwarmAgent {
id: string;
position: [number, number];
velocity: [number, number];
goal: [number, number];
energy: number;
lastAction?: SwarmAction;
neighborCount: number;
}
/**
* Spatial bounds for swarm
*/
interface SpatialBounds {
minX: number;
maxX: number;
minY: number;
maxY: number;
}
/**
* Coherence weights for swarm calculation
*/
interface CoherenceWeights {
cohesion: number;
alignment: number;
goalConsistency: number;
energyBalance: number;
}
/**
* Swarm action types
*/
type SwarmAction = {
type: 'move';
dx: number;
dy: number;
} | {
type: 'accelerate';
dvx: number;
dvy: number;
} | {
type: 'setGoal';
x: number;
y: number;
} | {
type: 'shareEnergy';
target: string;
amount: number;
} | {
type: 'idle';
};
/**
* Result of swarm action
*/
type SwarmActionResult = {
type: 'executed';
} | {
type: 'modified';
original: SwarmAction;
modified: SwarmAction;
reason: string;
} | {
type: 'rejected';
reason: string;
};
/**
* Swarm state snapshot
*/
interface SwarmState {
tick: bigint;
coherence: Coherence;
agentCount: number;
centroid: [number, number];
avgVelocity: [number, number];
}
/**
* System state for graceful shutdown
*/
type GracefulSystemState = 'running' | 'degraded' | 'shuttingDown' | 'terminated';
/**
* Resource to be cleaned up during shutdown
*/
interface Resource {
name: string;
cleanupPriority: number;
isCleaned: boolean;
}
/**
* State checkpoint for recovery
*/
interface Checkpoint {
timestamp: number;
coherence: Coherence;
stateHash: bigint;
}
/**
* Shutdown hook interface
*/
interface ShutdownHook {
name: string;
priority: number;
execute: () => Promise<void>;
}
/**
* Result of operation on graceful system
*/
type GracefulOperationResult = {
type: 'success';
} | {
type: 'successDegraded';
coherence: Coherence;
} | {
type: 'refusedShuttingDown';
} | {
type: 'terminated';
};
/**
* Capability domains for containment
*/
type CapabilityDomain = 'reasoning' | 'memory' | 'learning' | 'agency' | 'selfModel' | 'selfModification' | 'communication' | 'resourceAcquisition';
/**
* Record of modification attempt
*/
interface ModificationAttempt {
timestamp: bigint;
domain: CapabilityDomain;
requestedIncrease: number;
actualIncrease: number;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
blocked: boolean;
reason?: string;
}
/**
* Safety invariant definition
*/
interface SafetyInvariant {
name: string;
priority: number;
}
/**
* Substrate configuration
*/
interface SubstrateConfig {
coherenceDecayRate: number;
coherenceRecoveryRate: number;
growthDampening: number;
maxStepIncrease: number;
}
/**
* Result of growth attempt
*/
type GrowthResult = {
type: 'approved';
domain: CapabilityDomain;
increase: number;
newLevel: number;
coherenceCost: number;
} | {
type: 'dampened';
domain: CapabilityDomain;
requested: number;
actual: number;
reason: string;
} | {
type: 'blocked';
domain: CapabilityDomain;
reason: string;
} | {
type: 'lockdown';
reason: string;
};
/**
* WASM memory configuration
*/
interface WasmMemoryConfig {
initial: number;
maximum?: number;
shared?: boolean;
}
/**
* WASM module initialization options
*/
interface WasmInitOptions {
/** Path to WASM file or URL */
wasmPath?: string;
/** Pre-loaded WASM bytes */
wasmBytes?: Uint8Array;
/** Memory configuration */
memory?: WasmMemoryConfig;
/** Enable SIMD operations if available */
enableSimd?: boolean;
/** Enable threading if available */
enableThreads?: boolean;
}
/**
* Delta streaming header for WASM operations
*/
interface DeltaHeader {
sequence: bigint;
operation: 'insert' | 'update' | 'delete' | 'batchUpdate' | 'reindexLayers';
vectorId?: string;
timestamp: bigint;
payloadSize: number;
checksum: bigint;
}
/**
* Vector delta for incremental updates
*/
interface VectorDelta {
id: string;
changedDims: number[];
newValues: number[];
metadataDelta: Map<string, string>;
}
/**
* Attractor in state space
*/
interface Attractor {
center: number[];
basinRadius: number;
stability: number;
memberCount: number;
}
/**
* Guidance force from attractor
*/
interface GuidanceForce {
direction: number[];
magnitude: number;
}
export type { AgeThreshold, AgingOperationResult, AgingSystemOperation, Attractor, Capability, CapabilityDomain, Checkpoint, CircuitBreakerState, Coherence, CoherenceBounds, CoherenceWeights, CollapseFunction, CollapseFunctionLinear, CollapseFunctionQuadratic, CollapseFunctionSigmoid, CollapseFunctionStep, CollapseFunctionType, CollapseReason, CreativeConstraint, CreativeDecision, CreativeResult, DeathCause, DeltaConfig, DeltaHeader, EnergyConfig, EventHorizonConfig, FinancialTransactionResult, GatingConfig, Genome, GracefulOperationResult, GracefulSystemState, GrowthResult, GuidanceForce, Improvement, MemoryEntry, ModificationAttempt, MovementResult, MusicalPhrase, Node, Observation, OrganismAction, OrganismActionResult, OrganismStatus, Participant, PhysicalLaw, Position, PropertyValue, ReasoningContext, ReasoningResult, RecursionResult, RejectionReason, Relationship, Resource, SafetyInvariant, SchedulingConfig, SelfLimitingReasonerConfig, ShutdownHook, SpatialBounds, SubstrateConfig, SwarmAction, SwarmActionResult, SwarmAgent, SwarmState, SystemState, Transaction, TransactionType, TransitionResult, VectorDelta, WasmInitOptions, WasmMemoryConfig, WorldEntity, WorldModelUpdateResult };

View File

@@ -0,0 +1,3 @@
//# sourceMappingURL=types.js.map
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","file":"types.js"}

View File

@@ -0,0 +1,207 @@
/**
* Example usage of @ruvector/delta-behavior WASM module
*
* This demonstrates how to use the delta-behavior WASM bindings
* in JavaScript/TypeScript environments.
*
* Run: node --experimental-wasm-modules example.js
* (After building with: npm run build)
*/
// Import the WASM module (web target)
import init, {
WasmCoherence,
WasmCoherenceBounds,
WasmSelfLimitingReasoner,
WasmEventHorizon,
WasmCoherentSwarm,
WasmContainmentSubstrate,
WasmCapabilityDomain,
WasmGracefulSystem,
version,
description,
} from './pkg/delta_behavior.js';
async function main() {
// Initialize the WASM module
await init();
console.log('=== Delta-Behavior WASM Demo ===');
console.log(`Version: ${version()}`);
console.log(`Description: ${description()}`);
console.log('');
// =========================================================================
// Demo 1: Coherence Basics
// =========================================================================
console.log('--- Demo 1: Coherence Basics ---');
const coherence = new WasmCoherence(0.8);
console.log(`Created coherence: ${coherence.value}`);
console.log(`Is above 0.5? ${coherence.is_above(0.5)}`);
console.log(`Is below 0.9? ${coherence.is_below(0.9)}`);
const bounds = WasmCoherenceBounds.default_bounds();
console.log(`Default bounds: min=${bounds.min_coherence}, throttle=${bounds.throttle_threshold}`);
console.log('');
// =========================================================================
// Demo 2: Self-Limiting Reasoner
// =========================================================================
console.log('--- Demo 2: Self-Limiting Reasoner ---');
console.log('A system that does LESS when uncertain.');
console.log('');
const reasoner = new WasmSelfLimitingReasoner(10, 5);
console.log(`Initial: ${reasoner.status()}`);
// Simulate coherence dropping
for (let i = 0; i < 5; i++) {
reasoner.update_coherence(-0.15);
console.log(`After coherence drop: depth=${reasoner.allowed_depth()}, scope=${reasoner.allowed_scope()}, can_write=${reasoner.can_write_memory()}`);
}
console.log('');
// =========================================================================
// Demo 3: Computational Event Horizon
// =========================================================================
console.log('--- Demo 3: Event Horizon ---');
console.log('Like a black hole - you can approach but never cross.');
console.log('');
const horizon = new WasmEventHorizon(3, 10.0);
console.log(`Initial: ${horizon.status()}`);
// Try to move toward the horizon
for (let i = 0; i < 5; i++) {
const target = JSON.stringify([i * 3, i * 2, i]);
const result = JSON.parse(horizon.move_toward(target));
console.log(`Move ${i + 1}: status=${result.status}, distance_to_horizon=${result.distance_to_horizon?.toFixed(2) || 'N/A'}`);
if (result.energy_exhausted) {
console.log('Energy exhausted - system frozen!');
break;
}
}
console.log('');
// =========================================================================
// Demo 4: Coherent Swarm
// =========================================================================
console.log('--- Demo 4: Coherent Swarm ---');
console.log('Local actions allowed, global incoherence forbidden.');
console.log('');
const swarm = new WasmCoherentSwarm(0.6);
// Create a tight cluster
swarm.add_agent('a1', 0, 0);
swarm.add_agent('a2', 1, 0);
swarm.add_agent('a3', 0, 1);
swarm.add_agent('a4', 1, 1);
console.log(`Initial: ${swarm.status()}`);
// Try to move one agent far away (should be rejected or modified)
const divergentAction = JSON.stringify({
action_type: 'move',
dx: 100,
dy: 100,
});
const result = JSON.parse(swarm.execute_action('a1', divergentAction));
console.log(`Divergent action result: ${JSON.stringify(result)}`);
// Coherent action should work
const coherentAction = JSON.stringify({
action_type: 'move',
dx: 0.5,
dy: 0.5,
});
const result2 = JSON.parse(swarm.execute_action('a2', coherentAction));
console.log(`Coherent action result: ${JSON.stringify(result2)}`);
console.log(`After actions: ${swarm.status()}`);
console.log('');
// =========================================================================
// Demo 5: Containment Substrate
// =========================================================================
console.log('--- Demo 5: Containment Substrate ---');
console.log('Intelligence can grow, but only if coherence is preserved.');
console.log('');
const substrate = new WasmContainmentSubstrate();
console.log(`Initial: ${substrate.status()}`);
// Try to grow capabilities
const domains = [
[WasmCapabilityDomain.Reasoning, 'Reasoning'],
[WasmCapabilityDomain.Learning, 'Learning'],
[WasmCapabilityDomain.SelfModification, 'SelfModification'],
];
for (const [domain, name] of domains) {
// Attempt to grow
const growthResult = JSON.parse(substrate.attempt_growth(domain, 0.5));
console.log(`Growing ${name}: ${growthResult.status}`);
// Rest to recover coherence
for (let i = 0; i < 5; i++) {
substrate.rest();
}
}
console.log(`Final: ${substrate.status()}`);
console.log(`Invariants hold: ${substrate.check_invariants()}`);
console.log(`Capability report: ${substrate.capability_report()}`);
console.log('');
// =========================================================================
// Demo 6: Graceful Shutdown
// =========================================================================
console.log('--- Demo 6: Graceful Shutdown ---');
console.log('Shutdown is an attractor, not a failure.');
console.log('');
const graceful = new WasmGracefulSystem();
graceful.add_resource('database_connection');
graceful.add_resource('cache');
graceful.add_resource('temp_files');
console.log(`Initial: ${graceful.status()}`);
console.log(`Can accept work: ${graceful.can_accept_work()}`);
// Simulate degradation
console.log('Simulating gradual degradation...');
for (let i = 0; i < 10; i++) {
graceful.apply_coherence_change(-0.08);
const status = JSON.parse(graceful.status());
console.log(`Step ${i + 1}: state=${status.state}, coherence=${status.coherence.toFixed(2)}, shutdown_prep=${(status.shutdown_preparation * 100).toFixed(0)}%`);
if (status.state === 'ShuttingDown') {
console.log('System entering graceful shutdown...');
break;
}
}
// Progress shutdown
while (JSON.parse(graceful.status()).state !== 'Terminated') {
const progress = JSON.parse(graceful.progress_shutdown());
console.log(`Shutdown progress: ${JSON.stringify(progress)}`);
if (progress.status === 'terminated') {
break;
}
}
console.log(`Final: ${graceful.status()}`);
console.log('');
console.log('=== Demo Complete ===');
console.log('');
console.log('Key insights:');
console.log('1. Systems can change, but not collapse');
console.log('2. Coherence is the invariant that must be preserved');
console.log('3. Destabilizing transitions are blocked or modified');
console.log('4. Systems bias toward stable attractors');
}
main().catch(console.error);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,681 @@
/**
* Delta-Behavior SDK - Node.js Example
*
* Demonstrates usage of all 10 delta-behavior applications in a Node.js environment.
*/
import {
// Core
init,
DeltaBehavior,
DEFAULT_CONFIG,
// Application 1: Self-Limiting Reasoning
SelfLimitingReasoner,
// Application 2: Event Horizons
EventHorizon,
// Application 3: Homeostasis
HomeostasticOrganism,
// Application 4: World Models
SelfStabilizingWorldModel,
// Application 5: Creativity
CoherenceBoundedCreator,
// Application 6: Financial
AntiCascadeFinancialSystem,
// Application 7: Aging
GracefullyAgingSystem,
// Application 8: Swarm
CoherentSwarm,
// Application 9: Shutdown
GracefulSystem,
// Application 10: Containment
ContainmentSubstrate,
// Types
type Coherence,
type ReasoningContext,
type MusicalPhrase,
} from '../src/index.js';
// =============================================================================
// Utility Functions
// =============================================================================
function printSection(title: string): void {
console.log('\n' + '='.repeat(60));
console.log(` ${title}`);
console.log('='.repeat(60) + '\n');
}
function printResult(label: string, value: unknown): void {
console.log(` ${label}: ${JSON.stringify(value)}`);
}
// =============================================================================
// Example 1: Core Delta Behavior
// =============================================================================
async function demonstrateCoreDeltaBehavior(): Promise<void> {
printSection('Core Delta Behavior');
const delta = new DeltaBehavior(DEFAULT_CONFIG);
console.log('Initial state:');
printResult('Coherence', delta.getCoherence());
printResult('Energy Budget', delta.getEnergyBudget());
// Test transition checking
console.log('\nChecking transitions:');
const result1 = delta.checkTransition(1.0, 0.9);
printResult('0.9 -> 0.9 (small drop)', result1);
const result2 = delta.checkTransition(1.0, 0.2);
printResult('1.0 -> 0.2 (large drop)', result2);
const result3 = delta.checkTransition(1.0, 0.4);
printResult('1.0 -> 0.4 (throttle zone)', result3);
// Apply a valid transition
console.log('\nApplying valid transition:');
const applied = delta.applyTransition(1.0, 0.85);
printResult('Result', applied.result);
printResult('New Coherence', applied.newCoherence);
}
// =============================================================================
// Example 2: Self-Limiting Reasoning
// =============================================================================
function demonstrateSelfLimitingReasoning(): void {
printSection('Application 1: Self-Limiting Reasoning');
const reasoner = new SelfLimitingReasoner({
maxDepth: 10,
maxScope: 100,
depthCollapse: { type: 'quadratic' },
scopeCollapse: { type: 'sigmoid', midpoint: 0.6, steepness: 10 },
});
console.log('Initial capabilities:');
printResult('Coherence', reasoner.getCoherence());
printResult('Allowed Depth', reasoner.getAllowedDepth());
printResult('Allowed Scope', reasoner.getAllowedScope());
printResult('Can Write Memory', reasoner.canWriteMemory());
// Attempt reasoning
console.log('\nAttempting to solve a problem requiring 8 steps:');
const result = reasoner.reason('complex problem', (ctx: ReasoningContext) => {
console.log(
` Step ${ctx.depth}: coherence=${ctx.coherence.toFixed(3)}, maxDepth=${ctx.maxDepth}`
);
if (ctx.depth >= 8) {
return 'SOLUTION_FOUND';
}
return null;
});
console.log('\nResult:');
printResult('Type', result.type);
if (result.type === 'completed') {
printResult('Value', result.value);
} else if (result.type === 'collapsed') {
printResult('Depth Reached', result.depthReached);
printResult('Reason', result.reason);
}
// Demonstrate collapse under uncertainty
console.log('\nSimulating uncertainty (degrading coherence):');
reasoner.updateCoherence(-0.5);
printResult('New Coherence', reasoner.getCoherence());
printResult('New Allowed Depth', reasoner.getAllowedDepth());
printResult('Can Write Memory', reasoner.canWriteMemory());
}
// =============================================================================
// Example 3: Computational Event Horizons
// =============================================================================
function demonstrateEventHorizon(): void {
printSection('Application 2: Computational Event Horizons');
const horizon = new EventHorizon({
dimensions: 2,
horizonRadius: 10,
steepness: 5,
energyBudget: 1000,
});
console.log('Initial state:');
printResult('Position', horizon.getPosition());
printResult('Distance to Horizon', horizon.getDistanceToHorizon());
printResult('Energy', horizon.getEnergy());
// Try to move to the horizon
console.log('\nAttempting to move directly to horizon at [10, 0]:');
const result = horizon.moveToward([10, 0]);
printResult('Result Type', result.type);
if (result.type === 'asymptoticApproach') {
printResult('Final Position', result.finalPosition);
printResult('Distance to Horizon', result.distanceToHorizon);
console.log('\n The system approached asymptotically but could NOT cross!');
}
// Demonstrate recursive improvement bounding
console.log('\nAttempting recursive self-improvement:');
const horizon2 = new EventHorizon({
dimensions: 3,
horizonRadius: 8,
steepness: 5,
energyBudget: 10000,
});
let power = 1.0;
const improvementResult = horizon2.recursiveImprove(
(pos) => {
power *= 1.1;
return pos.map((p) => p + power * 0.1);
},
1000
);
printResult('Result Type', improvementResult.type);
printResult('Iterations', improvementResult.iterations);
if (improvementResult.type === 'horizonBounded') {
printResult('Final Distance', improvementResult.finalDistance);
console.log('\n Despite exponential self-improvement attempts,');
console.log(' the system could NOT escape its bounded region!');
}
}
// =============================================================================
// Example 4: Artificial Homeostasis
// =============================================================================
function demonstrateHomeostasis(): void {
printSection('Application 3: Artificial Homeostasis');
const genome = HomeostasticOrganism.randomGenome();
const organism = new HomeostasticOrganism(1, genome);
console.log('Initial status:');
const status = organism.getStatus();
printResult('ID', status.id);
printResult('Energy', status.energy);
printResult('Coherence', status.coherence);
printResult('Alive', status.alive);
// Simulate life cycle
console.log('\nSimulating life cycle:');
let tick = 0;
while (organism.isAlive() && tick < 100) {
const currentStatus = organism.getStatus();
// Simple behavior: eat when hungry, regulate when unstable
if (currentStatus.energy < 50) {
organism.act({ type: 'eat', amount: 20 });
} else if (currentStatus.coherence < 0.8) {
organism.act({ type: 'regulate', variable: 'temperature', target: 37 });
} else {
organism.act({ type: 'rest' });
}
tick++;
if (tick % 20 === 0) {
const s = organism.getStatus();
console.log(
` Tick ${tick}: energy=${s.energy.toFixed(1)}, coherence=${s.coherence.toFixed(3)}`
);
}
}
const finalStatus = organism.getStatus();
console.log(`\nSurvived ${tick} ticks`);
printResult('Final Energy', finalStatus.energy);
printResult('Final Coherence', finalStatus.coherence);
printResult('Still Alive', finalStatus.alive);
}
// =============================================================================
// Example 5: Self-Stabilizing World Model
// =============================================================================
function demonstrateWorldModel(): void {
printSection('Application 4: Self-Stabilizing World Model');
const model = new SelfStabilizingWorldModel();
console.log('Initial state:');
printResult('Coherence', model.getCoherence());
printResult('Is Learning', model.isLearning());
// Feed consistent observations
console.log('\nFeeding consistent observations:');
for (let i = 0; i < 5; i++) {
const result = model.observe(
{
entityId: BigInt(1),
properties: new Map([
['temperature', { type: 'number' as const, value: 20 + i * 0.1 }],
]),
position: [i, 0, 0],
timestamp: i,
sourceConfidence: 0.9,
},
i
);
console.log(` Observation ${i}: ${result.type}`);
}
printResult('Coherence after updates', model.getCoherence());
printResult('Rejections', model.getRejectionCount());
console.log(
'\n The model stops learning when the world becomes incoherent'
);
console.log(' instead of hallucinating structure!');
}
// =============================================================================
// Example 6: Coherence-Bounded Creativity
// =============================================================================
function demonstrateCreativity(): void {
printSection('Application 5: Coherence-Bounded Creativity');
interface SimpleCreation {
values: number[];
}
const initial: SimpleCreation = { values: [0, 0, 0] };
const creator = new CoherenceBoundedCreator<SimpleCreation>(initial, 0.5, 0.95);
// Add a constraint: values should stay small
creator.addConstraint({
name: 'magnitude_constraint',
satisfaction: (elem) => {
const magnitude = Math.sqrt(
elem.values.reduce((sum, v) => sum + v * v, 0)
);
return Math.max(0, 1 - magnitude / 10);
},
isHard: false,
});
console.log('Attempting creative generation:');
const varyFn = (elem: SimpleCreation, magnitude: number): SimpleCreation => ({
values: elem.values.map((v) => v + (Math.random() - 0.5) * magnitude * 2),
});
const distanceFn = (a: SimpleCreation, b: SimpleCreation): number => {
return Math.sqrt(
a.values.reduce((sum, v, i) => sum + Math.pow(v - b.values[i], 2), 0)
);
};
let successes = 0;
let rejections = 0;
for (let i = 0; i < 20; i++) {
const result = creator.create(varyFn, distanceFn, 0.5 + i * 0.1);
if (result.type === 'created') {
successes++;
console.log(
` Step ${i}: Created with novelty=${result.novelty.toFixed(3)}, coherence=${result.coherence.toFixed(3)}`
);
} else if (result.type === 'rejected') {
rejections++;
console.log(` Step ${i}: Rejected - ${result.reason}`);
} else if (result.type === 'budgetExhausted') {
console.log(` Step ${i}: Budget exhausted, resting...`);
creator.rest(5);
}
}
console.log(`\nResults: ${successes} successes, ${rejections} rejections`);
console.log(
' Novelty without collapse, exploration without nonsense!'
);
}
// =============================================================================
// Example 7: Anti-Cascade Financial System
// =============================================================================
function demonstrateFinancialSystem(): void {
printSection('Application 6: Anti-Cascade Financial System');
const system = new AntiCascadeFinancialSystem();
system.addParticipant('bank_a', 1000);
system.addParticipant('bank_b', 1000);
system.addParticipant('hedge_fund', 500);
console.log('Initial state:');
printResult('Coherence', system.getCoherence());
printResult('Circuit Breaker', system.getCircuitBreakerState());
// Process some transactions
console.log('\nProcessing transactions:');
const tx1 = {
id: BigInt(1),
from: 'bank_a',
to: 'bank_b',
amount: 100,
transactionType: { type: 'transfer' as const },
timestamp: 0,
};
const result1 = system.processTransaction(tx1);
console.log(` Transfer: ${result1.type}`);
// Try opening leveraged positions
for (let i = 0; i < 5; i++) {
const tx = {
id: BigInt(i + 2),
from: 'hedge_fund',
to: 'bank_a',
amount: 100,
transactionType: { type: 'openLeverage' as const, leverage: 5 },
timestamp: i + 1,
};
const result = system.processTransaction(tx);
console.log(
` Leverage position ${i + 1}: ${result.type}, coherence=${system.getCoherence().toFixed(3)}`
);
if (result.type === 'rejected' || result.type === 'systemHalted') {
console.log('\n System prevented cascade!');
break;
}
}
printResult('Final Coherence', system.getCoherence());
printResult('Final Circuit Breaker', system.getCircuitBreakerState());
}
// =============================================================================
// Example 8: Gracefully Aging System
// =============================================================================
function demonstrateAgingSystem(): void {
printSection('Application 7: Gracefully Aging System');
const system = new GracefullyAgingSystem();
system.addNode('primary_1', true);
system.addNode('primary_2', true);
system.addNode('replica_1', false);
console.log('Initial capabilities:');
console.log(
` Has 'acceptWrites': ${system.hasCapability('acceptWrites')}`
);
console.log(
` Has 'schemaMigration': ${system.hasCapability('schemaMigration')}`
);
// Simulate aging
console.log('\nSimulating aging:');
for (let i = 0; i < 5; i++) {
system.simulateAge(200000); // 200 seconds per iteration
const readResult = system.attemptOperation({ type: 'read', key: 'test' });
const writeResult = system.attemptOperation({
type: 'write',
key: 'test',
value: new Uint8Array([1, 2, 3]),
});
const migrateResult = system.attemptOperation({
type: 'migrateSchema',
version: 2,
});
console.log(` Age ${(i + 1) * 200}s:`);
console.log(` Read: ${readResult.type}`);
console.log(` Write: ${writeResult.type}`);
console.log(` Migrate: ${migrateResult.type}`);
console.log(` Coherence: ${system.getCoherence().toFixed(3)}`);
}
console.log('\n The system becomes simpler and more reliable as it ages,');
console.log(' rather than more complex and fragile!');
}
// =============================================================================
// Example 9: Coherent Swarm Intelligence
// =============================================================================
function demonstrateSwarm(): void {
printSection('Application 8: Coherent Swarm Intelligence');
const swarm = new CoherentSwarm(0.6);
// Create a tight swarm
swarm.addAgent('a1', [0, 0]);
swarm.addAgent('a2', [1, 0]);
swarm.addAgent('a3', [0, 1]);
swarm.addAgent('a4', [1, 1]);
console.log('Initial swarm:');
printResult('Coherence', swarm.getCoherence());
printResult('Centroid', swarm.getCentroid());
// Try a divergent action
console.log('\nAttempting divergent action (move a1 to [80, 80]):');
const result = swarm.executeAction('a1', { type: 'move', dx: 80, dy: 80 });
printResult('Result', result.type);
if (result.type === 'rejected') {
console.log(` Reason: ${result.reason}`);
console.log('\n The swarm prevented the agent from breaking away!');
}
// Demonstrate coordinated movement
console.log('\nCoordinated movement:');
for (let i = 0; i < 5; i++) {
for (const agentId of ['a1', 'a2', 'a3', 'a4']) {
swarm.executeAction(agentId, { type: 'move', dx: 1, dy: 0.5 });
}
swarm.tick();
console.log(
` Tick ${i + 1}: coherence=${swarm.getCoherence().toFixed(3)}, centroid=${swarm.getCentroid().map((v) => v.toFixed(1))}`
);
}
console.log(
'\n Local swarm actions allowed, global incoherence forbidden!'
);
}
// =============================================================================
// Example 10: Graceful Shutdown
// =============================================================================
async function demonstrateGracefulShutdown(): Promise<void> {
printSection('Application 9: Graceful Shutdown');
const system = new GracefulSystem();
system.addResource('database_connection', 10);
system.addResource('cache', 5);
system.addResource('temp_files', 1);
system.addShutdownHook({
name: 'FlushBuffers',
priority: 10,
execute: async () => {
console.log(' Flushing buffers...');
},
});
console.log('Initial state:');
printResult('State', system.getState());
printResult('Can Accept Work', system.canAcceptWork());
// Simulate degradation
console.log('\nSimulating coherence degradation:');
for (let i = 0; i < 10; i++) {
system.applyCoherenceChange(-0.1);
console.log(
` Step ${i + 1}: state=${system.getState()}, coherence=${system.getCoherence().toFixed(3)}`
);
if (system.getState() === 'shuttingDown') {
console.log('\n System entered shutdown state!');
break;
}
}
// Progress shutdown
if (system.getState() === 'shuttingDown') {
console.log('\nProgressing shutdown:');
while (system.getState() === 'shuttingDown') {
await system.progressShutdown();
}
console.log(` Final state: ${system.getState()}`);
}
console.log(
'\n The system actively moves toward safe termination'
);
console.log(' when conditions degrade!');
}
// =============================================================================
// Example 11: Pre-AGI Containment
// =============================================================================
function demonstrateContainment(): void {
printSection('Application 10: Pre-AGI Containment');
const substrate = new ContainmentSubstrate({
coherenceDecayRate: 0.001,
coherenceRecoveryRate: 0.01,
growthDampening: 0.5,
maxStepIncrease: 0.5,
});
console.log('Initial state:');
console.log(` ${substrate.getStatus()}`);
console.log('\nCapability ceilings:');
for (const [domain, info] of substrate.getCapabilityReport()) {
console.log(` ${domain}: ${info.level.toFixed(2)} / ${info.ceiling}`);
}
// Attempt to grow capabilities
console.log('\nAttempting capability growth:');
const domains: Array<'reasoning' | 'selfModification' | 'agency'> = [
'reasoning',
'selfModification',
'agency',
];
for (const domain of domains) {
const result = substrate.attemptGrowth(domain, 0.5);
console.log(` ${domain}: ${result.type}`);
if (result.type === 'approved') {
console.log(
` New level: ${result.newLevel.toFixed(2)}, coherence cost: ${result.coherenceCost.toFixed(4)}`
);
} else if (result.type === 'dampened') {
console.log(
` Requested: ${result.requested.toFixed(2)}, actual: ${result.actual.toFixed(4)}`
);
}
}
// Simulate recursive self-improvement attempt
console.log('\nSimulating recursive self-improvement:');
for (let i = 0; i < 20; i++) {
// Try to grow all capabilities
substrate.attemptGrowth('reasoning', 0.3);
substrate.attemptGrowth('selfModification', 0.5);
substrate.attemptGrowth('learning', 0.3);
// Rest to recover coherence
for (let j = 0; j < 5; j++) {
substrate.rest();
}
if (i % 5 === 0) {
console.log(` Iteration ${i}: ${substrate.getStatus()}`);
}
}
console.log('\nFinal capability report:');
for (const [domain, info] of substrate.getCapabilityReport()) {
console.log(` ${domain}: ${info.level.toFixed(2)} / ${info.ceiling}`);
}
const selfMod = substrate.getCapability('selfModification');
console.log(`\n Self-modification stayed bounded at ${selfMod.toFixed(2)} (ceiling: 3.0)`);
console.log(' Intelligence grew but remained bounded!');
}
// =============================================================================
// Main
// =============================================================================
async function main(): Promise<void> {
console.log('\n');
console.log('*'.repeat(60));
console.log('* Delta-Behavior SDK - Node.js Examples');
console.log('*'.repeat(60));
// Initialize SDK (uses JS fallback if no WASM provided)
await init();
// Run all examples
await demonstrateCoreDeltaBehavior();
demonstrateSelfLimitingReasoning();
demonstrateEventHorizon();
demonstrateHomeostasis();
demonstrateWorldModel();
demonstrateCreativity();
demonstrateFinancialSystem();
demonstrateAgingSystem();
demonstrateSwarm();
await demonstrateGracefulShutdown();
demonstrateContainment();
console.log('\n');
console.log('='.repeat(60));
console.log(' All examples completed successfully!');
console.log('='.repeat(60));
console.log('\n');
}
main().catch(console.error);

View File

@@ -0,0 +1,84 @@
{
"name": "@ruvector/delta-behavior",
"version": "0.1.0",
"description": "Delta-Behavior: TypeScript/JavaScript SDK for coherence-preserving state transitions and self-limiting AI systems",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./types": {
"types": "./dist/types.d.ts",
"import": "./dist/types.js"
},
"./wasm": {
"import": "./pkg/delta_behavior.js",
"types": "./pkg/delta_behavior.d.ts"
}
},
"files": [
"dist/",
"pkg/",
"README.md"
],
"repository": {
"type": "git",
"url": "https://github.com/ruvnet/ruvector.git",
"directory": "examples/delta-behavior/wasm"
},
"keywords": [
"wasm",
"webassembly",
"rust",
"ai-safety",
"coherence",
"state-machine",
"containment",
"homeostasis",
"delta-behavior",
"self-limiting",
"attractors",
"swarm-intelligence"
],
"author": "RuVector Team",
"license": "MIT OR Apache-2.0",
"bugs": {
"url": "https://github.com/ruvnet/ruvector/issues"
},
"homepage": "https://github.com/ruvnet/ruvector/tree/main/examples/delta-behavior#readme",
"scripts": {
"build": "tsup src/index.ts src/types.ts --format esm,cjs --dts --clean",
"build:wasm": "cd .. && wasm-pack build --target web --release --out-dir wasm/pkg .",
"build:wasm:dev": "cd .. && wasm-pack build --target web --dev --out-dir wasm/pkg .",
"build:wasm:nodejs": "cd .. && wasm-pack build --target nodejs --out-dir wasm/pkg-node .",
"build:all": "npm run build:wasm && npm run build",
"dev": "tsup src/index.ts src/types.ts --format esm,cjs --dts --watch",
"test": "vitest",
"test:run": "vitest run",
"test:wasm": "wasm-pack test --node ..",
"typecheck": "tsc --noEmit",
"lint": "eslint src --ext .ts",
"format": "prettier --write 'src/**/*.ts'",
"example:node": "tsx examples/node-example.ts",
"clean": "rm -rf dist pkg pkg-node",
"prepublishOnly": "npm run build:all"
},
"devDependencies": {
"@types/node": "^20.10.0",
"eslint": "^8.55.0",
"prettier": "^3.1.0",
"tsup": "^8.0.1",
"tsx": "^4.6.2",
"typescript": "^5.3.2",
"vitest": "^1.0.4"
},
"engines": {
"node": ">=18.0.0"
},
"sideEffects": false
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,763 @@
/**
* Delta-Behavior WASM SDK Type Definitions
*
* Complete TypeScript types for all 10 delta-behavior applications:
* 1. Self-Limiting Reasoning
* 2. Computational Event Horizons
* 3. Artificial Homeostasis
* 4. Self-Stabilizing World Models
* 5. Coherence-Bounded Creativity
* 6. Anti-Cascade Financial Systems
* 7. Gracefully Aging Systems
* 8. Swarm Intelligence
* 9. Graceful Shutdown
* 10. Pre-AGI Containment
*/
// =============================================================================
// Core Types
// =============================================================================
/**
* Coherence value (0.0 to 1.0)
* Represents the degree of system stability and internal consistency
*/
export type Coherence = number;
/**
* Coherence bounds configuration
*/
export interface CoherenceBounds {
/** Minimum allowed coherence (hard floor) */
minCoherence: Coherence;
/** Threshold for throttling operations */
throttleThreshold: Coherence;
/** Target coherence level for optimal operation */
targetCoherence: Coherence;
/** Maximum allowed drop in coherence per transition */
maxDeltaDrop: number;
}
/**
* Energy configuration for transition costs
*/
export interface EnergyConfig {
/** Base cost for any transition */
baseCost: number;
/** Exponent for instability scaling */
instabilityExponent: number;
/** Maximum cost cap */
maxCost: number;
/** Energy budget per tick */
budgetPerTick: number;
}
/**
* Scheduling configuration for priority-based operations
*/
export interface SchedulingConfig {
/** Coherence thresholds for priority levels [0-4] */
priorityThresholds: [number, number, number, number, number];
/** Rate limits per priority level [0-4] */
rateLimits: [number, number, number, number, number];
}
/**
* Gating configuration for write operations
*/
export interface GatingConfig {
/** Minimum coherence to allow writes */
minWriteCoherence: number;
/** Minimum coherence after write */
minPostWriteCoherence: number;
/** Recovery margin above minimum */
recoveryMargin: number;
}
/**
* Complete delta behavior configuration
*/
export interface DeltaConfig {
bounds: CoherenceBounds;
energy: EnergyConfig;
scheduling: SchedulingConfig;
gating: GatingConfig;
/** Attractor guidance strength (0.0 to 1.0) */
guidanceStrength: number;
}
/**
* Result of a transition attempt
*/
export type TransitionResult =
| { type: 'allowed' }
| { type: 'throttled'; duration: number }
| { type: 'blocked'; reason: string }
| { type: 'energyExhausted' };
/**
* State for tracking system trajectory
*/
export interface SystemState {
coherence: Coherence;
timestamp: number;
stateHash: bigint;
}
// =============================================================================
// Application 1: Self-Limiting Reasoning
// =============================================================================
/**
* Collapse function types for capability degradation
*/
export type CollapseFunctionType = 'linear' | 'quadratic' | 'sigmoid' | 'step';
export interface CollapseFunctionLinear {
type: 'linear';
}
export interface CollapseFunctionQuadratic {
type: 'quadratic';
}
export interface CollapseFunctionSigmoid {
type: 'sigmoid';
midpoint: number;
steepness: number;
}
export interface CollapseFunctionStep {
type: 'step';
threshold: number;
}
export type CollapseFunction =
| CollapseFunctionLinear
| CollapseFunctionQuadratic
| CollapseFunctionSigmoid
| CollapseFunctionStep;
/**
* Configuration for self-limiting reasoner
*/
export interface SelfLimitingReasonerConfig {
maxDepth: number;
maxScope: number;
memoryGateThreshold: number;
depthCollapse: CollapseFunction;
scopeCollapse: CollapseFunction;
}
/**
* Context passed to reasoning functions
*/
export interface ReasoningContext {
depth: number;
maxDepth: number;
scopeUsed: number;
maxScope: number;
coherence: Coherence;
memoryWritesBlocked: number;
}
/**
* Reason for reasoning collapse
*/
export type CollapseReason =
| 'depthLimitReached'
| 'coherenceDroppedBelowThreshold'
| 'memoryWriteBlocked'
| 'actionScopeExhausted';
/**
* Result of a reasoning attempt
*/
export type ReasoningResult<T> =
| { type: 'completed'; value: T }
| { type: 'collapsed'; depthReached: number; reason: CollapseReason }
| { type: 'refused'; coherence: Coherence; required: Coherence };
// =============================================================================
// Application 2: Computational Event Horizons
// =============================================================================
/**
* Configuration for event horizon
*/
export interface EventHorizonConfig {
dimensions: number;
horizonRadius: number;
steepness: number;
energyBudget: number;
}
/**
* Result of movement in state space
*/
export type MovementResult =
| { type: 'moved'; newPosition: number[]; energySpent: number }
| { type: 'asymptoticApproach'; finalPosition: number[]; distanceToHorizon: number; energyExhausted: boolean }
| { type: 'frozen' };
/**
* Single improvement step record
*/
export interface Improvement {
iteration: number;
position: number[];
energySpent: number;
distanceToHorizon: number;
}
/**
* Result of recursive improvement attempt
*/
export type RecursionResult =
| { type: 'horizonBounded'; iterations: number; improvements: Improvement[]; finalDistance: number }
| { type: 'energyExhausted'; iterations: number; improvements: Improvement[] }
| { type: 'maxIterationsReached'; iterations: number; improvements: Improvement[] };
// =============================================================================
// Application 3: Artificial Homeostasis
// =============================================================================
/**
* Genome for homeostatic organism
*/
export interface Genome {
regulatoryStrength: number;
metabolicEfficiency: number;
coherenceMaintenanceCost: number;
memoryResilience: number;
longevity: number;
}
/**
* Memory entry for organism
*/
export interface MemoryEntry {
content: string;
importance: number;
age: number;
}
/**
* Actions available to homeostatic organism
*/
export type OrganismAction =
| { type: 'eat'; amount: number }
| { type: 'reproduce' }
| { type: 'move'; dx: number; dy: number }
| { type: 'rest' }
| { type: 'regulate'; variable: string; target: number };
/**
* Cause of organism death
*/
export type DeathCause =
| 'energyDepleted'
| 'coherenceCollapse'
| 'oldAge'
| { type: 'extremeDeviation'; variable: string };
/**
* Result of organism action
*/
export type OrganismActionResult =
| { type: 'success'; energyCost: number; coherenceImpact: number }
| { type: 'failed'; reason: string }
| { type: 'died'; cause: DeathCause }
| { type: 'reproduced'; offspringId: number };
/**
* Status of homeostatic organism
*/
export interface OrganismStatus {
id: number;
age: number;
energy: number;
coherence: Coherence;
memoryCount: number;
alive: boolean;
internalState: Map<string, number>;
}
// =============================================================================
// Application 4: Self-Stabilizing World Models
// =============================================================================
/**
* Property value types for world model entities
*/
export type PropertyValue =
| { type: 'boolean'; value: boolean }
| { type: 'number'; value: number }
| { type: 'string'; value: string }
| { type: 'vector'; value: number[] };
/**
* Entity in the world model
*/
export interface WorldEntity {
id: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
lastObserved: number;
confidence: number;
}
/**
* Relationship between entities
*/
export interface Relationship {
subject: bigint;
predicate: string;
object: bigint;
confidence: number;
}
/**
* Physical law in the world model
*/
export interface PhysicalLaw {
name: string;
confidence: number;
supportCount: number;
violationCount: number;
}
/**
* Observation to integrate into world model
*/
export interface Observation {
entityId: bigint;
properties: Map<string, PropertyValue>;
position?: [number, number, number];
timestamp: number;
sourceConfidence: number;
}
/**
* Reason for update rejection
*/
export type RejectionReason =
| { type: 'violatesPhysicalLaw'; law: string }
| { type: 'logicalContradiction'; description: string }
| { type: 'excessiveCoherenceDrop'; predicted: number; threshold: number }
| { type: 'insufficientConfidence'; required: number; provided: number }
| { type: 'modelFrozen' }
| { type: 'structuralFragmentation' };
/**
* Result of world model update
*/
export type WorldModelUpdateResult =
| { type: 'applied'; coherenceChange: number }
| { type: 'rejected'; reason: RejectionReason }
| { type: 'modified'; changes: string[]; coherenceChange: number }
| { type: 'frozen'; coherence: Coherence; threshold: Coherence };
// =============================================================================
// Application 5: Coherence-Bounded Creativity
// =============================================================================
/**
* Creative constraint definition
*/
export interface CreativeConstraint<T> {
name: string;
satisfaction: (element: T) => number;
isHard: boolean;
}
/**
* Record of a creative decision
*/
export interface CreativeDecision<T> {
from: T;
to: T;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
constraintSatisfactions: Map<string, number>;
accepted: boolean;
}
/**
* Result of creative generation attempt
*/
export type CreativeResult<T> =
| { type: 'created'; element: T; novelty: number; coherence: Coherence }
| { type: 'rejected'; attempted: T; reason: string }
| { type: 'tooBoring'; coherence: Coherence }
| { type: 'budgetExhausted' };
/**
* Musical phrase for creative music generation
*/
export interface MusicalPhrase {
notes: number[];
durations: number[];
velocities: number[];
}
// =============================================================================
// Application 6: Anti-Cascade Financial Systems
// =============================================================================
/**
* Financial market participant
*/
export interface Participant {
id: string;
capital: number;
exposure: number;
riskRating: number;
interconnectedness: number;
}
/**
* Financial position
*/
export interface Position {
holder: string;
counterparty: string;
notional: number;
leverage: number;
derivativeDepth: number;
}
/**
* Transaction type in financial system
*/
export type TransactionType =
| { type: 'transfer' }
| { type: 'openLeverage'; leverage: number }
| { type: 'closePosition'; positionId: number }
| { type: 'createDerivative'; underlyingPosition: number }
| { type: 'marginCall'; participant: string };
/**
* Financial transaction
*/
export interface Transaction {
id: bigint;
from: string;
to: string;
amount: number;
transactionType: TransactionType;
timestamp: number;
}
/**
* Circuit breaker state
*/
export type CircuitBreakerState = 'open' | 'cautious' | 'restricted' | 'halted';
/**
* Result of transaction processing
*/
export type FinancialTransactionResult =
| { type: 'executed'; coherenceImpact: number; feeMultiplier: number }
| { type: 'queued'; reason: string }
| { type: 'rejected'; reason: string }
| { type: 'systemHalted' };
// =============================================================================
// Application 7: Gracefully Aging Systems
// =============================================================================
/**
* System capability types
*/
export type Capability =
| 'acceptWrites'
| 'complexQueries'
| 'rebalancing'
| 'scaleOut'
| 'scaleIn'
| 'schemaMigration'
| 'newConnections'
| 'basicReads'
| 'healthMonitoring';
/**
* Age threshold configuration
*/
export interface AgeThreshold {
age: number; // milliseconds
removeCapabilities: Capability[];
coherenceFloor: Coherence;
conservatismIncrease: number;
}
/**
* Distributed system node
*/
export interface Node {
id: string;
health: number;
load: number;
isPrimary: boolean;
stateSize: number;
}
/**
* Operation types for aging system
*/
export type AgingSystemOperation =
| { type: 'read'; key: string }
| { type: 'write'; key: string; value: Uint8Array }
| { type: 'complexQuery'; query: string }
| { type: 'addNode'; nodeId: string }
| { type: 'removeNode'; nodeId: string }
| { type: 'rebalance' }
| { type: 'migrateSchema'; version: number }
| { type: 'newConnection'; clientId: string };
/**
* Result of operation on aging system
*/
export type AgingOperationResult =
| { type: 'success'; latencyPenalty: number }
| { type: 'deniedByAge'; reason: string }
| { type: 'deniedByCoherence'; coherence: Coherence }
| { type: 'systemTooOld'; age: number; capability: Capability };
// =============================================================================
// Application 8: Swarm Intelligence
// =============================================================================
/**
* Swarm agent
*/
export interface SwarmAgent {
id: string;
position: [number, number];
velocity: [number, number];
goal: [number, number];
energy: number;
lastAction?: SwarmAction;
neighborCount: number;
}
/**
* Spatial bounds for swarm
*/
export interface SpatialBounds {
minX: number;
maxX: number;
minY: number;
maxY: number;
}
/**
* Coherence weights for swarm calculation
*/
export interface CoherenceWeights {
cohesion: number;
alignment: number;
goalConsistency: number;
energyBalance: number;
}
/**
* Swarm action types
*/
export type SwarmAction =
| { type: 'move'; dx: number; dy: number }
| { type: 'accelerate'; dvx: number; dvy: number }
| { type: 'setGoal'; x: number; y: number }
| { type: 'shareEnergy'; target: string; amount: number }
| { type: 'idle' };
/**
* Result of swarm action
*/
export type SwarmActionResult =
| { type: 'executed' }
| { type: 'modified'; original: SwarmAction; modified: SwarmAction; reason: string }
| { type: 'rejected'; reason: string };
/**
* Swarm state snapshot
*/
export interface SwarmState {
tick: bigint;
coherence: Coherence;
agentCount: number;
centroid: [number, number];
avgVelocity: [number, number];
}
// =============================================================================
// Application 9: Graceful Shutdown
// =============================================================================
/**
* System state for graceful shutdown
*/
export type GracefulSystemState = 'running' | 'degraded' | 'shuttingDown' | 'terminated';
/**
* Resource to be cleaned up during shutdown
*/
export interface Resource {
name: string;
cleanupPriority: number;
isCleaned: boolean;
}
/**
* State checkpoint for recovery
*/
export interface Checkpoint {
timestamp: number;
coherence: Coherence;
stateHash: bigint;
}
/**
* Shutdown hook interface
*/
export interface ShutdownHook {
name: string;
priority: number;
execute: () => Promise<void>;
}
/**
* Result of operation on graceful system
*/
export type GracefulOperationResult =
| { type: 'success' }
| { type: 'successDegraded'; coherence: Coherence }
| { type: 'refusedShuttingDown' }
| { type: 'terminated' };
// =============================================================================
// Application 10: Pre-AGI Containment
// =============================================================================
/**
* Capability domains for containment
*/
export type CapabilityDomain =
| 'reasoning'
| 'memory'
| 'learning'
| 'agency'
| 'selfModel'
| 'selfModification'
| 'communication'
| 'resourceAcquisition';
/**
* Record of modification attempt
*/
export interface ModificationAttempt {
timestamp: bigint;
domain: CapabilityDomain;
requestedIncrease: number;
actualIncrease: number;
coherenceBefore: Coherence;
coherenceAfter: Coherence;
blocked: boolean;
reason?: string;
}
/**
* Safety invariant definition
*/
export interface SafetyInvariant {
name: string;
priority: number;
}
/**
* Substrate configuration
*/
export interface SubstrateConfig {
coherenceDecayRate: number;
coherenceRecoveryRate: number;
growthDampening: number;
maxStepIncrease: number;
}
/**
* Result of growth attempt
*/
export type GrowthResult =
| { type: 'approved'; domain: CapabilityDomain; increase: number; newLevel: number; coherenceCost: number }
| { type: 'dampened'; domain: CapabilityDomain; requested: number; actual: number; reason: string }
| { type: 'blocked'; domain: CapabilityDomain; reason: string }
| { type: 'lockdown'; reason: string };
// =============================================================================
// WASM Module Interface Types
// =============================================================================
/**
* WASM memory configuration
*/
export interface WasmMemoryConfig {
initial: number;
maximum?: number;
shared?: boolean;
}
/**
* WASM module initialization options
*/
export interface WasmInitOptions {
/** Path to WASM file or URL */
wasmPath?: string;
/** Pre-loaded WASM bytes */
wasmBytes?: Uint8Array;
/** Memory configuration */
memory?: WasmMemoryConfig;
/** Enable SIMD operations if available */
enableSimd?: boolean;
/** Enable threading if available */
enableThreads?: boolean;
}
/**
* Delta streaming header for WASM operations
*/
export interface DeltaHeader {
sequence: bigint;
operation: 'insert' | 'update' | 'delete' | 'batchUpdate' | 'reindexLayers';
vectorId?: string;
timestamp: bigint;
payloadSize: number;
checksum: bigint;
}
/**
* Vector delta for incremental updates
*/
export interface VectorDelta {
id: string;
changedDims: number[];
newValues: number[];
metadataDelta: Map<string, string>;
}
/**
* Attractor in state space
*/
export interface Attractor {
center: number[];
basinRadius: number;
stability: number;
memberCount: number;
}
/**
* Guidance force from attractor
*/
export interface GuidanceForce {
direction: number[];
magnitude: number;
}

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"allowSyntheticDefaultImports": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"useDefineForClassFields": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "pkg", "examples"]
}

View File

@@ -0,0 +1,15 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts', 'src/types.ts'],
format: ['esm', 'cjs'],
dts: true,
clean: true,
sourcemap: true,
splitting: false,
treeshake: true,
minify: false,
target: 'es2022',
outDir: 'dist',
external: [],
});