Skip to main content

mecha10_behavior_runtime/
behavior.rs

1//! Core BehaviorNode trait and types
2//!
3//! This module defines the fundamental `BehaviorNode` trait that all behaviors must implement.
4
5use crate::NodeStatus;
6use async_trait::async_trait;
7use mecha10_core::Context;
8use std::fmt::Debug;
9
10/// Core trait that all behavior nodes must implement.
11///
12/// This is the fundamental building block of the behavior system. Everything - from simple
13/// actions to complex AI models to composition primitives - implements this trait.
14///
15/// # Design Principles
16///
17/// 1. **Simplicity** - One method: `tick()`
18/// 2. **Async-first** - All behaviors are async by default
19/// 3. **Composable** - Nodes can be freely combined
20/// 4. **Type-safe** - Rust's type system ensures correctness
21///
22/// # Example
23///
24/// ```rust
25/// use mecha10_behavior_runtime::prelude::*;
26///
27/// #[derive(Debug)]
28/// struct PrintMessage {
29///     message: String,
30/// }
31///
32/// #[async_trait]
33/// impl BehaviorNode for PrintMessage {
34///     async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
35///         println!("{}", self.message);
36///         Ok(NodeStatus::Success)
37///     }
38///
39///     fn name(&self) -> &str {
40///         "print_message"
41///     }
42/// }
43/// ```
44#[async_trait]
45pub trait BehaviorNode: Send + Sync + Debug {
46    /// Execute one tick of the behavior.
47    ///
48    /// This method is called repeatedly by the execution engine. It should:
49    /// - Perform one unit of work
50    /// - Return quickly (non-blocking)
51    /// - Return `NodeStatus` to indicate progress
52    ///
53    /// # Arguments
54    ///
55    /// * `ctx` - Execution context with access to messaging, sensors, etc.
56    ///
57    /// # Returns
58    ///
59    /// * `NodeStatus::Success` - Behavior completed successfully
60    /// * `NodeStatus::Failure` - Behavior failed (irrecoverable error)
61    /// * `NodeStatus::Running` - Behavior is still executing (call again)
62    ///
63    /// # Errors
64    ///
65    /// Return an error for exceptional conditions that should halt execution.
66    /// For recoverable failures, return `Ok(NodeStatus::Failure)` instead.
67    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus>;
68
69    /// Get the name of this behavior node.
70    ///
71    /// Used for debugging, logging, and monitoring. The default implementation
72    /// returns the type name.
73    fn name(&self) -> &str {
74        std::any::type_name::<Self>()
75    }
76
77    /// Return mutable references to this node's child behaviors, in the order
78    /// they should receive lifecycle events.
79    ///
80    /// Leaf nodes have no children and should not override this - the default
81    /// implementation returns an empty list. Composite nodes (e.g. `SequenceNode`,
82    /// `SelectOrNode`, `ParallelNode`, `SubsumptionNode`, `EnsembleNode`) override
83    /// this to expose their children, which drives the default `on_init`/
84    /// `on_terminate`/`reset` propagation below without each composite having to
85    /// hand-roll the same loop.
86    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
87        Vec::new()
88    }
89
90    /// Reset the behavior to its initial state.
91    ///
92    /// Called when the behavior needs to be restarted (e.g., in a loop or
93    /// after a failure). The default implementation propagates the reset to
94    /// every child returned by `children_mut`.
95    async fn reset(&mut self) -> anyhow::Result<()> {
96        for child in self.children_mut() {
97            child.reset().await?;
98        }
99        Ok(())
100    }
101
102    /// Called when the behavior is first initialized.
103    ///
104    /// Use this for one-time setup like loading models, establishing connections, etc.
105    /// The default implementation propagates `on_init` to every child returned by
106    /// `children_mut`.
107    async fn on_init(&mut self, ctx: &Context) -> anyhow::Result<()> {
108        for child in self.children_mut() {
109            child.on_init(ctx).await?;
110        }
111        Ok(())
112    }
113
114    /// Called when the behavior is being terminated.
115    ///
116    /// Use this for cleanup like closing connections, saving state, etc.
117    /// The default implementation propagates `on_terminate` to every child
118    /// returned by `children_mut`.
119    async fn on_terminate(&mut self, ctx: &Context) -> anyhow::Result<()> {
120        for child in self.children_mut() {
121            child.on_terminate(ctx).await?;
122        }
123        Ok(())
124    }
125}
126
127/// Type alias for boxed behavior nodes.
128///
129/// This is used for storing heterogeneous collections of behaviors.
130pub type BoxedBehavior = Box<dyn BehaviorNode>;
131
132// ============================================================================
133// Helper Implementations
134// ============================================================================
135
136/// Extension trait for BehaviorNode to provide convenient helpers.
137///
138/// This trait is automatically implemented for all types that implement `BehaviorNode`.
139#[async_trait]
140pub trait BehaviorNodeExt: BehaviorNode {
141    /// Run this behavior until it completes (Success or Failure).
142    ///
143    /// This is a convenience method for testing and simple execution.
144    ///
145    /// # Example
146    ///
147    /// ```rust
148    /// use mecha10_behavior_runtime::prelude::*;
149    ///
150    /// # async fn example(mut behavior: impl BehaviorNode, ctx: &Context) -> anyhow::Result<()> {
151    /// let status = behavior.run_until_complete(ctx).await?;
152    /// assert_eq!(status, NodeStatus::Success);
153    /// # Ok(())
154    /// # }
155    /// ```
156    async fn run_until_complete(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
157        loop {
158            match self.tick(ctx).await? {
159                NodeStatus::Success => return Ok(NodeStatus::Success),
160                NodeStatus::Failure => return Ok(NodeStatus::Failure),
161                NodeStatus::Running => continue,
162            }
163        }
164    }
165
166    /// Run this behavior with a maximum number of ticks.
167    ///
168    /// Returns `Err` if the behavior doesn't complete within `max_ticks`.
169    ///
170    /// # Example
171    ///
172    /// ```rust
173    /// use mecha10_behavior_runtime::prelude::*;
174    ///
175    /// # async fn example(mut behavior: impl BehaviorNode, ctx: &Context) -> anyhow::Result<()> {
176    /// let status = behavior.run_with_limit(ctx, 100).await?;
177    /// # Ok(())
178    /// # }
179    /// ```
180    async fn run_with_limit(&mut self, ctx: &Context, max_ticks: usize) -> anyhow::Result<NodeStatus> {
181        for _tick_count in 0..max_ticks {
182            match self.tick(ctx).await? {
183                NodeStatus::Success => return Ok(NodeStatus::Success),
184                NodeStatus::Failure => return Ok(NodeStatus::Failure),
185                NodeStatus::Running => continue,
186            }
187        }
188        anyhow::bail!("Behavior exceeded maximum ticks ({})", max_ticks)
189    }
190}
191
192// Blanket implementation for all BehaviorNode types
193impl<T: BehaviorNode + ?Sized> BehaviorNodeExt for T {}