Language Reference

DMX Specification Language

The complete reference for writing DevMatrix specifications. From data types and annotations to flows, state machines, and infrastructure.

Declare domain event publishers, job handlers, search projections and analytical sources explicitly, with their payloads and resource bindings.

Overview

DMX (DevMatrix Specification Language) is a declarative language for defining backend platforms — their services, their infrastructure and their deployment. A single .dmx file describes entities, APIs, business flows, state machines, security, infrastructure, and more — then compiles deterministically to production-ready code.

A platform is not necessarily a set of microservices. architecture { mode = ... } takes standalone (one service — a monolith), microservices or mixed, and the rest of the spec is written the same way in all three: the shape of the deployment is a declaration, not a different language.

DMX is not a template engine. Every construct maps to concrete backend code, and the same spec always compiles to the same output. There is no interpolation, no scripting, and no runtime interpretation.

Lexical Structure

DMX source files use UTF-8 encoding. The language is whitespace-insensitive (indentation is conventional, not syntactic). Blocks are delimited by curly braces {}.

Comments

Line comments start with //. Block comments use /* ... */.

Comments
// This is a line comment

/* This is a
   block comment */

service "UserService" {
  docs { operator_only }
  version  = "1.0.0"   // trailing comment
  port     = 8000
  database = "user_service"
}

Strings

Strings are double-quoted only. Backslash escapes are supported: \", \\, \n.

Numbers

Integer literals: 42, 0. Float literals: 3.14. No hex/octal support.

Identifiers

PascalCase for entities and types (UserProfile). snake_case for fields and keywords (created_at). UPPER_SNAKE_CASE for enum values (ACTIVE, PENDING_REVIEW).

Operators

= — assignment. -> — state transition or mapping. * — wildcard/all. The operators of a condition, an expression or a @check are under Expressions.

Filter comparisons

A filter {} entry compares its field with its value: = by default, and !=, >, >=, <, <= where the step selects a set of rows. Every entry of one filter must hold (they are ANDed), and each field appears once.

  • Where. A comparison other than = works in the filter of a batch, delete or export step, of a query step that declares query_cardinality = "list", and of a foreach source_query. A step that addresses one row (a query without "list", an update) and a foreach do {} compare by = only.
  • Types. >, >=, <, <= compare a numeric field (Integer, Float, Decimal) or a Date/DateTime field; != compares any field. An Integer or Decimal field takes a whole-number literal, a Float field takes any number; a Date/DateTime field takes no literal, only a value of its type ($input, $query, $result, or a $computed date such as $computed.now); a $input, $query or $result value is read as the field's type.
  • Meaning. Each comparison is its own SQL condition, its value a bound parameter. A row whose field is empty is selected by no comparison, and a value that is absent at run time selects no row (!= included).
  • Refused at /validate and by the build, naming the line and the fix: FILTER_COMPARISON_POSITION (a comparison other than = where only = is accepted), FILTER_COMPARISON_SINGLE_ROW (a comparison in a step that addresses one row), FILTER_COMPARISON_SOFT_DELETE (a delete by comparison on a @soft_delete entity: iterate the rows with a foreach whose source_query holds the filter, and delete each one), FILTER_COMPARISON_UNORDERED (>, >=, <, <= on a field whose values do not order), FILTER_COMPARISON_VALUE_TYPE (a literal of another type than the field's, or any literal on a Date/DateTime field), FILTER_COMPARISON_IDENTITY (a comparison with a $context value: the caller's identity scopes rows by = only), FILTER_COMPARISON_SENSITIVE (a comparison on a @sensitive field, stored encrypted and matched by = only) and FILTER_FIELD_TWICE (one field twice in one filter).
Filter comparisons
flow "Born Before" {
  type    = workflow
  trigger = "GET /customers/born-before"
  entity  = Customer
  step 1 "Read them" {
    action            = query
    target            = Customer
    filter            { status = "ACTIVE"  birth_date < $query.before }
    result_field      = "customers"
    query_cardinality = "list"
  }
}

Expressions

A flow step's condition and expression, a foreach do {} condition, a state guard's condition, a validation rule's condition and a field's @check(...) are written in one expression language, without quotes:

  • condition = $instance.status IN ['SCHEDULED', 'CONFIRMED']
  • condition = $input.amount > 0 and $context.tenant_id != null
  • expression = sum(task.hours for task in $result.open_tasks)
  • amount Decimal(10,2) @check(amount >= 0)

DevMatrix reads it once, as a typed expression; nothing recovers operators from text later. A call outside the list below is refused, by /validate and by the compile (EXPRESSION-CALL-NOT-IN-LANGUAGE-001): the generated code would call a name nothing defines. The validator also checks that $input.<f> names a field of the endpoint's request, that $query.<f> names a declared query { } parameter of an HTTP-triggered flow, and that $instance.<f> names a field of the target entity.

The earlier quoted form. condition = "$input.amount > 0" still compiles as the same expression; /validate warns and shows the unquoted spelling (EXPRESSION-WRITTEN-QUOTED-001). Quoted text that is not an expression is refused (EXPRESSION-SLOT-IS-PROSE-001): prose cannot become code. Two phrases of a validate step keep compiling until their typed form exists, with a warning (EXPRESSION-SLOT-IS-A-RECOGNISED-PHRASE-001): the one-time-code check TOTP code $input.<f> matches user secret and the password check [algorithm] verify $input.<f> against <Entity>.<field>.

Operator words as keys. Right after a value, a key spelled as an operator word (in, is, not, and, or, if, else, for, contains) reads as the operator; the parse error says so, and the entry is written first in its block.

Value positions. A mapping {}, filter {} or payload_map {} entry and a query_value read one value: a literal or one $ reference ($input.<f>, $query.<f>, $context.<f>, $instance.<f>, $result.<f>[.<f>], $item[.<f>], $computed.<fn>(...)). null is written in mapping {} only. Any other value is refused naming it (VALUE-POSITION-HAS-NO-READING-001); compute it in a step expression and read its result.

A comparison with an empty side refuses. In a validate (and in every guard generated from one), ==, !=, <, <=, >, >=, IN, NOT IN, contains, starts with and ends with with an empty value on either side are unknown, as SQL reads a WHERE, and an unknown guard refuses the request. $result.manager.manager_id != $instance.id refuses a manager with no manager of their own. To let an empty value through, say so: $result.manager.manager_id == null or $result.manager.manager_id != $instance.id. Only == null / != null test for an empty value. The Workshop validator warns (GUARD_REFUSES_EMPTY_SIDE) on each such comparison over a nullable field that neither the condition nor an earlier validate rules out, and gives the line to write; keep the comparison as it is when refusing is what you mean. The test of a conditional (<a> if <test> else <b>) chooses as SQL CASE WHEN does: an unknown test takes the else branch.

Text tests. a contains b holds when b is part of the text a, or a member of the list a; a starts with b and a ends with b test the start and the end of the text a. All three are case-sensitive: 'NET-7' starts with 'net-' is false. contains on a $context value is the caller's own authorization: the only form DevMatrix supports is a scope requirement written as the whole condition, $context.scopes contains '<scope>', which the route checks; any other contains on $context is refused at /validate (FLOW-VALIDATE-PREDICATE-NOT-LOWERABLE) and by the compile.

Two quoted dialects remain. A field's @check may be written relative to its field, quoted: @check(">= 0 AND <= 28") (the field is the subject of each clause that starts with an operator). An entity-level @check("a < b") and @computed("...") stay quoted text: @computed reads || as concatenation (@computed("first_name || ' ' || last_name")), where the expression language reads it as or.

reference

`$input.<f>`, `$query.<f>`, `$context.<f>`, `$instance.<f>`, `$result.<step>.<f>`, `$item.<f>`, each with a deeper path (`$input.address.city`); `$instance` and `$item` alone; `$computed.<fn>` and `$computed.<fn>(...)`

literal

`'text'` or `"text"`, `12`, `1.5`, `true` `false`, `null` (`None`)

arithmetic

`+` `-` `*` `/` `%`, unary `-`

comparison

`==` `=` `!=` `<>` `<` `<=` `>` `>=`, `contains`, `starts with`, `ends with`

membership

`x in (a, b)`, `x in [a, b]`, `x not in ...`, a list comprehension or a reference as the members

null test

`x is null`, `x is not null` (`IS NULL` / `IS NOT NULL`)

logic

`and` `or` `not` (`AND` `OR` `NOT`, `&&` `||` `!`)

conditional

`a if test else b`

call

`abs all any bool float int len max min round str sum isinstance type now current_timestamp`; `round(x, n, "<mode>")` names a rounding mode

rounding

`round(x, n)` rounds to `n` decimal places, half to even. `round(x, n, "<mode>")` names the mode, one of `half_even` (the default), `half_up` and `half_down` (to the nearest, a tie away from or toward zero), `up` and `down` (away from or toward zero), `ceiling` and `floor` (toward positive or negative infinity). Only a value written to a `Decimal` field takes a mode. A value written to a `Decimal(p,s)` field keeps at most `s` fraction digits: the service stores it exactly or refuses it with 422 and never rounds it to fit, so `/validate` names a value that can carry more digits and the correction to write, `round(<value>, s)`.

comprehension

`[x.f for x in $result.rows if x.g]`, and reduced: `sum(x.f for x in $result.rows)` (`sum all any min max`)

postfix

`.attribute`, `.total_seconds()`, `[index]` on any value but a bare `$` reference (whose path is written in full)

Annotations

Annotations start with @ followed by an identifier. Some accept parenthesized arguments: @default("active"), @fk(User.id).

Dollar Tokens

Runtime references prefixed with $. Simple: $input, $context. Dotted: $computed.now, $input.email, $query.status.

Data Types

DMX supports 18 data types that map to database column types and API schema types.

UUID

Universally unique identifier (v4)

String

Variable-length text, up to 255 characters

Text

Unlimited-length text (CLOB/TEXT)

Integer

Whole number (32-bit signed)

Float

IEEE 754 floating-point

Decimal

Arbitrary-precision decimal

Boolean

true or false

Date

Calendar date without time (YYYY-MM-DD)

DateTime

Date and time with timezone (ISO 8601)

Time

Time of day without date

JSON

Arbitrary JSON object or array

Bytes

Binary data (BLOB)

Array

Ordered collection of a single type

Enum

Enumerated set of named values

Char

Fixed-length character string

Point

Geographic point (latitude, longitude)

Polygon

Geographic polygon boundary

Geometry

Arbitrary geometric shape

Every entity field has a name, a type, and optional annotations.

Field declarations with types
entity User {
  id          UUID       @pk @default($computed.uuid)
  email       String(255) @not_null @unique
  name        String(200) @not_null @freetext
  bio         Text
  age         Integer
  balance     Decimal(12, 2) @default(0)
  is_active   Boolean    @not_null @default(true)
  joined_at   DateTime   @not_null @default($computed.now)
  metadata    JSON       @default({})
  role        Enum(ADMIN, MEMBER, GUEST) @not_null @default("MEMBER")
}

Annotations

Annotations modify the behavior of fields, entities, APIs, state machines, and ClickHouse columns.

Field Annotations

@pk

Primary key

@pk
@not_null

NOT NULL constraint

@not_null
@unique

Unique constraint

@unique
@nullable

Allows NULL values

@nullable
@default

Default value

@default("value") or @default($computed.now)
@fk

Foreign key reference. Three options, each at most once and in any order: on_delete (cascade, restrict, set_null, no_action; restrict when undeclared) and on_parent_terminal, whether this entity's rows keep their own lifecycle once the referenced row is in a terminal state of its state_machine: independent (they do; the warning TERMINAL_TRANSITION_WITH_RELATED_ROWS_MID_STATE is answered for this reference) or settled (they are settled before the parent closes; the warning stays). on_parent_terminal is never defaulted: undeclared keeps the warning. attribution: true says the column only names who or what the row is attributed to: reading the row reads no row of the referenced entity, so the reference does not make this entity its child for read scopes. It is refused with a policy condition on the same column, with on_delete: cascade and with on_parent_terminal: settled, each of which says the row belongs to that entity. A repeated option does not parse.

@fk(Entity.field) or @fk(Entity.field, on_delete: cascade, on_parent_terminal: independent)
@check

Check constraint expression

@check(age >= 18)
@min_length

Minimum string / collection length (non-negative integer). Pairs with the max_length that String(N) / Char(N) already imply

@min_length(8)
@min

Minimum numeric value. SIGNED — negative bounds are legitimate

@min(0) or @min(-40)
@max

Maximum numeric value. SIGNED — negative bounds are legitimate

@max(100) or @max(-1)
@required

Required in API input

@required
@sensitive

PII / secrets — excluded from logs

@sensitive
@sensitive(readable_by)

A @sensitive field the listed security roles read back: shown to a principal holding one of them, omitted for everyone else. Each role must be declared and allowed to read the entity; credentials are never granted

@sensitive(readable_by: [ADMIN, DISPATCHER])
@computed

Server-computed, not in API input

@computed
@json_list

Store as JSON array column

@json_list
@immutable

Cannot be updated after creation

@immutable
@indexed

Create a database index

@indexed
@freetext

Free human text — fixes the injection security class

@freetext
@scoped

ABAC row-filter: binds this column to a principal claim (scoped / scope_match strategy)

@scoped(claim="sub")
@scope_anchor

ABAC scope anchor: when a child has N>1 @fk to the same @scoped parent, marks WHICH FK anchors the inherited transitive row-scope (else first-declared anchors)

@fk(User.id) @scope_anchor
@scope_reverse

ABAC reverse scope marker: on a junction (M2M bridge) entity's parent-@fk column, grants the parent reverse row-visibility to rows reachable through the junction (reverse-EXISTS RLS). Junction (@role(membership)) @fk columns only.

@fk(Org.id) @scope_reverse
@format

OpenAPI format hint (closed vocab: date-time, credit-card, datetime, hostname, duration, binary, email, guid, ipv4, ipv6, phone, regex, uuid, iban, byte, date, time, url, uri, tel). email, uuid and guid are enforced by the generated service — 422 on malformed input

@format(email)
@pattern

Explicit validation regex

@pattern("^[A-Z]{3}$")
@validation_pattern

Validation pattern type (snapshot, calculation, immutability, constraint, relationship)

@validation_pattern(calculation)
@value_from

Origin of a credential-grant response DateTime field: access_token_expires_at or refresh_token_expires_at. Uses the same expiry instant as the minted token; refresh origin requires refresh_token_enabled=true. The field is nullable on grant branches that do not mint that token.

valid_until DateTime @value_from(access_token_expires_at)
@seed_template

Seed-data value shape (email, personal_name, url, phone, description, currency_code, timestamp)

@seed_template(email)
@field_purpose

Semantic field purpose (closed allowlist: auth_failed_attempts, auth_locked_until, auth_last_login, auth_email_verified, password, ref_external, ref_polymorphic, ref_historical, object_key) — declares a capability-owned auth field (or the credential password: on a column, the password hash; on a login request field, the password) so the compiler recognises it by its role rather than by its name. The ref_* family declares WHY an <name>_id column is NOT a local foreign key, so the compiler stops minting one from the spelling: ref_external (referent in another service, needs a declared depends_on edge), ref_polymorphic (referent entity varies per row, needs a discriminator column), ref_historical (referent may already be deleted, needs @append_only). Declaring one together with @fk is a contradiction and is refused. object_key declares that a String column holds a key of this module's object store: every request that writes it refuses a key with an empty, . or .. segment, and a stored row is never re-checked on read. It is declared, never inferred — a URL, a hash and an identifier admit / and . too — so validation warns (HIERARCHICAL_STRING_DECLARES_NO_PURPOSE) a String whose @pattern admits both and declares no purpose, in a module whose object_storage has no key holder yet (once one is declared, every other String is not a key; with no store, none is); declaring object_key on a non-String column, or in a module with no object_storage block (OBJECT_KEY_WITHOUT_OBJECT_STORAGE), is refused.

@field_purpose(auth_locked_until)
@hashed_from

On a @field_purpose(password) column: the request field whose value the column stores hashed. A flow that writes the column with $computed.hash_password($input.<field>) already says it; declare @hashed_from when no flow writes the column (principals that only sign in, created by the seed). The login reads its request's @field_purpose(password) field instead. When both are present they must name the same field: two different fields are refused, never resolved by precedence. Valid only on a @field_purpose(password) column.

@hashed_from(password)
@polymorphic

The declarative half of a polymorphic reference. Goes on the SAME column as the ref_polymorphic purpose, which is required (without that opt-out the compiler still mints a foreign key to ONE table out of the column spelling while the map declares N, and the pair is refused at authoring time). discriminator: names an Enum column on the same entity; targets: maps each of its values to the entity that value names. The mapping is explicit — nothing reads the target out of the value spelling, so CONTACT -> Contact, PRIMARY_CONTACT -> Contact and CONTACT -> Deal are all legal. Both arguments are mandatory and the target list is one-or-more, so a half-declared reference is a parse error. Checked: the discriminator exists and is an Enum, its members and the declared values are the same set, and every target is an entity of the module or an imported one.

@polymorphic(discriminator: entity_type, targets: [CONTACT -> Contact, DEAL -> Deal])
@value_from

Origin of a credential-grant response value (closed taxonomy: access_token_expires_at, refresh_token_expires_at). DevMatrix owns the login/refresh response envelope — it mints the token, so it decides the shape — which used to mean a field the author declared there was accepted at validation and then never appeared in the generated response. It now either restates a field the envelope already mints, or names its origin with @value_from and is filled from that origin, or the build stops naming the field. The instant it names is the SAME object the token was minted with, never a second reading of the clock, so the expiry the response advertises and the expiry inside the token cannot disagree. @value_from(refresh_token_expires_at) requires refresh tokens enabled in the module; a grant that does not always re-mint (no rotation, or the MFA challenge branch) makes the field nullable rather than lying about it.

@value_from(access_token_expires_at)
@otp_code

Marks the field carrying a fixed-format OTP/TOTP code. The validator structurally joins its String(N) length against security { mfa { code_digits = N } } — never a name match on a field called "code"

code String(6) @otp_code
@auth_me

Appends this scalar to the compiler-owned GET /auth/me response. Field scope, and the authenticated principal entity only — the validator rejects it on any other entity, on a sensitive/credential field, on an unsupported type, and when the same field declares it twice

display_name String @auth_me
@deprecated

Marks field deprecated (since / until / replacement)

@deprecated(since: "1.2", replacement: "new_field")

Entity Annotations

@aggregate_root

DDD aggregate root — owns child entities

@aggregate_root
@tenancy

Tenant scope and the column that holds it: workspace (the column holds the tenant) or user (the column holds the signed-in user). Any other scope is refused; a global entity declares no @tenancy

@tenancy(workspace, workspace_id)
@description

Human-readable description

@description("User accounts")
@audit

Auto-generate created_at / updated_at / deleted_at

@audit
@cache

Rows may be served from the cache for at most ttl seconds (1–86400); bare @cache takes the ttl of redis { cache { enabled = true; ttl = N } }, which the module must declare. The cache stores the rows sealed with a key derived from the service's ENTITY_CACHE_ENCRYPTION_KEY (url-safe, at least 32 characters; the service does not start without it). Not allowed on an entity that decides access or the audit trail; rows with sensitive fields need use_ssl = true in redis

@cache(ttl: 300)
@soft_delete

Soft delete (set deleted_at) instead of hard delete

@soft_delete
@platform_scope

Not tenant-scoped (platform-level entity)

@platform_scope
@append_only

Insert-only table (no UPDATE or DELETE)

@append_only
@append_only_after

Entity becomes immutable once the named field reaches the given state. The state value comes FIRST, the field name second.

@append_only_after(ISSUED, status)
@tamper_evident

Chains the rows: each carries a per-tenant sequence, the previous row's hash and an HMAC-SHA256 over its values keyed by AUDIT_SIGNING_KEY (which becomes required). Sealed on insert (@append_only) or when the row reaches STATE (@append_only_after); a verifier script reports the first broken row. Requires @append_only or @append_only_after on the same entity.

@append_only @tamper_evident
@append_only_with

Child rows freeze with their parent: while the parent row the named @fk field references is in the state its @append_only_after declares, no row under it is inserted, updated or deleted (a database trigger holds it for every writer; the service answers 409). The field must carry @fk to an entity of the same spec that declares @append_only_after.

@append_only_with(entry_id)
@regulated

Traceability trinity: the request field, the reference the shared-kernel counter generates (a String/Char/Text that is not the primary key) and the traced item. Three distinct stored fields; the only way an entity is traced.

@regulated(request: booking_ref, reference: waybill_no, item: parcel_tag)
@unique_together

Composite unique constraint

@unique_together(field_a, field_b)
@check

Entity-level check constraint

@check("start_date < end_date")
@relation

Define relationship to another entity

@relation("has_many", Target)
@role

Entity role classification (domain, user, credential, workspace, membership, audit, infra)

@role(audit)
@deprecated

Marks entity deprecated (since / until / replacement)

@deprecated(since: "2.0", replacement: "Order")

API Annotations

@entity

Bind API to an entity

@entity(User)
@paginated

Enable pagination

@paginated
@status

Override HTTP status code

@status(201)
@triggers

Declares that this endpoint causes a state transition. The entity's state_machine must declare a transition to that state

@triggers(Order.status -> CONFIRMED)
@self_resource

Endpoint operates on the caller's own resource (self-access)

@self_resource
@filters

Binds a declared query param to the entity column it filters, and to the operator it filters WITH (closed taxonomy: eq, ne, gt, gte, lt, lte, contains, in — defaults to eq). A param declared in query { } and bound to nothing used to reach the route, be accepted, and change nothing: the endpoint answered 200 with the rows UNFILTERED and the generated test passed, because an unbound query param is silently ignored. The target names an entity and one of ITS attributes, so a typo in either half blocks at authoring time instead of shipping a filter that never filters. Params the pagination contract owns (skip, limit, page) need no binding — they are consumed by the contract, not by a where clause.

@filters(Patient.status)
@path

On a request_params parameter of a request-reply interaction: the value travels in the path of the outbound call. The location is declared, never inferred from the name.

order_id UUID @path @required
@query

On a request_params parameter of a request-reply interaction: the value travels in the query string of the outbound call.

currency String @query
@body

On a request_params parameter of a request-reply interaction: the value travels in the body of the outbound call.

coupon String @body
@filters (with operator)

The second argument picks the comparison. contains renders a LIKE with the value escaped, and in takes a list — both parameterised, never interpolated.

@filters(Patient.last_name, contains)
@security_tier

Endpoint security tier

@security_tier = "public"
@deprecated

Marks endpoint deprecated (since / until / replacement)

@deprecated(since: "2.0", replacement: "/v2/users")

State Machine Annotations

@roles

Restrict transition to roles

@roles(ADMIN, MANAGER)
@guard

Guard condition for transition

@guard(APPROVED) { condition = $instance.amount > 0 }

ClickHouse Annotations

@nullable

Allow null values in the analytical column

@nullable
@low_cardinality

ClickHouse LowCardinality optimization

@low_cardinality
@pii

Mark column as PII with its declared strategy

@pii(hash)

Dollar Tokens ($)

Runtime value references used in defaults, flow steps, and computed fields. The compiler resolves these to actual code. **Erasing a person's row.** A step that erases a record replaces each personal value with one that says nothing about the person. For a required, unique address column write `$computed.erased_value`: a fresh random address at `erased.example`, a domain reserved by RFC 2606 that receives no mail, so the column keeps its `@format(email)` and its `@unique`. For other text columns `$computed.random_token` or a literal is enough. Never write `$computed.hash` of the old value: the same address always gives the same digest, so the digest still identifies the person. A fresh random helper that is not an address (`$computed.random_token`, `$computed.secure_random(n)`, `$computed.uuid`, a digest, a TOTP secret) written to a column declared `@format(email)` is refused (`COMPUTED-VALUE-NOT-AN-EMAIL-001`): the row would be stored and could no longer be returned.

$input

Current request/step input data

$input.email, $input.password
$query

A value from the request QUERY STRING, bound to a param the endpoint declares in its query { } block. Distinct from $input, which is the request BODY: the two resolve from the same runtime dict, but a filter bound to a body field on a GET is a different contract from one bound to a query param, and the build records which it is. The validator rejects a $query reference that names no declared param, and one written on a flow with no HTTP trigger

$query.status, $query.from
$context

Execution context (authenticated user, tenant, request metadata)

$context.user_id, $context.tenant_id
$instance

Current entity instance (in flows and state machines)

$instance.status, $instance.id
$result

Result from the previous flow step

$result.id, $result.token
$item

Current iteration element inside a foreach do{} body — bare $item is a scalar element, $item.<field> a field of a record element

$item, $item.id
$computed.now

The current date and time, in UTC.

@default($computed.now)
$computed.now_plus_minutes

The current date and time plus `n` minutes, in UTC.

$computed.now_plus_minutes(15)
$computed.now_minus_minutes

The current date and time minus `n` minutes, in UTC.

$computed.now_minus_minutes(5)
$computed.now_plus_hours

The current date and time plus `n` hours, in UTC.

$computed.now_plus_hours(24)
$computed.now_minus_hours

The current date and time minus `n` hours, in UTC.

$computed.now_minus_hours(72)
$computed.now_plus_days

The current date and time plus `n` days, in UTC.

$computed.now_plus_days(7)
$computed.now_minus_days

The current date and time minus `n` days, in UTC.

$computed.now_minus_days(30)
$computed.token_expiry

The current date and time plus 24 hours, in UTC: the default lifetime of a reset or verification token.

expires_at = $computed.token_expiry
$computed.uuid

A new random UUID (version 4).

@default($computed.uuid)
$computed.random_token

A new unguessable URL-safe token from 32 random bytes.

reset_token = $computed.random_token
$computed.secure_random

A new unguessable URL-safe token from `n` random bytes.

api_key = $computed.secure_random(48)
$computed.erased_value

A new random email address at a reserved domain that receives no mail, unrelated to any earlier value: what an erased record keeps in a required, unique address column.

email = $computed.erased_value
$computed.recovery_codes

A list of `count` new recovery codes, each from 8 random bytes.

$computed.recovery_codes(10)
$computed.token_hash

The SHA-256 hex digest of `token`, to store a token without storing the token itself.

refresh_hash = $computed.token_hash($result.refresh_plaintext)
$computed.hash

Same as `$computed.token_hash`: the SHA-256 hex digest of `value`.

$computed.hash($input.payload)
$computed.verify_hash

True when the SHA-256 hex digest of `value` equals `hash`.

$computed.verify_hash($instance.token_hash, $input.token)
$computed.hash_password

A one-way hash of `password`, in the application's password hashing scheme.

password_hash = $computed.hash_password($input.password)
$computed.bcrypt

Same as `$computed.hash_password`: a one-way hash of `password`.

password_hash = $computed.bcrypt($input.password)
$computed.password_verify

True when `password` matches `stored_hash`.

$computed.password_verify($input.password, $instance.password_hash)
$computed.bcrypt_random

A password hash of a new random secret, so the account's previous password stops working; pair it with `requires_reset = true`.

password_hash = $computed.bcrypt_random
$computed.totp_secret

A new base32 secret for time-based one-time codes (TOTP).

mfa_secret = $computed.totp_secret
$computed.verify_totp

True when `code` is the current one-time code for `secret`.

$computed.verify_totp($instance.mfa_secret, $input.code)
$computed.utf8_decode

`value` as text, read as UTF-8 bytes.

$computed.verify_totp($computed.utf8_decode($instance.mfa_secret), $input.code)
$computed.decode_jwt

The claims of the JSON Web Token `token`, once its signature and expiry are checked.

claims = $computed.decode_jwt($input.token)
$computed.jwt_sign

A signed access token for `subject` in `tenant_id` with `role`; every claim comes from these arguments.

access_token = $computed.jwt_sign($instance.id, $context.tenant_id, "PATIENT_PORTAL_ACCOUNT")
$computed.system_admin_role_id

The id of the SYSTEM_ADMIN role in `tenant_id`; the onboarding flow that creates that role must be declared.

role_id = $computed.system_admin_role_id($context.tenant_id)
$computed.prefix

The first `n` characters of `value`, for a short code or a key prefix.

short_code = $computed.prefix($instance.raw_key, 8)
$computed.s3_sign

A download link to the object `key` in `bucket` that expires after `ttl_s` seconds.

download_url = $computed.s3_sign($instance.bucket, $instance.object_key, 3600)
$computed.s3_object_sha256

The SHA-256 hex digest of the stored bytes of object `key` in `bucket`, to prove its content has not changed.

content_hash = $computed.s3_object_sha256($instance.bucket, $instance.object_key)
$computed.tenant_sequence

The next value of the sequence `name` for `tenant_id`, formatted as declared in `sequences {}`; further arguments fill the sequence's other scope fields in order.

invoice_number = $computed.tenant_sequence("invoice_number", $context.tenant_id)
$computed.nc_sequence

Same as `$computed.tenant_sequence("nc_number", tenant_id)`.

nc_number = $computed.nc_sequence($context.tenant_id)
$computed.protocol_sequence

Same as `$computed.tenant_sequence("protocol_number", tenant_id)`.

protocol_number = $computed.protocol_sequence($context.tenant_id)

Top-Level Blocks

DMX specs are composed of top-level blocks. Each block defines a different concern of the service.

backup_policies

Declare one database row per applicable database, with cadence_cron, positive retention_days, restore_test_cadence_cron and bucket_ref. Write the block inside platform, or beside the service root for a monolith. The database id is explicit: infrastructure.database.name takes precedence over service.database. A platform bucket_ref names its declared bucket id; a service bucket_ref names a deployment variable; its physical bucket is read at runtime and a missing or empty value is refused. A store that keeps no files (object_storage with no document_type) is the backup's destination: bucket_ref is its explicitly declared bucket_name_env_var, and no document_type is required for the backup storage client. A service that keeps files (object_storage with a document_type, or file_storage) never backs up into the bucket of its files: bucket_ref names the backup bucket's own variable, one the file store does not read, and the backup worker reads that variable and its own credentials, <bucket_ref>_ACCESS_KEY and <bucket_ref>_SECRET_KEY, with the store's region and endpoint. Naming the files' variable is an authoring ERROR (BACKUP_SHARES_FILES_BUCKET): one bucket or one credential for both would let the process that serves downloads read every database dump, and give the backup's retention sweep, which lists and deletes objects, a credential that can delete the files. The name is a variable name (letters, digits, underscores); anything else is refused (BACKUP_BUCKET_REF_NOT_A_VARIABLE). A framework's typed backup obligation requires explicit policies; otherwise daily/30-day/weekly defaults retain their derived provenance. Without a bound destination and without a declared backup obligation, execution is NOT_APPLICABLE with its reason recorded. A required backup needs a declared destination. A service destination must keep enable_server_side_encryption=true; disabled or unproduced encryption is refused before upload. PostgreSQL restore compares a versioned per-table baseline captured with the dump; a missing manifest or a mismatch is red. ClickHouse backup transport is currently a compiler gap reported by /validate; the author cannot remedy it by renaming the database. Storage encryption uses the declared binding, and an SSE-KMS reference never becomes a payload AES key. Backup has its own policy-bound queue in both roots. A snapshot reads every row with row security off, so it never connects with the application's credential: a database a policy names declares backup_credential_spec, the env:// secret reference of a separate read-only role (in a platform on the database inside databases { }, in a monolith inside infrastructure { database { } }). It must differ from the database's credential_spec; a missing or equal value is refused, and so is a backup_credential_spec on a database no policy names. Declaration alone does not certify backup execution or restore parity.

cadence_cron

Five-field backup cron.

cadence_cron = "0 2 * * *"
retention_days

Positive retention in days.

retention_days = 30
restore_test_cadence_cron

Five-field restore-test cron.

restore_test_cadence_cron = "0 4 * * 0"
bucket_ref

The backup bucket's deployment variable: the store's own when it keeps no files, the backup's own beside files

bucket_ref = "BACKUP_BUCKET"
backup_credential_spec

On the database a policy names: the env:// secret reference of the read-only backup role, distinct from the database's credential_spec.

database { backup_credential_spec = "env://BACKUP_DB_CREDENTIALS" }

The database identity, the bucket variable and the backup role's secret are declarations, not inferred names.

Service backup without document storage routes
service "standalone" { docs { operator_only } version = "1.0.0" database = "primary_store" }
object_storage { backend = s3 bucket_name_env_var = "BACKUP_BUCKET" }
infrastructure { database { backup_credential_spec = "env://BACKUP_DB_CREDENTIALS" } }
backup_policies {
  database "primary_store" {
    cadence_cron = "0 2 * * *"
    retention_days = 30
    restore_test_cadence_cron = "0 4 * * 0"
    bucket_ref = "BACKUP_BUCKET"
  }
}

service

The root block that defines one service, and the container for every other block. A platform may declare exactly one of these — a monolith — or many; the block itself is written identically either way.

Every service says, once, who reads its API documentation (/docs, /redoc, /openapi.json). docs { operator_only } keeps it behind the operator key (X-Admin-Key). docs { readable_by = [ROLE, ...] } names the roles whose people sign in on the documentation with the service's own login: /docs sends them to /docs/sign-in, which opens a session cookie that reaches only the documentation's paths; the operator key keeps working, and anyone else gets the same 403. Each role must be one the security block declares, once, the list must not be empty, and the service must sign its people in itself (auth_scheme = jwt with a user_entity, without microservice_mode or auth_service). A service without the block, or with it twice, is rejected (DOCS-UNDECLARED, DOCS-DECLARED-TWICE).

Service definition
service "UserService" {
  docs { operator_only }
  version = "1.0.0"
  port = 8000
  api_prefix = "/api/v1"
  database = "postgresql"

  // ... entities, api, flows, etc.
}

identity

Optional nested sub-block inside service { ... } that lets the spec author override canonical-derived service-identity fields. Each attribute is drawn from a closed set and checked while parsing, so a wrong value is an error in the editor, not at run time. When the block is absent the producer derives every field canonically (service_id from the service block name, service_slug + internal_hostname from the canonical lowercase slug, internal_port from the infrastructure block, etc.). When present, every attribute set here is recorded as an override in the build's provenance.

mode

Inside the nested `architecture { }` block: whether the platform is one service, several, or a mix.

microservicesmixedstandalone
mode_source

Whether the architecture mode above was written by the author, worked out from the spec, or left at the compiler's default. Recorded so a later reader can tell a decision from a fallback.

defaultexplicitinferred
mode

Inside the nested `gateway { }` block: whether the gateway forwards requests untouched or checks authentication before it does. Same word as the `architecture { }` attribute above, drawn from a different set — the parser decides which one you meant from the block you wrote it in.

auth_precheckpassthrough

All 12 spec-declarable attrs in a single block. Each sub-block keeps the canonical-strict closed taxonomy enforcement (GATEWAY_MODE = passthrough | auth_precheck; ARCHITECTURE_MODE = standalone | microservices | mixed; ARCHITECTURE_MODE_SOURCE = explicit | inferred | default).

Identity overrides — full surface
service "AuthService" {
  docs { operator_only }
  version    = "1.0.0"
  port       = 8000
  api_prefix = "/api"
  database   = "auth_service"

  identity {
    service_name      = "Auth Service"
    service_version   = "2.4.1"
    service_slug      = "auth-svc"
    internal_hostname = "auth-svc.svc.cluster.local"
    internal_port     = 8081
    description       = "identity overrides"

    gateway {
      enabled          = true
      public_port      = 8443
      public_base_path = "/v2"
      mode             = auth_precheck
    }

    architecture {
      mode        = microservices
      mode_source = explicit
    }
  }
}

Spec authors only pin the attributes they want to override; the rest canonical-derive. Here the platform pins a service version explicitly, leaving every other identity field on its canonical default.

Identity overrides — single attribute
service "AuthService" {
  docs { operator_only }
  version    = "1.0.0"
  port       = 8000
  api_prefix = "/api"
  database   = "auth_service"

  identity {
    service_version = "2.4.1"
  }
}

entity

Defines a data model. Fields have a name, type, and optional annotations. Entities compile to database tables, ORM models, and Pydantic schemas.

retention

How long a row of the entity is kept, written among the entity's fields: a row whose `field` is older than `days` whole days is deleted for good; a row whose field is empty is kept. One `retention {}` per entity, with `days` and `field` each written once (`ENTITY-RETENTION-SHAPE`). `field` names a declared `DateTime` field of the entity (`ENTITY-RETENTION-FIELD`); on a `@soft_delete` entity it may be `deleted_at`. Not on an entity declared `@append_only`, `@append_only_after` or `@append_only_with`, or named in `conditional_append_only_entities {}`: its rows are never deleted (`ENTITY-RETENTION-APPEND-ONLY`). A field may still be named `retention`: the block is the word followed by `{`. Audit rows are not declared here: their window is `audit { retention = "365d" }`, which is applied. Not on the tenancy root or a per-user entity (`ENTITY-RETENTION-TENANCY`); every reference to the entity, and to each entity a cascade reaches, says `on_delete: cascade` or `on_delete: set_null` and none leads into an append-only entity (`ENTITY-RETENTION-BLOCKED-BY-REFERENCE`). At startup and then daily the service deletes the rows past the window, in batches, one tenant at a time under its row policy; each run is counted in the log and the service's metrics, never with row content.

retention { days = 90  field = read_at }
days

Inside `retention { }`: whole days a row is kept after `field`. At least 1.

field

Inside `retention { }`: a `DateTime` field of this entity. On a `@soft_delete` entity it may be `deleted_at`: soft-deleted rows are then removed for good after `days`.

Entity with annotations
entity Order {
  @aggregate_root
  @description("Customer order")
  @audit(level: standard)
  @soft_delete
  @role(domain)

  id          UUID           @pk @default($computed.uuid)
  customer_id UUID           @fk(Customer.id) @not_null
  total       Decimal(12, 2) @not_null
  status      Enum(DRAFT, PENDING, PAID, SHIPPED, CANCELLED) @not_null @default("DRAFT")
  notes       Text
  created_at  DateTime       @not_null @default($computed.now)

  @unique_together(customer_id, created_at)
}

api

Defines REST and GraphQL endpoints for an entity. Route-level RBAC via permissions = ["resource:action"] is enforced end-to-end — the generated service checks the permission, it is not advisory metadata. Each key is resource:action (2+ non-empty colon-separated segments). Request field typed by its column: inside request {} a field's type may be written as the column it carries, <Entity>.<field>. The field then has that column's declared type, with its length, precision and Enum members, so a route that writes a column does not repeat its type: with status Enum(OPEN, CLOSED) declared on entity Ticket, request { status Ticket.status @required } reads as request { status Enum(OPEN, CLOSED) @required }. Only the type is taken: the request field's annotations (@required, @min, …) are its own. The form is read in request {} only, never in an entity, query {} or an inline response {}. A reference to an entity or a field the spec does not declare is refused (REQUEST-FIELD-TYPE-REFERENCE-UNKNOWN). A request field whose hand-written type contradicts the column it is written into stays refused (INV-REQUEST-FIELD-TYPE-CONTRADICTS-COLUMN); typing the field by its column is the way to never write that contradiction.

REST API
api {
  POST "/orders/{id}/cancel" {
    operation_id = "cancel_order"
    permissions  = ["orders:manage"]
    tags         = ["orders"]
    addressing   { id = Order.id }
    @triggers(Order.status -> CANCELLED)
    response @entity(Order)
  }

  GET "/orders/summary" {
    operation_id = "order_summary"
    permissions  = ["orders:read"]
    query {
      from Date
    }
    response @paginated(Order)
  }
}

flow "Order summary" {
  type    = workflow
  trigger = http(method = "GET", path = "/orders/summary")
  entity  = Order
  step 1 "load" {
    action = query
    target = Order
    filter { placed_after = $query.from }
  }
}

Per-endpoint attributes

Beside permissions, an endpoint body takes:

operation_id

The stable name this operation carries into the generated OpenAPI document and the clients built from it. Set it when the generated name would otherwise change with the route.

operation_id = "..."
tags

OpenAPI tags, which is how the generated docs group the operation.

tags = [...]
auth_required

Whether the route demands an authenticated caller at all. It is the coarser question than `permissions`: this decides *whether anyone is asked*, `permissions` decides *who passes*.

auth_required = <bool>
assignable_roles

On a public registration (`auth_required = false`, `POST`), the roles whoever calls it may choose among. The flow writes the account's role from a `@required` Enum of the request with exactly those members; every other value is refused. None of them may hold a privilege: administering accounts, reading the audit trail or the `@sensitive` fields of other people's rows, inviting, opening or approving a `breakglass` window, calling a route no `allow` line grants it, or acting on rows another role may only touch when it owns them.

assignable_roles = [ROLE, ROLE]

Path addressing

A route with placeholders says where to look but never by what. The addressing { } block answers that, binding each HTTP path placeholder to the one entity column it addresses — addressing { <placeholder> = <Entity>.<column> }. Three properties are the point of declaring it rather than inferring it:

  • Spelling never binds. /widgets/{key} with no addressing block produces no binding at all, and neither does a placeholder that happens to be named after a column. A route addressed by a column the compiler guessed is a route that silently changes meaning the day the column is renamed.
  • Declaration order is the order. Bindings carry the order they are written in, which is independent of the order the placeholders appear in the path — so a composite key is read as declared and not as the URL happens to spell it.
  • The target must be a real key. The complete binding has to be exactly a declared primary or business key of that entity; anything else is rejected rather than turned into a lookup that could match more than one row.

Each placeholder bound to the column it addresses. The second route is keyed by a composite: the bindings are read in the order they are declared, not the order the path spells them.

Path addressing
api {
  GET "/widgets/{opaque}" {
    operation_id = "get_widget"
    addressing { opaque = Widget.arbitrary_label }
    response @entity(Widget)
  }

  GET "/widgets/{first}/{second}" {
    operation_id = "get_widget_scoped"
    addressing {
      second = Widget.local_ref
      first  = Widget.tenant_ref
    }
    response @entity(Widget)
  }
}

WebSocket attributes

Set is_websocket = true to declare a WebSocket endpoint. WebSocket endpoints require an authenticated principal with declared tenant membership, explicit subscriber permissions, typed subscription parameters and event payloads, explicit message size and frequency limits, declared room bindings, transactional event publication and configured Redis fanout. Supported declarations provide a real WebSocket route, durable event delivery across replicas and real-client tests. A missing declaration or an unsupported policy is refused with its named correction or capability limit; a declaration lost while compiling is reported as a problem on our side. PDF generation remains unavailable.

When the policy of the entity whose events the endpoint streams grants read (or the action a command binds the endpoint to) with when ownership(field), the field is a subscription parameter: add it to subscription_params and bind it in the room_bindings of every message of that entity, so each room holds the rows of one owner. A subscriber whose role reads only its own rows is admitted to its own room and refused any other, at the handshake and again before every message, including replayed ones; a role the policy lets read every row is admitted to any room of its tenant. An ownership rule on another action (update, delete) does not concern the endpoint. When the owner field is not a room of the endpoint, or the room is read through a related entity that carries its own ownership rule, the endpoint is refused as a limit of DevMatrix: keep the policy as declared, and serve the data over HTTP or postpone the WebSocket endpoint.

A subscriber must hold a role that may read every entity whose rows the endpoint streams: the entity whose events it pushes, and an entity a message reads a field of through a foreign key (a row the subscription only addresses is looked up, never sent). For each such entity, the roles that may read it are the roles its policy grants read, by role or with when ownership(field), and the roles it grants the action a command bound to the endpoint names on it. The handshake requires one role of each entity's set, and checks it again after every client message and before every message it sends, so a role taken away stops the next message. A policy that names no role restricts no role. Two declarations are refused at validation as errors of the spec (WS-DECLARATION-001):

  • a policy that names roles and grants none of them read on a streamed entity: WebSocket endpoint '<path>', policy '<policy>', read: the endpoint streams rows of '<Entity>', and policy '<policy>' grants `read` on them to none of the roles it names; grant `read` to the roles that subscribe, or stream rows they may read. (WS-DECLARATION-001) (with a command bound to the endpoint, the message names each action it checks, read and the command's, in alphabetical order joined by or);
  • when a principal holds one role (no role junction), policies whose readers share no role: WebSocket endpoint '<path>', policies, read: no role may read every row the endpoint streams (read is granted on '<Entity>' to <roles>; '<Entity>' to <roles>); grant `read` to one role on every entity the endpoint streams, or stream them from separate endpoints. (WS-DECLARATION-001)

The three message limits and the client message type list are mandatory and have no defaults:

subscription_params

The identifiers a client may subscribe by.

subscription_params = [a, b]
heartbeat_interval

Required positive interval in seconds that bounds an idle connection and heartbeat delivery. No default.

heartbeat_interval = <int>
max_connections

Required positive ceiling on concurrent sockets in each resolved room on each serving replica. No default.

max_connections = <int>
max_message_bytes

Required UTF-8 application-message byte limit, checked before decoding. No default.

max_message_bytes = <positive int>
max_messages_per_window

Required ceiling on incoming messages per connection in the declared time window. No default.

max_messages_per_window = <positive int>
rate_window_seconds

Required positive duration of the incoming-message rate window, in seconds. No default.

rate_window_seconds = <positive int>
max_connections_per_principal

Required ceiling on the sockets one signed-in principal may hold open on the endpoint at once, across every replica. Past it the socket is refused with 429; when the count cannot be read, with 503. No default.

max_connections_per_principal = <positive int>
replay_window_seconds

Optional seconds a pushed message stays replayable. A client reconnecting with resume_after=<delivery_id> gets every later message of its room first, in order, then the live ones (order is per room, not across rooms). Delivery is at least once: drop a delivery_id already received. A message no longer kept is refused with 410, and a resume whose window passes mid-replay is closed with 4410 (resync over HTTP in both cases). Omitted, the endpoint offers no resume and resume_after is refused with 400.

replay_window_seconds = <positive int>
client_message_types

Required nonempty list of admitted client heartbeat types. A heartbeat contains only its type member; unknown types and extra members are refused. No default.

client_message_types = [ping, pong]
auth_type

The token domain that verifies the handshake. Optional: omitted, the domain whose route_prefixes cover the path verifies it. On an HTTP route it is refused (ENDPOINT-STRING-ATTRIBUTE-UNREAD-001).

auth_type = "<token domain>"

flow

Multi-step business process. Each step has an action, target entity, and field mappings. Flows compile to service-layer functions with transaction management. A flow must have at least one step. A stepless flow with intentional_stub = "reason" still parses, but it declares a gap, not an endpoint: validation flags it and the compile blocks it.

type

What kind of flow this is. Decides how the compiler wires it: an HTTP route, a queued job, an event consumer or an internal call.

event_handlerpolicystate_transitionworkflow
action

What a STEP does. The verb decides which other attributes the step accepts — a `query` step takes `target` and `filter`, an `export` step takes `output_format`.

analyticsapi_callbatchcalculatecreatedeleteexportexternal_callextractforeachinfraissue_secretquerysearchstate_changeupdateupsertvalidate
Registration flow
service "Accounts" {
  docs { operator_only }
  version  = "1.0.0"
  database = "accounts_db"
}

// Public sign-up by link: the caller sends its tenant. Behind a login, read $context.tenant_id under a principal instead.
security {
  auth_scheme = none
}

entity User {
  id         UUID        @pk @default($computed.uuid)
  tenant_id  UUID        @not_null
  email      String(255) @not_null @format(email)
  name       String(200) @not_null @freetext
  created_at DateTime    @not_null @default($computed.now)

  @unique_together(tenant_id, email)
}

api {
  POST "/users" {
    operation_id  = "register_user"
    auth_required = false
    request {
      tenant_id UUID @required
      email String(255) @required @format(email)
      name  String(200) @required @freetext
    }
    response @entity(User) @status(201)
  }
}

flow "Register User" {
  type    = workflow
  trigger = http(method="POST", path="/users")
  entity  = User

  step 1 "Create user" {
    action = create
    target = User
    mapping {
      tenant_id  = $input.tenant_id
      email      = $input.email
      name       = $input.name
      created_at = $computed.now
    }
  }
}

Step attributes beyond action / target / mapping

A step body is one production, so the grammar accepts all of them on any step; which ones MEAN anything is decided by action, and the validator is what enforces that pairing:

query_field / query_value

The single-field lookup a `query` step runs. `query_value` takes a literal or a `$`-token, so a step can look up by something the request carried.

query_field = "..."
query_value = <value>
result_field

Which field of the step's result is kept. Distinct from `result_capture`, which names the whole result for later steps to refer to.

result_field = "..."
condition

On a `create`, `update` or `delete` step, the step runs only when the condition holds; when it does not, the step is skipped and the flow goes on with its next step. On a `validate` step it is the check itself. No loop is needed for a write that happens zero or one time: write the step with its `condition`, not a `foreach` whose `source_query` pins a key (the primary key or a `@unique` field) by equality (the Workshop validator says so: `FLOW-FOREACH-OVER-ONE-VALUE-IS-A-CONDITION`). A later step cannot read what a skipped step would have produced (`FLOW-STEP-CONDITION-FALSE-PATH-UNBOUND`); a later step that writes the flow's own row (`$instance`) still writes that row, never the one the skipped step would have created.

condition = $input.archive == true
tx_policy

Every step runs in the flow's one transaction, so only `join` compiles today; `new` and `none` parse but are refused (STEP-TX-POLICY-UNLOWERED-001).

joindefault
call

The operation an `api_call` step calls on a declared integration whose client is the generic API client (`api_client { }`). The base URL, auth, timeout and retries are the integration's. `mode = async` writes the call to the service's outbox in the flow's own transaction and sends it after the commit; `mode = sync` calls after the flow's reads and checks and before its first write or lock, and writes the typed answer into `result_field`.

call {
  integration = "..." method = POST path = "/v1/..." mode = async
}
integration

Inside `call { }`: the declared integration the step calls.

method

Inside `call { }`: the HTTP method. `GET` and `DELETE` send no `body`.

DELETEGETPATCHPOSTPUT
path

Inside `call { }`: the path, relative to the integration's base URL. Each `{name}` segment is bound once in `path_params`.

path_params

Inside `call { }`: one `$` binding per `{name}` segment of the path. A name may be spelled like a keyword (`secret`, `name`, `type`, `description`, `to`, …) in any position; the operator words `in`, `contains` and `for` are not names.

path_params { id = $instance.id }
body

Inside `call { }`: the JSON object sent, in declared order. Keys are quoted; a value is a literal, a `$` binding, an object or an array. An async body reads the row the flow wrote (`$instance.<field>`) or the row one earlier `query` step loaded with `query_cardinality = "single"` (`$result.<name>.<field>`). A `@sensitive` text field it reads is sealed beside the job and erased after the send; one of another type, or in the path, is refused (INV-API-CALL-NOT-SENDABLE).

body { "to" = [ { "email" = $instance.email } ] }
mode

Inside `call { }`: `async` (outbox, after the commit, retried, delivered at least once) or `sync` (after the flow's reads and checks, before its first write or lock, answered inline).

asyncsync
idempotency_header

Inside `call { }`: the header the call's idempotency key is sent in, never one the client sets itself (`Authorization`, `Host`, `Content-Type`, `Content-Length`…) or the integration's effective `api_client.auth_header`. Header names are compared without regard to letter case; declare a distinct idempotency header so its key cannot replace the authentication credential. Every API-key or Bearer client's credential header must be an HTTP token name, even with no calling step; empty names, spaces, quotes, backslashes and line breaks are refused once per integration. A malformed credential header does not hide the call's idempotency problems. The key is always generated and stored, declared or not. An async `POST` or `PATCH` without it gets a warning: a retried send may reach the provider twice.

idempotency_header = "Idempotency-Key"
response

Inside a `sync` `call { }`: the typed fields of the answer, written into `result_field`.

response { state String(32) }
on_failure

Inside a `sync` `call { }`: the declared error of `errors { }` the flow answers when the call fails; the flow then writes nothing.

on_failure = "MAIL_DOWN"
secret

The single-use secret an `issue_secret` step issues. `name` is read as `$secret.<name>` only in a later `call { body { } }` of the same flow; `generate` is a CSPRNG helper; `hash_into` is a nullable `@sensitive` column that receives its sha256. The raw value is never in a response, a log or a metric.

secret {
  name = "invite" generate = $computed.random_token hash_into = "token_hash"
}
hash_into

Inside `secret { }`: the column of the flow's entity that receives the secret's sha256.

target_service

For an `external_call` step, which service is called. Today the step is refused at validation: the language cannot yet bind it to an endpoint the target declares.

target_service = "..."
output_format

For an `export` step: the serialisation written out. Required by an `export` step: `csv`, `json` or `pdf`. The grammar accepts it anywhere; the export pass is what requires it where it belongs.

csvjsonpdf
source_collection

The array a `foreach` step iterates, when the source is a `$`-token rather than a query. Its alternative is a `source_query { }` block — `target = <Entity>`, an optional `order_by = <field>`, and an optional `filter { }` — and the two are discriminated structurally, not by a mode flag. A `source_query` without `order_by` still iterates in a fixed order: the target's primary key orders it, so the same input produces the same output. Inside the `do { }` body each element binds to `$item`, which is scoped to that body — a `$item` outside one is a validate error, not a runtime surprise. When the collection holds keys, an `update` or `delete` body loads the row each key names with `filter { <declared key> = $item }` (the same `filter` as `source_query`); a filter on any other column, or none, is `ROW-LOAD-UNADDRESSED-001`.

source_collection = $token

mapping { } in a step

  • null in mapping { } — closed_at = null writes SQL NULL into the column. Accepted in mapping { } only (a filter { } compares, it does not write). The validator requires a row-writing step (create, update, upsert, batch, or a foreach do { } that writes), a column that is not the entity's state_machine field, and a nullable column — not @pk, @not_null or @required. A null foreign key clears the link.
  • mapping { } on a calculate step — shapes values for the route's inline response { }. When the flow answers the body as one object, each declared field has exactly one producer: a column of the row the flow writes (its last create / update / upsert of the flow's entity) or a key of a calculate step's mapping { } (access_code = $result.access_code for a value an earlier step computed). An earlier step's result_field of the same name does not fill a response field. Refused at validation: a declared field nothing produces (RESPONSE-FIELD-WITHOUT-SOURCE-001), a field that is both a row column and a mapping key (RESPONSE-FIELD-AMBIGUOUS-SOURCE-001), a field the entity declares @sensitive (RESPONSE-FIELD-SENSITIVE-001), and a mapping key the body does not declare (RESPONSE-MAPPING-NOT-DECLARED-001).

state_machine

Defines valid state transitions and role restrictions. Compiles to a state machine implementation with validation. initial names the state a new row starts in. terminal = [...] lists the states nothing may transition out of. A state no transition leaves must be one of them (a wildcard target * -> X is terminal by itself): a dead end that is not declared terminal is refused at validation with SM-STATE-WITHOUT-TRANSITION, and the compile fails the build on it. sensitive = [...] lists the states whose INBOUND transitions require an elevated role — declare them and the compiler injects the guard, instead of inferring sensitivity from the state's name.

⚠️ Guards target a declared state. @guard(STATE) { condition = ...; error = "..." } keeps its condition and error message and is checked on transitions entering that state. The state must exist, the condition must name declared fields, and the error message is required. Invalid guards are refused at validation and compilation with the guard's location and remedy.

Order state machine
state_machine Order.status {
  initial   = DRAFT
  terminal  = [DELIVERED, CANCELLED]
  sensitive = [PAID, SHIPPED]

  DRAFT   -> PENDING    @roles(MEMBER, ADMIN)
  PENDING -> PAID
  PAID    -> SHIPPED    @roles(ADMIN)
  SHIPPED -> DELIVERED
  PENDING -> CANCELLED  @roles(MEMBER, ADMIN)
  DRAFT   -> CANCELLED

  @guard(SHIPPED) {
    condition = $instance.paid_at != null
    error = "An order ships only after its payment is recorded"
  }
}

validations

Validation rules applied to entity fields. Compile to both database constraints and API-level validation.

A rule is keyed either by entity (User { }) or by field (User.email { }), and type names WHICH KIND of rule it is — format, range, presence, uniqueness, relationship, stock_constraint, status_transition, workflow_constraint or custom. It is a bare token, not a quoted string, and it is not the same axis as the check itself: type = format says what kind of rule this is, format = "..." carries the pattern.

severity is a closed taxonomy of exactly two members, error and warning. There is no third level. An error rule refuses the write; a warning rule logs the breach (the rule and, for a field rule, the field and its value, masked when the field is @sensitive) and lets the write through. severity = warning applies to format, range, presence and custom rules; uniqueness, relationship and transition rules are integrity constraints and are always errors. enforcement is a separate axis again: it says WHERE the rule is applied (validator, computed_field, immutable, state_machine, business_logic, description), not how loudly it complains.

A range bound is a number (range = ">= 0 and <= 100"); on a date field, the current time (range = "> $computed.now"); or, on a numeric field, another numeric field of the same record (range = "<= $instance.awarded"), compared by value and checked on the saved record after every write of either field. Its enforcement is business_logic, validator or left out, which all mean the same check; computed_field, immutable, state_machine and description do not compare two fields, so such a rule is refused by name when you validate. When the ruled field is empty the rule does not apply; when it has a value and the other field is empty, the write is refused. A bound through another record ($instance.lease.monthly_rent) and any other bound are refused by name when you validate; to compare a field with a value sent in the request or with another record, use a flow validate step.

A custom rule on a field (type = custom with a condition) is checked on the saved record after each write of the entity, when its enforcement is business_logic or left out (writing enforcement = description counts the same as leaving it out). computed_field, validator, immutable and state_machine check nothing on the saved record, so such a rule is refused by name when you validate.

A status_transition rule on a field (type = status_transition with an error, no condition) is how that field's state machine answers: every route that moves the field refuses an illegal move with that error and 409 Conflict. The rule needs its error: nothing writes that answer for you, and without the rule the state machine refuses an illegal move with its own sentence. The field must have a state_machine block and the rule's enforcement, if declared, must be state_machine; a rule on a field with no state machine, with another enforcement, or with no error (or a blank one) is refused by name when you validate.

type

Which check this validation rule performs.

customformatpresencerangerelationshipstatus_transitionstock_constraintuniquenessworkflow_constraint
severity

Whether a failing rule blocks the write (`error`) or is logged and allowed through (`warning`). Only format, range, presence and custom rules can be warnings.

errordefaultwarning
enforcement

When and how strictly the rule runs. Distinct from `severity`: severity says what a failure costs, enforcement says when the check happens at all.

business_logiccomputed_fielddescriptionimmutablestate_machinevalidator
Validation rules
validations {
  User.email {
    type   = format
    format = "^[^@]+@[^@]+$"
    error  = "Invalid email address"
  }

  User.username {
    type        = uniqueness
    enforcement = validator
    severity    = error
    error       = "Username already taken"
  }

  User.bio {
    type     = format
    format   = "^.{0,500}$"
    severity = warning
    error    = "Bio is longer than we display"
  }

  User.age {
    type  = range
    range = "0..150"
    error = "Age must be between 0 and 150"
  }
}

security

Authentication, authorization, rate limiting, and password policies.

method

Which second factor the generated service enrols and verifies. Only `totp` generates a working enrolment flow today; the others are declarable and reserved.

emailhardware_keysmstotp
algorithm

The HMAC algorithm the one-time code is derived with. `SHA1` is what every mainstream authenticator app expects — the stronger two are accepted for callers that can be configured.

SHA1defaultSHA256SHA512
auth_scheme

How callers authenticate against the generated service. Picks the middleware, the token shape and what the OpenAPI security scheme advertises. Only `jwt` and `none` compile today; `basic`, `api_key` and `oauth2` parse but are refused.

jwtdefaultnone
password_hashing

The algorithm used to hash stored credentials. Chosen once for the platform; changing it later invalidates existing hashes.

argon2bcryptpbkdf2
role_field

The Enum column of the principal that holds the caller's role, its values among the declared roles: the login mints the role from it and the role guards and the seed read it. No column is read by its name: a module with a local principal and declared roles must declare it, and a role_field that does not name such a column is refused.

role_field = "role"
Security configuration
security {
  auth_scheme = jwt
  jwt_algorithm = "HS256"
  token_expiry_minutes = 60
  refresh_token_enabled = true
  password_hashing = bcrypt

  rate_limit {
    login_attempts = 5
    requests_per_minute = 100
    lockout_duration = "15m"
  }

  roles = [ADMIN, MEMBER, GUEST]
}

The `mfa { }` sub-block declares the platform's TOTP capability. `method`: DevMatrix compiles only `totp`; `sms` / `email` / `hardware_key` are not compiled today and /validate refuses them (MFA-METHOD-NOT-COMPILED-001); `algorithm` is SHA1 / SHA256 / SHA512. `config_entity` / `enabled_field` / `secret_field` name the entity + fields that persist per-user MFA state (structural, never name-matched). The `@otp_code` field annotation marks the verify-code field; the validator joins its `String(N)` length against `code_digits = N`. `challenge_lifetime_minutes` is how long the challenge the login hands back stays answerable: once the factor is enrolled, the login writes the session row whose key it returns as the challenge handle with expiry = now + N minutes and no refresh row, and the public route that completes the second factor locks that row, requires it live and unexpired, consumes it and only then mints. It has no default: /validate refuses a module whose public route completes a second factor without it (MFA-CHALLENGE-LIFETIME-UNDECLARED-001), and it must be shorter than the session store's `lifetime_days`. This is what gives the generated service working TOTP enrolment and verification.

MFA / TOTP capability
security {
  auth_scheme = jwt

  mfa {
    enabled          = true
    method           = totp
    code_digits      = 6
    interval_seconds = 30
    algorithm        = SHA1
    valid_window     = 1
    config_entity    = User
    enabled_field    = "mfa_enabled"
    secret_field     = "mfa_secret"
    challenge_lifetime_minutes = 5
  }
}

entity MfaVerifyInput {
  id   UUID @pk
  code String(6) @otp_code
}

When the password hash lives on a separate credential entity carrying a credential-kind enum, `credential_type_field` names that enum field and `password_credential_kind` names the member that denotes a password credential. Both keys are optional; omitting them is byte-equal.

Credential-split discriminator (optional)
security {
  auth_scheme = jwt
  user_entity = "User"
  active_field = "is_active"

  credential_type_field = "credential_type"
  password_credential_kind = "password"
}

`role_field` names the Enum column of `user_entity` that holds the caller's role; its values are among `roles`. No column is read by its name: a module with a local principal and declared roles must declare it. A role on a junction and `microservice_mode = true` declare no column. On a route with `auth_required = false` the role and the tenant of an account are never the caller's to choose: the create step writes the role as a literal and the tenant as the one the same flow created, also when the route reaches the write through an event or a job, or the spec is refused (PUBLIC-ROUTE-ROLE-NOT-LITERAL, PUBLIC-ROUTE-PRINCIPAL-TENANT-NOT-CREATED-HERE); giving a role belongs on a route with `permissions`.

Role column
security {
  auth_scheme = jwt
  user_entity = "Account"
  role_field  = "tier"
  roles = [OWNER, MEMBER]
}

`user_lookup_field` names the attribute of `user_entity` the login authenticates against; the login request must send a field with the same name, and the attribute must be an identity of the principal (`@unique`, alone or inside a composite unique). Without it the carrier is derived: an `@format(email)` attribute first, otherwise a non-null `@unique` String. When two or more attributes qualify equally the compiler does not pick one by name or order: it refuses with INV-DSL-AUTH-LOOKUP-003 and asks for this key. INV-DSL-AUTH-LOOKUP-002 names a declared carrier the principal does not have.

Login carrier (optional)
entity Account {
  id               UUID        @pk
  email            String(320) @not_null @unique @format(email)
  pending_email    String(320) @nullable @format(email)
  password_hash    String(255) @sensitive @field_purpose(password)
  is_active        Boolean     @not_null @default(true)
}

security {
  auth_scheme       = jwt
  user_entity       = "Account"
  user_lookup_field = "email"
  active_field      = "is_active"
}

Attributes beyond the example

Beyond the attributes in the Security configuration example above:

refresh_token_rotation

Issue a NEW refresh token on every use and invalidate the old one. It is what turns a stolen refresh token into a detectable event instead of a standing key; `refresh_token_enabled` alone only decides that refresh tokens exist.

refresh_token_rotation = <bool>
token_revocation

Check a revocation list when validating, so a session can be ended before its expiry rather than at it.

token_revocation = <bool>
microservice_mode / auth_service

This service does not authenticate on its own; the named module does, and this one trusts and verifies what it issues. Declaring the mode without the module leaves the service expecting an authority nobody appointed.

microservice_mode = <bool>
auth_service = "<Module>"
max_request_body

The largest request body accepted, as a size string. It belongs here rather than in a proxy config because the generated service enforces it: a limit that lives only in front of the service disappears the moment anything reaches the service another way.

rate_limit { }

security also carries four sub-blocks, and their attributes are not interchangeable with the platform-scope surfaces that share their names.

rate_limit { } — service scope, and it throttles LOGIN, not traffic. This is a DIFFERENT block from the platform-scope rate_limits { } (which takes per_tenant / per_ip / per_route policies) and from an adapter's rate_limit_policy { }. Three surfaces, three spellings, three scopes — and an attribute from one does not parse in another.

Three attributes, all of them about credential guessing:

login_attempts

Failed attempts before the account locks.

login_attempts = <int>
lockout_duration

How long the lock holds. Without it a threshold is only a speed bump: the attacker waits out nothing and continues.

lockout_duration = "..."
requests_per_minute

The per-caller ceiling on this service.

requests_per_minute = <int>
login_attempts_setting

The `tenant_config` setting each tenant sets its own threshold with. The setting is `data_type = "integer"` with a `platform_minimum` of 1 or more and a `platform_maximum` (`LOGIN-ATTEMPTS-SETTING-SHAPE`: a tenant must not switch the lock off), and `login_attempts` stays required beside it: the literal applies before the tenant is known and when the tenant has set none. A setting the spec does not declare is refused (`TENANT-SETTING-BINDING-UNKNOWN`). **Refused today:** the login reads only the literal yet, so a spec that declares `login_attempts_setting` is refused at validation (`TENANT_LOGIN_ATTEMPTS_PRODUCER_MISSING`, a limit of the compiler, listed in «What the compiler refuses today»).

login_attempts_setting = "<tenant setting>"

mfa { policy }

policy, policy_setting and required_roles say who must hold a second factor, beside the TOTP attributes above. Refused today. They parse and are validated, and nothing refuses a session by policy yet: a spec that declares any of them is refused at validation (MFA_POLICY_PRODUCER_MISSING, a limit of the compiler, listed in «What the compiler refuses today»). A principal that enrolled a second factor is asked for it either way.

policy

Who must hold a second factor: `optional` requires it of no one. `encouraged` requires it of no one either and states that the application recommends one. `required_for_roles` requires it of the principals holding a role in `required_roles`. `required_for_all` requires it of every principal. The application's own value, and the one that stands when a tenant has set none.

encouragedoptionalrequired_for_allrequired_for_roles
policy = required_for_roles
policy_setting

The `tenant_config` setting a tenant chooses its policy with: `data_type = "string"` and `enum_values` inside the four policies (`MFA-POLICY-SETTING-SHAPE`); a setting the spec does not declare is refused (`TENANT-SETTING-BINDING-UNKNOWN`). Needs `policy` beside it.

policy_setting = "<tenant setting>"
required_roles

The declared roles `required_for_roles` binds. Required when `policy`, or a value of the `policy_setting`, is `required_for_roles`; refused when neither can be (`MFA-POLICY-INCOMPLETE`).

required_roles = [ROLE, ...]

sessions { }

sessions { } — whether a user can see and end their own sessions. enabled turns session tracking on; list_endpoint = true and revoke_endpoint = true each generate one route. They are separate on purpose: listing sessions without being able to revoke them shows a user a compromise they cannot act on.

Inside sessions { }, session_store { } and refresh_store { } declare which entity persists each auth fact — never inferred from an entity or column name. Both take entity, owner_field (a @fk to the user entity), expiry_field and revoked_at_field, plus ONE of two forms: the state form (active_state, revoked_state, and on the refresh store consumed_state, all states of the entity's own state machine) or the marker form (revoked_field, a nullable DateTime or a Boolean defaulting to false, for an entity without a machine). The session store adds lifetime_days, ip_field with its ip_source, and user_agent_field; the refresh store adds secret_field (the hashed token), session_field (the @fk to the session row, required when a session store is declared) and consumed_at_field. The login writes each row exactly once; a create the login flow declares on a store entity is merged into that write and may only set columns the store block does not bind (SESSION-CONTRACT rule 7). In the state form, a refresh token presented again after it was consumed revokes every refresh row of that session and the session itself, and answers 401; the marker form cannot tell a consumed token from a revoked one, so reuse answers 401 without revoking the chain. Refresh also requires the session row to be live and unexpired. Without a refresh_store the compiler declares its own store. A declaration the model cannot honour is refused as SESSION-CONTRACT rule N, with the repair. While the spec is written, a create step on a store is not asked to source the columns the store block binds, and a step that maps one is reported on that step as SESSION-CONTRACT-STORE-WRITE-001.

The session store in the state form (its entity declares a state machine) and the refresh store in the marker form. Every key names a declared column or state; the compiler checks each against the model before it writes a line.

sessions { } — declared auth stores
security {
      auth_scheme = jwt
      refresh_token_enabled = true
      refresh_token_rotation = true
      user_entity = "Operator"
    
      sessions {
        enabled = true
        list_endpoint = true
        revoke_endpoint = true
        session_store {
          entity = Device
          owner_field = "operator_id"
          expiry_field = "expires_at"
          lifetime_days = 7
          ip_field = "origin"
          ip_source = request_client_address
          user_agent_field = "agent"
          active_state = live
          revoked_state = retired
          revoked_at_field = "retired_at"
        }
        refresh_store {
          entity = Grant
          owner_field = "operator_id"
          session_field = "device_id"
          secret_field = "digest"
          expiry_field = "expires_at"
          active_state = issued
          consumed_state = spent
          revoked_state = withdrawn
          consumed_at_field = "spent_at"
        }
      }
    }

token_domains { }

token_domains { <name> {... } } — more than one JWT audience inside one service, each with its own key and its own slice of the URL space. Per domain: issuer, audience, algorithm, token_expiry_minutes, claims = { ... }, plus:

secret_env_var

The environment variable holding the signing secret. A reference, never the secret: the value stays out of the spec and out of git.

secret_env_var = "..."
route_prefixes

The paths this domain governs. It is what makes the domains actually separate; two domains whose prefixes overlap are two keys accepted on the same route, which is one key with extra steps.

route_prefixes = [...]
issued_by

Who gives out this domain's tokens. Required: a domain that states neither is refused (TOKEN_DOMAIN_ISSUER_UNDECLARED), because no caller could obtain a token its routes accept. `login`: the application's sign-in gives them to the roles in `for_roles`, signed with the secret in `secret_env_var`, so its `algorithm` is HS256, HS384 or HS512 (TOKEN_DOMAIN_LOGIN_ASYMMETRIC_ALGORITHM). That secret is its own, never `JWT_SECRET_KEY`, `JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY` or `JWT_PREVIOUS_PUBLIC_KEY`, the keys of the application's own token: one key signs one kind of token (TOKEN_DOMAIN_LOGIN_SHARES_APPLICATION_SECRET). `external`: a service outside the application gives them, and its `secret_env_var` is never the secret a `login` domain signs with, nor the key the application's own sign-in signs its tokens with (`JWT_SECRET_KEY`, `JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY` or `JWT_PREVIOUS_PUBLIC_KEY`) (TOKEN_DOMAIN_EXTERNAL_SHARES_SIGN_IN_SECRET); a token the sign-in issued is refused on its routes.

externallogin
issued_by = login
for_roles

With `issued_by = login`: the roles whose sign-in receives this domain's token. Not empty, each role one `security { roles }` declares (TOKEN_DOMAIN_ROLE_UNDECLARED), and a role sits in at most one domain. A role no domain lists signs in with the application's own token. A caller given the tokens of several domains names one of its `token_domains` when it signs in; naming one it is not given is refused with 403.

for_roles = [ROLE, ...]
jwks_uri

With `issued_by = external`: the key set the domain's verifier reads. Required when the `algorithm` is not HS256, HS384 or HS512 (TOKEN_DOMAIN_EXTERNAL_WITHOUT_KEY_SOURCE). It must be an `https://` address with a host, written without spaces around it (TOKEN_DOMAIN_JWKS_NOT_HTTPS). Not written when the `algorithm` is HS256, HS384 or HS512 (TOKEN_DOMAIN_JWKS_WITH_SHARED_SECRET). Each attribute of a domain is written once (TOKEN_DOMAIN_ATTRIBUTE_REPEATED).

jwks_uri = "https://..."

bootstrap_principal { }

bootstrap_principal { } — the first privileged principal. Sign-up never gives a caller a role and every route that could grant one requires a role, so without this block a deployed service cannot reach its own privileged routes. After the migrations, a script writes the principal, its role and its credential in one transaction, once: when a principal already holds the role it writes nothing, so a redeploy never resets a password. No secret is written in the spec.

role

One of the declared `roles`: the role the first principal holds.

role = <ROLE>
login_ref

The variable the principal's login is read from at deploy: the value of the login column, a String column.

login_ref = "env://VAR"
password_ref

The variable the password is read from at deploy. It must meet the service's password policy; the placeholder `.env.example` ships is refused.

password_ref = "env://VAR"
set

Values for the principal's other required columns that have no default: text, numbers, booleans, dates and UUIDs.

set { <field> = <literal> }

account_email { } — identity by email

account_email { } — email verification, password reset and invitation, served by the module that owns the principal. It sits inside security { }, and every value the flows need is declared: the compiler chooses none of them. Each flow (verification, password_reset, invitation) is optional, and at least one is declared. Only the SHA-256 of a secret is stored, bound to the account and the flow's purpose. A secret can be used once, and issuing a new one for the same account and purpose ends the live ones. A request route answers the same for an address that has an account and one that does not. A password reset ends every session of the account. Every step writes an audit row, and the secret never appears in a log or a path. The module needs an enabled audit trail, a login column with @format(email) and, for password_reset, a sessions { session_store { } }. A declaration missing an attribute is refused on its line (ACCOUNT_EMAIL_INCOMPLETE), and so is a key written in another flow (ACCOUNT_EMAIL_KEY_MISPLACED). One that does not fit the domain model is refused before the build produces anything (ACCOUNT_EMAIL_REFUSED). The shapes no route serves yet are named by ACCOUNT_EMAIL_PRODUCER_MISSING.

provider

The module's SMTP provider, one of `notifications { providers { } }`.

provider = "<name>"
default_locale

The mail a recipient gets when their locale column holds no declared locale. Every flow has a mail for it.

default_locale = "<locale>"
locale_field

The principal's `String` column holding each recipient's locale. Required when a flow has more than one mail.

locale_field = "<column>"
token_store

The entity holding one row per issued secret and the column of each fact: `owner_field` (an `@fk` to the principal), `purpose_field` (an Enum holding each flow's purpose), `hash_field` (an `@sensitive` `String(64)`: the SHA-256 of the secret, never the secret), `address_field` (the address the mail went to), `expiry_field` (a required `DateTime`) and `consumed_at_field` (a nullable `DateTime`).

token_store { entity = <Entity> owner_field = "..." purpose_field = "..." hash_field = "..." address_field = "..." expiry_field = "..." consumed_at_field = "..." }
limits

Requests allowed per address (`per_address`) and per client IP (`per_ip`) in `window_seconds`, on every request and confirm route.

limits { per_address = <INT> per_ip = <INT> window_seconds = <INT> }
retry_count

How many times a mail the provider did not accept is retried after the first attempt, and the first wait in seconds (`retry_backoff`). Both are required, with the bounds of a notification's retry policy: there is no default.

retry_count = <INT>  retry_backoff = <FLOAT>
purpose

In each flow: the member of the store's purpose Enum this flow's secrets are bound to; each flow has its own.

purpose = <MEMBER>
lifetime_minutes

In each flow: how long a secret is accepted. At most 60 for `password_reset`, 1440 for `verification`, 10080 for `invitation`.

lifetime_minutes = <INT>
link_ref

In each flow: the variable holding the base URL of the link. The secret goes in the link's fragment (`#token=`), never in a path or query.

link_ref = "env://VAR"
verified_field

`verification` only: the principal's nullable `DateTime` the confirmation sets.

verified_field = "<column>"
invited_by

`invitation` only: the roles that may invite (`invited_by`), and the roles an invitation may give (`assignable_roles`).

invited_by = [ROLE, ...]  assignable_roles = [ROLE, ...]
set

`invitation` only: values for the invited principal's other required columns.

set { <field> = <literal> }
mail

In each flow, one per locale: `subject`, `text` (the plain part) and `html` (the HTML part). A mail names `{{link}}` in its text, and in its HTML as `href="{{link}}"`. Its only other names are `{{lifetime_minutes}}` and columns of the principal that are not `@sensitive`.

mail "<locale>" { subject = "..." text = "..." html = "..." }

policy { }

policy "<name>" { } is the fourth, and its body uses a different syntax from everything above — entity = <Ident> plus allow [<perms>] for [<roles>], positional and without =. It is the one place in security where an attribute-shaped line is wrong.

`policy "<name>" { }` is how an author declares who may do what: `allow [<actions>] for [<roles>]`, optionally scoped to an entity with `entity = <Entity>` and conditioned with `when <predicate>(<field>)`, where the predicate is one of `ownership`, `team` or `tenant_isolation` and the field is the entity column it compares (the row's owner, team or tenant); any other predicate stops the build. `when tenant_isolation(<field>), across_owners` is the same tenant filter, for a role whose duty is reading every row of its tenant: a referenced entity that limits the role to the rows it owns does not bound that grant. It is refused on a grant with no tenant condition, on an action other than read or list, and for a role no referenced entity limits to its own rows. It is written inside `security { }` — the parser accepts it and carries it through to the generated service. Endpoint enforcement remains independently governed by endpoint bindings and its security gates. The syntax below is derived from the grammar, not copied from any spec.

policy { } — declared access control
security {
      auth_scheme = jwt
      roles = [ADMIN, MANAGER, MEMBER]
    
      policy "shipment_write" {
        entity = Shipment
        allow [create, update] for [ADMIN, MANAGER]
        allow [read] for [MEMBER] when ownership(owner_id)
      }
    }

errors

Custom error definitions with HTTP status codes, categories, and messages.

Error definitions
errors {
  USER_NOT_FOUND {
    status   = 404
    category = not_found
    message  = "User not found"
    entity   = User
    field    = id
  }
  INVALID_CREDENTIALS {
    status   = 401
    category = auth
    message  = "Invalid email or password"
  }
}

jobs

Scheduled jobs — declared inside platform { jobs {... } }, or at the root of a single-service application's one spec with the same rule (a service that belongs to a microservices platform declares none at its root). A job is a quoted name and its schedule (five cron fields, UTC), the target_task (a local trigger = job("<service>.<task>") flow), and optional queue, priority, timeout_seconds, description and retry { max_attempts backoff delay }. tenant_scope says whose rows a run reads, because a scheduled run has no caller: each_tenant is one run per tenant, each seeing only that tenant's rows; no_tenant is one run bound to no tenant. In a spec where an entity declares @tenancy(...), every job declares tenant_scope (JOB-TENANT-SCOPE-MISSING): the compiler never chooses it. tenant_scope = each_tenant in a spec where no entity declares @tenancy(...) is refused (JOB-TENANT-SCOPE-WITHOUT-TENANCY). Refused today. The block at the root of a single-service spec parses and is validated, and no scheduled run is built for a single-service application yet: a spec that declares jobs {} at its root, or tenant_scope on any job, is refused at validation (SCHEDULED_JOB_PRODUCER_MISSING, a limit of the compiler, listed in «What the compiler refuses today»). Until it is built, dispatch the work from an API operation through interactions {}. A platform {} manifest declares its jobs inside platform {}, never at the top level of the file (OPERATIONS_OUTSIDE_PLATFORM_BLOCK).

tenant_scope

Whose rows a scheduled run reads, because a run has no caller: `each_tenant` is one run per tenant, each seeing only that tenant's rows; `no_tenant` is one run bound to no tenant.

each_tenantno_tenant
tenant_scope = each_tenant
Job definitions
platform "MyPlatform" {
  jobs {
    "cleanup_expired_tokens" {
      schedule        = "0 */6 * * *"
      target_task     = "identity.handlers.cleanup_task.cleanup_expired_tokens"
      queue           = "maintenance"
      timeout_seconds = 300
      description     = "Purge tokens past their expiry window"

      retry {
        max_attempts = 3
        backoff      = "exponential"
        delay        = "30s"
      }
    }

    "send_daily_digest" {
      schedule    = "0 8 * * *"
      target_task = "notifications.handlers.digest_task.send_daily_digest"
      queue       = "low_priority"
      priority    = "low"
    }
  }
}

notifications

SMTP email is enqueued in the flow transaction through the shared outbox. Declare flow_completed("Name"), command_completed("Name") or state_change(Entity.field -> STATE), a matching entity, recipient, subject, body and explicit retry_count / retry_backoff. The target and fields must exist in the surrounding service. Substitutions name typed entity or completion payload fields; unknown fields block validation. Bodies are plain text. Subject CRLF is refused before sending. SMTP requires authenticated starttls or implicit TLS with certificate verification and credentials_secret_ref; from_name is optional with no default. Declare one email template with explicit subject and body. Duplicate attributes or localized alternatives without a selection binding are refused. Retry policies must fit the shared storage and calendar; reduce retry_count or retry_backoff when validation reports a capacity error. Credentials are JSON username/password in the required SMTP_CREDENTIALS_<SHA256-ref-prefix> environment binding, resolved at send time. Other notification channels retain their own producer checks.

host

Inside smtp: the SMTP server hostname, without a URL scheme.

port

Inside smtp: the declared TLS server port.

tls

Inside smtp: the required encrypted transport mode; certificates are verified.

implicitstarttls
from

Inside smtp: the sender mailbox.

from_name

Inside smtp: an optional visible sender name. Omission sends no visible name.

credentials_secret_ref

Inside smtp: the required reference to username/password credentials, resolved at sending.

retry_count

On each email event: the explicitly declared number of retries after the first attempt.

retry_backoff

On each email event: the explicitly declared exponential backoff in seconds.

recipient

On each email event: entity_field names a String, Text or Char field holding the destination mailbox.

locale

On the single email template: an optional locale label. Multiple localized templates require a selection binding and are refused without one.

Requires Entity.email, Entity.label and a declared CreateEntity flow in the surrounding service.

SMTP completion email
notifications {
  providers { email { smtp {
    host = "smtp.example.com"
    port = 587
    tls = starttls
    from = "[email protected]"
    credentials_secret_ref = "smtp/credentials"
  } } }
  event "created" {
    entity = Entity
    trigger = flow_completed("CreateEntity")
    channels = [email]
    recipient = entity_field("email")
    retry_count = 2
    retry_backoff = 1.5
    template "email" {
      subject = "Created {{label}}"
      body = "Dear {{label}}"
    }
  }
}

file_storage

Declares the files a service stores, one bucket per kind of file. The block is a second way to write object_storage: each bucket becomes a document type of that block, and the same routes serve it — authenticated, under the rules of the row holding each key, with the size and media-type checks. A service declares one or the other, not both. file_storage and a backup policy are declared together. The files are stored under the store's default variable, STORAGE_BUCKET_NAME; the backup names its own bucket variable in bucket_ref (for example bucket_ref = "BACKUP_BUCKET_NAME") and reads its own credentials. Naming STORAGE_BUCKET_NAME there is refused (BACKUP_SHARES_FILES_BUCKET).

The bucket name is an identifier (letters, digits and underscores, not starting with a digit): it is the document type the routes and the object keys carry. max_size is a whole number of megabytes ("10MB", "2GB") and allowed_types lists exact media types. provider = s3 and access = private are the defaults and the only values produced. Inside retention { }, days is the retention window and allow_overwrite = false makes the stored files write-once.

⚠️ What the object-storage routes do not produce is refused at validation, with the same text at compile time — nothing declared is ignored. DevMatrix capability gaps: provider other than s3 (FILE-STORAGE-PROVIDER-NOT-PRODUCED), access other than private (FILE-STORAGE-ACCESS-NOT-PRODUCED), retention { regulatory_basis } (FILE-STORAGE-REGULATORY-BASIS-NOT-PRODUCED), virus_scan = true (FILE-STORAGE-VIRUS-SCAN-NOT-PRODUCED) and cdn_enabled = true (FILE-STORAGE-CDN-NOT-PRODUCED). Spec errors: file_storage together with object_storage (FILE-STORAGE-WITH-OBJECT-STORAGE: the refusal prints the object_storage declaration to move each bucket into, as a document_type), a bucket name that is not an identifier (FILE-STORAGE-BUCKET-NAME), a bucket declared twice (FILE-STORAGE-BUCKET-DUPLICATE), a max_size that is not whole megabytes (FILE-STORAGE-MAX-SIZE) and allowed_types with an extension or a wildcard (FILE-STORAGE-ALLOWED-TYPES). For an S3-compatible store that is not AWS (MinIO, Cloudflare R2), declare object_storage with endpoint_url_env_var.

Whose files the keys are kept under. In a service that keeps its rows by tenant (an entity declares @tenancy(workspace, ...) or @role(workspace)), each stored file's key carries the tenant of the user who uploads it, and the user who signs in must belong to a tenant. In a service with no tenancy, keys carry no tenant (the default layout is "{document_type}/{year}/{month}"), and a file is reached only under the rules of the row that holds its key: the upload takes that entity's create route rules, the download its read route rules (403 when they do not admit the caller, 404 when no row holds the key). No route lists the store, and no file is public. A key layout that places {tenant_id} in a service with no tenancy is refused (OBJECT-STORAGE-KEY-TENANT-WITHOUT-TENANCY-001).

Uploads need a declared store. An upload in a service that declares no object storage, or one that declares storage_backend = local, is refused (FLOW-UPLOAD-NEEDS-OBJECT-STORAGE): the delivered service runs on a read-only disk, so the file would have nowhere to go. Declare the bucket the file goes to and name it in upload_destination.

File storage
file_storage {
  bucket "lab_reports" {
    provider      = s3
    max_size      = "100MB"
    allowed_types = ["application/pdf"]
    access        = private

    retention {
      days            = 3650
      allow_overwrite = false
    }
  }

  bucket "customer_documents" {
    max_size      = "10MB"
    allowed_types = ["application/pdf", "image/jpeg", "image/png"]
  }
}

No `@tenancy` anywhere in the service: the key is `sealed_scan/2026/11/...`, and the file is reached under the rules of the `Shelf` row that holds it.

Files in a service with no tenancy
entity Shelf {
  id       UUID @pk
  scan_key String(512) @field_purpose(object_key)
}
file_storage {
  bucket "sealed_scan" { provider = s3  max_size = "8MB" }
}

infrastructure

Docker, Redis, RabbitMQ, Elasticsearch, Celery, API gateway, CORS, and deployment configuration.

redis { cache { ... } } — the cache connection. An entity opts in with @cache or @cache(ttl: N); ttl here is the lifetime a bare @cache takes, and the only thing bounding staleness when invalidation cannot reach Redis. The cache stores the rows a read returned, sealed (AES-256-GCM) with a key derived from the service's ENTITY_CACHE_ENCRYPTION_KEY, a url-safe secret of at least 32 characters without which the service does not start. A write of a row the entity's row-level policies read, or a delete the database carries into its rows through an on_delete: cascade or on_delete: set_null key, invalidates the entity. Writes remain available; cached reads bypass the local circuit until a successful ping and recovery bump. The cache { type; ttl } form directly under infrastructure is refused. namespace keeps two services sharing a Redis from colliding on the same key. pool_max_connections and pool_min_idle size the connection pool: the ceiling is what a traffic spike cannot exceed, the floor is how many connections stay warm so the first request after a quiet period does not pay a handshake.

rabbitmq { ... } — the connection is declared as ENV VAR NAMES, never values: host_env, port_env, user_env, password_env. protocol_version pins the AMQP version, so a broker upgrade cannot silently move the wire format under a running service.

The grammar accepts these attributes of rabbitmq { }, and they do not compile yet: dead_letter_routing_key, discovery_mode, heartbeat_seconds, mandatory_routing, prefetch_count, publisher_confirms, quorum, quorum_replication_factor, static_peers, tls_ca_path_env, use_tls, vhost.

The grammar accepts these attributes of kafka { }, and they do not compile yet: acl_read_principals, acl_write_principals, auth_password_env, auth_user_env, auto_offset_reset, cleanup_policy, compression_type, consumer_group_id, min_insync_replicas, partitions, producer_acks, producer_idempotence, replication_factor, sasl_mechanism, schema_registry, security_protocol.

The grammar accepts these attributes of elasticsearch { }, and they do not compile yet: bulk_batch_size, bulk_timeout_seconds, ca_bundle_path_env, ilm_policy, ingest_pipeline, lifecycle_policy, min_age, number_of_replicas, number_of_shards, rbac_roles, refresh_interval, snapshot_repository, tenant_prefix, use_https, verify_certs, watcher_enabled.

type

Which SQL dialect the generated models, migrations and queries target. The same closed set as the platform `databases { database "x" { dialect } }` block — one question, one taxonomy.

clickhousepostgresql
type

Which edge gateway fronts the platform. A closed set: any other value does not parse.

kongnginxtraefik
gateway_type

The same attribute as `type`: the grammar routes both spellings to one production.

kongnginxtraefik
unit

Calendar bucket for an `analytics` step (refused at validation today). The bucket writes field, unit and as in that order.

dayhourminutemonth
Infrastructure config
infrastructure {
  docker {
    compose_version = "3.8"
    base_image      = "python:3.12-slim"
  }
  database {
    type = postgresql
    name = "user_service"
  }
  redis {
    use_ssl = true
    cache { enabled = true; ttl = 600 }
  }
  observability {
    metrics         = true
    tracing         = true
    health_endpoint = "/health"
  }
  api_gateway {
    enabled = true
    type    = kong
  }
}

Per-queue attributes

Per-queue (queue "<name>" { ... }), the three below decide what survives:

exclusive

The queue belongs to ONE connection and is deleted when that connection drops. Useful for a short-lived per-connection queue, wrong for a work queue: it makes the queue as durable as the process that opened it.

exclusive = true
auto_delete

Deleted once its last consumer goes away. Combined with `durable = true` it reads as a contradiction, and the auto-delete wins: surviving a broker restart does not help a queue that vanished when the consumer redeployed.

auto_delete = true
message_ttl_ms

How long a message may sit unconsumed before the broker drops it (or routes it to `dead_letter_exchange`). Without a DLX declared, this is silent data loss on a timer.

elasticsearch { auth { } }

elasticsearch { auth { ... } } — method picks the scheme and the rest name the ENV VARS that carry the credential: basic_auth_user_env + basic_auth_password_env, or bearer_token_env, or api_key_env. The spec names the variable, never the secret.

api_gateway { }

api_gateway { ... } — gateway_type picks the gateway product. ⚠️ type and gateway_type are TWO SPELLINGS OF THE SAME ATTRIBUTE — the grammar routes both to the same production — so a spec using one and a spec using the other are saying the same thing, and neither is more correct than the other.

jwt_claims_to_verify

Which claims the gateway checks before the request ever reaches a service. A claim absent from this list is not verified at the edge no matter what the token carries.

jwt_claims_to_verify = [...]
jwt_max_expiration

The longest token lifetime the gateway will accept. It is the gateway's defence against a token minted with a generous lifetime elsewhere; the issuer's own expiry claim is a promise, this is an enforcement.

rate_limiting

Three independent windows, not one expressed three ways. `per_minute` bounds a short spike, `per_day` bounds a quota, and declaring only the minute leaves a caller free to spend all day at the limit.

rate_limiting { per_minute / per_hour / per_day }

Integration resource bindings

Integration resource bindings. RabbitMQ queues declare bind "name" { exchange = "events" routing_key = "submitted" } on a declared exchange. A missing or contradictory binding stops with PRODUCER_MISSING (a spec gap). Not supported yet, refused at validation until connected (INTEGRATION-CONSUMER-MISSING, a compiler gap; the message names what to remove): an interaction's delivery, event publication by trigger/partition_key/payload_map, a topic's external_consumers, an index's sync_on/sync_from (with the index's document_id), the search step (with its text, near { distance } and within clauses), a ClickHouse table's source and the analytics step (with its group_by, range, bucket and measures). Kafka topics, Elasticsearch indexes and ClickHouse tables therefore do not compile yet, and this reference shows no example of them.

redis_topology

Platform-scope. Declares WHICH Redis namespaces exist, WHO owns each one and which services may read each key. The compiler checks the generated services against exactly this declaration: cross-service consumption goes through the generated typed accessor, never through a raw key.

credential_spec is a secret-store reference (env://REDIS_URL), NOT a host/port pair; the topology refuses to be enabled without it. namespace "<name>" { } carries one or more owner_service lines and its key "<name>" { } entries: template is the key pattern, value_kind the Redis data shape (closed set), ttl_s the lifetime (omit it for no TTL, and then the owner owes an explicit deletion path), and each consumer line names a service allowed to read the key. replica { } is optional and its presence is the opt-in: kind picks the replication mode and read_after_write_consistency_window_s bounds how stale a replica read may be.

Not the same block as infrastructure { redis { host, port } }, which declares only the endpoint; that one still parses so existing specs keep compiling until they migrate.

credential_spec

Secret-store reference for the Redis endpoint (`env://REDIS_URL`). Never a host/port pair in the clear.

owner_service

Inside `namespace { }`: a service that owns the namespace. Repeat the line for several owners; ownership is what the gate adjudicates.

template

Inside `key { }`: the key pattern with its placeholders, e.g. `session:{token_id}`.

value_kind

Inside `key { }`: the Redis data shape stored under the key. A wrong word is refused at parse time with the accepted set named.

counterhashlistsetstreamstringzset
ttl_s

Inside `key { }`: lifetime in seconds. Omit for no TTL — the owner then owes an explicit deletion path.

consumer

Inside `key { }`: a service allowed to read the key through the generated typed accessor. Repeat for several consumers.

kind

Inside `replica { }`: the replication mode.

read_after_write_consistency_window_s

Inside `replica { }`: how many seconds a replica read may lag a write before the platform treats it as inconsistent.

Two namespaces with one owner each, a session key readable by two consumers under a TTL, and an async replica with a bounded read-after-write window.

Redis topology with an owned session namespace and an async replica
platform "MyPlatform" {
  version = "1.0.0"

  redis_topology {
    credential_spec = "env://REDIS_URL"

    namespace "session" {
      owner_service = "identity"

      key "session_by_token" {
        template   = "session:{token_id}"
        value_kind = string
        ttl_s      = 3600
        consumer   = "gateway"
        consumer   = "audit"
      }
    }

    namespace "audit_stream" {
      owner_service = "audit"
      key "audit_events" { template = "audit:events"; value_kind = stream }
    }

    replica {
      kind = "async_streaming"
      read_after_write_consistency_window_s = 5
    }
  }
}

platform

Multi-service platform orchestration. Declares modules with their compile-time dependencies; the compiler derives topological build order automatically.

Platform intent. description, purpose = "..." and principles = ["...", "..."] carry what the platform is FOR and the rules it holds itself to. principles is an array of free strings, not a taxonomy — the compiler does not enforce them, which is precisely why they are worth writing where the spec lives instead of in a document nobody opens next to the code. They are the platform's own statement of what a change must not break.

Platform definition
platform "MyPlatform" {
  version = "1.0.0"

  modules {
    UserService         { spec = "user.dmx";         dependencies = [] }
    OrderService        { spec = "order.dmx";        dependencies = [UserService] }
    NotificationService { spec = "notification.dmx"; dependencies = [OrderService] }
  }

  shared_kernel { modules = [tenant_context, jwt_utils, event_bus, audit_decorator, observability] }

  interactions {
    "order-confirmed-notifies" {
      tier     = 1
      producer = OrderService
      consumer = NotificationService
      trigger  = event("order.confirmed")
      task     = "send_confirmation"
      queue    = "notificationservice"
    }
  }
}

Per-module attributes

The kernel set every module receives is decided in two places, and both only ever SUBTRACT. shared_kernel { exclusions = [...] } drops components platform-wide — a name listed there is gone from every module, including modules that never mention it — and each module's exclude_kernel_components drops more, for that module alone. The two lists are unioned, never differenced: a module cannot bring back a component the platform excluded by leaving it off its own list.

Beyond spec and dependencies, each module inside modules { } may declare who answers for it and how it is grouped:

owner / contact

The team that answers for the module and the address to reach it. They travel into the generated service so a page that fires at 3am names a destination instead of a repository.

owner = "..."
contact = "..."
billing_tag

The tag the module's cost is attributed under. It is the only way a per-service cost split exists at all: without it every module's spend lands in one undivided total.

billing_tag = "..."
sla

The module's declared service level. `response_time_p99_ms` is a p99 and not an average on purpose: an average hides the tail that users actually notice. `rps` is the load it is sized for, and `criticality` is what decides whose page fires first when several modules degrade at once — without it, every module is equally urgent, which is the same as none being urgent.

sla { response_time_p99_ms, rps, criticality }
bounded_context

The semantic boundary the module belongs to. This is intent, not topology: two modules may sit in the same bounded context and still be deployed apart, and the compiler will not infer it from `dependencies`.

bounded_context = "..."
exclude_kernel_components

Shared-kernel components this module opts OUT of.

exclude_kernel_components = [...]

shared_kernel (what every module gets, and the floor it needs)

A platform-scope block naming the modules every service inherits — errors, jwt_utils, base_repository and the rest of a closed set the grammar enforces at parse time, so a name that is not a real kernel module does not parse rather than resolving to nothing later.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

modules

What every service gets.

exclusions

What is held back, by bare identifier.

python_requires

The interpreter floor the shared kernel needs, written the way a package does it (`">=3.12"`). It belongs to the KERNEL and not to a module: everything inherits the kernel, so its floor is the platform's floor, and there is nowhere else in the language to say it once.

python_requires = "..."

Module names are a closed set enforced by the grammar; the version floor is a string.

The kernel every module inherits
platform "MyPlatform" {
  shared_kernel {
    modules         = [errors, jwt_utils, base_repository]
    exclusions      = [legacy_reports]
    python_requires = ">=3.12"
  }
}

message_types · default_level · storage_model

Set is_websocket = true to declare a WebSocket endpoint. WebSocket endpoints require an authenticated principal with declared tenant membership, explicit subscriber permissions, typed subscription parameters and event payloads, explicit message size and frequency limits, declared room bindings, transactional event publication and configured Redis fanout. Supported declarations provide a real WebSocket route, durable event delivery across replicas and real-client tests. A missing declaration or an unsupported policy is refused with its named correction or capability limit; a declaration lost while compiling is reported as a problem on our side. PDF generation remains unavailable.

default_level (in a service's audit { }) is a closed taxonomy of five: none, minimal, standard, full, debug. It sets the level for the service; an entity's own @audit(level: ...) is the per-entity override. Two places, one taxonomy — and the service-level default is what applies to everything that does not override it, which is usually most of the model.

storage_model (in tenant_config { }) is the one attribute in that block that is not a setting definition: it declares HOW tenant settings are stored ("dedicated_table" and friends), while every other entry in the block is a named setting with its own data_type, default and optional platform_minimum / platform_maximum. It reads like one more setting and is the rule the rest are stored under.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

message_types

The declared producer events delivered by a channel; each entry selects its payload and explicit room mappings.

message_types { "event" { payload_fields = [field] room_bindings { subscription_key = event_field } } }
payload_fields

The typed fields of the declared event that subscribers receive.

payload_fields = [field]
room_bindings

One explicit event-payload field for every subscription dimension, retaining its type and authenticated tenant scope.

room_bindings { subscription_key = event_field }
default_level

How much every audited operation records unless it overrides this. Higher levels keep more per event and cost more storage.

debugfullminimalnonestandarddefault
readable_by

The security roles that may read this module's audit trail (GET /audit-logs). Each role must be declared by the security block. With no reader declared the route refuses every caller, and /validate warns with the roles to choose from.

readable_by = [AUDITOR, ADMIN]

The service-level audit default, the roles that may read the trail, and how tenant settings are stored. The room is served to members who may read it.

An audit default, its readers, and tenant storage
service "Chat" {
  docs { operator_only }
  version  = "1.0.0"
  database = "chat"

  audit {
    enabled       = true
    default_level = standard
    retention     = "5y"
    readable_by   = [AUDITOR]
  }
}

entity Member {
  @role(user)

  id            UUID        @pk
  email         String(255) @not_null @unique @format(email) @sensitive
  password_hash String(255) @not_null @sensitive @field_purpose(password)
  role          Enum(MEMBER, ADMIN, AUDITOR) @not_null @default("MEMBER")
  is_active     Boolean     @not_null @default(true)
}

entity Room {
  @audit(level: full)

  id UUID @pk
}

security {
  auth_scheme       = jwt
  password_hashing  = bcrypt
  user_entity       = "Member"
  user_lookup_field = "email"
  active_field      = "is_active"
  role_field        = "role"

  roles = [MEMBER, ADMIN, AUDITOR]

  rate_limit {
    login_attempts      = 5
    requests_per_minute = 120
    lockout_duration    = "15m"
  }

  policy "member_admin" {
    entity = Member
    allow [update] for [ADMIN]
  }

  policy "room_access" {
    entity = Room
    allow [read] for [MEMBER, ADMIN]
  }
}

api {
  POST "/auth/login" {
    auth_required = false
    request { email String(255) @required; password String(128) @required @sensitive @field_purpose(password) }
    response { access_token String }
  }

  PATCH "/members/{id}" {
    operation_id = "update_member"
    addressing { id = Member.id }
    request { is_active Boolean @required }
    response @entity(Member)
  }

  GET "/rooms/{id}" {
    operation_id = "get_room"
    permissions  = ["chat:read"]
    addressing { id = Room.id }
    response @entity(Room)
  }
}

tenant_config {
  storage_model = "dedicated_table"

  max_rooms {
    data_type = "integer"
    default   = 50
  }
}

health_check · test_database · partition_by (shaping the run, not the code)

Three attributes that do not change what the service DOES, and change whether it behaves under load, under test, and over time.

  • health_check { interval, timeout, retries } sits inside docker { }. interval and timeout are duration STRINGS ("30s", "5s"); retries is a plain integer. The three multiply: with 30s and 3 retries a container is not declared unhealthy for about a minute and a half, which is the number worth knowing before an orchestrator restarts something mid-request.
  • test_database { name = "..." } is its own top-level entry in infrastructure { }, a SIBLING of database { } and not a field inside it. It is the only way to say that tests must not run against the same database as the service — declaring it is what makes that separation part of the spec instead of a convention in someone's shell.
  • partition_by belongs to a ClickHouse table, alongside engine, order_by and ttl. It takes an EXPRESSION as a quoted string ("toYYYYMM(occurred_at)"), not a column list — which is what separates it from order_by, its neighbour, which takes bare identifiers. The two are different axes: order_by decides how rows are sorted inside a part, partition_by decides which part they land in, and only the second one is what a ttl can drop wholesale.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

acks_late · celery_worker · internal (what happens when something dies)

Three booleans that look like tuning and are not — each one decides what survives a failure.

  • acks_late (in the platform's celery { }) says WHEN a task is acknowledged. Acknowledging late means the broker is told the task is done only after it actually ran, so a worker that dies mid-task leaves the message on the queue and someone picks it up again. Acknowledging early means the message is gone the moment it is handed over, and a worker crash loses it silently. The cost of true is that a task can run twice — which is why it belongs next to idempotent on the interaction, not on its own.
  • celery_worker (inside a module's output { }, beside generate_tests and generate_frontend) decides whether that module gets a worker at all. It is a per-module switch: a platform can declare celery once and still get workers only for the modules that need one.
  • internal (on a rabbitmq { exchange "..." { } }) marks an exchange that publishers cannot post to directly — it only receives from other exchanges. It is how a fan-out stays an implementation detail: clients publish to the public exchange, and the internal one cannot be reached even by a client that learns its name.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

`output { }` is per module; `celery { }` is declared once for the platform.

Late acks, and a worker only for the module that needs one
platform "MyPlatform" {
  modules {
    identity { spec = "identity.dmx"; dependencies = [] }

    orders {
      spec         = "orders.dmx"
      dependencies = [identity]

      output {
        generate_tests = true
        celery_worker  = true
      }
    }
  }

  celery {
    broker_url      = "redis://redis:6379/0"
    result_backend  = "redis://redis:6379/1"
    task_serializer = "json"
    acks_late       = true
    concurrency     = 2

    worker worker_fast {
      queues = ["fast", "notifications"]
    }
  }
}

request_params · reply · integration_ref (asking something and waiting)

Most cross-service interactions are one-way: a producer publishes, a consumer reacts, nobody waits. A request-reply interaction is the one that waits, and it needs two things a fire-and-forget edge never declares — what goes out and what must come back.

  • request_params { } declares the parameters of the outbound call, and each one carries WHERE it travels: @path, @query or @body, plus @required. This is the part worth reading closely — the location is declared, never inferred from the name. order_id UUID @path @required and coupon String @body are the same shape of line and end up in different parts of the request.
  • reply { } is a nested block that takes the SAME attributes as the interaction itself, so the answer declares its own response_schema and its own timeout_ms. Its sibling request { } works the same way. The two halves are described separately because they can differ: the outbound side may be idempotent while the answer is what actually carries the deadline.

Without a reply, response_schema and timeout_ms on the interaction describe a call whose answer nobody declared a shape for — which parses, and is usually not what was meant.

integration_ref solves a different problem, on flows. A top-level integration "name" { } declares an outside system once — its type, its provider, its required_env_vars, what happens when it is down (fallback_behavior). A flow then BINDS to it by name with integration_ref = "name". The reference is resolved when the platform is built, so the generated handler never looks the integration up by name at run time: the binding is a declaration, not a lookup.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

`integration_ref` names the declaration; it does not repeat its contents.

An integration declared once, bound by name from a flow
integration "stripe_payments" {
  type              = payment_service
  provider          = "stripe"
  version           = "2024-06-20"
  fallback_behavior = fail_fast
  is_critical       = true
  required_env_vars = ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"]
}

flow "Charge Order" {
  type            = workflow
  trigger         = http(method="POST", path="/orders/{id}/pay")
  entity          = Order
  integration_ref = "stripe_payments"

  step 1 "Charge the card" {
    action = create
    target = Order
  }
}

Each parameter declares WHERE it travels. `reply { }` carries the answer's own schema and deadline.

A request-reply interaction (platform scope)
platform "MyPlatform" {
  modules {
    billing { spec = "billing.dmx"; dependencies = [] }
    orders  { spec = "orders.dmx";  dependencies = [billing] }
  }

  interactions {
    "billing.quote_order" {
      tier          = 2
      producer      = orders
      consumer      = billing
      pattern       = request_reply
      trigger_operation = "create_order"
      timeout_ms    = 2000
      retry         = 2
      idempotent    = true

      request_params {
        order_id UUID   @path @required
        currency String @query
        coupon   String @body
      }

      request {
        target_entity = Order
      }

      reply {
        response_schema = Quote
        timeout_ms      = 2000
      }
    }
  }
}

retention · on_delete · buckets (the same word, different blocks)

Four blocks are spelled retention and they are not the same block. Each lives at a different scope and takes a different attribute set, so copying one into another's place does not parse:

  • file_storage { bucket "..." { retention { } } } — how long a BUCKET keeps its objects. Takes days and allow_overwrite, and the second is the one to read twice: false means an object at a key cannot be replaced, which is what write-once evidence requires and what makes a correction a new key rather than an edit. The grammar also accepts regulatory_basis = "...", and it is refused at validation (FILE-STORAGE-REGULATORY-BASIS-NOT-PRODUCED): nothing DevMatrix generates carries it yet.
  • platform { retention { module X { } } } — how long a MODULE's data is kept. Takes days, on_delete = "..." (what happens when the window closes) and storage_class = "...", a quoted string.
  • object_storage { document_type X { retention_days = N } } — not a block at all here, a plain integer attribute.

The fourth, entity X { retention { days = N field = f } }, says how long a ROW of the entity is kept: it takes days and field, a DateTime field of the entity, and it is written among the entity's fields. The service deletes every row whose field is older than days whole days, at startup and then once a day, in batches, one tenant at a time under that tenant's row policy. It is refused on the tenancy root or a per-user entity (ENTITY-RETENTION-TENANCY), and when a reference to the entity, or to an entity a cascade reaches, says neither on_delete: cascade nor on_delete: set_null, or leads into an append-only entity (ENTITY-RETENTION-BLOCKED-BY-REFERENCE).

on_delete also has two homes with two syntaxes, which is the easier of the two mistakes to make:

  • On a foreign key it is an ARGUMENT with a colon and a bare word: @fk(Order.id, on_delete: cascade).
  • In platform retention it is an ATTRIBUTE with an equals and a quoted string: on_delete = "archive".

The same split hits the storage class. storage_class (platform retention) takes a QUOTED string; to_storage_class, inside an object_storage lifecycle, takes a BARE identifier. And a lifecycle transition is a single construct that requires BOTH keys, in that order — after_days = N to_storage_class = CLASS on one line. to_storage_class cannot be written on its own, and the two halves cannot be swapped.

Object storage has TWO lifecycle surfaces, and only one of them can delete. The service-scope lifecycle { } shown above only moves objects between classes. The platform-scope one is a lifecycle_rule { } block per rule, with rule_kind naming which of the two things it is — transition (move to storage_class after after_days) or expiration (delete after after_days, and no storage class, because there is nowhere to move to). A bucket declares one lifecycle_rule per rule, so tiering and deletion are separate declarations rather than one entry with an optional half. If a retention window must actually END, expiration is the only thing that says so — the service-scope lifecycle cannot express it.

buckets is a false friend. It has nothing to do with storage: it is the explicit bucket boundaries of a histogram metric, inside service_observability { metrics { } }. Object storage spells its own container bucket (singular, a block with a label); the plural is always the histogram.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

rule_kind

Whether the lifecycle rule moves an object to another storage class or deletes it.

expirationtransition
to_storage_class

For a transition rule: the tier the object moves into once the window closes. Four provider-agnostic tiers — NOT the platform-level `storage_class`, which takes a provider’s own catalogue name (`GLACIER`, `COLDLINE`) and rejects these.

archivedeep_archiveinfrequent_accessstandard

Service scope. Note `on_delete:` with a colon on the FK, and `buckets` belonging to a metric rather than to storage.

Bucket retention, object lifecycle, and histogram buckets
entity OrderItem {
  id       UUID @pk @default($computed.uuid)
  order_id UUID @fk(Order.id, on_delete: cascade) @not_null
}

object_storage {
  backend             = s3
  bucket_name_env_var = "DOCS_BUCKET"

  document_type Invoice {
    retention_days   = 3650
    write_once       = true
    max_file_size_mb = 25

    lifecycle {
      after_days = 90  to_storage_class = infrequent_access
      after_days = 365 to_storage_class = archive
    }
  }
}

service_observability {
  metrics_enabled = true

  metrics {
    request_latency_seconds {
      type        = histogram
      labels      = [route, method]
      buckets     = [0.05, 0.1, 0.5, 1.0, 5.0]
      description = "Request latency distribution"
    }
  }
}

A service declares `file_storage` or `object_storage`, not both, so the bucket form of retention lives in its own service.

Bucket retention (file_storage)
file_storage {
  bucket "invoices" {
    provider      = s3
    max_size      = "25MB"
    allowed_types = ["application/pdf"]
    access        = private

    retention {
      days            = 3650
      allow_overwrite = false
    }
  }
}

The other `retention`. Here `on_delete` takes an equals and a quoted string, and `storage_class` is quoted too.

Per-module retention (platform scope)
platform "MyPlatform" {
  retention {
    module orders {
      days          = 2555
      on_delete     = "archive"
      storage_class = "GLACIER"
    }
  }
}

`rule_kind` says which of the two a rule is. An `expiration` rule has no storage class: there is nowhere to move to.

Platform-scope lifecycle rules — tiering and expiry are separate
platform "MyPlatform" {
  object_storage {
    provider = s3

    bucket "invoices" {
      name            = "acme-invoices"
      region          = "us-east-1"
      owning_service  = "billing"
      encryption_kind = SSE-S3

      lifecycle_rule {
        rule_kind     = transition
        storage_class = "GLACIER"
        after_days    = 365
      }

      lifecycle_rule {
        rule_kind  = expiration
        after_days = 2555
      }
    }
  }
}

Secrets and TLS inside infrastructure { }

Twenty-seven attributes across the infrastructure { } blocks end in _env, and every one of them follows the same rule: the value is the NAME of an environment variable, never the secret itself. db_password_env = "ORDER_SERVICE_DB_PASSWORD" does not declare a password — it declares which variable the running service will read one from. Writing the literal password there would put a credential in the spec, which is exactly what the suffix exists to prevent.

The convention is uniform, so once it is read once it holds everywhere: bootstrap_servers_env, sasl_user_env, sasl_password_env, api_key_env, client_secret_env, hosts_env, url_env and the rest all name variables.

use_ssl (in redis { }) is a plain boolean and sits at the block's own level, a SIBLING of cache { } / broker { } / pubsub { } rather than inside one of them — it is a property of the connection, not of a role.

retention_bytes (in a kafka { topic "..." { } }) is the size-based companion to retention_ms: a cap in bytes per partition. The two are independent and either may be omitted; a topic that declares both discards a segment when it crosses EITHER limit, whichever comes first.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

keystore and truststore

keystore and truststore are not two words for the same file. Both appear as a path/password pair, in kafka { } and again in elasticsearch { }:

Mixing them up is the common mistake and it fails asymmetrically: a wrong truststore is refused at handshake, while a missing keystore is only refused when the peer actually asks for a client certificate — which may be in production and not in staging.

tls_keystore_path_env / tls_keystore_password_env

The identity THIS service PRESENTS. The keystore holds our own certificate and private key; it is what makes mutual TLS mutual. Declaring only this side means we prove who we are and accept whoever answers.

tls_truststore_path_env / tls_truststore_password_env

The authorities this service ACCEPTS. The truststore holds the CA certificates a peer must chain to. Declaring only this side means we verify the broker and stay anonymous ourselves.

depends_on · imports · exports (module boundary)

How a module says what it needs and what it offers. Two surfaces declare this, at two scopes, and imports means something different in each — the same word is a KEYWORD in one and a BLOCK OPENER in the other.

  • depends_on { } — inside service { }. Each entry is a module name followed by the keyword imports and the symbols taken from it: UserService imports [User, Role]. The keyword sits BETWEEN the name and the array. optional_imports is the same shape for a dependency the service can run without.
  • imports { } — inside a modules { X { } } entry. Here imports opens a block, and inside it the plain entry drops the keyword entirely: UserService [User, Role], name then array, nothing between. The optional form is the exception that KEEPS its keyword: UserService optional_imports [Audit]. So the asymmetry survives inside the block — required entries are bare, optional ones are labelled.
  • exports { } — inside the same module entry. Only two entry kinds exist, and they do not take the same literal: entities [User, Role] takes bare identifiers, services ["user-api"] takes strings. Exporting an entity and exporting a service are different declarations, not one list with two spellings.

dependencies and imports are not alternatives. A module entry may carry dependencies = [UserService] — which orders the build — AND an imports { } block, which names the symbols crossing the boundary. The first answers what must compile first; the second answers what is actually taken. Declaring the dependency does not declare the import, and a module that lists a dependency it imports nothing from is telling the compiler to serialise a build for no reason.

Inside service { }: the module name, then the keyword, then the array.

Service scope — `imports` is a keyword
service "OrderService" {
  docs { operator_only }
  version  = "1.0.0"
  database = "order_service"

  depends_on {
    UserService      imports          [User, Role]
    AuditService     optional_imports [AuditEntry]
  }
}

Inside platform { modules { ... } }: no keyword on the required entry; `optional_imports` keeps its own. `exports` separates entities (identifiers) from services (strings).

Module scope — `imports` is a block, and required entries are bare
platform "MyPlatform" {
  modules {
    UserService  { spec = "user.dmx";  dependencies = [] }
    AuditService { spec = "audit.dmx"; dependencies = [] }

    OrderService {
      spec         = "order.dmx"
      dependencies = [UserService]

      imports {
        UserService [User, Role]
        AuditService optional_imports [AuditEntry]
      }

      exports {
        entities [Order, OrderLine]
        services ["order-api"]
      }
    }
  }
}

test_coverage (per-module)

A module's declared testing commitment, written inside a modules { X { } } entry. Four attributes, and three of them do not take a number:

So the block answers two questions with two shapes: which suites does this module owe (three strings) and how deep should the unit tests cut (one float). Mixing them — writing e2e = 0.8 or target_branch_coverage = "required" — does not parse.

As with every block on this page, this documents the LANGUAGE — what the compiler parses. Whether a declaration here changes the generated code is a separate question this page does not answer.

integration / e2e / contract

Each takes the string `"required"` or `"optional"`, naming whether that suite is expected for the module. They are a commitment, not a measurement. The plausible reading — a percentage like `"80%"` — is wrong: these say WHETHER the suite is owed, never how much of it exists.

target_branch_coverage

The one number in the block, a float (`0.85`, not `"85%"` and not `85`). It is the branch-coverage target the module is aiming at, which is a different question from whether a suite is owed at all.

Three strings say which suites are owed; the float is the branch target.

Per-module coverage commitment
platform "MyPlatform" {
  modules {
    OrderService {
      spec = "order.dmx"

      test_coverage {
        integration            = "required"
        e2e                    = "optional"
        contract               = "required"
        target_branch_coverage = 0.85
      }
    }
  }
}

integration_gateway (platform-scope)

Platform-scope ingress/egress for non-REST partner traffic, declared inside platform { integration_gateway { ... } }. Five bodies, all optional and repeatable: inbound_endpoints { endpoint "<id>" { path, protocol, ...destination } } — where protocol is a closed taxonomy of nine (csv-rfc4180 / fhir-r4 / hl7v2-2.5 / https / json-api / rest / soap-1.2 / webhook-generic-hmac / xml-1.0) and each endpoint may carry a signature_validation { kind, secret_ref, algorithm } sub-block. A kind = "jwt" endpoint declares the ONE algorithm its tokens are signed with (HS256 / RS256 / ES256 / EdDSA, the set the jwt_domains use; no default), and secret_ref names the shared secret for HS256 or the verification key for an asymmetric algorithm; every other kind declares no algorithm. An endpoint declares exactly ONE destination, and the two mean opposite directions. target_capability dispatches through an adapter, and a generated adapter is always an outbound network client, so that destination always means the message leaves the platform. target_interaction names a declared interaction and hands the message to a module of this platform, by enqueueing the task that interaction declares — it is the one to use for ingestion. The referenced interaction must declare a producer (the module that receives) and the task that gets enqueued; its queue is optional, and when absent the dispatch name-routes to the owning service's queue like every other cross-service task. Declaring neither destination is refused before emission; declaring both is refused as ambiguity, not resolved by precedence. Until target_interaction existed there was no vocabulary for "this webhook feeds my own module", so authors named an adapter and got a webhook that forwarded the received payload back out to a provider — a declaration that read as ingestion and compiled as egress. outbound_dispatch { "<capability>" = "<target>" } mapping entries; parsers = [ ... ]; dead_letter_queue { backend, stream_key_template, table_name, max_depth_threshold }; and retry_orchestration_policy { drain_interval_seconds, max_redrives_per_message, backoff_factor }.

integration (service-scope)

How a service talks to something outside the platform. integration "<name>" { ... } declares its type — a closed taxonomy of webhook_receiver / api_client / oauth_flow — plus provider, version, documentation_url, whether it is_critical, the required_env_vars it needs, the depends_on_entities it touches, and a fallback_behavior (log_and_continue / fail_fast / queue_retry) saying what happens when the far side does not answer. Provider names are free strings on purpose: the compiler enumerates no catalogue of vendors. One of three sub-blocks carries the transport detail — webhook { ... }, oauth { ... }, api_client { ... }.

Integrations are not offered yet. An integration with type = webhook_receiver is refused at validation and compilation (WEBHOOK-RECEIVER-NOT-PRODUCED-001): remove the integration and the flows that receive through it. An integration of any other type is refused as unused, because no step calls an outbound client yet.

A receiver's webhook { } block reads signature_header, signature_secret_env, signature_algorithm, events, event_field, idempotency_field and retry_policy; it parses, and is refused with its integration.

type

What kind of external system this integration talks to. Decides which nested block the rest of the declaration goes in.

api_clientemail_servicenotification_serviceoauth_flowpayment_servicestorage_servicewebhook_receiver
fallback_behavior

What the generated service does when the integration is unreachable or errors.

fail_fastlog_and_continuequeue_retry
auth_type

How the generated client authenticates against the remote API.

api_keybasic_authbearer_tokenhmac_signaturenoneoauth2
signature_algorithm

For an inbound webhook: the HMAC algorithm the signature is verified with. Webhook receivers are refused at validation and compilation (WEBHOOK-RECEIVER-NOT-PRODUCED-001).

sha1sha256
Two outbound transports
integration "PartnerAuth" {
  type     = oauth_flow
  provider = "acme"

  oauth {
    authorization_url = "https://acme.example/oauth/authorize"
    token_url         = "https://acme.example/oauth/token"
    scopes            = ["invoices:read"]
    client_id_env     = "ACME_CLIENT_ID"
    client_secret_env = "ACME_CLIENT_SECRET"
    redirect_uri_path = "/oauth/acme/callback"
  }
}

integration "PartnerApi" {
  type     = api_client
  provider = "acme"

  api_client {
    base_url_env    = "ACME_BASE_URL"
    auth_type       = bearer_token
    auth_header     = "Authorization"
    auth_env_var    = "ACME_TOKEN"
    timeout_seconds = 30
    retry_count     = 3
    retry_backoff   = 1.5
  }
}

cors (platform-scope)

Cross-origin policy for the whole platform: allowed_origins, allowed_methods, allowed_headers, exposed_headers (arrays), allow_credentials (boolean), and max_age_seconds. This is the only CORS declaration: every service and the API gateway apply it. Omit the block and no origin is trusted. allow_credentials together with a wildcard origin is the combination browsers refuse — declare the origins you mean.

infrastructure { api_gateway { } } does not take a cors block: the gateway answers with this declaration. A spec that still has one there moves its values here, under the names above.

A monolith declares this same block at the top level of its one spec, next to service: its main.py and its gateway answer with it. A service that belongs to a microservices platform does not declare one; the platform's is the policy, and a service spec that has one is refused.

output (platform-scope)

Where and what the compiler writes: base_dir is the output root, timestamp_prefix puts each run in its own directory, and the four booleans generate_frontend, generate_portal_apis, generate_tests, run_tests select what the build produces. Frontend generation is not production-ready today.

validation (platform-scope)

Which platform-assembly checks are enforced, all booleans: check_circular_deps (a cycle in the module graph), validate_exports and require_all_imports (a module importing what no module offers), fail_on_missing_spec (a modules row pointing at a spec that is not there), and strict_mode. Distinct from the service-scope validations { } block, which constrains DATA — this one constrains the platform's own wiring.

jwt_domains (platform-scope)

Multi-domain JWT configuration, declared inside platform { jwt_domains { ... } }. Each domain "<name>" { ... } row declares issuer, audience, algorithm, and its key material by reference — secret_env, secret_ref, private_key_ref, public_key_ref, or jwks_uri — plus path_scope (the request paths the domain governs) and the lifetimes token_lifetime_minutes, refresh_token_lifetime_days, key_rotation_days. Keys are named, never inlined: the DSL declares a reference and the secret stays out of the spec.

authority (platform-scope)

Binds the platform to an external authority spec pack: spec_pack names the pack, binding and enforcement are identifiers (not strings) selecting how it attaches and how strictly it is enforced, and coverage lists what it covers.

enforcement

For a separation-of-duties conflict: what a request from a principal holding both sides gets. `block` records the conflict and denies with 403; `warn` and `log_only` record it and let the request through. Omitting it means `block`, so an existing rule keeps behaving exactly as it did.

blockdefaultlog_onlywarn
scope

How far a separation-of-duties conflict reaches. A different set from the feature-flag `scope`.

same_sessionsame_transactionsame_user

edge_agents (platform-scope)

Declares the edge agent fleet inside platform { edge_agents { ... } }. Each agent "<name>" { ... } carries deployment_target, runtime, local_store, the protocols it speaks, its sync_endpoint and config_update_channel, the cadences heartbeat_interval_s and telemetry_emission_rate, and its offline_buffer_policy — what the agent does with data it cannot ship yet.

rate_limits (platform-scope)

Platform-scope rate limiting. Three policy shapes, each taking the same three attributes limit, window_seconds, burst_capacity: per_tenant { ... }, per_ip { ... }, and per_route "<path>" { ... } for a single route. The per-service rate_limit block is a different surface; this one governs the platform edge.

mtls (platform-scope)

Mutual TLS material for platform-to-platform traffic, by reference only: client_cert_ref, client_key_ref, ca_bundle_ref. No certificate or key is ever written into a spec.

security_headers (platform-scope)

HTTP response hardening at the platform edge: hsts_max_age_seconds, hsts_include_subdomains, hsts_preload, frame_options, content_type_options_nosniff, referrer_policy, content_security_policy. The three HSTS flags and the nosniff switch are booleans; the rest are strings carrying the header value verbatim.

adapters (platform-scope)

The registry of OUTBOUND integrations, declared inside platform { adapters { ... } }. Each adapter "<id>" { ... } describes one third party and, more importantly, what the platform does when that third party misbehaves — which is the part a caller cannot decide for itself at the call site.

adapter_type / protocol / capabilities

What kind of integration this is, and `protocol` the wire it speaks. `capabilities = [...]` is what it can DO; `capability_routes` below dispatches on exactly those names, so a capability absent here is unroutable.

adapter_type = "..."
capabilities = [...]
owned_by

The team that answers when it breaks. An outbound integration always has an owner; declaring it is what makes the owner findable from the generated service instead of from memory.

owned_by = "..."
countries

Where this adapter is usable. It is a routing constraint, not documentation: a capability route may resolve differently per tenant because of it.

countries = [...]
timeout_ms / fallback_adapter_id

How long to wait, and who takes over. A fallback without a timeout never triggers, because nothing ever gives up.

fallback_adapter_id = "..."
credential_spec

A REFERENCE to the credential (`env_var` / `vault_path` / `kms_key_id`) and how long it may be cached. The secret itself never appears in a spec.

credential_spec { kind, value, ttl_seconds }
retry_policy

`retryable_error_classes` is the one that decides correctness rather than patience: retrying a non-idempotent failure is how one timeout becomes two charges.

retry_policy { max_attempts, backoff_factor, backoff_cap_ms, retryable_error_classes }
protocol

Which wire protocol the adapter speaks. The same set is drawn on by an integration-gateway endpoint.

csv-rfc4180fhir-r4hl7v2-2.5httpsjson-apirestsoap-1.2webhook-generic-hmacxml-1.0

circuit_breaker_policy { }

circuit_breaker_policy { ... } is retry's counterpart, and the three attributes are one decision each:

error_threshold

How many failures open the breaker. Below it the platform keeps calling a service that is already down, and every one of those calls costs the caller its timeout.

recovery_timeout_ms

How long the breaker stays open before testing again. Too short and the recovering dependency is re-drowned by the traffic that broke it.

half_open_max_calls

How many probes are allowed through while testing. This is what makes recovery a MEASUREMENT rather than a gamble: without a cap, half-open is just the closed state with extra steps.

rate_limit_policy { }

rate_limit_policy { requests_per_second, burst, scope } bounds what the platform sends OUT — a limit the third party would otherwise have to enforce by rejecting. requests_per_second is the sustained rate and burst is how much of it may be spent at once: without a burst allowance a caller that batches work is throttled for being bursty rather than for exceeding its share, and scope decides whether the budget is the platform's or each tenant's. state_code_mapping { "<theirs>" = "<ours>" } translates the partner's status vocabulary into the platform's, so a partner renaming a code is a spec edit and not a code change.

capability_routes { }

capability_routes { "<capability>" { adapter, for_tenants, default } } picks which adapter serves a capability, optionally per tenant, with one default = true as the fallback. It is the reason an adapter can be swapped for one tenant without touching the service that calls the capability.

quotas (platform-scope)

Per-module resource ceilings, declared inside platform { quotas { ... } }. Each module <ModuleName> { ... } row — the module is an identifier, not a quoted string — takes max_concurrent_requests, storage_budget_gb, and egress_gb_per_day, all integers. Same module <Name> { } shape as the sibling blocks retention and alerts.

alerts (platform-scope)

Per-module alert routing: module <ModuleName> { sev0_route, sev1_route, sev2_route, escalation_minutes }. The three routes are strings naming where each level goes; escalation_minutes is how long before it escalates.

cicd (platform-scope, monolith root)

Platform delivery pipeline: provider names the CI system, deploy_order is an array of module identifiers giving the order services roll out in, and manual_approval_envs is an array of the environments that require a human before promotion.

A monolith declares this same block at the top level of its one spec, next to service; its deploy_order names its own module. A service that belongs to a microservices platform does not declare one; the platform's is the pipeline, and a service spec that has one is refused. A declared compliance framework whose controls require change management (SOC2 CC8.1, PCI-DSS 6.4) is refused until the platform declares it.

command

A named state-changing operation on an entity: command "<name>" { ... } at file top level. Where a flow describes steps, a command describes a TRANSITION — which entity, from which states, to which one — and DevMatrix generates the route, the guard and the state write together rather than leaving them to agree by hand.

state_from is the attribute worth getting right: omitting it does not mean from anywhere, it means the transition is declared without the one fact that makes it refusable.

entity / verb

What it acts on and what it is called.

entity = <Entity>
verb = "..."
state_field

The entity attribute holding the state.

state_field = "..."
state_from

The states the command may be issued from. An array, because most real transitions are legal from more than one, and listing them is what lets the compiler refuse the rest.

state_from = [...]
state_to

The state it leaves the entity in.

state_to = "..."
endpoint_path / http_method

The route it is served on.

endpoint_path = "..."
precondition

Conditions checked before the transition. Same block the flow `validate` step uses, so a guard is written once and means the same thing in both places.

precondition { }
http_method

The verb the generated route answers on. A command is exposed as one endpoint; this decides which.

DELETEGETPATCHPOSTPUT

Legal from two states, and from no others. Top-level block, not nested in the entity.

Cancelling an order
command "CancelOrder" {
  entity        = Order
  verb          = "cancel"
  state_field   = "status"
  state_from    = ["pending", "confirmed"]
  state_to      = "cancelled"
  endpoint_path = "/orders/{id}/cancel"
  http_method   = POST
}

file_operation (inside flow)

The file side of a flow: flow "..." { file_operation { ... } }. type picks one of four operation kinds and decides which of the other attributes apply — the block is one production, not four, so the grammar accepts attributes that a given kind ignores.

  • generate — a document rendered at request time is not built yet: a file_operation with type = generate is refused at validation and compilation (FLOW-FILE-GENERATE-NOT-PRODUCED); remove the block. template_entity, template_name, template_engine, content_type and filename_pattern belong to it.
  • export — entity rows out to a file. export_entity (identifier) is the source, export_fields an array selecting the columns, and export_format one of csv, json, xlsx, xml, pdf. An export writes only what reading its entity returns to the caller. With no export_fields it writes every field some caller may read: a field marked @sensitive only for the roles its readable_by names, and for no one when it names none; the sign-in state (failed attempts, lockout, last sign-in) for no one unless the entity declares who reads it. A column some roles alone read is left out of the file, header and cells, for a caller holding none of them. A declared column that names no field of the entity (FLOW-EXPORT-FIELD-UNDECLARED), that no caller may read (FLOW-EXPORT-FIELD-NOT-READABLE), that is declared twice (FLOW-EXPORT-FIELD-DUPLICATE), or that some roles alone read on a route with auth_required = false (FLOW-EXPORT-FIELD-ROLES-ON-PUBLIC-ROUTE) is refused at validation and compilation; so is an export with no export_fields of an entity none of whose fields its callers may read (FLOW-EXPORT-NO-READABLE-COLUMN), an export of an entity the module does not declare (FLOW-EXPORT-ENTITY-UNDECLARED), and one of an entity without exactly one @pk field (FLOW-EXPORT-ENTITY-KEY-NOT-SINGLE). The rows of the file are declared once: in the export step (its filter and lookup key), else in the query step that feeds it; with none, every row the caller may read. Two declarations that differ (FLOW-EXPORT-ROWS-DECLARED-TWICE), a query step that neither feeds the file nor is read by a later step (FLOW-EXPORT-QUERY-NOT-READ), a filter on a field the entity does not declare (FLOW-EXPORT-FILTER-FIELD-UNDECLARED) or with a literal of another type (FLOW-EXPORT-FILTER-VALUE-TYPE) are refused. The rows are written in primary-key order, at most max_rows of them (max_rows = N; undeclared: 100,000, and an xlsx file at most 1,048,575). More rows than that answer 422 EXPORT_TOO_LARGE and no file; an xlsx text longer than a cell (32,767 characters) answers 422 EXPORT_CELL_TOO_LONG, and a number past 15 significant digits is written as text, its value exact. A max_rows of zero (FLOW-EXPORT-MAX-ROWS-NOT-POSITIVE) or above the rows its format holds (FLOW-EXPORT-MAX-ROWS-ABOVE-FORMAT) is refused at validation and compilation.
  • download — stream a stored file. storage_backend is local (also the default); s3 and gcs are refused there (FLOW-FILE-STORAGE-BACKEND-NOT-PRODUCED). storage_field names the entity attribute holding the object key.
  • upload — accept a file from the client and keep it in the service's object storage. allowed_types restricts what is accepted, max_file_size caps it in bytes, upload_destination names the bucket (file_storage) or document type (object_storage) the file goes to, and storage_field names the column that receives the stored file's key. Omit storage_backend (or write s3). A delivered service runs on a read-only disk, so an upload in a service with no object storage, or with storage_backend = local, is refused (FLOW-UPLOAD-NEEDS-OBJECT-STORAGE). process_async = true is refused on every kind (FLOW-FILE-PROCESS-ASYNC-NOT-PRODUCED).

export_format and storage_backend are closed sets — a value outside them is rejected when the spec is read, rather than generating something that fails later.

type

Which file operation this declares.

downloadexportgenerateupload
export_format

The serialisation the export produces.

csvjsonpdfxlsxxml
storage_backend

Where the file is read from or written to.

gcslocals3

`export_fields` selects columns; `export_format` is one of the five closed values; `max_rows` bounds the file.

Exporting entity rows
flow "ExportInvoices" {
  type    = workflow
  trigger = http(method="GET", path="/invoices/export")
  entity  = Invoice

  file_operation {
    type          = export
    export_entity = Invoice
    export_fields = ["number", "issued_at", "total"]
    export_format = csv
    max_rows      = 50000
  }

  // A flow needs at least one step: the validator rejects an empty body rather
  // than generating a flow that does nothing, and `file_operation` configures the
  // export without being one.
  step 1 "Export the rows" {
    action        = export
    target        = Invoice
    output_format = csv
  }
}

The service declares `file_storage { bucket "receipts" { } }`: the file is stored there and its key written into the field `storage_field` names. `max_file_size` is an integer in bytes.

Accepting an upload
flow "AttachReceipt" {
  type    = workflow
  trigger = http(method="POST", path="/receipts")
  entity  = Receipt

  file_operation {
    type               = upload
    allowed_types      = ["application/pdf", "image/png"]
    max_file_size      = 10485760
    upload_destination = "receipts"
    storage_field      = "receipt_key"
  }

  // The upload fills receipt_key with the stored file's key: no step maps it.
  step 1 "Record the upload" {
    action = create
    target = Receipt
    mapping {
      uploaded_at = $computed.now
    }
  }
}

conditional_append_only_entities

Entities that become immutable only after they reach a given state — the conditional form of @append_only. Declared at file top level, as a peer of platform { } rather than inside it. Each row is <EntityName> { after_state = "<state>", state_field = "<field>" }: the entity name is an identifier, both values are quoted strings. state_field names the attribute holding the state and after_state the value past which rows stop accepting updates. Where @append_only forbids updates always, this forbids them from a point in the lifecycle onward — an invoice that stays editable while its status is a draft and freezes once it has been issued.

The generated service enforces this: once an entity is past the declared state, an update is refused with the canonical 409 Conflict rather than silently applied. The rule is per-entity — declaring one here does not freeze the others.

Its unconditional sibling @append_only forbids updates outright. Reach for this block when a record is meant to be editable for part of its life and fixed after: @append_only would refuse the early edits too.

Top-level block. Both values are quoted strings; the entity name is not.

An invoice that freezes once issued
conditional_append_only_entities {
  Invoice {
    state_field  = "status"
    after_state  = "issued"
  }
}

environment (inside deploy)

The per-environment sub-block of deploy { }: environment "<name>" { namespace, ingress_host, ingress_tls_secret, cluster_ref }. One of these expands into one deployment environment; deploy itself carries image_registry and default_replicas.

emitter_overrides (platform-scope)

Overrides which plugin handles a dispatch slot when the default resolution order does not pick the one you want. Each "<label>" { ... } row is keyed by an authorial label so diffs and docs can reference it — the label itself is not consumed by resolution — and declares the slot (language, emitter_id, optional tech_kind) together with the plugin_id and plugin_version that must serve it.

plugin_policy (platform-scope)

Platform-wide plugin allow/deny: allowed_third_party_plugins and denied, both arrays.

interactions (cross-service registry · WAVE 0)

Platform-scope cross-service interaction registry, declared inside platform { interactions { ... } }. Each "<id>" { ... } row declares a producer → consumer edge with its tier, trigger, and task/queue. Registry-centric (WAVE 0) enriches a producer edge with these declared attributes:

event_schema

A versioned reference into the platform `event_schemas { }` registry. Resolution is *lenient*: a bare `Name` resolves when the registry holds a single version of it; the `@version` suffix is required only when two or more versions of that `Name` are declared.

event_schema = "Name@version"
ordering_key

Advisory per-key ordering hint.

ordering_key = "..."
payload_map

Envelope projection. Each `<source>` is a closed discriminator in three kinds: a *literal* (string/number/bool), `$instance.<field>` (the triggering entity), or `$context.<field>` (request/tenant context). `$computed` and `$result` are not valid inside a `payload_map`, and `$input` is not yet supported here.

payload_map { <field> = <source> }
delivery

The delivery + reliability policy (`transport`, `outbox`, `retry { max_attempts backoff initial_delay_ms max_delay_ms }`, `dlq { stream_name max_attempts_before_dlq dlq_archive_strategy archive_retention_days }`). Not supported yet: refused at validation until connected; the Workshop keeps it as written, and a `dlq { }` without `stream_name` is rejected first (`INV-XSVC-W0-1`).

delivery { ... }
transport

How this interaction is delivered. A different set from the event-bus `transport` — an interaction can be answered synchronously, an event cannot.

celerykafkarabbitmqredis_streamssqs

Row i-11: a producer → consumer edge with a versioned event schema and a payload projection from the triggering instance.

Enriched async interaction (registry-centric)
platform "MyPlatform" {
  modules {
    OrderService        { spec = "order.dmx";        dependencies = [] }
    NotificationService { spec = "notification.dmx"; dependencies = [OrderService] }
  }

  event_schemas {
    event "order.confirmed" version "v2" {
      payload {
        order_id    UUID
        customer_id UUID
        tenant_id   UUID
      }
    }
  }

  interactions {
    "i-11-order-confirmed-notifies" {
      tier         = 1
      producer     = OrderService
      consumer     = NotificationService
      trigger      = event("order.confirmed")
      task         = "send_confirmation"
      queue        = "notificationservice"
      trigger_operation = "confirm_order"
      event_schema = "order.confirmed@v2"
      ordering_key = "tenant_id"

      payload_map {
        order_id    = $instance.id
        customer_id = $instance.customer_id
        tenant_id   = $context.tenant_id
      }
    }
  }
}

The rest of the row's attributes

Every field comes from the registry rows you declare; nothing is guessed from names. The shapes above are what validation accepts; what each one generates is described in its own section.

The rest of the row's attributes. A row is one production, so these sit beside the ones above rather than in a variant of their own:

  • trigger_state = "..." and trigger = state_change(Entity.field -> VALUE) — not supported yet: accepted by the grammar and refused at validation and compilation (INTERACTION-STATE-TRIGGER-PRODUCER-MISSING): no transactional, durable producer dispatches the exact state transition. Keep the declaration blocked until that producer exists. Use trigger_operation = "<operation_id>" only when operation completion is the intended contract; it is not equivalent to a state transition.
consumers

The plural of `consumer`, an array of identifiers, for one producer fanning out to several services. Use one or the other, not both.

consumers = [A, B]
trigger_operation

Narrows *when* the edge fires: the operation that fires it. It refines `trigger`, it does not replace it.

trigger_operation = "..."
direction / channel_kind

Identifiers describing which way the edge runs and what kind of channel carries it. These are open identifiers, not closed sets.

response_schema

For edges that answer, the schema of what comes back.

response_schema = <Ident>
event_schema_version

The version alone, for rows that name the schema elsewhere. `event_schema = "Name@version"` carries both in one string; this is the separate form.

event_schema_version = "..."
timeout_ms

How long the caller waits, in milliseconds. Its sibling `retry` is a plain integer count.

timeout_ms = <int>
authority_refs

The authority rule codes this cross-service contract cites.

authority_refs = [...]

events

Domain event definitions for event-driven communication between services. Each entry is "<event.name>" { ... }. Attributes (grammar rule event_attr): entity (the entity the event concerns) and actor_type (the acting principal — user, service, system, scheduler or integration, where integration means an OUTSIDE party acted through an inbound integration and service means another service of this platform did) classify it; transport names the carrier (redis_streams / kafka / sqs / in_memory) and stream names the event's stream; an event that declares transport = redis_streams, transport = sqs or a consumer_group is refused (INV-EVENT-TRANSPORT-UNBUILT, a limit of the compiler): the compiled service sends events to neither, so remove them and the event is still delivered to the service's own flows; dlq (bool) enables a dead-letter queue and dual_channel (bool) mirrors the event over a second channel; idempotency_key names the field used to de-duplicate deliveries and correlation_fields lists the fields carried for correlation. trigger_entity + trigger_action bind the event to every committed write of one kind (create, update or delete) of a trigger_entity row, and each payload field is read from a column of that row; publisher_function_name overrides the generated publisher name; event_version pins the schema version; description documents it; internal_mirror_path sets the in-app mirror route. A nested payload { <name> <type> ... } block declares typed payload fields, including @nullable. interactions{} retains its cross-service producer/consumer contract. Event publication on the Kafka plane by trigger, partition_key or payload_map is not supported yet: refused at validation until connected (INTEGRATION-CONSUMER-MISSING).

An entity-write event may read a payload value through declared foreign keys: payload_map { site_id = $instance.survey_id.site_id }. Every traversed field declares one @fk(Target.field), and the target entity and field must exist. Invalid paths are refused by /validate and compilation under INV-EVENT-PUBLICATION-UNLOWERABLE, naming the event, payload key and broken declaration. The service reads a valid path in the publishing transaction, with the publishing row's tenant; a UUID value alone never establishes a relationship or subscription authority.

actor_type

Who or what the event records as having caused it.

integrationschedulerservicesystemuser
transport

How the event is carried between services. `redis_streams` and `sqs` are refused today: nothing sends events there.

in_memorykafkaredis_streamssqs

tenant_config

Multi-tenancy configuration: isolation strategy, tenant resolution, and feature flags per tier.

Per-setting attributes. Each named setting inside the block declares what a tenant may change and how far:

data_type

The setting's type, and `enum_values = [...]` the closed list when it is one.

data_type = "..."
default

The value a tenant gets without choosing.

platform_minimum / platform_maximum

The bounds the PLATFORM imposes, which a tenant cannot widen. They are the difference between a setting a tenant tunes and one a tenant can use to take resources from everyone else.

elevation_direction

Which way counts as *more* privilege for this setting, so the platform knows whether a tenant raising it or reducing it is the request that needs approval. Without it, a numeric bound cannot tell a stricter setting from a looser one.

elevation_direction = "..."

workers (platform-scope)

Platform-scope worker topology: tiers, queue routing patterns, retry + dead-letter policies, concurrency, scaling hints. Declared inside platform { workers {... } }. Superseded the per-service task_queue block. Optional tasks { "<task_id>" { consumes_from = [...]; produces_to = [...] } } sub-block declares which entities a task reads and writes.

Block-level attributes. broker_url_env_var and result_backend_env_var name the ENV VARS the workers read their broker and result backend from — the spec carries the variable name, never the URL, so a connection string never lands in a spec. worker_framework picks the runtime that executes the tiers.

Per-tier attributes (tier "<name>" { ... }) — a tier is a pool with its own queues and its own scaling, and the four below are what make it one:

min_replicas / max_replicas

The floor and ceiling of the pool. The floor is the interesting one: at `0` the tier scales to nothing and the first job after an idle period pays the cold start.

scale_trigger / scale_threshold

What the autoscaler watches and the value that moves it. Declaring the ceiling without the trigger gives a pool that is allowed to grow and has nothing telling it to.

scale_trigger = "..."
concurrency / queue_routing_patterns

Decide how much one replica takes at once and which queues this tier drains — the routing patterns are what keep a slow tier from eating the queue a fast tier was sized for.

row_level_isolation

Row-level security policies for data isolation.

strategy

`rls_session_variable`, `rls_role_based` or `application_only`. The first two put the isolation in the DATABASE; the third leaves it in application code, which means every future query is a chance to forget it. The grammar accepts any identifier here; the closed set is enforced by the validator, so a typo surfaces at validation rather than at parse.

strategy = ...
session_variable_name

The Postgres session variable the policies read the current tenant from. It is the one name the generated `SET LOCAL` and `USING` clause must agree on.

session_variable_name = "..."
force_rls_on_owner

Applies the policies to the table's OWNER too. Without it, Postgres exempts the owner, and the account the migrations run as is typically the owner: RLS looks configured and the one role most likely to run an ad-hoc query bypasses it.

force_rls_on_owner = true
exempt_superuser

Whether `BYPASSRLS` roles are exempted. This is not a convenience toggle: it decides whether tenant isolation is a property of the DATA or a property of who is asking.

exempt_superuser = ...

sequences

Ordered sequence generators (e.g., invoice numbers). Each entry is a named generator whose attributes decide how the value is built and when the counter goes back to the beginning:

format_template

The shape of the generated value, into which the counter is rendered.

format_template = "..."
start_value

Where the counter begins.

start_value = <int>
prefix_field

An entity attribute whose value is used as a prefix, so one generator can produce independently numbered series.

prefix_field = "..."
reset_policy

When the counter restarts (never, or on a calendar boundary).

dailymonthlyneveryearly
tenant_scoped

Whether each tenant gets its own counter. Leaving it off means one shared series across tenants, which is visible to them: consecutive numbers tell one tenant how much business the others did in between.

tenant_scoped = <bool>
backend

Where the monotonic counter lives. The two differ in what they guarantee under concurrency and what they cost.

postgres_sequenceredis_incr

observability

Canonical observability surface — metrics, structured logging, OTEL tracing, correlation, and health probes in one block. Carries the union of the legacy service_observability + infrastructure.observability surfaces plus tracing_enabled / tracing_exporter / log_level_env_var.

THREE BLOCKS ARE SPELLED observability AND THEY ARE NOT THE SAME BLOCK. Which attributes are legal depends on where you opened it, and a .dmx that mixes them gets a parse error naming an attribute that is perfectly valid one scope over:

  • the canonical one, described above — the one to write in new specs.
  • inside infrastructure { } — the older, smaller surface: metrics, tracing and logging are booleans that switch each subsystem on, while log_level and log_format are strings, and health_endpoint / metrics_endpoint / tracing_endpoint are the paths each is served on.
  • inside platform { } — platform-wide, and none of its attributes are booleans: logs, metrics and traces are strings naming the backend each signal goes to, with dashboards_tool and alerting_tool beside them. Each alert_receiver "<name>" { kind = "<kind>" severities = [...] } names who an alert severity is sent to: kind is pagerduty, slack, email or webhook, and every severity the alert rules carry (critical, warning) is received by exactly one receiver. Its secrets are environment variables the operator sets, never values in the spec. A receiver declared without an alerting_tool is refused, and so is a service that sets metrics_enabled = false on a platform that declares metrics. Three more govern behaviour rather than destination: pii_attrs = [...] lists attributes to keep out of logs, log_sample_rate is a float between 0 and 1, and log_sample_floor_level names the least important level that sampling may still drop — it is the floor sampling never goes under, not the level it samples at.

metrics is the sharpest of the collisions: a boolean in infrastructure, a string at platform scope.

A monolith's platform tools. A monolith's platform is its one spec, so its canonical block also takes the platform's monitoring tools, spelled as inside platform { }: metrics = "prometheus" (the metrics tool, a string), alerting_tool, dashboards_tool and its alert_receivers. metrics = "..." (the tool) and metrics { ... } (the metric definitions) are different attributes and may sit in the same block. A service that belongs to a microservices platform does not declare the tools: the platform's are the ones the build reads, and a service spec that has them is refused.

The canonical block's own attributes. metrics_enabled, structured_logging and tracing_enabled switch each subsystem on; metrics_path, health_liveness_path and health_readiness_path are the routes they are served on. Liveness and readiness are two questions, not one — liveness asks whether the process should be restarted, readiness whether it should receive traffic — and pointing both at the same route makes a service that is merely warming up look dead.

correlation_id_header names the header a request's correlation id travels in, and propagate_correlation = <bool> decides whether outbound calls carry it onward. Without the second one the id stops at the first hop, which is where a trace across services stops being a trace. log_level_env_var and tracing_exporter name the environment variable holding the level and the exporter to send spans to.

Two sub-blocks refine it. metrics { <name> { ... } } declares individual metrics; inside a request metric, label_sources { <label> = <source> } binds every declared label exactly once to a validated source — method, route_template or status_code; a raw request URL is not a source. Default label names carry their standard bindings, so the block is only required for custom names. An unbound custom label, a duplicate binding, an unknown source or conflicting request metric types block validation with OBS-REQUEST-METRIC-CONTRACT. health_probes { <name> { probe_type, timeout_seconds } } declares checks beyond the two paths above — a dependency the service needs before it can honestly report itself ready. Each carries its own timeout, because a probe without one turns a slow dependency into a hung probe, and a hung probe reads as healthy for exactly as long as nothing times it out.

event_bus (platform-scope, monolith root)

Platform-wide event streaming, declared inside platform { event_bus { ... } }. A monolith declares this same block at the top level of its one spec, next to service; a service that belongs to a microservices platform does not declare one, and a service spec that has one is refused. transport picks the carrier — redis_streams, kafka, sqs or in_memory — and stream_prefix namespaces every stream the platform creates. transport = sqs is refused today (INV-EVENT-TRANSPORT-UNBUILT): nothing sends events there.

The rest is consumer and delivery behaviour: consumer_batch_size is how many messages a consumer takes at once and consumer_block_ms how long it waits when there are none. dead_letter_enabled turns on the dead-letter path and dead_letter_max_retries is how many redeliveries follow the first delivery. dead_letter_backoff_seconds is the first wait before a redelivery, doubled each time, and dead_letter_backoff_max_seconds the longest wait. An event a service records on its own entity writes and handles itself is one outbox job per handler, attempted dead_letter_max_retries + 1 times and then kept dead for the operator; such a service is refused until the three values are declared, the first wait at least 1 second and the longest not shorter than it. idempotency_ttl_seconds is how long a processed message id is remembered — it is what makes redelivery safe, so it should outlast the retry window rather than merely exist.

in_memory is a real transport and behaves like one, but nothing survives a restart; it belongs in a single-process environment, not in one where a dropped event is a lost record.

allowed_transports is the platform's narrowing, and it is a different thing from transport: transport is the carrier this block uses, while allowed_transports is the list of carriers anything in the platform may use. One declared policy governs BOTH surfaces — the event bus here and every cross-service delivery transport (whose delivery { } block is refused at validation today) — which is why its vocabulary is the union of the two: redis_streams, kafka and sqs are legal on either side; celery and rabbitmq are cross-service only; in_memory is event-bus only. Omitting the block permits the full taxonomy, so declaring it is how a platform says these and no others — a Celery-only platform is allowed_transports = [celery], and a platform that forbids Celery just leaves it out. Listing in_memory additionally requires allow_in_memory = true in the same block: the non-durable transport has to be asked for twice, never arrived at by default.

transport

Which transport the platform event bus runs on.

in_memorykafkaredis_streamssqs

platform_roles (platform-scope, monolith root)

The platform's role registry, declared inside platform { platform_roles { ... } }. A monolith declares this same block at the top level of its one spec, next to service; a service that belongs to a microservices platform does not declare one, and a service spec that has one is refused. Each entry names a role and the scopes it holds: ADMIN { scopes = ["*"] }. A role declared scopes = ["*"] holds every value of every @scoped field, so it reads every row a scope would otherwise hide.

A registration (a route that requires no sign-in) that creates a user with an @scoped field it leaves unset needs the role it writes declared scopes = ["*"], or the step must set the field. Otherwise the spec is refused, naming the place to declare the role: the root of a monolith's spec, or platform { platform_roles { ... } } of a microservices platform.

scopes

The scopes the role holds. `"*"` is every value.

<ROLE> { scopes = ["*"] }

databases (platform-scope)

Platform database topology: platform { databases { database "<name>" { ... } } }. Each entry is a quoted name plus its configuration, so a platform can declare several.

dialect

Which SQL dialect the generated models, migrations and queries target. `postgresql` or `clickhouse`, a closed set.

clickhousepostgresql
owned_by

Which module owns this database. Ownership is the boundary the compiler enforces: another service reaches this data over its API, never with a query of its own.

owned_by = "<Module>"
host_ref / port_ref

The names of the environment variables holding host and port. References, not values: no address is baked into the generated code.

name / credential_spec

The database name, and the env-var name holding the credential. Same rule — the reference is declared, the secret is not.

backup_credential_spec

The secret of the read-only role that takes backups (`user:password`), distinct from `credential_spec`. Required when `backup_policies` names this database, and an error when no policy does. The owner's migration grants that role PostgreSQL's built-in read-all-data membership and `BYPASSRLS` only, and the backup worker refuses to run with more. Only `env://` is accepted today; a secret-store reference is refused. A monolith declares it in `infrastructure { database { } }`.

backup_credential_spec = "env://<VAR>"
pool_size / max_overflow / pool_timeout_s

Connection pool ceiling, how many extra connections it may open past that, and how long a caller waits before failing.

migration_tool

Which migration runner the schema history is generated for. `alembic` or `liquibase`.

alembicliquibase

service_observability (deprecated alias)

Deprecated alias for observability (same attributes, minus tracing / log_level_env_var). Parses identically; migrate to observability.

object_storage

Platform-scope object storage topology — declares the cloud provider, credentials, and per-bucket configuration. Five providers are supported (closed taxonomy enforced parse-time): s3 / gcs / azure-blob / minio / cloudflare-r2. Each bucket carries name, region, owning_service, access_pattern (read/write/admin/shared), encryption_kind (SSE-S3/SSE-KMS/SSE-C), optional encryption_secret_ref (required for SSE-KMS+SSE-C), presigned_url_ttl_s, and lifecycle_rule blocks (transition/expiration with after_days). Cloudflare R2 with SSE-KMS is refused at validation (R2 has no KMS integration).

provider

Which object-storage service the generated client talks to.

azure-blobcloudflare-r2gcsminios3
backend

Where service-owned files are kept. Distinct from the sequence `backend`, which names a counter store.

azure_blobgcsminios3
access_pattern

What the bucket is reachable for, and by whom. Omitting it means `admin` — the owning service is the only consumer; `shared` is the one that opens it to others.

admindefaultreadsharedwrite
encryption_kind

How objects are encrypted at rest, and who holds the key. `SSE-KMS` is rejected without a paired `encryption_secret_ref`.

SSE-CSSE-KMSSSE-S3

Block-level attributes

Block-level attributes, which apply to everything the block declares:

bucket_name_env_var / endpoint_url_env_var

The ENV VARS carrying the bucket and endpoint. Naming the variable rather than the value is what lets one spec compile for staging and production without a diff.

path_prefix_template

The key prefix every object is written under. It is what keeps one tenant's objects from sharing a key space with another's, so a listing operation cannot enumerate across tenants.

path_prefix_template = "..."
enable_server_side_encryption

Encryption at rest, applied by the provider. Per-bucket `encryption_kind` chooses WHICH scheme; this decides whether there is one at all.

enable_server_side_encryption = true

document_type { }

document_type <Name> { ... } classifies what may be stored, and the rules travel with the class rather than with each upload site:

allowed_content_types / max_file_size_mb

What the platform accepts. Declared here they are enforced for every route that writes this document type, which is the point: a limit that lives on one endpoint stops applying the moment a second endpoint writes the same bucket.

allowed_content_types = [...]
write_once

The object cannot be replaced after it is written. This is the storage-side counterpart of `@append_only`, and it is what makes a stored document usable as evidence: a record that can be silently overwritten proves nothing about what it said yesterday.

write_once = true
presigned_url_ttl_seconds

How long a handed-out download link stays valid. It is the entire access control on that link: once issued, nothing revokes it before the TTL expires, so the number is a decision about blast radius, not a convenience.

publish_event_on_upload / event_name

Publishes a domain event when an object of this type lands, so downstream work triggers off the upload instead of polling the bucket for it.

publish_event_on_upload = true
retention_days

How long objects of this type are kept before the lifecycle rules act on them.

permissions

Role-based and attribute-based access control definitions. The sod_rules { ... } sub-block declares Separation-of-Duties rules; each named rule lists conflicting_permissions = [...] (the permission set that must not be co-held), an optional scope, description, and an enforcement mode. scope is a closed taxonomy too: same_user (the DEFAULT — one user holding both sides is the conflict), same_session and same_transaction. It is NOT the same vocabulary as the identically spelled scope of a feature_flags { flag ... } block (platform | tenant | user) — the two sets are disjoint, and a value legal in one is rejected in the other. enforcement is a closed taxonomy: block (the DEFAULT — omit and the rule behaves as block — records the conflict at read time and denies with 403, the fail-closed floor), warn and log_only (both record the conflict forensically and then ALLOW the request). Grant-time is always block structurally (not tunable); the enforcement mode only relaxes read-time behavior.

breakglass { }

breakglass { ... } declares an emergency access window: a role named in requested_by, holding request_permission, asks for it with a reason; when approver_permission is declared, a different principal holding it in a role named in approved_by approves or rejects it; and while the window is open the requester holds grants on top of their own permissions, until it expires. Without it, an operator with an emergency and no legitimate path finds one anyway, usually a shared account nobody can attribute.

An enabled block is compiled into a typed plan and a compiler-owned activation record, and the service serves its routes under the API prefix: POST /breakglass/activations (asks request_permission; 409 while the caller already has a window waiting or open), POST /breakglass/activations/{activation_id}/approve and .../reject (ask approver_permission; a principal cannot decide their own request), and GET /breakglass/activations (asks approver_permission; the tenant's activations, newest first). Without approver_permission only the request route exists and the request opens the window. A request nobody answers within max_duration_hours lapses.

Every transition is written to the audit trail, so the module must keep one (audit { enabled = true }). grants never lists the requesting or approving key, and a window never lifts a Separation-of-Duties rule: breakglass_eligible = true on an SoD rule is refused at validation. The refusals are INV-PM-012 to INV-PM-023, reported both when the spec is validated and when it compiles.

enabled

Whether the window exists at all. A block that is not enabled and still declares its policy attributes is refused: it would declare a control that does not apply.

grants

The permissions an open window adds to what the requester holds. Each must be a declared permission, and the list may not be empty or include the requesting or approving key.

grants = ["...", ...]
request_permission

The declared permission the request route asks for. It is held only by the roles `requested_by` names.

request_permission = "..."
requested_by

The roles that may ask for a window. Each must be a role `security { roles }` declares, listed once, and at least one.

requested_by = [ROLE, ...]
approver_permission

Optional. The permission the approve, reject and list routes ask for. Declaring it is what keeps the window from being self-service: a request then waits for a decision by someone else.

approver_permission = "..."
approved_by

The roles that decide. Declared exactly when `approver_permission` is, with the same rules as `requested_by`; these roles hold the approver key and no other role does.

approved_by = [ROLE, ...]
max_duration_hours

How long a window lasts once open, and how long a request may wait for a decision. A positive number of hours: the window expires on its own, which is what makes it an emergency path rather than a second role.

requires_reason

The requester must state why. The reason is what the audit record is for; without it the trail says someone asked and cannot say whether they should have.

requires_reason = true
audit_event_name

The name the window's transitions are recorded under in the audit trail, so they land in the stream that is already monitored.

audit_event_name = "..."

Attributes of permissions { }

Two attributes sit directly in permissions { }, outside every sub-block:

default_deny

What happens to a request no rule mentions. This is the single most consequential line in the block: with it false, every permission you forget to declare is granted, and the spec cannot tell you which ones those are.

default_deny = <bool>
cache_ttl_seconds

How long a resolved permission decision is cached. It is the lag between revoking access and access actually stopping. ⚠️ The same attribute name also exists in the platform-scope `feature_flags { }` block, where it caches flag evaluations instead — same spelling, two blocks, two different things being cached.

cache_ttl_seconds = <int>

permission { }

permission "<name>" { } declares one permission. Besides description:

requires_step_up

Holding the permission is not enough; the caller must re-authenticate to use it. This is what separates a permission a session carries from one a person has to prove again at the moment of use.

requires_step_up = <bool>
step_up_window_minutes

How long that fresh proof counts for. Declaring the step-up without the window is the common mistake: re-authentication with no expiry converts back into an ordinary permission on the second call.

step_up_window_minutes = <int>

abac_constraints { }

abac_constraints { <name> { ... } } is the attribute-based half — a permission answers may this role do this?, a constraint answers on WHICH rows?

Constraints narrow what an already-granted permission reaches; they never grant. A constraint on a permission nobody holds changes nothing, and a permission with no constraint reaches every row.

Each named constraint takes:

constraint_type

The kind of comparison, written as a bare identifier, not a string.

constraint_type = <ident>
attribute_name

The attribute it reads.

attribute_name = "..."
description

What the constraint means, which is the part that survives the person who wrote it.

description = "..."

feature_flags (platform-scope)

Runtime toggles, declared inside platform { feature_flags { ... } }. The point of declaring them in the spec rather than in a config file is that the generated services read them through one resolver instead of each inventing its own.

Three attributes govern the whole block:

storage_backend

Where flag state lives, as a bare identifier.

storage_backend = <ident>
cache_ttl_seconds

How long an evaluated flag is cached before it is read again. This is how long it takes for a flip to change how the platform behaves, differently, so it is the number to look at when a flip appears not to have worked. ⚠️ The `permissions { }` block has an attribute of the same name that caches permission decisions — two blocks, one spelling, unrelated caches.

cache_ttl_seconds = <int>
admin_endpoint_enabled

Whether the platform exposes a route to read and change flags at runtime. Off means flags change by deploy; on means they change by request, and that route governs behaviour without going through review.

admin_endpoint_enabled = <bool>

flag { }

Each flag <name> { ... } then declares:

flag_type

What kind of value it holds, as a bare identifier.

flag_type = <ident>
default_value

The value used when nothing has been set, written as a string whatever the type. It is what every service sees on first boot and after a backend outage, which makes it the flag's real behaviour rather than its fallback.

default_value = "..."
scope

How widely a flag's value applies — everyone, one tenant, or one principal.

platformtenantuser
scope = <ident>
description

What the flag controls. A flag whose meaning is lost cannot be removed, because nobody can prove what turning it off would do.

description = "..."

sagas

Not offered yet. A saga step cannot yet be bound to a flow the service declares, so every saga is refused by validation and by the compile (SAGA_STEP_HANDLER_NOT_EMITTED, a limit of the compiler): remove the sagas block to compile this application. Nothing below is generated today; it documents the shape the language accepts.

Distributed transaction orchestration with compensating actions. Each saga declares a sequence of step definitions; on failure of any step, prior completed steps run their compensation action in reverse order. Two patterns supported: orchestration (default — central coordinator drives steps) and choreography (event-driven — each step subscribes to the previous step's completion event). Persistence: outbox (default — DB-backed state machine + transactional outbox table for event publishing in the same TX as business state) or in_memory_only (opt-in for non-critical sagas where crash recovery is not required). Brokers: none (in-process — orchestration only), redis (redis-streams), kafka (aiokafka). Choreography requires a non-none broker. Per-step action_handler and compensation_handler are fully-qualified Python references (e.g. src.services.payment.charge); when omitted the compiler defaults to src.services.sagas.<saga_name>.<action>. idempotency_key_field is the request-payload field used as the unique key for retry / replay safety. max_retries per step overrides the saga-level default. DLQ topic + retention (integer + days|hours unit) configure the dead-letter queue for failed events that exceed retries.

The keywords for the three settings described above, because the concept being explained is not the word an author types: the persistence choice is written persistence_strategy = ..., the dead-letter retention unit is dlq_retention_kind = ... (paired with the integer dlq_retention), and the broker credential is broker_url_secret_ref = "..." — a REFERENCE to the secret, never the URL itself, which is why a saga definition is safe to read in a spec review.

broker

Which message broker carries the saga's steps and compensations.

kafkanoneredis
persistence_strategy

How saga state survives a restart mid-transaction.

in_memory_onlyoutbox
dlq_retention_kind

The unit the dead-letter retention window is measured in. Pairs with the integer beside it.

dayshours

reference_data

The rows a platform ships with: a currency catalog, a country list, the reasons a ticket can be closed with. One block per @platform_scope entity, one row { ... } per row, literals only (strings, numbers, true, false, null). Each row is inserted by the migration that creates its table, once: ON CONFLICT on the row's natural key does nothing when the row is already there, and that migration's downgrade removes exactly the declared rows. The row's id is derived from its natural key, so reordering rows never changes it. Absent, the platform ships with no rows.

Refused with REFERENCE-DATA-REFUSED, in the Workshop and by the compiler alike: an entity that is not @platform_scope; an entity without a single UUID primary key and exactly one unique key (one @unique field or one @unique_together group); a row that leaves a NOT NULL column without default unset, or sets the primary key, a foreign key, a server-generated or a secret field; a value outside its field's type, length, @pattern, @min or @max; a row that breaks a @check or a validations {} rule of its entity (the message names the row and the rule); two rows with the same natural key or the same value of a field a declared uniqueness rule names; an entity named in two blocks.

Refused with REFERENCE-ROW-PRODUCER-MISSING: a declared rule no constant row can be judged against (a relationship, transition, workflow or stock rule, or one that reads the clock or the caller). No row is inserted unjudged.

row

One row of the entity's table. Sets every column the database cannot fill, and only columns of the entity.

row { <field> = <literal> ... }

protocol_handlers (non-REST transport fleet)

Platform-scope registry of non-REST transport handlers, declared inside platform { protocol_handlers { ... } }. Each handler "<name>" { ... } row declares one transport listener with seven attributes:

transport_kind

The wire transport (e.g. ``tcp``, ``udp``, ``mllp``, ``serial``).

transport_kind = "..."
transport_config

A bare nested block (no ``=``) of transport-specific settings as ``IDENT = "string"`` pairs (e.g. ``host`` / ``port``).

transport_config { <key> = "..." }
framing_strategy

How messages are delimited on the wire (e.g. ``length_prefixed``, ``delimiter``, ``fixed_length``).

framing_strategy = "..."
wire_format_parser_ref

The named parser that decodes each frame into a domain payload.

wire_format_parser_ref = "..."
owner_service_or_agent

The service or edge agent that owns (deploys + runs) the handler.

owner_service_or_agent = "..."
delivery_semantics

The reliability contract (e.g. ``at_least_once``, ``at_most_once``, ``exactly_once``).

delivery_semantics = "..."
idempotency_key_source

Where the dedup key is read from (e.g. ``header:X-Message-Id``, ``body:message_id``).

idempotency_key_source = "..."

A length-prefixed TCP listener owned by the ingest service, decoding frames via a named binary parser with at-least-once delivery keyed off a message-id header.

TCP telemetry stream handler
platform "MyPlatform" {
  modules {
    ingest { spec = "ingest.dmx"; dependencies = [] }
  }

  protocol_handlers {
    handler "telemetry-stream" {
      transport_kind         = "tcp"
      transport_config {
        host = "0.0.0.0"
        port = "9000"
      }
      framing_strategy       = "length_prefixed"
      wire_format_parser_ref = "binary_frame_parser"
      owner_service_or_agent = "ingest"
      delivery_semantics     = "at_least_once"
      idempotency_key_source = "header:X-Message-Id"
    }
  }
}

Kind-valued fields

The kind-valued fields (transport_kind / framing_strategy / delivery_semantics) are opaque: the compiler never branches on their values — the plugins block resolves the concrete handler — so the values above are examples, not a closed taxonomy.

Flow Actions

Actions available in flow steps. Each action maps to a specific operation on the target entity or system.

create

Create a new entity instance

action = create
update

Update an existing entity

action = update
delete

Delete an entity instance

action = delete
query

Query entities with filters

action = query
validate

Run validation rules

action = validate
extract

Extract fields from data

action = extract
calculate

Compute derived values. With a mapping { }, shape the fields of the route's inline response { }

action = calculate
state_change

A step that updates a status field (target + mapping, which must include the status field). Not the state_change() trigger

action = state_change
external_call

Call another service of the platform (refused at validation today)

action = external_call
batch

Batch multiple operations

action = batch
export

Export data to a format

action = export
infra

Infrastructure step

action = infra
foreach

Fan out a do{} body per item of a source collection (per-item loop)

action = foreach
upsert

Insert the entity, or update it when it already exists

action = upsert
search

Query a declared Elasticsearch projection through a search block (refused at validation today)

action = search
analytics

Query a declared ClickHouse table through an analytics block (refused at validation today)

action = analytics
api_call

Call an operation of a declared integration through a call block: async through the outbox after the commit, or sync after the flow's reads and checks, before its writes

action = api_call
issue_secret

Issue a single-use secret through a secret block: its hash on the row, the raw value only in a later call body

action = issue_secret

Preconditions (Guards)

Structured, kind-discriminated guards. The taxonomy is closed (20 productive + 2 markers), but executability is placement-specific: a kind accepted on one carrier is not automatically valid on commands, flow-level guards and validate STEPs. Workshop and the compiler reject an unsupported placement instead of silently reducing it to another guard. Every entity, field and integration reference is spec-declared; no domain vocabulary is inferred. Commands currently execute `field_value_compare` only. Validate STEPs execute `permission_required`, `related_rows_in_state`, `no_overlapping_interval` and `integration_signature_valid`. Each of them answers with its author's message: error_message on the guard, or error on the step; the compiler refuses a guard with neither. The three B162 guards are STEP-only. Flow-level guards retain their own productive roster and reject STEP-only kinds. A missing HMAC secret, mismatched parallel match arrays, missing required field or unsupported placement fails closed and loud.

field_value_compare (default)

Compare a field to a value. operator ∈ eq, not_eq, in, not_in, gt, gte, lt, lte, is_null, is_not_null. Carries error_message / error_code.

field, operator, value
role_required_single

The principal holds the single role.

role = "admin"
role_required_any_of

The principal holds ANY of roles (≥ 2).

roles = ["admin", "manager"]
permission_required

The principal holds a named permission.

permission_name = "invoice:write"
not_expired

A timestamp field is still in the future (not expired).

expiry_field = "expires_at"
workspace_present

A workspace/tenant id is present on the request.

workspace_source = jwt | header | jwt_or_header
field_present

An input field is supplied (non-null).

field = "email"
field_unique

The field value is unique across entity rows.

entity = "User", field = "email"
fk_valid

An FK field resolves to a live target_entity row.

field = "user_id", target_entity = "User"
min_list_cardinality

A list/collection field has at least count items.

field = "items", count = 1
no_conflict

No overlapping entity row exists on time_field (time-window conflict).

entity = "Booking", time_field = "slot"
token_valid

A token is valid and unrevoked.

token_source = "refresh_token"
entity_exists

An entity row identified by id_field exists.

entity = "Order", id_field = "order_id"
entity_active

The resolved entity row is active (active_field defaults to is_active).

entity = "User", active_field = "is_active"
relationship_exists

A join-table row links the subject to the object (e.g. reviewer assigned to submission).

subject_entity, via_entity, object_entity, subject_field, object_field
self_access

The acting principal owns the row (owner_field == context user id).

entity = "Profile", owner_field = "user_id"
collection_in_state

Cross-entity collection-state guard over a JSON-array-of-natural-keys (mode = all_in_state | no_referents_in_state). Counted per tenant over the related rows. Carries error_message / error_code.

mode, catalog_entity, list_field, key_field, key_value, scoped_entity, state_field, state_value, scope_field
related_rows_in_state (STEP only)

Checks the latest matching related row, or all matching rows, against an allowed-state set.

row_mode = latest | all, related_entity, match_fields, match_values, state_field, allowed_states, order_field?, require_nonempty?
no_overlapping_interval (STEP only)

Rejects a matching row whose declared interval overlaps the requested interval.

conflict_entity, match_fields, match_values, start_field, start_value, duration_field, duration_value, state_field, excluded_states?
integration_signature_valid (STEP only)

Verifies the exact raw request body using the named integration's HMAC contract; missing secret fails closed. It verifies a webhook receiver, which is refused at validation and compilation (WEBHOOK-RECEIVER-NOT-PRODUCED-001).

integration_ref = "..."
trigger_marker (marker)

Marks a trigger the route itself handles; it adds no guard.

session_scope_marker (marker)

Marks a session concern the sign-in service handles; it adds no guard.

session_scope = single | global | current

Omitting kind preserves the legacy field_value_compare command contract. Other explicit command kinds are rejected unless the command placement roster supports them.

Legacy command comparison guard
command "CloseInvoice" {
  entity = Invoice
  verb   = "close"
  precondition {                       // kind omitted → field_value_compare
    field         = "status"
    operator      = eq
    value         = "open"
    error_message = "Invoice must be open to close"
    error_code    = "INV_409"
  }
}

Parallel match_fields/match_values arrays are positional and must have equal cardinality. latest requires order_field; require_nonempty keeps an empty result fail-closed. Every guard on a validate STEP declares error_message (or its step declares error); a guard with neither halts the compile.

STEP-scoped related-row guard
service "GuardExample" {
  docs { operator_only }
  version = "1.0.0"
  database = "guard_example_db"
}

entity SubjectRow {
  id UUID @pk
  instrument_id UUID
  test_code String
}

entity QualityControl {
  id UUID @pk
  instrument_id UUID
  test_code String
  status String
  created_at DateTime
}

entity Analyst {
  @role(user)

  id            UUID        @pk
  email         String(255) @not_null @unique @format(email)
  password_hash String(255) @not_null @sensitive @field_purpose(password)
  role          Enum(ANALYST) @not_null @default("ANALYST")
  is_active     Boolean     @not_null @default(true)
}

security {
  auth_scheme       = jwt
  password_hashing  = bcrypt
  user_entity       = "Analyst"
  user_lookup_field = "email"
  active_field      = "is_active"
  role_field        = "role"

  roles = [ANALYST]

  rate_limit {
    login_attempts      = 5
    requests_per_minute = 120
    lockout_duration    = "15m"
  }

  policy "subject_validation" {
    entity = SubjectRow
    allow [validate] for [ANALYST]
  }
}

api {
  POST "/auth/login" {
    auth_required = false
    request { email String(255) @required; password String(128) @required @sensitive @field_purpose(password) }
    response { access_token String }
  }

  POST "/subjects/{id}/validate" {
    operation_id = "validate_subject"
    addressing { id = SubjectRow.id }
    response @entity(SubjectRow)
  }
}

flow "Validate subject" {
  trigger = "POST /subjects/{id}/validate"
  entity = SubjectRow
  step 1 "Load subject" {
    action = query
    target = SubjectRow
    query_field = "id"
    query_value = $input.id
  }
  step 2 "Latest QC passed" {
    action = validate
    precondition {
      kind             = related_rows_in_state
      row_mode         = latest
      related_entity   = "QualityControl"
      match_fields     = ["instrument_id", "test_code"]
      match_values     = ["$instance.instrument_id", "$instance.test_code"]
      state_field      = "status"
      allowed_states   = ["PASS"]
      order_field      = "created_at"
      require_nonempty = true
      error_message    = "The latest quality control for this instrument and test has not passed"
    }
  }
}

Attributes inside precondition { }

The rows above are the guard KINDS. These are the attributes an author writes inside the block, and the values each one accepts. Both lists are read from the grammar, so neither can drift away from what the parser takes.

kind

Which guard this is. Omit it and the block is a `field_value_compare` — the legacy command contract. Executability is placement-specific: a kind valid on one carrier is rejected on another rather than quietly reduced to a different guard.

collection_in_stateentity_activeentity_existsfield_presentfield_uniquefield_value_comparefk_validintegration_signature_validmin_list_cardinalityno_conflictno_overlapping_intervalnot_expiredpermission_requiredrelated_rows_in_staterelationship_existsrole_required_any_ofrole_required_singleself_accesssession_scope_markertoken_validtrigger_markerworkspace_present
operator

How `field` is compared against `value` in a `field_value_compare`. `is_null` and `is_not_null` take no `value`.

eqdefaultgtgteinis_not_nullis_nullltltenot_eqnot_in
mode

For `collection_in_state`: whether every referenced row must be in the state, or none of them may be.

all_in_stateno_referents_in_state
row_mode

For `related_rows_in_state`: check only the most recent matching row, or every one of them.

alllatest
session_scope

For the `session_scope_marker`: which sessions the concern covers. It marks a decision of the sign-in service and adds no guard.

currentglobalsingle
workspace_source

For `workspace_present`: where the workspace/tenant id is read from on the request.

headerjwtjwt_or_header

Trigger Functions

Forms of `trigger = ...` in a flow and in an interactions edge.

event()

Background event trigger

trigger = event("user_created")
job()

Job-triggered flow. Must match a declared jobs entry

trigger = job("send_welcome_email")
state_change()

Not supported yet. The grammar accepts it, and no flow is run by a state transition today: a flow declared with this trigger is refused (FLOW-TRIGGER-UNDISPATCHED-001). Put the work in a step of the flow that writes the state, or trigger the flow with job("name") or event("name").

trigger = state_change(Order.status -> CONFIRMED)
A side effect of a transition: a further step of the same flow
flow "Confirm Order" {
  type    = state_transition
  trigger = "POST /orders/{id}/confirm"
  entity  = Order

  step 1 "Validate pending" {
    action    = validate
    condition = $instance.status == 'PENDING'
    error     = "Order must be PENDING to confirm"
  }

  step 2 "Confirm" {
    action = state_change
    target = Order
    mapping {
      status       = "CONFIRMED"
      confirmed_at = $computed.now
      confirmed_by = $context.user_id
    }
  }

  // Side effect: a further step of the same flow, in the same request
  step 3 "Record the confirmation" {
    action = create
    target = OrderEvent
    mapping {
      order_id    = $instance.id
      kind        = "CONFIRMED"
      recorded_at = $computed.now
    }
  }
}

Platform Spec

A platform spec declares the architecture of a multi-service application. It lives in a separate platform.dmx file and is never compiled directly — it provides context when compiling individual service specs.

Two file types in DMX:

  • Platform spec (platform.dmx): Declares shared infrastructure, lists all services/modules, defines compilation order, cross-service interactions, Celery workers, event bus, and infrastructure config. ONE per application.
  • Service spec (service_name.dmx): Defines ONE microservice — its entities, APIs, flows, security, state machines. The service "name" must match the module key in the platform's modules {} block.

The compiler compiles service specs one at a time, using the platform spec as infrastructure context.

Platform-Level Blocks

version

Platform version string

version = "1.0.0"
platform_roles { }

Compile-time RBAC role definitions (optional)

modules { }

REQUIRED: service/module declarations. Each module's dependencies = [...] drive the compilation order — no explicit ordering block

interactions { }

Cross-service communication: async event(...) and/or sync http(method=, path=) (optional)

celery { }

Task queue configuration with named workers (optional)

event_bus { }

Event streaming configuration (optional)

shared_kernel { }

Shared kernel module selection. modules accepts the 22 canonical productive plugin names: audit_decorator, base_repository, compliance_policy, encryption_policy, errors, event_bus, event_envelope, jwt_utils, module_gate, observability, protocol_counter, response_envelope, rls_policies, s2s_client, secrets, soft_delete, soft_delete_policy, sqlalchemy_ext, tenant_context, test_fixtures, traceability, trinity_policy. Non-canonical values rejected at parse time

feature_flags { }

Platform-wide feature toggles (optional)

output { }

Output directory configuration (optional)

validation { }

Compilation validation rules (optional)

infrastructure { }

API gateway, JWT, Redis, databases, ports (optional)

compliance { }

Spec-declared compliance profiles per platform jurisdictional scope. Canonical registry : CCPA / FEDRAMP / GDPR / HIPAA / HITRUST / ISO-27001 / NIST-800-53 / OWASP-API / OWASP-WEB / PCI-DSS / SOC2 / SOX + enterprise jurisdictional extensions ISO_15189 / AFIP_ARCA / FABA_AOL / LEY_25_326 / LEY_17_132. Non-canonical framework names rejected at validate-time (COMPLIANCE_PROFILE_UNKNOWN) via registry-loader lookup. Each profile carries retention, encryption, audit, residency, subject-rights and 17 framework-detail attrs

platform_scope_entities

Entities shared across all tenants (no tenant_id)

platform_scope_entities = [Currency, Country]
append_only_entities

Immutable audit/log entities

append_only_entities = [AuditEvent, SecurityLog]
abac_scope_policy { }

ABAC row-filter scope catalog: declares scope columns once (claim → strategy). A per-entity field @scoped(claim="<key>") activates a catalog entry. Optional required_for_roles = [role,...] makes a scope-dim role-conditional.

abac_scope_policy { branch_ids { strategy = scoped; required_for_roles = [receptionist] } }

Module Attributes

Every module declared in modules {} supports these fields.

spec

REQUIRED. Path to the service spec file

spec = "filename.dmx"
name

Human-readable display name for UI/reports

name = "Billing Service"
layer

Dependency layer: 0 = foundation; a higher layer depends on the ones below it

layer = 0
entities

Entity count (informational, for validation/UI)

entities = 10
dependencies

Compile-time deps: these must compile before this module

dependencies = [mod_a, mod_b]
service_type

standard | consumer | reader | stateless | aggregator

service_type = standard
database_engine

Database backend: postgresql (default) | clickhouse

database_engine = postgresql
clickhouse_tables

ClickHouse table names (when database_engine = clickhouse)

clickhouse_tables = [fact_orders, dim_tenants]
runtime_dependencies

Runtime services beyond default postgres

runtime_dependencies = [redis, clickhouse]
websocket_enabled

Records module intent; each socket endpoint declares its full admission and delivery contract.

falsetrue
websocket_enabled = false
token_also_issues

Additional JWT token types this service issues

token_also_issues = [patient_token, provider_token]
module_category

DDD Strategic Design classification (closed taxonomy). Industry-agnostic. See module_category Values section for the 6 canonical keywords.

module_category = core_domain

module_category Values (DDD Strategic Design)

Closed taxonomy from Domain-Driven Design Strategic Design (Eric Evans, Domain-Driven Design, 2003; Vaughn Vernon, Implementing Domain-Driven Design, 2013). Industry-agnostic — applies to any platform regardless of business vertical. Validated parse-time by the grammar; non-canonical keywords surface a parse error inline.

core_domain

The strategic differentiator. Where the business invests the most because it provides competitive advantage. Custom-built, evolves with strategy.

supporting_subdomain

Necessary for the business but not differentiating. Usually built in-house when no off-the-shelf option fits; can sometimes be outsourced.

generic_subdomain

Solved problem with widely available solutions (auth, notifications, audit, document storage). Buy / adopt / standardise rather than build.

integration_layer

Bridges to external systems / third-party adapters / gateway concerns. Maps the bounded contexts of partners to the platform's ubiquitous language.

presentation_layer

User-facing surfaces (web UI, portals, dashboards, BFFs that exist only to serve the UX). Composes responses from other modules; usually no own entities.

infrastructure_layer

Platform plumbing: control planes, deploy automation, observability scaffolding, secrets / cert / identity management at the platform level (not business-domain auth).

service_type Values

standard

Default. Normal microservice with entities, APIs, business logic

consumer

Event consumer with no REST API (e.g., data lake ingestor)

reader

Read-only service querying external data (e.g., analytics API over ClickHouse)

stateless

No database, real-time processing

aggregator

Portal API that composes responses from multiple services (no own entities)

Compilation Order

Derived automatically from each module's dependencies. There is no explicit ordering keyword — the compiler builds a topological DAG and rejects any legacy phase/ordering block.

control_plane has no deps so compiles first; identity depends on control_plane; registry and catalog depend on identity and compile in parallel; lab waits for both connectivity and preanalytic.

Dependency-driven order
platform "MyPlatform" {
  modules {
    control_plane { spec = "control_plane.dmx"; dependencies = [] }
    identity      { spec = "identity.dmx";      dependencies = [control_plane] }
    registry      { spec = "registry.dmx";      dependencies = [identity] }
    catalog       { spec = "catalog.dmx";       dependencies = [identity] }
    connectivity  { spec = "connectivity.dmx";  dependencies = [registry] }
    preanalytic   { spec = "preanalytic.dmx";   dependencies = [connectivity] }
    lab           { spec = "lab.dmx";           dependencies = [connectivity, preanalytic] }
  }
}

Celery Workers

Named worker definitions — each gets its own process with dedicated queues.

Define multiple workers with dedicated queue assignments.

Named workers
platform "MyPlatform" {
  celery {
    broker_url      = "redis://redis:6379/0"
    result_backend  = "redis://redis:6379/1"
    task_serializer = "json"
    concurrency     = 2

    worker worker_fast {
      queues = ["fast", "ocr", "notifications"]
    }
    worker worker_standard {
      queues = ["default", "pdf", "billing"]
    }
    worker worker_beat {
      role = scheduler    // Celery Beat scheduler
    }
  }
}

Interactions

Cross-service event-driven communication with tiered guarantees.

tier

1 = always generated, 2 = generated if both modules compiled, 3 = optional/audit

pattern

fire_and_forget (default) or request_reply (bidirectional)

choreographyorchestration
producer = *

Wildcard: any module can produce this event (broadcast)

Standard one-way event between two modules.

Fire-and-forget event
platform "MyPlatform" {
  modules {
    OrderService        { spec = "order.dmx";        dependencies = [] }
    NotificationService { spec = "notification.dmx"; dependencies = [OrderService] }
  }

  event_schemas {
    event "order.confirmed" version "v2" {
      payload {
        order_id    UUID
        customer_id UUID
        tenant_id   UUID
      }
    }
  }

  interactions {
    "i-11-order-confirmed-notifies" {
      tier         = 1
      producer     = OrderService
      consumer     = NotificationService
      trigger      = event("order.confirmed")
      task         = "send_confirmation"
      queue        = "notificationservice"
      trigger_operation = "confirm_order"
      event_schema = "order.confirmed@v2"
      ordering_key = "tenant_id"

      payload_map {
        order_id    = $instance.id
        customer_id = $instance.customer_id
        tenant_id   = $context.tenant_id
      }
    }
  }
}

Infrastructure

API gateway, JWT, Redis, databases, pagination, and service ports.

Platform-wide infrastructure configuration.

Full infrastructure block
platform "MyPlatform" {
  infrastructure {
    api_gateway {
      enabled = true
      type    = kong
      rate_limiting {
        enabled             = true
        requests_per_minute = 100
      }
    }
    service_ports {
      control_plane = 8010
      identity      = 8001
    }
    jwt {
      algorithm              = "HS256"
      token_lifetime_minutes = 30
      issuer                 = "platform-name"
    }
  }
}

`rate_limiting { burst = N }` is optional. Kong counts a fixed window per minute: it admits up to `requests_per_minute` within each minute, and there is no burst to set. Traefik limits with a token bucket that admits up to `burst + requests_per_minute` in a minute; `burst` declares that bucket, and left undeclared the bucket is `1`, so no more than the declared minute gets through. `/validate` and the compiler refuse a declared `burst` on a `kong` gateway, declared or by default (a gateway with no `type` is a kong: remove `burst` or set `type = traefik`), with `rate_limiting { enabled = false }` (nothing applies it), or outside `1..requests_per_minute` (a larger bucket lets one burst spend more than the whole minute). Up to it, the busiest minute is at most twice the declared one, what Kong's fixed window also admits across a minute boundary.

Gateway burst
platform "MyPlatform" {
  infrastructure {
    api_gateway {
      enabled = true
      type    = traefik
      rate_limiting {
        requests_per_minute = 100
        burst               = 20
      }
    }
  }
}

Canonical list-response pagination defaults. Drives the wrapper class, route Query() ge/le constraints, service signature, and BaseRepository.list defaults end-to-end (α-PAGINATION program). When omitted, the compiler falls back to default_limit = 100 + max_limit = 1000.

Pagination block
infrastructure {
  database {
    type = postgresql
    name = "user_service"

    pagination {
      default_limit = 100
      max_limit     = 1000
    }
  }
}

Compliance

Platform-scope compliance profiles. Each profile is a registered framework identifier the spec author binds to the platform per its jurisdictional scope; the compiler treats the name as opaque taxonomy and reads concrete obligations from the canonical compliance_frameworks registry + the attributes declared inside the block. The Workshop validator queries `registry_loader.is_supported_compliance_framework`; non-canonical names are rejected at validate-time as COMPLIANCE_PROFILE_UNKNOWN. The full canonical set as of 2026-05-15: CCPA / FEDRAMP / GDPR / HIPAA / HITRUST / ISO-27001 / NIST-800-53 / OWASP-API / OWASP-WEB / PCI-DSS / SOC2 / SOX + enterprise jurisdictional extensions ISO_15189 / AFIP_ARCA / FABA_AOL / LEY_25_326 / LEY_17_132 Every per-profile attribute below may be declared in the spec, which then decides the whole profile. Omit one and the compiler falls back to its built-in default for that framework.

scope

Free-form scope description (e.g. data residency rule).

scope = "protected_health_information"
data_classes

Data classes governed by the profile.

data_classes = ["PHI", "PII"]
retention_days

Hard retention floor (days).

retention_days = 2190
encryption_at_rest

Mandate encryption-at-rest.

falsetrue
encryption_at_rest = true
encryption_in_transit

Mandate TLS-everywhere.

falsetrue
encryption_in_transit = true
audit_required

Mandate audit-trail emission.

falsetrue
audit_required = true
access_review_days

Periodic access-review interval (days).

access_review_days = 90
subject_rights

Subject rights honoured (access / rectification / erasure / portability / restriction / objection).

subject_rights = ["access", "rectification", "erasure"]
breach_notification_hours

Breach notification SLA (hours).

breach_notification_hours = 72
residency

Data residency jurisdiction code.

residency = "US"
validation_controls

Required control families (e.g. technical_safeguards, administrative).

validation_controls = ["technical_safeguards", "administrative"]
legal_basis

Citable regulatory anchor.

legal_basis = "HIPAA-45-CFR-164"
full_name

Human-readable framework name.

full_name = "Health Insurance Portability and Accountability Act"
mode_alias

Compatibility alias for legacy SaaS payload modes.

mode_alias = "covered-entity"
phi_keywords

PHI keyword set used by data-classification gates.

phi_keywords = ["diagnosis", "patient_id", "mrn"]
phi_segments

Path-segment patterns hinting PHI (e.g. URL or table fragments).

phi_segments = ["/medical_records/", "/clinical/"]
pii_keywords

PII keyword set used by data-classification gates.

pii_keywords = ["ssn", "passport", "drivers_license"]
pii_segments

Path-segment patterns hinting PII.

pii_segments = ["/profile/", "/identity/"]
financial_keywords

Financial keyword set used by data-classification gates.

financial_keywords = ["card_number", "iban", "swift"]
financial_segments

Path-segment patterns hinting financial data.

financial_segments = ["/payment/", "/wallet/"]
min_retention_days

Minimum retention floor when distinct from retention_days.

min_retention_days = 365
requires_read_audit

Mandate read-side audit logging.

falsetrue
requires_read_audit = true
requires_pii_masking

Mandate PII masking in non-production environments.

falsetrue
requires_pii_masking = true
requires_extended_retention

Mandate retention beyond the platform default.

falsetrue
requires_extended_retention = true
requires_immutable_audit

Mandate append-only audit storage (no UPDATE/DELETE).

falsetrue
requires_immutable_audit = true
requires_encrypted_audit

Mandate encryption of the audit-trail at rest.

falsetrue
requires_encrypted_audit = true
requires_actor_info

Mandate actor identity capture in audit records.

falsetrue
requires_actor_info = true
requires_digital_signature

Mandate digital signature on audit records.

falsetrue
requires_digital_signature = true
requires_request_metadata

Mandate request-metadata capture (IP, UA, correlation_id).

falsetrue
requires_request_metadata = true
test_frameworks

Required compliance test framework labels (informational).

test_frameworks = ["hipaa-test-suite", "gdpr-rights"]

Spec-driven profile declaration; compiler reads every attribute below and stops consulting the default registry when the value is present.

Compliance profile (full feature-set)
platform "MyPlatform" {
  compliance {
    profile "covered-entity" {
      scope                     = "protected_health_information"
      data_classes              = ["PHI", "PII"]
      retention_days            = 2190
      encryption_at_rest        = true
      encryption_in_transit     = true
      audit_required            = true
      access_review_days        = 90
      subject_rights            = ["access", "rectification", "erasure"]
      breach_notification_hours = 72
      residency                 = "US"
      validation_controls       = ["technical_safeguards", "administrative"]
      legal_basis               = "HIPAA-45-CFR-164"
      full_name                 = "Health Insurance Portability and Accountability Act"
      mode_alias                = "covered-entity"
      phi_keywords              = ["diagnosis", "patient_id", "mrn"]
      pii_keywords              = ["ssn", "passport"]
      min_retention_days        = 2190
      requires_read_audit       = true
      requires_pii_masking      = true
      requires_extended_retention = true
      requires_immutable_audit  = true
      requires_encrypted_audit  = true
      requires_actor_info       = true
      requires_digital_signature = false
      requires_request_metadata = true
      test_frameworks           = ["hipaa-test-suite"]
    }
  }
}

Complete Examples

Full spec examples from simple to complex.

A minimal spec: one entity, REST API, basic security. Note the shape — `entity`, `api` and `security` are SIBLINGS of `service`, not nested inside it, and entity annotations go INSIDE the braces.

Day 1 — Simple User Service
service "UserService" {
  docs { operator_only }
  version     = "1.0.0"
  port        = 8000
  api_prefix  = "/api/v1"
  database    = "user_service"
}

entity User {
  @aggregate_root
  @description("Application user account")
  @audit(level: standard)
  @role(user)

  id         UUID        @pk @default($computed.uuid)
  email      String(255) @not_null @unique @format(email)
  password_hash String(255) @not_null @sensitive @field_purpose(password)
  name       String(200) @not_null @freetext
  role       Enum(ADMIN, MEMBER) @not_null @default("MEMBER")
  is_active  Boolean     @not_null @default(true)
  created_at DateTime    @not_null @default($computed.now)
}

api {
  POST "/auth/login" {
    auth_required = false
    request { email String(255) @required; password String(128) @required @sensitive @field_purpose(password) }
    response { access_token String }
  }

  GET "/users" {
    operation_id = "list_users"
    permissions  = ["users:read"]
    query {
      page  Integer @default(1)
      limit Integer @default(50)
    }
    response @paginated(User)
  }

  POST "/users" {
    operation_id = "create_user"
    permissions  = ["users:manage"]
    request {
      email    String(255) @required @format(email)
      name     String(200) @required @freetext
      password String(128) @required @sensitive @min_length(12)
    }
    response @entity(User) @status(201)
  }
}

flow "Create User" {
  type    = workflow
  trigger = "POST /users"
  entity  = User

  step 1 "Create the user with a hashed credential" {
    action = create
    target = User
    mapping {
      email         = $input.email
      name          = $input.name
      password_hash = $computed.hash_password($input.password)
      role          = "MEMBER"
      is_active     = true
    }
  }
}

security {
  auth_scheme          = jwt
  jwt_algorithm        = "HS256"
  token_expiry_minutes = 60
  password_hashing     = bcrypt
  user_entity          = "User"
  user_lookup_field    = "email"
  active_field         = "is_active"
  role_field           = "role"

  roles = [ADMIN, MEMBER]

  rate_limit {
    login_attempts      = 5
    requests_per_minute = 120
    lockout_duration    = "15m"
  }

  policy "user_access" {
    entity = User
    allow [list, create] for [ADMIN]
    allow [list] for [MEMBER]
  }
}

A more complex spec with flows, state machines, and jobs.

Day 5 — E-commerce with Flows and State Machines
service "OrderService" {
  docs { operator_only }
  version     = "2.0.0"
  port        = 8001
  api_prefix  = "/api/v1"
  database    = "order_service"
}

entity User {
  @aggregate_root
  @description("Account that places and manages orders")
  @role(user)

  id            UUID        @pk @default($computed.uuid)
  email         String(255) @not_null @unique @format(email)
  password_hash String(255) @not_null @sensitive @field_purpose(password)
  role          Enum(ADMIN, MEMBER) @not_null @default("MEMBER")
  is_active     Boolean     @not_null @default(true)
  created_at    DateTime    @not_null @default($computed.now)
}

entity Order {
  @aggregate_root
  @description("Customer order")
  @audit(level: full)
  @role(domain)
  @cache(ttl: 300)

  id          UUID     @pk @default($computed.uuid)
  customer_id UUID     @not_null
  total       Decimal(12, 2) @not_null
  currency    String(3) @not_null @default("USD")
  status      Enum(DRAFT, PENDING, PAID, SHIPPED, DELIVERED, CANCELLED) @not_null @default("DRAFT")
  paid_at     DateTime
  created_at  DateTime @not_null @default($computed.now)
}

state_machine Order.status {
  initial  = DRAFT
  terminal = [DELIVERED, CANCELLED]

  DRAFT   -> PENDING    @roles(MEMBER, ADMIN)
  PENDING -> PAID
  PAID    -> SHIPPED    @roles(ADMIN)
  SHIPPED -> DELIVERED
  PENDING -> CANCELLED  @roles(MEMBER, ADMIN)

  @guard(SHIPPED) {
    condition = $instance.paid_at != null
    error     = "An order ships only after its payment is recorded"
  }
}

flow "Place Order" {
  type    = workflow
  trigger = http(method="POST", path="/orders")
  entity  = Order

  step 1 "Validate manage scope" {
    action = validate
    precondition {
      kind            = permission_required
      permission_name = "orders:manage"
      error_message   = "Manage scope required"
    }
  }

  step 2 "Create order" {
    action = create
    target = Order
    mapping {
      customer_id = $context.user_id
      total       = $input.total
    }
  }
}

flow "Pay Order" {
  type    = state_transition
  trigger = "POST /orders/{id}/pay"
  entity  = Order

  step 1 "Record the payment" {
    action = state_change
    target = Order
    mapping {
      status  = "PAID"
      paid_at = $computed.now
    }
  }
}

api {
  GET "/orders/{id}" {
    addressing { id = Order.id }
    permissions = ["orders:manage"]
    response @entity(Order)
  }

  POST "/auth/login" {
    auth_required = false
    request { email String(255) @required; password String(128) @required @sensitive @field_purpose(password) }
    response { access_token String }
  }

  POST "/orders" {
    operation_id = "create_order"
    permissions  = ["orders:manage"]
    request {
      total Decimal(12, 2) @required
    }
    response @entity(Order) @status(201)
  }

  POST "/orders/{id}/submit" {
    operation_id = "submit_order"
    addressing   { id = Order.id }
    permissions  = ["orders:manage"]
    @triggers(Order.status -> PENDING)
    response @entity(Order)
  }

  POST "/orders/{id}/pay" {
    operation_id = "pay_order"
    addressing   { id = Order.id }
    permissions  = ["orders:manage"]
    @triggers(Order.status -> PAID)
    response @entity(Order)
  }

  POST "/orders/{id}/ship" {
    operation_id = "ship_order"
    addressing   { id = Order.id }
    permissions  = ["orders:fulfil"]
    @triggers(Order.status -> SHIPPED)
    response @entity(Order)
  }

  POST "/orders/{id}/deliver" {
    operation_id = "deliver_order"
    addressing   { id = Order.id }
    permissions  = ["orders:fulfil"]
    @triggers(Order.status -> DELIVERED)
    response @entity(Order)
  }

  POST "/orders/{id}/cancel" {
    operation_id = "cancel_order"
    addressing   { id = Order.id }
    permissions  = ["orders:manage"]
    @triggers(Order.status -> CANCELLED)
    response @entity(Order)
  }

  GET "/orders" {
    operation_id = "list_orders"
    permissions  = ["orders:read"]
    response @paginated(Order)
  }
}

errors {
  prefix = "OR"

  OR_001 { status = 404 category = not_found  message = "Order not found"    entity = Order field = id }
  OR_002 { status = 409 category = conflict   message = "Insufficient stock" entity = Order field = id }
}

security {
  auth_scheme          = jwt
  jwt_algorithm        = "HS256"
  token_expiry_minutes = 60
  password_hashing     = bcrypt
  user_entity          = "User"
  user_lookup_field    = "email"
  active_field         = "is_active"
  role_field           = "role"

  roles = [ADMIN, MEMBER]

  rate_limit {
    login_attempts      = 5
    requests_per_minute = 100
    lockout_duration    = "15m"
  }

  policy "order_access" {
    entity = Order
    allow [list, create, submit, pay, cancel, ship, deliver] for [ADMIN]
    allow [list, create, submit, pay, cancel] for [MEMBER]
  }
}

infrastructure {
  database {
    type = postgresql
    name = "order_service"
  }
  redis {
    use_ssl = true
    cache { enabled = true; ttl = 600 }
  }
  api_gateway {
    enabled = true
    type    = kong
  }
}

Refused today

What the grammar accepts and the compiler refuses today. A row is a limit of the compiler, not a rule of the language: when the capability lands, the row goes.

ConstructRefused todayWrite insteadRefusal
abac_constraints { C { constraint_type = T } }A constraint whose constraint_type is missing or is not an enforcement strategy: nothing would enforce it.Declare constraint_type as one of: ip_check, portal_match, relationship, role_attr_match, scope_match, scoped, self_only.ABAC-CONSTRAINT-STRATEGY-UNDECLARED
security account_emailAccount email declared in a module whose principal another service owns, a password reset or invitation for a principal whose password lives on a separate credential store, or an invitation for a principal whose role is not a column of its own: DevMatrix cannot serve these routes yet.Declare account_email in the service that owns the principal, keep the password on the principal (@field_purpose(password)) and its role in security.role_field, or declare only the flows that can be served.ACCOUNT_EMAIL_PRODUCER_MISSING (a limit of the compiler)
a flow whose route requires no sign-in and writes audited records, in an application whose sign-in entity has an @scoped fieldAudit rows that cannot say who acted: the flow creates no record of the sign-in entity (a record it only looks up does not say who is calling), creates more than one, or leaves its scoped field unset, so the audit trail, which admits a row only through its actor's scope, would refuse every row.Require sign-in on the route, or create in the flow the one record of the sign-in entity it acts for, with its scoped field set.AUDIT-ACTOR-BEFORE-SIGN-IN-UNBOUND-001
audit readable_byAn audit block whose readable_by names a role the security block does not declare, names no role, or sits in a module that authenticates nobody: the audit trail would be gated on a role no caller can hold.Name only roles the security block declares, in a module that declares authentication; delete readable_by to serve the audit trail to nobody.AUDIT-READERS-UNENFORCEABLE-001
a batch step on the flow's own entity reading $instanceA batch writes every row its filter matches in one statement, where $instance is the flow's row, not each matched row.Declare the per-row write as a foreach over a source_query, reading each row as $item.<field>.BATCH-ROW-VALUE-001
a batch step without its target, filter {} or mapping {}A batch is one bulk statement: it writes the target's rows its filter matches with its mapping, and none of the three has a default.Declare the missing target, filter {} or mapping {} on the step.BATCH_STEP_MISSING_INVARIANT_FIELD
security bootstrap_principalA bootstrap principal whose entity belongs to a tenant, or one another service owns: DevMatrix cannot create it at deploy yet.Declare bootstrap_principal in the service that owns the principal, on a principal that belongs to no tenant.BOOTSTRAP_PRINCIPAL_PRODUCER_MISSING (a limit of the compiler)
a flow declared at a route the compiler serves itself: an auth route, the audit-trail read, a self-check, system, storage, flag, metrics or probe routeat validation and at compile, when the route does not do a step, answer the status or return the body the flow declaresremove from the flow and its endpoint what the route does not carry, as the finding names it, or declare the flow at a route of its ownCESSION-CONTRACT-REFUSED-001
clock comparisonA clock read ($computed.now, now()) compared with a field that is not a Date, a DateTime or a Time ($input.quantity < $computed.now).Compare the clock with a Date, DateTime or Time field.CLOCK-COMPARISON-001
clock comparisonOne comparison that reads the clock and fields of different temporal types (a Date and a DateTime in a < $computed.now < b).Split it so each comparison reads fields of one declared type.CLOCK-COMPARISON-002
clock comparisonA clock read compared with a value whose declared type nothing states (a literal, or a value no declared field types).Compare the clock with a declared Date, DateTime or Time field ($input.<field>, $instance.<field>, $result.<read>.<field>, or a row of a read).CLOCK-COMPARISON-003
clock comparisonOutside a validate step, a clock read compared with a Date or a Time field (a step condition with $instance.due_on < $computed.now).Move the comparison to a validate step, or compare the clock with a DateTime field.CLOCK-COMPARISON-004
@computed("<expression>") on a Decimal fieldAn operator or call other than +, -, * and / in the expression of a Decimal field, which is computed exactly before one rounding.Write the Decimal expression with + - * / over fields and numeric literals, or declare the field as another type.COMPUTED-DECIMAL-OPERATOR-NOT-LOWERED-001 (a limit of the compiler)
a retired $computed helper name, such as $computed.bcrypt_verify(...)A retired spelling of a computed helper: bcrypt_verify names an algorithm, not the application's password hashing contract.Write $computed.password_verify(password, stored_hash).COMPUTED_FUNCTION_REFUSED_ALIAS
response @entity(...) / @paginated(...) on a route that mints a tokenA login or second-factor completion route whose response declares a stored resource instead of the token pair the route answers.Write response @status(...) with no body, or an inline response { } restating the token fields (an expiry as expires_at DateTime @value_from(access_token_expires_at)).CREDENTIAL-GRANT-RESPONSE-DECLARES-RESOURCE-001
attribute, path parameter, request or response field, or file handler entity nameA declared name that is a reserved word of the emitted language (from, class, import, …), including the lowercase parameter of a file handler.Rename it; a query parameter may keep such a name.DECLARED-NAME-RESERVED-WORD-001
flow step aggregateAn aggregate (sum, min, max, …) over rows that no query step of the same flow read.Read the rows in a query step of the same flow (result_field, query_cardinality = "list") and reduce $result.<alias>.EMISSION-PLANNING-AGGREGATE-TYPE-001
flow step aggregateAn aggregate whose values have no one type to reduce to: a sum of values that are not numbers, a min or max over values of more than one declared type, or a Float combined with a Decimal.Reduce one declared type per aggregate: sum over Integer, Float or Decimal fields, min/max over fields of one type; to combine a Float with a Decimal, declare both Decimal.EMISSION-PLANNING-AGGREGATE-TYPE-002
flow step $resultA foreign key written from $result.<alias>.id when the step that declared the alias is not the one step that always ran before the write (two steps produce that entity, or the step is conditional).Take the key from one earlier unconditional step of the same flow, or from $input / $instance.EMISSION-PLANNING-CROSS-STEP-FK-AUTHORITY
flow step action = queryA query step with a result_field that expects one row and declares neither filter { } nor query_field / query_value.State which row the step reads; a step that reads the whole collection says so with query_cardinality = "list".EMISSION-PLANNING-NAMED-QUERY-PREDICATE-001
flow exportAn export of rows of an entity without exactly one @pk field: the file lists its rows in the order of the one primary key.Mark exactly one field of the exported entity @pk.FLOW-EXPORT-ENTITY-KEY-NOT-SINGLE
flow exportAn export of rows of an entity the module does not declare: there is no row to write.Name an entity the module declares (export_entity, the export or query step's entity, or the flow's), or declare that entity in the module.FLOW-EXPORT-ENTITY-UNDECLARED
flow export columnAn export column declared twice: a file has one column per name.Remove the repeated column.FLOW-EXPORT-FIELD-DUPLICATE
flow export columnAn export column the entity lets no caller read: the export would hand out what reading the entity never returns.Remove the column, or declare the roles that may read the field: @sensitive(readable_by: [ROLE]).FLOW-EXPORT-FIELD-NOT-READABLE
flow export columnAn export column only some roles may read, on a route declared auth_required = false: no caller is known there, so no one would ever get the column.Remove the column, or remove auth_required = false from the route so callers sign in.FLOW-EXPORT-FIELD-ROLES-ON-PUBLIC-ROUTE
flow export columnAn export column that names no field of the exported entity: the column would be empty in every file.Remove the column, or name a field the exported entity declares.FLOW-EXPORT-FIELD-UNDECLARED
flow export filterAn export filter on a field the exported entity does not declare.Filter by a field the exported entity declares.FLOW-EXPORT-FILTER-FIELD-UNDECLARED
flow export filterAn export filter that compares a field with a literal of another type.Compare the field with a value of its type.FLOW-EXPORT-FILTER-VALUE-TYPE
flow export formatAn export in a format DevMatrix does not write: the route would answer with no file.Declare the export in one of the formats DevMatrix writes.FLOW-EXPORT-FORMAT-NOT-PRODUCED (a limit of the compiler)
flow file_operation max_rowsAn export bound above the rows its format holds: an xlsx file cannot hold more rows than one worksheet.Declare a max_rows the format holds, or export in another format.FLOW-EXPORT-MAX-ROWS-ABOVE-FORMAT
flow file_operation max_rowsAn export bound of zero rows: an export writes at least one row.Declare a positive max_rows, or remove it to use the default bound.FLOW-EXPORT-MAX-ROWS-NOT-POSITIVE
flow exportAn export that names no column, of an entity with no field its callers may read: the file would have no column.Declare the roles that may read a field of the entity (@sensitive(readable_by: [ROLE])), or, on a route declared auth_required = false, let callers sign in.FLOW-EXPORT-NO-READABLE-COLUMN
flow exportA query step of an export flow that neither feeds the file nor is read by a later step: what it selects would be ignored.Declare the rows in the export step, name the query's result and read it, or remove the query.FLOW-EXPORT-QUERY-NOT-READ
flow exportAn export whose rows are declared twice and differently: a file has one set of rows.Keep the filter of the export step or of the query step, not both; name and read the result of a query of other rows.FLOW-EXPORT-ROWS-DECLARED-TWICE
flow file_operation type = downloadA file_operation of type download: it reads the service's disk, and the delivered service writes no file there.Remove the file_operation block and declare the document type in object_storage: its download route serves the stored file.FLOW-FILE-DOWNLOAD-NOT-PRODUCED (a limit of the compiler)
flow file_operation export_entityexport_entity on a file_operation of type upload: it writes no exported rows, so nothing reads it.Remove export_entity; it belongs to an export.FLOW-FILE-EXPORT-ENTITY-NOT-READ
flow file_operation export_fieldsexport_fields on a file_operation of type upload: it writes no exported rows, so nothing reads it.Remove export_fields; it belongs to an export.FLOW-FILE-EXPORT-FIELDS-NOT-READ
flow file_operation export_formatexport_format on a file_operation of type upload: it writes no exported rows, so nothing reads it.Remove export_format; it belongs to an export.FLOW-FILE-EXPORT-FORMAT-NOT-READ
flow file_operation type = generateA file_operation of type generate: document generation (PDF or other files) is not produced, and the generated service would not start.Remove the file_operation block, or produce the document outside the service.FLOW-FILE-GENERATE-NOT-PRODUCED (a limit of the compiler)
flow file_operation max_rowsmax_rows on a file_operation of type upload: it writes no exported rows, so nothing reads it.Remove max_rows; it belongs to an export.FLOW-FILE-MAX-ROWS-NOT-READ
flow step in a download flowA step other than validate or upsert in a flow with file_operation { type = download }: the flow loads its row and returns the file, and the step would not be carried out. Today the whole download flow is refused first, whatever its steps.Remove the step, or move it to a flow of its own; the download itself is refused until DevMatrix reads it from object storage.FLOW-FILE-OPERATION-STEP-NOT-LOWERED (a limit of the compiler)
flow file_operation process_asyncprocess_async = true on a file_operation: background file processing is not produced, and the handler would run inline.Remove process_async or set it to false.FLOW-FILE-PROCESS-ASYNC-NOT-PRODUCED (a limit of the compiler)
flow file_operation storage_backendstorage_backend on a file_operation of type export: the response is streamed and nothing is stored.Remove storage_backend; it belongs to an upload.FLOW-FILE-STORAGE-BACKEND-NOT-READ
flow file_operation storage_fieldstorage_field on a file_operation of type export: the response is streamed and no stored file is found by a column.Remove storage_field; it belongs to an upload.FLOW-FILE-STORAGE-FIELD-NOT-READ
flow file_operation template_enginetemplate_engine on a file_operation, with any value: no generated document is produced, so nothing reads it.Remove template_engine.FLOW-FILE-TEMPLATE-ENGINE-NOT-READ
flowA flow whose route names no row, with a step that reads $instance or writes the flow's entity without an address, on an entity related to the signed-in account through more than one column.Declare the load: add a query step on the entity with the column that identifies the caller's row, or address the step with query_field / query_value.FLOW-INSTANCE-LOAD-AMBIGUOUS-001
route that addresses a tenant in its pathA route that takes its tenant from a path parameter ({tenant_id}, or the owner's tenancy column) while its caller carries no tenant to compare it with: the route requires no authentication, or the principal entity declares no tenancy column. Any caller could read and write any tenant by typing its id.Require authentication on the route and declare the tenancy column of the principal entity, or stop addressing the tenant in the path.FLOW-SECURITY-ADDRESSED-TENANT-UNBOUND
$context.tenant_id on a public routeA flow whose route declares auth_required = false (or whose service authenticates nobody) and whose steps read $context.tenant_id: no caller exists to take the tenant from, and nothing fills the key.Require authentication on the route, or do not read $context.tenant_id in the flow.FLOW-SECURITY-REQUEST-TENANT-UNSOURCED
route granted by allow ... when ownership(field)A route whose policy grants the action by ownership, where no step of its flow loads, lists, creates or filters rows of that entity by an owner bound to the signed-in account, so the route would act on, or list, rows the caller does not own.Filter the step that reads the caller's rows (the one row it acts on, or the rows a list returns) by its owner field = $context.user_id (or by a row that belongs to it through its foreign key to that field), or write the owner field from $context.user_id in the step that creates the row.FLOW-SECURITY-ROW-OWNER-SCOPE-UNBOUND
flow step conditionA step under a condition whose result a later step of the same flow reads: when the condition is false the value does not exist, and a flow has no implicit else.Make the step that reads the value part of the same conditioned step, bind the value before the condition, or declare a void or status-only outcome for the false path.FLOW-STEP-CONDITION-FALSE-PATH-UNBOUND
create step on a public routeA step on a route with auth_required = false that creates a row of a tenant-scoped entity without mapping its tenancy column, in a flow whose first read is not a row addressed by a unique request field.Map the tenancy column in the step (from a request field or from a row the flow read), read a row of that tenant first by a unique request field, or require authentication on the route.FLOW-TENANT-SOURCE-UNRESOLVED
flow file_operation upload_destinationAn upload to s3 whose upload_destination names no bucket this service declares.Declare it in the block the service keeps its files in: a document_type <name> { ... } of object_storage, or a bucket "<name>" { provider = s3 } of file_storage (kept, with write_once = true or retention { allow_overwrite = false }, when no route of the entity holding the key is granted delete); or set upload_destination to one the service declares.FLOW-UPLOAD-DESTINATION-NOT-A-BUCKET
flow file_operation storage_backend (upload)An upload in a service that declares no object storage, or one that declares storage_backend = local: the delivered service runs on a read-only disk, so the file would have nowhere to go.Declare the bucket the file goes to, in the block the service keeps its files in: file_storage { bucket "<name>" { provider = s3 } }, or a document_type <name> { ... } of object_storage, with upload_destination = "<name>", and remove storage_backend = local. When no route of the entity holding the key is granted delete, the files are kept: retention { allow_overwrite = false } on the bucket, or write_once = true on the document type.FLOW-UPLOAD-NEEDS-OBJECT-STORAGE
flow step field_mapping of an upload's storage_fieldA step of an upload that maps its storage_field from the request: the upload fills that column with the stored file's key.Remove the mapping from the step. If the client already stored the object and the flow only registers it, remove the file_operation block.FLOW-UPLOAD-STORAGE-FIELD-FROM-INPUT
flow file_operation storage_field (upload)An upload with no storage_field, or with one that names no column of its entity: nothing would record where the file was stored.Declare storage_field = "<column>" naming a column of the entity (for example file_key String(512) @nullable).FLOW-UPLOAD-STORAGE-FIELD-NOT-A-COLUMN
a flow check repeating the @guard of the state the flow writesEvery condition of the check is a condition of the guard, which the service checks before it, so the check can never refuse.Remove the check and keep the guard's answer, or make the check ask for something the guard does not.FLOW_STEP_ANSWERED_BY_STATE_GUARD
integration_gatewayThe integration gateway is not offered yet.Remove the integration_gateway block to compile this application.INTEGRATION-GATEWAY-NOT-OFFERED-001 (a limit of the compiler)
interactions state triggerAn interaction declaring trigger_state or trigger = state_change(Entity.field -> STATE): no producer binds and durably delivers the exact transition performed in the transaction.Keep the declaration blocked until the transition producer exists. Use trigger_operation = "<operation_id>" only if operation completion is the intended contract; it is not equivalent to a state transition.INTERACTION-STATE-TRIGGER-PRODUCER-MISSING (a limit of the compiler)
events internal_mirror_pathinternal_mirror_path on a published event: a synchronous route that runs the event's handling, and nothing the service declares says what that route would run.Remove the internal_mirror_path line; the event is still published as declared. Changing the path does not help.INTERNAL-MIRROR-TARGET-PRODUCER-MISSING (a limit of the compiler)
state_machine Entity.fieldA state machine on a field that is not an Enum(...) column of its entity, or whose initial, terminal = [...] or a transition names a value that Enum does not have.Declare the field as Enum(...) with every state the machine names: the machine's states are the Enum's values.INV-208-005
flow step writing an optional $input into a NOT NULL column; route with no flow, optional request field over a NOT NULL columnWithout @default, a request that omits the field fails at the write.Mark it @required, or the column @default or @nullable; for an update, PATCH.INV-208-029, INV-CRUD-NULL-SOURCE
field @scoped(claim=...)Columns scoped by the same claim whose values are of different types (for example an Array(UUID) and a Decimal): the claim's values cannot be read as the type of every column it filters.Declare every column a claim scopes with one value type; a list counts by the type of its items.INV-ABAC-SCOPE-CLAIM-TYPE-MISMATCH
field @scoped(claim=...)A scoped column of a type whose text can contain a comma (String, Text, Float, Date, DateTime, Time, a JSON list with no item type), where a comma would split one value into two scope values; or an Array of integers, booleans or decimals, whose items the list filter does not match.Declare the column as UUID, integer or an enum, or as an Array(UUID) or an Array of an enum.INV-ABAC-SCOPE-COLUMN-FREE-TEXT
a flow step changing a row of an @append_only entityRows of an @append_only entity are added and never changed.Remove the step, write a new row instead (action = create), or use @append_only_after(STATE, field) if rows may change until a state; if a webhook route answers its redeliveries with rows of the entity, keep it @append_only and write what changes to a second entity.INV-APPEND-ONLY-WRITE
security { auth_scheme = basic | api_key | oauth2 }A credential scheme the emitted backend has no reader for: it reads a bearer JWT or no credential.Declare auth_scheme = jwt, or auth_scheme = none when nobody authenticates.INV-AUTH-SCHEME-EMITTED
redis { cache { namespace = "..." } }A blank namespace, which leaves this module's cache keys unseparated from other services'.Write a namespace, or remove the attribute to use the module's name.INV-CACHE-NAMESPACE-BLANK
command { http_method = M endpoint_path = "P" }A command whose http_method + endpoint_path names no declared api endpoint exactly (a placeholder spelled differently counts as another route).Spell endpoint_path and http_method as the endpoint is declared, or declare the endpoint in the api block.INV-COMMAND-ROUTE-UNDECLARED
a column numbered by $computed.tenant_sequence(...) or another sequence helperA tenant or scope argument the numbered row does not keep, more than one sequence on the column, or different arguments in different steps: a seeded or imported row cannot be given a number of the counter the next create draws fromWrite the argument's value into a column of the row in the same step, or pass a literal, a column of the row or a column of the row a foreign key of it references; number the column from one sequence with the same arguments in every stepINV-COMPUTED-SEQ-PARTITION
a sequence's format_template numbering a column that declares a @patternA template whose first values the numbered column's own @pattern refuses ({seq:9} pads with spaces, which ^[0-9]{9}$ refuses): every create would write a value the column does not accept; or a @pattern on that column that is not a regular expressionWrite the template so every number it renders fits the pattern, for example a zero-filled width ({seq:09}), or declare the pattern the template renders as a valid regular expressionINV-COMPUTED-SEQ-PATTERN
@unique column from a per-tenant or per-period sequenceTwo tenants or periods draw the same value@unique_together(<tenancy column>, field), or render the period/{tenant_id}INV-COMPUTED-SEQ-UNIQUE
entity <Name> { ... } named like an entity the compiler mintsAn entity named like one the compiler emits on its own, which would be a second class and a second table under that name.Rename the entity and every reference to it.INV-ENTITY-NAME-COMPILER-RESERVED
events binding (trigger_entity) under an event_bus {} without its dead-letter deliveryAn event recorded on entity writes when the spec's event_bus {} does not declare dead_letter_max_retries, dead_letter_backoff_seconds and dead_letter_backoff_max_seconds.Declare all three in event_bus { dead_letter_max_retries = 5 dead_letter_backoff_seconds = 10 dead_letter_backoff_max_seconds = 3600 }: a monolith at the root of its spec, a microservices application inside platform { }.INV-EVENT-DELIVERY-UNDECLARED
events binding (trigger_entity) on an entity with no tenancyAn event bound to writes of an entity that carries no tenant column, in a service that isolates its rows by tenant.Bind the event to an entity scoped by @tenancy, or declare @tenancy on that entity.INV-EVENT-PUBLICATION-UNLOWERABLE
events declaration with transport = redis_streams, transport = sqs or consumer_group; event_bus { transport = sqs }An event carried on a Redis stream or on SQS: nothing the compiled service runs sends events there, so a reader of the stream or the queue would never receive them.Remove transport and consumer_group from the event, and transport = sqs from event_bus; an event bound to a write of one of the service's entities is still delivered to the service's own flows.INV-EVENT-TRANSPORT-UNBUILT (a limit of the compiler)
flow with trigger = event("E") where no events binding records EA flow triggered by an event that no write of the service's entities records: nothing delivers it, so the flow never runs.Bind the event to the write in events { "E" { trigger_entity = <Entity> trigger_action = create } }, or change the flow's trigger.INV-EVENT-TRIGGER-UNDELIVERED
fallback_behavior of an integrationA failure posture nothing binds to a queue, so a failed call would be reported as queued with nothing queued.Declare fallback_behavior = fail_fast or log_and_continue.INV-INTEGRATION-FALLBACK-NOT-LOWERED
The oauth block of an oauth_flow integrationA setting the OAuth client reads left undeclared.Declare every setting the oauth block names.INV-INTEGRATION-OAUTH-SETTING-UNDECLARED
timeout_seconds in an integration's api_client blockA timeout below one second, which every request would hit before it completes.Declare timeout_seconds of at least 1.INV-INTEGRATION-TIMEOUT-NOT-POSITIVE
type of an integrationAn integration type no emitted client implements: the spec cannot declare the provider operations such a client would call.Declare the integration as api_client with its api_client block.INV-INTEGRATION-TYPE-NOT-LOWERED
The webhook block of a webhook_receiver integrationA setting the webhook route reads left undeclared, or an empty events list, which acknowledges every delivery and runs nothing.Declare every setting the webhook block names, and list the event types handled.INV-INTEGRATION-WEBHOOK-SETTING-UNDECLARED
entity / field / flow / command / state_machine / policy / roleThe same name declared more than once in its scope: two entity X blocks, a field twice in one entity, two flows, commands or policies of one name, two state_machine blocks on one Entity.field, a role listed twice.Keep one declaration, or rename the other.INV-NAME-DECLARED-TWICE
breakglass { enabled = true }An enabled block with no grants.List the permissions the window grants in grants = [...].INV-PM-012
breakglass { grants = [...] }A grant that is not a declared permission key, a wildcard, or listed twice.List each granted permission once, by its declared key.INV-PM-013
breakglass { grants = [...] }grants listing request_permission or approver_permission.Remove the requesting or approving permission from grants.INV-PM-014
breakglass { max_duration_hours = N }max_duration_hours below 1.Declare the longest window in whole hours, at least 1.INV-PM-015
sod_rules { R { breakglass_eligible = true } }breakglass_eligible = true on an SoD rule: a window never lifts a rule.Set breakglass_eligible = false or remove it from the rule.INV-PM-016
breakglass { ... }Policy attributes on a block that does not declare enabled = true.Declare enabled = true, or remove the block.INV-PM-017
api { POST "/breakglass/activations" { ... } }An endpoint on a route the breakglass block synthesizes.Remove the endpoint, or move it to another path.INV-PM-018
breakglass { request_permission = "P" }An enabled block with no request_permission, or one not declared.Declare the permission and name it in request_permission.INV-PM-019
breakglass { enabled = true }An enabled block on a module that declares no authenticated principal.Declare security { user_entity } or @role(user), or remove the block.INV-PM-020
breakglass { requested_by = [...] }An enabled block that names no declared role to ask for a window.Declare requested_by = [ROLE, ...] with declared roles, each once.INV-PM-021
breakglass { approver_permission, approved_by = [...] }An approver without the declared roles that decide, or roles that decide without an approver.Declare approved_by = [ROLE, ...] beside approver_permission, or remove the one that stands alone.INV-PM-022
breakglass { enabled = true }An enabled block on a module that keeps no audit trail.Declare audit { enabled = true }, or remove the block.INV-PM-023
A GET route that reads through a row, such as /sites/{id}/sheetA route whose last segment names no entity's collection and that declares neither the rows it lists nor a file it hands back.Declare response @paginated(Entity) for the rows it lists, or bind a flow with a file_operation of type export.INV-RELATED-READ-UNDECLARED
response @entity(X) / response @paginated(X)A route that governs a flow and declares a response of an entity the module does not declare.Name a declared entity in the marker, declare the entity, or describe the body with response { ... }.INV-RESPONSE-ENTITY-UNDECLARED
step permissionA flow step guarded by a permission key that no permission is declared for (or the service declares no permissions at all).Declare each exact key in the permissions block or in the endpoint's permissions field.INV-STEP-PERMISSION-CATALOG
platform_minimum / platform_maximum on a tenant config settingOnly settings whose data_type is an ordered number can be bounded.Change the setting's data_type to a numeric one, or remove the bound.INV-TC-BOUND-TYPE
data_type on a tenant config settingThe type is not one a tenant setting can declare.Change data_type to one of the supported types the refusal lists.INV-TC-DATA-TYPE-UNSUPPORTED
storage_model on a tenant_config blockThe value is not a storage layout tenant settings can be stored in.Declare storage_model as one of the layouts the refusal lists, or leave it out for jsonb.INV-TC-STORAGE-MODEL-UNSUPPORTED
String(n) / Char(n) / Decimal(p, s) / Enum(...)A length or a precision of 0, a scale greater than its precision, an Enum member listed twice, two Enum values that differ only in letter case.Lengths and precisions start at 1, the scale is at most the precision, and each Enum member is listed once, the values differing by more than letter case.INV-TYPE-PARAMETER-OUT-OF-RANGE
async interaction triggered by a flow on a public routeAn async interaction whose trigger is a flow whose route has auth_required = false, in a module that isolates its rows by tenant, when the flow resolves no tenant before authentication and creates none that always runs (a create under a step condition may be skipped).Require authentication on the route, resolve the tenant in the flow before the dispatch, or dispatch from the flow that creates the tenant, with no condition on the steps that create it.JOB-TENANT-001
service_observability { health_liveness_path = "<path>" }A liveness path that is the path of a system endpoint the compiler already serves ("/" or "/health"): the container HEALTHCHECK needs a shallow probe of its own.declare health_liveness_path at a path no system endpoint serves (the default is "/health/live")LIVENESS-PATH-IS-A-SYSTEM-ENDPOINT-001
flow file_operation upload routeAn upload for an existing row whose route says neither in its path nor in its request which row the file belongs to.Add a path parameter to the route (POST "/documents/{id}") with addressing { id = Entity.id }.LOAD-KEY-UNDECLARED-001
flow step that takes rowsA take of rows after an entity that stands later in the module's lock order, when its key cannot be read before the method takes its locks.Take that entity's rows earlier in the flow, or name its key from the flow's input or a value read before any write to it.LOCK-TAKE-UNORDERABLE-001 (a limit of the compiler)
login route request fieldA password field on a login route declared shorter than the password policy's maximum, which is 128 (password String(72)).Declare every password request field as String(128) or wider.LOGIN-PASSWORD-BOUND-BELOW-POLICY-001
the request of a login route that checks a passwordA login request in which no field, or more than one, declares @field_purpose(password): no field of the request is known to be the password.Declare @field_purpose(password) on the one request field that carries the password, for example password String(128) @required @sensitive @field_purpose(password), and on no other.LOGIN-PASSWORD-INPUT-UNDECLARED
the request of a public login routeA login request that does not require exactly the principal's lookup field and its password field: one of them is not @required, or another field is.Mark the lookup field and the password field @required in the login's request and leave every other field of it optional.LOGIN-REQUEST-FIELDS-MISMATCH
a service that authenticates its own users and declares no login routeboth layersdeclare the public login route in api (lookup field + password in the request, access_token in the response), or a public flow that verifies the credential.LOGIN-ROUTE-UNDECLARED-001
an MFA enrolment flow whose create step links the factor to the principal through the store's principal keyThe QR account label would be the login identifier of a principal the caller did not prove to be, or of a principal this module does not hold.Write <principal key> = $context.user_id in the create step, or hold the request field to the caller with a validate step $input.<field> == $context.user_id.MFA-ACCOUNT-LABEL-UNRESOLVED-001
a second-factor enrolment route that declares response @entity(X) of an entity other than the store, or response @paginated(X)The enrolment creates one row of the second-factor store; an answer of another entity or a list describes something the route does not return.Declare response @entity(<store entity>) on the enrolment route, or no response to answer the one-time secret alone.MFA-ENROLMENT-ANSWERS-ANOTHER-SHAPE
a second-factor store answered by its enrolment route whose Read shows a field named secret, qr_code or issuerThe enrolment answers the row beside the one-time secret, qr_code and issuer; a row field of the same name would hide one of them.Rename that field of the store entity.MFA-ENROLMENT-FIELD-COLLIDES (a limit of the compiler)
a second-factor enrolment route that declares an inline response { ... }The enrolment answers the one-time secret, its QR code and the issuer; the compiler does not yet add the fields of an inline response to them.Declare response @entity(<store entity>) on the enrolment route, or no response to answer the one-time secret alone.MFA-ENROLMENT-INLINE-RESPONSE (a limit of the compiler)
a second-factor enrolment route with no response, beside a confirmation route that addresses the enrolment row by idThe enrolment answers only the one-time secret, so the client never learns the id of the row the confirmation addresses, and the factor can never be confirmed.Declare response @entity(<store entity>) on the enrolment route.MFA-ENROLMENT-ROW-NOT-ANSWERED
security mfa { policy policy_setting required_roles }A second-factor policy (who must hold one, for the application or per tenant): nothing refuses a session by policy yet.Remove policy, policy_setting and required_roles from mfa {}; a principal that enrolled a second factor is still asked for it.MFA_POLICY_PRODUCER_MISSING (a limit of the compiler)
service-root interactions { … payload { field Point|Polygon|Geometry } }A geometric value in a job payload: the job's JSON form cannot carry a shape yet.Send the row's id and read the shape in the task's flow.MONOLITH-LOCAL-ASYNC-PAYLOAD-GEOMETRY-UNSUPPORTED (a limit of the compiler)
service-root interactions { … payload_map { … } } fieldA job payload field mapped from a @sensitive field: the payload is stored with the job and sent in clear.Map the field to the row's id ($instance.id) and read the value in the task's flow.MONOLITH-LOCAL-ASYNC-PAYLOAD-SENSITIVE (a limit of the compiler)
service-root interactions { … payload_map { … } } field from $context or $resultA job payload field whose value the compiler cannot tell is or is not sensitive: the payload is stored with the job and sent in clear.Map it from $instance.<field> of the entity the triggering flow writes, or from a literal.MONOLITH-LOCAL-ASYNC-PAYLOAD-SENSITIVITY-UNKNOWN (a limit of the compiler)
a no_overlapping_interval guardNone of its match_fields is declared as a foreign key to an entity of this module whose rows can be locked (an @append_only entity's cannot), so two concurrent requests could both book the interval.Add to match_fields (and match_values) the field that references the row the interval belongs to, declared with @fk to an entity that is not @append_only.NO_OVERLAP_MATCH_NAMES_NO_PARENT
flow step expressionArithmetic (+ - * / // %) or an ordering comparison (< <= > >=) with a @nullable field, in a step's value, condition or validate, when nothing before it says the field has a value ($instance.due_at + $input.extra_hours with due_at nullable). Also the start or the duration of a no_overlapping_interval precondition read from a @nullable field.Say the field has a value first: <field> != null and ... in the same expression, or a step condition, or an earlier validate; or declare the attribute @not_null. == and != with a nullable field are accepted.NULL-OPERAND-001
flow step writing a key column from the request (mapping <key column> = $input.<field>, a create step with no mapping on a request that declares the column, or a create step whose mapping omits a column its route's request declares); in an upload flow, any key column but its storage_field on the one create the upload writes its stored key intoA step that writes a @field_purpose(object_key) column from the request: the client names the key, and can register the key of a file another caller stored.Declare file_operation { type = upload storage_field = "<key column>" } on the flow, so the server stores the file and produces the key, and remove the mapping of the key column from the step (a create step with no mapping, or whose mapping omits the column: map the column from a value that is not the request, or remove it from the route's request). In an upload flow, which writes its stored key only into its storage_field on one create, remove the key column's field from the request, or map it from a value the server produces.OBJECT-KEY-FROM-REQUEST-001
a column declared @field_purpose(object_key)No flow writes the column that holds a stored file's key.Declare file_operation { type = upload storage_field = "<column>" } on the create or attach flow, or a step that records a server-produced key.OBJECT-KEY-WRITER-MISSING
object_storage in a service that keeps its rows by tenant and whose users belong to no tenantboth layersgive the entity users sign in as its tenant with @tenancy(workspace, <field>) on an entity that declares @role(workspace), and put {tenant_id} first in the key layout; a layout without {tenant_id} does not scope the files to a tenant.OBJECT-STORAGE-FILES-UNSCOPED-001
object_storage whose key-holding entity declares two routes for the same action with different roles or permissionsboth layersgive the routes of the entity that holds the store's keys one set of roles and permissions per action (create, read).OBJECT-STORAGE-HOLDER-ACCESS-CONFLICT-001
object_storage with a document type that is not write_once, whose key-holding entity has no route granted deleteboth layersdeclare a DELETE route of the entity that holds the store's keys, addressed by its id, and grant delete on that entity in its policy to the roles that may remove a file (allow [delete] for [<ROLE>]); a file is removed with the row that holds it. Or declare the document types write_once = true when their files are never removed.OBJECT-STORAGE-HOLDER-DELETE-UNDECLARED-001
object_storage whose key-holding entity grants create or read by ownership (when ownership(<field>))both layersGrant the action on the entity that holds the store's keys by role or permission, without an ownership condition; storage routes scoped by ownership are not compiled yet.OBJECT-STORAGE-HOLDER-OWNER-SCOPE-001 (a limit of the compiler)
object_storage whose key-holding entity is @tenancy(user, <field>) or @platform_scope, in a service whose rows are isolated by tenanta file kept on a row that belongs to no tenant: the compiler removes a released file under the tenant of the row that held it, and does not yet remove one held by a row with no tenant.keep the file's key on an entity that belongs to a tenant (@tenancy(workspace, <field>)), for example a row that references the user-scoped or @platform_scope row.OBJECT-STORAGE-KEY-HOLDER-TENANTLESS-BY-DECLARATION-001 (a limit of the compiler)
object_storage whose key-holding entity declares no @tenancy, in a service whose rows are isolated by tenantboth layersdeclare @tenancy(workspace, <field>) on the entity that holds the store's keys, naming the field that references the tenant its row belongs to.OBJECT-STORAGE-KEY-HOLDER-UNTENANTED-001
object_storage whose key layout places a tenant, in a service whose users belong to no tenantboth layersin a service with no tenancy, remove {tenant_id} from path_prefix_template: each file is then reached under the rules of the row that holds its key. In a service that keeps its rows by tenant, give the entity users sign in as its tenant with @tenancy(workspace, <field>); a tenant_id field is not a tenancy.OBJECT-STORAGE-KEY-TENANT-WITHOUT-TENANCY-001
object_storage in a service that declares no authenticationboth layersdeclare how callers sign in: a security block with an auth_scheme other than none, its user_entity, and the public login route in api.OBJECT-STORAGE-ROUTES-NEED-AUTH-001
@field_purpose(object_key) on a columnThe module declares no object_storage block, so there is no store whose keys the column holds.Declare where the module keeps its files: a file_storage bucket, or a document_type in object_storage, named as the upload into the column names it; or drop @field_purpose(object_key) from the column.OBJECT_KEY_WITHOUT_OBJECT_STORAGE
object_storage in a service where several fields declare @field_purpose(object_key) and a document type is uploaded into none of them, or into two, or a field receives no upload, or one entity keeps keys in two of its fieldsboth layerstie each document type to one key field through its uploads: the upload names the type (upload_destination) and the field it records the key in (storage_field); give files uploaded into another field a type of their own, and remove @field_purpose(object_key) from a field no upload records a key in, or from the second key field of one entity.OBJECT_STORAGE_KEY_HOLDER_UNBOUND
object_storage in a service where no field declares @field_purpose(object_key)both layersdeclare the field that keeps a file's key on the entity the file belongs to: object_key String(512) @field_purpose(object_key); the files then follow that entity's rules (create to upload, read to download).OBJECT_STORAGE_KEY_HOLDER_UNDECLARED
api_call step with mode = async on a public routeAn async api_call in a flow whose route has auth_required = false, in a module that isolates its rows by tenant, when the flow resolves no tenant before authentication and creates none that always runs (a create under a step condition may be skipped).Require authentication on the route, resolve the tenant in the flow before the call, or make the call from the flow that creates the tenant, with no condition on the steps that create it.OUTBOX-TENANT-001
@hashed_from(<field>) on a password column that a flow also writesA password column whose @hashed_from(<field>) names one request field while a flow writes it with $computed.hash_password($input.<other>): the compiler does not choose between the two.Name the same request field in @hashed_from and in the flow's $computed.hash_password($input.<field>), or drop @hashed_from: the flow already says which field the hash comes from.PASSWORD-PLAINTEXT-CONTRADICTED
permissions { default_deny = false }Allow-by-default: permissions deny every request no declared grant covers.Remove default_deny = false; declare each access in permissions or policy.PERMISSIONS-DEFAULT-DENY-FALSE
the principal entity (security.user_entity or @role(user))a principal whose @pk is not a UUID named id: the service reads and mints the signed-in user's identity as a UUID id, and would not find its own user.Key the principal entity with id UUID @pk and keep its natural key as a @unique attribute.PRINCIPAL-KEY-UNSUPPORTED-001 (a limit of the compiler)
a service that requires authentication and does not name its user entity, names one that is not its own, or has several @role(user) entities and no user_entityboth layerssecurity { user_entity = "<Entity>" } or @role(user) on exactly one entity; auth_scheme = none when nobody authenticates; microservice_mode = true when another service does.PRINCIPAL-UNDECLARED-001
validations range boundA type = range rule on a field that is not a date or a date and time, whose bound is a $ reference: the field and the reference are values of different kinds.Write a number as the bound (range = "<= 100"), or compare the field in a flow validate step.RANGE-BOUND-NOT-A-NUMBER
validations range bound (date or date and time)A type = range rule on a date or a date and time whose bound is a $ reference other than $computed.now: only the current time is checked when a request arrives.Bound the field by $computed.now, or compare it in a flow validate step.RANGE-BOUND-NOT-PRODUCED (a limit of the compiler)
a flow step that writes <column> = $input.<field> into a column declared @field_purpose(password)A bare $input.<field> written into a password column: the column would store the password the client sent instead of its hash.Write <column> = $computed.hash_password($input.<field>) in that step.RAW-INPUT-INTO-PASSWORD-COLUMN
a reference to a tenant-scoped row on a route with no callerA flow whose route authenticates nobody and whose steps write a reference to a row of a tenant-scoped entity, unless the flow verifies a declared integration signature and creates exactly one row whose tenancy column names the tenant: nothing says which tenant the referenced row must belong to.Require authentication on the route; or verify the caller with a declared integration signature and write the created row's tenancy column from a request field or from a single-row read filtered only by request fields; or reference an entity that is not tenant-scoped.RELATIONSHIP-REFERENCE-TENANT-UNRESOLVED
@default on an optional request field, outside its own contractThe served contract of the field refuses its default: an omission would store a value no client may send.Declare a default inside the field's type, range, length, shape and members, or widen that contract.REQUEST-FIELD-DEFAULT-OUTSIDE-CONTRACT
@json_list on a request field written into a column that does not hold a list; @nullable on a request field written into a NOT NULL column; @pattern / @format on a request field whose column declares another shapeThe request field declares what the column it is written into contradicts: the write would refuse or lose the value.Declare the same on the column, or remove it from the request field.REQUEST-FIELD-JSON-LIST-CONFLICTS-COLUMN, REQUEST-FIELD-NULLABLE-INTO-NOT-NULL, REQUEST-FIELD-SHAPE-CONFLICTS-COLUMN
@json_list on a request field that is not Json; @min_length on a request field that is not a String or an Array; @min / @max on a request field that is not a number; @pattern / @format on a request field that is not a StringThe annotation bounds or describes a value of another type: the served schema has nothing to check on this field.Declare the annotation the field's type takes (@min/@max on Integer, Float or Decimal; @min_length on String or Array; @pattern/@format on String; @json_list on Json), or change the field's type.REQUEST-FIELD-JSON-LIST-ON-NON-JSON, REQUEST-FIELD-LENGTH-ON-WRONG-TYPE, REQUEST-FIELD-RANGE-ON-NON-NUMBER, REQUEST-FIELD-SHAPE-ON-NON-TEXT
@min_length on a request field above the length it can hold; @min / @max on a request field that, with its column's range, admit no valueThe request field's bounds and those of the column it is written into leave no value a client can send.Widen the bound on the request field, or on the column it is written into.REQUEST-FIELD-LENGTH-EMPTY, REQUEST-FIELD-RANGE-EMPTY
flow foreach over an Array(JSON) request fieldA loop over a request collection that uses an item whole, reads an item key it writes into no column, or writes one key into columns whose types, bounds or referenced rows differ: the item has no single contract to check.Write each key the item carries into its column ($item.<key>), one column per key or columns with the same type, bounds and reference.REQUEST-ITEM-CONTRACT-001
A request field named tenant_id on a route whose flow reads $context.tenant_idA request body field under the key the request's tenant travels in, when the flow's entity declares no tenancy column for it to travel in instead.Declare @tenancy(workspace, <column>) on the flow's entity, or rename the request field.REQUEST-TENANT-CHANNEL-COLLISION-001
a required reference to an entity whose rows nothing createsA created entity's required foreign key targets an entity no route, flow, reference row, bootstrap seed or compiler-written store creates, so no row of the referencing entity can be created.Declare the target's rows in reference_data {}, or a POST route or a flow step action = create (or upsert) with target = <Entity>.REQUIRED-REFERENCE-WITHOUT-ROWS
inline response { } fieldA declared field of an inline response that is both a column of the row the flow writes and a key of a calculate step's mapping { }.Rename the mapping key, or remove it and let the row's column answer.RESPONSE-FIELD-AMBIGUOUS-SOURCE-001
inline response { } fieldA declared field of an inline response that the row's entity declares @sensitive, or that hands over a secret the flow draws and also writes in the clear into a column.Remove the field from the response; write only the secret's digest.RESPONSE-FIELD-SENSITIVE-001
inline response { } fieldA declared field of an inline response that is neither a column of the row the flow writes nor a key of a calculate step's mapping { } (an earlier step's result_field of the same name does not fill it); on a route that mints a token pair, a field that is not one of the pair's.Add a last step action = calculate whose mapping { } names the field (<field> = $result.<result_field>), or remove the field from the response.RESPONSE-FIELD-WITHOUT-SOURCE-001
calculate step mapping { } keyA key of a calculate step's mapping { } in a flow whose route declares an inline response { } without that field.Declare the field in response { }, or remove the key from the mapping.RESPONSE-MAPPING-NOT-DECLARED-001
a single-segment $result.<name> read in a flow that answers a dict or upserts a rowNo step of the flow declares result_field = "<name>".Declare a calculate step with result_field = "<name>" and an expression, or read a name a step of the flow declares.RESULT_READ_UNDECLARED
role junction entityA junction that links the principal to two or more entities besides the tenancy scope, so nothing says which one is the role catalog.Declare @role(workspace) on the tenancy scope entity, or keep a single catalog foreign key on the junction.ROLE_CATALOG_AMBIGUOUS
role catalog entityA role catalog whose declared identity spans more than one column besides the tenancy scope; a role claim is one string.Declare the uniqueness over the tenancy scope plus one identifier column.ROLE_CATALOG_IDENTITY_COMPOSITE
role catalog entityA role catalog that declares no uniqueness, so no column identifies a role and two rows of one tenant may carry the same name.Declare @unique_together(<scope fk>, <identifier>) on the catalog.ROLE_CATALOG_IDENTITY_UNDECLARED
role junction entityA role junction whose role foreign key points at an entity this module does not declare, so require_role has no catalog table to join on.Declare the role catalog in the same module as the junction, or point the junction's role foreign key at a catalog the module declares.ROLE_CATALOG_NOT_IN_MODULE
@role(membership)Two or more entities declare @role(membership) and each assigns the principal a role catalog, so nothing says which one require_role joins on.Declare @role(membership) on the single junction that assigns roles, and @role(workspace) on the tenancy scope entity.ROLE_JUNCTION_AMBIGUOUS
role junction entityA junction with two or more foreign keys to the principal (member, inviter, …) whose @unique_together does not name exactly one of them as the member.Declare @unique_together(<scope fk>, <member fk>) on the junction.ROLE_JUNCTION_PRINCIPAL_AMBIGUOUS
an authenticated route in api with no permissions, or permissions = []A route that authenticates its caller and declares no authorization: any signed-in caller could call it, and permissions = [] grants no caller.Declare a policy allow line naming the roles for the entity it serves, permissions = ["<resource>:<action>"], or a validate step whose whole condition is $context.scopes contains '<scope>'; mark it @self_resource when the caller acts only on its own record, or set auth_required = false when the route is public.ROUTE-AUTHORIZATION-UNDECLARED
a route declaring response @entity(X) or @paginated(X) whose flow creates rows only of other entitiesThe flow loads no X for the route to return, or loads it more than once, and a row it creates of another entity is never what the route returns.Address the X on the route (addressing { <placeholder> = X.<key> }), load it with exactly one query step of X with the route's query_cardinality, or declare the route's response as the entity the flow creates.ROUTE-RESPONSE-ROW-MISSING-001
a route not declared public in a service with auth_scheme = noneA route of a service that authenticates no caller and is not declared public: who may call it cannot be enforced.Set auth_required = false on the route when it is public, or declare auth_scheme = jwt in the security block so its callers are authenticated.ROUTE-SERVED-WITHOUT-AUTHENTICATION
a flow that changes, deletes or reads one existing row and does not say whichNo route placeholder, the entity's declared key in the route's request, lookup step, foreach over rows of the entity or do{} filter on its declared key selects the row the flow works on.Declare a query step on the entity whose filter selects one row, address it on the route (addressing { placeholder = Entity.field }), iterate a source_query of the entity, or, in a foreach over keys, load each row in the do{} body with filter { <declared key> = $item }.ROW-LOAD-UNADDRESSED-001
broker_url_secret_ref with a scheme other than env://A service process cannot resolve that scheme yet.Declare the URL through an environment variable (env://NAME) for now.SAGA_BROKER_REFERENCE_HAS_NO_SERVICE_RESOLVER (a limit of the compiler)
broker_url_secret_ref on a saga brokerThe reference is empty, is not a typed secret reference, or names an environment variable that cannot exist.Declare the broker URL as env://NAME, with NAME of letters, digits and _, not starting with a digit.SAGA_BROKER_REFERENCE_UNTYPED
a saga stepA saga step cannot yet be bound to a flow or operation the service declares, so it has nothing to run.Remove the saga until its steps can name what they run.SAGA_STEP_HANDLER_NOT_EMITTED (a limit of the compiler)
tenant_scope on a job of an application of several servicesA job of an application of several services that declares tenant_scope: the platform's scheduled runs are not bound to a tenant yet. A single-service application runs its jobs, with their tenant scope, itself.Remove the job's tenant_scope attribute in the platform's jobs {}, and keep the job's flow to rows it can reach without a tenant.SCHEDULED_JOB_PRODUCER_MISSING (a limit of the compiler)
a create step, in a flow whose route requires no sign-in, on an entity with an @scoped field or a reference to oneA row written before anyone is signed in whose scoped field the step leaves unset, or whose reference names a record the same flow does not create: no value it could be seen with exists, so it is never saved.Set the scoped field in the step, or declare the role the record is written with scopes = ["*"] in platform_roles { }: at the root of the spec of a monolith, inside platform { } of a microservices application; set a reference to a record the same flow creates first.SCOPE-WRITE-BEFORE-SIGN-IN-UNBOUND-001
when <condition>(field), across_owners on a grant with no tenant_isolation condition, on an action other than read or list, or for a role no referenced entity limits to the rows it ownsA grant that declares a role reads across owners where no parent limits the role to its own rows, or where the grant does not read the tenant's rows.Remove across_owners, or declare it on a read or list grant with when tenant_isolation(<field>) for a role a referenced entity limits to its own rows.SECURITY-POLICY-ACROSS-OWNERS-001
policy allow [<action>] for [ROLE] with no condition, on an entity whose policy grants ROLE read or list only when ownership(field) or when tenant_isolation(field)An action other than create that reaches rows the role may not read: the role changes or takes rows of other owners or tenants.Grant the action with the read's condition (when ownership(field) or when tenant_isolation(field)), or grant the role read on every row when it may act on every row.SECURITY-POLICY-ACTION-ROW-SCOPE-001
@fk(Parent.key, attribution: true) on a column that a read or list grant reads when ownership(column) or when tenant_isolation(column), or with on_delete: cascade or on_parent_terminal: settledA reference that says the row is only attributed to the row it names, while another declaration says the row belongs to it.Remove attribution: true, or remove the declaration that contradicts it.SECURITY-POLICY-ATTRIBUTION-CONTRADICTION-001
policy allow [read|list] for [ROLE] on an entity with a reference to an entity whose policy grants ROLE only when ownership(field) or when tenant_isolation(field)A grant that lets the role read the rows of the referencing entity beyond the rows its parent limits it to: the role reads the rows that belong to parent rows it may not read.Declare on the referencing entity the column that holds the owner (or the tenant) and grant the role with when ownership(<that column>) (or when tenant_isolation(<tenant column>)): an entity's tenancy alone does not narrow the grant. Or grant the role every row of the parent as well. A column that only names who or what the row is attributed to declares @fk(Parent.key, attribution: true); a role whose duty is reading every row of its tenant is granted when tenant_isolation(<tenant column>), across_owners; a row that belongs to its parent, read by a role with no such duty, keeps this refusal.SECURITY-POLICY-CHILD-ROW-SCOPE-001
policy allow ... when team(field), or when tenant_isolation(field) on a field the entity's tenant scope does not filter onA condition no part of the compiled service enforces on the rows: team membership, or tenant isolation on a field other than the entity's tenant column. The role it names would reach every row, not only the ones the condition names.Grant the role without the condition, scope the rows by ownership(field) on a reference to the account entity, or name in tenant_isolation(field) the column the entity's @tenancy declares.SECURITY-POLICY-CONDITION-UNENFORCED-001
policy allow ... when ownership(field)An ownership rule on a field that does not hold the signed-in account's identity: a field the entity does not declare, or one that is not a reference to the account entity's primary key.Name a field of the entity declared as a reference to the account entity's primary key; on the account entity itself, its primary key.SECURITY-POLICY-OWNER-SCOPE-001
required reference (many_to_one, not nullable)Required references that form a loop, an entity's required reference to itself included: no row can be written first.Make one reference in the loop optional.SEED-CYCLE-001
field @defaultA literal @default that the field's own declaration refuses: its type, its length, its @pattern or the pattern its @format imposes (@format(uri) @default("not a url")).Declare a default the field accepts, or remove the @default.SEED-DECLARED-DEFAULT-001
test rows under declared rules, guards and uniquenessRules that leave no room for a test row: flows that could each have created it with different counters, a guarded sum its field's scale cannot hold, two guards asking one field for different sums, no user a guard admits, unique values fewer than the rows, or a row of the second test tenant that needs a row outside it.Widen the field's values or scale, make the reference optional, or add the seed examples the rule needs; the refusal names the row and the rule.SEED-LIMIT-ARRANGE-001 (a limit of the compiler)
membership, workspace and role entitiesA membership entity without one reference to the user entity and one to the workspace entity, more than one workspace or membership entity, or a role, assignment or permission entity with a required reference the security block does not name.Give the membership entity one reference to the user entity and one to the workspace entity, keep one workspace and one membership entity, and make other references of the role entities optional.SEED-LIMIT-MEMBERSHIP-001 (a limit of the compiler)
flow steps that write counters, states or summed fieldsA flow whose writes cannot be read back on a test row: counters it cannot replay, a state set from an expression, or a sum over rows whose summed field takes a default.Write counters and states from a literal or a field of the row, and give the summed field a value in the seed examples.SEED-LIMIT-REPLAY-001 (a limit of the compiler)
security block, the user entity's sign-in fields and its password storeA user entity whose sign-in field is not @unique, has no single sign-in or password field, names an active field it does not declare, or starts in a state in which sign-in is refused; or a password store (@role(credential)) that is not one: several stores, several password fields or references to the user, a relationship to the user that is not many_to_one or one_to_one, or a credential_type_field no store has.Mark the sign-in field @unique, name it with user_lookup_field, keep one password field, and give the user an initial state in which sign-in is allowed. Keep one password store with one password field and one reference to the user, or name in security a credential_type_field only that store has.SEED-LOGIN-001
roles and the field that holds a user's roleA role field that is not an enum of the declared roles, two fields that could hold the role, roles with no most privileged one, or per-tenant roles on a user with no tenant field.Hold the role in one enum field whose values are the declared roles, give one role every permission, and keep roles, grants and users per tenant together.SEED-ROLES-001
entity validations ruleA rule that reads a field its entity does not declare ($instance.<field> naming no field of the entity).Name a field the entity declares, or declare the field on the entity; the refusal lists the entity's fields.SEED-ROW-RULE-READS-UNDECLARED-FIELD
entity @check / validations ruleDeclared rules of one entity that no row can satisfy together: a strict order that closes on itself (@check("b > a") with @check("a > b")), or conditions on Boolean and Enum fields that no combination of their values meets.Correct the rule that does not say what the entity means; the refusal names the rules and the fields they read.SEED-ROW-RULES-CONTRADICT
entity @check / validations rule (seed row)A rule the seed cannot evaluate on a row it writes: one that calls a function the seed does not evaluate (len(...)), or reads the caller ($context.actor_tenant_id), which a seed row has none of.State the rule with comparisons over the row's own fields, or check the caller in the flow that serves the request.SEED-ROW-VALIDATION-UNDECIDABLE (a limit of the compiler)
a reference to the session store the compiler addsAn entity with a reference to the session store the compiler adds.Declare the store in sessions { refresh_store { ... } }, or remove the reference.SEED-SAMPLE-001
field @seed_templateA @seed_template whose values the field's own declaration refuses: another @format (@format(uuid) @seed_template(url)), a length or a @pattern the template's values do not fit.Remove the @seed_template, or choose the one whose values the field accepts.SEED-TEMPLATE-CONFLICT-001
state machine transitionsA flow that creates rows from a parent in a state the parent's state machine has no transitions to reach.Declare the transitions the flow relies on.SEED-TRANSITION-001
security { sessions { session_store | refresh_store } } entityA required column of the store that the login writes no value to.Make the column @nullable, give it a @default(…), or bind it in the store.SESSION-CONTRACT-MINT-COLUMN-UNBOUND-001
a flow that decides on a set of rows and then writesNothing declared serializes the decision with a concurrent request that adds a row to the same set.Declare one of the matched fields with @fk to an entity of this service, or declare them unique (@unique / @unique_together).SET_DECISION_ON_ADDED_ROWS_HAS_NO_SERIALIZER
endpoint path (the address of a route the compiler serves itself)An endpoint whose method and path differ from a route the compiler serves itself (sign-in, audit-trail read, stored files, probes) only in the names of their path parameters: both would answer the same requests.declare the endpoint at a path no compiler-owned route serves, or at the route's exact path to have the compiler serve itSIDE-CHANNEL-ROUTE-COLLISION-001
state_machine (several fields of one entity)state_machine blocks on more than one field of the same entity: one machine per entity is built, and the others would be dropped.Keep one state machine on the entity and give each other lifecycle its own entity.STATE-MACHINE-SECOND-FIELD-UNLOWERED-001 (a limit of the compiler)
a state write through a transition with @roles on a route with no callerA flow whose route declares auth_required = false (or whose service authenticates nobody) and that writes a state field to a target reached by a transition declaring @roles(...): no caller exists whose role the transition could check.Require authentication on the route, or write a target whose incoming transitions declare no @roles.STATE-MUTATION-ROLE-PRINCIPAL-MISSING
a flow writing into a state whose @guard reads $contextThe flow has no route, or its route does not require authentication, so there is no caller to check the guard against.Require authentication on the route that triggers the flow, or compare the row with $instance and $computed only.STATE_MACHINE_GUARD_CALLER_UNAUTHENTICATED
state_machine @guard(STATE)A @guard(STATE) without both condition and error, on a state no transition enters, or whose condition reads anything but $instance, $computed and the authenticated caller's identity ($context.user_id).Declare condition = <expression over $instance> and error = "..." on a state some transition enters; to compare the row with the caller, read $context.user_id.STATE_MACHINE_GUARD_REFUSED
a flow writing the field of a machine with a @guardThe value written is neither one of the machine's states nor a request field, so the guards it answers to are not declared.Write one of the machine's states, or the request's field.STATE_MACHINE_GUARD_TARGET_UNDECLARED
a transition into a state whose @guard no row can meetThe guard is read on the row before the write, and every row in the source state holds values the guard refuses.Check what the transition must establish as a rule of the entity (@check), which reads the row after the write, or write the column the guard needs before the transition.STATE_MACHINE_GUARD_UNSATISFIABLE_ON_EDGE
a step moving the rows its filter selects to a stateThe filter does not bound the state column, so a selected row in a state with no declared edge into the target refuses the whole request.Add the state column to the filter for the states that move, one step per state.STATE_WRITE_OVER_UNBOUNDED_ROWS
flow step tx_policytx_policy = new or tx_policy = none on a flow step: every step of a flow runs in the flow's one transaction, and the step would not run as declared.Remove tx_policy from the step, or declare tx_policy = join.STEP-TX-POLICY-UNLOWERED-001 (a limit of the compiler)
security rate_limit { login_attempts_setting }A login lockout threshold each tenant sets for itself: the login reads only the application's login_attempts yet.Remove login_attempts_setting; login_attempts applies to every tenant.TENANT_LOGIN_ATTEMPTS_PRODUCER_MISSING (a limit of the compiler)
A tenancy column of the principal, or an @scoped claim, named like a claim the access token already carries (sub, exp, type, role, roles, permissions, session_id, step_up_verified, jti)One JWT claim cannot carry two values: the second writer would overwrite the first in every token the service mints.Rename the tenancy column or the @scoped claim attribute.TOKEN-CLAIM-NAME-COLLISION-001
An audited token store with no tenant column, on a module with row-level isolationThe audit table is tenant-isolated and every audit row carries its tenant, read off the store row; this store has no tenant column to read.Give the store entity @tenancy with a tenant column, or stop auditing the store.TOKEN-STORE-AUDIT-TENANTLESS-001
@otp_codeMore than one @otp_code attribute on the MFA entity: the compiler cannot tell which one records the last accepted code.Mark only the attribute that records the last accepted code with @otp_code.TOTP-REPLAY-CARRIER-AMBIGUOUS-001
@otp_codeA step that verifies a TOTP code against an MFA entity with no @otp_code attribute: nothing records the last accepted code, so the same code could be accepted again for the rest of its window.Declare on the MFA entity the attribute that records the last accepted code, String(N) with N = mfa.code_digits, and mark it @otp_code (last_used_code String(6) @nullable @otp_code).TOTP-REPLAY-CARRIER-MISSING-001
security.mfaA module that verifies TOTP codes against its MFA entity and neither declares security { mfa { } } nor provisions the secret it checks: no declaration says which digits, time step, algorithm and window the code was issued under.Declare security { mfa { enabled = true; method = totp } } on the module, with code_digits, interval_seconds, algorithm and valid_window when the secret was provisioned with other parameters.TOTP-VERIFY-PARAMETERS-UNDECLARED-001
@triggers on a state-transition endpointA state-transition flow served at an endpoint on which its entity's state machine declares no trigger, or that names no endpoint: no declaration says which state the request moves the row to.Annotate the endpoint the flow is served at with @triggers(<Entity>.<state field> -> <STATE>), naming a state the machine declares, or serve the flow at an endpoint that carries one.TRANSITION-TARGET-UNDECLARED
foreign key on_deleteA foreign key that restricts deleting its source (default restrict, or no_action) on a row a flow creates every time that source is created: the source's DELETE route can never succeed.Declare @fk(<Source>.id, on_delete: cascade) (the row follows its source) or on_delete: set_null.TRIGGERED-ROW-RESTRICTS-SOURCE-DELETE
upsert stepAn upsert whose mapping does not state every column of the key it matches rows by (the first @unique_together, else the first @unique, else the primary key).Add the missing columns to the step's mapping, or declare the key the upsert should match with @unique / @unique_together on the entity.UPSERT-CONFLICT-KEY-UNSET-001
flow validate step conditionA validate condition DevMatrix does not support yet, such as contains on a $context value other than the whole condition $context.scopes contains '<scope>'. It is a limit of DevMatrix, not a defect in the spec.To require a scope, make the whole condition $context.scopes contains '<scope>'; the route checks it. Otherwise declare a precondition { kind = ... } block on the validate step, or add a query step before it that reads the value and compare $result in this condition. Do not delete the validate step: the flow would then run without the check.VALIDATE-GUARD-NOT-LOWERED-001 (a limit of the compiler)
validations custom ruleA custom rule whose condition names, bare, something that is not a field of the rule's own entity.Name a field the entity declares, or write $instance.<field>; a field of another entity is not a value of this row.VALIDATION-RULE-NAME-NOT-A-FIELD
a flow that names a webhook_receiver whose endpoint's request does not declare the receiver's event_fieldboth layersdeclare the field event_field names in the request of the endpoint that triggers the flow (<event_field> String(N) @required); the route reads the event type from it and refuses fields the request does not declare.WEBHOOK-RECEIVER-EVENT-FIELD-UNDECLARED-001
a flow that names a webhook_receiver and is not triggered by a routeboth layerstrigger the flow with trigger = "POST <path>" and declare that endpoint in api; a job, an event or no trigger cannot receive a delivery.WEBHOOK-RECEIVER-FLOW-UNROUTED-001
a flow that names a webhook_receiver on a route that is not POSTboth layerstrigger the flow by POST on an endpoint api declares as POST; the trigger must name a declared endpoint with the same method and path.WEBHOOK-RECEIVER-METHOD-NOT-POST-001
integration with type = webhook_receiverA webhook receiver: the receiving route accepts third-party deliveries, and the generated tests do not yet prove it for every spec.Remove the integration and the flows that receive through it.WEBHOOK-RECEIVER-NOT-PRODUCED-001 (a limit of the compiler)
a webhook_receiver integration that no flow names at flow levelboth layersadd integration_ref = "<receiver>" to the flow that receives the deliveries, next to its POST trigger; a signature check in a step does not bind the route.WEBHOOK-RECEIVER-ROUTE-UNBOUND-001
endpoint with is_websocket = trueA WebSocket endpoint whose matching transport was lost or duplicated while compiling.Do not change the spec for this message. Contact DevMatrix support.WEBSOCKET-ENDPOINT-NOT-PRODUCED-001 (a limit of the compiler)
WebSocket endpointA declared socket protocol, policy or event delivery that DevMatrix does not support yet.Keep every access rule as declared (policy, @tenancy, @sensitive, permissions, the module's authentication): none of them is the part to change. Follow the sentence of the message that names the endpoint attribute, or serve this data over an HTTP endpoint and remove or postpone the WebSocket endpoint; kept as written, the endpoint stays refused until DevMatrix supports it.WS-CAPABILITY-NOT-PRODUCED-001 (a limit of the compiler)
WebSocket endpointA socket missing explicit limits, subscriber authority or a typed event binding.Declare the named endpoint attribute and its referenced event fields.WS-DECLARATION-001
WebSocket endpoint (is_websocket = true)A WebSocket endpoint in a module that authenticates nobody; in a tenant-scoped module, one whose subscription params omit the principal's tenancy column; one that names a token domain the module does not declare or that is not the one covering its path; or one bound to a command that declares a precondition, a transition or a side effect, which a subscription never runs.Declare the module's authentication and user entity; add the tenancy column to subscription_params; name the domain whose route_prefixes cover the path, or omit auth_type; bind only a command that names its entity and verb, and move what it executes to an HTTP endpoint.WS-HANDSHAKE-001
WebSocket endpointA valid socket declaration that DevMatrix lost while compiling.The failure is DevMatrix's, not the spec's: do not change the spec for it.WS-LOWERING-001 (a limit of the compiler)
permission keyA permission key with a hyphen, an upper-case letter or a space in any segment (work-orders:read).Lower-case letters, digits and underscores, each segment starting with a letter (work_orders:read).«Invalid permission_key format»
route under permissionsA route guarded only by a permission, on an entity that has a role policy, when no allow line of that policy names the route's action and a role the policy never names holds the permission.Add the route's action to an allow line of the entity's policy for each role meant to reach the route.RBAC-POLICY-WIDENING
endpoint permissionsAn endpoint permission that no role can acquire: no policy allows its action to any role, the principal declares no permissions field, and no role-permission junction is declared. Every caller would get 403.Allow the route's action to at least one role in the entity's policy (allow [<action>] for [ROLE]); for a custom route whose last segment is not a plain name, bind a command whose verb the policy allows. Or declare the role-permission junction.DIRECT_ROLE_PERMISSION_AUTHORITY_INCOMPLETE
flow triggerA flow whose trigger is state_change(Entity.field -> VALUE): the grammar accepts it and nothing runs the flow yet.Put the work in a step of the flow that writes the state, or trigger the flow with job("…") or event("…").FLOW-TRIGGER-UNDISPATCHED-001
state-machine fieldA state-machine field written from a route that is addressed on another entity: the transition gets no trigger, and what depends on it stops later with a message that does not name this cause.Move a state field through a route whose addressing binds a placeholder to the entity that owns the state machine.«no trigger can express. Not minted» (a log line, no refusal)
DevMatrix DMX Language Reference. Built for developers who compile, not configure.