Behavior and change
An App declares its behavior as named handlers on itself or on a Template. A Query reads and returns declared output. A Mutation writes and may publish Events. A Listener reacts to an Event after it is appended. An App Hook runs when a Workspace is created or seeded. Each kind receives a context that permits exactly what it may do.
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface ApproveInput { readonly id: string;}
export const expensesApp: AppSpec = (app) => { app.configure('expenses');
const report = app.addTemplate('report'); report.addProperty('totalCents', 'integer');
const claim = app.addTemplate('claim'); claim.addProperty('amountCents', 'integer'); claim.addProperty('approvedAt', 'datetime');
const draft = claim.addState('draft').setDefault(); const approved = claim.addState('approved'); draft.addTransition('approve', approved);
const claimApproved = claim.addEvent('approved'); claimApproved.addListener('stamp', async (_event, item, _current, ctx) => { await item.updateProperties({ approvedAt: ctx.now }); }); report.addParentListener('tally', claimApproved, async (_event, parent, child) => { const amount = child.properties.amountCents; const total = parent.properties.totalCents; await parent.updateProperties({ totalCents: (typeof total === 'number' ? total : 0) + (typeof amount === 'number' ? amount : 0), }); });
app.onCreate(async (prev, current, ctx) => { const workspace = await ctx.getWorkspaceItem(); await workspace.createChild(current.templates.report, { key: 'current', properties: { totalCents: 0 } }); await prev(); });
const approve = app.addMutation('approve', async (input: ApproveInput, current) => { const item = await current.templates.claim.getItem(input.id); if (item === undefined) throw new Error('Claim not found'); if (item.state?.value !== 'draft') return; // A retry after a conflict lands here const updated = await item.state.transitions.approve.execute({}); await updated.events.approved.publish({}); // Listeners run after this write commits }); approve.input.addProperty('id', 'id').mandatory(); approve.output.void();
const total = app.addQuery('total', async (_input: Record<string, never>, current, ctx) => { const item = await ctx.getItemByKeyPath('current'); if (!current.templates.report.isType(item)) return 0; const value = item.properties.totalCents; return typeof value === 'number' ? value : 0; }); total.output.value('integer');};Queries and Mutations
Section titled “Queries and Mutations”An operation has a key, a handler (input, current, ctx), a declared input and a declared output. input is parsed against the declared Properties before the handler runs. current is the App the operation belongs to, so current.templates.claim resolves without a PRN. ctx is the execution context.
A Query is declared with addQuery and runs in a read execution. Its ctx is a ReadRuntimeInstance: it reads Items, follows Relations and runs selectors, and it cannot update an Item or publish an Event. A Mutation is declared with addMutation and runs in a write execution. Its ctx is a WriteRuntimeInstance, which adds creating and updating Items, executing transitions and publishing Events. Both kinds carry Grants: a principal calls an operation only when one of its Roles holds a Grant on it.
Prefer a Mutation for every intentional change a caller makes, and a Listener for every consequence of that change. The Mutation states what happened; the Listeners decide what follows.
Events and current state
Section titled “Events and current state”An Event is a named occurrence declared with addEvent on an App, a Template or a Union. A Template Event is published against an Item of that Template; an App Event is published against the Workspace Item. Each Event carries a payload parsed against its declared input Properties, the Identifier of its Item and the principal that caused it. An Event raised while processing another Event also carries the lineage back to the first.
Events form a durable history alongside current Item state. Alpyne does not rebuild state by replaying history: the Item is authoritative for what is, and the Event history is authoritative for what happened. A Mutation therefore changes the Item and publishes the Event as two explicit steps in one write execution, as approve does.
An Event has two publishing modes on WriteEventPublishInstance. publish appends the Event for asynchronous processing; its Listeners run after the write commits, each in a write execution started by the reactor. immediate appends the Event and runs its Listeners inline, inside the active execution, before the call resolves. A Listener error during immediate propagates to the caller and stops the remaining inline Listeners. An error the caller does not catch fails the execution and discards its writes. Awaiting publish awaits the append, not the Listeners.
Prefer publish. It keeps the Mutation’s transaction short and lets each Listener fail and retry on its own. Use immediate only when the caller must observe the Listener’s writes before it returns.
Listeners, parent Listeners and App Hooks
Section titled “Listeners, parent Listeners and App Hooks”A Listener is registered on an Event with addListener(key, handler). The handler receives (event, item, current, ctx): the Event, the Item it was published against, the App that owns the Listener and a write context. A parent Listener is registered on a parent Template with addParentListener(key, childEvent, handler) and receives (event, parent, child, current, ctx). When a child Item publishes the Event, the reactor walks up the child’s ancestors and invokes each matching parent Listener in turn. In the example, report.tally runs whenever a claim beneath it is approved.
A Listener runs as system in the Event’s Workspace. It reads the payload, changes Items and publishes further Events; those Events carry the lineage, and the Runtime bounds the chain depth. addChildEvent on an Event declares the Events its Listeners publish, and the Builder rejects a declared cycle. To roll a change upward, publish an Event against an ancestor of the original Item. A parent Listener is the shortcut when the parent needs no Event of its own.
An App Hook is a lifecycle Listener: onCreate runs when a Workspace is created for the Definition, onSeed when it is seeded. The handler receives (prev, current, ctx) with a SystemWriteRuntimeInstance, which adds seed, seedId and selectEvents. Hooks form a chain across imported Apps, and await prev() runs the rest of the chain. Where you place that call decides whether your hook runs before or after the Apps you import.
State machines
Section titled “State machines”A state machine is declared on a Template with addState. One state is marked setDefault(); a new Item starts there unless createChild names another state marked setInitial(). addTransition(key, to) on a state declares a directional move to another state of the same Template. Loops are permitted, and two transitions between the same states are permitted when their keys differ. A transition carries its own Grants, so who may move an Item is declared next to the move.
At run time item.state?.value is the current state and item.state.transitions.<key>.execute({}) performs a move. The Runtime executes the transition atomically against the declared source state. The Item must still be in the from state at the moment of the write, or the call fails with a StateTransitionConflictError and changes nothing. Two concurrent approvals therefore produce one approval and one conflict, never two. The Runtime classifies that conflict as transient and retries the execution once by default, so the second attempt sees approved and approve returns without acting. execute returns the updated Item; the reference you held before it is stale.
A transition changes state; it does not publish an Event. Declare the Event that names the business fact and publish it from the Mutation after the transition succeeds, as approve does with approved. The state machine stays a pure constraint, and the Event history stays a pure account of what happened.
Boundaries
Section titled “Boundaries”- A Query does not publish Events or change Items.
- A Mutation returning does not mean its Listeners have run or its Metrics have updated.
- A Listener for a published Event does not run inside the Mutation. It runs in its own execution, after commit, as
system; onlyimmediateruns Listeners inline. - A transition is not an Event. Publishing the matching Event is the Mutation’s job.
Related
Section titled “Related”- Add queries and mutations to add a Mutation and a Query with typed input and output.
- Handle events to register Listeners, parent Listeners, schedules and App Hooks.
- Add states and transitions to declare states, transitions and their Grants.
- Execution model for what commits when and what a retry means.
- Events for the normative rules on origin, lineage and depth.

