/protean:event-sourced-aggregatefrom protean
Builds event-sourced aggregates in Protean where state is derived by replaying domain events. Covers @apply decorator, raising events from business methods, state reconstruction via from_events(), event-sourced repositories, and version tracking.
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 event-sourced aggregate stores events instead of current state. State is reconstructed by replaying events through @apply methods. Business methods validate and call raise_(), which automatically invokes the matching @apply handler to mutate state:
from protean import Domain
from protean.core.aggregate import apply
from protean.fields import String, Identifier
domain = Domain()
@domain.event(part_of="Account")
class AccountOpened:
account_id: Identifier(required=True)
owner_name: String(required=True)
@domain.event(part_of="Account")
class AccountClosed:
account_id: Identifier(required=True)
@domain.aggregate(event_sourced=True)
class Account:
account_id: Identifier(identifier=True)
owner_name: String(required=True)
status: String(default="ACTIVE")
@classmethod
def open(cls, account_id, owner_name):
account = cls(account_id=account_id, owner_name=owner_name)
account.raise_(AccountOpened(
account_id=account_id, owner_name=owner_name
))
return account
def close(self):
if self.status != "ACTIVE":
raise ValueError("Account is not active")
self.raise_(AccountClosed(account_id=self.account_id))
@apply
def opened(self, event: AccountOpened):
self.account_id = event.account_id
self.owner_name = event.owner_name
self.status = "ACTIVE"
@apply
def closed(self, event: AccountClosed):
self.status = "CLOSED"
event_sourced=True: Pass to the @domain.aggregate decorator@apply is the single source of truth for state mutations: raise_() automatically invokes the matching @apply handler to mutate state. Business methods should validate preconditions and call raise_(). They never mutate state directly@apply handler: When raise_() is called, it looks up and invokes the @apply handler for that event type. A missing handler raises IncorrectUsageError@apply runs on both live and replay paths: The same @apply handler runs when raise_() is called during normal operations AND when replaying events from the event store. This guarantees identical state regardless of path@apply method handles exactly one event type: Use a type annotation on the event parameter: def opened(self, event: AccountOpened)apply from protean.core.aggregate: from protean import apply also works and is the same decorator; this skill uses the protean.core.aggregate path throughoutpart_of: Associate each event with its aggregate: @domain.event(part_of="Account")_version, which drives optimistic concurrency control. Fact-event snapshots (rule 11) do not increment _versiondomain.repository_for(Account) returns an event-sourced repository when the aggregate has event_sourced=True@domain.aggregate(event_sourced=True, fact_events=True) to auto-publish complete state after each persist@apply must set ALL fields: from_events() creates a blank aggregate and applies all events through @apply, so the first event's handler must establish all state including identitywith UnitOfWork(): block reach the event store only when the unit of work commits. If the handler raises after repo.add(account), the unit of work rolls back and none of the new events reach the account's stream. A new account's stream stays empty; an existing account's stream keeps the events it already had. The account object in memory is not reset: it still holds the raised events in _events and the state its @apply handlers set. Do not reuse it.reserved=[...] names removed fields: @domain.aggregate(event_sourced=True, reserved=["nickname"]) marks nickname as a field that once existed. Declaring a live field with a reserved name fails at registration with IncorrectUsageError, message "Field(s) ['nickname'] on aggregate `Account` reuse a reserved name; a reserved name can never be declared again as a field". During replay (from_events() or repo.get()), an @apply handler for an old event can still run self.nickname = event.nickname. The assignment is dropped without an error, and the rebuilt aggregate has no nickname attribute. The same assignment on the live raise_() path raises a Pydantic pydantic_core.ValidationError, not protean.exceptions.ValidationError.Using Account.close() from Basic structure:
When close() is called:
raise_() increments _version, appends the event, then invokes the @apply handler (wrapped in invariant checks)@apply handler mutates state (self.status = "CLOSED")When the aggregate is loaded later (via from_events() or repo.get()):
@apply methodAlways use a factory classmethod to create new event-sourced aggregates. Here User.register() is the factory:
@domain.event(part_of="User")
class UserRegistered:
user_id: Identifier(required=True)
name: String(required=True)
email: String(required=True)
@domain.aggregate(event_sourced=True)
class User:
user_id: Identifier(identifier=True)
name: String(required=True)
email: String(required=True)
@classmethod
def register(cls, user_id, name, email):
user = cls(user_id=user_id, name=name, email=email)
user.raise_(UserRegistered(user_id=user_id, name=name, email=email))
return user
@apply
def registered(self, event: UserRegistered):
self.user_id = event.user_id
self.name = event.name
self.email = event.email
# Usage
domain.init(traverse=False)
with domain.domain_context():
user = User.register(user_id="U-001", name="Alice", email="[email protected]")
_create_new() for lean creationWhen not all required fields can be satisfied at construction time, use _create_new(). It creates a blank aggregate with only identity, and lets the creation event's @apply handler establish all state:
@classmethod
def register(cls, user_id, name, email):
user = cls._create_new(user_id=user_id) # Only identity required
user.raise_(UserRegistered(user_id=user_id, name=name, email=email))
return user
With _create_new(), the @apply handler for UserRegistered must set ALL fields. This is the preferred pattern when the aggregate has many required fields.
Event-sourced aggregates can be reconstructed from their event history:
with domain.domain_context():
events = user._events # the events raised so far
# Build aggregate from events
rebuilt = User.from_events(events)
assert rebuilt.email == user.email
# Internally:
# 1. Creates a blank aggregate via _create_for_reconstitution()
# 2. Applies ALL events sequentially through their @apply methods
# 3. The first event's @apply handler must set ALL fields including identity
The repository handles this automatically when loading:
with domain.domain_context():
repo = domain.repository_for(User)
repo.add(user) # Writes the raised events to the event store
user = repo.get(user.user_id) # Reconstructs from event store
repository_for() returns an event-sourced repository, which persists events instead of state (State reconstruction shows add() and get()). For custom queries, define an explicit ES repository by subclassing BaseEventSourcedRepository and registering it against the aggregate:
from protean.core.event_sourced_repository import BaseEventSourcedRepository
class AccountRepository(BaseEventSourcedRepository):
pass # Default behavior handles add/get
domain.register(AccountRepository, part_of=Account)
See Event-Sourced Repository for details.
Enable fact events to auto-generate state snapshots after each persist:
@domain.aggregate(event_sourced=True, fact_events=True)
class Product:
name: String(required=True)
price: Decimal(precision=19, scale=4, required=True)
...
Each time the aggregate is saved, Protean auto-generates a ProductFactEvent containing the complete state. Downstream consumers can subscribe to these instead of tracking individual delta events.
Use fact events when:
See Snapshots and Fact Events for details.
Choose event sourcing when an aggregate meets 2 or more of these criteria:
| Criterion | Indicator |
|---|---|
| Audit trail | Regulatory compliance, financial transactions, complete traceability |
| Temporal queries | "What was the state at time T?", historical reporting |
| Complex state transitions | Multi-step workflows, intricate business rules |
| Event-driven integration | Other bounded contexts consume events as primary data |
| Team readiness | Team understands event modeling and can operate event stores |
You can mix patterns per-aggregate within the same domain:
@domain.aggregate # Standard: state stored directly
class Product: ...
@domain.aggregate(event_sourced=True) # Event sourced: state from events
class Order: ...
# fragment
# WRONG: state mutated in business method AND in @apply (double mutation)
def close(self):
self.status = "CLOSED" # Don't do this
self.raise_(AccountClosed(account_id=self.account_id))
@apply
def closed(self, event: AccountClosed):
self.status = "CLOSED" # This also runs via raise_()!
Business methods only validate and call raise_(), as Account.close() does in Basic structure.
Every event type raised by the aggregate must have a corresponding @apply method. Missing one raises IncorrectUsageError at runtime (No @apply handler registered for event ...) because raise_() invokes @apply automatically. check reports this ahead of time as ES_EVENT_MISSING_APPLY.
An event_sourced=True aggregate that raises no domain events has no state history and cannot be rebuilt by replay. check reports this as ES_AGGREGATE_NO_EVENTS: declare at least one event with part_of=<Aggregate> and raise it from the aggregate's behaviour, or drop event_sourced=True if the aggregate is not meant to be event-sourced.
# fragment
# WRONG: no creation event recorded
@classmethod
def open(cls, account_id, owner_name):
return cls(account_id=account_id, owner_name=owner_name)
Always raise_() an event in the factory classmethod.
repository_for() returns the event-sourced repository automatically for an ES aggregate. For custom query methods, subclass BaseEventSourcedRepository and register it. A standard @domain.repository builds a state-based repository, which is the wrong persistence model for an ES aggregate.
See Anti-patterns for more.
aggregate: Base aggregate structure, fields, invariants, associationsevent: Event definition, naming conventions, event fieldsevent-handler: Event handler structure, @handle decoratorcommand-handler: Command handler processingrepository: Standard repository (contrast with ES repository)check and resolve what it reportsassets/es_aggregate_basic.py (opens in a new tab)assets/es_aggregate_command_flow.py (opens in a new tab)assets/es_aggregate_fact_events.py (opens in a new tab)assets/es_aggregate_with_entities.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/apply-decorator.md (opens in a new tab)references/event-sourced-repository.md (opens in a new tab)references/snapshots-and-fact-events.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