Skip to main content

aura_core/effects/
mod.rs

1//! Layer 1: Core Effect Trait Definitions
2//!
3//! Pure trait definitions for all side-effect operations in Aura.
4//! This module defines **what** effects can be performed; handlers define **how**.
5//! (per docs/103_effect_system.md)
6//!
7//! # Effect Classification
8//!
9//! Effects are organized into four categories based on where they should be implemented:
10//!
11//! ## Infrastructure Effects (Layer 3: `aura-effects`)
12//! OS integration with no Aura-specific semantics:
13//! - **Time**, **Crypto**, **Network**, **Storage**, **Random**, **Console**, **Transport**
14//! - **Biometric**, **Bloom**, **Reliability**, **Secure**, **System**
15//!
16//! ## Application Effects (Layer 2-4: Domain crates)
17//! Aura-specific business logic:
18//! - **Journal** (`aura-journal`), **Authorization**, **Capability** (`aura-authorization`)
19//! - **Agent** (`aura-agent`), **Authority** (`aura-protocol`/`aura-relational`)
20//! - **Guard** (`aura-protocol::guards`), **Ledger** (`aura-journal`/`aura-protocol`)
21//!
22//! ## Protocol Coordination Effects (Layer 4: `aura-protocol`)
23//! Multi-party protocol coordination:
24//! - **Choreographic** (`aura-protocol::choreography`)
25//! - **Sync** (`aura-sync` or `aura-protocol`)
26//!
27//! ## Testing/Simulation Effects (Layer 8: Test infrastructure)
28//! Testing and verification:
29//! - **Chaos**, **Simulation**, **Testing** (`aura-simulator`, `aura-testkit`)
30//! - **Quint** (`aura-quint`)
31//!
32//! ## Composite Effects (Layer 1: `aura-core`)
33//! Convenience supertraits combining other effects (no handlers needed)
34//!
35//! **Execution Modes** (per ExecutionMode enum):
36//! - **Testing**: Mock implementations, deterministic behavior
37//! - **Production**: Real system operations
38//! - **Simulation**: Deterministic with controllable effects (seed-driven)
39//!
40//! All effect-using code is parameterized by effect traits, enabling:
41//! Deterministic testing, flexible handler composition, runtime mode switching (per docs/103_effect_system.md)
42
43// Core effect trait definitions
44pub mod agent;
45pub mod amp;
46pub mod authority;
47pub mod authorization;
48pub mod availability; // Data availability within replication units
49pub mod biometric;
50pub mod bloom;
51pub mod capability;
52pub mod choreographic; // Multi-party protocol coordination
53pub mod console;
54pub mod crypto;
55pub mod fact; // Temporal database mutations (write side of journal)
56pub mod flood; // Rendezvous flooding for discovery
57pub mod flow; // Flow budget management
58pub mod guard; // Pure guard evaluation with effect commands
59pub mod guardian; // Guardian relational coordination
60pub mod indexed; // Indexed journal lookups (B-tree, Bloom, Merkle)
61pub mod intent; // Intent dispatch effects
62pub mod journal;
63pub mod leakage; // Privacy leakage tracking
64pub mod ledger; // Event sourcing and audit trails
65pub mod network;
66pub mod noise;
67pub mod query; // Datalog query effects (bridges Journal + Biscuit + Reactive)
68pub mod random;
69pub mod reactive; // FRP as algebraic effects
70pub mod registry; // Canonical operation mappings
71pub mod relay; // Relay selection for message forwarding
72pub mod reliability;
73pub mod route_crypto;
74pub mod runtime_capability; // Runtime theorem-pack capability admission
75pub mod secure;
76pub mod storage;
77pub mod supertraits;
78pub mod sync; // Anti-entropy synchronization
79pub mod system;
80pub mod task;
81pub mod terminal; // Terminal I/O for deterministic TUI/CLI testing
82pub mod threshold; // Unified threshold signing
83pub mod time;
84pub mod trace;
85pub mod transport;
86pub mod tree; // Commitment tree operations
87pub mod vm_bridge; // Session-local sync bridge state for VM host callbacks
88
89// Simulation/testing effect traits (feature-gated)
90cfg_if::cfg_if! {
91    if #[cfg(feature = "simulation")] {
92        pub mod chaos;
93        pub mod quint;
94        pub mod simulation;
95        pub mod testing;
96    }
97}
98
99// Re-export core effect traits
100pub use agent::{
101    AgentEffects, AgentHealthStatus, AuthMethod, AuthenticationEffects, AuthenticationResult,
102    ConfigError, ConfigValidationError, ConfigurationEffects, CredentialBackup, DeviceConfig,
103    DeviceInfo, DeviceStorageEffects, HealthStatus, SessionHandle, SessionInfo,
104    SessionManagementEffects, SessionMessage, SessionRole, SessionStatus, SessionType,
105};
106pub use amp::{
107    AmpChannelEffects, AmpChannelError, AmpCiphertext, AmpHeader, ChannelCloseParams,
108    ChannelCreateParams, ChannelJoinParams, ChannelLeaveParams, ChannelSendParams,
109};
110pub use authority::{AuthorityEffects, AuthorityRelationalEffects, RelationalEffects};
111pub use authorization::{
112    AuthorizationDecision, AuthorizationEffects, AuthorizationError, BiscuitAuthorizationEffects,
113};
114pub use availability::{AvailabilityError, DataAvailability};
115pub use biometric::{
116    BiometricCapability, BiometricConfig, BiometricEffects, BiometricEnrollmentResult,
117    BiometricError, BiometricSecurityLevel, BiometricStatistics, BiometricType,
118    BiometricVerificationResult,
119};
120pub use bloom::{BloomConfig, BloomError, BloomFilter};
121pub use capability::{
122    CapabilityConfig, CapabilityEffects, CapabilityError, CapabilityStatistics,
123    CapabilityTokenFormat, CapabilityTokenInfo, CapabilityTokenRequest,
124    CapabilityVerificationResult, TokenStatus, VerificationLevel,
125};
126#[cfg(feature = "simulation")]
127pub use chaos::{ByzantineType, ChaosEffects, ChaosError, CorruptionType, ResourceType};
128pub use console::ConsoleEffects;
129pub use crypto::{CryptoCoreEffects, CryptoEffects, CryptoError, CryptoExtendedEffects};
130pub use fact::{CheckpointInfo, FactEffects, FactError, TemporalFact};
131pub use flood::{
132    FloodAction, FloodBudget, FloodError, LayeredBudget, RendezvousFlooder, RendezvousPacket,
133};
134pub use flow::{FlowBudgetEffects, FlowHint};
135pub use guardian::{GuardianAcceptInput, GuardianEffects, GuardianRequestInput};
136pub use indexed::{FactId, IndexStats, IndexedFact, IndexedJournalEffects};
137pub use intent::{
138    AuthorizationLevel, IntentDispatchError, IntentEffects, IntentMetadata, SimpleIntentEffects,
139};
140pub use journal::JournalEffects;
141pub use leakage::{
142    LeakageBudget, LeakageChoreographyExt, LeakageEffects, LeakageEvent, ObserverClass,
143};
144#[allow(deprecated)]
145// Migration utilities removed - middleware transition complete
146pub use network::{
147    NetworkAddress, NetworkChange, NetworkChangeEffects, NetworkChangeStream, NetworkCoreEffects,
148    NetworkEffects, NetworkError, NetworkExtendedEffects, NetworkUsability, PeerEvent,
149    PeerEventStream, UdpEffects, UdpEndpoint, UdpEndpointEffects,
150};
151pub use noise::{HandshakeState, NoiseEffects, NoiseError, NoiseParams, TransportState};
152pub use query::{QueryEffects, QueryError, QuerySubscription};
153#[cfg(feature = "simulation")]
154pub use quint::{
155    // Generative simulation types
156    ActionDescriptor,
157    ActionEffect,
158    ActionResult,
159    // Core verification types
160    Counterexample,
161    EvaluationResult,
162    EvaluationStatistics,
163    Property,
164    PropertyEvaluator,
165    PropertyId,
166    PropertyKind,
167    PropertySpec,
168    QuintEvaluationEffects,
169    QuintMappable,
170    QuintSimulationEffects,
171    QuintStateExtractable,
172    QuintVerificationEffects,
173    VerificationId,
174    VerificationResult,
175};
176pub use random::{RandomCoreEffects, RandomEffects, RandomExtendedEffects};
177pub use reactive::{
178    ReactiveDeriveEffects, ReactiveEffects, ReactiveError, Signal, SignalId, SignalStream,
179};
180pub use relay::{RelayCandidate, RelayContext, RelayError, RelayRelationship, RelaySelector};
181pub use reliability::{
182    // Unified retry types
183    AdaptiveMode,
184    BackoffStrategy,
185    JitterMode,
186    RateLimit,
187    // Unified rate limiting types
188    RateLimitConfig,
189    RateLimitResult,
190    RateLimiter,
191    RateLimiterStatistics,
192    ReliabilityEffects,
193    ReliabilityError,
194    RetryContext,
195    RetryPolicy,
196    RetryResult,
197};
198pub use route_crypto::{RouteCryptoEffects, RouteCryptoError, RouteHopKeyMaterial};
199pub use runtime_capability::{AdmissionError, CapabilityKey, RuntimeCapabilityEffects};
200pub use secure::{
201    SecureStorageCapability, SecureStorageEffects, SecureStorageError, SecureStorageLocation,
202};
203#[cfg(feature = "simulation")]
204pub use simulation::{
205    ByzantineFault, CheckpointId, ComputationFault, ExportFormat, FaultInjectionConfig,
206    FaultInjectionEffects, FaultType, NetworkFault, OperationStats, RuntimeEffectsBundle,
207    ScenarioId, ScenarioState, SimulationCheckpoint, SimulationControlEffects, SimulationEffects,
208    SimulationEnvironmentConfig, SimulationEnvironmentError, SimulationEnvironmentFactory,
209    SimulationMetrics, SimulationObservationEffects, SimulationScenario, SimulationTime,
210    StorageFault, TimeFault,
211};
212pub use storage::{
213    StorageCoreEffects, StorageEffects, StorageError, StorageExtendedEffects, StorageLocation,
214    StorageStats,
215};
216pub use supertraits::{
217    AntiEntropyEffects, ChoreographyEffects, CrdtEffects, MinimalEffects, SigningEffects,
218    SnapshotEffects, TreeEffects,
219};
220pub use system::{SystemEffects, SystemError};
221pub use terminal::{
222    Cell, Color, CursorPosition, CursorShape, KeyCode, KeyEvent, KeyEventKind, Modifiers,
223    MouseButton, MouseEvent, MouseEventKind, Style, TerminalEffects, TerminalError, TerminalEvent,
224    TerminalFrame, TerminalInputEffects, TerminalOutputEffects,
225};
226#[cfg(feature = "simulation")]
227pub use testing::{TestingEffects, TestingError};
228pub use time::{
229    LogicalClockEffects, OrderClockEffects, PhysicalTimeEffects, TimeComparison, TimeEffects,
230    TimeError, TimeoutHandle, WakeCondition,
231};
232pub use trace::{TraceEffects, TraceEvent, TraceSpanId};
233pub use transport::{
234    TransportEffects, TransportEnvelope, TransportError, TransportReceipt, TransportStats,
235};
236pub use vm_bridge::{
237    VmBridgeBlockedEdge, VmBridgeEffects, VmBridgeLeaseMetadataSnapshot, VmBridgePendingSend,
238    VmBridgeSchedulerSignals, VmBridgeTransferMetadataSnapshot,
239};
240
241// Re-export protocol coordination effect traits
242pub use choreographic::{
243    ChoreographicEffects, ChoreographicRole, ChoreographyError, ChoreographyEvent,
244    ChoreographyMetrics,
245};
246pub use guard::{
247    Decision, EffectCommand, EffectInterpreter, FlowBudgetView, GuardOutcome, GuardSnapshot,
248    JournalEntry, MetadataView, SimulationEvent,
249};
250pub use ledger::{EffectApiEffects, EffectApiError, EffectApiEvent, EffectApiEventStream};
251pub use sync::SyncMetrics;
252pub use threshold::{PublicKeyPackage, ThresholdSigningEffects, ThresholdSigningError};
253pub use tree::{Cut, Partial, ProposalId, Snapshot, TreeOperationEffects};
254
255// Re-export unified error system
256pub use crate::AuraError;
257
258/// Execution mode controlling effect handler selection across all system layers
259///
260/// This enum controls which implementations of effect handlers are used throughout
261/// the entire Aura system, from testing to production deployments.
262#[derive(
263    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
264)]
265pub enum ExecutionMode {
266    /// Testing mode: Mock implementations, deterministic behavior
267    #[default]
268    Testing,
269    /// Production mode: Real implementations, actual system operations
270    Production,
271    /// Simulation mode: Deterministic implementations with controllable effects
272    Simulation {
273        /// Random seed for deterministic simulation
274        seed: u64,
275    },
276}
277
278impl ExecutionMode {
279    /// Check if this mode uses deterministic effects
280    pub fn is_deterministic(&self) -> bool {
281        matches!(self, Self::Testing | Self::Simulation { .. })
282    }
283
284    /// Check if this mode uses real system operations
285    pub fn is_production(&self) -> bool {
286        matches!(self, Self::Production)
287    }
288
289    /// Get the seed for deterministic modes
290    pub fn seed(&self) -> Option<u64> {
291        match self {
292            Self::Simulation { seed } => Some(*seed),
293            _ => None,
294        }
295    }
296}
297
298/// Effect type enumeration for all effects in the Aura system
299///
300/// Categorizes all effects in the Aura system for efficient dispatch
301/// and middleware composition.
302#[derive(
303    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
304)]
305pub enum EffectType {
306    /// Cryptographic operations (FROST, DKD, hashing, key derivation)
307    Crypto,
308    /// Network communication (send, receive, broadcast)
309    Network,
310    /// Persistent storage operations
311    Storage,
312    /// Time-related operations (current time, sleep)
313    Time,
314    /// Console and logging operations
315    Console,
316    /// Random number generation
317    Random,
318    /// Reactive state management (FRP signals)
319    Reactive,
320    /// Intent dispatch (user action processing)
321    Intent,
322    /// Effect API operations (transaction log, state)
323    EffectApi,
324    /// Journal operations (event log, snapshots)
325    Journal,
326    /// Fact operations (temporal database mutations)
327    Fact,
328    /// Tree operations (commitment tree, MLS)
329    Tree,
330    /// Choreographic protocol coordination
331    Choreographic,
332    /// System monitoring, logging, and configuration
333    System,
334    /// Structured tracing and instrumentation
335    Trace,
336    /// Device-local storage
337    DeviceStorage,
338    /// Device authentication and sessions
339    Authentication,
340    /// Configuration management
341    Configuration,
342    /// Session lifecycle management
343    SessionManagement,
344    /// Fault injection for testing
345    FaultInjection,
346    /// Time control for simulation
347    TimeControl,
348    /// State inspection for debugging
349    StateInspection,
350    /// Property checking for verification
351    PropertyChecking,
352    /// Chaos coordination for resilience testing
353    ChaosCoordination,
354    /// Datalog query execution and subscriptions
355    Query,
356    /// Terminal I/O for TUI/CLI
357    Terminal,
358}
359
360impl std::fmt::Display for EffectType {
361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362        match self {
363            Self::Crypto => write!(f, "crypto"),
364            Self::Network => write!(f, "network"),
365            Self::Storage => write!(f, "storage"),
366            Self::Time => write!(f, "time"),
367            Self::Console => write!(f, "console"),
368            Self::Random => write!(f, "random"),
369            Self::Reactive => write!(f, "reactive"),
370            Self::Intent => write!(f, "intent"),
371            Self::EffectApi => write!(f, "effect_api"),
372            Self::Journal => write!(f, "journal"),
373            Self::Fact => write!(f, "fact"),
374            Self::Tree => write!(f, "tree"),
375            Self::Choreographic => write!(f, "choreographic"),
376            Self::System => write!(f, "system"),
377            Self::Trace => write!(f, "trace"),
378            Self::DeviceStorage => write!(f, "device_storage"),
379            Self::Authentication => write!(f, "authentication"),
380            Self::Configuration => write!(f, "configuration"),
381            Self::SessionManagement => write!(f, "session_management"),
382            Self::FaultInjection => write!(f, "fault_injection"),
383            Self::TimeControl => write!(f, "time_control"),
384            Self::StateInspection => write!(f, "state_inspection"),
385            Self::PropertyChecking => write!(f, "property_checking"),
386            Self::ChaosCoordination => write!(f, "chaos_coordination"),
387            Self::Query => write!(f, "query"),
388            Self::Terminal => write!(f, "terminal"),
389        }
390    }
391}
392
393impl EffectType {
394    /// Get all effect types
395    pub fn all() -> Vec<Self> {
396        vec![
397            Self::Crypto,
398            Self::Network,
399            Self::Storage,
400            Self::Time,
401            Self::Console,
402            Self::Random,
403            Self::Reactive,
404            Self::Intent,
405            Self::EffectApi,
406            Self::Journal,
407            Self::Fact,
408            Self::Tree,
409            Self::Choreographic,
410            Self::System,
411            Self::Trace,
412            Self::DeviceStorage,
413            Self::Authentication,
414            Self::Configuration,
415            Self::SessionManagement,
416            Self::FaultInjection,
417            Self::TimeControl,
418            Self::StateInspection,
419            Self::PropertyChecking,
420            Self::ChaosCoordination,
421            Self::Query,
422            Self::Terminal,
423        ]
424    }
425}