/protean:add-domain-service-flowfrom protean
Guides building domain services in Protean for business logic spanning multiple aggregates. Handles cross-aggregate validation, invariants, and wiring into command/event handlers.
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 domain service encapsulates business logic that spans multiple aggregates. It is stateless, operates on aggregates passed to it, and validates cross-aggregate invariants.
Do NOT use one for:
| Component | Purpose | Decorator |
|---|---|---|
| Domain service | Cross-aggregate validation + the change to the primary aggregate | @domain.domain_service(part_of=[Agg1, Agg2]) |
| Pre/post invariants | Validate conditions across aggregates | @invariant.pre / @invariant.post on service |
| Command handler | Load aggregates → run service → persist the primary aggregate | @domain.command_handler(part_of=Agg1) |
| Event handler | React to the primary aggregate's event and issue a command to the other aggregate | @domain.event_handler(part_of=Agg1) |
| Command handler | Apply the change to the other aggregate, once | @domain.command_handler(part_of=Agg2) |
A domain service reads several aggregates, but a handler persists only one of them. The service checks the rule across all the aggregates and changes only the primary aggregate, the one the command belongs to. The command handler persists that aggregate. The primary aggregate raises an event, and an event handler in its cluster issues a command to the other aggregate. That aggregate's command handler applies the change in a transaction separate from the primary aggregate's. With async command processing, the default, the command handler commits on its own. With sync command processing, it joins the event handler's transaction.
The service checks every aggregate in one step, before anything changes. The change to the other aggregate is eventually consistent: it happens after the primary aggregate commits, and there is a short window where the two disagree. If that change fails, the primary aggregate stays changed. Nothing undoes it on its own. Undoing it takes a compensating command, for example one sent by a process manager.
The service sees each other aggregate as it was last saved. Two commands that arrive before the first one's event is delivered both pass a check such as "enough stock" or "at most three reservations", so the rule can be broken during that window. A rule that must never be broken belongs inside one aggregate.
On the SQL providers, a Unit of Work is one real database transaction, and it can hold changes to several aggregates. Elasticsearch has no transactions, so there the Unit of Work logs a warning that commit and rollback are not atomic. "One aggregate per transaction" is a design rule, and the Unit of Work does not enforce it. See ADR-0027 (The Unit of Work is a real database transaction) and ADR-0031 (A handler method persists or calls out, never both).
Before building a domain service flow:
The examples on this page use these aggregates, commands, and events:
@domain.event(part_of="Order")
class OrderConfirmed:
order_id: Identifier(required=True)
product_id: Identifier(required=True)
quantity: Integer(required=True)
@domain.aggregate
class Order:
product_id: Identifier(required=True)
quantity: Integer(required=True)
status: String(default="pending")
def confirm(self):
self.status = "confirmed"
self.raise_(
OrderConfirmed(
order_id=self.id,
product_id=self.product_id,
quantity=self.quantity,
)
)
@domain.aggregate
class Inventory:
product_id: Identifier(required=True)
available: Integer(default=0)
reserved_order_ids: List(content_type=String)
def reserve_stock(self, order_id, quantity):
# The service checked the stock as it was last saved. Another order
# may have taken it since, so check again before taking it.
if quantity > self.available:
raise ValidationError({"available": ["Insufficient stock"]})
self.available -= quantity
self.reserved_order_ids = [*self.reserved_order_ids, order_id]
@domain.command(part_of="Order")
class PlaceOrder:
order_id: Identifier(required=True)
@domain.command(part_of="Inventory")
class ReserveStock:
order_id: Identifier(required=True)
product_id: Identifier(required=True)
quantity: Integer(required=True)
Use the callable pattern: __init__ accepts aggregates, __call__ executes the logic.
@domain.domain_service(part_of=[Order, Inventory])
class PlaceOrderService:
def __init__(self, order, inventory):
self.order = order
self.inventory = inventory
def __call__(self):
self.order.confirm()
Key rules:
part_of=[Agg1, Agg2]: list the aggregate classes the service spans__init__ is enough. The invariants are wired when the service is registered, so you do not need to call the base class __init____call__ executes the business logic and changes only the primary aggregate (here, the Order)Pre-invariants validate before execution. Post-invariants validate after. Add them as methods on the service:
# fragment
@invariant.pre
def sufficient_stock(self):
if self.inventory.available < self.order.quantity:
raise ValidationError({"_service": ["Insufficient stock"]})
@invariant.post
def order_is_confirmed(self):
if self.order.status != "confirmed":
raise ValidationError({"_service": ["Order was not confirmed"]})
Invariants run around every public method of the service, including __call__. If one public method calls another, the invariants run again for the inner call. Name helper methods with a leading _ so they are not wrapped. An invariant must never call a public method: that method's wrapper runs the invariant again, which calls the method again, until Python's recursion limit stops the call.
The command handler loads the aggregates, runs the service, and persists the primary aggregate.
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def handle_place_order(self, command):
order_repo = current_domain.repository_for(Order)
order = order_repo.get(command.order_id)
inventory = current_domain.repository_for(Inventory).find_by(
product_id=order.product_id
)
# Run domain service (pre checks → logic → post checks)
PlaceOrderService(order, inventory)()
# Persist only the aggregate the service changed
order_repo.add(order)
Important: The command handler persists the Order. The service changes the Order and saves nothing. The Inventory was read for the check, and it changes in Step 4.
An event handler in the Order's cluster reacts to OrderConfirmed and issues a command that belongs to Inventory. Inventory's command handler applies the change and skips an order it has already applied, because an event can be delivered more than once.
@domain.event_handler(part_of=Order)
class ReserveConfirmedStock:
@handle(OrderConfirmed)
def on_order_confirmed(self, event):
current_domain.process(
ReserveStock(
order_id=event.order_id,
product_id=event.product_id,
quantity=event.quantity,
)
)
@domain.command_handler(part_of=Inventory)
class InventoryCommandHandler:
@handle(ReserveStock)
def reserve_stock(self, command):
repo = current_domain.repository_for(Inventory)
inventory = repo.find_by(product_id=command.product_id)
if command.order_id in inventory.reserved_order_ids:
return # already applied; reserving again would double count
inventory.reserve_stock(command.order_id, command.quantity)
repo.add(inventory)
part_of=Order: the event handler sits in the cluster that owns OrderConfirmed, with no stream_categoryf"{order_id}:{product_id}". Add up the lines for the same product first, so each product gets one write. Two lines for one product would otherwise share an id, and the handler would skip the second as a repeatreserved_order_ids grows with every order and loads with the Inventory each timeThis is the cross-aggregate pattern from the event-handler skill.
domain.init(traverse=False)
with domain.domain_context():
order = Order(product_id="SKU-1", quantity=2)
inventory = Inventory(product_id="SKU-1", available=5)
# Instantiate with aggregates, then call
service = PlaceOrderService(order, inventory)
service() # Runs: pre invariants → __call__ → post invariants
assert order.status == "confirmed"
You can still call super().__init__(order, inventory) in __init__. It stores the aggregates on self._aggregates; it is not needed for the invariants.
| Pattern | Scope | Persistence | Use case |
|---|---|---|---|
| Aggregate method | Single aggregate | Via handler | Logic belonging to one aggregate |
| Domain service | Multiple aggregates | Via handler | Cross-aggregate business rules |
| Command handler | Orchestration | Yes (repository) | Loading, wiring, persisting one aggregate |
| Event handler | Reaction | No (issues a command) | Changing another aggregate after an event |
# fragment
# Wrong! The service persists
class PlaceOrderService:
def __call__(self):
self.order.confirm()
current_domain.repository_for(Order).add(self.order) # No
Instead: keep the service stateless; the calling command handler persists the primary aggregate.
# fragment
# Wrong! Two aggregates in one handler
@handle(PlaceOrder)
def handle_place_order(self, command):
...
PlaceOrderService(order, inventory)()
current_domain.repository_for(Order).add(order)
current_domain.repository_for(Inventory).add(inventory) # No
Instead: change and persist only the primary aggregate, and change the other one through an event and a command (Step 4).
# fragment
# Wrong! Only one aggregate is involved
@domain.domain_service(part_of=[Order])
class CancelOrderService:
...
Instead: put single-aggregate logic on the aggregate itself; reach for a domain service only when 2+ aggregates participate.
# fragment
# Wrong! stock_for() is public, so it is wrapped with the invariants
@domain.domain_service(part_of=[Order, Inventory])
class PlaceOrderService:
def stock_for(self, product_id):
return self.inventory.available
@invariant.pre
def sufficient_stock(self):
if self.stock_for(self.order.product_id) < self.order.quantity: # No
raise ValidationError({"_service": ["Insufficient stock"]})
The call to stock_for() runs the pre-invariants again, which call stock_for() again, until Python's recursion limit stops the call. Instead: name the helper _stock_for(). Methods that start with _ are not wrapped.
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-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.npx claudepluginhub proteanhq/protean --plugin proteanOther plugins' skills for the same job