Workflows

Definitions, instances, and stages

A definition describes a process. An instance is one run of it, pinned to the definition version it started under and sitting in exactly one stage.

You write a workflow definition in code and deploy it. It describes a process and combines fields, stages, transitions, activities and actions, conditions, effects, and guards. Each deployed version of a definition stays fixed.

An instance stores the state of one pass through a definition. One definition can produce many instances. Each has its own field values, current stage, history, pending effects, and child workflows.

Definition versioning

Use defineWorkflow from @sanity/workflows/define to author a definition. An instance of this definition starts in a Drafting stage. The condition of its submit transition is true, so the engine moves the instance to a Review stage right after it starts:

import {defineField, defineStage, defineTransition, defineWorkflow} from '@sanity/workflows/define'

const articleReview = defineWorkflow({
  name: 'article-review',
  title: 'Article review',
  initialStage: 'drafting',
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      initialValue: {type: 'input'},
      required: true,
    }),
  ],
  stages: [
    defineStage({
      name: 'drafting',
      transitions: [defineTransition({name: 'submit', to: 'review', when: 'true'})],
    }),
    defineStage({name: 'review'}),
  ],
})

defineWorkflow validates the definition before anything reaches the Content Lake. It expands shorthand into the stored shape, then checks rules that span the whole definition:

  • Names must be unique.
  • Every transition target must name a declared stage.
  • Every stage must be reachable from the initial stage.
  • No named predicate may reuse the name of a built-in variable.
  • An operation value, or an initialValue of type literal, that writes into an object field with fields or an array field with of may use only the declared keys. Array rows may also carry _key and _type. A literal list where an object is declared, such as [] set into an object field, is refused too.
  • A field that leaves out fields or of accepts any keys; see Field types. A reference that such a value places in it must set _weak: true, which makes it a weak reference. A definition with such a field requires reader model 13, the lowest stored-data model version an engine must support to read it. So set the deployment’s expectedMinReaderModel to 13 before you deploy it. For the steps, see Upgrade Workflows packages.
  • defineWorkflow refuses fields: [] on an object field and of: [] on an array field. Leave the property out to accept any keys.
  • A condition’s $fields read must name a declared field and fit the field’s declared shape, because a read that fits no shape never holds a value. For doc.refs, array, assignee, and assignees field types, this includes the path after []. If contributors is a doc.refs field, $fields.contributors[].id fits and $fields.contributors[]._ref doesn’t. A singular assignee field stores a list, so if lead is an assignee field, $fields.lead[].id fits and $fields.lead.id doesn’t. For the paths that aren’t checked, see Condition variables.

If any check fails, defineWorkflow throws one error that lists every problem with its path:

defineWorkflow("article-review") failed validation (3 issues):
  - stages[1].transitions[0].to: transition target "ready" is not a declared stage. Known stages: "drafting", "review", "approved"
  - stages[2].name: stage "approved" is unreachable — no transition path leads from initialStage "drafting" to it, so no instance can ever enter it. Add a transition targeting it, or remove the stage
  - predicates.allActivitiesDone: predicate "allActivitiesDone" shadows the built-in $allActivitiesDone — pick another name

You never write a version number. Deploying a definition compares its content with the latest version already deployed under the same name:

  • If the content is the same, deploying does nothing.
  • If the content differs in any way, the engine creates the next version.

Deploying never edits a version that already exists, because running instances use those versions. Each version is its own document, with an ID of the form <partition>.<name>.v<version>.

The engine compares with the latest version only. If you redeploy content that matches an older version, you get a new version. Version numbers only go up.

Pinned instance versions

An instance follows one version of its definition. When startInstance creates an instance, the engine stores three values on it that never change:

  • pinnedVersion: the definition version number this instance started under.
  • pinnedContentHash: the fingerprint of that version, so you can tell when the definition has moved on.
  • definitionSnapshot: a frozen copy of the whole definition as it stood at that moment.

An instance follows its own snapshot for its whole life. For example, if you deploy version 4 while some instances still run on version 3, those instances keep the version 3 stages and conditions until they finish. New instances start on the highest deployed version, unless you pass a version to startInstance.

No engine method moves a running instance to a newer version. To run the new shape, start new instances and let the old ones finish. Plan changes with this in mind: a stage you delete in version 4 still exists for instances on version 3. To find instances on an older definition, compare their pinnedContentHash with the deployed definition.

Stages, stage visits, and terminal stages

An instance is in exactly one stage at a time. It begins at the definition’s initialStage. The fields, activities, actions, guards, and outgoing transitions declared on the current stage apply. Those declared on other stages don’t.

A stage doesn’t have to contain work. It can wait for something outside the workflow, route the instance on at once, or represent an outcome. A stage with no outgoing transitions is terminal. Reaching a terminal stage completes the instance.

Stage shape

A stage declares its name and, optionally, a title, fields, activities, and transitions:

defineStage({
  name: 'review',
  title: 'Review',
  fields: [
    defineField({type: 'string', name: 'decision'}),
  ],
  activities: [
    defineActivity({
      name: 'editorial-review',
      actions: [
        defineAction({name: 'approve', status: 'done'}),
      ],
    }),
  ],
  transitions: [
    defineTransition({
      name: 'to-published',
      to: 'published',
      when: '$allActivitiesDone',
    }),
  ],
})

A stage can declare fields that exist only during that stage, plus optional activities and transitions. Fields explains stage scope and Activities and actions explains the work model.

Stage visits

When an instance enters a stage, the engine resolves the stage’s fields, creates its activities, and registers its guards. Each entry into a stage is a stage visit. If an instance enters the same stage again, that starts a new visit, and earlier visits stay in history.

When the instance enters the stage, the engine creates each activity as active. If an activity’s filter is false at that moment, the engine creates it as skipped instead, and $allActivitiesDone counts it as done. Active activities stay active until an action gives them a final status. A stage with no activities is valid. Finishing all activities doesn’t move the instance by itself. Only a transition moves it.

Transitions and routing conditions

A transition moves an instance from one stage to another, in one direction. The engine fires it only when its when condition is true. The condition can read the transition’s GROQ variables:

defineTransition({
  name: 'to-review',
  to: 'review',
  when: 'defined($fields.reviewer)',
})

If you omit when, defineWorkflow sets it to $allActivitiesDone. Use when: 'true' to route without a condition.

A transition has no operations and no effects. It only moves the instance. Put the work in actions instead:

  • To route the instance, have an action write a field, and make the transition’s condition read that field.
  • For work on arrival, use a triggered action in the destination stage.
  • For work before the move, use an action in the stage the instance leaves.

Selection, cascade, and settling

After each commit, the engine checks the outgoing transitions of the current stage in the order you declared them. The first transition whose condition is true fires. The instance moves to the target stage, and the engine checks again from there. Because order sets priority, put specific routes before a catch-all route.

If the engine can’t decide a condition, it stops checking and fires nothing. It doesn’t move on to the next transition. This happens when GROQ returns null, for example because a value is missing or can’t be compared. null isn’t the same as false, so the engine doesn’t skip past the undecided route to a later catch-all. Once the missing value is written, the next commit checks the transitions again.

An instance can wait on an undecided transition even when every activity in the stage is finished. In that case, the CLI diagnose command and the MCP workflows_diagnose tool report the instance as stuck with the cause transition-unevaluable. They name the undecided transitions, even when a later transition is satisfied. You don’t need to fix anything by hand: once the missing value is written, the next commit or tick checks the transitions again. If the undecided transition reads a referenced document that no longer exists, the cause is document-missing instead.

A triggered action is an action with a when condition, which the engine fires itself once the condition is true, instead of a caller firing it. Triggered actions and transitions can make each other ready to fire. So the engine keeps going until the instance settles or reaches a terminal stage. This chain is the cascade. The cascade moves one stage per hop:

  • The engine fires the current stage’s triggered actions until none is left to fire.
  • The engine checks the transitions against the resulting state.
  • The engine saves the hop as one commit.

If a transition fired, the next hop starts in the new stage and runs that stage’s triggered actions. A cascade across several stages is saved stage by stage. For the full transition shape, see Transitions and routing conditions.

The instance settles on the first hop where no transition fires, and the call returns. A cascade can run at most 100 hops. After that, the engine throws CascadeLimitError. Reaching the limit usually means two conditions send the instance back and forth between stages.

The engine is a library, not a service, so it has no timer of its own. A cascade runs only inside an engine call: startInstance, fireAction, editField, completeEffect, commitEffectOps, resetActivity, or tick. A transition that waits for a deadline fires only when something calls tick after the deadline passes. The generated Sanity Functions runtime includes a scheduled heartbeat that does this. Without one, the instance stays where it is.

Starting an instance

startInstance creates one instance from a deployed definition. It does these things in order:

  • Checks the caller’s start roles, the initial field values you pass, and the definition’s start requirements, before writing anything.
  • Stores the definition snapshot on the instance.
  • Enters the initial stage and creates its activities.
  • Runs the cascade until the instance settles.

If you pass your own instance ID, retrying an interrupted start finishes that start instead of creating a second instance.

The start checks only help callers that go through the engine. Anyone with a write token can create documents in the Content Lake directly. If a start rule must always hold, enforce it with dataset access control. The Content Lake doesn’t enforce guards.

Start a workflow instance builds the subject reference, pre-flights the start, and handles a refused or interrupted start. Start filters and requirements explains the difference between discovering a workflow and being allowed to start it.

Decide who may start an instance

By default, anyone who can create the instance can start it. To limit starting to certain roles, add start: {roles: [...]} to the definition. These roles work like an action’s roles and the abort roles, including roleAliases:

defineWorkflow({
  name: 'article-review',
  title: 'Article review',
  initialStage: 'draft',
  start: {kind: 'interactive', roles: ['editor', 'administrator']},
  stages: [defineStage({name: 'draft', title: 'Draft'})],
})

A caller with any one of the roles may start. roles: [] is rejected, because it names no roles. The start roles apply in these places:

  • startInstance throws StartNotAllowedError for a caller without one of the roles, before it writes anything. The error’s roles lists the roles the definition accepts. This applies to every caller, including Administrators and robot tokens, whatever the start kind.
  • evaluateStart reports the same result: its roles lists the accepted roles, and allowed is false.
  • The Studio plugin leaves the workflow out of the start button and start menu for editors without one of the roles. A workflow with an unfinished start on the document stays listed so it can be finished.

A robot qualifies the same way, by holding one of the roles. An autonomous workflow is started by its runtime’s robot, so list that robot’s role, or every start is refused. The robot token that blueprints generate emits holds editor. Resuming an interrupted start and spawning a child workflow don’t check the start roles.

A definition with start roles requires reader model 13, because an older engine would ignore the roles and let anyone start. Before you deploy it, upgrade every runtime that shares the workflow resource. Then set the deployment’s expectedMinReaderModel to 13. For the steps, see Upgrade Workflows packages.

Decide who may abort an instance

Aborting stops a running instance where it is. By default, anyone who can write the instance can abort it. To limit aborting to certain roles, add abort: {roles: [...]} to the definition. These roles work like an action’s roles, including roleAliases:

defineWorkflow({
  name: 'article-review',
  title: 'Article review',
  initialStage: 'draft',
  abort: {roles: ['editor', 'administrator']},
  stages: [defineStage({name: 'draft', title: 'Draft'})],
})

The abort roles apply in these places:

  • abortInstance throws AbortDeniedError for a caller without one of the roles, before it writes anything. This applies to every caller, including Administrators.
  • Evaluations report the same result as WorkflowEvaluation.abort.
  • The Studio plugin shows Cancel workflow only to editors with one of the roles.

This differs from start.filter, which only controls whether a workflow is offered. The abort roles refuse the call itself.

Some aborts skip the abort roles:

  • Child workflows stop when their parent aborts, or when the parent leaves a stage whose spawn uses onExit: 'abort'.
  • deleteDefinition with cascade aborts the definition’s instances.

A definition with an abort block requires reader model 11. Older engines ignore the block and let anyone abort. Before you deploy it, upgrade every runtime that shares the workflow resource. Then set the deployment’s expectedMinReaderModel to 11. For the steps, see Upgrade Workflows packages. Content Lake permissions still decide who can write the instance at all.

Stored instance state

An instance is an engine-owned sanity.workflow.instance document. It records the pinned definition, current stage, resolved fields, stage-visit history, effects, child workflows, audit history, and lifecycle timestamps.

To change an instance, call the engine. Don’t patch the instance document directly: a direct patch skips the engine’s checks and history.

Instance previews

Lists and dashboards that show many instances don’t need each full instance document. instancePreviewsQuery builds a GROQ query that returns one smaller WorkflowInstancePreview per instance. A preview includes the current stage, its open activities, list-relevant fields, timestamps, parent instances, perspective, and any claimed or failed effects. It leaves out the definition snapshot and the audit history, which can grow large. Parse each result with readInstancePreviewDoc.

To read previews one page at a time, newest first, set filter.limit. For the next page, pass the last row’s {id, startedAt} as filter.before. Pages then stay stable when instances start or finish between reads. filter.before requires filter.limit. Other instance filters, such as definition and includeCompleted, also work with previews.

const page = instancePreviewsQuery({
  partition: 'dev',
  filter: {
    includeCompleted: true,
    limit: 500,
    before: previousLastRow,
  },
})

const changes = instanceChangesQuery({partition: 'dev'})

instanceChangesQuery builds one listen filter that covers every instance in the partition. Listen to it once. When an instance changes, fetch its preview again by ID. After the listener reconnects, fetch the list again. In React, useInstancePreviews handles this paging and refreshing for you.

Next steps

Visiting agent?

Was this page helpful?

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