> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# 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, agent hosts, 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/workflows](https://reference.sanity.io/_sanity/workflow-engine/) and [@sanity/workflows-test](https://reference.sanity.io/_sanity/workflow-engine-test/).

A [definition](https://www.sanity.io/docs/workflows/definitions-and-instances) describes a process. When your code calls it, the engine starts instances of the definition, evaluates their current state, and applies the operations that move them forward.

You may not need to call the engine directly. The [CLI](https://www.sanity.io/docs/workflows/deploy-definitions) and [agent hosts](https://www.sanity.io/docs/workflows/mcp) wrap it for command-line and agent workflows. The [reactive session](https://www.sanity.io/docs/workflows/reactive-session), App SDK adapter, and [Studio plugin](https://www.sanity.io/docs/workflows/studio-plugin) create and call it inside an application. Create an engine yourself when you are building a custom server-side integration, worker, or Function.

## 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](https://www.sanity.io/docs/workflows/run-the-engine). This example uses the quick start’s `dev` deployment and assumes the `article-review` definition is already deployed:

```typescript
import {createClient} from '@sanity/client'
import {createEngine, gdrRef, instanceDocId} from '@sanity/workflows'

const client = createClient({
  projectId: 'PROJECT_ID',
  dataset: 'DATASET_NAME',
  apiVersion: '2026-10-01',
  token: process.env.SANITY_API_TOKEN!,
  useCdn: false,
})

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'}),
    },
  ],
})
```

Pass your own `instanceId` to make a programmatic start safe to retry. If a start is interrupted, retry it with the same ID, and the engine finishes creating and starting that instance. Retrying a start that already finished does nothing. If you leave the ID out, each call generates a new one, so a blind retry can create a second instance. Reusing an ID for a different definition, or for a different explicitly selected version, throws `ContractViolationError`.

`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 a `partition`, and it has no default. After construction, `engine.partition` returns the bound value.

When `client` has `withConfig`, as `@sanity/client` does, the engine reaches content in other datasets, projects, Media Libraries, Canvases, and dashboards with no extra option. It reads and writes them through a sibling of `client`, derived with `withConfig`, and accepts a reference to any of them. Pass a `resourceClients` resolver to give a resource its own client, or to narrow the resources a written reference may name. These helpers build one:

- `deploymentResourceClients({client, deployment})` serves only the resources a deployment binds in `resourceAliases`. It derives each client from `client` with `withConfig`. The engine then refuses a written reference to any other resource with `RefResourceUndeclaredError`. The CLI uses it.
- `deploymentAliasResolver({deployment, clientFor})` serves the same resources with clients you build. It calls `clientFor(resource)` once for each resource, when you build the resolver, and uses the client it returns. The generated runtime uses it with its `clientFactory`.
- `reachableResourceClients({client, workflowResource})` serves every resource except the workflow resource: any dataset in any project, and any Media Library, Canvas, or dashboard. That matches the routing without `resourceClients`. It derives each client from `client` with `withConfig`, so each one keeps the same token, API host, and request-tag prefix. It caches one client per resource.

`foreignAliasResources(deployment)` returns the resources `deploymentResourceClients` and `deploymentAliasResolver` serve: each resource the deployment binds in `resourceAliases` other than its workflow resource, once, in binding order. Use it to list the clients you need to build.

`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 in your own process, register handlers in `effects` when you construct the engine, then call `drainEffects`. [Effect runtime configuration](https://www.sanity.io/docs/workflows/engine) lists the options, and [Run an external step with an effect](https://www.sanity.io/docs/workflows/effects-and-runtimes) 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` in the [@sanity/workflows API reference](https://reference.sanity.io/_sanity/workflow-engine/).

#### Properties

**client** (SanityClient, required)

Required. Authenticated client for the workflow resource. Every engine write commits with this client's token. Without access, the engine also resolves the caller from that token, so keep its auth stable; to act as someone else, create another engine or pass access. Any apiVersion works.

Without access, the engine reads the caller’s grants for $can from the access control list of workflowResource: /projects/<id>/datasets/<dataset>/acl for a dataset, /media-libraries/<id>/acl for a Media Library, or /canvases/<id>/acl for a Canvas. A dashboard has no access control list, so deploy refuses a definition that reads $can there with ResourceCapabilityError.

A grants read refused with HTTP 401 to 404 leaves $can unbound for that client. Any other failure leaves it unbound for that call only, and the next evaluation or write reads the grants again.

@sanity/client’s SanityClient qualifies. A hand-written client implements fetch, getDocument, getDocuments(ids, options?), patch, create, and transaction. createEngine throws ContractViolationError for a client without getDocuments. Its getDocument and getDocuments must return every commit already applied, including async and deferred ones, so read the document endpoint, not GROQ. A patch’s commit() must resolve to the complete committed document with its new _rev.

**workflowResource** (WorkflowResource, required)

Required. Resource that stores definitions and instances.

**partition** (string, required)

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 the resource of a global document reference (GDR), or undefined to let the engine route it. Without it, and when client has withConfig, the engine routes every resource through a sibling of client and accepts a written reference to any of them. With it, a written reference may name only the workflow resource and the resources it returns a client for.

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

**access** ({actor: Actor, grants?: Grant[], attributes?: Record<string, unknown>, localPrincipalId?: string})

Optional. Names the actor the engine evaluates roles and conditions for when your host commits with its own credential on behalf of someone else. It grants nothing: every write still commits with client's token, and the Content Lake checks the write against that token. The raw workflow.* verbs take the same access per call. Omit it to resolve the caller from the token.

With access, every history row that records an actor names access.actor, whichever verb or effect drainer wrote it. $actor and action and abort roles read actor, $can reads grants, and $attributes reads attributes, in every verb and in engine.session(). The engine never asks the Content Lake who the caller is and never fills an omitted part from the token: without grants, $can is unbound, and without attributes, $attributes is unbound, so conditions that read either fail closed. Evaluations don’t report subject-permission-denied for subjects in other resources.

actor.id must be an account-global user ID (the Sanity user ID) or a robot ID, and actor.kind one of person, agent, or system. Anything else throws ContractViolationError. The engine stores only the actor's kind, id, roles, and onBehalfOf.

The engine doesn't verify the assertion. Pass only an identity your host has authenticated, and read actor.roles from the workflow resource's member list, never from the client request. On a project dataset, also pass localPrincipalId, the caller's project user ID. Without it, guard previews compare the account-global ID with the project user IDs that guards deploy, so attribution guards deny the caller. Don't set access on an engine that drains effects for every caller, because every claim it stamps would name that one caller.

**idempotencyTtlMs** (number)

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.

Some services write workflow instances on behalf of an editor. For example, a review service can fire an approval for the editor who clicked it. In that case, keep the service token on the client and pass the editor as `access`. The engine then uses each identity for a different job:

- The Content Lake authorizes the write against the service token, because the client sends that token.
- History rows name the editor as the actor.
- The action’s `roles` are checked against the editor’s roles.

The engine doesn’t verify the editor’s identity, so pass only an editor your service has authenticated. This example fires an approval for such an editor:

```typescript
import {createClient} from '@sanity/client'
import {createEngine, type Grant} from '@sanity/workflows'

// An editor your service has authenticated, with roles from the project's member list.
interface AuthenticatedEditor {
  sanityUserId: string
  projectUserId: string
  roles: string[]
  grants: Grant[]
}

const serviceClient = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'production',
  apiVersion: '2026-10-01',
  token: process.env.SANITY_SERVICE_TOKEN!,
  useCdn: false,
})

export async function approveFor(editor: AuthenticatedEditor, instanceId: string) {
  const engine = createEngine({
    client: serviceClient, // every write commits with the service token
    partition: 'default',
    workflowResource: {type: 'dataset', id: 'YOUR_PROJECT_ID.production'},
    executionContext: {kind: 'server', id: 'review-service'},
    access: {
      actor: {kind: 'person', id: editor.sanityUserId, roles: editor.roles},
      grants: editor.grants,
      localPrincipalId: editor.projectUserId,
    },
  })
  return engine.fireAction({instanceId, activity: 'decide', action: 'approve'})
}
```

### WorkflowEvaluation

The engine and reactive session return the same read-only projection of one instance:

#### Properties

**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 on an instance started from a definition deployed at model 10 or later, and references read by unmet activity 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.

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

#### Properties

**action** (Action, required)

The stored action declaration.

**semantics** (ActionSemantic[])

Optional. The action's semantics, unchanged.

**allowed** (boolean, required)

Whether the actor may fire the action now.

**triggered** (true)

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 on the assumption that the fire is accepted. exitsStage is true when the cascade leaves the current stage; transition names the selected transition. For an action with params, the replay uses the values given in actionParams. A param that is not given leaves firing present when nothing before transition selection reads its value. A given doc.ref or doc.refs value that points at a document the evaluation does not hold counts as not given. Omitted when the outcome reads a param value that is not given, when a given value fails the action’s param validation, and when the answer depends on a spawn, a terminal instance, a diverged stage, or an action with when. The replay does not check project membership or role eligibility for assignees written from given values.

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

**scripts/evaluate.ts**

```typescript
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)
  }
}
```

`evaluate` and `evaluateFromSnapshot` accept an optional `actionParams` list. Use it to preview where an action leads before the editor submits the action’s form. Each `ActionParamsEntry` holds the `{activity, action, params}` that a later `fireAction` call would send. Only the `firing` preview reads these values. The list follows these rules:

- A param that is left out, `undefined`, or `null` counts as not given.
- Two entries for the same activity and action throw `ContractViolationError`, even when the action is outside the current stage.
- A single entry for an action outside the current stage is ignored.

This example assumes a `send-back` action with two params: a `decision` that an op copies into a field the stage’s transitions read, and a `note` that nothing before transition selection reads. While the editor has picked a decision but not written the note, `firing` already names the transition:

**scripts/preview-form.ts**

```typescript
import type {ActionParamsEntry} from '@sanity/workflows'
import {engine} from './engine'

// The values an editor has entered so far in the send-back form.
const form: ActionParamsEntry = {
  activity: 'fact-check',
  action: 'send-back',
  params: {decision: 'changes-requested', note: undefined},
}

const evaluation = await engine.evaluate({instanceId: 'INSTANCE_ID', actionParams: [form]})
const sendBack = evaluation.currentStage.activities
  .find(({activity}) => activity.name === form.activity)
  ?.actions.find(({action}) => action.name === form.action)

if (sendBack?.firing) {
  console.log(sendBack.firing.exitsStage ? `Leads to ${sendBack.firing.transition}` : 'Stays in this stage')
} else {
  console.log('The destination depends on a value the form does not have yet')
}
```

With no `decision` given, or a `decision` the param does not accept, the script prints the fallback line, because the transition reads a value the evaluation does not have.

### Engine methods

These methods are called on the engine instance returned by `createEngine(...)`. Higher layers such as the CLI, agent hosts, 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`.

The `nextEvaluationAt` on an `OperationResult` is computed without a caller. It ignores conditions that combine `$now` with a caller variable: `$actor`, `$assigned`, `$can`, or `$attributes`. The `WorkflowEvaluation` for a specific caller includes those conditions when it can evaluate them. If you pass a `clock`, the engine reads it once per cascade pass, and one command can run several 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. The script imports `engine` from `scripts/engine.ts`, a module that exports the engine you created with `createEngine`:

**scripts/run.ts**

```typescript
import {gdrRef} from '@sanity/workflows'

import {dev} from '../sanity.workflow'
import {articleReview} from '../workflows/article-review'
import {engine} from './engine'

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.missingHandler to 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. Takes an optional actionParams list for actions with params.

**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. Add a row key to the target to set, unset, or move one row of an array field.

**tick(): Promise<OperationResult>**

Reevaluates an instance and continues any newly enabled cascade. The engine never calls itself on a schedule, so call tick to recheck conditions that read $now.

**children(): Promise<WorkflowInstance[]>**

Lists child instances spawned by a parent.

It reads children by GROQ, so it can miss a commit made in the last second or so. See Commit visibility.

#### 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 is resolved, missing, inaccessible, or not-person. Agent and system actors return not-person without a lookup. The standalone resolveClientActor(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.

It reads by GROQ, so it can miss a commit made in the last second or so. See Commit visibility.

**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 every claimable pending effect, runs its registered handler in the calling process, and commits the result. 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.

The query can miss a commit made in the last second or so. See Commit visibility.

**queryInScope(): Promise<T>**

Runs GROQ against the instance snapshot and rendered workflow scope.

**clientForGdr(parsed)(): WorkflowClient**

Returns the client the engine reads a parsed GDR's resource with: the resourceClients resolver's client when it serves that resource, else the engine client for the workflow resource or a sibling derived from it with withConfig. Throws ContractViolationError for a foreign resource when no client can be derived. Tools built on an engine use it to read foreign documents the way the engine does.

#### Cleanup and recovery

**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`, `abortInstance`, and `resetActivity`, returns this shape. Failures throw.

#### Properties

**instance** (WorkflowInstance, required)

The instance after the command and its cascade. See Workflow instance document.

**cascaded** (number, required)

Transitions the engine fired during the cascade.

**changed** (boolean, required)

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

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

**scripts/fire.ts**

```typescript
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)
```

### Commit visibility

By default, instance commands return before the Content Lake’s query index includes their changes. Reads by document ID see the change at once. These include the instance the command returns, `getInstance`, and the engine’s own reads while it commits and cascades. Every instance write still checks `ifRevisionId`, so a write fails rather than overwrite a newer revision.

GROQ queries can miss the change for up to about a second. This affects `engine.query`, `instancesForDocument`, `children`, `definitionsForDocument`, `evaluateStart`, the in-flight instance check in `deleteDefinition`, and your own GROQ instance lists when you run them straight after a command.

`startInstance`, `fireAction`, `editField`, `completeEffect`, `commitEffectOps`, `tick`, `abortInstance`, and `resetActivity` accept a per-call `visibility` with `@sanity/client`’s values: `'async'` (the default), `'sync'`, or `'deferred'`. With `'sync'`, every instance commit the call makes waits for the query index. Pass `visibility: 'sync'` when you query by GROQ straight after the command, typically in scripts and end-to-end tests:

```typescript
await engine.fireAction({instanceId, activity: 'review', action: 'approve', visibility: 'sync'})
const approved = await engine.query({
  groq: '*[_type == "sanity.workflow.instance" && tag == $tag && currentStage == "approved"][0...50]',
})
```

Some commits don’t use the `visibility` you pass:

- Some instances always commit with `'sync'`. This happens when the instance’s definition, or the definition of an ancestor or a live child, has a query-sourced field, a `spawn`, a `singleSubject` start requirement, or a `start.filter` or `groq` start requirement that reads the dataset (`*[…]` or `->`), such as a limit on unfinished instances. Those features run GROQ that must see the engine’s earlier writes. As a result, a `singleSubject` start still refuses a second instance on a subject started a moment earlier, and an instance limit counts an instance started just before.
- `drainEffects` and `sweepStaleClaims` take no `visibility` option. Effect claims, lease renewals, and `sweepStaleClaims` always commit with `'async'`. Effect completions from a drain commit with `'async'`, unless the instance always commits with `'sync'`.
- Definition deploys, definition deletes, and guard writes always commit `'sync'`.

### Code generator helpers

`@sanity/workflows/generate` exports helpers for code that generates Functions from workflow definitions. `functionTriggerOf(type)` returns the Functions trigger of a resource type as a `FunctionTrigger`. Its `functionType` is the Blueprints function resource type. Its `documentTypes` lists the document types a write must have to fire the trigger, and is `undefined` when the trigger fires on writes of every type. For `canvas` and `dashboard`, `functionTriggerOf` throws `ResourceCapabilityError` with `capability: 'functionEvents'`.

### Resource type helpers

`@sanity/workflows` exports helpers that answer what a resource type supports and how to name it, so an integration doesn’t compare resource types itself. They read the same table as [What each resource type supports](https://www.sanity.io/docs/workflows/global-document-references):

**RESOURCE_TYPES(): readonly ['dataset', 'canvas', 'media-library', 'dashboard']**

Every resource type, in this fixed order.

**isResourceType(value)(): value is GdrScheme**

Whether a string names a resource type: dataset, canvas, media-library, or dashboard.

**resourceLabel(type)(): string**

The display name of a resource type: dataset, Media Library, Canvas, or Dashboard. The dataset name is lowercase; capitalize it at the start of a sentence or label.

**describeResource(resource)(): string**

A resource as text for messages: its type’s display name, then its ID, such as dataset acme.production.

**resourceName(resource, from)(): string | undefined**

The name a reader knows resource by, seen from the resource from: a dataset’s name, or its full <projectId>.<dataset> ID when it sits in another project than from. undefined for a Media Library, Canvas, or dashboard, whose IDs aren’t names.

**documentUrl({type, documentId, organizationId, dashboardOrigin})(): string | undefined**

The URL that opens a document in the Sanity Dashboard, or undefined when no Dashboard page opens that resource type: a dataset document opens in a Studio, and a dashboard document has no page. dashboardOrigin is the Dashboard host, https://www.sanity.io in production. organizationId is the organization that owns the resource. The page asks the reader to sign in and checks their access. For example, a Canvas document doc-1 in organization oAbc123 opens at https://www.sanity.io/@oAbc123/canvas/doc/doc-1.

**resourceListPath(type)(): string | undefined**

The API path that lists the caller’s resources of a type on the global API host, answering {data: [{id, organizationId}]}. undefined for dataset, because datasets are listed per project.

**hasCapability(type, capability)(): boolean**

Whether resources of a type provide a capability: drafts, versions, perspectives, releases, history, grants, roles, members, organization, or functionEvents. A Canvas, for example, has no members or roles.

**directoryOf(resource)(): ResourceDirectory**

Where a resource’s people and roles live: {kind: 'project', projectId} for a dataset, whose people are its project’s members, or {kind: 'access', resource} for every other type. Check hasCapability too: a type without members still names a directory, and that directory lists nobody.

## 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` in the [@sanity/workflows API reference](https://reference.sanity.io/_sanity/workflow-engine/).

### Identity and definition pin

These fields identify the instance and preserve the definition it started with.

#### Properties

**_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.

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

#### Properties

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

#### Properties

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

#### Properties

**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)

The reader model: the lowest stored-data model version an engine must support to read the document. An engine that doesn't support it refuses to read the document.

## 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](https://www.sanity.io/docs/workflows/workflow-authoring-reference).

### Effect declaration

This is an effect request in an action’s `effects` array, commonly authored with `defineEffect(...)`. Its `name` connects the declaration to the handler registered under that name on the engine your runtime drains with.

#### Properties

**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. A whole document, such as '$fields.subject', resolves to its reference and the revision the binding read, {id, type, rev}. Read it with context.getDocument. A path such as '$fields.subject.title' resolves to its value when the effect was queued. A projection or spread, such as '{...$fields.subject}', builds a new object, so it stores a copy of the fields it reads.

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

#### Properties

**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 the engine call that queues the effect has an actor.

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

#### Properties

**kind** ('engine')

The engine runs the policy inside one drain call. Authoring may omit this property; the stored definition contains 'engine'.

**attempts** (number, required)

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.

With this declaration, the engine attempts the `notify-reviewer` handler up to three times, counting the first attempt:

**workflows/article-review.ts**

```typescript
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, followed by the handler’s own `detail` when it returns one, such as `succeeded on attempt 2 of 3: Posted to #releases`. 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 runtime registers the handlers for the effects it runs, so an effect’s handler can run in a different process from the one that queued it.

#### Properties

**handlers** (Record<string, EffectHandler>)

Handlers keyed by the effect name the definition queues. One handler per name.

hasEffectHandler(handlers, name) reports whether a handler map registers an effect by the drain’s rule: an own entry that is not undefined. Inherited names such as toString never count.

**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 pending effect before it runs the handler. A claim is a lease that lasts `effects.leaseMs`. If the lease expires, another drain can take over the effect and run its handler again. The takeover writes an `effectClaimReleased` history row.

`sweepStaleClaims({client, partition, instanceId})` cleans up claims. It’s a standalone export of `@sanity/workflows`, not an engine method. It does two things:

- It releases expired claims without running their handlers.
- It re-queues a pending effect that no drain has claimed for `DEFAULT_EFFECT_LEASE_MS` (five minutes). It sets the entry’s `queuedAt` to the sweep time and leaves the entry unclaimed. That change to `pendingEffects` wakes a drain trigger that watches it.

The sweep 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. A handler can read `ctx.attempt` to tell a retry from a first try.

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 and properties 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 progress field. On an instance started from a definition deployed at model 12 or later, a bare name, or {field}, resolves from the activity whose action queued the effect: its field, then the stage’s, then the workflow’s. On an instance started from an earlier definition, a bare name or {field} writes the workflow field. Pass {scope, field} to address one scope directly; scope can be activity, stage, or workflow. A bare name that resolves to a stage or activity field writes only while the stage visit that queued the effect is open, and throws EffectOpsInvalidError after it closes. Pending updates to the same target coalesce.

**ctx.commitOps({ops, idempotencyKey})(): Promise<void>**

Commits other field operations while the handler is running. Each operation sets target.scope to workflow, stage, or activity, as completion operations do. Each report requires its own idempotency key.

**ctx.attempt(): number**

This call's attempt number within the effect's retry policy run. It is 1 on the first try and one higher for each retry the policy admits after a failed attempt. It counts within one dispatch only: a redispatch after a lapsed claim, or the run a later drain starts, begins again at 1.

**ctx.redelivered(): boolean**

true when an earlier dispatch of this effect may have started: the stale-claim sweep released a claim on it, or a drain took it over after its lease lapsed. false on a first dispatch. It stays the same for every attempt of one retry policy run, so a handler can tell a redispatch from a first dispatch even though ctx.attempt starts again at 1.

**ctx.getDocument(ref, options?)(): Promise<SanityDocument | undefined>**

Reads a document a binding references. Pass the {id, type, rev} a whole-document binding stores, or any global document reference. The read uses the client for the document’s resource and follows the instance’s perspective: the version in the instance’s releases first, then the draft when the perspective includes drafts, then the published document. It resolves undefined when none of them exists.

Options: signal aborts the read, tag sets the request tag, and releaseId names a Content Release whose version is read before the instance’s releases. at: 'rev' reads the revision the binding recorded, from document history.

With at: 'rev', a revision that can’t be read throws. The read never returns the current version instead. A revision older than the resource’s history retention throws DocumentRevisionUnavailableError with ref, rev, and reason: 'not-in-history'. A dashboard keeps no document history, so a read there throws ResourceCapabilityError with capability: 'history'. A revision read needs a client with both request and getDataUrl, as @sanity/client has.

Instances started from a definition deployed with an earlier engine version store a copy of the document instead. getDocument accepts that copy too: a current read loads the document by its _id, and at: 'rev' returns the copy.

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.

```typescript
'generate-assets': async (_params, ctx) => {
  await ctx.setProgress('generationProgress', 25)
  await ctx.commitOps({
    idempotencyKey: `${ctx.effectKey}:asset-ready`,
    ops: [
      {
        type: 'field.set',
        target: {scope: 'activity', field: 'assetStatus'},
        value: {type: 'literal', value: 'ready'},
      },
    ],
  })
  await ctx.setProgress('generationProgress', 100)
}
```

`generationProgress` and `assetStatus` stand for progress and string fields that the activity queuing the effect declares. The bare `generationProgress` name resolves from that activity outward, so a same-named activity field wins over a stage or workflow field.

This handler reads the article that a binding `{article: '$fields.subject'}` references. It compares the current version with the version the action approved:

```typescript
import {DocumentRevisionUnavailableError, type EffectHandler} from '@sanity/workflows'

export const notifyReviewer: EffectHandler = async (params, context) => {
  // params.article is {id, type, rev}, bound with '$fields.subject'
  const article = await context.getDocument<{title?: string}>(params.article)
  if (!article) return // deleted after the effect was queued

  try {
    const approved = await context.getDocument(params.article, {at: 'rev'})
    if (approved?._rev !== article._rev) {
      context.log('The article changed after approval', {id: article._id})
    }
  } catch (error) {
    if (!(error instanceof DocumentRevisionUnavailableError)) throw error
    context.log('The approved revision is no longer in history', {reason: error.reason})
  }

  console.log(`Notify the reviewer: ${article.title} is ready`)
}
```

The handler context also carries these values:

- `instanceId`: the ID of the instance that queued the effect.
- `effectKey`: the queued effect’s key. It stays the same across retry attempts and lease takeovers.
- `log(message, extra?)`: logs a message from the handler.
- `client`: a client for the workflow resource. It’s a sibling of the `createEngine` client with the same credentials and its full API, including namespaces such as `client.agent.action`.
- `clientFor(ref)`: a client of the same kind for the resource that `ref` points at.

Requests through either client that set no request tag use the tag `workflow.effect`. If the client supports `withConfig`, such as `@sanity/client`, a tag you set is nested under `workflow.effect`. The engine never changes the client’s API version.

A handler resolves to nothing or to `{outputs?, ops?, detail?}`: declared outputs, completion field operations, and a short note string. The engine stores `detail` on the settled run’s `effectHistory` entry and its `effectCompleted` history row, and Studio shows it as the effect’s note. A non-string `detail` fails the attempt.

### 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`, `stage`, or `activity`, 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.

An `activity` target writes a field on the activity whose action queued the effect. The write works only while the stage visit that queued the effect is open. A stage visit starts when the instance enters the stage and ends when it leaves. The write fails in these cases:

- The instance has left that stage visit, including a loop back into the same stage.
- The engine cannot identify the activity: the effect was queued before the engine recorded its stage entry, or the pinned definition declares the effect name more than once.

What happens on that failure depends on where the operation came from:

- From `commitOps`: the call throws `EffectOpsInvalidError`.
- From a completion: the effect settles as `failed` with that error’s message. The engine records none of the completion’s operations, outputs, or detail, and doesn’t dispatch the effect again.

When a dispatch’s own `commitOps` or `setProgress` report closes that stage visit, because its write satisfies a transition, the dispatch’s later activity-scope writes are skipped, completion operations included. So are bare `setProgress` names that resolved to a stage or activity field. The engine logs each skip at the info level through its logger, applies the remaining operations, and completes the effect normally.

Some field reads inside an effect’s operations don’t name a scope: a `fieldRead` value without `scope`, and `$fields` in the `where` of `field.updateWhere` or `field.removeWhere`. The engine looks these fields up in this order:

- On an instance started from a definition deployed at model 12 or later, while the stage visit is open and the engine can identify the activity: the queuing activity, then the stage, then the workflow.
- Otherwise, including on every instance started from an earlier definition: the stage, then the workflow.

To read one scope only, give the `fieldRead` an explicit `scope`.

In this example the definition declares a workflow-scoped string field named `accountRef`, and `createAccount` stands for your own code:

**effect-handlers.ts**

```typescript
import type {EffectHandler} from '@sanity/workflows'

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

Your runtime calls these methods to claim, run, and complete queued effects. They are not properties of the effect declaration.

**drainEffects({instanceId, names?})(): Promise**

Claims eligible pending effects, runs the handlers registered on this engine in the calling process, and commits each result. Optional non-empty names filters 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 done or failed outcome for the entry’s effectKey. A done completion 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 an idempotencyKey on 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:

#### Properties

**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:

#### Properties

**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 filter when declared.

**ActionEvaluation.whenInsight** (ConditionInsight | undefined)

Explains the when trigger for a cascade-fired action.

**ActivityEvaluation.filterInsight** (ConditionInsight | undefined)

Explains an activity filter when 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 when condition. 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 activity requirement or transition condition reads. The required-reference rule applies to instances started from a definition deployed at model 10 or later. On an instance started from an earlier definition, a required reference blocks progress only when such a requirement or condition reads it. To choose how a workflow handles deleted content, see [Handle workflows when referenced content is deleted](https://www.sanity.io/docs/workflows/cookbook-handle-deleted-subject).

`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:

#### Properties

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

Under the required-reference rule, a missing required reference blocks the current stage. It holds every caller-fired action and trigger in the stage, and every transition, even one whose condition is satisfied. So enable a control from the action’s full verdict (`allowed` and `disabledReason`), not from its condition insight.

A blocked action reports `disabledReason.kind` as `requirements-unmet`. Its `unmetRequirements` list holds `{name, title?, description?}` descriptors of two kinds:

- Authored activity requirements: the named GROQ readiness checks in an activity’s `requirements` array. They keep their declared names and have an entry in `requirementInsights`.
- Required-reference checks: named `field:<name>`, where `<name>` is the reference field’s name, such as `field:subject`. They have no entry in `requirementInsights`.

### FieldInsight properties

#### 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

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

**reads** (ResolvedRead[] | undefined)

Every unique scope read in the condition, such as $fields.claimedBy.id, as {read, value}. value is what GROQ access reaches in the evaluated scope: undefined when the variable is absent or a step cannot be followed, and null when the stored value is null. Evaluation insights always set it; an insight built another way may omit it.

### AtomInsight

#### Properties

**atom** (ConditionAtom)

The atomic predicate. atom.groq holds its GROQ for tooling; don't show it to readers. To render an atom, use describeAtom, whose text never contains GROQ.

**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. A negated comparison solves to its complement: !($fields.amount > 100) gives a compares requirement with op: '<=' and value: 100.

### Insight types and utilities

`@sanity/workflows` exports the insight types and utilities:

```typescript
import type {
  AtomInsight,
  AtomRequirement,
  ConditionInsight,
  ConditionOutcome,
  ConditionRead,
  FieldInsight,
  FieldProposal,
  InsightSite,
  ResolvedRead,
  ScopeAssignment,
  SiteConsequence,
} from '@sanity/workflows'

import {
  analyzeCondition,
  explainCondition,
  whatIfCondition,
} from '@sanity/workflows'
```

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`. The following table lists the fields each entry type adds.

`HistoryEntry` is exported from `@sanity/workflows`. It is a discriminated union: switch on `entry._type` and TypeScript narrows the available fields.

#### Properties

**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 changes stages.

**activityStatusChanged** (stage, activity, from, to, actor?)

An activity changes status.

**actionFired** (stage, activity, action, actor?, driverKind?, triggered?)

A caller fires an action, or the engine fires one during a cascade.

**opApplied** (stage, activity?, action?, edit?, effect?, opType, target?, resolved?, actor?)

An operation changes instance state. On a direct edit or an effect’s write to an activity field, activity names the activity whose field it wrote. 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.

#### Properties

**instance.history** (HistoryEntry[])

Durable, ordered workflow events. Use actionFired for human decisions and effectCompleted for 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 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](https://www.sanity.io/docs/workflows/workflow-authoring-reference).

> [!NOTE]
> Visiting agent?
> Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host [includes the Workflows tools](https://www.sanity.io/docs/workflows/mcp).





## Related changelog entries

Entries are listed newest first; each link points to the full entry as markdown. Follow one when you need to know what changed, when, or why — for example, to summarize recent updates, explain behavior that differs from older documentation, or check whether a fix has shipped.

- [Workflows v0.38.0: Faster engine calls and two runtime stacks](https://www.sanity.io/docs/changelog/workflows-MC4zOC4w.md) — November 10, 2026