/protean:entityfrom protean
Defines a Protean entity, a domain object with unique identity that is part of an aggregate. Entities are accessed through their parent aggregate and do not manage their own persistence.
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 entity is an object with its own identity that lives inside an aggregate and is loaded and saved with it. This skill defines entities: their fields, associations, options and invariants.
An entity is defined using the @domain.entity decorator and must specify which aggregate it belongs to:
from protean import Domain
from protean.fields import Decimal, HasMany, Identifier, Integer
domain = Domain()
@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, min_value=1)
unit_price: Decimal(precision=19, scale=4, required=True)
customer_id and product_id hold the ids of other aggregates. Link to another aggregate with an Identifier field, never with a Reference.
part_of parameter to associate with parent aggregate. Use a string reference (part_of="Order"), as Entity with part_of explains. A nested entity names its parent entity (part_of=LineItem or part_of="LineItem")id field is auto-generated unless auto_add_id_field=FalseHasOne or HasMany relationshipsfrom protean.fields import String
@domain.aggregate
class Post:
title: String(required=True, max_length=200)
comments = HasMany("Comment")
@domain.entity(part_of="Post")
class Comment:
content: String(required=True, max_length=500)
author: String(required=True, max_length=100)
# Automatically gets: id field
# Automatically gets: post = Reference(Post)
# Automatically gets: post_id # Shadow field holding the post's id
Use a string reference to the aggregate for part_of to avoid circular dependencies. A nested entity names its parent entity instead (see Nested entities):
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True)
quantity: Integer(required=True)
Why string references? Aggregates, entities, and value objects are often defined in the same file. The aggregate references entities via HasMany("LineItem") (forward reference), and entities reference back via part_of. If entities use a class reference (part_of=Order), the entity must be defined after the aggregate, but the aggregate's HasMany needs the entity to exist too. Using string references on both sides (HasMany("LineItem") and part_of="Order") breaks this circular dependency and allows elements to be defined in any order.
One-to-one relationship with another entity:
@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 other entities:
@domain.aggregate
class Order:
customer_id: Identifier(required=True)
shipping_info = HasOne("ShippingInfo")
line_items = HasMany("LineItem")
@domain.entity(part_of="Order")
class LineItem:
product_id: Identifier(required=True)
quantity: Integer(required=True)
Auto-generated helper methods: When you define a HasMany field on an aggregate or entity, 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 that matches the keyword arguments. It raises ObjectNotFoundError (from protean.exceptions) when no item matches, and TooManyObjectsError when more than one does.filter_line_items(**criteria): Return the items whose fields equal the given values, such as filter_line_items(product_id="P1"). It matches on equality only.Important: Do NOT manually create these methods: they are automatically available. Only create custom methods if you need behavior different from the defaults.
Entities automatically get a reference field to their parent aggregate. A LineItem that is part of Order gets item.order, which returns the Order object, and item.order_id, which holds the order's id. Accessing entities shows both in use.
@domain.entity has no abstract option. To share fields between entities, put them on a plain subclass of BaseEntity and leave it undecorated. Decorate only the concrete subclasses. Keep association fields (HasMany, HasOne) on the concrete entities, because two entities that inherit the same association fail domain.init():
from protean.core.entity import BaseEntity
class BaseLineItem(BaseEntity):
quantity: Integer(required=True)
@domain.entity(part_of="Order")
class ProductLineItem(BaseLineItem):
product_id: Identifier(required=True)
# Inherits quantity from BaseLineItem
The base class is not registered with the domain, so it gets no table and no association. Do not decorate it: a decorated base becomes a real entity of its own.
auto_add_id_fieldControl automatic ID field generation:
@domain.entity(part_of="Order", auto_add_id_field=False)
class LineItem:
# You must provide your own identifier field
line_number: Integer(required=True, identifier=True)
product_id: Identifier(required=True)
schema_nameCustomize the persistence name:
@domain.entity(part_of="Order", schema_name="order_items")
class LineItem:
product_id: Identifier(required=True)
quantity: Integer(required=True)
Creating instances needs an initialized domain and an active domain context, so the examples call domain.init(traverse=False) once and wrap their code in with domain.domain_context():. They use the auto-generated add_line_items() and remove_line_items() helpers, on this model:
@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)
domain.init(traverse=False)
with domain.domain_context():
order = Order(customer_id="C123")
# Create and add entity using auto-generated add_line_items() helper
item = LineItem(product_id="P1", quantity=2)
order.add_line_items([item])
# Or add multiple
items = [
LineItem(product_id="P2", quantity=1),
LineItem(product_id="P3", quantity=4),
]
order.add_line_items(items)
domain.repository_for(Order).add(order)
order_id = order.id
with domain.domain_context():
# Access via aggregate
order = domain.repository_for(Order).get(order_id)
line_items = order.line_items # List of LineItem entities
# Iterate over entities
for item in order.line_items:
print(f"Product: {item.product_id}, Qty: {item.quantity}")
# Access the parent from an entity
parent_order = item.order # Returns the Order object
parent_id = item.order_id # Returns the order's ID
with domain.domain_context():
# Update through aggregate
order = domain.repository_for(Order).get(order_id)
order.line_items[0].quantity = 5 # Update entity
domain.repository_for(Order).add(order) # Save aggregate
with domain.domain_context():
order = domain.repository_for(Order).get(order_id)
item = order.line_items[0]
order.remove_line_items(item) # Uses auto-generated remove_line_items() helper
domain.repository_for(Order).add(order) # Save aggregate
Entities can have methods and computed properties:
from decimal import Decimal as D # stdlib Decimal, aliased so it does not clash with the field
@domain.entity(part_of="Order")
class LineItem:
product_id: Identifier(required=True)
quantity: Integer(required=True, min_value=1)
unit_price: Decimal(precision=19, scale=4, required=True)
@property
def subtotal(self) -> D:
"""Calculate line item subtotal."""
return self.quantity * self.unit_price
def increase_quantity(self, amount: int):
"""Increase quantity by specified amount."""
if amount <= 0:
raise ValueError("Amount must be positive")
self.quantity += amount
Entities support three levels of validation (use in this order):
1. Field-level constraints: For data type validations and simple constraints.
Important: Always define data type validations at the field level using built-in parameters. Never validate these manually in methods.
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True, max_length=50, min_length=3)
quantity: Integer(required=True, min_value=1, max_value=1000)
unit_price: Decimal(precision=19, scale=4, required=True, min_value=0.01)
discount_percent: Float(min_value=0.0, max_value=100.0, default=0.0)
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)2. Business rules as invariants: For cross-field validations and domain logic, one business rule per invariant.
from protean import invariant
from protean.exceptions import ValidationError
@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, min_value=0.01)
discount_percent: Float(min_value=0.0, max_value=100.0, default=0.0)
@invariant.post
def large_discount_needs_bulk_quantity(self):
"""Granular business rule: discounts above 20% need 10 or more units.
Post invariants run at the end of __init__ and on every field assignment.
"""
if self.discount_percent > 20 and self.quantity < 10:
raise ValidationError(
{"_entity": ["Discounts above 20% need a quantity of 10 or more"]}
)
@invariant.post
def quantity_times_price_must_be_reasonable(self):
"""Granular business rule: total price sanity check.
Keep each invariant focused on ONE business constraint.
"""
total = self.quantity * self.unit_price
if total > 1_000_000: # Business limit
raise ValidationError(
{"_entity": ["Line item total exceeds maximum allowed"]}
)
@property
def subtotal(self) -> D:
"""Calculate line item subtotal."""
base = self.quantity * self.unit_price
discount = base * D(str(self.discount_percent)) / 100
return base - discount
Note: Entity invariants are validated as part of the aggregate's validation. Post-invariants run at the end of __init__ and on every field assignment. A change to a child entity also runs the aggregate root's post-invariants. repository.add() does not check them again, so an invalid change fails at the assignment, not at save time.
❌ Querying entities directly
# fragment
# Don't do this
comments = domain.repository_for(Comment).filter(author="John")
✅ Access through aggregate: Load the aggregate and use its helper, post.filter_comments(author="John").
❌ Entity containing another entity without relationship
# fragment
@domain.entity(part_of="Order")
class LineItem:
note = Comment() # Wrong: Use HasOne relationship
✅ Use proper association fields:
@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)
notes = HasMany("LineItemNote")
@domain.entity(part_of=LineItem)
class LineItemNote:
content: String(max_length=500)
A nested entity is part_of its parent entity, not the aggregate. Pass the parent entity as a class or as a string.
❌ Using entity as aggregate root
# fragment
@domain.entity(part_of="Order")
class LineItem:
product_id: String(required=True)
# Don't persist entities directly
domain.repository_for(LineItem).add(item) # Wrong!
✅ Persist through aggregate: Add the entity to its aggregate, as in Adding entities to aggregate, and persist the aggregate.
check and resolve what it reportsassets/entity_nested.py (opens in a new tab)assets/entity_simple.py (opens in a new tab)assets/entity_with_hasmany.py (opens in a new tab)assets/entity_with_hasone.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/configuration.md (opens in a new tab)references/nested-entities.md (opens in a new tab)references/with-hasmany.md (opens in a new tab)references/with-hasone.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"./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