DDD Teaching Layer + Model Guards Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Make the library practice the DDD it preaches โ€” decider-first docs at the front doors, the event_type contradiction resolved, aggregate identity guarded at construction time, domain/types.py reconciled with real signatures, and typed decider commands โ€” per .fractal/ddd-dogfooding-review.md.

Architecture: Code guards land first (Tasks 1-4) so the docs rewrite (Tasks 5-6) documents final behavior. All breaking changes are clean breaks (user mandate 2026-08-01: "we can break as desired right now"; no external users). Domain ring stays stdlib+pydantic.

Tech Stack: Python 3.13 (PEP 696 native TypeVar defaults), pydantic v2, pytest, uv, mkdocs, import-linter, mypy strict.

Global Constraints


Task 1: Guard aggregate identity (required aggregate_type + pattern validation)

Files:

Interfaces:


git fetch origin main
git checkout -b ddd-teaching-wave origin/main

In tests/unit/domain/test_aggregate_root.py:


class TestAggregateTypeRequired:
    def test_subclass_without_aggregate_type_raises_on_construction(self) -> None:
        from eventsource.domain.exceptions import AggregateTypeNotSetError

        class ForgotType(AggregateRoot[dict]):
            def _apply(self, event: DomainEvent) -> None: ...

        with pytest.raises(AggregateTypeNotSetError, match="ForgotType"):
            ForgotType(uuid4())

    def test_subclass_with_aggregate_type_constructs(self) -> None:
        class HasType(AggregateRoot[dict]):
            aggregate_type = "HasType"

            def _apply(self, event: DomainEvent) -> None: ...

        assert HasType(uuid4()).aggregate_type == "HasType"

In tests/unit/domain/test_domain_event.py:


class TestAggregateTypePattern:
    def test_invalid_category_characters_raise(self) -> None:
        class BadEvent(DomainEvent):
            aggregate_type: str = "Or:der"  # ':' is the StreamId separator

        with pytest.raises(ValidationError):
            BadEvent(aggregate_id=uuid4())

    def test_valid_category_passes(self) -> None:
        class GoodEvent(DomainEvent):
            aggregate_type: str = "Order_v2"

        assert GoodEvent(aggregate_id=uuid4()).aggregate_type == "Order_v2"

(Reuse each file's existing imports; add ValidationError from pydantic where missing. Note: declaring aggregate_type: str = "..." on an event class is fine and current practice โ€” the rule against hand-declaration is about event_type.)

Run: uv run pytest tests/unit/domain/test_aggregate_root.py tests/unit/domain/test_domain_event.py -q -k "TestAggregateTypeRequired or TestAggregateTypePattern" Expected: FAIL โ€” no AggregateTypeNotSetError; "Or:der" accepted.

(a) src/eventsource/domain/exceptions.py, next to AggregateNotCreatedError:


class AggregateTypeNotSetError(EventSourceError):
    """
    Raised when a concrete aggregate class is constructed without declaring
    aggregate_type.

    Aggregate identity is not optional: aggregate_type becomes the stream
    category, so a missing value would silently create wrongly-typed
    streams (the old behavior was a silent "Unknown" default).
    """

    def __init__(self, class_name: str) -> None:
        self.class_name = class_name
        super().__init__(
            f"{class_name} does not declare 'aggregate_type'. Every concrete "
            f"aggregate class must set it to its stream category, e.g. "
            f'aggregate_type = "Order".'
        )

(b) src/eventsource/domain/aggregate.py: replace aggregate_type: str = "Unknown" (and its comment) with:


    # Aggregate type identifier -- REQUIRED. Becomes the stream category;
    # construction raises AggregateTypeNotSetError if a concrete subclass
    # does not set it. (Annotated ClassVar, deliberately no default.)
    aggregate_type: ClassVar[str]

and add to __init__, before the existing assignments:


        if not getattr(type(self), "aggregate_type", None):
            raise AggregateTypeNotSetError(type(self).__name__)

Import AggregateTypeNotSetError alongside the other exception imports; ClassVar is already imported.

(c) src/eventsource/domain/event.py: import at top (import re, from eventsource.domain.stream_id import CATEGORY_PATTERN โ€” stream_id imports only stdlib, no cycle), module-level _CATEGORY_REGEX = re.compile(CATEGORY_PATTERN), and add below _ensure_event_type:


    @field_validator("aggregate_type")
    @classmethod
    def _validate_aggregate_type(cls, v: str) -> str:
        if not _CATEGORY_REGEX.match(v):
            raise ValueError(
                f"aggregate_type {v!r} is not a valid stream category "
                f"(must match {CATEGORY_PATTERN}); it is used as "
                f"StreamId.category on the event's stream"
            )
        return v

(field_validator joins the existing pydantic imports. If CATEGORY_PATTERN already carries re anchors incompatible with .match, mirror exactly how stream_id.py compiles/applies it โ€” the two must accept identical values.)

(d) src/eventsource/domain/__init__.py: add AggregateTypeNotSetError to the import block and __all__ (alphabetical). The Task-8-era completeness test in tests/unit/domain/test_exceptions_home.py will fail until this is done โ€” that's your safety net, not an obstacle.

Run: uv run pytest tests/unit -q 2>&1 | tail -5. Every test aggregate class that never set aggregate_type now fails construction. Fix each by adding an honest aggregate_type = "" โ€” do NOT restore a default. Also grep -rn '"Unknown"' src/eventsource docs โ€” remove/reword any mention of the old default (e.g. repository docstrings); AggregateRepository._infer_aggregate_type needs no code change (with no default, "Unknown" can no longer occur implicitly), but if its docstring mentions the default, update it. List every touched file in your report.


uv run pytest tests/unit -q
uv run ruff check src tests && uv run mypy src/eventsource/
git add -A src tests
git commit -m "feat: require aggregate_type on aggregates and validate event aggregate_type as stream category"

Task 2: Reconcile domain/types.py with reality

Files:

Interfaces:


class TestTypesVocabulary:
    def test_identity_aliases_are_plain_uuid(self) -> None:
        from uuid import UUID

        from eventsource.domain import types

        assert types.TenantId is UUID
        assert types.CausationId is UUID

    def test_position_aliases_are_gone(self) -> None:
        from eventsource.domain import types

        for name in ("Version", "StreamPosition", "GlobalPosition"):
            assert not hasattr(types, name)

Run: uv run pytest tests/unit/domain/test_domain_event.py -q -k TestTypesVocabulary Expected: FAIL โ€” TenantId is UUID | None; position aliases exist.

Rewrite src/eventsource/domain/types.py:


"""
Domain vocabulary type aliases.

These aliases name the identities that flow through DomainEvent and
DomainCommand, and are threaded through those signatures so the published
vocabulary and the real annotations agree. Optionality belongs to the
field that references an identity, never to the identity type itself: an
event's *reference* to a causing event is optional; a causation id is a
UUID.

Positions are deliberately absent: global feed positions are opaque
ordered tokens owned by the adapter -- see eventsource.ports.positions.
"""

from typing import TypeVar
from uuid import UUID

from pydantic import BaseModel

# Type variable for aggregate state
TState = TypeVar("TState", bound=BaseModel)

# Identity vocabulary
AggregateId = UUID
EventId = UUID
TenantId = UUID
CorrelationId = UUID
CausationId = UUID

Thread through src/eventsource/domain/event.py (import the aliases; annotation-only change, zero runtime effect since aliases erase to UUID): event_id: EventId, aggregate_id: AggregateId, tenant_id: TenantId | None, correlation_id: CorrelationId, causation_id: CausationId | None. Same in command.py for its command_id/correlation_id/causation_id/tenant_id fields (match names actually present โ€” read the file first).

src/eventsource/domain/__init__.py: remove Version, StreamPosition, GlobalPosition from the import block and __all__. src/eventsource/__init__.py: grep -n "StreamPosition\|GlobalPosition\|\"Version\"" src/eventsource/__init__.py โ€” remove any _LAZY/__all__/TYPE_CHECKING entries found (prior grep suggests none exist; verify). Then grep -rn "StreamPosition\|GlobalPosition" src docs and update stragglers (ports/adapters code that type-hints these must switch to plain int or Position as locally appropriate โ€” expect few or none).


uv run pytest tests/unit -q
uv run ruff check src tests && uv run mypy src/eventsource/
git add -A src tests docs
git commit -m "refactor: reconcile domain vocabulary aliases with real signatures; drop position aliases"

Task 3: Typed decider commands โ€” `DeciderAggregate[TState, TCommand]`

Files:

Interfaces:


class TestTypedDecider:
    def test_two_param_subscript_works_at_runtime(self) -> None:
        @dataclass(frozen=True)
        class Ping:
            target: UUID

        class PingState(BaseModel):
            id: UUID

        class PingDecider(DeciderAggregate[PingState, Ping]):
            aggregate_type = "Ping"

            @staticmethod
            def initial_state(aggregate_id: UUID) -> PingState:
                return PingState(id=aggregate_id)

            @staticmethod
            def decide(command: Ping, state: PingState) -> list[DomainEvent]:
                return []

            @staticmethod
            def evolve(state: PingState, event: DomainEvent) -> PingState:
                return state

        agg = PingDecider(uuid4())
        assert agg.execute(Ping(target=agg.aggregate_id)) == []

    def test_single_param_subscript_still_works(self) -> None:
        class LegacyState(BaseModel):
            id: UUID

        class LegacyDecider(DeciderAggregate[LegacyState]):
            aggregate_type = "Legacy"

            @staticmethod
            def initial_state(aggregate_id: UUID) -> LegacyState:
                return LegacyState(id=aggregate_id)

            @staticmethod
            def decide(command: object, state: LegacyState) -> list[DomainEvent]:
                return []

            @staticmethod
            def evolve(state: LegacyState, event: DomainEvent) -> LegacyState:
                return state

        assert LegacyDecider(uuid4()).execute(object()) == []

(Add from dataclasses import dataclass and from pydantic import BaseModel to the test file imports if absent.)

Run: uv run pytest tests/unit/domain/test_decider_aggregate.py -q -k TestTypedDecider Expected: FAIL โ€” DeciderAggregate[PingState, Ping] raises TypeError (too many parameters).

In decider.py: add Generic, TypeVar to the typing import; define after the existing imports:


TCommand = TypeVar("TCommand", default=object)

Change the class line to class DeciderAggregate(AggregateRoot[TState], Generic[TState, TCommand]):, and the signatures to decide(command: TCommand, state: TState) -> list[DomainEvent] and execute(self, command: TCommand) -> list[DomainEvent] (_stamp keeps command: object). Extend the class docstring: two-param subscript gives mypy exhaustiveness checking on a userland command union; single-param keeps object (structural typing per ADR-0022 unchanged).

pyproject.toml: requires-python = ">=3.13"; delete the 3.11 and 3.12 classifier lines (keep :: 3 and :: 3.13). .github/workflows/ci.yml: change every pinned python-version: '3.11' to '3.13', the matrix ['3.11', '3.12'] to ['3.13'], and any if: matrix.python-version == '3.11' guard to '3.13'. Also grep ruff/mypy config in pyproject for target-version/python_version pins (grep -n "py311\|3.11\|target-version\|python_version" pyproject.toml) and bump to py313/3.13 so the linters enforce the new floor.


uv run pytest tests/unit/domain -q && uv run pytest tests/unit/aggregates -q
uv run ruff check src tests && uv run mypy src/eventsource/
git add -A src tests pyproject.toml .github
git commit -m "feat: parameterize DeciderAggregate with defaulted TCommand; require python 3.13"

Task 4: Strict-by-default DeclarativeAggregate + current-practice docstrings

Files:

Interfaces:


class TestStrictUnregisteredDefault:
    def test_unhandled_event_raises_by_default(self) -> None:
        from eventsource.domain.exceptions import UnhandledEventError

        class Surprise(DomainEvent):
            aggregate_type: str = "Strict"

        class StrictAggregate(DeclarativeAggregate[dict]):
            aggregate_type = "Strict"

        agg = StrictAggregate(uuid4())
        with pytest.raises(UnhandledEventError):
            agg.apply_event(Surprise(aggregate_id=agg.aggregate_id), is_new=True)

    def test_explicit_ignore_still_available(self) -> None:
        class Surprise2(DomainEvent):
            aggregate_type: str = "Lenient"

        class LenientAggregate(DeclarativeAggregate[dict]):
            aggregate_type = "Lenient"
            unregistered_event_handling = "ignore"

        agg = LenientAggregate(uuid4())
        agg.apply_event(Surprise2(aggregate_id=agg.aggregate_id), is_new=True)
        assert agg.version == 1

Run: uv run pytest tests/unit/domain/test_aggregate_root.py -q -k TestStrictUnregisteredDefault Expected: first test FAILS (no raise under the old "ignore" default).

(a) Flip the default: unregistered_event_handling: ClassVar[UnregisteredEventHandling] = "error"; rewrite the adjacent comment and the class docstring's strict-mode example (strictness is now the default; show unregistered_event_handling = "ignore" as the explicit opt-down for forward-compat replay scenarios). Rationale line for the docstring: an aggregate is the write model โ€” a silently unapplied event means command handlers reason over divergent state.

(b) Sweep: uv run pytest tests/unit -q โ€” Declarative test aggregates replaying events they don't handle now raise. Per failure, judge intent: if the test exercises lenient handling, set unregistered_event_handling = "ignore" explicitly; if the missing handler is an oversight, add the handler. List each in your report.

(c) Docstring refresh to current practice (no behavior change):


uv run pytest tests/unit -q
uv run ruff check src tests && uv run mypy src/eventsource/
git add -A src tests
git commit -m "feat: default DeclarativeAggregate to error on unregistered events; refresh stale domain docstrings"

Task 5: Decider-first front doors โ€” getting-started.md + index.md

Files:

Interfaces:

Content requirements (authorial task โ€” these bind, wording is yours):


uv run mkdocs build --strict
git add docs
git commit -m "docs: rewrite getting-started and index decider-first"

Task 6: Restructure the explanation layer โ€” aggregate-styles.md + tutorial 08

Files:

Content requirements:


git add docs mkdocs.yml
git commit -m "docs: aggregate-styles as three-style comparison, decider-first testing tutorial"

Task 7: Migrate shared test fixtures to promoted patterns

Files:

Interfaces:


uv run ruff check tests && uv run pytest tests/unit -q
git add tests
git commit -m "test: migrate shared event fixtures to register_event and auto-derived event_type"

Task 8: ADR 0043, changelog, architecture rules

Files:

Content requirements:


### Changed
- **BREAKING: aggregates must declare `aggregate_type`.** The silent `"Unknown"` default on `AggregateRoot` is removed; constructing a concrete aggregate class that does not set the attribute raises the new `AggregateTypeNotSetError`. Aggregate identity is not optional โ€” the old default silently created `"Unknown"`-typed streams.
- **BREAKING: `DomainEvent.aggregate_type` is validated as a stream category** (must match `CATEGORY_PATTERN`); values that would corrupt a `StreamId` (e.g. containing `:`) now fail at event construction instead of detonating at stream-render time.
- **BREAKING: `DeclarativeAggregate.unregistered_event_handling` now defaults to `"error"`** (was `"ignore"`). An aggregate replaying an event it has no `@handles` method for raises `UnhandledEventError` instead of silently skipping it โ€” silent skips let command handlers reason over divergent state. Opt down explicitly with `unregistered_event_handling = "ignore"`. Projections are unaffected.
- **BREAKING: `eventsource.domain.types` reshaped.** `Version`, `StreamPosition`, and `GlobalPosition` are deleted (global positions are opaque adapter-owned tokens โ€” use `eventsource.ports.positions.Position`); `TenantId` and `CausationId` are now plain `UUID` aliases (optionality belongs to the referencing field, not the identity type). The identity aliases are now threaded through `DomainEvent`/`DomainCommand` annotations, so the published vocabulary matches the real signatures.

- **BREAKING: Python 3.13+ is now required** (`requires-python = ">=3.13"`; was `>=3.11`). The typed decider uses native PEP 696 TypeVar defaults, and the project now targets one modern floor instead of carrying compatibility imports. CI tests 3.13.

### Added
- `DeciderAggregate[TState, TCommand]`: optional second type parameter (PEP 696 default `object`) so `decide` can be typed against a userland command union and mypy flags unhandled commands. Single-parameter subscripts keep working unchanged.
- `AggregateTypeNotSetError` exception.

### Docs
- The teaching layer is now decider-first per ADR-0022 ยง5: getting-started and index lead with `DeciderAggregate` + `DomainCommand` + `CommandRejectedError`; `explanation/aggregate-styles.md` is a three-style comparison with the decider first; the testing tutorial leads with `DeciderScenario`. The quickstart no longer recommends hand-declaring `event_type` (auto-derived; explicit only for versioned wire names) and uses `Decimal` money. Stale docstrings in `aggregate.py`/`event_registry.py` updated to current practice.

git add docs CHANGELOG.md mkdocs.yml .claude/rules/architecture.md
git commit -m "docs: adr 0043, changelog, and architecture rules for ddd teaching wave"

Task 9: Full gate and PR


git push -u origin ddd-teaching-wave
gh pr create --base main --title "DDD teaching layer + model guards (ADR 0043)" --body "$(cat <<'EOF'
## Summary
- Teaching layer is now decider-first per ADR-0022 ยง5: getting-started/index rewritten around DeciderAggregate + DomainCommand + CommandRejectedError (Decimal money); aggregate-styles is a three-style comparison; testing tutorial leads with DeciderScenario; event_type hand-declaration contradiction resolved everywhere (docs, docstrings, shared fixtures).
- Model guards (ADR 0043, all breaking, pre-1.0 no-shims): aggregate_type required on aggregates (AggregateTypeNotSetError) and category-validated on events; DeclarativeAggregate defaults to error on unregistered events; domain/types.py reconciled (position aliases deleted, identity aliases plain UUID threaded through real signatures).
- DeciderAggregate[TState, TCommand] with PEP-696 defaulted TCommand: typed decide/execute, exhaustiveness under mypy, single-param subscripts unchanged.

Source: DDD + dogfooding review (.fractal/ddd-dogfooding-review.md), 2026-08-01.

## Test plan
- make check green; TDD per code task (identity guards, category validation, strict default, typed subscripts, vocabulary shapes).
- Quickstart example extracted and executed as a script (output in task report) โ€” the front-door code is verified runnable.

๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"