/protean:refactor-introduce-eventsfrom protean
Introduces domain events to replace direct cross-aggregate calls and synchronous side effects. Detects transaction boundary violations (handlers modifying multiple aggregates) and refactors into event-driven flows with proper aggregate isolation.
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.
Illustrative, guided refactoring. This is a before→after walkthrough, not an automated transform: recognize the smell and apply the change yourself, adapting to the code at hand. The
introduce_events_*_before.pyasset is the intentional starting point (cross-aggregate coupling); the*_after.pyasset shows the event-driven target.
Replace direct cross-aggregate calls with domain events and event handlers, establishing proper transaction boundaries and enabling eventual consistency.
| Output | Purpose |
|---|---|
| Domain events | @domain.event classes for each state change |
| Event raises | self.raise_() calls in aggregate methods |
| Event handlers | @domain.event_handler for cross-aggregate side effects |
| Updated handlers | Single-aggregate command handlers |
The primary signal is a handler that modifies two or more aggregate types:
# fragment
# RED FLAG: two aggregates modified in one handler
@handle(PlaceOrder)
def place_order(self, command):
order = Order.create(...)
domain.repository_for(Order).add(order)
# VIOLATION: second aggregate in same transaction
inventory = domain.repository_for(Inventory).get(command.product_id)
inventory.reduce(command.quantity)
domain.repository_for(Inventory).add(inventory)
Operations that should be reactions to events but are coded as direct calls:
# fragment
# RED FLAG: side effects in command handler
@handle(CompleteOrder)
def complete_order(self, command):
order = domain.repository_for(Order).get(command.order_id)
order.complete()
domain.repository_for(Order).add(order)
# These should be event-driven reactions
send_confirmation_email(order)
update_analytics(order)
notify_warehouse(order)
Aggregate methods that reference other aggregates:
# fragment
# RED FLAG: aggregate knows about another aggregate
class Order:
def place(self):
self.status = "PLACED"
# Aggregate should not access other aggregates
inventory = domain.repository_for(Inventory).get(self.product_id)
inventory.reduce(self.quantity)
List the aggregates the handler modifies. The one the command belongs to is the source; each other one becomes event-driven.
The steps below use the handler's PlaceOrder command, the Inventory aggregate
it reaches into, and the ReserveStock command that Inventory will handle:
@domain.command(part_of="Order")
class PlaceOrder:
customer_id = String(required=True)
product_id = String(required=True)
quantity = Integer(required=True, min_value=1)
unit_price = Decimal(precision=19, scale=4, required=True)
@domain.aggregate
class Inventory:
product_id = String(required=True, identifier=True)
available = Integer(default=0)
reserved_order_ids = List(content_type=String)
def reserve(self, order_id: str, quantity: int) -> None:
if self.available < quantity:
raise ValueError("Insufficient stock")
self.available -= quantity
self.reserved_order_ids = [*self.reserved_order_ids, order_id]
@domain.command(part_of="Inventory")
class ReserveStock:
order_id = Identifier(required=True)
product_id = String(required=True)
quantity = Integer(required=True, min_value=1)
Create an event representing what happened to the source aggregate:
@domain.event(part_of="Order")
class OrderPlaced:
order_id = Identifier(required=True)
customer_id = String(required=True)
product_id = String(required=True)
quantity = Integer(required=True)
total_amount = Decimal(precision=19, scale=4, required=True)
Event naming: past tense of what happened: OrderPlaced, PaymentProcessed, TicketEscalated.
Event fields: include everything the event handler needs. The handler shouldn't need to look up the source aggregate to get context.
An event with no fields carries nothing beyond its name, so a handler cannot react to what
actually changed. check reports that as EVENT_WITHOUT_DATA. Add the fields that capture
the change, or confirm the event is meant as a bare signal.
from decimal import Decimal as D
@domain.aggregate
class Order:
customer_id = String(required=True)
status = String(default="DRAFT")
total = Decimal(precision=19, scale=4, default=0)
def place(self, product_id: str, quantity: int, price: D) -> None:
self.status = "PLACED"
self.total = price * quantity
self.raise_(
OrderPlaced(
order_id=self.id,
customer_id=self.customer_id,
product_id=product_id,
quantity=quantity,
total_amount=self.total,
)
)
Raise the event from the aggregate or entity method that makes the change it records. An
event nothing raises there is reported as UNRAISED_EVENT. The check reads only aggregate
and entity method bodies, so an event raised from a command handler, a subscriber, or a
module-level factory still shows up; that is the signal to move the raise onto the aggregate
method, which is the refactor this skill performs.
The event handler sits in Order's cluster, because it reacts to Order's own
event. It issues a command to Inventory, and Inventory's command handler does
the write:
@domain.event_handler(part_of=Order)
class InventoryReservation:
@handle(OrderPlaced)
def on_order_placed(self, event: OrderPlaced) -> None:
current_domain.process(
ReserveStock(
order_id=event.order_id,
product_id=event.product_id,
quantity=event.quantity,
)
)
Events are delivered at least once, so the receiving command handler must be safe
to repeat. ReserveStock carries the order id from the event. Inventory keeps
the order ids it has already reserved stock for, and the handler returns without
changes when it sees one again:
@domain.command_handler(part_of=Inventory)
class InventoryCommandHandler:
@handle(ReserveStock)
def reserve_stock(self, command: ReserveStock) -> None:
repo = current_domain.repository_for(Inventory)
inventory = repo.get(command.product_id)
if command.order_id in inventory.reserved_order_ids:
return # already reserved for this order
inventory.reserve(command.order_id, command.quantity)
repo.add(inventory)
Inventory.reserve() reduces the stock and appends the order id to
reserved_order_ids. Use the order id from the event, never a fresh uuid4(),
or a repeat cannot be recognized.
Key points:
part_of = the cluster that owns the event (Order), with no stream_categorypart_of the target aggregate (Inventory)A handler in Inventory's cluster that handles OrderPlaced is what check
reports as EVENT_HANDLER_FOREIGN_EVENT. For a flow with several causally
dependent steps, use a process manager.
Remove the cross-aggregate logic. The event handler takes over:
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def place_order(self, command: PlaceOrder) -> None:
order = Order(customer_id=command.customer_id)
order.place(
product_id=command.product_id,
quantity=command.quantity,
price=command.unit_price,
)
domain.repository_for(Order).add(order)
# Inventory update happens via OrderPlaced event handler
# In conftest.py or test setup
domain.config["event_processing"] = "sync"
domain.config["command_processing"] = "sync"
This ensures events, and the commands their handlers issue, are processed inline during tests.
Event too fat: Including the entire aggregate state in every event wastes space and couples consumers to the full schema. Include only what changed and context needed.
Returning values from event handlers: Event handlers are fire-and-forget. They don't return values. If you need a return, use a command handler.
Circular events: A handles B's events, B handles A's events. This creates infinite loops. Design event flows as DAGs (directed acyclic graphs).
check and resolve what it reportsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
39 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".npx claudepluginhub proteanhq/protean --plugin proteanOther plugins' skills for the same job