/protean:aggregatefrom protean
Defines a Protean aggregate — the root entity of a domain cluster that encapsulates business logic, enforces invariants, and defines transaction boundaries. Use when modeling core business concepts like Order, Customer, or Account.
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.
An aggregate is the unit a repository loads and saves, and the place a domain's business rules are enforced. This skill defines one: its fields, associations, invariants and options.
An aggregate is defined using the @domain.aggregate decorator:
from protean import Domain
from protean.fields import String, Date, Integer
domain = Domain()
@domain.aggregate
class Post:
title: String(required=True, max_length=200)
content: String(max_length=5000)
status: String(max_length=20, default="draft")
published_on: Date()
view_count: Integer(default=0)
@invariant.pre or @invariant.post method, one rule per invariantid field is auto-generated unless auto_add_id_field=False_version field for optimistic concurrency controlcheck flags an aggregate with more entity types than the configured aggregate_size_limit (default 5) as AGGREGATE_TOO_LARGE. Split a growing aggregate, or raise the limit if the size is intentionalImportant: Protean fields come with built-in validation parameters. Always use these instead of manual validation in methods.
from datetime import datetime, timezone
from protean.fields import String, Integer, Float, Decimal, Boolean, Date, DateTime, Text
def utc_now():
return datetime.now(timezone.utc)
@domain.aggregate
class Product:
name: String(required=True, max_length=200, min_length=3)
description: Text()
price: Decimal(precision=19, scale=4, required=True, min_value=0.01) # Field-level validation
in_stock: Boolean(default=True)
stock_count: Integer(default=0, min_value=0) # Field-level validation
discount_percent: Float(min_value=0.0, max_value=100.0, default=0.0)
created_at: DateTime(default=utc_now)
Common field validation parameters:
required, default, unique, choices, validatorsmax_length, min_length, sanitizemin_value, max_valueprecision, scale (use Decimal(precision=19, scale=4) for money)Use field validations for:
Use invariants for:
One-to-one relationship with an entity:
from protean.fields import HasOne
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
shipping_info = HasOne("ShippingInfo")
@domain.entity(part_of="Order")
class ShippingInfo:
address: String(required=True, max_length=500)
city: String(required=True, max_length=100)
Note: For HasOne relationships, access the related entity directly through the field (e.g., order.shipping_info). No special helper methods are needed.
One-to-many relationship with entities:
from protean.fields import HasMany
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
line_items = HasMany("LineItem")
@domain.entity(part_of="Order")
class LineItem:
product_id: Identifier(required=True)
quantity: Integer(required=True)
unit_price: Decimal(precision=19, scale=4, required=True)
Auto-generated helper methods: When you define a HasMany field, Protean automatically creates helper methods for managing the association. For the line_items field above, these methods are generated:
add_line_items(item): Add one or more items to the collectionremove_line_items(item): Remove an item from the collectionget_one_from_line_items(id=item_id): Get the one item whose fields match the keyword arguments. Raises ObjectNotFoundError (from protean.exceptions) when nothing matches, and TooManyObjectsError when more than one item matchesfilter_line_items(**criteria): Return the items whose fields equal the given values, for example order.filter_line_items(product_id="P1"). It matches equality only; there are no __gt-style operatorsBoth lookup helpers take keyword arguments. A positional argument raises TypeError.
Important: Do NOT manually create these methods: they are automatically available. Only create custom methods if you need behavior different from the defaults (e.g., custom validation when adding items).
For complex immutable data types:
from protean.fields import ValueObject
@domain.value_object
class Money:
amount: Decimal(precision=19, scale=4, required=True)
currency: String(max_length=3, default="USD")
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
line_items = HasMany("LineItem")
total = ValueObject(Money)
Create aggregate instances by passing field values as keyword arguments. Instances need an initialized domain and an active domain context:
domain.init(traverse=False)
with domain.domain_context():
# Simple aggregate
post = Post(
title="Getting Started with Protean",
content="Protean is a DDD framework...",
status="draft"
)
# With entities (using auto-generated add_line_items() helper)
order = Order(customer_id="C123")
order.add_line_items(LineItem(product_id="P1", quantity=2, unit_price="50.00"))
# With value objects
order = Order(
customer_id="C123",
total=Money(amount="100.00", currency="USD")
)
Define methods on the aggregate to change state:
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
status: String(max_length=20, default="draft")
line_items = HasMany("LineItem")
def add_item(self, product_id: str, quantity: int, price):
"""Add an item to the order with custom business logic.
Note: This uses the auto-generated add_line_items() helper.
Create custom methods like this when you need additional validation,
calculations, or business logic beyond simple item addition.
"""
item = LineItem(product_id=product_id, quantity=quantity, unit_price=price)
self.add_line_items(item) # Uses auto-generated helper
def place_order(self):
"""Place the order."""
if not self.line_items:
raise ValueError("Cannot place empty order")
self.status = "placed"
def cancel(self):
"""Cancel the order."""
if self.status == "shipped":
raise ValueError("Cannot cancel shipped order")
self.status = "cancelled"
@domain.entity(part_of=Order)
class LineItem:
product_id: Identifier(required=True)
quantity: Integer(required=True)
unit_price: Decimal(precision=19, scale=4, required=True)
Protean checks post-invariants at the end of __init__. Every field assignment runs the pre-invariants before the new value is set and the post-invariants after it. Adding, removing or changing a child entity checks the root's invariants too. To change several fields that are only valid together, wrap the changes in with atomic_change(order): (from protean import atomic_change), which runs the pre-invariants once at the start and the post-invariants once at the end of the block. repository.add() does not check invariants again.
Use @invariant.pre (checked before changes) and @invariant.post (checked after changes):
@invariant.post: Validates after changes occur. Use for constraints that depend on the final state (e.g., "balance must not be negative"). Checked after initialization and after attribute updates.@invariant.pre: Validates before changes occur. Use for preconditions that must be true before allowing state changes (e.g., "account must be active"). Note: Pre invariants are NOT checked during initialization.An invariant raises ValidationError with a dict that maps the field at fault to a list of messages: ValidationError({"status": ["..."]}). A rule that compares fields, such as a balance against an overdraft limit, uses the key _entity. Protean catches only ValidationError from an invariant and attaches the code INVARIANT_PRE_FAILED or INVARIANT_POST_FAILED (a code= argument on the decorator replaces it). A ValueError or a custom exception gets no code, and a plain-string ValidationError("...") fails with a TypeError.
from protean import invariant
from protean.exceptions import ValidationError
@domain.aggregate
class Account:
balance: Decimal(precision=19, scale=4, default=0)
overdraft_limit: Decimal(precision=19, scale=4, default=0)
status: String(default="active")
# Post invariants - checked after initialization and after changes
@invariant.post
def balance_must_be_above_overdraft_limit(self):
"""Balance cannot fall below the negative overdraft limit.
Granular rule: Each invariant checks ONE business constraint.
"""
if self.balance < -self.overdraft_limit:
raise ValidationError(
{"_entity": ["Balance cannot be below overdraft limit"]}
)
# Pre invariants - only checked before changes (NOT during initialization)
@invariant.pre
def account_must_be_active(self):
"""Account must be active for transactions.
Pre-check ensures we don't attempt invalid operations.
"""
if self.status != "active":
raise ValidationError({"status": ["Account is not active"]})
def withdraw(self, amount):
"""Withdraw money from account.
Note: Parameter validations (amount > 0) belong in the method
when they validate method arguments, not aggregate fields.
Field-level constraints should be defined on the field itself.
"""
if amount <= 0:
raise ValueError("Withdrawal amount must be positive")
self.balance -= amount # Invariants automatically checked after this
Best practices:
@invariant.post: Use for most validations that check final state@invariant.pre sparingly: Only for preconditions that must prevent state changesCreate abstract base aggregates for shared fields:
from datetime import datetime, timezone
def utc_now():
return datetime.now(timezone.utc)
@domain.aggregate(abstract=True)
class TimeStamped:
"""Abstract base with timestamp fields."""
created_at: DateTime(default=utc_now)
updated_at: DateTime(default=utc_now)
@domain.aggregate
class User(TimeStamped):
"""Concrete aggregate inheriting timestamps."""
email: String(required=True, max_length=255)
name: String(required=True, max_length=200)
Pass options to the decorator:
@domain.aggregate(
auto_add_id_field=False, # Control automatic ID field
provider="default", # Provider name from the domain config's `databases` section
schema_name="customer_orders", # Table/collection name
stream_category="order" # Event sourcing stream category
)
class ArchivedOrder:
order_number: String(identifier=True, max_length=20)
abstract=True marks a base aggregate that cannot be instantiated (see Inheritance). An inner class Meta: on the aggregate is ignored; pass every option to the decorator.
See Configuration Reference for detailed documentation.
Aggregates are persisted using repositories:
from protean import current_domain
domain.init(traverse=False)
with domain.domain_context():
repo = current_domain.repository_for(Order)
# Create
order = Order(customer_id="C123")
order.add_item("P1", 2, "50.00") # Custom method using add_line_items()
repo.add(order)
# Retrieve
order = repo.get(order.id)
# Update
order.place_order()
repo.add(order)
# "Delete": record the change as a status, then persist it with add()
order.cancel()
repo.add(order)
Repositories have no save() or remove() method. add() both inserts and updates. Model removal as a state change, such as cancel() above.
from protean import Domain, invariant
from protean.exceptions import ValidationError
from protean.fields import Decimal, HasMany, Identifier, Integer, String
from decimal import Decimal as D
domain = Domain()
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True, max_length=50)
quantity: Integer(required=True, min_value=1)
unit_price: Decimal(precision=19, scale=4, required=True)
@property
def subtotal(self) -> D:
return self.quantity * self.unit_price
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
status: String(max_length=20, default="draft")
line_items = HasMany(LineItem)
@property
def total(self) -> D:
return sum((item.subtotal for item in self.line_items), D("0"))
@invariant.post
def placed_order_must_have_items(self):
if self.status == "placed" and not self.line_items:
raise ValidationError({"line_items": ["Cannot place empty order"]})
def place_order(self):
if not self.line_items:
raise ValueError("Cannot place empty order")
self.status = "placed"
# Usage
domain.init(traverse=False)
with domain.domain_context():
order = Order(customer_id="CUST-12345")
# Using auto-generated add_line_items() helper
order.add_line_items(LineItem(product_id="PROD-001", quantity=2, unit_price="29.99"))
order.add_line_items(LineItem(product_id="PROD-002", quantity=1, unit_price="49.99"))
order.place_order()
print(f"Order total: ${order.total:.2f}")
print(f"Status: {order.status}")
@domain.aggregate
class Order:
status: String(default="draft")
# No methods! Business logic scattered elsewhere
✅ Instead: Encapsulate behavior in aggregate methods.
See Anti-patterns for additional mistakes: oversized aggregates, direct entity access, transaction boundary violations, manually recreating auto-generated helpers.
check reportscheck inspects your aggregates and reports these diagnostics:
AGGREGATE_NO_INVARIANTS: the aggregate declares no @invariant.pre or @invariant.post method, so it enforces no business rules and is usually an anemic data holder. Add the invariants it must always satisfy, or reconsider whether this concept is an aggregate.AGGREGATE_NOT_NOUN: the aggregate's name ends in a suffix that reads as a verb, gerund, or adjective (OrderProcessing, Cancelable). Rename it to the domain-concept noun it models (Order).AGGREGATE_TOO_LARGE: the aggregate declares more entity types than the configured [lint] aggregate_size_limit. The count is of entity classes in the cluster, not of rows loaded at runtime. Split it into smaller aggregates, or raise the limit if the size is intentional.AGGREGATE_WITHOUT_COMMAND_HANDLER: the aggregate has no command handler, so nothing can change its state. Add a command handler for it, or model it as a read-only projection if no writes are expected.CROSS_AGGREGATE_REFERENCE: a field holds a direct Reference to another aggregate root. Hold the other aggregate by its identifier instead (<other>_id: Identifier()) and load it through its own repository when needed.entity: Entities within aggregatesvalue-object: Value objects for complex datacommand: Commands that trigger aggregate state changesevent: Events raised by aggregatesrepository: Persisting and retrieving aggregatesevent-sourced-aggregate: Event-sourced aggregates with @apply, from_events(), fact eventscheck and resolve what it reportsassets/aggregate_inheritance.py (opens in a new tab)assets/aggregate_simple.py (opens in a new tab)assets/aggregate_with_entity.py (opens in a new tab)assets/aggregate_with_invariants.py (opens in a new tab)assets/aggregate_with_value_object.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/configuration.md (opens in a new tab)references/invariants.md (opens in a new tab)references/with-entities.md (opens in a new tab)references/with-value-objects.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
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".Other plugins' skills for the same job