/protean:add-validationfrom protean
Adds validation rules to Protean domain elements across 4 layers: field constraints, value object invariants, aggregate invariants, and handler guards. Use when implementing business rules, input validation, or pre/post-conditions.
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.
Protean organizes validation into 4 layers. Put each rule in the one layer that fits it, and only there.
| Layer | Mechanism | Purpose | When it runs |
|---|---|---|---|
| 1. Field constraints | Field parameters | Type safety, format, range, presence | On field assignment |
| 2. Value object invariants | @invariant.post | Domain concept rules | After VO creation |
| 3. Aggregate invariants | @invariant.pre / @invariant.post | Business rules, cross-field consistency | Before/after state changes |
| 4. Handler/service guards | Explicit checks in handler | Authorization, context-dependent rules | During command processing |
Before adding a validation, understand:
@invariant.pre) or after change (@invariant.post)?Use for single-field data type rules. These are the simplest and most common validations.
from decimal import Decimal as D
from enum import Enum
from protean.fields import Decimal, Integer, String
class OrderStatus(Enum):
DRAFT = "DRAFT"
PLACED = "PLACED"
SHIPPED = "SHIPPED"
@domain.aggregate
class Order:
# Required field
customer_id: String(required=True)
# Range constraints
quantity: Integer(required=True, min_value=1, max_value=10000)
price: Decimal(precision=19, scale=4, required=True, min_value=D("0.01"))
# Length constraints
notes: String(max_length=500)
# Enum/choices constraint
status: String(max_length=10, choices=OrderStatus, default="DRAFT")
When to use Layer 1:
required=True: Field must have a valuemin_value / max_value: Numeric rangemin_length / max_length: String lengthchoices: Value must be from enum/listvalidators=[...]: Custom single-field format checks (see custom-validator)Validation timing: Immediately on field assignment (during __init__ or __setattr__).
Use for domain concept rules that span multiple fields of a value object. Value objects only support @invariant.post (they are immutable, so there are no pre-conditions).
from protean import invariant
from protean.exceptions import ValidationError
from protean.fields import Date, Decimal, String
@domain.value_object
class DateRange:
start_date: Date(required=True)
end_date: Date(required=True)
@invariant.post
def end_must_be_after_start(self):
"""End date must be after start date."""
if self.end_date <= self.start_date:
raise ValidationError(
{"date_range": ["End date must be after start date"]}
)
@domain.value_object
class Money:
amount: Decimal(precision=19, scale=4, required=True)
currency: String(max_length=3, required=True)
@invariant.post
def amount_must_be_non_negative(self):
"""Money amounts cannot be negative."""
if self.amount < 0:
raise ValidationError(
{"amount": ["Amount cannot be negative"]}
)
When to use Layer 2:
When a VO invariant fails: The value object validates its invariants at construction and is immutable afterward, so a broken invariant raises ValidationError right there. The default code on that raise is VALUE_OBJECT_INVARIANT_FAILED, unless you set a custom code= on the invariant. The values you built the VO from are what broke the rule. To fix it, build the value object from values that satisfy the invariant, or catch the ValidationError where you build it; its messages name the field and rule that failed. Set @invariant.post(code=...) to raise a more specific catalog code in place of the default.
Use for business rules that enforce consistency across an aggregate's state. Supports both @invariant.pre (before change) and @invariant.post (after change).
Money fields are Decimal, so the total compares exactly. With Float fields, subtotals of 0.1 and 0.2 do not add up to a total of 0.3.
from decimal import Decimal as D
from protean import invariant
from protean.exceptions import ValidationError
from protean.fields import Decimal, HasMany, Integer, String
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True)
quantity: Integer(required=True)
price: Decimal(precision=19, scale=4, required=True)
subtotal: Decimal(precision=19, scale=4, required=True)
@domain.aggregate
class Order:
status: String(default="draft")
items = HasMany("LineItem")
total_amount: Decimal(precision=19, scale=4, default=D("0"))
def place(self):
self.status = "placed"
@invariant.post
def total_must_equal_sum_of_items(self):
"""Order total must match sum of line item subtotals."""
expected = sum(item.subtotal for item in self.items)
if self.total_amount != expected:
raise ValidationError(
{"_entity": ["Total must equal sum of item subtotals"]}
)
@invariant.post
def must_have_items_when_placed(self):
"""Placed orders must have at least one item."""
if self.status != "draft" and not self.items:
raise ValidationError(
{"items": ["Order must have at least one item when placed"]}
)
@invariant.pre
def cannot_modify_shipped_order(self):
"""Shipped orders cannot be modified."""
if self.status == "shipped":
raise ValidationError(
{"_entity": ["Cannot modify a shipped order"]}
)
@invariant.pre vs @invariant.post:
@invariant.pre: Checked BEFORE attribute changes (not on initialization). Use for state guards: "cannot modify shipped orders", "cannot withdraw below limit".@invariant.post: Checked AFTER initialization AND after each attribute change. Use for consistency rules: "total must equal sum", "must have items when placed".When to use Layer 3:
An aggregate with no invariants at all: check reports AGGREGATE_NO_INVARIANTS for an
aggregate that declares neither @invariant.pre nor @invariant.post. An aggregate is a
consistency boundary, so one that enforces no rule is usually an anemic data holder. Add the
business rules it must always satisfy, or reconsider whether the concept is an aggregate: a
plain value-carrier is often better modelled as a value object or as an entity inside another
aggregate.
Use for authorization, context-dependent rules, and checks that need external data not available inside the aggregate.
from protean import current_domain, handle
from protean.exceptions import ValidationError
from protean.fields import Identifier, String
@domain.command(part_of=Order)
class PlaceOrder:
order_id: Identifier(required=True)
requested_by_role: String(required=True)
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def place_order(self, command: PlaceOrder):
# Layer 4: Context-dependent guard
if command.requested_by_role not in ["customer", "admin"]:
raise ValidationError(
{"authorization": ["Only customers or admins can place orders"]}
)
# Layer 4: External data check. get() raises ObjectNotFoundError
# on a miss; get_or_none() returns None so the handler can say why.
repo = current_domain.repository_for(Order)
order = repo.get_or_none(command.order_id)
if order is None:
raise ValidationError(
{"order_id": [f"Order {command.order_id} not found"]}
)
# Business logic (Layers 1-3 validate automatically)
order.place()
repo.add(order)
When to use Layer 4:
When multiple attributes need to change together, use atomic_change to defer validation until all changes are made. This example uses the Order and LineItem from Layer 3. Creating an aggregate needs an initialized domain and an active domain context, so domain.init() runs after every element is defined:
from decimal import Decimal as D
from protean import atomic_change
domain.init(traverse=False)
with domain.domain_context():
order = Order(
items=[
LineItem(product_id="P1", quantity=10, price=D("10"), subtotal=D("100"))
],
total_amount=D("100"),
)
with atomic_change(order):
order.total_amount = D("120") # No validation yet
order.add_items(
LineItem(product_id="P3", quantity=2, price=D("10"), subtotal=D("20"))
)
# Post-invariants checked here: the total matches the items again
@invariant.pre/@invariant.post instead of if checks in methods. Invariants run automatically.total_must_equal_sum_of_items, not validate_total.ValidationError with field context: Use {"field_name": ["message"]} format. Use "_entity" key for aggregate-level rules.Decimal(precision=19, scale=4, min_value=0) handles it, don't also add an invariant for the same check.@invariant.pre only runs before attribute changes AFTER the object is created.atomic_change for multi-field updates: When changing related fields together, wrap in atomic_change to avoid intermediate invalid states.__init__: Use Protean's validation framework (fields + invariants), not manual __init__ checks.check and resolve what it reportsassets/validation_all_layers.py (opens in a new tab)assets/validation_layer1_field_constraints.py (opens in a new tab)assets/validation_layer2_vo_invariants.py (opens in a new tab)assets/validation_layer3_aggregate_invariants.py (opens in a new tab)assets/validation_layer4_handler_guards.py (opens in a new tab)references/choosing-the-right-layer.md (opens in a new tab)references/layer1-field-constraints.md (opens in a new tab)references/layer2-value-object-invariants.md (opens in a new tab)references/layer3-aggregate-invariants.md (opens in a new tab)references/layer4-handler-guards.md (opens in a new tab)What 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-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