Engine, effects, and insights reference
Reference for createEngine, WorkflowEvaluation, engine methods, effect handler contracts, evaluation insights, and HistoryEntry types.
The engine is the working core of Workflows. It is a TypeScript library, not a hosted service. createEngine binds a Sanity client, the resource where workflow documents live, and an environment partition. The CLI, MCP server, server applications, and reactive UI layers all operate this same engine.
This page covers runtime contracts. For every exported function, type, and option, see the generated API reference for @sanity/workflow-engine and @sanity/workflow-engine-test.
A definition describes a process. The engine turns it into running instances, evaluates their current state, and applies the operations that move them forward.
You may not need to call the engine directly. The CLI and MCP server wrap it for command-line and agent workflows. The reactive session, App SDK adapter, and Studio plugin run it underneath an application. Create an engine yourself when you are building a custom server-side integration, worker, or runtime.
Create and use an engine
Use an authenticated Sanity client connected to the dataset that stores workflow documents. For a step-by-step walkthrough, see Run the engine from your own code. This example uses the quick start’s dev deployment and assumes the article-review definition is already deployed:
import {createEngine, gdrRef, instanceDocId} from '@sanity/workflow-engine'
const workflowResource = {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'} as const
const engine = createEngine({
client,
workflowResource,
partition: 'dev',
})
// Given a deployed definition named “article-review”, mint the retry key once
// and persist it with the job or request that owns this start.
const instanceId = instanceDocId('dev')
const result = await engine.startInstance({
definition: 'article-review',
instanceId,
initialFields: [
{
type: 'subject',
name: 'subject',
value: gdrRef({res: workflowResource, documentId: 'DOCUMENT_ID', type: 'article'}),
},
],
})A caller-supplied instanceId is the idempotency and retry key for a programmatic start. Retry with the same ID to resume an interrupted create, prime, and cascade sequence. Replaying a start that has already settled does nothing. If you leave the ID out, every call generates a new one, and a blind retry can create a second instance. Reusing an ID for a different definition, or for a different explicitly selected version, is rejected.
instanceDocId(partition, suffix) returns the same ID for the same suffix. Derive the suffix from the start's own identity, such as the triggering document's _id and _rev, so every attempt of that start uses one instanceId.
createEngine requires partition; there is no default at this level. Read engine.partition for the bound value. To reach content in other datasets or projects, pass resourceClients; deploymentResourceClients builds that resolver from a deployment's resourceAliases.
startInstance refuses a start whose supplied subject, doc.ref, or doc.refs value points at a document that does not exist. It throws InitialFieldsInvalidError with reason document-not-found and the reference's id before anything is written. A document that exists only as a draft or in a release counts as existing, and a reference the caller cannot read is not refused. Spawned child instances are not checked.
To run queued effects, configure effects when constructing the engine. Effect runtime configuration lists the options, and Run an external step with an effect builds a drainer.
Reference
createEngine options
Pass these options to createEngine(...). They are fixed for the engine's lifetime. For the full type, see `CreateEngineArgs` on reference.sanity.io.
Requiredclient
SanityClient
Required. Authenticated client for the workflow resource. The engine resolves its acting identity from this client's token, so keep its auth stable; to act as someone else, create another engine. Any
apiVersionworks.RequiredworkflowResource
{type: 'dataset', id: string}
Required. Resource that stores definitions and instances.
Requiredpartition
string
Required, no default. Lowercase letters, digits, and dashes, no leading dash. Stored on documents as
tag. Passingtaginstead throwsContractViolationError.resourceClients
ResourceClientResolver
Optional. Returns a client for another dataset or project, or
undefinedto let the engine route it.effects
{handlers?, leaseMs?, missingHandler?}
Optional. Effect runtime configuration. See Effect runtime configuration.
executionContext
{kind: string, id?: string}
Optional. Declared host label stamped on every history entry beside the actor.
idempotencyTtlMs
number
Optional. Default 24 hours. How long a recorded
idempotencyKeydedupes retries.clock
() => string
Optional. Returns the ISO time for
$nowand stamps. Default: wall-clock time. For tests.sleep
(ms: number) => Promise<void>
Optional. How retry backoff waits. Default: real time. For tests.
loggerFactory
(name: string) => EngineLogger
Optional. Logger used by
drainEffectsandverifyDeployedDefinitions.telemetry
WorkflowTelemetryLogger
Optional. Receives product telemetry events. Default: emits nothing.
WorkflowEvaluation
The engine and reactive session return the same read-only projection of one instance:
instance
WorkflowInstance
The evaluated instance snapshot.
definition
WorkflowDefinition
The deployed definition resolved for the instance.
missingDocuments
MissingDocument[], optional
Missing targets of populated
subject,doc.ref, anddoc.refsfields in active scopes. Omitted when nothing is missing. See Missing referenced documents.blockingMissingDocuments
MissingDocument[], optional
The missing documents that prevent current progress: required reference targets, or references read by unmet runtime requirements or transition conditions. Empty when every missing reference is optional for current progress.
semantics
Semantic[], optional
The workflow’s authored semantics, unchanged from the definition.
currentStage, each activity evaluation, and each action evaluation carry their ownsemanticsthe same way. Advisory metadata, separate from verdicts and condition insights.actor
Actor
The actor whose identity, roles, and grants were used for this evaluation.
currentStage
StageEvaluation
The current stage with its activity and transition evaluations.
pendingOnYou
ActivityEvaluation[]
Active activities assigned to the evaluated actor.
canInteract
boolean
True when at least one action on an active activity is allowed.
abort
AbortEvaluation
Whether the evaluated actor may abort the instance with
abortInstance, as{allowed, disabledReason?}.filter-failedmeans the definition'sabortroles do not admit this actor, so hide the abort control. A terminal instance reportsinstance-completedorinstance-aborted. Required: code that builds aWorkflowEvaluationby hand, such as a test fixture, must set it.editableFields
EditableFieldEvaluation[]
Declared editable fields in the current scope, with their values, provenance, and edit verdicts.
fieldInsights
FieldInsight[]
Derived condition state for fields read by the current stage. See Evaluation insights for involvement and verified proposals.
autonomy
WorkflowAutonomy
The definition-wide projection of whether activities, stages, and the workflow can progress without a caller.
nextEvaluationAt
string, optional
Earliest future ISO 8601 instant the engine can derive when time alone changes this actor’s evaluation. Includes caller-bound clock gates. Absent on terminal instances and when no site yields a boundary from the current values. Date arithmetic and dataset scans may yield none; absence on a nonterminal instance is not proof that time cannot change it. Derived per call, never persisted.
ActionEvaluation
Each ActivityEvaluation in WorkflowEvaluation.currentStage lists its actions as ActionEvaluation objects. All values are advisory verdicts for the evaluated actor.
Requiredaction
Action
The stored action declaration.
semantics
ActionSemantic[]
Optional. The action's semantics, unchanged.
Requiredallowed
boolean
Whether the actor may fire the action now.
triggered
true
Optional. Set on an action with
when. Narrate it rather than render a button;disabledReasoniscascade-fired.disabledReason
DisabledReason
Optional. Present when
allowedisfalse; the first failing check wins.kindisfilter-failed,cascade-fired,activity-not-active,stage-terminal,mutation-guard-denied,instance-completed,instance-aborted,requirements-unmet, orsubject-permission-denied.firing
{exitsStage: boolean, transition?: string}
Optional. What firing now would do, replayed in memory.
exitsStageistruewhen the cascade leaves the current stage;transitionnames the selected transition. Omitted when the answer depends on caller params, a spawn, a terminal instance, a diverged stage, or an action withwhen.insight
ConditionInsight
Optional. Explains the
filter. Present when the action declares one.whenInsight
ConditionInsight
Optional. Explains the
whentrigger.holderGate
{holders: Assignee[]}
Optional. A
$assignedfilter hid this action;holdersnames who holds the work.
import {engine} from './engine'
const evaluation = await engine.evaluate({instanceId: 'INSTANCE_ID'})
for (const activity of evaluation.currentStage.activities) {
for (const a of activity.actions) {
console.log(activity.activity.name, a.action.name, a.allowed, a.disabledReason?.kind, a.firing?.exitsStage)
}
}Engine methods
These methods are called on the engine instance returned by createEngine(...). Higher layers such as the CLI, MCP server, reactive adapters, and Studio plugin call the same engine surface for you.
Instance commands such as startInstance, fireAction, and tick return an OperationResult. Its instance is the settled workflow instance. A successful no-op has changed: false and can still return nextEvaluationAt.
An operation result derives its clock boundary without an actor. A condition combining $now with $actor, $assigned, $can, or $attributes contributes only to the actor-specific WorkflowEvaluation when that projection can judge it. A supplied clock is read once per engine pass; one operation can run several cascade passes.
With the quick start’s article-review definition and dev deployment, a direct engine integration typically deploys, starts, reads, and advances an instance like this:
import {gdrRef} from '@sanity/workflow-engine'
import {dev} from '../sanity.workflow'
import {articleReview} from '../workflows/article-review'
await engine.deployDefinitions({
expectedMinReaderModel: 10,
definitions: [articleReview],
})
const {instance} = await engine.startInstance({
definition: articleReview.name,
initialFields: [
{
type: 'subject',
name: 'subject',
value: gdrRef({res: dev.workflowResource, documentId: 'DOCUMENT_ID', type: 'article'}),
},
],
})
const instanceId = instance._id
const evaluation = await engine.evaluate({instanceId})
await engine.fireAction({
instanceId,
activity: 'write',
action: 'submit',
})
await engine.tick({instanceId})Deploy and validate a runtime
deployDefinitions(): Promise<DeployDefinitionsResult>
Validates, versions, and stores definitions.
verifyDeployedDefinitions(): Promise<VerifyDeployedDefinitionsResult>
Audits deployed effect names against this engine’s registered handlers and applies
effects.missingHandlerto each name no handler covers. Call it at runtime startup.
Drive instances directly
startInstance(): Promise<OperationResult>
Starts an instance and enters its initial stage.
getInstance(): Promise<WorkflowInstance>
Fetches an instance by ID.
evaluate(): Promise<WorkflowEvaluation>
Projects current state, gates, activities, and action verdicts.
availableActions(): Promise<AvailableActionsResult>
Lists current-stage actions with allowed or disabled verdicts.
fireAction(): Promise<OperationResult>
Fires a caller-driven action and continues the cascade.
editField(): Promise<OperationResult>
Changes a declared editable field and continues the cascade.
tick(): Promise<OperationResult>
Reevaluates an instance and continues any newly enabled cascade.
children(): Promise<WorkflowInstance[]>
Lists child instances spawned by a parent.
Reactive layer and document discovery
resolveActor(): Promise<ActorResolution<ClientProjectUser>>
Resolves a stored actor stamp, with its
projectId, to the current project user. The result status isresolved,missing,inaccessible, ornot-person. Agent and system actors returnnot-personwithout a lookup. The standaloneresolveClientActor(client, {actor, projectId})does the same with any client.evaluateStart(): Promise<StartEvaluation>
Preflights ordered start requirements and required inputs without starting an instance.
definitionsForDocument(): Promise<DeployedDefinition[]>
Finds the latest deployed version of each definition whose subject type and start filter accept a loaded document.
instancesForDocument(): Promise<WorkflowInstance[]>
Finds in-flight instances with a live reference to a document, including unresolved child references and excluding exited-stage references.
subscriptionDocumentsForInstance(): Promise<WatchSet>
Returns the documents and perspective a reactive consumer must watch.
session(): InstanceSession
Creates a caller-driven reactive session around an instance.
Effect runtimes
drainEffects(): Promise<DrainEffectsResult>
Claims and dispatches every claimable pending effect through registered handlers. Accepts an optional names filter.
listPendingEffects(): Promise<PendingEffect[]>
Lists every pending effect on an instance.
findPendingEffects(): Promise<PendingEffect[]>
Filters pending effects by claim state or effect name.
completeEffect(): Promise<OperationResult>
Records an effect result and continues the cascade.
commitEffectOps(): Promise<OperationResult>
Commits field state from a running effect handler and renews its claim.
Inspection and diagnostics
diagnose(): Promise<DiagnoseResult>
Explains why an instance is or is not progressing.
guardsForInstance(): Promise<MutationGuardDoc[]>
Lists mutation guards registered by an instance across its resources.
guardsForDefinition(): Promise<MutationGuardDoc[]>
Lists statically discoverable mutation guards for a deployed definition.
query(): Promise<T>
Runs GROQ against the engine workflow resource with the partition bound as $tag, the stored field name.
queryInScope(): Promise<T>
Runs GROQ against the instance snapshot and rendered workflow scope.
Cleanup and recovery
setStage(): Promise<OperationResult>
Forces an instance into a stage as an administrative override.
abortInstance(): Promise<OperationResult>
Hard-stops an in-flight instance.
deleteDefinition(): Promise<DeleteDefinitionResult>
Removes deployed definition versions, optionally aborting active instances.
resetActivity(): Promise<OperationResult>
Reruns or skips a terminal activity in the current stage, then continues the cascade.
OperationResult
Every instance command, including startInstance, fireAction, editField, tick, completeEffect, commitEffectOps, setStage, abortInstance, and resetActivity, returns this shape. Failures throw.
Requiredinstance
WorkflowInstance
The instance after the command and its cascade. See Workflow instance document.
Requiredcascaded
number
Automatic transitions fired during the cascade.
Requiredchanged
boolean
falsewhen the command succeeded without changing state: a repeat fire of a resolved activity, atickthat wrote nothing, asetStagealready at the target, an abort of a finished instance, or a processedidempotencyKey.ranOps
OpAppliedSummary[]
Optional. Operations that ran during the action commit.
nextEvaluationAt
string
Optional. Earliest future ISO instant when time alone can change the instance. Schedule the next
tickfor it. Excludes conditions that combine$nowwith a caller variable. Absence on a running instance does not prove time can't change it.
import {engine} from './engine'
const result = await engine.fireAction({instanceId: 'INSTANCE_ID', activity: 'write', action: 'submit'})
console.log(result.changed, result.instance.currentStage, result.nextEvaluationAt)Workflow instance document
A workflow instance is the engine-owned sanity.workflow.instance document. startInstance and every other instance command return it as OperationResult.instance, and getInstance reads it. Read it through the engine, and change it only through engine methods. For the full type, see `WorkflowInstance` on reference.sanity.io.
Identity and definition pin
These fields identify the run and preserve the definition it started with.
_id
string
Sanity document ID for the workflow instance.
_type
sanity.workflow.instance
Document type for a workflow instance.
tag
string
Stored name of the partition. Equals the
partitionpassed tocreateEngine. The field keeps the nametagin stored documents and GROQ ($tag).workflowResource
WorkflowResource
Sanity resource where the instance is stored.
definition
string
Name of the deployed workflow definition.
pinnedVersion
number
Definition version selected when the instance started.
pinnedContentHash
string | undefined
Content hash of the pinned definition. Advisory: compare it to detect a redeployed definition that changed. Absent when the definition had no hash.
definitionSnapshot
string
Frozen JSON snapshot of the definition used at start.
State and hierarchy
These fields hold the instance’s resolved state and its place in a workflow hierarchy.
fields
ResolvedFieldEntry[]
Workflow-scope field values.
context
ContextEntry[]
Start context supplied once and read through $context.
ancestors
GlobalDocumentReference[]
Ancestor workflow instances, ordered root-first.
perspective
WorkflowPerspective | undefined
Perspective for content reads, including field queries and spawn discovery. Absent means
drafts. Set it withstartInstance; children inherit it.currentStage
StageName
Name of the current stage.
stages
StageEntry[]
Stage visits in entry order; the current visit has no exitedAt.
subworkflows
SubworkflowEntry[] | undefined
Registry of every child this instance spawned, read as
$subworkflows. Rows are never deleted.
Effects, history, and idempotency
These fields track queued work and committed engine activity.
pendingEffects
PendingEffect[]
Effects waiting to be claimed or completed.
effectHistory
EffectHistoryEntry[]
Completed effect results.
history
HistoryEntry[]
Committed engine events for the instance.
processedRequests
ProcessedRequest[] | undefined
Idempotency keys recorded by keyed commands, each with
key,op,processedAt, andexpiresAt. Rows expire afteridempotencyTtlMs(default 24 hours).
Lifecycle and model compatibility
These fields record lifecycle timestamps and the persisted data-model contract.
startedAt
string
ISO-8601 timestamp set when the instance starts.
lastChangedAt
string
ISO-8601 timestamp of the latest engine commit.
completedAt
string | undefined
Set when the instance reaches any terminal state.
abortedAt
string | undefined
Set with completedAt when the instance is aborted.
modelVersion
number | undefined
Engine data-model version that last wrote the document.
minReaderModel
number | undefined
Oldest engine data model that can read the document. An older engine refuses to read it.
Effects and handler runtime contracts
The declarations and runtime methods in this section are the public contracts for effects. Handler reporting uses the same field-operation vocabulary described in Operations.
Effect declaration
This is an effect request in an action’s effects array, commonly authored with defineEffect(...). Its name connects the declaration to a registered runtime handler.
name
string
Required. Registry name that identifies the effect and its handler. Unique within the definition.
title
string
Optional human-readable label.
description
string
Optional explanation for editors and tooling.
bindings
Record<string, string>
Optional GROQ expressions evaluated when the action queues the effect. The handler receives their resolved values.
input
Record<string, unknown>
Optional static parameters. An input key overrides the same key from bindings, including when its value is null.
outputs
FieldShape[]
Optional strict allowlist of output names and types. Omitting it means the effect may return no outputs; undeclared or invalid values reject completion.
retry
EffectRetry
Optional bounded retry policy. Omit it to settle on the handler's first failure. See the retry policy reference.
runtime
EffectRuntimeBlock
Optional authoring-only hosting declaration. The effect inherits its workflow's hosting kind unless it declares one. See Run Workflows with Sanity Functions.
Unavailable
$can, $attributes, $row
Never bound in effect bindings. See Conditions.
Caller-fired action
$params
Unavailable when a cascade-fired action queues the effect.
Acting action
$actor, $assigned
Available when an acting token rides the action.
Always available
$self, $fields, $parent, $ancestors, $stage, $now, $context, $effects, $effectStatus, $activities, $allActivitiesDone, $anyActivityFailed, $subworkflows
All effect bindings.
Retry policy
Set these properties on an effect's retry block. Durations are whole milliseconds greater than zero.
kind
'engine'
The engine runs the policy inside one drain call. Authoring may omit this property; the stored definition contains 'engine'.
Requiredattempts
number
Total attempts per retry run, including the first. Must be a positive integer. A value of 1 makes no further attempt.
backoff
{kind: 'fixed' | 'exponential'; delayMs: number}
Optional wait between attempts. Fixed waits use delayMs each time. Exponential waits double it after each failed attempt. Omit backoff for no deliberate wait.
expiryMs
number
Optional elapsed-time limit for starting another attempt. Handler time counts; a running attempt is not interrupted.
Deployment rejects an expiryMs or accumulated backoff above 31,622,400,000 milliseconds (366 days). It also rejects a policy whose declared waits reach its expiry before all attempts can start. Handler duration is unknown at deployment and can leave attempts unused.
This declaration retries notify-reviewer up to three times:
defineEffect({
name: 'notify-reviewer',
bindings: {article: '$fields.subject._id'},
outputs: [{name: 'messageId', type: 'string'}],
retry: {
attempts: 3,
backoff: {kind: 'exponential', delayMs: 1_000},
expiryMs: 30_000,
},
}),The first call counts as an attempt. With this policy a failed first attempt waits one second before the second attempt, and two seconds before the third. A successful attempt stops the retries. A later success settles as done, so adding a policy can change which transition fires.
expiryMs limits when another attempt may start. It includes handler execution and waits, but never interrupts an attempt already running. The engine stops if the next wait would reach the limit, or if the limit has passed when the wait ends. A success from an admitted attempt still counts after the limit.
Retries run inside one drainEffects invocation, so the waits and handler execution must fit the host’s timeout. The engine renews the claim across waits and does not schedule another invocation. If the process stops and another drainer takes over, that drainer starts a fresh retry run, so total handler calls can exceed attempts.
A final failure records the attempts used and the last error in the completion’s detail. A later success records which attempt succeeded. There are no per-attempt history rows. A definition with retry needs reader model 10.
For deterministic tests, createEngine accepts sleep beside clock. A supplied sleeper must not resolve before that clock has advanced by the requested milliseconds. The engine test bench advances its clock automatically.
Effect runtime configuration
Pass these options as effects to createEngine. Each service registers the handlers it owns, so one effect can run in a different process from the one that queued it.
handlers
Record<string, EffectHandler>
Handlers keyed by the effect name the definition queues. One handler per name.
leaseMs
number
Claim lease in milliseconds. Default 300,000 (
DEFAULT_EFFECT_LEASE_MS, five minutes). Choose a duration longer than the slowest handler, and make handlers safe to repeat.missingHandler
'fail' | 'skip' | (info: MissingHandlerInfo) => void | Promise<void>
What
drainEffectsandverifyDeployedDefinitionsdo with an effect name no handler covers.'fail', the default, throwsMissingHandlerError.'skip'leaves the entry pending for another drainer and reports it as skipped. A function is called with the details; if it throws, the policy fails, otherwise the entry is skipped.
Claims and leases
drainEffects claims each entry under a lease of effects.leaseMs. After the lease expires, another drain can take the entry over and run its handler again; the takeover writes an effectClaimReleased history row. sweepStaleClaims({client, partition, instanceId}), a standalone export of @sanity/workflow-engine rather than an engine method, releases expired claims without dispatching them. The same call re-queues a pending effect that no drain has claimed for DEFAULT_EFFECT_LEASE_MS: it sets the entry’s queuedAt to the sweep time and leaves it unclaimed, which wakes a drain trigger on pendingEffects. It re-queues an entry at most once per interval and writes no history row for it, so queuedAt is the latest time the entry was queued.
At-least-once delivery
Delivery is at-least-once: a handler can run more than once for the same queued effect. A process can stop after doing the external work but before committing completion. Another drainer can take over an expired lease. A declared retry policy also invokes the handler again after a failed attempt.
Use ctx.effectKey as an idempotency key in the external system so repeated calls produce one result. It stays the same across retry attempts and lease takeovers. Checking effectHistory can detect an already-completed effect, but cannot detect earlier retry attempts: the engine records one completion after the whole retry run ends.
Completion is first-writer-wins. When two dispatches of one effect both finish, the first completion to commit is the one recorded. The other one reports the entry in its lost bucket and writes nothing.
Failure settlement
Without a retry policy, a thrown handler error settles the effect as failed. With a policy, the engine can invoke the handler again before settling. Settlement removes the entry from pendingEffects, records an effectHistory row, and re-evaluates transitions.
Route failure explicitly with $effectStatus['<effect>'] == 'failed'. A condition using defined($effectStatus['<effect>']) accepts both success and failure. Once settled, the effect is not queued again unless another action execution queues it.
Handler context
These methods are available as the second argument to every registered effect handler.
ctx.setProgress(target, value)(): Promise<void>
Sets an absolute 0–100 progress value on a workflow- or stage-scoped progress field. Pending updates to the same target coalesce.
ctx.commitOps({ops, idempotencyKey})(): Promise<void>
Commits other field operations while the handler is running. Each report requires its own idempotency key.
Always await each report. Otherwise, un-awaited field operations can outrun backpressure and overflow the bounded report queue. Awaiting also surfaces a failed report where it was issued. Give every commitOps call a unique idempotency key.
'generate-assets': async (_params, ctx) => {
await ctx.setProgress('generationProgress', 25)
await ctx.commitOps({
idempotencyKey: `${ctx.effectKey}:asset-ready`,
ops: [
{
type: 'field.set',
target: {scope: 'workflow', field: 'assetStatus'},
value: {type: 'literal', value: 'ready'},
},
],
})
await ctx.setProgress('generationProgress', 100)
}generationProgress and assetStatus stand for progress and string fields the definition declares.
The context also carries instanceId, effectKey, log(message, extra?), client, and clientFor(ref). effectKey stays the same across retry attempts and lease takeovers. client is a concrete sibling of the createEngine client, bound to the workflow resource with its full surface intact, including namespaces such as client.agent.action. clientFor(ref) does the same for another resource. Untagged requests through either client use the request tag workflow.effect, and on a concrete client an explicit request tag is nested beneath that prefix. The engine never changes the client’s API version.
Completion field operations
A handler can return field operations with its outcome, and the engine applies them in the completion commit. Every field operation returned by an effect handler must set target.scope explicitly to workflow or stage, because an effect completion has no authoring site the engine could infer the scope from. A missing scope throws EffectOpsInvalidError, commits nothing, and leaves the effect pending so the corrected outcome can be reported again.
In this example the definition declares a workflow-scoped string field named accountRef, and createAccount stands for your own code:
import type {EffectHandler} from '@sanity/workflow-engine'
import {createAccount} from './accounts'
export const provisionAccount: EffectHandler = async (params) => {
const account = await createAccount(String(params.email))
return {
ops: [
{
type: 'field.set',
target: {scope: 'workflow', field: 'accountRef'},
value: {type: 'literal', value: account.ref},
},
],
}
}Runtime API
These methods live on the engine and runtime surfaces that claim, run, and complete queued effects. They are not properties of the effect declaration.
drainEffects({instanceId, names?})(): Promise
Claims eligible pending effects and invokes registered handlers. Optional non-empty
namesfilters effect names. Dispatches every claimable entry it selects. Returns drained, failed, skipped, and lost entries. See the engine API reference for the complete signature.completeEffect({effectKey, status, …})(): Promise
Reports a
doneorfailedoutcome for the entry’seffectKey. Adonecompletion may include declared outputs and field operations. A process that never claimed the effect, such as a webhook receiver or a cron job, can call it. Pass anidempotencyKeyon a retrying transport so a redelivery replays instead of failing. Completion is first-writer-wins.commitEffectOps({effectKey, claimToken, ops, idempotencyKey, …})(): Promise
Low-level mid-dispatch field report. Requires the exact unexpired claim token and renews the lease after a transactional commit. Effect handlers normally use ctx.commitOps or ctx.setProgress.
findPendingEffects({instanceId, claimed?, names?})(): Promise<PendingEffect[]>
Lists pending effects, optionally filtered by claim presence or effect name. A present claim may already be expired.
sweepStaleClaims({client, partition, instanceId})(): Promise<SweepStaleClaimsResult>
Releases expired claims without dispatching their effects. A standalone export, not an engine method.
drainEffects continues until no claimable entries remain, including effects queued by its own completion cascades, and groups the entries it handled:
drained
PendingEffect[]
The handler succeeded and the
donecompletion committed.failed
PendingEffect[]
The handler threw, after any retries, and the entry settled as
failed.skipped
PendingEffect[]
No handler is registered and
missingHandlerallowed skipping. The entry stays pending.lost
PendingEffect[]
Dispatched without being settled by this drainer. If another party completed or canceled the entry first, it is already settled. If the drainer lost its claim while the entry was still pending, a later drain can pick it up.
Evaluation insights and diagnostic utilities
A direct engine integration receives a WorkflowEvaluation from engine.evaluate({instanceId}). A reactive session exposes the same projection as session.evaluation and recomputes it when the instance, referenced content, guards, or field previews change.
Insights are explanations nested inside an evaluation. A condition insight explains why one condition is satisfied, unsatisfied, or unevaluable. WorkflowEvaluation.fieldInsights groups those explanations by the fields the conditions read.
Insights answer two questions: why an action, requirement, transition, or field is in its current state, and which condition outcomes would change if a field held a proposed value. Conditions work without them.
Condition insight sites
Evaluated nodes expose the insight beside the decision it explains:
StartRequirementEvaluation.insight
ConditionInsight | undefined
Explains one declared start requirement. Present on each entry of
StartEvaluation.requirements; absent for non-GROQ requirement kinds.ActionEvaluation.insight
ConditionInsight | undefined
Explains an action
filterwhen declared.ActionEvaluation.whenInsight
ConditionInsight | undefined
Explains the
whentrigger for a cascade-fired action.ActivityEvaluation.filterInsight
ConditionInsight | undefined
Explains an activity
filterwhen declared.ActivityEvaluation.requirementInsights
Record<string, ConditionInsight> | undefined
Explains each authored activity requirement. Required-reference readability checks appear in unmetRequirements with names such as field:source and have no condition insight.
TransitionEvaluation.insight
ConditionInsight
Explains the transition’s
whencondition. Every transition evaluation includes it.EditableFieldEvaluation.insight
ConditionInsight | undefined
Explains a field’s effective editable predicate when it is conditional.
Missing referenced documents
An instance cannot advance when a selected document cannot be read: the target of a required reference field, or of an optional reference that an unmet runtime requirement or transition condition reads. Fields covers requiredness and repair.
WorkflowEvaluation.missingDocuments lists the absent targets. Each MissingDocument carries the field target, the document reference, the declared title when available, and availability. blockingMissingDocuments is the subset that prevents current progress. Absence alone does not make every action unavailable.
When present, each entry's availability field carries the result of a completed check:
not-found
DocumentAvailability
No published, draft, or release version of the document exists. This holds both for a deleted document and for one that never existed, so do not describe it as a confirmed deletion.
unreadable
DocumentAvailability
Access is denied, or the availability check failed or is unsupported. Do not describe this result as deletion.
outside-perspective
DocumentAvailability
A representation exists, but it is absent from the content snapshot evaluated for this workflow.
evaluateFromSnapshot omits availability unless you pass a documentAvailability reader. Treat an omitted availability as missing evidence, not as deletion.
A missing required reference holds every caller-fired action and trigger in the stage, and every transition, even one whose condition is satisfied. Enable a control from the action’s full verdict, not from its condition insight. A blocked action reports disabledReason.kind requirements-unmet with unmetRequirements, a list of {name, title?, description?} descriptors. Authored activity requirements, the named GROQ readiness checks in an activity’s requirements array, keep their declared names and have an entry in requirementInsights. A required-reference check is named field:<name>, where <name> is the reference field’s name, such as field:subject, and has no entry in requirementInsights.
FieldInsight properties
field
string
The rendered
$fieldsentry name.reads
ConditionRead[]
Every distinct read of that field across current-stage condition sites.
involvedIn
InsightSite[]
The actions, action triggers, activity filters, requirements, transitions, or editable fields whose conditions read it.
proposals
FieldProposal[]
Verified assignments and the condition sites whose outcomes they change. Empty when no single concrete assignment can be proposed.
ConditionInsight properties
analysis
ConditionAnalysis
The parsed condition, its atom tree, and the scope reads found in it.
outcome
'satisfied' | 'unsatisfied' | 'unevaluable'
The engine’s verdict for the complete condition.
atoms
AtomInsight[]
Every atomic predicate with its outcome, pivotal flag, and any derivable requirement.
frontier
ConditionClause | undefined
The remaining unmet clause tree. Absent when the condition is satisfied.
blockedBy
AtomInsight[]
A flat, source-ordered list of the unmet frontier. Empty when the condition is satisfied.
AtomInsight
atom
ConditionAtom
The atomic predicate. Use
atom.groqfor display.outcome
ConditionOutcome
The atom’s current verdict.
pivotal
boolean
True when satisfying this atom alone, while other atoms keep their current outcomes, would satisfy the condition.
requirement
AtomRequirement | undefined
A machine-readable requirement when the atom can be solved from one scope read and a literal value.
Insight types and utilities
@sanity/workflow-engine exports the insight types and utilities:
import type {
AtomInsight,
AtomRequirement,
ConditionInsight,
ConditionOutcome,
ConditionRead,
FieldInsight,
FieldProposal,
InsightSite,
ScopeAssignment,
SiteConsequence,
} from '@sanity/workflow-engine'
import {
analyzeCondition,
explainCondition,
whatIfCondition,
} from '@sanity/workflow-engine'Engine and reactive consumers usually read the insights already present on WorkflowEvaluation. Use these utilities only when you need to analyze or evaluate a condition on its own. The package’s TypeScript declarations document every parameter.
analyzeCondition(): ConditionAnalysis
Parses a condition and returns its clause tree, atoms, scope reads, and whether it reads the dataset.
explainCondition(): Promise<ConditionInsight>
Evaluates one condition against a supplied dataset and parameter scope, then returns its outcome and atom-level explanation.
whatIfCondition(): Promise<WhatIfOutcome>
Re-evaluates a condition with one scope value replaced and reports the outcome before and after the assignment.
Instance history and audit trail contracts
History read paths
getInstance({instanceId})(): Promise
Primary programmatic API. Read the returned instance.history array.
client.fetch(query, params)(): Promise<WorkflowInstance[]>
Use GROQ against the workflow resource for reporting across instances. Always scope the query by partition with
tag == $tag.sanity-workflows show <instanceId> --include history(): CLI output
Print the instance and all history entries currently stored.
sanity-workflows tail <instanceId>(): stream
Stream history entries appended after the command starts.
HistoryEntry types
Every entry has _key, _type, and at. Every engine-stamped entry may also have executionContext. Event-specific fields are listed in the reference table below.
HistoryEntry is exported from @sanity/workflow-engine. It is a discriminated union: switch on entry._type and TypeScript narrows the available fields.
stageEntered
stage, fromStage?, transition?, via?, reason?, actor?
A stage becomes current.
stageExited
stage, toStage, transition?, via?, reason?, actor?
The instance leaves a stage.
transitionFired
fromStage, toStage, transition?, via?, reason?, actor?
A transition or administrative move changes stages.
activityStatusChanged
stage, activity, from, to, actor?
An activity changes status.
actionFired
stage, activity, action, actor?, driverKind?, triggered?
A caller or cascade fires an action.
opApplied
stage, activity?, action?, edit?, effect?, opType, target?, resolved?, actor?
An operation changes instance state. A
field.setIfMissingno-op writes no row.effectQueued
effectKey, effect, origin
An action queues an effect.
effectCompleted
effectKey, effect, status, outputs?, detail?, actor?
An effect settles.
effectClaimReleased
effectKey, effect, claim, via, actor?
An expired effect claim is taken over or swept.
spawned
activity, instanceRef, rowKey?, actor?
A child workflow is created.
subworkflowAdopted
stage, activity, instanceRef, rowKey
A live child is rebound on stage re-entry.
subworkflowResolved
activity, instanceRef, status
A child reaches done or aborted.
subworkflowOrphaned
instanceRef, detail
A terminal child cannot match a parent registry row.
fieldQueryDiscarded
scope, field, detail
A query-sourced initial value fails its declared shape.
aborted
stage, reason?, actor?
The instance is hard-stopped.
Activity feed lanes
An activity feed renders history in its stored order as what happened, and shows pendingEffects as live work rather than converting it into audit events.
instance.history
HistoryEntry[]
Durable, ordered workflow events. Use
actionFiredfor human decisions andeffectCompletedfor settled automation. Entries remain after the current work changes.instance.pendingEffects
PendingEffect[]
Current queued or claimed effect work. These rows disappear when they settle; completion is recorded durably in
historyand in the detailedeffectHistoryresult ledger.instance.effectHistory
EffectHistoryEntry[]
The result ledger for settled effect runs: status, duration, outputs, and error detail. Rows correlate with
historyentries througheffectKey. Conditions read declared effect outputs through$effects, never thehistoryarray.
Retention and deletion
The engine never prunes an instance’s history, including after the workflow finishes. deleteDefinition never deletes instance documents: with cascade it aborts active instances and leaves their documents as the audit record, and without it the delete refuses while such instances exist. A retention or deletion policy you add removes that record. Never mutate a live instance outside the engine.
Custom audit rows
The authoring audit operation appends a timestamped, attributed row to a workflow field such as notes. That row is business data your workflow defines. It does not replace the engine-owned history trail. See Operations.
Visiting agent?
Workflows includes an MCP server for inspecting, operating, authoring, validating, and deploying workflows. Ask your human to set up the MCP server.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?