Skip to content

Your first action

An action has four strict Pydantic models: command, private snapshot, display preview, and safe result. The gradual-reveal API keeps those semantics static while host stores, transactions, identities, policies, keys, and ports remain operation scoped.

This tour uses the experimental authoring surface

Adopt threvo_actions.experimental only if the application pins an exact patch, reruns expert-path equivalence tests before every patch upgrade, and reviews migration notes before every minor-line upgrade. Otherwise start with the supported Action facade or construct ActionDefinition directly. All paths use the same runtime and lifecycle.

Copy-paste the installed-wheel example

Copy the file below into an empty directory and run it with the exact package version. It imports only threvo_actions and the Python standard library:

uv run --no-project --with "threvo-actions==0.6.3" python installed_quickstart.py
Copy the file below as installed_quickstart.py
"""Copy-paste quickstart that runs with only the installed wheel."""

from __future__ import annotations

import asyncio
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING

from threvo_actions import (
    ActionType,
    AuthoritativeTarget,
    AuthorityEvaluation,
    AuthorizationResult,
    ExecutionResult,
    ExecutionStatus,
    GovernedExecutor,
    PreparedAction,
    RequestingPrincipal,
    ResolvedState,
    VerificationResult,
    VerificationStatus,
)
from threvo_actions.experimental import (
    ActionApplication,
    ActionComponents,
    ActionRecipe,
    ActionSpec,
)
from threvo_actions.models import ExperimentalModel, SafeReference
from threvo_actions.stores.memory import MemoryActionStore
from threvo_actions.testing import EphemeralProtection, FixedClock, SequentialIdentifiers

if TYPE_CHECKING:
    from threvo_actions.authority import AuthorityBinding, AuthorityEvidence
    from threvo_actions.registry import (
        DecisionContext,
        ExecutionContext,
        PreparationContext,
        ReadContext,
    )

TENANT = "tenant:demo"


class CategorizeCommand(ExperimentalModel):
    expense_reference: SafeReference
    category: SafeReference


class CategorizeSnapshot(ExperimentalModel):
    expense_reference: SafeReference
    previous_category: SafeReference
    category: SafeReference


class CategorizePreview(ExperimentalModel):
    expense_reference: SafeReference
    category: SafeReference


class CategorizeResult(ExperimentalModel):
    applied: bool


class DemoPorts:
    """A deliberately non-effecting host used only to show safe preparation."""

    def __init__(self) -> None:
        self.categories = {"expense:42": "meals"}

    async def prepare(
        self, command: CategorizeCommand, *, context: PreparationContext
    ) -> PreparedAction[CategorizeSnapshot, CategorizePreview]:
        del context
        previous = self.categories[command.expense_reference]
        snapshot = CategorizeSnapshot(
            expense_reference=command.expense_reference,
            previous_category=previous,
            category=command.category,
        )
        return PreparedAction(
            private_snapshot=snapshot,
            display_preview=CategorizePreview(
                expense_reference=snapshot.expense_reference,
                category=snapshot.category,
            ),
            semantic_effect_reference=f"categorize:{command.expense_reference}",
        )

    async def can_prepare(
        self, command: CategorizeCommand, *, context: PreparationContext
    ) -> AuthorizationResult:
        del command
        return AuthorizationResult(allowed=context.tenant_reference == TENANT)

    async def can_decide(
        self, evidence: AuthorityEvidence, *, context: DecisionContext
    ) -> AuthorizationResult:
        del evidence, context
        return AuthorizationResult(allowed=False, reason_code="quickstart_prepare_only")

    async def can_execute(
        self, snapshot: CategorizeSnapshot, *, context: ExecutionContext
    ) -> AuthorizationResult:
        del snapshot, context
        return AuthorizationResult(allowed=False, reason_code="quickstart_prepare_only")

    async def can_read(self, proposal_reference: str, *, context: ReadContext) -> bool:
        del proposal_reference
        return context.tenant_reference == TENANT

    async def evaluate(
        self, *, binding: AuthorityBinding, evidence: tuple[AuthorityEvidence, ...]
    ) -> AuthorityEvaluation:
        del binding, evidence
        return AuthorityEvaluation(satisfied=False, reason_code="quickstart_prepare_only")

    async def resolve(
        self, snapshot: CategorizeSnapshot, *, context: ExecutionContext
    ) -> ResolvedState[CategorizeSnapshot, CategorizePreview]:
        del context
        return ResolvedState(
            current_snapshot=snapshot,
            execution_precondition=f"category:{snapshot.previous_category}",
            materially_drifted=False,
        )

    async def execute(
        self,
        snapshot: CategorizeSnapshot,
        *,
        context: ExecutionContext,
        execution_precondition: str,
    ) -> ExecutionResult[CategorizeResult]:
        del snapshot, context, execution_precondition
        return ExecutionResult(
            status=ExecutionStatus.FAILED_KNOWN,
            reason_code="quickstart_prepare_only",
        )

    async def verify(self, *, context: ExecutionContext) -> VerificationResult[CategorizeResult]:
        del context
        return VerificationResult(
            status=VerificationStatus.TARGET_UNAVAILABLE,
            reason_code="quickstart_prepare_only",
        )

    async def authorize_erasure(self, proposal_reference: str, *, context: ReadContext) -> bool:
        del proposal_reference, context
        return False


@dataclass(frozen=True)
class Dependencies:
    ports: DemoPorts
    store: MemoryActionStore
    protection: EphemeralProtection
    clock: FixedClock
    identifiers: SequentialIdentifiers


def components(
    dependencies: Dependencies,
) -> ActionComponents[CategorizeCommand, CategorizeSnapshot, CategorizePreview, CategorizeResult]:
    return ActionComponents(
        preparation=dependencies.ports,
        authorization=dependencies.ports,
        authority_evaluator=dependencies.ports,
        state_resolver=dependencies.ports,
        executor=dependencies.ports,
        verifier=dependencies.ports,
        commitment_provider=dependencies.protection,
        protection_codec=dependencies.protection,
        retention=dependencies.ports,
        store=dependencies.store,
        retention_store=dependencies.store,
        clock=dependencies.clock,
        identifiers=dependencies.identifiers,
    )


async def main() -> None:
    dependencies = Dependencies(
        ports=DemoPorts(),
        store=MemoryActionStore(),
        protection=EphemeralProtection(acknowledge_data_loss=True),
        clock=FixedClock(datetime(2026, 1, 1, tzinfo=UTC)),
        identifiers=SequentialIdentifiers(),
    )
    actions = ActionApplication[Dependencies]()
    categorize = actions.register(
        ActionSpec[CategorizeCommand, CategorizeSnapshot, CategorizePreview, CategorizeResult](
            action_type=ActionType(namespace="example.expense", name="categorize", version=1),
            command_model=CategorizeCommand,
            private_snapshot_model=CategorizeSnapshot,
            display_preview_model=CategorizePreview,
            result_model=CategorizeResult,
            proposal_ttl=timedelta(minutes=15),
            executor_identity=GovernedExecutor(reference="executor:expense-service"),
            target_identity=AuthoritativeTarget(reference="target:expense-ledger"),
            authority_audience="audience:finance",
            authority_channel_assurance="channel:authenticated-ui",
        ),
        ActionRecipe(bind=components),
    )
    actions.freeze()

    print(actions.inspect(categorize).action_type)
    with actions.bind(categorize, dependencies=dependencies) as action:
        prepared = await action.prepare(
            tenant_reference=TENANT,
            command=CategorizeCommand(
                expense_reference="expense:42",
                category="travel",
            ),
            requesting_principal=RequestingPrincipal(reference="user:demo"),
        )
    print(prepared.display_preview)


if __name__ == "__main__":
    asyncio.run(main())

This first program deliberately stops after safe preparation: its host denies authority and execution. EphemeralProtection and MemoryActionStore are explicit test helpers, not production custody or persistence.

Run the production-shaped source tour

The source distribution contains a 68-line executable tour:

uv run python -m examples.docs.quickstart

It imports the complete, production-shaped refund host from examples/refund/. That separation keeps the full lifecycle readable while the installed-wheel example above remains self-contained.

Show the executable tour
"""Small executable tour of the experimental authoring API.

Run from the source distribution with ``uv run python -m examples.docs.quickstart``.
The imported refund host is the production-shaped part; this file stays small
so the registration, inspection, and operation flow are easy to see.
"""

from __future__ import annotations

import asyncio
from decimal import Decimal

from examples.refund.app import TENANT, build_refund_application

from examples.refund.domain import PaymentOrder, RefundCommand
from threvo_actions import EvidenceConsumer, Money, ReadContext



def money(amount: str) -> Money:
    return Money(amount=Decimal(amount), currency="EUR")


async def main() -> None:
    demo = build_refund_application()
    contract = demo.actions.inspect(demo.refund)
    print(contract.action_type)
    demo.ledger.add(
        PaymentOrder(
            order_reference="order:42",
            payment_reference="payment:private:42",
            customer_contact="private@example.test",
            captured=money("100.00"),
            refunded=money("20.00"),
        )
    )

    prepared = await demo.prepare(
        RefundCommand(
            intent_reference="intent:refund:42",
            order_reference="order:42",
            amount=money("30.00"),
        )
    )
    print(prepared.display_preview)

    # The host authenticates the manager and records exact authority evidence.
    await demo.approve(prepared.proposal_reference)

    # Execution re-reads the order and refuses material drift.
    accepted = await demo.execute(prepared.proposal_reference)
    demo.clock.advance(demo.specification.verification_delay)
    verified = await demo.reconcile(prepared.proposal_reference)
    print(accepted.outcome, verified.outcome, verified.safe_result)

    view = await demo.read(
        prepared.proposal_reference,
        context=ReadContext(
            tenant_reference=TENANT,
            consumer=EvidenceConsumer(reference="operator:auditor"),
        ),
    )
    print([receipt.receipt_type for receipt in view.receipts])



if __name__ == "__main__":
    asyncio.run(main())

Compose the application

For this experimental tour, use ActionSpec for immutable action semantics and ActionComponents for borrowed, live resources. Register explicitly, then freeze the catalog before serving work:

actions = ActionApplication[RefundDependencies]()
refund = actions.register(
    specification,
    ActionRecipe(bind=refund_components),
)
actions.freeze()

ActionApplication retains the specification, recipe callable, and opaque typed handle. It must not retain a tenant, principal, transaction, store instance, proposal key, viewer, or bound ports. The host owns those resources and supplies a dependency container from a fresh operation or request scope. The in-memory reference app creates a new container for each call while sharing its store, clock, and port objects; it does not pretend to model a database transaction.

Bind one operation

with actions.bind(refund, dependencies=dependencies) as bound:
    prepared = await bound.prepare(
        tenant_reference=tenant_reference,
        command=command,
        requesting_principal=requester,
        proposing_agent=agent,
    )

The binding compiles to the unchanged expert ActionDefinition and ActionRuntime. Exiting the context invalidates the facade; the library never closes borrowed host resources. Your dependency scope owns commit, rollback, and cleanup.

Inspect without touching live resources

contract = actions.inspect(refund)
print(contract.action_type)
print(contract.boundary_models)
print(contract.settings)

Inspection is static and allowlisted. It does not invoke the recipe, query a store, check credentials, or authorize execution. Database readiness remains an adapter-specific startup gate.

What the tour proves

  1. prepare() resolves canonical host state and persists a protected snapshot.
  2. Only the minimized preview crosses the confirmation boundary.
  3. Authority evidence binds the exact tenant, proposal, effect, commitment, audience, channel, and expiry.
  4. execute() repeats live authorization and state resolution before effect admission.
  5. Target acceptance becomes verification_pending, not false completion.
  6. reconcile() queries the authoritative target and reaches verified.
  7. read() returns a tenant-scoped projection and typed receipts.

The reference application uses in-memory storage and example-only protection. A real deployment still needs authenticated identity, durable storage, managed key custody, authoritative target queries, reconciliation scheduling, retention operations, and monitoring. Sugar may refuse or delegate; it never grants authority or invents those production requirements.

Next read how the lifecycle works, the complete refund reference application, and the versioning boundary.