@sewdn/workflow-runtime
v0.1.1
Published
The workflow runtime: the command pipeline over the engine, the stored event envelope, the ports of the runtime as Effect services, and the shared adapter test suite.
Readme
@sewdn/workflow-runtime
The workflow runtime: the command pipeline that runs the engine's commands over the ports, the envelope every stored event has, the ports as Effect services, the orchestrator port with its outbox adapter, and the test suites every adapter must pass. The ports see events and states as opaque JSON; the engine owns their schemas.
Built on effect 4.1.4. Runs in browsers, Node and Bun: no platform API is used.
The envelope (src/envelope.ts)
| Field | Schema | Set by |
| --------------- | --------------- | ------------------------------------------------------------ |
| id | EventId | the store, a ULID from Clock and Random |
| stream | StreamId | the store: run/<id>, definition/<id>, workspace/<id> |
| sequence | positive int | the store: 1-based, gapless per stream |
| type | EventType | the caller: run.task-completed |
| version | positive int | the caller: the payload's schema version |
| payload | Schema.Json | the caller |
| recordedAt | Instant | the store, from Clock |
| actor | Actor | the caller: { kind: "person" \| "system" \| "plugin", id } |
| commandId | CommandId | the caller |
| causationId? | EventId | the caller, when a reaction issued the command |
| correlationId | CorrelationId | the caller, constant across a chain of reactions |
A caller appends NewEvents (the caller's fields); stampEvents validates a batch and adds the rest, and
every adapter's append goes through it. A subscription delivers PositionedEvents: the event with its
global position, the store's commit order across all streams.
Ports
| Port | Operations |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| EventStore | append(stream, expectedSequence, events), read(stream, range?), subscribe(filter), streams(prefix) |
| SnapshotStore | save(stream, sequence, version, state, keep?), latest(stream, { atMost?, version? }), discardAfter(stream, sequence) |
| ReadModelStore | put(model, key, value), get(model, key), query(model, { where?, keyPrefix?, limit? }), remove(model, key), clear(model) |
| CommandLog | record({ commandId, command, outcome }), find(commandId) |
| Outbox | enqueue(entry), take(max, { leaseMillis? }), acknowledge(id), retryLater(id, at) |
| Scheduler | schedule(timerId, dueAt, command), cancel(timerId), claim(now, leaseMillis?) |
| Notifier | deliver(notification) |
| Directory | person(id), search({ text, limit? }) (groups of people are World.groups, written by setGroup) |
Each port is a Context.Service; an adapter is a Layer that provides it. The doc comment on every
operation states what an adapter must guarantee, and the suite tests exactly that. The errors are tagged
(SequenceConflict, StreamNotFound, InvalidEvent, StoreUnavailable, StorageFull,
OutboxEntryNotFound, NotificationRejected), each a code with parameters. Every operation
that writes may fail with StorageFull (WriteError = StoreUnavailable | StorageFull): the store had no room,
and the write was undone. Scheduler.claim leases what it hands out, as Outbox.take does, so timers fire
in one process when several poll one store.
Effect's Persistence and PersistedQueue (in effect/persistence, unstable) do not replace these ports:
Persistence caches request results by key and cannot answer "the latest snapshot at or below sequence N"
or "discard after N"; PersistedQueue hands out one element at a time to a scoped handler and owns the
retry policy, where the runtime needs to take a batch, acknowledge, and choose the retry time itself. They
remain options for implementing an adapter (a key-value or SQL backing), behind these ports.
The command pipeline (src/pipeline/)
Snapshot retention. A snapshot is a shortcut; the fold of the events is the truth. save keeps the newest
keep snapshots of the stream (default 1) and removes the older ones in the same write; the runtime passes
snapshotsKept. A rollback to a point older than every kept snapshot folds from the start: a longer fold, never a wrong state.
WorkflowRuntime is a Context.Service; layer(config) builds it over EventStore, SnapshotStore,
ReadModelStore, CommandLog and Directory. config names the workspace, its genesis world (what no event
made: definitions, groups, series meetings a host puts in place), and optionally the rights (can, default the engine's rightsCan()), the
validator, the words of the broadcast's log lines and outcomes (history, a HistoryCatalog, default English), the snapshot interval (snapshotEvery, 100) and how many snapshots a stream keeps (snapshotsKept, 1), the number of conflict retries, the query gates and the clock. An application's
rules on a command's effect are command checks of its own plugin, which the engine runs inside the decision.
The stock rule grants capabilities through version seats and explicitly configured roles. A capability with no
applicable seat right or role grant is refused.
The clock. The runtime reads the instant (a decision's now, the envelope's recordedAt, event ids) from Effect's
Clock. An Effect host provides one as usual (a TestClock under test). A host without Effect passes
now: () => number (epoch milliseconds) in the configuration: every operation of the runtime then runs on a clock
that tells it, whatever fiber calls the operation (sleeping and monotonic time stay with the clock it replaces).
Streams. The engine folds one World: ids come from one counter in it, and commands read across runs,
ad-hoc tasks, document versions and series meetings. Until those aggregates are separated, a workspace is one
stream, workspace/<workspaceId>, and every command writes it. The choice is made in one function
(streamFor in runtime.ts). A commit is the events one command appended (one command id); a rollback
appends the engine's stream.rolled-back event and names a commit's end. The caller needs the workspace
capability workflow.rollback. The runtime checks it against the current world before returning a repeated
outcome or appending the event. External actors cannot roll back.
Plugin data. A plugin's events (<plugin>.<fact>, version 1) are in the workspace stream, in the commit of the
command that made them; its state is world.plugins[<id>], folded by the engine, so snapshots, rollback, seed and the
simulation carry it with no code of their own. There are no streams of a plugin's own until the event store appends
to several streams atomically. A snapshot is saved and read under a version that combines FOLDED_VERSION with the
installed plugins with state and their state versions (pluginStateKey, snapshotVersion); a snapshot made under
another list is not read, and the stream is folded from the start.
execute(command, { actor, commandId, correlationId?, causationId? }), one command at a time per stream
in a process (one Semaphore per stream: PartitionedSemaphore shares one capacity among keys and is no lock
per key):
- catch up: fold what other writers appended; project and record whatever the read models and the command
log have not seen (a crash between
appendand their update); - the command log: a known command id answers its first outcome (
repeat: true), another command under it fails withCommandIdReused; - load: the newest snapshot the projections have passed, then the events after it;
decision(world, command, env)withnowfromClockand the people fromDirectory(roles,external): an engine command, or a plugin's ({ name: "<plugin>.<name>", input }, with its chained engine commands, all one batch), then every plugin's command checks; a refusal (plugin.*,command.vetoed, an engine code) fails withCommandRefused { refusal }and stores nothing. A plugin command's value is JSON, encoded by its value schema (ExecutedValue<C>);appendwith the loaded sequence; onSequenceConflictthe whole pass runs again, at mostconflictRetriestimes;- record the outcome, project the read models, move the checkpoint, and snapshot by the policy.
runtime.changes(after?) opens a scoped subscription and returns its starting sequence and a stream of
commits. The event store wakes it after a durable append. The feed waits for the projection checkpoint
and catches up if the writer stopped before it finished. Pass the last sequence processed in this workspace
to resume the ordered feed.
Idempotency is the command id. A retry of the same request by the same actor reuses its command id and
gets the first outcome (repeat: true). A command whose id is already recorded fails with CommandIdReused
if its canonical request digest differs. The last stored event of an append carries the private command receipt,
so a restart recovers the original outcome. Eventless commands record their result directly in the command log.
Use a distinct id for each distinct request. Concurrent different requests that share one id can race between
the event log and command log when only one request appends events. No engine command input carries a key of its own (an idempotencyKey input was removed:
the decision gets no command log, so it did nothing here), and decide takes no command log. A host that wants one id
per operation keeps it with the operation and passes it as the command id on every attempt.
ExecuteOptions.broadcast also derives the engine's broadcast events (WorkflowEvent: a phase started, a task done, a
trigger fired, the log lines), told by the engine while it decides; Executed.broadcast carries them. actorKind sets
the envelope's actor kind (a reaction's command is a plugin's, a timer's the system's). Catching up several commits
projects the read models once, at the last.
seed(commits) puts commits a host decided elsewhere (its own engine, an import) on an empty stream: each
SeedCommit is { commandId, actor, actorKind?, correlationId?, causationId?, events, recordedAt? } (recordedAt: the
instant the commit was made, kept as its events' recordedAt; absent, the seeding moment), all appended in one atomic
append at sequence 0, then caught up as any other writer's commits (fold, command log, read models, snapshot,
subscribers). It fails with StreamNotEmpty { stream, sequence } on a stream that holds an event, CommandIdReused
when two commits share an id, InvalidEvent { index } for an event that is no event of the engine or of an installed
plugin, whose payload its schema refuses, or that the envelope refuses; then nothing is stored. The events are
not decided again. It returns the sequence after the seed. A seed is the stream's past: before its append the runtime
writes the seed mark (checkpoints row <stream>#seed, seedMark(stream)) with the sequence it ends at, so the
orchestrator delivers none of its triggers and notifications but fires its runs' deadlines, and commits leaves its
commits out.
query(ref, params, { viewer? }) answers a read by reference, as JSON: the engine's (workflow.world,
workflow.sequence, workflow.runs, workflow.run, workflow.overview, workflow.history, workflow.phases,
workflow.task-list, workflow.commits, workflow.draft, workflow.draft-history; params in ENGINE_QUERY_PARAMS) or a plugin's (<plugin>.<name>, params decoded and result
encoded by its schemas, run on the folded head under the stream's lock, with a QueryEnv of the clock's instant:
now, can, actorOf, actorsWithRole, validator). Refusals: plugin.unknown-query, plugin.invalid-input, and
query.not-found for a run that does not exist or a plugin query whose run answered the engine's notFound. WorkflowRuntimeConfig.queryGates is a
gate table built with queryGates(plugins, { "<ref>": gate, … }), whose type demands a gate for every engine query and
every query of the plugins given; with it, a query needs a viewer, and a query without a gate, without a viewer, or
whose gate answers undefined is refused with query.not-found. The typed reads (world, runs, …) are the host's own
and pass no gate.
commits({ after? }) (query workflow.commits) lists the stream's live commits, oldest first, as
CommitSummary { sequence, before, commandId, command?, actor, recordedAt, events }: before is the sequence a
rollBack takes to undo it and everything live after it, command the command's name from the command log (absent
for a commit another process appended), events the event types. A commit a rollback undid is not live (one a later
rollback brings back is again), the rollbacks themselves are not listed, nor is the seed. after keeps the commits
recorded after that instant: a "what happened since" preview before a rollback. It reads the whole stream.
The screens' reads. Computed from the folded head at the clock's instant, over the engine's own functions
(views.ts): workflow.phase-task { runId, taskId } (PhaseTaskDetail), workflow.step { executionId }
(StepItemDetail, with the viewer's duty while it is open), workflow.step-outlook { executionId } (StepOutlook,
or null when the step's input decides the way on), workflow.follow-ups {} (the viewer's FollowUp),
workflow.follow { runId } (the viewer's RunFollow), workflow.adhoc-tasks { runId?, personId? } and
workflow.adhoc-task { taskId } (AdHocTaskView, the engine's task with its kind and data),
workflow.groups {} (GroupRow), workflow.definitions {} (DefinitionSummary: each definition with its versions'
number, status and running runs), workflow.versions { definitionId } (oldest first; an author's read, as the
draft), workflow.return-preview { taskId } | { executionId } (returnReview decided as the viewer, plugin checks
included, nothing written: { ok: true, executorId?, attempt } or the refusal) and workflow.rights { runId? }
({ capabilities }: every capability of CAPABILITIES the runtime's can gives the viewer, with the seats they hold
on the run). Each is query.not-found for what does not exist; follow-ups, follow, return preview and rights also
without a viewer. RunSeatRow carries the seat's color and external.
Drafts. workflow.draft { versionId } answers a DraftView { version, revision, undo?, redo? }: any version
of the world, with the viewer's newest undoable and redoable edit on its draft (DraftStackTop { edit, intent? }, what
undoEdit and redoEdit name; none without a viewer). workflow.draft-history { versionId, after?, limit? } answers
the version's history oldest first, one DraftHistoryLine (the engine's DraftLogLine and its position) per draft
event, its publish and its retirement, kept after the publish; after keeps the lines past a position, limit the
oldest that many of those. A line's position is the draft revision after it, one above for the publish and two for
the retirement (neither moves the revision). Both answer query.not-found for an unknown version and for a viewer
the runtime's can refuses workflow.author (external viewers under the stock rule), so a gate table may give them
an open gate; without a viewer the host reads them.
Read models (model names in READ_MODELS, keys <workspaceId>/<id>): runs (a RunSummary per run),
run-history (the run log as data lines), draft-history (one row per DraftHistoryLine, keyed
<workspaceId>/<versionId>/<position>: written per commit from its events and never rewritten as a history grows; a
rollback and rebuild write the workspace's rows again from the live commits, so a rollback to a later end brings back
the lines an earlier rollback removed), and checkpoints (per stream, the sequence the models and the command log
stand at). rebuild projects them again from the stream. Only what does not depend on the instant is kept as rows: a
run's overview (runOverview without its history), its phases (runPhases) and a person's task list (phase tasks and
steps) evaluate conditions, attestations and deadlines at "now", so overview, phases, taskList and their queries
are answered from the folded head at the clock's instant. Moving the clock with no commit moves their answers. The
overview also gives each seat of the run with its holders at that instant (seats: RunSeatRow[], { id, label,
people, roles, groups }, roles and groups not expanded), from which a screen tells whether its viewer holds a seat. A
RunSummary's responsibleIds are the responsible seat's people and its groups' members (else the starter); a
commit that changes only the groups or a plugin's state re-projects the runs whose responsible people it changes.
The pipeline suite (pipelineSuite, pipelineCases) drives the engine's scenario routes through the runtime
and compares the end with the engine's typed command functions, and covers idempotency, refusals, concurrent
commands, a lost race, crashes between append and projection or command log, snapshots and rollback; its plugin
cases (pluginCases, the engine's test plugin docket) cover a plugin command and its chained engine command in one
append, a refusal or a store failure after the decision storing nothing, rollback of plugin state, a snapshot of another
plugin list, a seed with plugin events, and gated queries; its role map cases (roleMapCases) cover a seat filled from
a plugin's context (a task's owner, responsibleIds, the overview's seats, live as the plugin's state changes) and a
run capability a seat holds under the default rights; its draft cases (draftCases) cover two writers on one draft
(merged on different items, refused on the same one), an undo of an edit a snapshot holds after a restart, the
draft-history rows after a publish, a rebuild and two rollbacks, and the draft queries' workflow.author check.
Orchestration (src/orchestration/)
What a commit sets off outside the engine (a trigger's handler, a notification, a deadline that comes due) is driven
by an orchestrator, beside the stream: it reads the stream and issues commands through the runtime, never
anything else, so the stream stays the only truth. The port is WorkflowOrchestrator:
catchUptakes up every commit since the orchestrator last looked; idempotent.passdoes what is due at the runtime's clock now and returns once it is done (tests, a browser, the CLI).rundrives the stream until the scope closes (after every commit, and on the adapter's own schedule).record(id),records: what became of each reaction, in thereactionsread model (ReactionRecord:handled,not-bound,delivered,rejected,retrying,given-up, with the attempts).
Every adapter keeps the same promises: a deadline moment fires once, under timerCommandId (a rollback that brings it
back lets it fire once more); a trigger reaches its bound handler once per reaction and a notification the notifier
once per recipient (at least once under failures, never again once recorded as finished); an unbound command is
recorded not-bound; a seed's past is not delivered; a new instance over the same stores carries on where the last
one stopped. A rollback does not undo outward work: what a handler or the notifier did stays done.
The pieces every adapter shares (so a durable engine or Temporal drives the same work the same way):
observeEvents(events, { cursor, seeded, runId? })(pure),observeStream(cursor)andobserveRun(runId, { cursor, lastTouch }): what a stretch of the stream asks for. Eachtrigger.firedbecomes aTriggerReactionwith id<eventId>/<command>(the trigger's command, params, what it fired for); each requested notification oneNotificationper recipient with id<eventId>/<recipient>(the engine chose the recipients, follow and unfollow included;kindandparamsare the reason's code and parameters plusrunId,title,text?,event, and the effect'seffectIdandoccurredAt, as inrun.runtimeEffects); in stream order (work). Events up to the stream's seed mark ask for nothing, but their runs count.observeRunadds the run's status, its next deadline, its last touch, the rollback generation and the clock: one look of a per-run workflow.nextDeadline(world, runId)(andnextDeadlineDay),deadlineTimerId(stream, runId)(<stream>/<runId>/deadline),rollbackGeneration(stream)(the sequence of the stream's last rollback, 0 for none; kept incheckpoints<stream>#rollbacks),timerCommandId(timer, generation)(timer/<timerId>@<dueAt>#<generation>) andfireDeadline(runId, dueAt, generation):fireDueTimersas the system under that id, in a spanworkflow.timer; a repeat changes nothing, a refusal answersfalse.deliverReaction(reaction): one attempt at the handler bound to its command (TriggerHandlers, built bylayerHandlers({ "<command>": handler });noHandlersbinds none), with aReactionContext(reactionContext) whoseexecuteissues engine or plugin commands with the trigger's event as causation, the chain's correlation id and the reaction's id as command id;handled,not-bound, orHandlerFailed.deliverNotification(notification): one attempt at theNotifier;delivered,rejected(final), or the notifier's failure.recordReaction,reactionRecord,reactionRecords,isFinished: thereactionsread model.
Reaction, notification and handler command ids derive from stored event ids, and what runs again after a rollback appends new events with new ids, so it is delivered as new work; only the timer's id is made of values a rollback brings back, hence its generation.
The outbox adapter (layerOutboxOrchestrator(config), makeOutboxOrchestrator(config) with its steps; over the
runtime, EventStore, ReadModelStore, Outbox, Scheduler, Notifier and TriggerHandlers) is the default, on the
runtime's own ports:
enqueue(itscatchUp) reads the stream after its checkpoint (checkpointsrow<stream>#reactions) and puts each reaction and notification in theOutbox(idempotent by id), and each run the events touch gets its next deadline moment as a timer<stream>/<runId>/deadlinewith the commandfireDueTimers { runId }, or its timer cancelled (a rollback touches every run).delivertakes due entries under a lease and delivers each; a failure is retried at theretryschedule's delay for its attempt (default exponential from 1 s, five retries) and given up when the schedule ends; an entry delivered again after a lost acknowledgement is acknowledged without a second call.fireTimersclaims due timers under a lease and fires each moment, so a second process that gets the timer after the lease ran out repeats it; then the run's next moment is set.passdoes all three, one pass at a time;runforks a pass after every commit and everypollEvery.
The engine's built-in triggers act inside the command that fires them (a task added, a meeting planned, a field set): that is the run's own bookkeeping and stays atomic with its cause. A handler is where the outward part goes.
The orchestrator suite (@sewdn/workflow-runtime/testing): orchestratorSuite(name, layer, makeOrchestrator)
runs orchestratorCases(makeOrchestrator) on the ports layer provides (built once per case, a Directory holding
pipelinePeople); makeOrchestrator makes one instance over the WorkflowRuntime, TriggerHandlers and Notifier
the case provides, and is called again for a restart. The cases: a long route played to the end (its deadlines fired
only by the orchestrator, each reaction and recipient once, and the stream, ids aside, equal to the reference run's:
the same route on the outbox adapter over the memory adapter); an orchestrator stopped right after a commit it has not
acted on and a new one carrying on; a finished run rolled back and driven to the end again; a failing handler tried
again within a minute; unbound triggers; a handler's command back; notifications to followers; two instances at one
deadline; a rolled-back deadline; a seed; the run loop alone. Time is the case's TestClock, which the runtime
reads: an adapter that runs the runtime's commands elsewhere runs them under it too. outboxOrchestratorSuite(layer)
runs the suite on the outbox adapter plus its own cases (a lost acknowledgement, a timer's lease between two instances,
the retry policy's delays); the memory, localStorage and PostgreSQL adapters run it.
Tracing. Effect's tracer, no exporter: every command is a span workflow.command (attributes
workflow.command, workflow.stream, workflow.command_id, workflow.correlation_id, workflow.causation_id,
workflow.actor; when through, workflow.sequence, workflow.repeat, workflow.events, workflow.event_ids; refused,
workflow.refusal). Every delivery is a span workflow.reaction (workflow.reaction_id, workflow.reaction_kind,
workflow.attempt, workflow.command, workflow.causation_id, workflow.correlation_id, workflow.reaction_status)
and every claimed timer a span workflow.timer; the commands they issue are their children. A host provides its own
Tracer (OpenTelemetry through effect/observability) to export them.
Plugins (src/plugins/)
A plugin's runtime part (RuntimePlugin<R> = EnginePlugin & { runtime?: PluginRuntimePart<R> }) is an effect that
builds its PluginBinding: handlers by trigger command name and resolvers (FactResolver) by fact name. It may use
any service (R): a browser binding keeps its records in the runtime's own ReadModelStore, a server binding uses a
client of its own; nothing in it depends on a server. bind(binding) makes one that needs nothing, fromPromise
wraps plain async functions for a host that does not write Effect.
layerPlugins(plugins) installs the engine parts (installPlugins) and provides TriggerHandlers and
FactResolvers by reference (<plugin>.<name>): provide it to the runtime and to the orchestrator. Before each command
the pipeline resolves the facts the running runs' conditions ask (resolveFacts) and hands them to the decision; a
fact no resolver answers is unknown. Without FactResolvers (the simulation), a fact takes its simulation behaviour. A
fact whose plugin evaluates it from its state is answered by the engine in the decision: no resolver is asked for
it, and layerPlugins refuses to bind one (a defect, PluginBindingError { reason: "evaluated-fact" }).
The simulation (src/simulation/)
@sewdn/workflow-runtime/simulation, synchronous, for a browser or a test:
SimulatedRuntime(content, options): one workflow's JSON onWorkflowRuntimeover the memory adapter, under a manualClock(clock.now/advanceTo/rewindTo/advanceDays). Typed commands (commands.<name>(actor, input),execute(name, actor, input),perform(action, actor, values)), the broadcast events toon(type)andonAnylisteners, the readers (runs,runSummary,phases,tasks,tasksFor,data,history,log,effects,timers,lifecycle,blocked,available), and the stream (events(),sequence(),sequences(),stateAt(n),rollBack(actor, n),cutTo(n);options.eventsresumes). No reaction process runs and nothing can be bound: it writes nothing outside itself and calls no handler. A fired trigger whose plugin declares a simulation behaviour (PluginTrigger.simulate) gives that behaviour's commands instead (engine or plugin commands), as the run's responsible.plugin(ref, actor, input)gives a plugin's command (its value as JSON) andquery(ref, params)answers a plugin's or the engine's query; the list of available actions stays the engine's.WorkflowSimulation/createWorkflowSimulation(content, options): a fictional run played on it, one action per step (step,next,runTo(phaseId),runToEnd,restart,setMinutesPerStep,state). Going back to a phase cuts the stream: the runtime is built again on a memory adapter holding the events up to that step. The default cast (defaultSimulationCast()) has no roles of its own:staffSimulationgives each role the workflow names to two of its people and holds every seat nobody would otherwise hold.
Both take history (a HistoryCatalog, default English): the words of the log, the history and the broadcast events,
in the host's language.
It is synchronous because the memory adapter and the manual clock never wait, so each method runs its effects with
Effect.runSyncWith. Effect's TestClock cannot be that clock: setTime forks and awaits a fiber, which no
synchronous run completes; the orchestration's tests use it.
The memory adapter (src/memory/)
@sewdn/workflow-runtime/memory: every port in memory (layer(seed?), one layer<Port> each). It is the
reference adapter, and it lives here because the simulation runs on it.
Writing an adapter
- Depend on
@sewdn/workflow-runtimeandeffect. - Provide each port with
Layer.effect(Port, make). Build state inside the effect, so two builds share nothing. Inappend, check the expected sequence and callstampEventsunder one lock or transaction. - Register the suite in a
*.test.tsrun bybun test:
import { adapterSuite } from "@sewdn/workflow-runtime/testing";
adapterSuite({
eventStore: myEventStoreLayer,
snapshotStore: mySnapshotStoreLayer,
// …one entry per port the adapter provides
directory: (seed) => myDirectoryLayer(seed),
});
// an adapter that provides every port the pipeline uses also runs the pipeline's cases
pipelineSuite(myLayer({ directory: { people: pipelinePeople } }));Every case runs on a fresh build of the layer under a TestClock starting at 0, so a layer over a
persistent backend must start each build from an empty store. The cases are also exported as data
(eventStoreCases, …) with runCase, for a runner other than bun test.
Scripts
bun run typecheck
bun run test # bun test src
bun run build # tsc -p tsconfig.build.json