Skip to main content

aura_agent/
lib.rs

1//! # Aura Agent - Layer 6: Runtime Composition
2//!
3//! This crate provides runtime composition and effect system assembly for authority-based
4//! identity management in the Aura threshold identity platform.
5//!
6//! ## Purpose
7//!
8//! Layer 6 runtime composition crate providing:
9//! - Authority-first runtime assembly and lifecycle management
10//! - Effect registry and builder infrastructure
11//! - Context management for multi-threaded agent coordination
12//! - Choreography adapter for protocol execution
13//! - Production, testing, and simulation execution modes
14//!
15//! ## Architecture Constraints
16
17#![allow(clippy::uninlined_format_args)] // Runtime code uses explicit format args for clarity
18#![allow(clippy::redundant_clone)] // Some clones needed for async context propagation
19#![allow(missing_docs)] // Runtime API documentation evolving with design
20//!
21//! This crate depends on:
22//! - **Layer 1-5**: All lower layers (core, domain crates, effects, protocols, features)
23//! - **MUST NOT**: Create new effect implementations (use aura-effects)
24//! - **MUST NOT**: Implement multi-party coordination (use aura-protocol)
25//! - **MUST NOT**: Be imported by Layer 1-5 crates (no circular dependencies)
26//!
27//! ## What Belongs Here
28//!
29//! - Effect registry and builder infrastructure
30//! - Runtime system composition and lifecycle
31//! - Authority context management and tracking
32//! - Execution mode implementation (production, testing, simulation)
33//! - Choreography protocol adapter for protocol execution
34//! - Receipt and flow budget management
35//! - Public API for agent creation and operation
36//!
37//! ## What Does NOT Belong Here
38//!
39//! - Effect handler implementations (belong in aura-effects)
40//! - Effect composition rules (belong in aura-composition)
41//! - Multi-party protocol logic (belong in aura-protocol)
42//! - Feature protocol implementations (belong in Layer 5 crates)
43//! - Testing harnesses and fixtures (belong in aura-testkit)
44//!
45#![warn(clippy::await_holding_lock)]
46//! ## Design Principles
47//!
48//! - Authority-first design: all operations scoped to specific authorities
49//! - Lazy composition: effects are assembled on-demand, not eagerly
50//! - Stateless handlers: runtime delegates state to journals and contexts
51//! - Mode-aware execution: production, testing, and simulation use same API
52//! - Lifecycle management: resource cleanup and graceful shutdown
53//! - Zero coupling to Layer 5: runtime is agnostic to specific protocols
54//!
55//! ## Key Components
56//!
57//! - **AgentBuilder**: Fluent API for composing agents with authority context
58//! - **EffectRegistry**: Dynamic registry of available effect handlers
59//! - **EffectSystemBuilder**: Assembly infrastructure for effect combinations
60//! - **AuraAgent**: Public API for agent operations
61//! - **RuntimeSystem**: Internal runtime coordination
62#![allow(unexpected_cfgs)]
63//!
64//! ## Usage
65//!
66//! ```rust,ignore
67//! use aura_agent::{AgentBuilder, AuthorityId};
68//!
69//! // Production agent with authority-first design
70//! let agent = AgentBuilder::new()
71//!     .with_authority(authority_id)
72//!     .build_production()
73//!     .await?;
74//!
75//! // Testing agent
76//! let agent = AgentBuilder::new()
77//!     .with_authority(authority_id)
78//!     .build_testing()?;
79//! ```
80
81#![allow(clippy::expect_used)]
82
83#[cfg(not(feature = "choreo-backend-telltale-machine"))]
84compile_error!(
85    "Aura agent requires the Telltale choreography backend. \
86     Enable feature `choreo-backend-telltale-machine`."
87);
88
89#[cfg(all(feature = "transparent_onion", not(any(test, debug_assertions))))]
90compile_error!(
91    "Feature `transparent_onion` is a debug/test/simulation-only tool and must \
92     not be enabled in release production builds."
93);
94
95// Core modules (public API)
96#[cfg(feature = "choreo-backend-telltale-machine")]
97pub mod core;
98
99// Builder system for ergonomic runtime construction
100#[cfg(feature = "choreo-backend-telltale-machine")]
101pub mod builder;
102
103// Runtime modules (internal)
104#[cfg(feature = "choreo-backend-telltale-machine")]
105mod runtime;
106#[cfg(feature = "choreo-backend-telltale-machine")]
107mod task_registry;
108#[cfg(feature = "choreo-backend-telltale-machine")]
109mod token_profiles;
110
111// Handler modules (public for service access)
112#[cfg(feature = "choreo-backend-telltale-machine")]
113pub mod adaptive_privacy_control;
114#[cfg(feature = "choreo-backend-telltale-machine")]
115pub mod handlers;
116#[cfg(feature = "choreo-backend-telltale-machine")]
117mod reconfiguration;
118
119// Runtime-owned indexed journal utilities (stateful)
120#[cfg(feature = "choreo-backend-telltale-machine")]
121pub mod database;
122
123// Reactive programming infrastructure (public)
124#[cfg(feature = "choreo-backend-telltale-machine")]
125pub mod reactive;
126
127// RuntimeBridge implementation (for aura-app dependency inversion)
128#[cfg(feature = "choreo-backend-telltale-machine")]
129mod runtime_bridge;
130#[cfg(test)]
131mod testing;
132
133// Journal fact registry helpers (public helper functions)
134#[cfg(feature = "choreo-backend-telltale-machine")]
135pub mod fact_registry;
136#[cfg(feature = "choreo-backend-telltale-machine")]
137pub mod fact_types;
138
139// Public API - authority-first design
140#[cfg(feature = "choreo-backend-telltale-machine")]
141pub use core::{AgentBuilder, AgentConfig, AgentError, AgentResult, AuraAgent, AuthorityContext};
142
143// Builder system exports
144#[cfg(all(feature = "android", feature = "choreo-backend-telltale-machine"))]
145pub use builder::AndroidPresetBuilder;
146#[cfg(all(feature = "web", feature = "choreo-backend-telltale-machine"))]
147pub use builder::WebPresetBuilder;
148#[cfg(feature = "choreo-backend-telltale-machine")]
149pub use builder::{BuildError, CliPresetBuilder, CustomPresetBuilder};
150#[cfg(all(feature = "ios", feature = "choreo-backend-telltale-machine"))]
151pub use builder::{DataProtectionClass, IosPresetBuilder};
152
153// Session management types
154#[cfg(feature = "choreo-backend-telltale-machine")]
155pub use handlers::{SessionHandle, SessionServiceApi, SessionStats};
156
157// Authentication types
158#[cfg(feature = "choreo-backend-telltale-machine")]
159pub use handlers::{
160    AuthChallenge, AuthMethod, AuthResponse, AuthResult, AuthServiceApi, AuthenticationStatus,
161};
162
163// Invitation types
164#[cfg(feature = "choreo-backend-telltale-machine")]
165pub use handlers::{
166    Invitation, InvitationResult, InvitationServiceApi, InvitationStatus, InvitationType,
167};
168
169// Recovery types
170#[cfg(feature = "choreo-backend-telltale-machine")]
171pub use handlers::{
172    GuardianApproval, RecoveryOperation, RecoveryRequest, RecoveryResult, RecoveryServiceApi,
173    RecoveryState,
174};
175
176// Rendezvous types
177#[cfg(feature = "choreo-backend-telltale-machine")]
178pub use handlers::{ChannelResult, RendezvousHandler, RendezvousResult, RendezvousServiceApi};
179
180// Runtime types for advanced usage
181#[cfg(feature = "choreo-backend-telltale-machine")]
182pub use runtime::system::RuntimeShutdownError;
183#[cfg(all(
184    feature = "choreo-backend-telltale-machine",
185    not(target_arch = "wasm32")
186))]
187pub use runtime::AuraHandlerAdapter;
188#[cfg(feature = "choreo-backend-telltale-machine")]
189pub use runtime::{
190    EffectContext, EffectExecutor, EffectOperation, EffectRegistry, EffectRegistryError,
191    EffectRegistryExt, EffectSystemBuilder, EffectType, FlowBudgetManager, LifecycleManager,
192    OperationSessionId, ReceiptManager, RuntimeChoreographySessionId, RuntimeService,
193    RuntimeServiceContext, ServiceError, ServiceErrorKind, ServiceHealth, SharedTransport,
194    TaskSupervisor,
195};
196
197// Protocol adapter for choreography execution (used by tests)
198#[cfg(feature = "choreo-backend-telltale-machine")]
199pub use runtime::choreo_engine::{AuraChoreoEngine, AuraChoreoEngineError};
200#[cfg(all(
201    feature = "choreo-backend-telltale-machine",
202    not(target_arch = "wasm32")
203))]
204pub use runtime::choreography_adapter::{AuraProtocolAdapter, MessageRequest, ReceivedMessage};
205#[cfg(feature = "choreo-backend-telltale-machine")]
206pub use runtime::parity_policy::{AuraEnvelopeParityError, AuraEnvelopeParityPolicy};
207#[cfg(feature = "choreo-backend-telltale-machine")]
208pub use runtime::vm_effect_handler::{AuraVmEffectEvent, AuraVmEffectHandler};
209#[cfg(feature = "choreo-backend-telltale-machine")]
210pub use runtime::vm_hardening::{
211    apply_protocol_execution_policy, apply_scheduler_execution_policy, aura_flow_policy_predicate,
212    aura_output_predicate_allow_list, build_envelope_diff_artifact_for_policy, build_vm_config,
213    configured_guard_capacity, parse_communication_replay_mode, parse_determinism_mode,
214    parse_effect_determinism_tier, policy_for_protocol, policy_for_ref,
215    policy_requires_envelope_artifact, required_runtime_capabilities_for_policy,
216    scheduler_control_input_for_image, scheduler_control_input_for_protocol_machine_image,
217    scheduler_policy_for_input, scheduler_policy_ref, validate_determinism_profile,
218    validate_envelope_artifact_for_policy, validate_protocol_execution_policy,
219    validate_scheduler_execution_policy, vm_config_for_profile, AuraVmDeterminismProfileError,
220    AuraVmGuardLayer, AuraVmHardeningProfile, AuraVmParityProfile, AuraVmProtocolExecutionPolicy,
221    AuraVmRuntimeMode, AuraVmRuntimeSelector, AuraVmSchedulerControlInput,
222    AuraVmSchedulerEnvelopeClass, AuraVmSchedulerExecutionPolicy, AuraVmSchedulerSignals,
223    AuraVmSchedulerSignalsProvider, AURA_OUTPUT_PREDICATE_CHOICE,
224    AURA_OUTPUT_PREDICATE_GUARD_ACQUIRE, AURA_OUTPUT_PREDICATE_GUARD_RELEASE,
225    AURA_OUTPUT_PREDICATE_OBSERVABLE, AURA_OUTPUT_PREDICATE_STEP,
226    AURA_OUTPUT_PREDICATE_TRANSPORT_RECV, AURA_OUTPUT_PREDICATE_TRANSPORT_SEND,
227    AURA_VM_POLICY_CONSENSUS_FALLBACK, AURA_VM_POLICY_CONSENSUS_FAST_PATH,
228    AURA_VM_POLICY_DKG_CEREMONY, AURA_VM_POLICY_PROD_DEFAULT, AURA_VM_POLICY_RECOVERY_GRANT,
229    AURA_VM_POLICY_SYNC_ANTI_ENTROPY, AURA_VM_SCHED_PRIORITY_AGING, AURA_VM_SCHED_PROGRESS_AWARE,
230    AURA_VM_SCHED_ROUND_ROBIN,
231};
232#[cfg(feature = "choreo-backend-telltale-machine")]
233pub use runtime::{
234    AuraEffectTraceEncoding, AuraEffectTraceGranularity, EffectTraceBundle, EffectTraceCapture,
235    EffectTraceCaptureError, EffectTraceCaptureOptions,
236};
237
238// Sync service types
239#[cfg(feature = "choreo-backend-telltale-machine")]
240pub use runtime::services::{SyncManagerConfig, SyncManagerState, SyncServiceManager};
241
242// Rendezvous service types
243#[cfg(feature = "choreo-backend-telltale-machine")]
244pub use runtime::services::bootstrap_broker::BootstrapBrokerConfig;
245#[cfg(feature = "choreo-backend-telltale-machine")]
246pub use runtime::services::{
247    CoverTrafficGenerator, CoverTrafficGeneratorConfig, LocalHealthObserver,
248    LocalHealthObserverConfig, SelectionManager, SelectionManagerConfig, ServiceRegistry,
249};
250#[cfg(feature = "choreo-backend-telltale-machine")]
251pub use runtime::services::{RendezvousManager, RendezvousManagerConfig};
252
253// Social service types
254#[cfg(feature = "choreo-backend-telltale-machine")]
255pub use runtime::services::{
256    AccountabilityWitness, AccountabilityWitnessKind, HoldBudgetSnapshot, HoldDepositOutcome,
257    HoldGcOutcome, HoldLocalIndexEntry, HoldManager, HoldManagerConfig, HoldProjection,
258    HoldRetrievalOutcome, HoldRetrievalStatus, HoldSelectionPlan, HoldSyncBatch,
259    QueuedAccountabilityReply, QueuedSyncRetrieval, VerifiedServiceWitness, VerifierRole,
260};
261#[cfg(feature = "choreo-backend-telltale-machine")]
262pub use runtime::services::{SocialManager, SocialManagerConfig, SocialManagerState};
263
264// Threshold signing service types
265#[cfg(feature = "choreo-backend-telltale-machine")]
266pub use reconfiguration::{CoherenceStatus, ReconfigurationError, SessionFootprintClass};
267#[cfg(feature = "choreo-backend-telltale-machine")]
268pub use runtime::services::ThresholdSigningService;
269#[cfg(feature = "choreo-backend-telltale-machine")]
270pub use runtime::services::{
271    ReconfigurationManager, ReconfigurationManagerError, SessionDelegationOutcome,
272    SessionDelegationTransfer,
273};
274#[cfg(feature = "choreo-backend-telltale-machine")]
275pub use runtime::SessionOwnerCapabilityScope;
276
277// Re-export core types for convenience
278#[cfg(feature = "choreo-backend-telltale-machine")]
279pub use aura_core::effects::ExecutionMode;
280
281// Effect system types
282#[cfg(feature = "choreo-backend-telltale-machine")]
283pub use runtime::AuraEffectSystem;
284
285// Simulation factory (feature-gated)
286#[cfg(all(feature = "simulation", feature = "choreo-backend-telltale-machine"))]
287pub use runtime::EffectSystemFactory;
288
289// Re-export core types for convenience (authority-first)
290#[cfg(feature = "choreo-backend-telltale-machine")]
291pub use aura_core::types::identifiers::{AuthorityId, ContextId, SessionId};
292
293#[cfg(feature = "choreo-backend-telltale-machine")]
294pub use fact_registry::build_fact_registry;
295
296/// Selected choreography backend label.
297#[cfg(feature = "choreo-backend-telltale-machine")]
298pub const CHOREO_BACKEND: &str = "telltale_machine";
299
300/// Create a production agent (convenience function)
301#[cfg(feature = "choreo-backend-telltale-machine")]
302pub async fn create_production_agent(
303    ctx: &EffectContext,
304    authority_id: AuthorityId,
305) -> AgentResult<AuraAgent> {
306    AgentBuilder::new()
307        .with_authority(authority_id)
308        .build_production(ctx)
309        .await
310}
311
312/// Create a testing agent (convenience function)
313#[cfg(feature = "choreo-backend-telltale-machine")]
314pub fn create_testing_agent(authority_id: AuthorityId) -> AgentResult<AuraAgent> {
315    AgentBuilder::new()
316        .with_authority(authority_id)
317        .build_testing()
318}
319
320/// Create a simulation agent (convenience function)
321#[cfg(feature = "choreo-backend-telltale-machine")]
322pub fn create_simulation_agent(authority_id: AuthorityId, seed: u64) -> AgentResult<AuraAgent> {
323    AgentBuilder::new()
324        .with_authority(authority_id)
325        .build_simulation(seed)
326}