/protean:split-aggregatefrom protean
Guides splitting an oversized aggregate into two along its consistency boundary. Detects AGGREGATE_TOO_LARGE, identifies the seam, extracts the second concern, and links aggregates via identity and domain events.
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. Recognize the smell, pick the seam yourself, and apply the change by hand; the framework does not transform the code for you. The
split_order_before.pyasset is the oversized starting point;split_order_after.pyis the target.
An aggregate should hold one consistency boundary. When it grows a second
concern, with its own entities and its own lifecycle, the cluster gets large and
check reports AGGREGATE_TOO_LARGE: it counts more child entities in one
cluster than [lint] aggregate_size_limit allows (default five). That count is
the signal to split.
split_order_before.py is an Order that carries
both the order concern (items, discounts, gift wraps) and the fulfilment concern
(packages, tracking events, delivery attempts). Six child entities in one
cluster, over the default limit of five, so check reports it:
AGGREGATE_TOO_LARGE Aggregate `Order` has 6 entities (limit: 5)
The seam is the invariant boundary. Read the entities and group the ones that must stay consistent together in one transaction. In the Order example, the order concern is one such group and the fulfilment concern is another. A change to a tracking event can commit on its own without a discount changing at the same time, so they are two boundaries and belong in two aggregates.
When the boundary is unclear, use lifecycle as the tiebreak: state that is created, changed, and retired on a different schedule is a second aggregate. The finding-the-seam reference covers both rules in full.
split_order_after.py extracts the fulfilment
concern into a Shipment aggregate. Each cluster now holds three entities, under
the limit, so AGGREGATE_TOO_LARGE is gone.
Create the new aggregate and move the extracted entities under it with
part_of. The entity classes are unchanged; only their parent changes. The rule
that nothing goes out for delivery before it is packed spans two of the moved
entities, which is why they share one aggregate:
from protean.exceptions import ValidationError
@domain.aggregate
class Shipment:
order_id: Identifier(identifier=True) # identity link back to Order
status: String(default="pending")
packages = HasMany("Package")
tracking_events = HasMany("TrackingEvent")
delivery_attempts = HasMany("DeliveryAttempt")
@classmethod
def start(cls, order_id: str) -> "Shipment":
return cls(order_id=order_id, status="pending")
@invariant.post
def cannot_be_delivered_before_it_is_packed(self) -> None:
if self.delivery_attempts and not self.packages:
raise ValidationError(
{
"delivery_attempts": [
"A shipment cannot be delivered before it is packed"
]
}
)
@domain.entity(part_of="Shipment")
class Package:
weight_kg: Float(required=True, min_value=0.0)
@domain.entity(part_of="Shipment")
class TrackingEvent:
status: String(required=True, max_length=50)
note: String(max_length=200)
@domain.entity(part_of="Shipment")
class DeliveryAttempt:
attempted_at: DateTime()
outcome: String(required=True, max_length=50)
Shipment names the order it fulfils by holding the order's id in a plain
Identifier field. Holding a Reference to the Order root would reach across
the boundary, which is what check reports as CROSS_AGGREGATE_REFERENCE:
# fragment
# Wrong: a Reference across an aggregate boundary re-couples the two clusters.
order = Reference("Order")
The identity field carries the link and keeps the two aggregates as separate
loading and locking units. Load the Order through its own repository when a
Shipment needs it.
In this example an order has one shipment, so order_id is also Shipment's
own identity (identifier=True). Pick that deliberately: it is what makes the
step below safe to repeat. Where an order can ship in several parcels, give
Shipment its own id and keep order_id a plain required=True field. The
guard below has to change with it: order_id no longer names one shipment, so
it cannot be the retry key either, and refusing every repeated order_id would
refuse the second parcel too. Carry a deterministic shipment id on the command
and look that up instead.
The two aggregates commit in separate transactions, so the step that spans them
happens as two writes joined by an event. Order raises OrderPlaced when it is
placed. An event handler in Order's own cluster reacts and issues a
StartShipment command, and Shipment's command handler starts the shipment.
After the split, Order keeps only the order concern: its items, discounts and
gift wraps. It raises OrderPlaced, and StartShipment is a command on
Shipment:
from decimal import Decimal as D
@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.aggregate
class Order:
customer_id: Identifier(required=True)
total: Decimal(precision=19, scale=4, default=0)
status: String(default="draft")
items = HasMany("OrderItem")
discounts = HasMany("Discount")
gift_wraps = HasMany("GiftWrap")
@classmethod
def place(cls, order_id: str, customer_id: str, total: D) -> "Order":
order = cls(id=order_id, customer_id=customer_id, total=total, status="placed")
order.raise_(
OrderPlaced(order_id=order.id, customer_id=customer_id, total=total)
)
return order
@invariant.post
def total_must_not_be_negative(self) -> None:
if self.total < 0:
raise ValidationError({"total": ["Order total cannot be negative"]})
@domain.entity(part_of="Order")
class OrderItem:
product_id: Identifier(required=True)
quantity: Integer(required=True, min_value=1)
unit_price: Decimal(precision=19, scale=4, required=True, min_value=0)
@domain.entity(part_of="Order")
class Discount:
code: String(required=True, max_length=50)
amount: Decimal(precision=19, scale=4, required=True, min_value=0)
@domain.entity(part_of="Order")
class GiftWrap:
style: String(required=True, max_length=50)
@domain.command(part_of="Shipment")
class StartShipment:
order_id: Identifier(required=True)
The event handler in Order's cluster issues the command:
@domain.event_handler(part_of=Order)
class ShipmentInitiation:
@handle(OrderPlaced)
def on_order_placed(self, event: OrderPlaced) -> None:
current_domain.process(StartShipment(order_id=event.order_id))
Events are delivered at least once, so write the receiving end to survive a
repeat. OrderPlaced can arrive twice, which reissues StartShipment, so
Shipment's command handler returns without doing anything when the shipment is
already open:
from protean.exceptions import ObjectNotFoundError
@domain.command_handler(part_of=Shipment)
class ShipmentCommandHandler:
@handle(StartShipment)
def start_shipment(self, command: StartShipment) -> None:
repository = current_domain.repository_for(Shipment)
try:
repository.get(command.order_id)
except ObjectNotFoundError:
repository.add(Shipment.start(command.order_id))
else:
return # already open; starting over would discard its progress
Without both the deterministic id and this guard, a second delivery inserts a second shipment for the same order. See Idempotent Event Handlers for the full set of strategies.
The handler stays in Order's cluster because it reacts to Order's own event.
A handler that reacts to another cluster's event trips
EVENT_HANDLER_FOREIGN_EVENT; for a flow with several causally dependent steps,
reach for a process manager. See event for raising the event
and domain-service for a step whose logic spans
both aggregates.
check and
resolve what it reports, including any AGGREGATE_TOO_LARGE or
CROSS_AGGREGATE_REFERENCE.What 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