/protean:refactor-move-logic-to-aggregatefrom protean
Detects business logic leaked from aggregates into handlers/services and refactors it into rich aggregate methods with invariants. Use when handlers are fat, aggregates are anemic, or logic leaks are identified.
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
move_logic_*_before.pyasset is the intentional starting point (anemic aggregate / fat handler); the*_after.pyasset shows the rich-aggregate target.
Identify business logic that has leaked out of aggregates into handlers, services, or endpoints, and move it back into rich aggregate methods with proper invariants and events.
| Output | Purpose |
|---|---|
| Rich aggregate methods | Business logic encapsulated in the aggregate |
| Aggregate invariants | Validation rules as @invariant.post decorators |
| Thin handlers | Handlers reduced to load → call → persist |
| Updated tests | Tests for aggregate behavior, not handler internals |
Handler does validation, calculation, construction, and persistence:
# fragment
# RED FLAG: handler has 10+ lines of logic
@handle(PlaceOrder)
def place_order(self, command):
if not command.items: # Validation
raise ValidationError(...)
total = sum(i.price * i.qty ...) # Calculation
if total > MAX: # Business rule
raise ValidationError(...)
order = Order(total=total, status="PLACED") # Construction
domain.repository_for(Order).add(order)
Aggregate is a data bag: no methods, no invariants:
# fragment
# RED FLAG: only fields, no behavior
@domain.aggregate
class Order:
customer_id = String(required=True)
total = Decimal(precision=19, scale=4, default=0)
status = String(default="DRAFT")
# No methods!
| Signal | Where found | What to move |
|---|---|---|
if + raise ValidationError | Handler | @invariant.post on aggregate |
| Arithmetic / calculations | Handler | Aggregate method |
self.status = "..." | Handler setting aggregate fields | Aggregate state-transition method |
| Multiple attribute assignments | Handler building aggregate state | Aggregate factory or method |
if status != "X": raise | Handler guard clause | Aggregate method pre-condition |
Read the handler and categorize each line:
| Line | Category | Destination |
|---|---|---|
if not command.items: raise | Validation | Aggregate invariant or method guard |
total = sum(...) | Calculation | Aggregate method |
if total > MAX: raise | Business rule | Aggregate invariant |
order.status = "PLACED" | State transition | Aggregate method |
repo.add(order) | Persistence | Stays in handler |
order = Order(...) | Construction | Stays in handler (or factory) |
The order's methods use a Money value object, a LineItem entity and an
OrderPlaced event. The handler in Step 4 takes a PlaceOrder command:
@domain.value_object
class Money:
amount = Decimal(precision=19, scale=4, required=True)
currency = String(max_length=3, default="USD")
@domain.entity(part_of="Order")
class LineItem:
product_id = String(required=True)
quantity = Integer(required=True, min_value=1)
unit_price = ValueObject(Money, required=True)
@domain.event(part_of="Order")
class OrderPlaced:
order_id = Identifier(required=True)
total = Decimal(precision=19, scale=4, required=True)
@domain.command(part_of="Order")
class PlaceOrder:
customer_id = String(required=True)
items = List(content_type=Dict)
For each group of logic, create an aggregate method on Order: here place() and
_calculate_total(). Step 3 shows the whole class, with these methods and its
invariants.
Move validation from handlers into @invariant.post. With the methods from Step
2, the Order class reads:
from decimal import Decimal as D
from protean.exceptions import ValidationError
@domain.aggregate
class Order:
customer_id = String(required=True)
items = HasMany(LineItem)
total = ValueObject(Money)
status = String(default="DRAFT")
def place(self, items: list[dict]) -> None:
"""Place the order with the given items."""
for item_data in items:
self.add_items(LineItem(**item_data))
self.total = self._calculate_total()
self.status = "PLACED"
self.raise_(OrderPlaced(order_id=self.id, total=self.total.amount))
def _calculate_total(self) -> Money:
"""Sum all line item totals."""
total = D(0)
for item in self.items:
total += item.unit_price.amount * item.quantity
return Money(amount=total)
@invariant.post
def must_have_items_when_placed(self):
"""A placed order must have at least one item."""
if self.status == "PLACED" and not self.items:
raise ValidationError({"items": ["Placed order must have items"]})
@invariant.post
def total_must_not_exceed_maximum(self):
"""Order total cannot exceed $50,000."""
if self.total and self.total.amount > 50000:
raise ValidationError({"total": ["Exceeds maximum order amount"]})
Placing an order with one line sets the total from that line:
domain.init(traverse=False)
with domain.domain_context():
order = Order(customer_id="CUST-001")
order.place(
items=[
{"product_id": "P-1", "quantity": 2, "unit_price": Money(amount=D("10.00"))}
]
)
assert order.total.amount == D("20.00")
Do not skip this step. An aggregate that ends the refactor with rich methods but no
@invariant.pre or @invariant.post is still reported as AGGREGATE_NO_INVARIANTS: the
logic moved off the handler, but the consistency boundary enforces nothing. The rules you
deleted from the handler in Step 1 are the invariants to declare here.
The handler becomes load → call → persist:
@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(items=command.items)
domain.repository_for(Order).add(order)
The ideal handler is 3-5 lines: load/create aggregate, call one method, persist.
A test that drives the handler checks the rule through its internals:
# fragment
# Before: testing handler internals
def test_place_order_validates_items():
with pytest.raises(ValidationError):
handler.place_order(PlaceOrder(items=[]))
Test the aggregate's behavior directly instead:
import pytest
from protean.exceptions import ValidationError
# After: testing aggregate behavior
def test_order_must_have_items_when_placed():
order = Order(customer_id="CUST-001")
with pytest.raises(ValidationError):
order.place(items=[]) # Invariant fires
Moving persistence into the aggregate: repository.add() stays in the handler.
Aggregates don't know about persistence.
Creating a method per field: If the handler sets 3 fields, create ONE method that captures the business operation, not 3 setter methods.
Leaving events in the handler: raise_() belongs inside the aggregate method,
not in the handler after calling the method.
Over-guarding: Not every if is an invariant. Simple null checks in handlers
(if not command.customer_id) are often handled by field required=True.
check and resolve what it reportsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
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