Skip to content

Screenplay context contracts

A Screenplay context supplies the values an inline or file-referenced implementation can read for its particular job. Choose the contract for a command handler, query performer, validation rule or policy before writing the body: each receives different inputs. The application host supplies those values; naming a member does not fetch it from an identity provider or enforce access.

For body-only code, the target provider supplies the wrapper with context in scope, so you usually write no namespace, class or method signature. A rule receives the caller’s audit identity but no roles or claims. A policy receives the caller’s authorization identity but no event history. Those contracts separate validation from authorization; the host owns compilation and isolation.

The records below describe decision inputs. A top-level application-declared context block serves a different purpose: it declares business time-zone names, with the binding limit explained there.

A command handler is given a CommandContext:

public record CommandContext(
dynamic Command, // the command, conforming to the shape the 'command' declaration gives it
TenantId Tenant, // the tenant the command executes for
Identity Identity, // the caller that sent it
CausedBy CausedBy, // the identity recorded as having caused it
Causation Causation, // what caused it
DateTimeOffset Occurred);

A query performer is given a QueryContext — the same, with the command replaced by the query’s arguments:

public record QueryContext(
dynamic Arguments, // the 'by' and 'filter' parameters the query declares
TenantId Tenant,
Identity Identity,
CausedBy CausedBy,
Causation Causation,
DateTimeOffset Occurred);

QueryContext is the portable sketch. The context a Stage performer body actually receives has Arguments, Tenant, Identity and ReceivedAt only, with no causation or Occurred member (see the performer block). A live performer body receives that same context, captured once per subscription, so ReceivedAt does not advance. It has no cancellation member: disposing the subscription ends the stream. See observable performers.

A validation rule is given a RuleContext — what is being validated, and nothing about what the caller is allowed to do:

public record RuleContext(
dynamic Artifact, // the whole thing under validation — the command, or the concept's own value
dynamic Value, // the value the rule is declared on
string Property, // where that value sits in the artifact; empty for a whole-artifact block
TenantId Tenant,
CausedBy CausedBy, // who is calling — so "you may not approve your own request" is expressible
DateTimeOffset Occurred);

A policy is given a PolicyContext — the caller, and what the decision is about:

public record PolicyContext(
dynamic Artifact, // the command being authorized, or the query's arguments
string Subject, // the identifier of the thing being acted on — what 'matches subject' compares to
Identity Identity, // the caller: authenticated, roles, claims
TenantId Tenant,
DateTimeOffset Occurred);

A concept’s generate rule Name receives a closed GenerationContext in executable semantic model (ESM) v21. The normative version-1 contract is the language-neutral descriptor: Now (an instant), Tenant (the portable TenantId) and a String result. Each language provider binds that descriptor to its target’s native type; Screenplay does not choose one runtime type for all targets.

Target Binding of the descriptor
Cratis C# (Stage, Arc) Cratis.Concepts.GenerationContext from Fundamentals, a struct of DateTimeOffset Now and string Tenant
C# hosts using only the base class library (BCL) Cratis.Screenplay.Contexts.GenerationContext, record GenerationContext(DateTimeOffset Now, TenantId Tenant)
Other languages The provider’s own type for the same descriptor

The provider, not the fence’s language tag, decides the binding: a csharp tag does not distinguish the Cratis C# target from a host that uses the Screenplay record, and file attachments carry no tag. Each provider compiles or admits a body against its own binding and rejects a body that does not fit it.

Cratis.Screenplay.Contexts.GenerationContext stays BCL-only with its current shape. It is name-compatible with the Fundamentals type (Now, Tenant), not type-identical.

To keep a body portable across these C# bindings, use context.Now, the tenant in string interpolation or string assignment, and BCL types. TenantId formats as its value, so $"{context.Tenant}" gives the same string on both bindings.

These uses are target-bound, because they mean something only for one binding:

  • Passing context to GenerateValue.*.
  • Naming GenerationContext or GenerationContext.DefaultTenant.
  • Constructing a context.
  • Reading context.Tenant.Value.

Passing context to Fundamentals APIs is valid only on the Cratis C# target. See the generate rule example and decision 0083.

A generation rule returns the String primitive in context/result contract version 1. It receives no command inputs, caller, injected entropy source or random-state members. TenantOrderId can use this context when the shop needs a tenant-bearing value; built-in TypeID has no tenant slot. A provider adapts Now/Tenant explicitly instead of reading ambient time/tenant APIs or comparing raw "Default" strings.

The reference runner consumes a fixture and never invokes the generation body. Validation implemented in opaque code, whose contents the portable evaluator does not interpret, remains Unsupported. Input-derived generation is tracked in #308.

The portable records live in the Cratis.Screenplay.Contexts package (namespace Cratis.Screenplay.Contexts). Generated applications can reference it without the compiler; existing compiler consumers resolve these types through type forwarding. The host supplies the instance, and the provider determines the binding, including the Stage query and generation differences above.

Reducer rules receive a ReducerContext with State (null before the first event) and Event; they also have StateAs<T>(), EventAs<T>() and KeyAs<T>(). In C# bodies, use the provider’s generated PascalCase member names: for example, context.Event.Amount for an authored amount property. Screenplay keeps authored names in the language and never rewrites opaque bodies. The provider maps compilation errors to body source locations.

A handler’s implementation hints do not add context members or change its result contract. ESM v23 admits described command handlers: a pending intent with unconditional produces gets a Pending CommandHandler requirement and a typed CommandContext descriptor (context/result v1). The descriptor retains generated properties available before the body.

Reference execution stops at the body with Unsupported (ImplementationBody); the descriptor is not proof that a body exists or ran.

Resolved, nonempty file/inline handlers with unconditional produces use the same v23 context/result v1 descriptor; their sidecars carry a language, content hash and span or file reference, not pending hints. Reference execution remains Unsupported at the body, and target-language admission is separate.

Use an application-root context block to declare named business time zones, as specified in decision 0132. This declaration is separate from the runtime records above:

context
description "Time zones the business reasons in."
businessTimeZone time zone
customerTimeZone time zone

A command reads a member as its calendar with calendar from $context.<member>, and the model then selects ESM v37. The host supplies the member’s IANA zone at run time; a specification supplies it with given time zone. A member is a calendar source only: it does not add a $context value to mappings or conditions.

Declare at most one block per application folder, across all its files, as with identity. The block may be empty and may have one description. Members have a lower-case-leading name and the type time zone; no other type or member body is supported. Names are unique after removing an @ escape. timeZone and every existing $context root (command, arguments, tenant, causedBy, causation, occurred and identity) are reserved. Escape a member named description as @description; the printer retains that escape.

The printer places context immediately after an application time zone declaration when one exists. The block declares names, not runtime values or time-zone defaults. See the grammar and context diagnostics.

A provide line adds a named value to $context. Write it in the body of the application, a module, a feature or a slice; everything beneath that level reads it as $context.<name>.

module Fleet
provide region String from "Nordics"
feature DataQuality
provide vessel Vessel optional from query VesselByKey by $context.arguments.vesselId
slice StateView Vessels
query VesselByKey => Vessel optional
by vesselId Uuid
readmodel Vessel
vesselId Uuid
event VesselRegistered
vesselId Uuid
projection Vessels => Vessel
from VesselRegistered key vesselId
vesselId = vesselId

The source is one of:

  • query <Query> [by <expression>, ...] - a snapshot read model query, run once per request.
  • host - a value of the declared name and type that the host supplies.
  • a literal or an expression over other $context values.
  • a file reference or an inline code block under the line, which compile against ProvideContext.

Inheritance is by name and the nearest declaration wins; an override keeps the type. The built-in names tenant, identity, causedBy, causation, occurred, audiences, command and arguments are reserved. Provided values may not read each other in a cycle, and an observable query cannot be a source. A value declared with optional may be absent; any other value is required. A value that comes from a file or an inline code block is admitted by ESM v57 (decision 0167): the model carries the body as an opaque implementation attachment with the ProvideValue role, and the reference evaluator never runs it: the value is opaque, the same as a value from the host. A model without such a value keeps its existing version and bytes.

There are four levels: application, module, feature (features nest) and slice. A slice can state the key for its own job - $context.command.vesselId for a command, $context.arguments.vesselId for a query - which a feature-level provider cannot do for both. A value declared at one level is visible beneath it; a nearer declaration of the same name wins and must keep the type (PLAY1125). Declaring the same name twice at one level is PLAY1123.

module Fleet
provide vessel Vessel optional from host
feature DataQuality
slice StateView Vessels
provide vessel Vessel optional from query VesselByKey by $context.arguments.vesselId
query VesselByKey => Vessel optional
by vesselId Uuid
readmodel Vessel
vesselId Uuid
event VesselRegistered
vesselId Uuid
projection Vessels => Vessel
from VesselRegistered key vesselId
vesselId = vesselId

The slice reads the query result; every other slice of the module reads the host value.

The built-in names tenant, identity, causedBy, causation, occurred, audiences, command and arguments cannot be provided (PLAY1124). A query source must be a declared, keyed snapshot query whose result type matches the provided type (PLAY1126, PLAY1127, PLAY1128). Values that read each other in a cycle are PLAY1129. A $context.<name> that no level provides is refused like any unknown context path.

Absence - a missing key, no matching row, a host value that was not supplied - is unknown, not an error. A gate that reads an unknown value denies, because unknown never opens a gate. A produces mapping refuses the command, so no event is appended. Code sees null for an optional value; a value declared without optional is required, and the request is refused with a clear reason when it is absent.

Failure - the store is unavailable, a code body throws, a timeout - fails the request as a retryable, logged error. It is never reported as a denial, so an outage is not shown as “not available”.

Every context the code behind a model receives - CommandContext, QueryContext, RuleContext, PolicyContext and ProvideContext - has a Values property holding the provided values by name (context.Values.Vessel), empty when the model provides none, and a typed ValuesAs<T>(). In ProvideContext, Values holds only the values already resolved for this request that this one reads.

host, inline code and file sources are opaque: the reference evaluator cannot run them. A gate that reads one is reported as unsupported, never as allowed or denied, as for an opaque policy predicate.

Owner Authoring wrapper Executable contract
Command property named rule Hints with zero or one file/tagged fence Attached source keeps the existing pure RulePredicate context/result version 1; pending fails PLAY0268. The reference runner cannot execute the opaque predicate.
Command handler Hints with zero or one source Pending with unconditional produces: ESM v23 CommandHandler context/result v1. Resolved, nonempty file/inline with unconditional produces: the same ESM v23 contract, no PLAY0695. Unconstrained or unresolved attachments retain PLAY0800; production-less pending is PLAY0696, conditional is PLAY0697.
Operation execute/compensate phase Hints with zero or one source Authoring only; not admitted by any supported executable model (ESM) version yet.
Concept generation rule No wrapper: exactly one direct file/tagged fence ESM v21 ValueGeneration, context/result v1, String result; no body is refused with PLAY0268.
Concept rule, builtin rule, whole-command validation, other owners No new wrapper support Existing direct forms retain their existing contracts and limits.

Command named-rule hints add no RuleContext members. Direct-to-wrapped source and hint edits preserve requirement IDs, typed-context descriptors and canonical ESM bytes. A file selection is not proof of resolution or execution. See named-rule intent and revision-checked edits.

Semantic compilation publishes TypedContextDescriptors beside ImplementationRequirements; pair them with ContextsFor(requirementId). These sidecars describe implementation inputs alongside the executable semantic model (ESM), rather than inside its canonical bytes.

The descriptor contract is revision 1, independently of ESM and the role’s result contract. Each ordered member names a portable model type or runtime token, its nullability and source identity/path. Shaped payloads include ordered properties with their resolved portable types and stable IDs; an optional payload property does not make its containing payload nullable. IsFirst and IsWholeArtifact are marked derived. *As<T>() accessors are methods, not stored data members.

A wrapper provider must reject unknown descriptor contract/context versions, unresolved shapes and unsupported roles rather than generating dynamic. Successful descriptors carry the exact ModelRevision of the same compilation and IsWrapperReady = true; failed compilations publish only resolvable command-handler descriptors, with IsWrapperReady = false and no model revision.

Each descriptor includes a transitive Types table for referenced concepts (including their primitive) and composite types (including their property references). A failed handler with missing type definitions is not renderable. Never attach a failed descriptor to an ESM from elsewhere.

Reducer descriptors are per on Event: State is nullable read-model shape, Event is the non-null current event generation, and Key is the event source identity. Rule descriptors distinguish the whole command or concept value (Artifact) from the validated property (Value); concept value rules use the concept type for both.

For a rule on an optional command property, Value is nullable: an absent property value is null (the reference evaluator represents it as SemanticValue.Null), even though the RuleContext dynamic parameter has no nullable annotation. A provider must permit null in its generated value type and preserve the rule’s documented absence semantics.

Policy descriptors are per authorized command or query use site; an unused policy has no wrapper-ready context. Property uses validated-property with the property ID and a ConstantValue containing its path, or validated-artifact with an empty constant for a whole artifact; Subject uses unavailable where a command has no identifier or its identifier is generated. An event source includes its current contract revision. Policy use sites are necessarily joined by name because ESM policy references carry names rather than IDs. A command with a resolvable shape exposes a CommandContext v1 descriptor even if its handler fails ESM binding. No handler result or envelope is implied.

Query performers, reactions and constraints have no descriptors.

In ESM v7, the typed contexts used before generation (CommandValidation, ConceptValidation, RulePredicate and PolicyPredicate, which serve validation rules, declarative requirements and policies) contain input properties only. Generated properties do not appear in those shapes because they exist only after validation. A generated identifier’s subject is unavailable there, so a policy cannot use it as the thing being acted on. The command handler’s CommandContext keeps the full shape, including generated properties.

The public SemanticContextTypeKinds vocabulary is runtime, shape, model; SemanticContextRuntimeTokens are Text, WholeNumber, Boolean, DateTime, TenantId, Identity, CausedBy, Causation. The first four match portable model primitives (with DateTime representing the runtime occurrence time); the latter four are named host contracts. SemanticContextSourceKinds are context-contract, derived, command, read-model, current-event, event-source-id, model-property, concept-value, validated-property, validated-artifact, authorized-operation, command-identifier, query-key, unavailable. The public SemanticTypedContextSerializer produces the checked-in JSON vectors typed-contexts-v1.json and unbound-handler-context-v1.json, independently of ModelRevision.

These are sidecars of the same compilation as the ESM: canonical v1–v4 bytes and revisions do not include them.

An ESM-only loader cannot reconstruct a typed context. Providers must carry the requirement ID, descriptor version and the matching model provenance together with the attachments, not combine arbitrary compilations.

ValueGeneration descriptors have only non-null Now (DateTime) and Tenant (TenantId) runtime members. Compilation checks owner/rule identity, role, context/result versions, capability and sole body-source linkage; an ESM-only loader can check the requirement id format but cannot fabricate this sidecar.

A command handler descriptor also carries a result object when its body declares may produce (result contract v2). Its members are:

  • resultVersion: the result contract version.
  • entries: one per possible event, in declaration order. Each has eventContract, eventName, eventRevision, payload (a context type), destinationKind, destinationProperty and destinationType.

The destination members say where the event is appended: the kind, the command property that names the stream, and that property’s type.

Type Carries
TenantId The portable tenant identifier. TenantId.Default is the zero GUID (00000000-0000-0000-0000-000000000000); TenantId.NotSet is the empty string.
Identity Id, Name, UserName, IsAuthenticated, Roles, Claims — who the caller is and what they can prove.
Claim Name and Value. A caller may carry the same claim name more than once, so claims are a sequence rather than a dictionary.
CausedBy Subject, Name, UserName — the same three values a projection reads through $eventContext.causedBy.
Causation Type (Command, Reactor, Schedule, …), Occurred, and free-form Properties.

Providers translate the Arc/Chronicle default namespace "Default" into TenantId.Default at the context boundary. They must keep named tenants distinct from the default and reject ambiguous mappings (including a genuinely named zero-GUID tenant), not silently merge them. This is a context-contract v1 rule; it does not change an ESM descriptor or its authored model names.

Identity and CausedBy describe the same caller from two sides. Identity is the decision view — what a policy is allowed to inspect. CausedBy is the audit view — the three values that travel with an appended event. Identity.Id and CausedBy.Subject are the same value.

Identity answers the questions the declarative conditions ask, so a policy written in code reads like the one written in conditions:

context.Identity.IsAuthenticated // require authenticated
context.Identity.HasRole("Accountant") // require role "Accountant"
context.Identity.ClaimValue("department") // require claim "department" matches …
context.Identity.ClaimValues("scope") // every value, when the caller carries the claim more than once

Role names and claim values use ordinal, case-sensitive comparison. Claim names use ordinal, case-insensitive comparison. ClaimValue returns the first matching claim value; use ClaimValues when repeated claims matter. The host supplies the caller data, so these accessors do not validate an authentication token.

The differences are the point, not an oversight:

Context Sees Does not see Why
RuleContext CausedBy Identity Rejecting an input because of who sent it — “you may not approve your own request” — is validation and needs the caller’s identifier. Inspecting roles or claims is authorization and belongs in a policy. Leaving roles and claims out is what keeps the two apart.
PolicyContext Identity CausedBy, Causation A policy decides what a caller may do, and needs what they can prove. It does not record anything, so the audit triple would be dead weight — and leaving it out means the one Subject in scope is unambiguously the thing being acted on, not the caller.
CommandContext / QueryContext both — Implementation code can use decision and audit inputs; receiving them does not itself authorize the operation.

Use context values in a produces mapping, a capture mapping, a tag, or a query parameter without writing code.

Use $identity.<path> to read the caller directly: it is the same value as $context.identity.<path>, not a separate identity. Both spellings remain supported and print as written. The built-in properties are id, name, userName, isAuthenticated, roles and claims; everything after claims. is an opaque claim name. A bare $identity without a path is invalid.

A top-level identity block can also declare typed caller details reachable as $identity.<detail> (not $context.identity.<detail>). These details are authoring metadata only: executable use reports PLAY0268 until admitted (#600); the runtime Identity contract and built-ins are unchanged.

Path Value
$context.occurred When the command or query was received.
$context.tenant The tenant identifier.
$context.command.<property> A property of the command being handled.
$context.arguments.<name> An argument of the query being performed.
$context.causedBy.subject The subject of the calling identity.
$context.causedBy.name The display name of the calling identity.
$context.causedBy.userName The user name of the calling identity.
$context.causation.type What caused this — a command, a reactor, a schedule.
$identity.id or $context.identity.id The caller’s identifier supplied by the host.
$identity.name or $context.identity.name The caller’s display name.
$identity.userName or $context.identity.userName The caller’s user name.
$identity.isAuthenticated or $context.identity.isAuthenticated Whether the caller is authenticated.
$identity.roles or $context.identity.roles The roles the caller holds.
$identity.claims.<name> or $context.identity.claims.<name> The value of a claim the caller carries.
produces InvoiceRegistered
invoiceId = invoiceId
registeredAt = $context.occurred
registeredFor = $context.tenant
registeredBy = $context.causedBy.subject
department = $identity.claims.department

In ESM v2 produces mappings, the portable subset is $context.occurred, $identity.id / .name / .userName (or $context.identity.id / .name / .userName), and the equivalent $context.causedBy.subject / .name / .userName. The two identity spellings bind to identical executable model bytes; roles, authentication state and claims have no portable scalar mapping.

The execution request supplies the occurrence time and audit identity; occurred is the event occurrence time, not a guaranteed append timestamp. identity.id maps to the event context’s causedBy.subject. This is separate from $eventSourceId, which is supplied by the fact’s typed event-source context. The target property must have the matching scalar type (DateTime for occurred, String or Uuid for audit identity). Without request occurrence data, reference execution rejects a command that reads these paths.

Other paths may still be available to code and to other language surfaces, but cannot bind as a portable produces mapping. identity.roles and identity.claims.<name> are collections or unbounded; causation.<anything> is not addressable on Chronicle’s collection-valued causation. $context.tenant is a tenant ID, not Chronicle’s event namespace, and the language does not name a $context.correlation value. These cases report PLAY0268 rather than guessing a mapping.

A path outside the documented language catalog remains a syntax-level warning; admission to ESM is a separate decision.

$context. reaches the command and query contexts only. It is a separate namespace from $eventContext., which reads the metadata of the event a projection is processing: neither falls back to the other, and each is checked against its own catalog. A rule and a policy have no declarative half — a rule names a predicate and a policy states conditions, and those are the declarative form.

Filling a query parameter from the context

Section titled “Filling a query parameter from the context”

Declare a query parameter with from when its value must come from context rather than caller-supplied arguments. For example, the model can state that a tenant filter uses $context.tenant. The host must supply the correct context and honor that binding; a filter declaration does not replace an authorization policy:

query ListInvoices => InvoiceListReadModel[]
description "Every invoice the caller may see"
filter status InvoiceStatus optional
filter tenantId TenantId from $context.tenant
authorize IsAuthenticated

See Queries for the full parameter syntax.

Inside a handler or performer block, context is the corresponding record:

query GetOverdueInvoices => OverdueInvoicesReadModel[]
performer
```csharp
return readModels
.Where(invoice => invoice.Status == InvoiceStatus.Overdue)
.Where(invoice => invoice.TenantId == context.Tenant)
.OrderBy(invoice => invoice.DueDate);
```

Inside a named rule body, context is the RuleContext and the block answers with a bool:

validate
orgNumber rule BeAValidOrganizationNumber message "Must be a valid organization number"
```csharp
string orgNumber = context.ValueAs<string>();
return orgNumber.Length == 9 && orgNumber.All(char.IsDigit);
```

Use the typed accessor for code that calls extension methods such as LINQ. For example, a rule whose value is a collection of integers can use context.ValueAs<IEnumerable<int>>().Sum(). The accessor returns the existing payload as T, so extension methods bind statically; it does not deserialize an ExpandoObject into a new type. The realization must supply the payload as a compatible T. If it does not, the accessor throws ContextPayloadTypeMismatch with the member name and both types (or null).

Context Typed accessor beside the dynamic member
CommandContext CommandAs<T>()
QueryContext ArgumentsAs<T>()
RuleContext ArtifactAs<T>(), ValueAs<T>()
PolicyContext ArtifactAs<T>()
ReducerContext StateAs<T>(), EventAs<T>(), KeyAs<T>()

StateAs<T>() returns null for the first event if T permits null (a reference or nullable value type); it throws ContextPayloadTypeMismatch for a non-nullable value type. Check context.IsFirst before reading a non-nullable state. The original dynamic members remain available, including for existing code that assigns one to a static local before using LINQ. These accessors require the caller to name T; they do not infer the shape from the Screenplay declaration.

ReducerContext.Key stays text. KeyAs<T>() converts it to string (unchanged), Guid (case-insensitive N/D/B/P UUID text, without whitespace), or a type with exactly one public instance constructor taking one string or Guid, such as a key concept: context.KeyAs<TalkId>(). Malformed UUIDs and unsupported types throw ContextKeyNotConvertible without including the raw key; a concept’s own validation exception propagates unchanged. Composite keys and reducers that target an event keep using Key. Renderers use SemanticReducerKeyConversion.KeyType to admit KeyAs<T>() only for the read model’s single required, non-collection Uuid/Text key type, preserving its concept reference when present.

Inside a policy block, context is the PolicyContext and the block answers with a bool — the same answer a require condition gives, so the two forms compose identically. See Policies.

A file reference compiles against the same type as the inline block it replaces, so moving a block out to a file changes nothing about what it can see.