mecha10-behavior-runtime 0.7.0

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;

#[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()
    }

    /// The `capability` this node implies should be published on `/behavior/status` while it's
    /// the one actively being ticked (e.g. `rl_task`'s hardcoded `"rl"`, gating `RlNode::is_active()`
    /// on the `rl` node crate's side) - `None` for a node with no such gate (the default, correct
    /// for the vast majority of leaves and for a composite with no currently-active child).
    ///
    /// Composite nodes (`SequenceNode`, `SelectOrNode`, `ParallelNode`) override this to forward
    /// whichever child is currently active/running - `behavior-executor` calls this on the tree
    /// root each status tick rather than each leaf declaring anything back up on its own, since
    /// which child is "current" is already tracked by the composite ticking it.
    fn active_capability(&self) -> Option<&str> {
        None
    }

    /// 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(())
    }
}

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()
}

#[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))
        }
    };
}

#[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);
        }
    };
}

#[macro_export]
macro_rules! reset_index_field {
    ($field:ident) => {
        fn reset_self(&mut self) {
            self.$field = 0;
        }
    };
}

#[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 {}