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

# Write GROQ conditions

Write GROQ conditions for workflow start filters, requirements, stage transitions, and activity gates.

> [!WARNING]
> Early access
> Workflows is in early access, built in public. Read [How early access works](https://www.sanity.io/docs/workflows/prerelease) before you rely on it.



A condition is a GROQ expression that answers a yes-or-no question about a workflow instance. What a condition controls depends on where you declare it:

- A transition’s `when`: whether the engine moves the instance to another stage.
- An action’s `when`: whether the engine fires the action itself, during another engine call, without a `fireAction` call for it.
- A `filter`: whether the engine creates an activity as active or as skipped when the instance enters the stage, or offers an action. A skipped activity counts as done for `$allActivitiesDone`.
- `requirements`: whether the engine lets an action fire or a start succeed.

This guide adds conditions to the quick start’s `article-review` workflow. You write a transition that waits for legal sign-off, reuse that rule as a named predicate, add rules for when a review can start, and route articles that come back for a second review. Each step ends with a CLI check.

## Prerequisites

- The finished [quick start](https://www.sanity.io/docs/workflows/getting-started): `workflows/article-review.ts` deployed through the `dev` deployment in `sanity.workflow.ts`, and the `_id` of the published article you started it with.
- Basic GROQ: filters, `defined()`, and `count()`.
- For the first check: `scripts/approve-legal.ts` from [Configure workflow fields](https://www.sanity.io/docs/workflows/fields), which sets a field through the engine.

## Know what a condition can read

The engine doesn’t evaluate a condition against the whole Content Lake. For each decision, it builds a small snapshot that holds:

- The current instance, its ancestor instances, and its running child instances.
- The documents named by `subject`, `doc.ref`, and `doc.refs` fields at workflow scope or in the current stage, if they exist and the engine can read them.
- The release named by a `release.ref` field.

The engine doesn’t follow references inside those documents. In `$fields`, values look like this:

- A single reference field (`subject` or `doc.ref`) holds the full document, so `$fields.subject.title` works. If the document is missing or can’t be read, the value has only `_id` and `_type`.
- A `doc.refs` field stays an array of references.
- Every other field holds its stored value.

Which variables a condition can use, such as `$fields`, `$stage`, `$allActivitiesDone`, and `$self`, depends on where it’s declared. [Condition variables and decision sites](https://www.sanity.io/docs/workflows/workflow-authoring-reference) lists the variables for each place.

Caller variables (`$actor`, `$assigned`, `$can`, and `$attributes`) describe whoever makes the call. Three places can read all four: the filter of an action a caller fires, an activity’s requirements, and an `editable` condition. Some other sites read only `$actor` or `$assigned`; the authoring reference lists the variables each site can read. A routing condition, such as a transition’s `when`, must give the same answer whoever makes the call, so `defineWorkflow` and deploy reject a transition `when` that reads `$assigned`. [Actors and enforcement](https://www.sanity.io/docs/workflows/actors-and-enforcement) explains why, and [Let reviewers claim an assignment](https://www.sanity.io/docs/workflows/claim-assignment) shows a filter that reads the caller.

To read the current time, use `$now`. It’s an ISO 8601 string, so compare it with `dateTime($now)`. Don’t use `now()` or `dateTime::now()`. Validation rejects them in conditions, predicates, spawn expressions, `start.filter`, and GROQ start requirements, because those calls read the wall clock, not the `$now` value the engine supplies. Query initial values on fields can use them; see [Configure workflow fields](https://www.sanity.io/docs/workflows/fields).

When GROQ can’t decide a condition, the condition returns `null`. A `null` transition condition stops the engine from checking later transitions. It doesn’t skip to the next one. To avoid this, guard optional values with `defined()` or `coalesce()`. [Selection, cascade, and settling](https://www.sanity.io/docs/workflows/definitions-and-instances) explains the rule.

## Wait for a field in a transition

Add an editable `legalApproved` field and make `to-approved` wait for it as well as for sign-off:

**workflows/article-review.ts**

```typescript
export const articleReview = defineWorkflow({
  // ...
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      // ...
    }),
    defineField({type: 'boolean', name: 'legalApproved', title: 'Legal approved', editable: true}),
  ],
  stages: [
    // drafting is unchanged
    defineStage({
      name: 'review',
      // ...
      transitions: [
        defineTransition({
          name: 'to-approved',
          title: 'Approve and finish',
          to: 'approved',
          when: '$allActivitiesDone && $fields.legalApproved == true',
        }),
      ],
    }),
    // approved is unchanged
  ],
})
```

A transition without `when` waits for `$allActivitiesDone`. Once you add a `when`, that default no longer applies. So this condition includes `$allActivitiesDone` and adds the field check. After sign-off, the instance stays in `review` until someone sets `legalApproved` to `true`.

Deploy the change and start a new instance. Then fire `submit` on `write` and `approve` on `sign-off`, as in the quick start.

Run `npx sanity-workflows show INSTANCE_ID`. The instance is still in `review`. Every activity is done, so `show` reports `STUCK — no exit transition's trigger is satisfied`.

Set the field with the `scripts/approve-legal.ts` script from [Configure workflow fields](https://www.sanity.io/docs/workflows/fields). The instance moves to `approved` in the same call. To see from code why a condition is waiting, read its insight; [Explain waiting conditions](https://www.sanity.io/docs/workflows/evaluation-insights) shows how.

## Reuse a rule with a named predicate

When several decisions use the same rule, declare it once in `predicates` and refer to it as `$name`. Named predicates follow these rules:

- A predicate can read instance variables. It can’t read caller variables, another predicate, or itself.
- `spawn.forEach` can’t use predicates.
- You can’t name a predicate `attributes`, because that name belongs to `$attributes`.
- If a condition uses a `$name` that is neither a predicate nor an available variable, `defineWorkflow` rejects it and suggests the closest valid name.

**workflows/article-review.ts**

```typescript
export const articleReview = defineWorkflow({
  // ...
  predicates: {
    readyToApprove: '$allActivitiesDone && $fields.legalApproved == true',
  },
  stages: [
    // drafting is unchanged
    defineStage({
      name: 'review',
      // ...
      transitions: [
        defineTransition({
          name: 'to-approved',
          title: 'Approve and finish',
          to: 'approved',
          when: '$readyToApprove',
        }),
      ],
    }),
    // approved is unchanged
  ],
})
```

Deploy and repeat the check. The behavior is unchanged: the instance waits in `review` until `legalApproved` is `true`.

## Control when a review can start

Three settings control starting a workflow:

- `start.filter`: controls which documents an interface, such as Sanity Studio, offers the workflow for. It doesn’t stop `startInstance` from starting an instance.
- `start.requirements`: an ordered list of checks that every new start must pass.
- `start.roles`: the roles a caller must hold to start. See [who may start](https://www.sanity.io/docs/workflows/definitions-and-instances).

[Start block](https://www.sanity.io/docs/workflows/workflow-authoring-reference) lists every option.

**workflows/article-review.ts**

```typescript
export const articleReview = defineWorkflow({
  name: 'article-review',
  // ...
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      title: 'Article',
      types: ['article'],
      required: true,
      initialValue: {type: 'input'},
    }),
    defineField({type: 'string', name: 'brief', title: 'Brief', initialValue: {type: 'input'}}),
  ],
  start: {
    filter: 'defined(title)',
    requirements: [
      {
        type: 'singleSubject',
        name: 'one-open-review',
        title: 'Review already in progress',
      },
      {
        type: 'groq',
        name: 'brief-required',
        title: 'Brief required',
        query: 'defined($fields.brief)',
      },
    ],
  },
  // stages are unchanged
})
```

`types: ['article']` offers this workflow for articles, and the filter narrows that to articles with a title. A start succeeds only when both requirements pass: no unfinished instance of this definition has the same subject, and the caller supplies a brief. Start requirements don’t run when you retry an unfinished start, or when a parent spawns a child.

A `start.filter` that reads the candidate document needs a `subject` field. A GROQ start requirement can’t read the candidate document. Its `$fields` holds the inputs as supplied, so a document reference is `{id, type}`, not a loaded document.

Deploy, then start an instance without `--field brief=...`. The CLI prints the requirement’s title:

**CLI**

```text
✖ Start rejected
✖ start error:
  startInstance refused definition "article-review": Brief required. Pre-flight the verdict with evaluateStart.
```

Start again with `--field brief="Launch post"`, and the instance starts. Run the same command again with the same subject. This time, the `singleSubject` requirement refuses it with `startInstance refused definition "article-review": Review already in progress.`

A `singleSubject` requirement works like this:

- It checks instances of every deployed version of this definition. Instances of other definitions don’t count.
- It needs one `subject` field with `initialValue: {type: 'input'}`.
- It compares subjects by their full [global document reference](https://www.sanity.io/docs/workflows/global-document-references). So documents in different datasets that share an `_id` never block each other.
- Once the existing instance completes, a new start is allowed.

## Detect a return visit to a stage

Inside a condition, `*` searches the snapshot, not the Content Lake. Use condition variables when they hold what you need. Query the raw instance only for state they don’t include, such as the history of stage visits. Add this transition to `review`, before `to-approved`:

**workflows/article-review.ts**

```typescript
defineTransition({
  name: 'approve-after-rework',
  title: 'Approve a reworked article',
  to: 'approved',
  // $stage == "review" is true on every visit.
  // Count the stored review entries to detect a return visit.
  when: '$allActivitiesDone && count(*[_id == $self][0].stages[name == "review"]) > 1',
})
```

`$stage` names the current stage, so `$stage == "review"` is true on every visit. There’s no variable for past stages. The `$self` query counts the stored `review` entries, so it can tell a return visit from the first one.

Keep `$allActivitiesDone` in the condition. Without it, the engine fires the transition in the call that moves the instance back into `review`, before anyone signs off.

To test it, the workflow needs a transition from `review` back to `drafting`, such as `back-to-drafting` in [Define activities and actions](https://www.sanity.io/docs/workflows/activities-and-actions). With that transition in place:

1. Deploy, and start an instance with a `brief`.
2. Submit the article, then fire the action that sends it back to `drafting`.
3. Submit it again, and approve it.

The instance reaches `approved` through `approve-after-rework`, without `legalApproved`.

## Next steps

- Inspect why a condition passed or failed in [Explain waiting conditions and field insights](https://www.sanity.io/docs/workflows/evaluation-insights).
- Look up the variable and decision-site tables in [Condition variables and decision sites](https://www.sanity.io/docs/workflows/workflow-authoring-reference).
- Write the fields conditions read from actions in [Define activities and actions](https://www.sanity.io/docs/workflows/activities-and-actions).
- Protect documents during a stage in [Hold publishing and freeze fields with guards](https://www.sanity.io/docs/workflows/guards).

> [!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).



