odem-rs-core 0.3.0

Core components of the odem-rs simulation framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! This module provides the `Agent` structure, representing an isolated
//! execution context within the simulation, along with supporting traits
//! and types.
//!
//! # Overview
//!
//! An `Agent` acts as the root of a potential tree of [jobs](Job), managing its
//! own isolated state. This isolation ensures that an agent's internal
//! execution is independent of the lexical context where it was created and
//! prevents side effects from influencing its behavior, except through
//! controlled simulation interactions (like scheduling events or waiting).
//!
//! Agent isolation is primarily achieved through the [`Actions`] trait and its
//! use of Higher-Ranked Trait Bounds (HRTBs). This mechanism prevents the
//! agent's core asynchronous logic (its "lifecycle") from capturing references
//! to non-static data from its creation environment.
//!
//! # Key Parts
//!
//!  - **Agent:** The [`Agent`] struct encapsulates an isolated execution
//!    context. It holds the agent's state and manages its lifecycle via an
//!    internal state machine. It automatically dereferences to its internal
//!    state, but mutable access is only possible *before* the agent is
//!    activated (enforced at compile-time via borrowing rules around
//!    [`Sim::activate`]).
//!
//!  - **Behavior:** The [`Behavior`] trait offers a user-friendly way to define
//!    an agent's actions. Implementing this trait for a type allows instances
//!    of that type to be easily converted into an [`Agent`]. It specifies the
//!    agent's return type (`Output`) and provides the core `async fn actions`.
//!    A blanket implementation exists for tuples `(I, A)` where `I` is the
//!    state and `A` is a compatible async function, allowing agent definition
//!    on foreign types.
//!
//!  - **Actions:** The [`Actions`] trait is the core abstraction defining an
//!    agent's lifecycle logic. It uses HRTBs (`for<'p>`) over the private
//!    `Action` trait to ensure isolation. It's parameterized on the simulation
//!    configuration and the agent's state type. Users cannot implement this
//!    directly but rely on implementations generated via the [`Behavior`] trait
//!    or the `(I, A)` tuple blanket implementation.
//!
//!  - **Builder:** The [`Builder`] provides a fluent API for constructing
//!    [`Agent`]s with detailed configuration options, such as a custom name,
//!    initial scheduling rank, source code location tracking, and custom
//!    finalization logic ([`Settle`]).
//!
//!  - **Puck:** An [`agent::Puck`](Puck) is the handle returned when an
//!    [`Agent`] is activated via [`Sim::activate`]. It allows interaction with
//!    the running agent, such as awaiting its completion, checking its status,
//!    accessing its shared state, or aborting it.
//!
//! # Examples
//!
//! ## Simple agent using `Behavior`
//!
//! ```
//! # use odem_rs_core::{agent::{Agent, Behavior}, simulator::Sim};
//! # use core::pin::pin;
//! struct MyData(usize);
//!
//! impl Behavior for MyData {
//!     type Output = (); // This agent doesn't return a meaningful value
//!
//!     async fn actions(&self, sim: &Sim) {
//!         println!("Agent starting with data: {}", self.0);
//!         sim.advance(10.0).await; // Simulate work
//!         println!("Agent finished.");
//!     }
//! }
//!
//! async fn sim_main(sim: &Sim) {
//!     // Create the agent state
//!     let data = MyData(42);
//!     // Create the agent using Agent::new, which leverages the Behavior impl
//!     let agent = pin!(Agent::new(data));
//!     // Activate the agent and get a handle (Puck)
//!     let handle = sim.activate(agent);
//!     // We can wait for the agent to finish (though it returns ())
//!     handle.await;
//! }
//! ```
//!
//! ## Agent returning a value
//!
//! ```
//! # use odem_rs_core::{agent::{Agent, Behavior}, simulator::Sim};
//! # use core::pin::pin;
//! struct Calculator(i32, i32);
//!
//! impl Behavior for Calculator {
//!     type Output = i32; // This agent returns a calculation result
//!
//!     async fn actions(&self, sim: &Sim) -> Self::Output {
//!         sim.advance(1.0).await; // Simulate calculation time
//!         self.0 + self.1
//!     }
//! }
//!
//! async fn sim_main(sim: &Sim) {
//!     let agent = pin!(Agent::new(Calculator(10, 5)));
//!     // Activate and await the result directly
//!     let result: i32 = sim.activate(agent).await;
//!     assert_eq!(result, 15);
//!     println!("Calculation result: {}", result);
//! }
//! ```
//!
//! ## Agent defined using a tuple `(State, AsyncFn)`
//!
//! This uses the blanket implementation `Behavior for (I, A)`.
//!
//! ```
//! # use odem_rs_core::{agent::Agent, simulator::Sim};
//! # use core::pin::pin;
//! struct SharedState { id: u32 }
//!
//! // Define the async logic as a standalone function or inherent method
//! async fn agent_logic(state: &SharedState, sim: &Sim) -> u32 {
//!     println!("Agent {} starting", state.id);
//!     sim.advance(5.0).await;
//!     println!("Agent {} finished", state.id);
//!     state.id * 2
//! }
//!
//! async fn sim_main(sim: &Sim) {
//!     let state = SharedState { id: 101 };
//!     // Create agent by pairing state and the async function
//!     let agent = pin!(Agent::new((state, agent_logic)));
//!     let result: u32 = sim.activate(agent).await;
//!     assert_eq!(result, 202);
//! }
//! ```
//!
//! ## Agent configured with the Builder
//!
//! ```
//! # use odem_rs_core::{agent::{Agent, Behavior}, config::Config, simulator::Sim, job::Checked};
//! # use core::pin::pin;
//! # #[derive(Config)] struct MyConfig { #[rank] rank: i32 }
//! struct Task { data: &'static str }
//!
//! impl Task {
//!     async fn actions(&self, sim: &Sim<MyConfig>) -> Result<String, &'static str> {
//!         if self.data.is_empty() {
//!             Err("Data cannot be empty")
//!         } else {
//!             sim.advance(2.0).await;
//!             Ok(format!("Processed: {}", self.data))
//!         }
//!     }
//! }
//!
//! async fn sim_main(sim: &Sim<MyConfig>) {
//!     let task = Task { data: "Valid Data" };
//!     
//!     let agent = Agent::build()
//!         .with_subject(task)          // Does not require `impl Behavior`
//!         .with_actions(Task::actions) // Provide the async fn
//!         .with_name("MyTask")         // Custom name
//!         .with_rank(10)               // Custom rank (C::Rank=i32)
//!         .checked()                   // Use checked finalization (for Result/Option/bool)
//!         .finish();                   // Get the Lease<'p, Agent<...>>
//!
//!     let pinned_agent = pin!(agent);
//!     let result = sim.activate(pinned_agent).await;
//!
//!     match result {
//!         Ok(output) => println!("Task succeeded: {}", output),
//!         Err(e) => println!("Task failed: {}", e),
//!     }
//!     // Note: .checked() ensures the ExitStatus reflects the Ok/Err outcome.
//!     // Accessing the result requires the Agent's Puck or awaiting it.
//! }
//! ```

use core::{
	any::{Any, type_name},
	future::{Future, IntoFuture, Pending, pending},
	marker::PhantomData,
	mem::ManuallyDrop,
	ops::{Deref, DerefMut},
	panic::Location,
	pin::Pin,
	task::{Context, Poll},
};

use crate::{
	Active, Dispatch, ExitStatus,
	config::Config,
	continuation::{Continuation, Label, Share, erased::State as ContState},
	job::{Builder as JobBuilder, Checked, Job, Puck as JobPuck, Settle, Unchecked},
	ptr::{AsIrc, Irc, Lease, LeasedMut},
	simulator::{Prec, Sim},
};

/* *************************************************** Internal Actions-Trait */

/// Defines the primary asynchronous behavior and output type for an [`Agent`].
///
/// This trait provides a convenient way to specify what an agent does. By
/// implementing `Behavior` for a type `T`, you allow `Agent::new(T)` to
/// automatically construct an agent using the provided `actions` method.
///
/// The `name` method determines the default base name for the agent's label,
/// defaulting to the type name of `T`.
///
/// A blanket implementation `Behavior<C> for (I, A)` exists, allowing you to
/// define agents by simply pairing a state type `I` with an appropriate
/// `async fn(&I, &Sim<C>) -> R` function, without needing a separate `impl`
/// block or a newtype wrapper.
///
/// # Examples
///
/// ```
/// # use odem_rs_core::{agent::{Agent, Behavior}, simulator::Sim};
/// # use core::pin::pin;
/// struct MyAgentState(f64);
///
/// impl Behavior for MyAgentState {
///     type Output = (); // No return value
///
///     async fn actions(&self, sim: &Sim) {
///         println!("Waiting for {} time units.", self.0);
///         sim.advance(self.0).await;
///         println!("Done waiting.");
///     }
/// }
/// # async fn run(sim: &Sim) {
/// // Use Agent::new thanks to the Behavior implementation
/// let agent = pin!(Agent::new(MyAgentState(5.0)));
/// sim.activate(agent).await;
/// # }
/// ```
///
/// Using the tuple blanket implementation:
/// ```
/// # use odem_rs_core::{agent::Agent, simulator::Sim};
/// # use core::pin::pin;
/// struct MyState(u32);
/// async fn my_async_fn(state: &MyState, sim: &Sim) { /* ... */ }
/// # async fn run(sim: &Sim) {
/// // Use Agent::new with a tuple (state, function)
/// let agent = pin!(Agent::new((MyState(10), my_async_fn)));
/// sim.activate(agent);
/// # }
/// ```
pub trait Behavior<C: ?Sized + Config = ()> {
	/// The type returned by the agent's `actions` method upon successful
	/// completion.
	type Output;

	/// The core asynchronous logic of the agent.
	///
	/// This method receives an immutable reference to the agent's state and the
	/// simulation context. It defines the sequence of operations and simulation
	/// interactions (like `sim.advance()`) the agent performs.
	///
	/// The returned `Future` cannot capture non-`'static` data from the
	/// surrounding environment, enforced implicitly by how [`Agent`] constructs
	/// the underlying task. `Send` is not required as simulations are
	/// single-threaded.
	#[allow(async_fn_in_trait)]
	async fn actions(&self, sim: &Sim<C>) -> Self::Output;

	/// Returns the base name for this agent type.
	///
	/// Defaults to the [`type_name`] of `Self`. Override this if a different
	/// base name is desired for logging or identification.
	fn name(&self) -> &'static str {
		type_name::<Self>()
	}
}

/// Abstracts over the asynchronous lifecycle logic of an [`Agent`].
///
/// This trait is the core mechanism for ensuring agent isolation. It uses a
/// Higher-Ranked Trait Bound (HRTB) over the sealed `Action` trait.
/// This HRTB (`for<'p> ...`) ensures that the future produced by the agent's
/// logic (`bind` method in `Action`) can only borrow data with lifetime `'p`
/// (namely, the agent's state `&'p I` and the sim context `&'p Sim<C>`),
/// preventing it from capturing references from the surrounding lexical scope
/// where the agent was created.
///
/// Users cannot implement this trait directly. Instead, they use types that
/// implement [`Behavior`], or tuples `(I, async_fn)`, which have blanket
/// implementations providing the necessary `Actions` implementation.
///
/// The main purpose of this trait is to act as a type parameter bound for
/// [`Agent`], allowing the agent's lifecycle (an unnameable `Future` type)
/// to be handled generically without needing to explicitly name it.
pub trait Actions<C: ?Sized + Config, I: ?Sized + Any>:
	// The implementation must satisfy `private::Action` for *any* lifetime 'p.
	for<'p> private::Action<'p, C, I, Future: Future<Output = Self::Output>>
{
	/// The result type produced by the agent's lifecycle future when it
	/// completes.
	type Output;
}

mod private {
	use super::*;

	/// **(Private)** Defines the function signature for creating an agent's
	/// lifecycle future.
	///
	/// This trait is an internal detail used by the [`Actions`] trait's HRTB.
	/// It represents a function that can be called once with temporarily
	/// borrowed references to the agent's state and the simulation context.
	/// It returns a [`Future`] that is allowed to borrow these inputs for the
	/// duration of lifetime `'p`.
	///
	/// The HRTB in [`Actions`] ensures that this `'p` lifetime cannot be tied
	/// to anything outside the scope of the `bind` call itself, thus enforcing
	/// agent isolation.
	///
	/// [HRTB]: https://doc.rust-lang.org/nomicon/hrtb.html
	pub trait Action<'p, C: ?Sized + Config, I: ?Sized + Any> {
		/// The type of `Future` returned by `bind`. Must live at least as long
		/// as `'p`.
		type Future: Future + 'p;

		/// Creates the agent's lifecycle `Future`.
		///
		/// This method consumes the action provider (`self`) and uses the
		/// provided borrowed state (`item`) and simulation context (`sim`)
		/// to construct the `Future` that represents the agent's execution.
		fn bind(self, item: &'p I, sim: &'p Sim<C>) -> Self::Future;
	}
}

/* ****************************************************************** Agent */

/// Represents an isolated execution context (an *agent*) within the simulation.
///
/// An `Agent` encapsulates:
///   - Subject: The data associated with this agent.
///   - Lifecycle: The asynchronous logic defining its behavior.
///   - Execution State: Manages whether the agent is ready, running, or finished.
///
/// Agents provide isolation: their internal logic, defined via the [`Actions`]
/// (and typically [`Behavior`]) trait, cannot directly access or be influenced
/// by the lexical scope where the `Agent` struct was created, due to the HRTB
/// mechanism employed by [`Actions`]. Communication happens through simulation
/// primitives (scheduling, waiting) and the agent's final `Output`.
///
/// `Agent` implements [`Deref`] and [`DerefMut`] to its subject.
/// However, mutable access is only practically possible *before* the agent is
/// passed to [`Sim::activate`], as activation blocks the access path. This is
/// enforced by Rust's borrowing rules at compile time.
///
/// Agents are typically created using [`Agent::new`] (for types implementing
/// [`Behavior`]) or [`Agent::build`] for more configuration options. They must
/// be pinned (e.g., using [`core::pin::pin!`]) before being passed to
/// [`Sim::activate`].
///
/// The generic parameter `S` defines the [`Settle`] strategy, controlling how
/// the agent's `Output` is translated into an [`ExitStatus`]. [`Unchecked`] is
/// the default, treating all outcomes as success. [`Checked`] interprets
/// `Result`, `Option`, and `bool` as success/failure indicators.
///
/// # Type Parameters
///
/// - `C`: The simulation configuration type ([`Config`]).
/// - `I`: The type of the agent's internal state (the "item" or "subject").
/// - `A`: The type implementing [`Actions`], defining the agent's lifecycle logic.
/// - `S`: The [`Settle`] strategy (defaults to [`Unchecked`]).
#[pin_project::pin_project(!Unpin, PinnedDrop)]
pub struct Agent<C: ?Sized + Config, I: ?Sized + Any, A: Actions<C, I>, S = Unchecked> {
	/// Internal state machine (`Born`, `Bust`, `Live`). Must be declared before
	/// `item`.
	#[pin]
	inner: Inner<C, I, A, S>,

	/// The user-provided state associated with this agent.
	#[pin]
	item: ManuallyDrop<I>,
}

/// Internal runtime states of an [`Agent`].
///
/// - `Born`: The initial state before activation. Holds the configuration
///   needed to construct the agent's lifecycle future.
/// - `Bust`: A transient state entered if the `action.bind()` call panics
///   during activation. The agent is effectively dead if observed in this state.
/// - `Live`: The state after successful activation. Contains the running root
///   [`Job`] and the shared context ([`Share`]) for the agent's job tree.
///
/// # Safety Warning
///
/// - Field Order (within `Live` variant): The order of fields `job` and `share`
///   **must not** be changed. `job` must come *before* `share`. Reversing this
///   order can lead to undefined behavior because the `job`'s future may hold
///   references derived from data pointed to by `share` (specifically, the
///   agent's `item` and `Sim` context). Drop order guarantees that `job` is
///   dropped before `share`, ensuring these references are not dangling.
#[pin_project::pin_project(
	project = StateProject,
	project_ref = StateProjectRef,
	project_replace = StateOwn
)]
enum Inner<C: ?Sized + Config, I: ?Sized + Any, A: Actions<C, I>, S> {
	/// Initial state before activation.
	Born {
		/// The action provider that will create the agent's lifecycle future.
		action: A,
		/// The base name used for the agent's label.
		name: &'static str,
		/// Optional initial scheduling rank. Defaults according to `C`.
		rank: Option<C::Rank>,
		/// Partially configured builder for the root job, awaiting the future.
		builder: JobBuilder<true, (), S>,
	},
	/// Transient state if `action.bind()` panics during activation.
	Bust,
	/// State after successful activation, agent is running or completed.
	Live {
		/// The root job executing the agent's lifecycle future. Must be
		/// declared before `share`.
		#[pin]
		job: RootJob<'static, C, I, A, S>,
		/// Shared context data (sim, subject ptr, rank, label) for this agent
		/// and its jobs.
		share: Share<C>,
	},
}

/// Type alias for the `Future` created by the agent's [`Actions`].
type RootFuture<'l, C, I, A> = <A as private::Action<'l, C, I>>::Future;

/// Type alias for the root [`Job`] wrapping the agent's `RootFuture`.
type RootJob<'l, C, I, A, S> = Job<C, RootFuture<'l, C, I, A>, S>;

/// Type alias for the [`JobPuck`] associated with the agent's `RootJob`.
type RootPuck<'l, C, I, A, S> = JobPuck<'l, C, RootFuture<'l, C, I, A>, S>;

impl Agent<(), (), Pending<()>> {
	/// Creates a new [`Agent`] using a type that implements [`Behavior`].
	///
	/// This is the simplest way to create an agent. It infers the agent's
	/// actions, output type, and name from the `Behavior` implementation of
	/// `I`. The agent uses the default [`Unchecked`] settle strategy, meaning
	/// its `ExitStatus` will always be `Ok` unless it panics or is aborted,
	/// regardless of the `Output` type (even if it's a `Result::Err`).
	///
	/// The provided `subject` (of type `I`) becomes the agent's internal state.
	///
	/// Returns a [`Lease`], which must be pinned before activation.
	///
	/// # Example
	///
	/// ```
	/// # use odem_rs_core::{agent::{Agent, Behavior}, simulator::Sim};
	/// # use core::pin::pin;
	/// struct MyAgent;
	/// impl Behavior for MyAgent {
	///     type Output = ();
	///     async fn actions(&self, sim: &Sim) { /* ... */ }
	/// }
	/// # fn make_agent() {
	/// let agent_lease = Agent::new(MyAgent);
	/// let pinned_agent = pin!(agent_lease);
	/// // Pass pinned_agent to sim.activate(...)
	/// # }
	/// ```
	#[track_caller]
	pub fn new<'p, C, I>(
		subject: I,
	) -> Lease<'p, Agent<C, I, impl Actions<C, I, Output = I::Output> + use<C, I>>>
	where
		C: ?Sized + Config,
		I: Any + Behavior<C>,
	{
		Self::build()
			.with_name(subject.name())
			.with_subject(subject)
			.with_actions(I::actions)
			.finish()
	}

	/// Creates a [`Builder`] for configuring an [`Agent`] instance.
	///
	/// Use the builder when you need to customize options like the agent's name,
	/// initial rank, settle strategy ([`Checked`]), or source code location,
	/// or when defining the agent using a state/function tuple instead of a
	/// dedicated `Behavior` implementation.
	///
	/// # Example
	///
	/// ```
	/// # use odem_rs_core::{agent::Agent, simulator::Sim, config::Config};
	/// # #[derive(Config)] struct MyConfig { #[rank] rank: i32 }
	/// # struct MyState;
	/// # async fn my_actions(_s: &MyState, _sim: &Sim<MyConfig>) {}
	/// # fn build_agent() {
	/// let agent = Agent::build()
	///     .with_subject(MyState)
	///     .with_actions(my_actions)
	///     .with_name("CustomAgent")
	///     .finish();
	/// // Pin and activate agent...
	/// # }
	/// ```
	pub const fn build<C: ?Sized + Config>() -> Builder<C> {
		Builder::new()
	}
}

impl<C, I, A, S> Deref for Agent<C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
{
	type Target = I;

	fn deref(&self) -> &Self::Target {
		&self.item
	}
}

impl<C, I, A, S> DerefMut for Agent<C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
{
	fn deref_mut(&mut self) -> &mut Self::Target {
		&mut self.item
	}
}

impl<C, I, A, S> Dispatch for Agent<C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
	S: Settle<A::Output>,
{
	fn poll(self: Pin<&Self>, cx: &mut Context<'_>) -> Poll<ExitStatus> {
		// Project to the 'inner' field
		match self.project_ref().inner.project_ref() {
			// If the agent is live, poll its root job
			StateProjectRef::Live { job, .. } => job.poll(cx),
			// Should not be polled in Born or Bust state.
			StateProjectRef::Born { .. } | StateProjectRef::Bust => {
				panic!("`poll` called before activation or after activation panicked")
			}
		}
	}
}

impl<C, I, A, S> Active<C> for Agent<C, I, A, S>
where
	C: ?Sized + Config,
	I: Any,
	A: Actions<C, I>,
	S: Settle<A::Output>,
{
	type Output = A::Output;
	type Puck<'p>
		= Puck<'p, C, I, A, S>
	where
		Self: 'p;

	/// Binds the agent to the simulation context, transitioning it from `Born`
	/// to `Live`.
	///
	/// This method is called internally by [`Sim::activate`]. It performs the
	/// critical steps:
	/// 1. Temporarily replaces the `Inner::Born` state with `Inner::Bust`.
	/// 2. Calls the `action.bind()` method (from `private::Action`) to create
	///    the agent's lifecycle future (`RootFuture`).
	/// 3. If `bind` succeeds, creates the `Share` context and the `RootJob`.
	/// 4. Replaces the `Inner::Bust` state with `Inner::Live`, containing the
	///    `RootJob` and `Share`.
	/// 5. Returns the agent's [`Puck`] handle.
	///
	/// If `action.bind()` panics, the agent remains in the `Inner::Bust` state.
	///
	/// # Safety
	/// Relies on `unsafe` blocks for lifetime transmutation (`'p` to `'static`
	/// and back) and creating the `Share` context. These are justified because:
	/// - The `'static` lifetime on `RootJob` within `Inner::Live` is an
	///   internal implementation detail; the actual future only borrows data
	///   for `'p`. The lifetime is transmuted back to `'p` when creating the
	///   `Puck`.
	/// - `Share::new` requires ensuring the `item` pointer outlives `Share`.
	///   This is guaranteed by the struct field ordering (`inner` before
	///   `item`), and Rust's drop order guarantees (`inner` is dropped first).
	fn bind<'p>(this: Pin<LeasedMut<'p, Self>>, sctx: &'p Share<C>) -> Self::Puck<'p> {
		let mut this = this.project().project();

		// replace the `Born` state by `Bust` for the transition
		match this.inner.as_mut().project_replace(Inner::Bust) {
			StateOwn::Born {
				action,
				name,
				rank,
				builder,
			} => {
				use core::mem::transmute;

				// Get references needed for `action.bind` and `Share::new`.
				let item_ref: &'p I = this.item.into_ref().get_ref();
				let sim: &'p Irc<Sim<C>> = sctx.sim();
				let pid = sim.pid_gen::<I>();

				// Optional: Tracing span for the agent's lifetime
				#[cfg(feature = "tracing")]
				let _span = tracing::error_span!(
					parent: None, "Agent",
					label = %Label { name, pid: Some(pid) }
				)
				.entered();

				// *** Critical Section Start ***
				// Call the action's bind method to create the actual lifecycle
				// future. This is the point that might panic, leaving the agent
				// in `Bust` state.
				let lifecycle = action.bind(item_ref, sim);
				// *** Critical Section End ***

				// Complete the root job builder with the created future
				let root_job = builder.with_actions(lifecycle).finish();

				// Now, transition from Bust to Live state.
				this.inner.set(Inner::Live {
					// SAFETY: Transmuting lifetime from 'p to 'static for storage.
					// The actual future inside `RootJob` correctly captures 'p.
					// We transmute back to 'p when returning the Puck.
					job: unsafe {
						transmute::<RootJob<'p, C, I, A, S>, RootJob<'static, C, I, A, S>>(
							root_job.into_inner(),
						)
					},
					// SAFETY: `Share::new` takes a pointer to `item`. This is
					// safe because our `drop` impl makes sure that `item` stays
					// valid until `share` is finally dropped. The `drop` impl
					// of `Share` is not allowed to access `item` by the
					// contract established through `Share::new`.
					share: unsafe {
						Share::new(
							sim.clone(),
							item_ref,
							rank.unwrap_or(sim.config().default_rank()),
							name,
							pid,
						)
					},
				});

				// Project the now guaranteed `Live` state to get Pin<&mut Job>
				// and Pin<&mut Share>
				match this.inner.project() {
					StateProject::Live { job, share } => {
						// Bind the root job to its share context

						// SAFETY: Transmuting the 'static lifetime back to 'p
						// is safe because the underlying future only borrows
						// for 'p. Adding LeasedMut wrapper is safe as this
						// specific `job` reference is consumed here.
						let job_pin = unsafe {
							transmute::<
								Pin<&mut RootJob<'static, C, I, A, S>>,
								Pin<LeasedMut<'p, RootJob<'p, C, I, A, S>>>,
							>(job)
						};

						// Create and wrap the JobPuck in our Agent::Puck
						Puck(Active::bind(job_pin, share))
					}
					_ => unreachable!("State should be Live after successful transition"),
				}
			}
			StateOwn::Live { .. } | StateOwn::Bust => {
				unreachable!("Agent::bind called on an already bound or busted agent")
			}
		}
	}
}

#[pin_project::pinned_drop]
impl<C, I, A, S> PinnedDrop for Agent<C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
{
	fn drop(self: Pin<&mut Self>) {
		// Drop the root job first to prevent dangling references to the item.
		if let StateProjectRef::Live { job, .. } = self.as_ref().project_ref().inner.project_ref() {
			job.abort_on_drop();
		}

		// SAFETY: Only the root job had a chance to access the item before
		// completing the drop, therefore, it is safe to drop it here.
		// `Share`'s drop is not allowed to access its raw pointer to `item`
		// and the drop check of the inner `IrcBox` aborts if any other
		// references exist.
		unsafe {
			ManuallyDrop::drop(self.project().item.get_unchecked_mut());
		}
	}
}

/* ************************************************************* Agent Puck */

/// A handle to an activated [`Agent`], returned by [`Sim::activate`].
///
/// This handle allows interaction with the running (or completed) agent. It
/// wraps the [`JobPuck`] of the agent's root job, providing access to
/// agent-specific information and actions.
///
/// The `Puck` implements [`IntoFuture`], allowing you to `.await` it to get the
/// agent's final `Output`. It also implements [`crate::Puck`], providing common
/// methods for interacting with active simulation entities (checking state,
/// time, etc.).
pub struct Puck<'p, C: ?Sized + Config, I: ?Sized + Any, A: Actions<C, I>, S>(
	RootPuck<'p, C, I, A, S>,
);

impl<C, I, A, S> Puck<'_, C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
	S: Settle<A::Output>,
{
	/// Sets the rank of the root job.
	///
	/// The new rank takes immediate effect and causes the rearrangement
	/// of all jobs currently scheduled, both in the present and future.
	///
	/// Lowering the rank of the active `Agent` can lead to another `Agent`
	/// gaining control if one with a higher rank after the change has jobs
	/// scheduled at the current model time. This change takes effect once the
	/// currently active agent suspends.
	pub fn update_rank(&self, rank: C::Rank) {
		self.0.share().update_rank(rank);
	}

	/// Returns an immutable reference to the agent's internal state (`item`).
	///
	/// This allows observing the agent's state while it's running or after it
	/// has completed. Mutable access is not possible via the `Puck`.
	pub fn subject(&self) -> &I
	where
		I: Sized,
	{
		use crate::Puck;

		self.0.subject().downcast_ref::<I>().unwrap()
	}

	/// Aborts the agent's execution prematurely.
	///
	/// This terminates the agent's root job and any descendant jobs.
	/// The agent's `ExitStatus` will reflect the abortion. The `Output` value
	/// will not be produced.
	///
	/// Consumes the `Puck` to prevent further interaction after aborting.
	pub fn abort(self) {
		self.0.abort();
	}
}

// Allow awaiting the Agent::Puck to get the final result.
impl<C, I, A, S> IntoFuture for Puck<'_, C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
	S: Settle<A::Output>,
{
	type Output = A::Output;
	type IntoFuture = crate::ops::Join<C, Self>;

	fn into_future(self) -> Self::IntoFuture {
		crate::ops::join(self)
	}
}

// Implement the base Puck trait for Agent::Puck by delegating.
impl<C, I, A, S> crate::Puck<C> for Puck<'_, C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
	S: Settle<A::Output>,
{
	fn result(&mut self) -> Option<Self::Output> {
		self.0.result()
	}

	fn subject(&self) -> &dyn Any {
		self.0.subject()
	}

	fn sim(&self) -> &Sim<C> {
		self.0.sim()
	}

	fn label(&self) -> Label {
		self.0.label()
	}

	fn time(&self) -> Option<C::Time> {
		self.0.time()
	}

	fn rank(&self) -> C::Rank {
		self.0.rank()
	}

	fn prec(&self) -> Prec {
		self.0.prec()
	}

	fn state(&self) -> ContState {
		self.0.state()
	}

	fn location(&self) -> &'static Location<'static> {
		self.0.location()
	}

	fn puck(&self) -> crate::continuation::Puck<C> {
		self.0.puck()
	}
}

// Allow getting a reference to the underlying Continuation.
impl<C, I, A, S> AsRef<Continuation<'static, C>> for Puck<'_, C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
{
	fn as_ref(&self) -> &Continuation<'static, C> {
		self.0.as_ref()
	}
}

// Allow getting an intrusive reference counter (Irc) to the Continuation.
impl<C, I, A, S> AsIrc<Continuation<'static, C>> for Puck<'_, C, I, A, S>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	A: Actions<C, I>,
{
	fn as_irc(&self) -> Irc<Continuation<'static, C>> {
		self.0.as_irc()
	}
}

/* ********************************************************** Agent Builder */

/// A builder pattern for configuring and creating [`Agent`] instances.
///
/// Use the builder when you need more control over the agent's properties than
/// [`Agent::new`] provides, such as setting a custom name, initial rank,
/// source location, or finalization strategy ([`Settle`]).
///
/// Start with [`Agent::build()`] and chain `with_*` methods to configure,
/// finally calling [`finish()`](Builder::finish) to create the [`Agent`]
/// wrapped in a [`Lease`].
///
/// # Type Parameters
///
/// - `C`: The simulation configuration ([`Config`]).
/// - `I`: The type of the agent's state (`item`). Initially `()`.
/// - `A`: The type implementing [`Actions`]. Initially `()`.
/// - `S`: The [`Settle`] strategy. Initially [`Unchecked`].
pub struct Builder<C: ?Sized + Config, I = (), A = (), S = Unchecked> {
	/// The agent's state (subject). Set via `with_subject`.
	subject: I,
	/// The agent's lifecycle logic provider. Set via `with_actions`.
	actions: A,
	/// Optional custom base name for the agent's label. Set via `with_name`.
	name: Option<&'static str>,
	/// Optional initial scheduling rank. Set via `with_rank`.
	rank: Option<C::Rank>,
	/// The finalization strategy. Set via `with_finalizer` or `checked`.
	settle: S,
	/// Optional source code location.
	/// Set via `with_location` or implicitly by `with_actions`.
	location: Option<&'static Location<'static>>,
	/// Marker for the configuration type `C`.
	_config: PhantomData<C>,
}

impl<C: ?Sized + Config> Builder<C, (), ()> {
	/// Creates a new, empty agent builder.
	/// Called via [`Agent::build()`].
	const fn new() -> Self {
		Builder {
			subject: (),
			actions: (),
			name: None,
			rank: None,
			settle: Unchecked,
			location: None,
			_config: PhantomData,
		}
	}
}

// Methods to configure the Builder
impl<C: ?Sized + Config, I: Any, A, S> Builder<C, I, A, S> {
	/// Sets the state (`item`) for the agent being built.
	pub fn with_subject<X: Any>(self, object: X) -> Builder<C, X, A, S> {
		Builder {
			subject: object,
			actions: self.actions,
			name: self.name,
			rank: self.rank,
			settle: self.settle,
			location: self.location,
			_config: self._config,
		}
	}

	/// Sets the lifecycle logic (actions) for the agent.
	///
	/// This accepts any type `X` that implements [`Actions<C, I>`], where `I`
	/// is the type set by `with_subject`. Typically, this is an `async fn`
	/// reference compatible with the state `I`, or the `actions` method from a
	/// `Behavior` impl.
	///
	/// This method also captures the caller's source code location using
	/// `#[track_caller]` as the default location for the agent, unless
	/// explicitly overridden by `with_location`.
	#[track_caller]
	pub fn with_actions<X>(self, actions: X) -> Builder<C, I, X, S>
	where
		X: Actions<C, I>,
	{
		Builder {
			subject: self.subject,
			actions,
			name: self.name,
			rank: self.rank,
			settle: self.settle,
			location: Some(self.location.unwrap_or_else(Location::caller)),
			_config: self._config,
		}
	}

	/// Explicitly sets the source code [`Location`] associated with the agent.
	///
	/// Overrides the location captured by `with_actions`. Useful if the agent's
	/// definition site is different from where the builder is called.
	pub const fn with_location(mut self, location: &'static Location<'static>) -> Self {
		self.location = Some(location);
		self
	}

	/// Sets a custom base name for the agent's [`Label`].
	///
	/// If not set, the name defaults to the type name of the subject (`I`)
	/// when [`finish()`](Self::finish) is called.
	pub const fn with_name(mut self, name: &'static str) -> Self {
		self.name = Some(name);
		self
	}

	/// Sets a custom initial scheduling rank for the agent.
	///
	/// If not set, the rank defaults to `sim.config().default_rank()`
	/// during activation.
	pub fn with_rank(self, rank: C::Rank) -> Self {
		Builder {
			rank: Some(rank),
			..self
		}
	}

	/// Sets a custom [`Settle`] strategy for the agent's finalization.
	///
	/// The `Settle` trait determines how the agent's `Output` value (of type
	/// `R`) is converted into an [`ExitStatus`].
	pub fn with_finalizer<X>(self, finalizer: X) -> Builder<C, I, A, X> {
		Builder {
			subject: self.subject,
			actions: self.actions,
			name: self.name,
			rank: self.rank,
			settle: finalizer,
			location: self.location,
			_config: self._config,
		}
	}

	/// Sets the [`Settle`] strategy to [`Checked`].
	///
	/// This is a shortcut for `with_finalizer(Checked)`. The `Checked` strategy
	/// interprets `bool`, `Option`, and `Result` outputs to determine the
	/// agent's [`ExitStatus`] (`Success` vs. `Failure`).
	pub fn checked(self) -> Builder<C, I, A, Checked> {
		self.with_finalizer(Checked)
	}
}

impl<C: ?Sized + Config, I: Any, R, A, S> Builder<C, I, A, S>
where
	A: Actions<C, I, Output = R>,
	S: Settle<R>,
{
	/// Constructs the [`Agent`] instance from the builder configuration.
	///
	/// This method consumes the builder and returns the configured `Agent`
	/// wrapped in a [`Lease`]. The `Lease` provides ownership transfer
	/// semantics for mutable borrows and requires pinning before activation.
	///
	/// Requires that `with_subject` and `with_actions` have been called
	/// previously. It uses the type name of `I` as the default agent name if
	/// `with_name` was not called.
	pub fn finish<'p>(self) -> Lease<'p, Agent<C, I, A, S>> {
		// Create the Agent in the Born state
		Lease::new(Agent {
			item: ManuallyDrop::new(self.subject),
			inner: Inner::Born {
				action: self.actions,
				name: self.name.unwrap_or_else(|| type_name::<I>()),
				rank: self.rank,
				// Create the root job builder with finalizer and location
				builder: JobBuilder::root() // Mark as the root job
					.with_finalizer(self.settle)
					.with_location(self.location.unwrap()),
			},
		})
	}
}

/* **************************************************** Trait Implementations */

impl<C, I, A, R> Behavior<C> for (I, A)
where
	C: ?Sized + Config,
	I: Any,
	A: AsyncFn(&I, &Sim<C>) -> R,
{
	type Output = R;

	fn actions(&self, sim: &Sim<C>) -> impl Future<Output = R> {
		(self.1)(&self.0, sim)
	}

	fn name(&self) -> &'static str {
		type_name::<I>()
	}
}

// Blanket implementation forwarding `Actions` to `private::Action`.
// This connects the public `Actions` trait to the private HRTB machinery.
impl<A, C, I, R> Actions<C, I> for A
where
	A: for<'p> private::Action<'p, C, I, Future: Future<Output = R>>,
	C: ?Sized + Config,
	I: ?Sized + Any,
{
	type Output = R;
}

// Implement `private::Action` for `Pending<()>` used in the empty builder.
impl<'p, C, I> private::Action<'p, C, I> for Pending<()>
where
	C: ?Sized + Config,
	I: ?Sized + Any,
{
	type Future = Pending<()>;

	fn bind(self, _item: &'p I, _sim: &'p Sim<C>) -> Self::Future {
		pending()
	}
}

// Implement `private::Action` for function pointers and closures that match the
// signature. This is the core implementation that allows `async fn` references
// to be used as actions.
impl<'p, C, I, F, R> private::Action<'p, C, I> for F
where
	C: ?Sized + Config,
	I: ?Sized + Any,
	F: FnOnce(&'p I, &'p Sim<C>) -> R,
	R: Future + 'p,
{
	type Future = R;

	fn bind(self, item: &'p I, sim: &'p Sim<C>) -> Self::Future {
		self(item, sim)
	}
}