mecha10-behavior-runtime 0.6.5

Behavior tree runtime for Mecha10 - unified AI and logic composition system
Documentation
//! Core BehaviorNode trait and types
//!
//! This module defines the fundamental `BehaviorNode` trait that all behaviors must implement.

use crate::NodeStatus;
use async_trait::async_trait;
use mecha10_core::Context;
use std::fmt::Debug;

/// Core trait that all behavior nodes must implement.
///
/// This is the fundamental building block of the behavior system. Everything - from simple
/// actions to complex AI models to composition primitives - implements this trait.
///
/// # Design Principles
///
/// 1. **Simplicity** - One method: `tick()`
/// 2. **Async-first** - All behaviors are async by default
/// 3. **Composable** - Nodes can be freely combined
/// 4. **Type-safe** - Rust's type system ensures correctness
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::prelude::*;
///
/// #[derive(Debug)]
/// struct PrintMessage {
///     message: String,
/// }
///
/// #[async_trait]
/// impl BehaviorNode for PrintMessage {
///     async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
///         println!("{}", self.message);
///         Ok(NodeStatus::Success)
///     }
///
///     fn name(&self) -> &str {
///         "print_message"
///     }
/// }
/// ```
#[async_trait]
pub trait BehaviorNode: Send + Sync + Debug {
    /// Execute one tick of the behavior.
    ///
    /// This method is called repeatedly by the execution engine. It should:
    /// - Perform one unit of work
    /// - Return quickly (non-blocking)
    /// - Return `NodeStatus` to indicate progress
    ///
    /// # Arguments
    ///
    /// * `ctx` - Execution context with access to messaging, sensors, etc.
    ///
    /// # Returns
    ///
    /// * `NodeStatus::Success` - Behavior completed successfully
    /// * `NodeStatus::Failure` - Behavior failed (irrecoverable error)
    /// * `NodeStatus::Running` - Behavior is still executing (call again)
    ///
    /// # Errors
    ///
    /// Return an error for exceptional conditions that should halt execution.
    /// For recoverable failures, return `Ok(NodeStatus::Failure)` instead.
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus>;

    /// Get the name of this behavior node.
    ///
    /// Used for debugging, logging, and monitoring. The default implementation
    /// returns the type name.
    fn name(&self) -> &str {
        std::any::type_name::<Self>()
    }

    /// Return mutable references to this node's child behaviors, in the order
    /// they should receive lifecycle events.
    ///
    /// Leaf nodes have no children and should not override this - the default
    /// implementation returns an empty list. Composite nodes (e.g. `SequenceNode`,
    /// `SelectOrNode`, `ParallelNode`, `SubsumptionNode`, `EnsembleNode`) override
    /// this to expose their children, which drives the default `on_init`/
    /// `on_terminate`/`reset` propagation below without each composite having to
    /// hand-roll the same loop.
    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        Vec::new()
    }

    /// Reset this node's own local state, ignoring children.
    ///
    /// Called by the default `reset()` implementation before it propagates to children.
    /// Composite nodes with local progress to rewind (e.g. `SequenceNode`'s current child
    /// index, `ParallelNode`'s per-child statuses) override this instead of `reset()`
    /// itself, so they don't have to hand-roll the child-propagation loop below.
    fn reset_self(&mut self) {}

    /// Reset the behavior to its initial state.
    ///
    /// Called when the behavior needs to be restarted (e.g., in a loop or
    /// after a failure). The default implementation resets local state via
    /// `reset_self`, then propagates the reset to every child returned by
    /// `children_mut`.
    async fn reset(&mut self) -> anyhow::Result<()> {
        self.reset_self();
        for child in self.children_mut() {
            child.reset().await?;
        }
        Ok(())
    }

    /// Called when the behavior is first initialized.
    ///
    /// Use this for one-time setup like loading models, establishing connections, etc.
    /// The default implementation propagates `on_init` to every child returned by
    /// `children_mut`.
    async fn on_init(&mut self, ctx: &Context) -> anyhow::Result<()> {
        for child in self.children_mut() {
            child.on_init(ctx).await?;
        }
        Ok(())
    }

    /// Called when the behavior is being terminated.
    ///
    /// Use this for cleanup like closing connections, saving state, etc.
    /// The default implementation propagates `on_terminate` to every child
    /// returned by `children_mut`.
    async fn on_terminate(&mut self, ctx: &Context) -> anyhow::Result<()> {
        for child in self.children_mut() {
            child.on_terminate(ctx).await?;
        }
        Ok(())
    }
}

/// Type alias for boxed behavior nodes.
///
/// This is used for storing heterogeneous collections of behaviors.
pub type BoxedBehavior = Box<dyn BehaviorNode>;

/// Maps an iterator of boxed child behaviors to `BehaviorNode::children_mut`'s trait-object
/// return type.
///
/// Backs every composite node's `children_mut` override (`SequenceNode`, `SelectOrNode`,
/// `ParallelNode` here, plus `SubsumptionNode`/`EnsembleNode` in `mecha10-behavior-patterns`,
/// which map their `SubsumptionLayer`/`WeightedModel` wrappers down to `&mut BoxedBehavior`
/// first) - cargo-dupes flagged the repeated `iter_mut().map(|c| c.as_mut() as &mut dyn
/// BehaviorNode).collect()` body as an exact duplicate across all of them.
pub fn boxed_children_mut<'a>(children: impl Iterator<Item = &'a mut BoxedBehavior>) -> Vec<&'a mut dyn BehaviorNode> {
    children.map(|c| c.as_mut() as &mut dyn BehaviorNode).collect()
}

/// Generate the `children_mut` override for a composite node whose children are wrapped in a
/// per-child metadata struct (e.g. a priority or weight) rather than stored as bare
/// `BoxedBehavior`s directly.
///
/// `SubsumptionNode::layers` (`Vec<SubsumptionLayer>`) and `EnsembleNode::models`
/// (`Vec<WeightedModel>`), both in `mecha10-behavior-patterns`, need to map their wrapper's
/// `behavior` field down to `&mut BoxedBehavior` before delegating to [`boxed_children_mut`] -
/// cargo-dupes flagged the resulting one-line trait impl bodies as an exact duplicate of each
/// other (same shape, differing only in field/binding names).
#[macro_export]
macro_rules! children_mut_via_wrapped_behavior {
    ($field:ident, $wrapper:ident) => {
        fn children_mut(&mut self) -> Vec<&mut dyn $crate::BehaviorNode> {
            $crate::boxed_children_mut(self.$field.iter_mut().map(|$wrapper| &mut $wrapper.behavior))
        }
    };
}

/// Generate the `reset_self` override for a composite node that tracks one [`NodeStatus`] per
/// child in a `Vec<NodeStatus>` field, resetting them all back to [`NodeStatus::Running`].
///
/// `ParallelNode` (this crate) and `EnsembleNode` (`mecha10-behavior-patterns`) both do this -
/// cargo-dupes flagged their `reset_self` bodies as an exact duplicate of each other.
#[macro_export]
macro_rules! reset_child_statuses_field {
    ($field:ident) => {
        fn reset_self(&mut self) {
            self.$field
                .iter_mut()
                .for_each(|s| *s = $crate::NodeStatus::Running);
        }
    };
}

/// Generate the `reset_self` override for a composite node that tracks progress through its
/// children with a single `usize` index field, rewinding it back to `0`.
///
/// `SequenceNode` and `SelectOrNode` (this crate) both do this - cargo-dupes flagged their
/// `reset_self` bodies as an exact duplicate of each other.
#[macro_export]
macro_rules! reset_index_field {
    ($field:ident) => {
        fn reset_self(&mut self) {
            self.$field = 0;
        }
    };
}

/// Extension trait for BehaviorNode to provide convenient helpers.
///
/// This trait is automatically implemented for all types that implement `BehaviorNode`.
#[async_trait]
pub trait BehaviorNodeExt: BehaviorNode {
    /// Run this behavior until it completes (Success or Failure).
    ///
    /// This is a convenience method for testing and simple execution.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mecha10_behavior_runtime::prelude::*;
    ///
    /// # async fn example(mut behavior: impl BehaviorNode, ctx: &Context) -> anyhow::Result<()> {
    /// let status = behavior.run_until_complete(ctx).await?;
    /// assert_eq!(status, NodeStatus::Success);
    /// # Ok(())
    /// # }
    /// ```
    async fn run_until_complete(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        loop {
            match self.tick(ctx).await? {
                NodeStatus::Success => return Ok(NodeStatus::Success),
                NodeStatus::Failure => return Ok(NodeStatus::Failure),
                NodeStatus::Running => continue,
            }
        }
    }

    /// Run this behavior with a maximum number of ticks.
    ///
    /// Returns `Err` if the behavior doesn't complete within `max_ticks`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mecha10_behavior_runtime::prelude::*;
    ///
    /// # async fn example(mut behavior: impl BehaviorNode, ctx: &Context) -> anyhow::Result<()> {
    /// let status = behavior.run_with_limit(ctx, 100).await?;
    /// # Ok(())
    /// # }
    /// ```
    async fn run_with_limit(&mut self, ctx: &Context, max_ticks: usize) -> anyhow::Result<NodeStatus> {
        for _tick_count in 0..max_ticks {
            match self.tick(ctx).await? {
                NodeStatus::Success => return Ok(NodeStatus::Success),
                NodeStatus::Failure => return Ok(NodeStatus::Failure),
                NodeStatus::Running => continue,
            }
        }
        anyhow::bail!("Behavior exceeded maximum ticks ({})", max_ticks)
    }
}

impl<T: BehaviorNode + ?Sized> BehaviorNodeExt for T {}