/protean:domain-servicefrom protean
Defines a Protean domain service — a stateless orchestrator for complex business logic spanning multiple aggregates. Supports callable classes, instance methods, and class methods with pre/post invariants.
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.
Domain services are stateless orchestrators for complex business logic that spans multiple aggregates. They exist because some domain operations naturally involve more than one aggregate and shouldn't be forced into either.
part_ofThe examples on this page use these aggregates. Order.confirm() raises OrderConfirmed with the items, so the inventory side can reserve stock when it handles the event. Order.cancel() does the same with OrderCancelled, so the inventory side can release the stock.
from protean.exceptions import ValidationError
@domain.event(part_of="Order")
class OrderConfirmed:
order_id: Identifier(required=True)
items = List(content_type=Dict)
@domain.event(part_of="Order")
class OrderCancelled:
order_id: Identifier(required=True)
items = List(content_type=Dict)
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
payment_id: Identifier()
items = HasMany("OrderItem")
status: String(default="PENDING")
def confirm(self):
self.status = "CONFIRMED"
self.raise_(OrderConfirmed(order_id=self.id, items=self._item_quantities()))
def cancel(self):
self.status = "CANCELLED"
self.raise_(OrderCancelled(order_id=self.id, items=self._item_quantities()))
def _item_quantities(self):
return [
{"product_id": item.product_id, "quantity": item.quantity}
for item in self.items
]
@domain.entity(part_of=Order)
class OrderItem:
product_id: Identifier(required=True)
quantity: Integer(required=True)
price: Decimal(precision=19, scale=4, default=0)
@domain.aggregate
class Inventory:
product_id: Identifier(required=True)
quantity: Integer(default=0)
def reserve_stock(self, quantity):
self.quantity -= quantity
def release_stock(self, quantity):
self.quantity += quantity
Inventory.reserve_stock() and release_stock() are called by the inventory's own command handler, never by the domain service. An event handler in the order's cluster reacts to OrderConfirmed or OrderCancelled and issues a command to the inventory. The add-domain-service-flow skill builds that whole flow, and the event-handler skill's cross-aggregate reference shows the event handler.
A domain service is registered with the aggregate classes it works on, @domain.domain_service(part_of=[Order, Inventory]). The three flavors below differ in how you call it.
__call__)Best for a single business operation. Instantiate and call:
@domain.domain_service(part_of=[Order, Inventory])
class place_order:
def __init__(self, order, inventories):
super().__init__(order, inventories)
self.order = order
self.inventories = inventories
@invariant.pre
def inventory_should_have_sufficient_stock(self):
stock = {i.product_id: i.quantity for i in self.inventories}
# Lines for the same product draw on the same stock, so add them up.
ordered: dict[str, int] = {}
for item in self.order.items:
ordered[item.product_id] = ordered.get(item.product_id, 0) + item.quantity
for product_id, quantity in ordered.items():
if stock.get(product_id, 0) < quantity:
raise ValidationError({"_service": ["Product is out of stock"]})
def __call__(self):
self.order.confirm()
# Usage: place_order(order, [inventory])()
Best for multiple related operations on the same aggregates. A pre invariant runs before every public method, so a check that applies to one operation only goes in a _ helper that the operation calls:
@domain.domain_service(part_of=[Order, Inventory])
class OrderFulfillmentService:
def __init__(self, order, inventories):
super().__init__(order, inventories)
self.order = order
self.inventories = inventories
def place_order(self):
self._check_stock()
self.order.confirm()
def cancel_order(self):
self.order.cancel()
def _check_stock(self):
stock = {i.product_id: i.quantity for i in self.inventories}
# Lines for the same product draw on the same stock, so add them up.
ordered: dict[str, int] = {}
for item in self.order.items:
ordered[item.product_id] = ordered.get(item.product_id, 0) + item.quantity
for product_id, quantity in ordered.items():
if stock.get(product_id, 0) < quantity:
raise ValidationError({"_service": ["Product is out of stock"]})
# Usage:
# service = OrderFulfillmentService(order, [inventory])
# service.place_order()
Best for a stateless, functional style with no invariants. Protean does not run the service's @invariant.pre or @invariant.post methods around a class method, so a class-method service should not declare any. Protean still wraps a public class method, and treats its first argument as the service instance. It runs the first argument's own invariants around the call, so that argument must be an aggregate: a list there raises AttributeError. A call on an instance raises TypeError, because the instance is passed as one argument too many. Validate inside the method, and call it on the class:
@domain.domain_service(part_of=[Order, Inventory])
class StockReservationService:
@classmethod
def place_order(cls, order, inventories):
stock = {i.product_id: i.quantity for i in inventories}
# Lines for the same product draw on the same stock, so add them up.
ordered: dict[str, int] = {}
for item in order.items:
ordered[item.product_id] = ordered.get(item.product_id, 0) + item.quantity
for product_id, quantity in ordered.items():
if stock.get(product_id, 0) < quantity:
raise ValidationError({"_service": ["Product is out of stock"]})
order.confirm()
return order
# Usage:
# order = StockReservationService.place_order(order, [inventory])
part_of=[Agg1, Agg2] is required. A domain service with fewer than two aggregates raises IncorrectUsageError. Pass the aggregate classes, not their names as strings.@domain.domain_service decorator: Or register with domain.register(MyService, part_of=[Agg1, Agg2]).super().__init__() stores the aggregates: BaseDomainService.__init__ saves the aggregates it receives on self._aggregates, and does nothing else. Call it when your code reads self._aggregates. Protean wires invariants when it registers the service, so a service whose __init__ leaves the call out still runs its invariants.@invariant.pre and @invariant.post for validations that involve multiple aggregates._: Protean wraps every public instance method and __call__ with the invariant checks. A public helper called from another public method runs the pre and post invariants again, against the state the outer method has reached so far. If that half-finished state breaks an invariant, the helper raises ValidationError before the outer method completes. An invariant that calls a public helper fails: the helper's wrapper runs the invariant again, which calls the helper again, until Python's recursion limit stops the call. A method whose name starts with _ is not wrapped.event-handler skill's cross-aggregate reference and the add-domain-service-flow skill.| Option | Purpose | Required | Default |
|---|---|---|---|
part_of | List of 2+ aggregate classes this service orchestrates | Yes | None |
suppress_checks | Diagnostic codes protean check should not report for this service | No | () |
Domain services support @invariant.pre and @invariant.post decorators for cross-aggregate validation:
@domain.domain_service(part_of=[Order, Inventory])
class PlaceOrderService:
def __init__(self, order, inventories):
super().__init__(order, inventories)
self.order = order
self.inventories = inventories
@invariant.pre
def inventory_should_have_sufficient_stock(self):
stock = {i.product_id: i.quantity for i in self.inventories}
# Lines for the same product draw on the same stock, so add them up.
ordered: dict[str, int] = {}
for item in self.order.items:
ordered[item.product_id] = ordered.get(item.product_id, 0) + item.quantity
for product_id, quantity in ordered.items():
if stock.get(product_id, 0) < quantity:
raise ValidationError({"_service": ["Product is out of stock"]})
@invariant.post
def order_should_be_confirmed(self):
if self.order.status != "CONFIRMED":
raise ValidationError({"_service": ["Order was not confirmed"]})
def __call__(self):
self.order.confirm()
ValidationErrorCalling the services:
domain.init(traverse=False)
with domain.domain_context():
order = Order(
customer_id="CUST-1",
items=[OrderItem(product_id="PROD-1", quantity=2, price=10.0)],
)
inventory = Inventory(product_id="PROD-1", quantity=1)
# The pre invariant fails, so __call__ does not run
try:
PlaceOrderService(order, [inventory])()
except ValidationError as exc:
assert exc.messages == {"_service": ["Product is out of stock"]}
else:
raise AssertionError("expected the pre invariant to fail")
assert order.status == "PENDING"
inventory = Inventory(product_id="PROD-1", quantity=5)
PlaceOrderService(order, [inventory])()
assert order.status == "CONFIRMED"
# The service reads the inventory but does not change it
assert inventory.quantity == 5
# The event carries what the inventory side needs to reserve stock
assert order._events[-1].items == [{"product_id": "PROD-1", "quantity": 2}]
# The class-method flavor validates inline
order = Order(
customer_id="CUST-1",
items=[OrderItem(product_id="PROD-1", quantity=9)],
)
try:
StockReservationService.place_order(order, [inventory])
except ValidationError as exc:
assert exc.messages == {"_service": ["Product is out of stock"]}
else:
raise AssertionError("expected the inline check to fail")
assert order.status == "PENDING"
# fragment
# Wrong - raises IncorrectUsageError
@domain.domain_service(part_of=[Order])
class OrderService:
...
If your logic only involves one aggregate, it belongs in the aggregate itself.
# fragment
# Wrong - domain services don't handle persistence
def place_order(self):
self.order.confirm()
domain.repository_for(Order).add(self.order) # Don't do this!
# fragment
# Wrong - calculate_total is public, so it is wrapped with the invariant
# checks. The invariant calls it, its wrapper runs the invariant again, and
# so on until Python's recursion limit stops the calls.
@invariant.post
def total_should_be_positive(self):
if self.calculate_total() <= 0:
raise ValidationError({"_service": ["Order total must be positive"]})
def calculate_total(self):
return sum(item.quantity * item.price for item in self.order.items)
# fragment
# Correct - the underscore prefix keeps the helper unwrapped
@invariant.post
def total_should_be_positive(self):
if self._calculate_total() <= 0:
raise ValidationError({"_service": ["Order total must be positive"]})
def _calculate_total(self):
return sum(item.quantity * item.price for item in self.order.items)
aggregate: Domain aggregates that domain services orchestratecommand-handler: Where domain services are typically invoked fromadd-domain-service-flow: The whole flow: the service, the command handler that persists the primary aggregate, and the event handler and command that change the other aggregateevent-handler: Its cross-aggregate reference shows the event handler that issues a command to the other aggregateevent: Events raised by aggregates during domain service operationsvalue-object: Value objects used within aggregates passed to domain servicescheck and resolve what it reportsassets/domain_service_callable.py (opens in a new tab)assets/domain_service_class_methods.py (opens in a new tab)assets/domain_service_instance_methods.py (opens in a new tab)assets/domain_service_with_invariants.py (opens in a new tab)references/callable-class.md (opens in a new tab)references/class-methods.md (opens in a new tab)references/instance-methods.md (opens in a new tab)references/invariants.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
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