Workflows

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 apiVersion works.

  • 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. Passing tag instead throws ContractViolationError.

  • resourceClients

    ResourceClientResolver

    Optional. Returns a client for another dataset or project, or undefined to 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.

  • Optional. Default 24 hours. How long a recorded idempotencyKey dedupes retries.

  • clock

    () => string

    Optional. Returns the ISO time for $now and 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 drainEffects and verifyDeployedDefinitions.

  • 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, and doc.refs fields 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 own semantics the 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.

  • 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-failed means the definition's abort roles do not admit this actor, so hide the abort control. A terminal instance reports instance-completed or instance-aborted. Required: code that builds a WorkflowEvaluation by 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.

  • Optional. Set on an action with when. Narrate it rather than render a button; disabledReason is cascade-fired.

  • disabledReason

    DisabledReason

    Optional. Present when allowed is false; the first failing check wins. kind is filter-failed, cascade-fired, activity-not-active, stage-terminal, mutation-guard-denied, instance-completed, instance-aborted, requirements-unmet, or subject-permission-denied.

  • firing

    {exitsStage: boolean, transition?: string}

    Optional. What firing now would do, replayed in memory. exitsStage is true when the cascade leaves the current stage; transition names the selected transition. Omitted when the answer depends on caller params, a spawn, a terminal instance, a diverged stage, or an action with when.

  • insight

    ConditionInsight

    Optional. Explains the filter. Present when the action declares one.

  • whenInsight

    ConditionInsight

    Optional. Explains the when trigger.

  • holderGate

    {holders: Assignee[]}

    Optional. A $assigned filter hid this action; holders names 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

Drive instances directly

Reactive layer and document discovery

Effect runtimes

Inspection and diagnostics

Cleanup and recovery

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

    false when the command succeeded without changing state: a repeat fire of a resolved activity, a tick that wrote nothing, a setStage already at the target, an abort of a finished instance, or a processed idempotencyKey.

  • ranOps

    OpAppliedSummary[]

    Optional. Operations that ran during the action commit.

  • Optional. Earliest future ISO instant when time alone can change the instance. Schedule the next tick for it. Excludes conditions that combine $now with 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 partition passed to createEngine. The field keeps the name tag in stored documents and GROQ ($tag).

  • workflowResource

    WorkflowResource

    Sanity resource where the instance is stored.

  • Name of the deployed workflow definition.

  • 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.

  • 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 with startInstance; 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, and expiresAt. Rows expire after idempotencyTtlMs (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.

  • 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.

  • 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.

  • 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 drainEffects and verifyDeployedDefinitions do with an effect name no handler covers. 'fail', the default, throws MissingHandlerError. '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.

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 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 done completion committed.

  • failed

    PendingEffect[]

    The handler threw, after any retries, and the entry settled as failed.

  • skipped

    PendingEffect[]

    No handler is registered and missingHandler allowed 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:

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 $fields entry 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.groq for 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.

Instance history and audit trail contracts

History read paths

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.setIfMissing no-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 actionFired for human decisions and effectCompleted for settled automation. Entries remain after the current work changes.

  • Current queued or claimed effect work. These rows disappear when they settle; completion is recorded durably in history and in the detailed effectHistory result ledger.

  • instance.effectHistory

    EffectHistoryEntry[]

    The result ledger for settled effect runs: status, duration, outputs, and error detail. Rows correlate with history entries through effectKey. Conditions read declared effect outputs through $effects, never the history array.

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?

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme