/protean:process-managerfrom protean
Defines Protean process managers: stateful, event-driven coordinators for multi-step business processes spanning aggregates. Handles correlation, lifecycle, and command issuance for sagas and workflows.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A process manager coordinates a business process that spans several aggregates. It reacts to their events, keeps its own state between them, and issues commands to move the process forward. This skill defines process managers: correlation, lifecycle and command issuance.
from protean import Domain, handle
from protean.fields import Decimal, Identifier, String
domain = Domain(__file__, "ecommerce")
@domain.event(part_of="Order")
class OrderPlaced:
order_id: Identifier(required=True)
customer_id: Identifier(required=True)
total: Decimal(precision=19, scale=4, required=True)
@domain.event(part_of="Payment")
class PaymentConfirmed:
payment_id: Identifier(required=True)
order_id: Identifier(required=True)
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
total: Decimal(precision=19, scale=4, required=True)
@domain.aggregate
class Payment:
order_id: Identifier(required=True)
@domain.process_manager(
stream_categories=["ecommerce::order", "ecommerce::payment"]
)
class OrderFulfillmentPM:
order_id: Identifier()
status: String(default="new")
@handle(OrderPlaced, start=True, correlate="order_id")
def on_order_placed(self, event: OrderPlaced) -> None:
self.order_id = event.order_id
self.status = "awaiting_payment"
@handle(PaymentConfirmed, correlate="order_id", end=True)
def on_payment_confirmed(self, event: PaymentConfirmed) -> None:
self.status = "completed"
stream_categories or aggregates: PM must subscribe to at least one event stream: @domain.process_manager(stream_categories=["domain::order", "domain::payment"]). Alternatively, pass aggregates=[Order, Payment] and Protean infers the stream categories@handle with PM-specific parameters: Each handler uses @handle(EventClass, start=..., correlate=..., end=...). These three parameters control lifecycle and routingcorrelate: Maps events to PM instances: correlate="order_id" (string) or correlate={"order_id": "ext_order_ref"} (dict when names differ)start=True: The entry point that creates new PM instances. Protean enforces at least one; a PM with none fails at domain.init() with IncorrectUsageError. If a non-start event arrives with no existing PM, it is silently skippeddef method_name(self, event: EventType) -> Nonehandle from protean: from protean import handle (not from protean.core or protean.utils)current_domain.process(): Import from protean: from protean import current_domain. Call current_domain.process(CommandClass(...)) to drive other aggregatesend=True. check reports PROCESS_MANAGER_UNCLOSED for a process manager with no end=True handler, even when a handler calls self.mark_as_complete(). Without a terminal state, the PM accepts events indefinitely| Option | Purpose | Required |
|---|---|---|
stream_categories | List of stream categories to subscribe to | Yes (unless aggregates provided) |
aggregates | List of aggregate classes (categories inferred) | Alternative to stream_categories |
stream_category | Stream name the PM's own transition events are written to; derived from the class name if unset | No |
subscription_type | "stream" or "event_store" | No |
subscription_profile | "production", "fast", "batch", "debug", "projection" | No |
subscription_config | Custom config dict (messages_per_tick, max_retries, etc.) | No |
sequential_by | True opts into per-instance sequential processing, partitioned by the field the subscribed category's correlate spec maps to | No |
suppress_checks | Diagnostic codes to suppress for this process manager | No |
When PM field names differ from event field names, use a dictionary:
@domain.aggregate
class Invoice:
ext_order_ref: Identifier(required=True)
@domain.event(part_of=Invoice)
class ExternalPaymentReceived:
ext_order_ref: Identifier(required=True)
@domain.event(part_of=Invoice)
class ReconciliationCompleted:
ext_order_ref: Identifier(required=True)
@domain.process_manager(aggregates=[Invoice])
class PaymentReconciliationPM:
order_id: Identifier()
status: String(default="pending")
@handle(
ExternalPaymentReceived,
start=True,
correlate={"order_id": "ext_order_ref"},
)
def on_payment_received(self, event: ExternalPaymentReceived) -> None:
self.order_id = event.ext_order_ref
self.status = "received"
@handle(
ReconciliationCompleted,
correlate={"order_id": "ext_order_ref"},
end=True,
)
def on_reconciled(self, event: ReconciliationCompleted) -> None:
self.status = "reconciled"
This extracts event.ext_order_ref and uses its value to find the PM instance whose order_id holds it.
Process managers drive other aggregates forward by issuing commands:
# fragment
from protean import current_domain
@handle(OrderPlaced, start=True, correlate="order_id")
def on_order_placed(self, event: OrderPlaced) -> None:
self.order_id = event.order_id
self.status = "awaiting_payment"
current_domain.process(
RequestPayment(order_id=event.order_id, amount=event.total)
)
If the handler fails after issuing a command, the process manager's own state change rolls back. Whether the command is written at all depends on the event store. The memory store writes the command through the handler's Unit of Work, so the failure discards it. Message-DB writes straight through on its own connection, so there the command survives while the transition does not. Do not rely on either behavior. Keep issued commands idempotent so re-issuing one is safe.
| Aspect | Event Handler | Process Manager |
|---|---|---|
| State | Stateless | Stateful (event-sourced) |
| Correlation | None | Explicit via correlate |
| Lifecycle | N/A | start → intermediate → end |
| Persistence | None | Auto-generated transition events |
| Multi-stream | Typically single aggregate | Multiple aggregate streams |
Use an event handler when each event is handled independently with no memory of prior events.
Use a process manager when you need to track state across multiple events from different aggregates to coordinate a multi-step business process.
Override handle_error classmethod for custom error recovery during async processing:
import logging
logger = logging.getLogger(__name__)
@domain.aggregate
class Account:
email: String(required=True)
@domain.event(part_of=Account)
class AccountCreated:
account_id: Identifier(required=True)
@domain.event(part_of=Account)
class EmailVerified:
account_id: Identifier(required=True)
@domain.process_manager(aggregates=[Account])
class OnboardingPM:
account_id: Identifier()
status: String(default="new")
@handle(AccountCreated, start=True, correlate="account_id")
def on_account_created(self, event) -> None:
self.account_id = event.account_id
self.status = "awaiting_verification"
@handle(EmailVerified, correlate="account_id", end=True)
def on_email_verified(self, event) -> None:
self.status = "verified"
@classmethod
def handle_error(cls, exc: Exception, message) -> None:
logger.error(f"Onboarding PM failed: {exc}")
# fragment
from decimal import Decimal as D
# WRONG: PM is doing business validation
@handle(PaymentConfirmed, correlate="order_id")
def on_payment_confirmed(self, event):
if event.amount < self.total * D("0.95"):
current_domain.process(RejectPayment(...))
Instead: Keep business logic in aggregates. PM only coordinates.
A PM without end=True or mark_as_complete() on any handler never finishes, and its stream keeps growing (Key rule 9). The PROCESS_MANAGER_UNCLOSED diagnostic reads the decorator flag only. It never inspects mark_as_complete() calls, so a PM that completes that way alone is still reported. Mark the terminating handler end=True to clear it, or pass suppress_checks=("PROCESS_MANAGER_UNCLOSED",) to @domain.process_manager when completion is genuinely decided at runtime.
Each handler's correlate is resolved independently, by getattr(event, field_name), and the PM instance is looked up purely by that value. OrderPlaced using order_id and PaymentConfirmed using payment_order_id route to the same instance correctly as long as both hold the same value. Dictionary correlate, correlate={"order_id": "payment_order_id"}, resolves the same way; use it to document the mapping for readers.
event-handler: Stateless event handlers (contrast with stateful PM)event: Events are the input to process managersaggregate: Process managers coordinate aggregatescommand: Process managers issue commands to drive aggregatescommand-handler: Commands issued by PMs are processed by command handlerscheck and resolve what it reportsassets/pm_basic.py (opens in a new tab)assets/pm_command_issuance.py (opens in a new tab)assets/pm_dict_correlation.py (opens in a new tab)assets/pm_error_handling.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/command-issuance.md (opens in a new tab)references/correlation.md (opens in a new tab)references/lifecycle.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar"./add-eventAdd a complete event flow to an existing aggregate. It creates a domain event, adds or updates an aggregate method that raises the event via self.raise_(), and wires an event handler that processes the event and performs specified side effects (such as syncing state across aggregates, sending notifications, or triggering downstream processes). This is the primary workflow for adding reactive, event-driven behavior to a Protean domain. Use when the user wants to "add an event", "add a domain event", "add a reaction to a state change", "add a side effect", "create an event flow", "wire an event handler", "add event-driven behavior", "react to a state change", "sync aggregates on event", or describes something that happened or should happen (like "when an order is placed, reduce inventory", "after payment is confirmed, send a notification", "when a user registers, create a welcome email", "notify the warehouse when an order ships"). This workflow composes the event, aggregate, and event-handler element skills./add-fieldAdd fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases./add-read-modelBuild a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view", "add a dashboard query model", or when they need to combine data from multiple aggregates into one queryable structure./add-saga-flowBuild a complete saga in Protean using a process manager that coordinates a multi-step flow across several aggregates. The saga reacts to domain events, issues commands to drive each aggregate forward, tracks its own state, and closes on a terminal handler with a compensating path for failures. Use when the user asks to "add a saga", "coordinate a multi-step process", "orchestrate a workflow across aggregates", "manage order fulfillment", "add a process manager flow", "compensate on failure", "roll back a distributed transaction", or when they describe a flow like "reserve stock, take payment, then ship, and undo the reservation if payment fails".Other plugins' skills for the same job