acton-core 4.0.0

Acton Core provides the core functionality and abstractions used by the Acton Reactive crate. It includes the essential building blocks for creating reactive and distributed systems.
Documentation
# Acton Core Architecture Overview

This document provides a high-level overview of the architecture and functionality of the `acton-core` crate, generated by analyzing its source files.

*(Generated by Roo Code)*

---

## File/Module Descriptions

### `src/lib.rs`
- **Role**: Crate root.
- **Functionality**:
    - Declares the main internal modules (`common`, `actor`, `message`, `traits`).
    - Sets crate-level attributes (lints like `forbid(missing_docs)`).
    - Provides top-level crate documentation (`//!`).
    - Defines the public `prelude` module, which re-exports key types and traits from internal modules for convenient use by downstream crates (like `acton-reactive`).

### `src/actor/mod.rs`
- **Role**: Defines the `actor` module.
- **Functionality**:
    - Declares submodules (`managed_agent`, `agent_config`) responsible for agent implementation and configuration.
    - Re-exports key types (`AgentConfig`, `Idle`, `ManagedAgent`, `Started`) from its submodules to make them directly available under the `actor::` path and for potential inclusion in the crate prelude.

### `src/actor/agent_config.rs`
- **Role**: Defines the configuration structure for agents.
- **Functionality**:
    - Contains the `AgentConfig` struct, holding parameters needed to initialize an agent:
        - `id`: The agent's unique identifier (`Ern`).
        - `broker`: Optional reference to the system message broker (`BrokerRef`).
        - `parent`: Optional reference to the agent's supervisor (`ParentRef`).
    - Provides constructors (`new`, `new_with_name`) for creating configurations.
    - Includes logic in `new` to derive hierarchical ERNs for child agents based on their parent's ERN.

### `src/actor/managed_agent.rs`
- **Role**: Defines the core `ManagedAgent` struct, the runtime representation of an agent.
- **Functionality**:
    - Acts as a generic state machine wrapper around user-defined agent logic (`Model` generic parameter) and state markers (`AgentState` generic parameter, e.g., `Idle`, `Started`).
    - Encapsulates essential agent runtime components: `AgentHandle`, `parent` ref, `broker` ref, message `inbox`, lifecycle hooks (`before_start`, `after_start`, etc.), `message_handlers` map, `error_handler_map`, user `model`, `TaskTracker`, and `HaltSignal`.
    - The `error_handler_map` stores specific handlers for `(Message, Error)` pairs, keyed by their respective `TypeId`s.
    - Provides public getters for accessing agent context (`id`, `name`, `handle`, etc.).
    - Declares `idle` and `started` submodules for state-specific implementations.
    - Re-exports the `Idle` state marker struct.

### `src/actor/managed_agent/idle.rs`
- **Role**: Implements the configuration phase and state transition logic for an agent before it starts running.
- **Functionality**:
    - Defines the `Idle` unit struct as a type-state marker.
    - Implements methods on `ManagedAgent<Idle, State>`:
        - `act_on`: Registers an infallible asynchronous message handler.
        - `act_on_fallible`: Registers a fallible asynchronous message handler that returns a `Result`. If the handler returns an `Err`, the framework will attempt to dispatch it to a corresponding error handler.
        - `on_error`: Registers an error handler for a specific `(Message, Error)` pair. The handler receives the `MessageContext` and the concrete error type, allowing for precise, context-aware error handling.
        - `before_start`, `after_start`, `before_stop`, `after_stop`: Registers asynchronous lifecycle callback functions.
        - `create_child`: Allows an idle agent to configure and create child agents.
        - `start`: Transitions the agent from `Idle` to `Started`, spawns its main task loop (`wake`), and returns an `AgentHandle`.
    - Implements `Default` for `ManagedAgent<Idle, State>` to create new idle agents.
    - Implements `From<ManagedAgent<Idle, State>> for ManagedAgent<Started, State>` to define the state transition.
    - Provides the public utility function `downcast_message`.

### `src/actor/managed_agent/started.rs`
- **Role**: Implements the active runtime logic of a running agent.
- **Functionality**:
    - Defines the `Started` unit struct as a type-state marker for active agents.
    - Implements methods on `ManagedAgent<Started, State>`:
        - `new_envelope`, `new_parent_envelope`: Public helpers for creating `OutboundEnvelope`s for sending messages.
        - `wake` (internal): The main asynchronous event loop task. It receives messages from the inbox and dispatches them to registered handlers. For fallible handlers, if an `Err` is returned, it looks up the specific error handler based on the message and error type IDs and executes it. It also handles `SystemSignal::Terminate` and calls lifecycle hooks.
        - `terminate` (internal): Helper function for graceful shutdown. Stops all child agents concurrently before closing the agent's own inbox.

### `src/common/mod.rs`
- **Role**: Defines the `common` module, grouping shared utilities and core types.
- **Functionality**:
    - Declares submodules for specific common components (`types`, `acton`, `acton_inner`, `agent_handle`, `agent_broker`, `agent_runtime`, `agent_reply`).
    - Re-exports key public types (`ActonApp`, `AgentBroker`, `AgentHandle`, `AgentReply`, `AgentRuntime`) from submodules for easier access within the crate and potential inclusion in the prelude.
    - Uses internal types from submodules (`acton_inner`, `types`) and the `message` module.

### `src/common/acton.rs`
- **Role**: Defines the entry point for initializing the Acton system.
- **Functionality**:
    - Defines the `ActonApp` struct (likely a marker type).
    - Provides the public static `launch()` method.
    - `launch()` creates an `ActonApp` and converts it into an `AgentRuntime` using `From<ActonApp>`, triggering the system bootstrap process (e.g., broker initialization).

### `src/common/agent_broker.rs`
- **Role**: Implements the central publish-subscribe message broker.
- **Functionality**:
    - Defines the `AgentBroker` struct, which holds the subscription map (`subscribers`) and its own `AgentHandle`.
    - Implements `Deref`/`DerefMut` to `AgentHandle` for convenience.
    - Provides `initialize` (internal): Creates and starts the broker as a `ManagedAgent`, registering handlers for `BrokerRequest` (triggers broadcast) and `SubscribeBroker` (adds subscriber). Returns the broker's `AgentHandle`.
    - Provides `broadcast` (public static): Takes the subscriber map and a `BrokerRequest`, finds relevant subscribers by message `TypeId`, and sends the message concurrently to all of them.

### `src/common/agent_handle.rs`
- **Role**: Defines `AgentHandle`, the external reference and interaction point for an agent.
- **Functionality**:
    - Contains agent identifier (`id`), message channel (`outbox`), task monitor (`tracker`), optional `parent` and `broker` handles, and a map of `children` handles.
    - Implements `Clone`, `Debug`, `Default`, `PartialEq`, `Eq`, `Hash`. Cloning creates another handle to the same agent.
    - Implements `Subscriber` (provides `get_broker`).
    - Provides `supervise` method to start a child agent and add its handle to the `children` map.
    - Implements `Broker` (forwards `broadcast` to its associated broker handle).
    - Implements `Actor` trait, defining the main interaction interface:
        - Methods for identity (`id`, `name`), message creation (`reply_address`, `create_envelope`), hierarchy (`children`, `find_child`), task tracking (`tracker`), cloning (`clone_ref`).
        - Methods for sending messages to the agent (`send`, `send_sync`).
        - Method for stopping the agent (`stop`).

### `src/common/agent_reply.rs`
- **Role**: Utility for creating standard return types for `act_on` message handlers.
- **Functionality**:
    - Defines the `AgentReply` unit struct (namespace).
    - Provides static methods:
        - `immediate()`: Returns an immediately completing `Pin<Box<dyn Future>>`.
        - `from_async()`: Wraps a given `Future` into the required `Pin<Box<dyn Future>>` type.

### `src/common/agent_runtime.rs`
- **Role**: Represents the initialized Acton system runtime; provides agent management.
- **Functionality**:
    - Defines `AgentRuntime` struct wrapping internal state (`ActonInner`).
    - Provides methods to create/spawn top-level agents (`new_agent...`, `new_agent_with_config`, `spawn_agent...`) and registers them internally.
    - Provides access to system info (`agent_count`) and components (`broker`).
    - Provides `shutdown_all` for graceful system termination.
    - Implements `From<ActonApp>` to bootstrap the system (initialize broker, create runtime state) when `ActonApp::launch()` is called.

### `src/common/types.rs`
- **Role**: Centralizes common internal type definitions and aliases.
- **Functionality**:
    - Defines internal (`pub(crate)`) type aliases for agent implementation details: `ReactorMap`, `FutureHandler`, `FutureBox`, `AgentSender`, `HaltSignal`, `AsyncLifecycleHandler`.
    - Defines `FutureBoxResult`, the return type for fallible handlers. Its `Err` variant is a tuple `(Box<dyn Error>, TypeId)` to carry the error and its `TypeId` for handler dispatch.
    - Defines the public `ReactorItem` enum (wraps `FutureReactor` and `FutureReactorResult`).
    - Defines public type aliases `BrokerRef` and `ParentRef` as semantic wrappers around `AgentHandle`.

### `src/message/mod.rs`
- **Role**: Defines the `message` module, grouping message-related types.
- **Functionality**:
    - Declares submodules for specific message components (`broker_request`, `envelope`, `message_address`, `signal`, etc.).
    - Re-exports key public types (`BrokerRequest`, `BrokerRequestEnvelope`, `MessageAddress`, `OutboundEnvelope`, `SystemSignal`) from submodules for easier access within the crate and potential inclusion in the prelude.

### `src/message/broker_request.rs`
- **Role**: Defines a wrapper for messages intended for broadcast via the broker.
- **Functionality**:
    - Defines the `BrokerRequest` struct containing the message payload (`Arc<dyn ActonMessage>`), its type name (String), and its `TypeId`.
    - Using `Arc` allows efficient sharing of the message data among subscribers.
    - Provides a `new()` constructor to create the request from a concrete message type.

### `src/message/broker_request_envelope.rs`
- **Role**: Defines a specialized envelope for messages broadcast by the broker.
- **Functionality**:
    - Defines the `BrokerRequestEnvelope` struct containing only the message payload (`Arc<dyn ActonMessage>`).
    - Provides a `new()` constructor.
    - Implements `From<BrokerRequest>` to easily extract the message payload for broadcasting.

### `src/message/message_address.rs`
- **Role**: Defines the addressable endpoint of an agent.
- **Functionality**:
    - Defines the `MessageAddress` struct containing the agent's `AgentSender` (MPSC Sender) and its identifying `Ern`.
    - Provides a `name()` method to get the agent's root name.
    - Implements `Default`.

### `src/message/outbound_envelope.rs`
- **Role**: Represents a message prepared for sending, including addressing.
- **Functionality**:
    - Defines the `OutboundEnvelope` struct containing `return_address` and optional `recipient_address` (both `MessageAddress`).
    - Provides constructors (`new`, internal `new_with_recipient`) and getters (`reply_to`, `recipient`).
    - Provides `send` (async) and `reply` (sync wrapper around `send`) methods to dispatch the message payload (wrapped in an internal `Envelope`) to the appropriate MPSC channel based on the addresses.
    - Implements `PartialEq`, `Eq`, `Hash` based on `return_address`.

### `src/message/signal.rs`
- **Role**: Defines system-level control signals.
- **Functionality**:
    - Defines the `SystemSignal` enum (currently only `Terminate`).
    - Marked `#[non_exhaustive]` for future extensibility.
    - Provides `as_str()` for string representation.

### `src/traits/mod.rs`
- **Role**: Defines the `traits` module, aggregating core framework interfaces.
- **Functionality**:
    - Declares submodules for specific trait definitions (`acton_message`, `actor`, `broker`, `subscribable`, `subscriber`).
    - Re-exports key public traits (`ActonMessage`, `AgentHandleInterface`, `Broker`, `Subscribable`, `Subscriber`) from submodules for easier access and inclusion in the prelude.

### `src/traits/acton_message.rs`
- **Role**: Defines the marker trait for all valid messages in the system.
- **Functionality**:
    - Defines the `ActonMessage` trait requiring `DynClone`, `Any`, `Send`, `Sync`, `Debug`.
    - Requires `as_any()` and `as_any_mut()` methods for downcasting trait objects.
    - Provides a blanket implementation `impl<T> ActonMessage for T` for any type `T` satisfying the bounds.

### `src/traits/agent_handle_interface.rs`
- **Role**: Defines the core interface for interacting with agents via their handles.
- **Functionality**:
    - Defines the `AgentHandleInterface` async trait.
    - Specifies methods for identity (`id`, `name`), addressing (`reply_address`), message creation (`create_envelope`), message sending (`send`, `send_sync`), hierarchy (`children`, `find_child`), lifecycle (`stop`), and internal access (`tracker`, `clone_ref`).
    - Provides default implementations for `send` and `send_sync`.
    - Implemented by `AgentHandle`.

### `src/traits/broker.rs`
- **Role**: Defines the interface for message broadcasting capabilities.
- **Functionality**:
    - Defines the `Broker` async trait requiring `Clone`, `Debug`, `Default`.
    - Specifies the core `broadcast()` async method.
    - Provides a default `broadcast_sync()` method that likely relies on an underlying `AgentHandleInterface` implementation.
    - Implemented by `AgentHandle`.

### `src/traits/subscribable.rs`
- **Role**: Defines the interface for actors to manage their message subscriptions.
- **Functionality**:
    - Defines the `Subscribable` async trait.
    - Specifies `subscribe<T>()` and `unsubscribe<T>()` methods.
    - Provides a blanket implementation `impl<T> Subscribable for T` (where `T: Actor + Subscriber + ...`) that sends `SubscribeBroker`/`UnsubscribeBroker` messages to the broker obtained via `get_broker()`.

### `src/traits/subscriber.rs`
- **Role**: Defines the interface for accessing the message broker.
- **Functionality**:
    - Defines the `Subscriber` trait.
    - Specifies the `get_broker()` method to retrieve an `Option<BrokerRef>`.
    - Implemented by `AgentHandle`.

---

## Overall Architecture Summary

The `acton-core` crate provides the foundational components for an asynchronous agent system built on Tokio. Its architecture revolves around several key concepts:

1.  **Agents**: The core computational units are represented by user-defined state (`State`) wrapped within a `ManagedAgent`. `ManagedAgent` handles the runtime aspects, including lifecycle management and message processing, using a type-state pattern (`Idle`, `Started`).
2.  **Handles (`AgentHandle`)**: Interaction with agents happens exclusively through `AgentHandle`s. These handles provide methods for sending messages (`send`, `send_sync`), managing lifecycle (`stop`), supervising children (`supervise`), and accessing agent metadata. They implement the core `AgentHandleInterface` trait.
3.  **Messaging**: Communication occurs via asynchronous message passing using Tokio MPSC channels (`AgentSender`). Messages must implement the `ActonMessage` marker trait. Envelopes (`OutboundEnvelope`, internal `Envelope`) wrap messages with sender/recipient addressing (`MessageAddress`).
4.  **Message & Error Handling**: Agents register message handlers using `act_on` (for infallible operations) or `act_on_fallible` (for operations that return a `Result`). When a `Started` agent receives a message, its `wake` loop dynamically dispatches it to the appropriate handler based on the message's `TypeId`.
5.  **Context-Aware Error Handling**: If a fallible handler returns an `Err`, the framework uses the combination of the message's `TypeId` and the error's `TypeId` to look up and execute a specific error handler registered with `on_error`. This gives the developer access to the original message context when handling the error, enabling robust and precise recovery logic.
6.  **Publish/Subscribe (`AgentBroker`)**: A central `AgentBroker` agent manages topic-based subscriptions. Actors use the `Subscribable` trait (via their `AgentHandle`) to send `SubscribeBroker` messages to the broker. The `Broker` trait (implemented by `AgentHandle`) allows sending `BrokerRequest` messages to the broker, which then uses its internal subscription map to `broadcast` the message payload to all interested subscribers.
7.  **Lifecycle Management**: Agents have distinct `Idle` and `Started` states. Lifecycle hooks (`before_start`, `after_start`, etc.) allow custom logic execution during state transitions and shutdown. The `stop` method on `AgentHandle` initiates graceful shutdown using `SystemSignal::Terminate` and `TaskTracker`.
8.  **Supervision**: `AgentHandle`s maintain a map of their direct `children` and provide methods (`supervise`, `find_child`) to manage the hierarchy. Termination propagates down the hierarchy (`terminate` stops children).
9.  **System Runtime (`AgentRuntime`)**: The `ActonApp::launch()` function initializes the system (including the broker) and returns an `AgentRuntime`, which acts as the main entry point for creating top-level agents and managing the overall system lifecycle (`shutdown_all`).
10. **Traits**: Core functionalities are defined through traits (`Actor`, `Broker`, `Subscriber`, `Subscribable`, `ActonMessage`), promoting composability and abstraction. Blanket implementations are provided for convenience.
11. **Prelude**: A `prelude` module re-exports the most commonly used public types and traits for easy import by users of the main `acton-reactive` crate.

Overall, `acton-core` establishes a robust, asynchronous, message-passing framework with clear separation of concerns for agent state, runtime management, communication, and lifecycle.