Examples
Event Streaming
What this example shows
Every transition emits a typed event. This example shows how to subscribe, persist an audit stream, and reconstruct a timeline from transition history for replay and debugging.
Loop diagram
1START ----> TRANSITION_1 ----> TRANSITION_2 ----> TERMINAL2 | | |3 +---- emit events on every transition ----+Actors
| Actor | Type | Transitions | Guards | |---|---|---|---| | runtime emitter | automation | all runtime transitions | loop-defined guards | | subscribers | automation | none (read-only stream consumers) | n/a |
Key annotated snippet
1"cmt">// @no-typecheck2import { LOOP_EVENT_TYPES } from "@loop-engine/events";3import { buildTimeline, replayLoop } from "@loop-engine/observability";4import { aggregateId } from "@loop-engine/core";5 6const audit: Array<{ at: string; type: string; aggregateId: string }> = [];7 8eventBus.subscribe(async (event) => {9 if (10 event.type === "loop.started" ||11 event.type === "loop.transition.executed" ||12 event.type === "loop.completed"13 ) {14 audit.push({15 at: event.occurredAt,16 type: event.type,17 aggregateId: String(event.aggregateId)18 });19 }20});21 22const id = aggregateId("EXP-1");23const instance = await engine.getState(id);24const history = await engine.getHistory(id);25if (instance) {26 const timeline = buildTimeline(instance, history);27 const replay = replayLoop(definition, history);28 console.log(timeline.durationMs, replay.valid);29}What emitted events look like
1{2 type: "loop.transition.executed",3 loopId: "expense.approval",4 aggregateId: "EXP-1",5 transitionId: "approve",6 fromState: "PENDING_APPROVAL",7 toState: "APPROVED",8 actor: { type: "human", id: "manager@acme.com" },9 occurredAt: "2026-03-13T12:57:01.440Z"10}Try it yourself
1cd loop-examples/event-streaming2pnpm install3pnpm dev