# @sanity/workflow-engine

## 0.36.0

### Minor Changes

- 12240b6: `@sanity/workflow-engine` exports `spawnSites(definition)`, which lists every `spawn` block a definition declares, in definition order, as a `SpawnSite` carrying the block and the stage, activity and action names that address it. Tooling that needs to know whether a definition spawns children, such as the blueprint generator deciding whether a heartbeat must re-evaluate a waiting parent, can read it instead of walking the definition tree itself.

  **No upgrade action required.** This is a new export; nothing existing changes.

  **Docs impact:** Add `spawnSites` and `SpawnSite` to the engine API reference beside `effectSites`.

- 9902088: **BREAKING:** `defineWorkflow` now rejects a `subject` entry whose `types` names a document type the engine owns and writes for itself: `sanity.workflow.instance`, `sanity.workflow.definition`, or the guard type `temp.system.guard`. The old contract accepted any type name in `types`, and such a definition loaded but never matched a document, because applicability already refuses an engine-owned type at every read. The replacement is `spawn`: a workflow that runs another workflow spawns it rather than taking its instance or definition as a subject. The rejection message names the entry and the engine-owned types and points at `spawn`.

  Affected: authors whose subject entry lists an engine-owned type. Stored definitions are unaffected: nothing already deployed changes. The same check runs at `deployDefinitions`, so a stored-shape definition submitted straight to the verb is rejected too. To migrate, remove the engine-owned types from the entry's `types`, and model workflow-from-workflow orchestration as a `spawn` on the parent. Without the change, `defineWorkflow` throws and nothing in that module loads.

  **Docs impact:** State in the `subject` field reference and the subworkflows guide that engine-owned types are refused as subject types at authoring and that `spawn` is how one workflow runs another.

- 9902088: **BREAKING:** An effect's `runtime` function budget is validated against the range Sanity Functions accepts, so a definition the platform would reject at `blueprints deploy` now fails at `defineWorkflow`. The old contract accepted any positive integer for `timeout` and `memory`, and documented `memory` in megabytes. The new contract takes `timeout` as a whole number of seconds from 1 to 900 and `memory` as a whole number of gigabytes from 1 to 10. Anything else (zero, a fraction, or a value over the limit) throws with the field, the unit, and the range named. This affects anyone whose definitions declare a budget, and in particular anyone who wrote `memory` in megabytes: `memory: 512` asks for 512 gigabytes and now fails at authoring. Without migrating, `defineWorkflow` throws and nothing in that module loads.

  Stored definitions are unaffected: nothing already deployed changes. To migrate, change a megabyte-shaped `memory` to the gigabytes you want (`512` becomes `1` unless the handler needs more) and bring any `timeout` over 900 down. A definition whose budget is already inside the range needs no change. The `@sanity/workflow-blueprint` generator emits the validated values unchanged, and its `FunctionLimits` type now documents `memory` in gigabytes.

  **Docs impact:** Update the `runtime` block section of the `@sanity/workflow-blueprint` README and the runtime reference to state both units with their accepted ranges and that an out-of-range budget fails at `defineWorkflow`; the release notes should name the megabyte-to-gigabyte correction so a reader who wrote `512` knows why authoring now rejects it.

- 9902088: **BREAKING:** `defineWorkflow` now rejects a condition that calls GROQ's own `now()` or `dateTime::now()`. The old contract accepted either call anywhere a condition runs. The replacement is `$now`, the one clock the engine advances, bound from the `Clock` you pass `createEngine`. A call spelling reads wall time behind the engine instead, so it ignores an injected clock, including the test bench's `setNow` and `advance`, and at a site the heartbeat schedules from it produces no `nextEvaluationAt` boundary. The rejection covers every condition site, spawn GROQ (`spawn.forEach`, `spawn.with`, `spawn.context`), named `predicates`, `start.filter`, and GROQ start requirements. An `initialValue: {type: 'query'}` seed is exempt and may still call `now()`; `$now` is bound there too.

  Affected: authors whose definitions spell the clock as a call. Stored definitions are unaffected: nothing already deployed changes, and running instances keep evaluating. The same check runs at `deployDefinitions`, so a stored-shape definition submitted straight to the verb is rejected too. To migrate, replace `now()` with `$now` and `dateTime::now()` with `dateTime($now)`: `embargoAt <= now()` becomes `embargoAt <= $now`, and `dateTime(embargoAt) <= dateTime::now()` becomes `dateTime(embargoAt) <= dateTime($now)`. `$now` is an ISO string, so replacing `dateTime::now()` with a bare `$now` compares a datetime with a string and never resolves. Without the change, `defineWorkflow` throws with a message that names the site and `$now`, and nothing in that module loads.

  **Docs impact:** Note in the condition reference and the deadlines guide that `$now` is the only clock a condition may read and that the call spellings are refused at authoring, so a reader who copied `now()` from GROQ documentation knows why it fails.

- d5da960: **BREAKING:** A `subject` entry that declares no `types` used to match any document type, including Sanity's reserved `sanity.` and `system.` namespace documents (Content Releases, assets) and the engine's own instance, definition, and guard documents. It now matches only content — a system document is never accepted by a type-less entry. `acceptsDocumentType`, `definitionsForDocument`, and document pickers are all affected.

  A definition that relied on a type-less `subject` reaching a system document must name that type explicitly in `types` to keep matching it (for example `types: ['system.release']` for a Content Release); until it does, the affected documents stop surfacing that definition — most consequentially, a definition with a type-less subject stops applying to the instances its own starts create. An engine-owned document (the instance, definition, or guard type) can never be named as an accepted subject type; a workflow that needs to run another workflow does so through `spawn`. Stored definitions are unaffected; the new rule applies only at read.

  **Docs impact:** Update the authoring reference for the `subject` field and the `types` facet to state that a type-less subject never matches a system document and that an engine-owned document type is never accepted even when named explicitly.

- c06a9a8: **BREAKING:** Workflows telemetry event names now all follow
  `Workflows <package> <event>`, the form the Studio plugin already uses. Every
  engine event gains `Engine` (`Workflows Instance Started` becomes
  `Workflows Engine Instance Started`). The CLI's definition-sharing events gain
  `CLI` (`Workflows CLI Definition Shared`,
  `Workflows CLI Definition Sharing Decided`), and the React session event gains
  `React` (`Workflows React Session Started`). Payloads and event versions are
  unchanged. Dashboards and queries that match the old names stop receiving new
  rows, and a telemetry logger passed to `createEngine({telemetry})` or set in
  `sanity.workflow.ts` that filters on an event name stops matching.

  Update Omni queries and dashboards to match both the old and new names until
  the old series no longer matters; rows already recorded keep their old names.
  Update any custom logger that compares `event.name` against a string. Code that
  references the exported event definitions, such as `WorkflowInstanceStarted`,
  needs no change.

  **Docs impact:** Update every telemetry reference that lists Workflows event
  names, including the engine, CLI, MCP, and React telemetry sections, and add the
  rename and the dual-name query guidance to the release notes.

- cbad3ae: `drainEffects` accepts two optional arguments that narrow one call's dispatch. `names` restricts the candidates it considers to entries whose effect name is in the list. An empty list throws instead of silently draining nothing. `max` stops the call after dispatching that many effect entries, leaving the rest pending for a later call. A skipped missing-handler entry, and one another drainer claimed first, don't count against it. A `retry`-driven entry that runs its handler more than once inside the call still counts once. Anything other than a whole number of one or more throws.

  The package also exports `isEntryUnheld(entry, now)`, the predicate that decides whether a pending effect entry carries no live claim, so a consumer can select recoverable instances with the same lease rule the engine's own drain uses.

  **No upgrade action required.** Omitting both `drainEffects` arguments reproduces the exact dispatch behavior of every existing `drainEffects({instanceId})` call.

  **Docs impact:** Update the `drainEffects` API reference entry to document `names` and `max`, and add `isEntryUnheld` to the package's exported-predicates reference.

### Patch Changes

- 56a7252: `readsRootDocument` now detects a read of the root document made through a `^` inside a mapping, such as `([{}]{"s": ^.status})[0].s == "ready"`, and through the functions that take the document implicitly: `references()`, `sanity::versionOf()` and `sanity::partOfRelease()`. It returned `false` for an expression whose only root read took one of these forms. The new `rootDocumentReads` function and `RootDocumentReads` type return the attribute paths a GROQ expression reads off its root document, whether it reads the whole document, and whether it reads other documents through a dataset scan (`*[…]`) or a dereference (`->`). For `count(items[]{"eligible": ^.status == "ready"}[eligible]) > 0`, the paths are `items` and `status`.

  Deploy validation uses `readsRootDocument`, so an expression whose only root read takes one of these forms now fails deploy with the existing root-read errors:
  - A `start.filter` on a definition with no `subject` entry. Declare a `subject` entry, or rewrite the filter so it does not read the candidate document.
  - A start requirement `query`. Read the subject through `$fields.<entry>` instead, or move a per-document visibility rule to `start.filter`.

  The Studio plugin re-evaluates such a `start.filter` when the document changes.

  **No upgrade action required** for a definition that does not use these forms.

  **Docs impact:** Add `rootDocumentReads` and `RootDocumentReads` to the engine API reference, and state in the `start.filter` and start requirement reference that a `^` inside a mapping and the implicit-document functions read the candidate document.

- Updated dependencies [56a7252]
  - @sanity/groq-condition-describe@0.5.2

## 0.35.0

### Minor Changes

- 7e24e4a: **BREAKING:** Every engine telemetry event payload now carries the engine's own view of its caller as two fields, `executionRuntime` and `executionKind`, and every event's `version` moves from `1` to `2`. Anything that pins an engine event version, or that constructs an engine event payload by hand to emit through its own `@sanity/telemetry` logger, breaks until it is updated: the payload types now require `executionRuntime`. `definitionDeployedData` returns the structural half of the deploy payload rather than the whole payload — its result no longer satisfies `WorkflowDefinitionDeployedData`, and the emit site supplies the stamp separately.

  `executionRuntime` is the runtime the engine infers for itself (`browser`, `node`, `worker`, `edge`, `deno`, `bun`, `unknown`) and matches the `executionContext.runtime` the same operation stamps on its history entries. The declared `id` is never reported.

  `executionKind` answers where the operation came from, which is narrower than the vocabulary a host can declare. `studio`, `sdk`, `cli`, `mcp`, and `server` report themselves. `drainer` reports `server`, because a drain runtime is a server host and that it is draining is what its own events say. `interactive`, `script`, and `test` name a role rather than a host and report `other`, as does any value outside the vocabulary. The field is absent when the host declared no kind. The exported `ReportedExecutionKind` type is that closed set, so the reported vocabulary is visible in the type rather than only in prose.

  `EXECUTION_KINDS.sdkApp` now carries the value `sdk` rather than `sdk-app`, so one spelling names the App SDK across the whole Workflows event family — the engine's `executionKind`, the session event's `host`, and the shell's `surface` user property. A host that declared `sdk-app` as a literal rather than through `EXECUTION_KINDS` should switch to the constant; nothing Sanity ships ever set the old value, so no stored history carries it.

  Emitting the fields is not the same as being able to query them. Analytics ingestion maps event payload keys to a fixed set of columns, so caller-based breakdowns stay unavailable until `data_execution_runtime` and `data_execution_kind` exist downstream; upgrade for the emission, and expect the analytics read to follow separately.

  Hosts that pass `executionContext` to `createEngine` need no action, with one exception: a host that declared the App SDK kind as the literal `sdk-app` rather than through `EXECUTION_KINDS` now falls outside the vocabulary and reports `other`, so it should switch to the constant or to `sdk`. Every other declared kind is reported under the projection described above. A host that declares nothing emits a runtime with no kind, so declare `executionContext: {kind, id}` at `createEngine` to make its activity distinguishable in analytics. Anyone matching on event versions or hand-building payloads must update to version `2` and set the two fields themselves.

  One projection is currently unexercised: the Blueprint-generated function shells declare their execution context but pass no telemetry logger, so nothing emits from the server tier and no `server` row exists yet.

  **Docs impact:** Update the telemetry reference for all 13 engine events to list the two payload fields and their version `2`, and give `ReportedExecutionKind` its own entry naming each reported value and what declares it. Document the `DerivedEventData` return type that the payload builders now return. In the engine host guidance, say that declaring `executionContext` at `createEngine` is what makes a host's events attributable, and that the reference docs currently describe that field only as a history stamp. Release guidance should carry the version bump and the hand-built-payload migration.

### Patch Changes

- ab8754a: `deployDefinitions` now derives the reader model its submitted definitions require through one named engine function that parses each definition and measures the parsed shape, rather than inlining that sequence at the call site. Anything that needs to predict the deploy's acknowledgement verdict offline derives the floor through the same function, so an offline check and the deploy cannot reach different answers. The verdict itself is unchanged: the same definitions produce the same required floor and the same `ReaderModelAcknowledgementError`.

  The data-model change rules also now state that raising any feature's reader floor raises every deployment acknowledgement whose definitions then require the higher floor, in the same change, and that a floor raised without moving those `expectedMinReaderModel` literals fails the affected definition deploys until it is. A deployment whose definitions still require less keeps its literal. The rule names the confirmation step it depends on: the runtimes sharing each workflow resource must read the new model first.

  **No upgrade action required.** No engine behavior, persisted shape, or supported API changes; `DATA_MODEL_VERSION` stays at 10 and no feature floor moves. The package entry point gains one `@internal` export carrying that shared derivation, which is unsupported outside the Workflows packages and is omitted from the generated reference. Anyone maintaining their own `sanity.workflow.ts` deployments can read the rule as the sequence to follow when a Workflows upgrade raises a floor their definitions require.

  **Docs impact:** The reader-floor rollout guide (`docs/reader-model-rollout.md`) carries the matching step, including how a config-declared acknowledgement is proven offline against the deploy's own derivation and why an acknowledgement passed directly to `deployDefinitions` is not; mirror that rollout sequence wherever published prerelease guidance describes `expectedMinReaderModel`.

## 0.34.0

## 0.33.0

### Minor Changes

- 8874c50: **BREAKING:** A `subject`, `doc.ref`, or `doc.refs` field marked `required: true`
  now requires its selected documents to remain readable after initialization.
  Previously, the flag checked only that an initial value was supplied. Missing
  required targets now produce a fault and prevent normal actions, triggered
  actions, and transitions from advancing, even without an activity requirement
  reading those targets. Abort and direct edits to editable fields remain
  available. Optional references fault only when an unmet runtime condition needs
  their content; completed workflows remain completed.

  `StuckCause` adds `document-missing`. Update exhaustive handlers before upgrading,
  or their typechecks fail and renderers have no matching branch. Evaluation
  identifies the affected field and reference in `missingDocuments`, with its title
  and completed availability evidence; `blockingMissingDocuments` selects the
  references that prevent progress. The engine checks draft, published, and release
  representations before distinguishing deletion from inaccessible content or
  content outside the workflow perspective. Studio, CLI, and MCP use that same
  result. Failed availability checks report unreadable content and log the cause;
  optional references still permit unrelated actions. Incomplete reads do not
  claim deletion, and an existing task fault keeps
  its recovery controls. The fault clears when the required content becomes
  readable; this release adds no undo-delete operation and does not automatically
  abort workflows.

  Upgrade every Workflows runtime sharing affected data, including Studio, CLI,
  MCP servers, and deployed Functions, before relying on continued required-target
  availability. Then set the deployment's reviewed `expectedMinReaderModel` to
  `10` before deploying definitions with required content references. Writers stamp
  model 10; this feature requires reader model 10, while documents without it keep
  the floor required by their other features, normally 4, 8, or 9. Existing
  instances remain readable without a backfill and adopt the rule under upgraded
  engines. Their stored floor rises on the next full write, so an older runtime
  can still advance an unstamped existing instance until the fleet is upgraded.
  See `packages/workflow-engine/DATAMODEL.md` for the complete rollout contract.

  The rendered CLI `show` command evaluates running instances. If evaluation fails,
  it warns and displays stored state; terminal instances and `show --json` retain
  their stored-state behavior.

  **Docs impact:** Update field requiredness and initialization guidance, required
  reference repair examples, the model-10 readers-first rollout, the diagnostics
  reference for `StuckCause` and `MissingDocument`, CLI `show` and `diagnose`, MCP
  workflow-state guidance, and the Workflows tool and document-view guides for
  loading, deletion, permissions, and perspectives.

- 0555271: An effect node can now declare a bounded retry policy the engine enforces on every runtime:
  `retry: {kind: 'engine', attempts, backoff?: {kind: 'fixed' | 'exponential', delayMs}, expiryMs?}`.
  The block's `kind` names who runs the policy and `engine` is the only accepted member; authoring may
  omit it, as with `start.kind`, and `defineWorkflow` fills it in while desugaring, so a stored block
  without it fails to parse at deploy. `attempts` is the total number of attempts
  including the first, `backoff` is the wait between two attempts
  (`delayMs` every time under `fixed`, doubled per attempt already made under `exponential`), and
  `expiryMs` decides whether a further attempt may start: the engine stops rather than begin a wait
  that would carry the run past it, so an attempt can go unused. It is not a handler timeout: an
  attempt already running is never interrupted, so a run can finish after the window and a success
  then still counts.

  The whole policy runs inside one `drainEffects` call, under one claim whose lease is renewed across
  each wait, and **every attempt invokes the handler again**. That is a third cause of the
  at-least-once repetition handlers already tolerate, and no `effectHistory` row sits between two
  attempts, so derive external-system identifiers from `ctx.effectKey` rather than checking history
  to deduplicate. Two
  things stop a run without settling it, both reported in the drain's `lost` bucket. A lease this
  drainer can no longer renew leaves the entry pending, for a later drain to pick up once the lease
  lapses. An entry another party completed or cancelled during a backoff is already settled by that
  party, and the handler is not invoked again.
  Otherwise the run settles in the single `effectCompleted` row the drain has always written: `failed`
  with a `detail` naming the attempts used and the last error (`failed after 3 of 3 attempts: gateway
timeout`), or `done` with a `detail` naming the attempt that succeeded when a later one did. A
  policy changes no routing rule, since `$effectStatus['<name>'] == 'failed'` routes the instance
  exactly as a single failure does. It does change which outcome those rules see, because an attempt
  after the first that succeeds makes the status `done`. Adding a policy to an effect a `'failed'`
  branch already watches is therefore a behaviour change, not only a latency change. Nothing
  about an attempt is persisted, so no scheduler is involved and no per-attempt history rows appear.
  An effect that declares no `retry` is unchanged: its handler's first failure settles it.

  The waits are the engine's only deliberate pause, so `createEngine({sleep})` now takes a `Sleeper`
  that decides how they are spent. Production omits it and spends real time; a deterministic harness
  passes one that moves its `clock` forward instead, which is what the engine test bench does, so a
  paced policy runs in a test without waiting.

  **No upgrade action required** to keep existing definitions working; `sweepStaleClaims` and every
  history shape are unchanged, and `drainEffects` keeps its signature and result shape. Two things to
  weigh before adopting it. The
  waits are real time inside the drain's invocation, so on a Functions host the policy has to fit
  that function's timeout. Handing the policy to a Durable Functions host's own retry strategy
  instead is future work in the generated runtime, not part of this contract; today every host waits
  inside the invocation. And **declaring `retry` raises the definition's reader floor to model 10**:
  `DATA_MODEL_VERSION` and `DATA_MODEL_MAX_READER` both move to 10, so upgrade every Studio, CLI, MCP
  server, Function, and other runtime sharing that workflow resource, then raise the reviewed
  `expectedMinReaderModel` literal to `10`, then deploy. A pre-model-10 reader would ignore the
  policy and settle the effect on its first failure. Deploy refuses a `retry` definition against an
  acknowledgement below 10, one whose backoff cannot fit its declared `attempts` inside `expiryMs`,
  and one whose `expiryMs` or accumulated backoff exceeds **366 days**, since the whole policy runs
  inside one `drainEffects` invocation and no host offers a single execution longer than a year.

  **Docs impact:** Update the effects concept in the Workflows concepts guide to describe retry as an
  in-invocation loop and name the per-host cost (the functions timeout, and durables delegation as future work), add `retry`
  and its one-year span ceiling to the effect-node reference, note the loop in the `drainEffects` protocol entry along with what
  the `lost` bucket now covers, list the `sleep` option in the `createEngine` reference, and add the retry
  feature to the crossing-to-model-10 section of the reader-model rollout guide. A cookbook recipe for a bounded
  external call should show the `retry` node instead of the counter-field retry loop.

- b3b2797: Where the generated unattended runtime hosts a workflow or an effect is declared as one `runtime` block on three authoring nodes: the deployment in `sanity.workflow.ts`, the workflow in `defineWorkflow`, and the effect node. `kind` is `'function'` (a plain Sanity Function), `'durableFunction'` (a durable one), or `'selfHosted'` (a process you run yourself). Each level inherits from the one above, so a workflow that declares no block takes its deployment's kind and an effect takes its workflow's. Omit it everywhere and everything hosts on `'function'`. `kind` is the whole block at the deployment and workflow levels; an effect's `'function'` block also carries the function budget, `timeout` in seconds and `memory` in megabytes, and an effect that declares either gets its own drain function so an expensive handler's budget does not size every other handler's. An unknown kind fails at `defineWorkflow` or `defineWorkflowConfig`, before any deploy runs, naming the three accepted members; a budget on any other kind is rejected there too.

  `@sanity/workflow-blueprint`'s emission plan groups by resolved kind. A `'function'` workflow gets the drain, the heartbeat, and the start watcher it always got. A `'durableFunction'` workflow or effect is listed under `planned.hosting` and emits nothing yet, while the rest of the deployment emits normally, with no error and no whole-deployment refusal. A `'selfHosted'` workflow or effect emits nothing, is skipped by the generated drains, is left out of the generated handler registry, and is reported under `planned.selfHosted`, which names the deadlines that process must tick, the effects it must drain, the parents it must re-evaluate when a child settles, and the autonomous definitions it must start. Two definitions in one deployment that host the same effect name differently fail generation, because one effect name has one handler and one budget. A start watcher is emitted for a durable workflow as well as a function-hosted one, because starting an instance does not depend on the host.

  The block is authoring-only. `defineWorkflow` returns the stored definition plus the `runtime` the generator reads, and the deploy strips it: it never reaches the Content Lake, the stored definition schema rejects it, and two definitions that differ only in a hosting kind fingerprint identically, so changing a kind never mints a definition version. It does change the emitted tree, so regenerate afterwards and delete the function directories the new tree no longer contains.

  **No upgrade action required.** Nothing this release replaces has been published: the deployment `runtime` block and the `@sanity/workflow-blueprint/generate` entry point that exposed the earlier planning helpers both ship for the first time here. Declare a block only where you want to move a workflow or an effect off the default.

  **Docs impact:** Document the `runtime` block once, at all three levels, in the deployment configuration reference beside `tag`, `workflowResource`, and `resourceAliases`: each kind, what the generator emits for it, and the effect-level `timeout` and `memory` units. Add the four hosting shapes (function hosted, durable hosted, self hosted with one workflow kept on functions, and mixed inside one workflow) to the generated-runtime guide, and state there that hosting decides whether a `$now` deadline causes a heartbeat to be emitted rather than which instances an emitted heartbeat ticks. State in the data-model concepts that `runtime` is the authoring-only block tooling reads and the deploy never stores.

- 225e0fb: **BREAKING:** Workflows App SDK and Studio integrations now require `@sanity/sdk` 3.1 or later in the 3.x line, and `@sanity/workflow-sdk` requires the matching `@sanity/sdk-react` 3.1 line when its React entry is used. The previous SDK 2 peer contract is no longer supported. The exported `WorkflowClient`, `TelemetryIntakeClient`, `ProjectUserProfileClient`, and `StudioUserClient` request contracts now pass their target in `url`; the previous `uri` request target is no longer used. The engine's effective client config also accepts the broader `{type: string, id: string}` resource descriptors returned by Sanity client 8.

  Before upgrading Workflows, upgrade `@sanity/sdk` and `@sanity/sdk-react` together to 3.1 or later. Applications that stay on SDK 2 must stay on an earlier Workflows release. If you implement any of the request contracts named above, update it to read the request target from `url` instead of `uri`; otherwise its request-backed reads will fail. Existing `WorkflowClient.config()` implementations need no change when their resource descriptor already has string `type` and `id` fields. No separate CLI upgrade action is required; its definition-sharing and telemetry requests adopt `url` internally.

  Before installing, override SDK 3's `@sanity/mutate` dependency to `0.18.2` in your application's root package-manager configuration, reinstall, and commit the updated lockfile. SDK 3.1.0 allows Mutate 0.18.1, which can leave document reads pending with client 8. For npm, set `overrides["@sanity/sdk"]["@sanity/mutate"]` to `"0.18.2"` in `package.json`. For pnpm, set `overrides['@sanity/sdk@3>@sanity/mutate']` to `0.18.2` in `pnpm-workspace.yaml`. Keep the override until your SDK release requires Mutate 0.18.2 or later. Complete examples and verification steps are in the Installation section of the published `@sanity/workflow-sdk` README.

  Malformed project-member responses now report an inaccessible directory and can recover on a later lookup, instead of being cached as a missing user. No additional upgrade action is required for this correction.

  **Docs impact:** Update the App SDK and Studio integration installation guidance, package compatibility references, and examples to require Sanity App SDK 3.1 and the consumer Mutate override described in the published `@sanity/workflow-sdk` README; update the client API references for `request({url})`, effective resource descriptors, and directory-response failures.

### Patch Changes

- 393ac71: CLI and MCP telemetry now includes `context.surface` (`cli` or `mcp`) and
  execution mode in each event's `context.environment`. Dashboards can include
  shell and engine activity while distinguishing it from SDK events marked
  `sdk`. Existing command trace context is preserved.

  All three surfaces report `production` for `NODE_ENV=production`, and
  `development` for `development` or `test`. Unset, empty, and unrecognized values
  default to `production` for CLI and MCP execution mode, and `development` for
  SDK build mode. SDK environment classification is unchanged. When comparing
  activity across surfaces, group or filter by surface alongside environment.
  Environment does not identify a production dataset or deployment; API host,
  dataset name, and workflow tag do not set it.

  **No upgrade action required.** Existing telemetry consent and opt-out
  settings still apply. Historical events are unchanged.

  **Docs impact:** Update CLI, MCP, and SDK telemetry guidance to explain surface
  context, build versus execution mode, the explicit defaults, and how to
  interpret environment when comparing activity across surfaces.

- 7eb9eca: Correct the API references for field initialization and edits, start requirements,
  transitions, reference IDs, effect handling, reactive state, member controls,
  Studio mappings, test helpers, and GROQ condition outcomes. The references state
  caller constraints and defaults that were missing or incorrect. Package setup
  guidance identifies the public npm packages and supported deployment command;
  the MCP validation description distinguishes validation from deployment checks.
  Runtime behavior and API signatures are unchanged.

  **No upgrade action required.**

  **Docs impact:** After release and reference sync, reconcile the modeling,
  runtime, reactive UI, Studio, testing, deployment, MCP, and evaluation-insight
  guides and references with the corrected contracts. Fix affected examples and
  replace redundant API inventories with verified symbol links while preserving
  useful teaching and the CLI/MCP reference material not exposed by TypeDoc.

- 2cef086: Internal maintenance consolidates engine action/edit handling and Studio document
  and workflow title sorting. Action and field-edit calls retain their inputs and
  results, and document and workflow titles retain their ordering. Action
  availability, telemetry, and persisted document formats are unchanged.

  **No upgrade action required.**

  **Docs impact: None** because public APIs, configuration, and workflow behavior
  are unchanged.

- 232f811: Workflows can resolve reviewer attributes from self-hosted studios without
  sending the attributes request to a global API host that rejects their origin.
  Actor resolution uses the account-global identity carried by the project user
  response when available, avoiding an unnecessary global request.

  Custom clients without `withConfig` can also resolve organization attributes
  when they already serve the engine's required API version.

  **No upgrade action required.** Existing project CORS settings and workflow
  definitions continue to apply.

  **Docs impact:** Update Workflows prerelease troubleshooting guidance to describe
  the fix for assignee loading on self-hosted studios and advise upgrading the
  Workflows packages together. Document the version requirement for custom clients
  in the engine client reference.

- Updated dependencies [7eb9eca]
  - @sanity/groq-condition-describe@0.5.1

## 0.32.0

### Minor Changes

- a8ed312: **BREAKING:** Assignment is now one ordered user-or-role member-list model: a direct user holder shadows every role in the same activity, role-only values route work to a pool, and singular `assignee` fields allow at most one user while retaining any number of roles. The `claim` field and action sugars have been removed from the authoring DSL; authors using them must replace each pair with an `assignee` field, a literal role seed where the work starts in a pool, ordinary field edits for take/release, a guarded `editable` predicate when second-taker exclusion is required, and `$assigned` on holder-only actions. Definitions that still submit `type: 'claim'` now fail validation.

  Upgrade every engine, Studio, CLI, MCP, and adapter runtime sharing a workflow resource before deploying a definition containing a singular `assignee`, then acknowledge reader model 9 on deployment. Existing model-8-and-earlier instances remain readable and keep their object/null singular representation; no stored-document backfill is required. Deploy now rejects project-role references absent from the target project's live role catalog and warns when a referenced role has no current human holder, so the deploying identity must be able to read the project role and member directories.

  Studio assignment matching and holder explanations now follow direct-user shadowing. The CLI adds viewer-scoped assignment list flags and counts, MCP instance listing adds corresponding assignment inputs and counts, and the public waiting `Diagnosis` adds a required `waitingFor` discriminant that distinguishes caller-actionable, manual-but-unavailable, and automation waits without implying that unassigned work is freely actionable.

  `@sanity/workflow-components` now exports `roleMemberCount`, which reports the distinct people who can fulfill any supplied project role using the workflow definition's aliases. Pass the current member directory, required role names, and normalized `roleAliases`; literal members and alias-only fulfillers are deduplicated by account-global user id. No upgrade action is required unless a custom assignment surface wants alias-aware pool sizes.

  **Docs impact:** Update the assignment model and authoring references, the reader-model rollout guide, guarded role-pool and take/release examples, the `@sanity/workflow-components` member-selection reference for `roleMemberCount`, Studio task-holder explanations, CLI instance-list flags, MCP list tool reference, deploy role-validation requirements, and migration guidance from removed claim sugar.

- 2de38fd: **BREAKING:** `createEngine` takes its effect settings as one `effects` group. The top-level `effectHandlers`, `effectLeaseMs`, and `missingHandler` options are removed, with no alias and no deprecation shim, so everyone who builds an engine — a Sanity Function drainer, a hosted runtime, a script, a test — must move them into `effects: {handlers, leaseMs, missingHandler}`. An unmigrated TypeScript call stops compiling. An unmigrated plain-JavaScript call still builds an engine, but one with no handlers and the default `fail` policy, so its first drain throws `MissingHandlerError` instead of dispatching.

  Migrate every construction site: `createEngine({client, workflowResource, tag, effectHandlers: H, effectLeaseMs: L, missingHandler: P})` becomes `createEngine({client, workflowResource, tag, effects: {handlers: H, leaseMs: L, missingHandler: P}})`. The resolved values read back off the engine under the same word, so `engine.effectHandlers` and `engine.missingHandler` become `engine.effects.handlers` and `engine.effects.missingHandler`. Nothing about draining changes: the same `fail` default, the same five-minute default lease, and the same claim, dispatch, and deploy-verification semantics. `@sanity/workflow-engine-test`'s `createBenchEngine(bench, overrides)` forwards `CreateEngineArgs` unchanged, so bench engines move their handler and policy overrides into the same group.

  `@sanity/workflow-studio`'s `useWorkflowEngine` follows the engine: its `effectHandlers` and `missingHandler` props are replaced by one `effects` prop taking the engine's exported `EngineEffectsArgs`, so a Studio-side drainer passes `effects: {handlers, missingHandler}`. Keep that object referentially stable, at module scope or through `useMemo` — the hook memoizes the engine on it, and a new object every render rebuilds the engine every render. The `@sanity/workflow-studio-plugin` `effectHandlers` config key is unchanged; the plugin translates it into the group where it builds the engine.

  **Docs impact:** Update the `createEngine` options reference and the effects concepts page for the new group, the missing-handler and claim-lease reference entries that named the old keys, the `useWorkflowEngine` adapter reference, the Studio plugin README's drain-function example, and every cookbook or runtime example that constructs an engine with handlers; carry the migration into the release notes.

- a2ce4a7: **BREAKING:** Mutation guards now have one public compilation path:
  `compileGuards` replaces the singular `compileGuard` export and returns every
  Lake document required for the authored guard. Callers using `compileGuard`
  must switch to `compileGuards` and persist every returned document; retaining
  the old call would either fail to compile after upgrade or omit required
  ID-space siblings. Literal field-seed document IDs now also enforce the Lake's
  128-character limit and reject double dots; replace an invalid seed with a
  valid resource-local document ID before upgrading. `MutationContext.action` now admits only the
  Lake's `create`, `update`, and `delete` operations, and
  `documentActionDenials` takes their concrete `before` / `after` mutation image
  instead of a prospective document plus authored lifecycle action. Callers of
  that helper must construct the same mutation the Lake will evaluate; otherwise
  their preview can disagree with enforcement. Pure `evaluateFromSnapshot`
  callers that supply dereference-bearing guards must also pass a
  `guardDereference` resolver for stored resource reads; the engine and reactive
  session supply their token-bound client resolver automatically.

  Mutation guards now deploy edit locks against draft IDs and publish or
  unpublish gates against published IDs using the create, update, and delete
  operations Content Lake evaluates. A guard combining both action classes
  emits separate temporary guard documents, preventing either match from leaking
  into the other ID space. Guard previews bind `document.before` and
  `document.after`, follow stored resource-local references, continue to
  understand temporary guards emitted with the older lifecycle-action vocabulary,
  and reject invalid actions, ID patterns, or predicates before deployment.

  Existing guard definitions keep their authored shape. Definitions whose guards
  stay within one emitted ID space require no rollout change and retain their
  existing reader floor. A guard that combines direct create/delete actions,
  content updates, or publish/unpublish actions across ID spaces is a detectable
  model-9 feature on both its definition and instances.

  Before deploying such a definition, upgrade every Studio, CLI, MCP server,
  Function, and other engine runtime sharing its workflow resource, then change
  that deployment's reviewed `expectedMinReaderModel` literal to `9`. This
  readers-first order is required because pre-model-9 engines only know the base
  guard document ID: after a newer engine emits an ID-space sibling, an older
  engine could otherwise advance or abort the instance, retract only the base,
  and leave an advisory lock behind. The affected instance commits reader floor
  9 before split guards deploy, so an old runtime fails explicitly instead of
  stranding a sibling. Existing affected instances need no data migration; their
  first model-9 commit raises the floor before it can create a split guard.

  **Docs impact:** Update `docs/reference.md` and the public mutation-guard
  reference to explain publish and unpublish action translation, predicate
  document bindings and dereferencing,
  deploy-time validation errors, and why mixed-ID-space guards emit separate
  documents. Update the prerelease reader-model rollout guide with the conditional
  model-9 adoption sequence, including every shared runtime, the
  `expectedMinReaderModel: 9` change, the old-retractor failure mode, and the fact
  that unaffected definitions retain their existing floor and require no data
  migration. Keep the `@sanity/workflow-engine-test` README's draft-ID examples
  and the root live-parity credential guidance aligned with those contracts.

- 2ddd3d7: **BREAKING:** `WorkflowErrorKind` can now be `concurrent-cascade`, paired with
  the new exported `ConcurrentCascadeError`, when an automatic cascade exhausts
  its revision-conflict retry budget. Consumers with exhaustive switches or
  `Record<WorkflowErrorKind, …>` mappings over the previous union must add the
  new member before upgrading; otherwise their TypeScript build will fail.

  Automatic cascade hops now recover from concurrent same-instance commits by
  reloading and re-evaluating state before retrying. Bounded retries for actions,
  field edits, and effect writes now also classify conflicts only at the parent
  instance commit, so a later guard or child-settlement 409 surfaces immediately
  instead of being mislabeled as instance contention. Update exhaustive error
  handling as described above; workflow definitions and stored instances require
  no migration.

  **Docs impact:** Add `ConcurrentCascadeError` to the engine error reference and
  describe automatic cascade conflict recovery.

- 6035672: Every mutating verb's `OperationResult` and `evaluate`'s `WorkflowEvaluation` now carry `nextEvaluationAt`, an optional ISO 8601 instant: the earliest future moment at which the passage of time alone could change what an instance evaluates to. It is the nearest `$now` boundary across every clock-reading condition site in the instance's current stage — transitions, activity filters, requirements, action filters and triggers, and editable-field gates — computed from the instance's current field values and verified by re-evaluating each site at the candidate instant. A runtime that polls on a cron can wait exactly instead (`tick`, read `nextEvaluationAt`, sleep until it, `tick` again), and a live session can re-render on the same instant.

  Read the absence of the field precisely: it is absent for two reasons and no others. Either no clock-reading site the engine can judge there has a boundary — the stage declares none, or none has one the instance's current values pin, since date arithmetic and dataset scans report nothing rather than a guess — or the instance is terminal and will never re-evaluate. A result with `changed: false` still carries it, which is exactly when a scheduler needs it: a tick that moved nothing because the deadline has not arrived yet still reports when it will. What the engine can judge differs between the two surfaces: it derives the operation-side copy caller-free, so an action filter, requirement, or editable predicate combining `$now` with `$actor`, `$assigned`, `$can`, or `$attributes` is unevaluable there and contributes nothing to a verb result. Such a site answers per actor and a verb result carries no actor, so `evaluate` — projected for one — is the surface that answers it; deploy already keeps caller-bound reads out of the cascade gates the engine acts on.

  The instant is a pure function of the evaluated instance state, its definition, and the operation's clock reading. It is never persisted and never derived after a write: a cascading verb derives it from the settled in-memory state before that hop persists, a verb returning the instance unchanged derives it from the state it loaded, and a derivation failure fails the call rather than following a commit that already landed.

  **No upgrade action required.** The field is optional and additive; existing callers, the reactive session, and the Studio and App SDK adapters compile and behave unchanged, and consumers that already return these result types expose the new field without any change of their own.

  **Docs impact:** The repository reference (`docs/reference.md`) is updated in this change; the published documentation is not. Update the published engine reference where it lists the `OperationResult` and `WorkflowEvaluation` shapes and where the verb entries describe what `tick`, `fireAction`, and `evaluate` return, so both shapes name `nextEvaluationAt` and carry the absence rule above, and correct the `createEngine.clock` entry, which says one reading per operation where the engine takes one per pass. Update the published concepts page where it explains that the engine never runs a clock and that a caller must `tick` when a deadline passes, so the scheduling story says how a runtime learns when that is.

- 26dd4e5: Generated API references now include every type used by a public signature and link cross-package symbols to their authoritative package entry. Caller-facing helper contracts such as field mutation operations, engine operation context types, test-bench argument types, member avatar data, MCP client policy, and Studio user clients are now available as named exports where their public APIs already expose those shapes. GROQ condition consumers can import the documented `COMPARISON_OPS` list alongside its `ComparisonOp` type, while the shared cross-package exhaustiveness helper is an unsupported `@internal` export and is omitted from the reference.

  **No upgrade action required.** Existing imports and runtime behavior remain compatible; consumers may adopt the new named type exports instead of reconstructing those shapes locally.

  **Docs impact:** Refresh the generated API references for the affected packages; no conceptual guides, examples, or migration guidance need changes.

- b04580d: **BREAKING:** The in-memory bench now exposes `GuardDeniedError` when Content Lake-style mutation guards reject client writes, replacing the engine-specific `MutationGuardDeniedError` previously thrown by the fake seam. Bench consumers that catch or assert the old class must import `GuardDeniedError` from `@sanity/workflow-engine-test` and match it instead; without this migration, denial assertions will fail even though the write remains rejected.

  Publish and unpublish tests must also express guards in terms of the lake mutations they commit: publish updates or creates the published document and deletes its draft, while unpublish creates the draft and deletes the published document. Replace synthetic `publish` and `unpublish` guard-action expectations with the applicable `create`, `update`, and `delete` actions.

  The engine's `DocumentValuePermission` and `Grant` types now include the lake's `manage` permission so access configurations can represent identities allowed to author system documents. `DOCUMENT_VALUE_PERMISSIONS` is now exported for consumers that need the complete runtime vocabulary.

  The bench also re-exports `WriteAccessDeniedError`, giving access-control denial assertions the same stable package entry point as mutation-guard denial assertions. No upgrade action is required. Consumers may move existing imports of this class from `@sanity-labs/client-fake-for-test` to `@sanity/workflow-engine-test`.

  **Docs impact:** Update the engine authorization API reference for the `manage` permission and `DOCUMENT_VALUE_PERMISSIONS`, plus the engine test-bench guard and access-denial guidance for the re-exported error classes and underlying publish/unpublish mutations.

### Patch Changes

- 2ba0c09: Generated API references keep navigation between public authoring, resource-alias, and observer helpers while no longer presenting private implementation helpers or private-package README targets as broken links.

  **No upgrade action required.** Runtime behavior and public TypeScript contracts are unchanged.

  **Docs impact:** Regenerate the API reference entries for these packages so their corrected TSDoc and README content is visible.

- Updated dependencies [26dd4e5]
  - @sanity/groq-condition-describe@0.5.0

## 0.31.0

### Patch Changes

- ff72ece: Reader-model errors and the Studio Workflows tool now link to the canonical `/docs/workflows` documentation routes.

  **No upgrade action required.** Permanent redirects preserve the former `/docs/editorial-workflows` URLs.

  **Docs impact:** Publish the Workflows documentation at `/docs/workflows` and retain permanent redirects from every previously published `/docs/editorial-workflows` route.

## 0.30.0

### Minor Changes

- a3a8dc0: The engine gains a list-projection read for instance dashboards. `instancePreviewsQuery` compiles the same filter arms as `instancesQuery` into a `WorkflowInstancePreview` projection — the open stage alone, field lists reduced to identity, date, document-reference, and release-reference kinds, and `claimedEffects`/`failedEffects` facts in place of the unbounded audit trails — kilobytes lighter per row than the full document. `readInstancePreviewDoc` is the matching gate-then-parse funnel (`WorkflowInstancePreviewSchema`/`parseInstancePreviewDocument` underneath), and the internal identity normalizer accepts any host carrying the identity slots, rows included. `InstancesQueryFilter` adds a keyset `before` cursor (requires `limit`) for paging the newest-first order without skipping or repeating rows across pages; both list orders now break `startedAt` ties on `_id`. **No upgrade action required** — existing reads are unchanged apart from the deterministic tie order.

  **Docs impact:** The engine reference's instance-query section documents `instancePreviewsQuery`, `WorkflowInstancePreview`, and the `before` cursor in this release's pass — the Workflows tool ships reading them in the same release.

- a3a8dc0: **BREAKING:** the exported `WorkflowObserver` contract (workflow-react) gains two required members, `fetchInstancePreviews` and `listenInstanceChanges` — a custom observer no longer compiles until it implements both; the shipped SDK and Studio adapters already do, so their consumers need no action.

  The reactive layer gains a progressively-hydrated preview list. `useInstancePreviews` (workflow-react) drains the engine's preview projection page by page until the whole filtered set is held — `drained: true` means counts over it are totals — then keeps every row fresh from ONE shared change listener per engine tag: an event refetches the touched previews alone, so update cost is per commit, never per list size. Page size is caller-supplied. The engine adds `instanceChangesQuery` (the tag partition as a listen filter), and the `WorkflowObserver` contract adds `fetchInstancePreviews` and `listenInstanceChanges`, implemented by the SDK observer (the Studio adapter inherits them). A change-feed failure never silently freezes a list: the SDK observer reconnects with exponential backoff and then emits a `reset` event, on which `useInstancePreviews` re-drains the whole partition — gap-missed additions, edits, and deletions all land.

  **Docs impact:** The reactive-core reference documents `useInstancePreviews` and the observer contract's two new required members in this release's pass — the Workflows tool ships reading them in the same release, and the custom-adapter guidance must name both members beside the BREAKING note.

- 90207dc: **BREAKING:** `assertReaderModelAcknowledgement` now requires `{requiredMinReaderModel, context?}` instead of a context string, and `ReaderModelAcknowledgementError` accepts its optional context through `{context}`. The Blueprint package's `AcknowledgedDeployment` type moves to the engine as `AcknowledgedWorkflowDeployment`; update imports and use that shared name. Assignment-valued fields can now declare a non-empty `roles` list that limits newly written assignees. Existing fields without `roles` stay unconstrained, retain reader floor 4, and continue deploying with `expectedMinReaderModel: 4`; installing this release requires no coordinated rollout or configuration change.

  Before adding `roles`, upgrade every Studio, CLI, MCP server, Function, and other runtime that shares the affected workflow resource, then change that deployment's literal `expectedMinReaderModel` to `8`. MCP deployments pass the same reviewed literal as the optional `expectedMinReaderModel` tool argument. Definitions and instances carrying the facet require reader model 8. User assignees qualify through direct roles or the definition's role aliases, while collective role assignees must literally match one configured role. Studio assignment controls, including manual start, auto-start, and assignees nested in to-do rows, offer only eligible choices while retaining stale current values so editors can remove or replace them. Constrained pickers name the active eligible roles and distinguish an empty eligible set from a search with no matches. Top-level plural and composite edits retain no more occurrences of a stale assignment at each declared assignment location than the previous value contained; removal and reordering therefore work, while an added copy is a new assignment and must qualify. Direct singular replacements and every assignment present in an `updateWhere` fragment remain strict. Each engine verb uses one member-directory snapshot across retries, cascade hops, and spawned children, then the next verb reads current membership.

  Malformed project-member and project-user directory responses now fail loudly instead of treating bad rows or role records as missing users, and actor resolution reports those failures as `inaccessible`, so integrations can distinguish directory failures from absent membership.

  CLI `start` and `definition delete` no longer apply the definition-submission acknowledgement gate; deploy, check, dry-run, definition diff, Blueprint provision, and engine definition APIs still validate the selected definitions' required floor.

  No reader-fleet rollout or deployment-literal change is required for existing definitions that do not use `roles`.

  **Docs impact:** Update the assignment field reference and authoring examples for `roles`, distinguish eligibility from editability, action permission, and literal queue ownership, and add the model-8 conditional adoption sequence to the prerelease rollout guide.

- b0b1550: **BREAKING:** Product-prefixed telemetry events now use `Workflows <event>` instead of `Editorial Workflows <event>`; `EditorialWorkflowsResource` is replaced by `WorkflowsResource`; and `defineWorkflows` now generates `workflows-<deployment name>` resource names instead of `editorial-workflows-<deployment name>`. Telemetry consumers matching the previous literals stop receiving events until updated, TypeScript consumers importing the previous Blueprint interface no longer compile, and an existing Blueprint stack that relies on the generated name treats the new default as a different resource identity.

  Update telemetry dashboards, schemas, alerts, and queries to match the `Workflows` prefix; event suffixes, payloads, and versions are unchanged. Replace Blueprint imports with `WorkflowsResource`. Before deploying an existing Blueprint stack, either pass its recorded resource name explicitly or plan the detach-and-create migration to the new default. Workflows request-tag families and billing classification are unchanged.

  Other user-facing package copy now uses the Workflows product name. No upgrade action is required for consumers that do not match telemetry event names or use the Blueprint package.

  **Docs impact:** Rename the product throughout the public documentation, move the docs section to `/docs/workflows/*` with permanent redirects from every `/docs/editorial-workflows/*` path, and document the telemetry-prefix, `WorkflowsResource`, and Blueprint resource-name migrations in the telemetry reference, Blueprint guide, and release notes.

### Patch Changes

- 210ca63: The API documentation shipped in every package's `.d.ts` files is rewritten to be substantially terser: multi-paragraph doc comments are cut to the facts a consumer needs, and internal narration no longer appears in editor hover text. Runtime behavior, exports, and type signatures are unchanged across the whole package group.

  **No upgrade action required.**

  **Docs impact: None** — the published documentation site is authored separately; only in-editor `.d.ts` hover text changes.

- a3a8dc0: `readInstancePreviewDoc` now takes an untyped lake row. A preview page slot without a string `_id` fails as a shape error named `(unknown id)` instead of being assumed to have an id for the model gate.

  **No upgrade action required.** Callers that already passed `{_id: string}` continue to type-check.

  **Docs impact:** None. The preview-row funnel is unchanged for well-formed rows; only the untyped input is honest.

- Updated dependencies [210ca63]
  - @sanity/groq-condition-describe@0.4.1

## 0.29.0

### Minor Changes

- f44fc33: Workflow conditions can now read the caller's org-level User Attributes (Enterprise) through the advisory `$attributes` variable — for example `$attributes.department == "politics"` on a fireAction action filter, activity requirement, or editable predicate. Values match what lake role filters read via `user::attributes()`, keyed by attribute name with each active scalar or array value. Soft-gate paths (`evaluate`, fireAction filter re-check, editField) fetch the bag; ticks and drainers do not. Expected absences (401/402/403/404 — non-Enterprise, missing feature, forbidden) leave `$attributes` unbound so conditions that read it fail closed; unexpected fetch failures (5xx, network) throw on those soft-gate paths only and are not cached so the next call retries. An empty successful page binds `{}`. When the Management API envelope reports `hasMore: true`, the engine still binds the partial bag and warns (`nextCursor` makes follow-up pagination a small engine change). Engine checks remain advisory; the Content Lake is still the only enforcement point. `$attributes` is never persisted on `Actor` / history. The MCP authoring guide names the new variable alongside the other caller-bound vars. The test bench accepts an `attributes` bag (construction shortcuts and per-call overrides) the same way it accepts `grants`.

  **No upgrade action required.** Existing definitions are unchanged. Authors who want attribute-gated actions opt in by writing `$attributes` in caller-bound condition sites; cascade gates continue to reject caller-bound vars at deploy.

  **Docs impact:** Update the condition-variables reference (`docs/reference.md` § context-bound variables) and any guide that lists `$actor` / `$can` / `$assigned` so `$attributes` and the Enterprise / fail-closed semantics are named; note the spelling difference vs lake `user::attributes()`.

- 26f25e0: Definition authors and effect runtimes can now use `field.inc`, `field.dec`, and
  `field.setIfMissing` operations. Arithmetic operations accept an optional
  numeric value expression that defaults to `1`, validate number-field targets,
  reject non-finite results, and participate in the same atomic engine commits as
  existing field operations. A retry is deduplicated only when the caller supplies
  an idempotency key; the arithmetic operation itself is not idempotent.
  `field.setIfMissing` targets nullable fields; list fields are always arrays and
  are rejected. When the target already has a value, `field.setIfMissing` does
  nothing and writes no `opApplied` history row. Like Sanity Content Lake patches,
  `field.inc` and `field.dec` require the target to already hold a number: a
  declared number without an initial value is `null`, so arithmetic rejects without
  committing. Initialize counters with `field.setIfMissing` set to `0` before
  incrementing when the value may be absent.

  Persisted-model version 6 adds the three operation discriminators. The change is
  additive and the reader floor remains 4, so existing definitions and instances
  require no migration. Before deploying a definition that uses these operations,
  upgrade every Studio, CLI, MCP server, Function, and other runtime that can
  process workflow data in the shared environment. The unchanged reader floor
  does not fence out an older engine, which rejects or aborts when it encounters a
  new operation rather than executing it with different semantics.

  **Docs impact:** Update the Operations guide and operation reference with all
  three forms, their defaults and validation, effect-completion availability, the
  Sanity-compatible `field.setIfMissing(0)` then `field.inc` initialization
  pattern, the warning that arithmetic never assumes a missing value is zero, and
  the bounded-retry counting pattern that loops below a fixed total-attempt limit
  and routes exhausted work to manual recovery. Note that no-op
  `field.setIfMissing` attempts write no `opApplied` history row, and include the
  readers-first rollout guidance for model 6 operations.

- 25bd1fb: Each card in the Studio plugin's Workflows tab now carries what the definition
  is doing, not just its name: how many of its documents have work in flight, when
  one of them last changed stage, how many hold a task past its due date, and one
  alert glyph when something is wrong. The card reports live state only — what a
  workflow runs on and what it says about itself change on a deploy, and that
  workflow's own Definition page already names both. The
  grid bands into "Assigned to you" and "Other workflows", so whether the reader
  has work in a workflow is carried by where its card sits; rows keep the
  catalog's alphabetical order inside each band. A card wears one alert, and it
  means a run of that workflow cannot continue without help. The engine's
  `blocked` readiness hold earns none, because it is an expected transient state
  and flagging it would mark most cards most of the time; a rejected
  document-type binding earns none either, because it belongs to the definition
  rather than to any of its runs and is reported on that workflow's Definition
  page.

  The age on a card is a STAGE ARRIVAL, not a last-modified stamp. Every engine
  commit moves an instance's change stamp — an assignment, a date, a drained
  effect — and a workflow can absorb a great deal of that without advancing, so
  the arrival is the event a catalog can read as progress. The consequence is
  deliberate: a busy workflow held inside one stage reads as old, which is the
  pathology worth seeing. Hovering that age names the move — which document went
  to which stage, and the exact time — resolving the document's title through the
  preview store only once the tooltip opens.

  Overdue is the only signal drawn in a tone — caution, where the alert glyph
  takes critical — and the only one that disappears when it reads zero: it reports
  that something is wrong rather than how things stand, so a card with nothing
  late spends no room saying so. A
  document counts as overdue while an unsettled task on it is past its due date;
  a finished task's date, however old, is not a debt. Overdue is measured on one
  shared rule with the todo rows, so a card's count and a row's face can no
  longer disagree about a single date.

  The grid counts DOCUMENTS where it used to count instances, because its reader
  is an editor and the document is what they open. Several instances on one
  document count once. An instance whose chain references no document counts as
  one unit of its own, so a workflow that runs on no document does not read as
  idle. The workflow's own page still reports instances, in those words.

  Hovering that count also says how many of those documents have yet to leave the
  stage their workflow starts from — on a line of its own, so the two facts can be
  scanned rather than read through, and folded into the first line when the answer
  is all of them, where a second line would repeat one number. A document counts
  there while any of its runs still waits at the start, judged against that run's
  own pinned snapshot, so a run begun under an earlier version answers to where
  that version started. The count stays in the hint rather than taking a slot on
  the rule: it is a part of a number the card already shows, meaningless without
  that total beside it, and no glyph in the set says "waiting at the start".

  The page no longer opens on a project-wide total. The band headings count the
  workflows, so a total above them stated the same figure twice, and a total of
  documents invited a comparison against the cards that can never add up — one
  document running two workflows is one document in a project total and one on
  each of their cards.

  The engine gains `documentStuckCause`, which classifies an instance as stuck
  from its persisted document and pinned snapshot alone — no evaluation, no
  reads, no actor. It answers for the effect- and activity-level causes
  `diagnoseInstance` reports (`failed-effect`, `failed-activity`,
  `hung-effect`) and returns `undefined` for the transition-level ones, which
  need GROQ results. It is sound but incomplete by construction: a cause it
  reports is real, and the absence of one means only that no cause was provable,
  never that the instance is healthy. Surfaces flagging on it must not word an
  unflagged state as an all-clear. `findActivityNode` and `findStageNode`, the
  tolerant definition tree lookups it uses, are exported alongside it.

  The tool's instance read is held per engine for the session and replayed on the
  next mount, which changes what the Workflows tab paints while it loads. A first
  visit now waits for that read before the definitions grid appears, where it used
  to lay out cards from the catalog and rearrange them once the instances landed —
  the grid's bands and counts come from the instances, so the cards had no stable
  shape until both reads were in. The grid waits on the reader's identity for the
  same reason: which band a card sits in depends on who is looking, and a
  project-scoped account resolves through the project member directory, so banding
  before that answer arrived would have moved every card once it did. An account
  the directory cannot place, or a directory that fails to load, is an answer
  rather than a wait — the grid paints unbanded and every card reports no assigned
  work. A later visit inside the same session paints the
  held read at once and refreshes behind it.

  The form strip's assigned-task count tells those two apart as well, so an account
  the member directory cannot place no longer leaves a spinner turning in that slot
  for the rest of the session. It shows no count, which is what it already did for
  an account with nothing assigned. The hold is not local to the grid: the
  task rows under "All documents" and "For me", and the active-instance count on a
  workflow's Definition page, read the same stream, so they too open on held
  numbers before the fresh read lands. A failed read is never held, and a provider remount mints a new engine and
  so starts cold.

  **No upgrade action required.** The card additions are automatic, and
  `documentStuckCause` is a new export that changes no existing verdict —
  `diagnoseInstance` classifies exactly as before, now sharing one
  implementation of the document-derivable causes.

  **Docs impact:** Update the Workflows tool guide where it describes the
  definitions grid, to cover the new card signals, the assigned-work ordering, the
  document-versus-instance split between the grid and a workflow's own page, and
  that the tab opens on a held read after the first visit.
  `docs/reference.md` already carries `documentStuckCause` beside
  `diagnoseInstance` with its bound stated; the hosted engine reference needs the
  same entry, so integrators do not read a missing cause as a health check.

- 3fd04f1: **BREAKING:** `ActionSemantic` was a closed union of action decision values; it now also includes signal values and the open `custom.${string}` form. TypeScript consumers that exhaustively map `ActionSemantic` must handle signal and custom values or narrow to the decision subset before upgrading, otherwise their build will fail. Workflow authors can attach advisory signals and validated custom semantics to workflow roots, stages, activities, and actions, and evaluation results expose them at each matching level.

  Existing stored definitions and runtime behavior remain compatible. The Studio plugin continues to render decision faces when decision values are composed with signal or custom semantics, while non-decision values receive the default action face.

  **Docs impact:** Update the definition and evaluation references plus the concepts guide to document level-wide advisory semantics, the signal vocabulary, custom grammar, and action-only decision values.

## 0.28.0

### Minor Changes

- 5050b06: **BREAKING:** Authoring a deployment now types through `WorkflowDeploymentInput` / `WorkflowConfigInput`, which require `expectedMinReaderModel` as the current reader-floor literal. Passing a parsed `WorkflowDeployment` / `WorkflowConfig` (where the floor is optional/unverified) into `defineWorkflowConfig` or `defineWorkflows` is a type error — share the authored deployment object instead of `config.deployments[n]`. The same pin shows up on the blueprint resource: `EditorialWorkflowsResource.deployment` and `parseWorkflowDeployment`'s return type are now `AcknowledgedDeployment` (floor asserted to the current literal), so a hand-constructed provider resource must carry that literal too.

  At runtime, config parse no longer rejects a stale or missing floor on an untargeted deployment. Only deployment-scoped commands assert, and only the selected deployment: definition deploy, `--check` / `--dry-run`, blueprint provision, `start`, `definition delete`, and `definition diff` (the last is a deployment-scoped read). Instance-id commands (`fire-action`, `abort`, `set-stage`, `reset-activity`) deliberately do not assert — they resolve by instance id, not by a declared deployment's acknowledgement — so an unacknowledged floor does not stop those instance commits.

  Upgrade TypeScript configs and blueprint manifests that fed a parsed deployment into those helpers: keep a shared authored object (`satisfies WorkflowDeploymentInput`) for both `defineWorkflowConfig` and `defineWorkflows`, and give any hand-built `EditorialWorkflowsResource` the current floor literal on `deployment`. Existing configs that already acknowledge the current floor keep working at runtime; a stale selected deployment still fails with `ReaderModelAcknowledgementError` (headline + short steps; the CLI renders it through the clean styled-error path).

  **Docs impact:** Update the CLI / blueprint authoring examples and the prerelease reader-floor guidance so they name `WorkflowConfigInput` / `WorkflowDeploymentInput` / `AcknowledgedDeployment`, forbid passing `config.deployments[n]` into `defineWorkflows`, state that instance-id writes are outside the acknowledgement gate, and stop implying whole-config parse-time rejection for commands that never select a deployment.

- a044ba5: Report a Studio start whose auto-advance lost a write race as the finished run
  it is. Starting a workflow from the Studio while another runtime (a deployed
  Function, a script) drives the same instance could hand the editor a warning
  toast — "'…' started but didn't finish", with a raw `unexpected revision ID`
  mutation error under it — for a run that had in fact completed: the Studio's own
  auto-advance simply lost the write race to whoever committed the equivalent move
  first. That toast was indistinguishable from a genuinely stuck workflow. The
  Studio now confirms the completed start instead of warning about it.

  Narrow by design: only a lost revision race whose run is already complete is
  reclassified. A conflict that left the run in flight, and any other reason an
  auto-advance failed, still surface as before.

  `@sanity/workflow-engine` exports `isRevisionConflict`, the predicate that tells
  a lost optimistic-locking race from a real error, so integrations can classify
  one without matching on message text. It answers on the error alone, so narrow
  to a single rev-guarded write before asking — a bare 409 also covers a create-id
  collision.

  **No upgrade action required.** Engine behaviour is unchanged and the new export
  is additive.

  **Docs impact:** `isRevisionConflict` is new public engine surface, added to the
  errors section of `docs/reference.md` alongside the concurrency errors it
  classifies; mirror that entry wherever published reference material lists the
  engine's error helpers.

### Patch Changes

- 1e4a5da: When two runtimes both try to create the same stage guard after each observing it absent — for example a deployed Function reacting to instance commits while a script advances the same workflow — the losing create no longer aborts guard deploy. It falls through to the body-reconciling patch the existing-document path already uses, and writes its own resolution of the guard's conditions rather than assuming the two are identical. Concurrent deploys of an already-present guard were already a patch and are unchanged.

  **No upgrade action required.**

  **Docs impact: None** — `docs/reference.md` already documents `deployStageGuards` as an idempotent upsert.

## 0.27.0

### Minor Changes

- 780cf93: **BREAKING:** `ProjectMember.roles` is now `readonly {name: string; title?: string}[]` instead of `readonly string[]`, and `AssigneeStack`'s `roles` prop takes the same records rather than name strings. This affects integrations that build or read `ProjectMember` rows directly, or render `AssigneeStack` themselves. Read `role.name` wherever a role name was read before, and pass role records rather than name strings into `projectMemberRow` and `AssigneeStack`. Until migrated, TypeScript fails at those sites. Integrations using `useProjectMembers` from `@sanity/workflow-sdk` or the Studio plugin's own equivalent get the new shape without changes, because the adapters own the projection.

  A role now reads as its project title rather than its machine name — `Administrator`, not `administrator` — wherever one is shown: picker role rows, assignee badges, the instance-snapshot pills, and the hover hint naming a collapsed assignee cluster. A square role avatar takes its letters from the title too, so `Blueprints Deployer` reads as `BD` where `blueprints-deployer` could only ever give one letter; its colour still derives from the machine name, so retitling a project role keeps the role's colour. A role whose membership record carries no title — or a title that is only whitespace, which counts as none — and a role named by an assignee that no current member holds, both still read as the machine name. `roleLabel`, `roleLabelFor`, and `memberRoleFor` are exported for callers rendering their own role labels.

  Both people-pickers now say who a person is, so choosing one no longer requires knowing the org chart. Search matches role names and titles as well as display name and email, so typing a role narrows the list to its holders. Members are also listed by display name rather than in the order the host supplied them, which was the sequence people joined the project — expect the list order to change, and on a large project to become usable. And hovering a row previews the account behind the name — a larger avatar badged with the person's identity provider, their email, and the roles they hold. Marks exist for Google, GitHub, and `saml-`-prefixed deployments; any other provider badges nothing rather than showing an empty circle. That is what tells two members sharing a display name apart, which no role label could. Rows share one tooltip delay group, so the wait to open is paid once and moving along the list swaps the preview rather than waiting again at each row.

  `MemberAvatar` takes an optional `loginProvider` to badge the provider mark onto its corner. `ProjectMember` gains optional `loginProvider` and `isCurrentUser`; both are populated by the adapters, so integrations using `useProjectMembers` get them without changes.

  Neither picker ranks or groups its member rows by the roles those members hold, and neither claims who is eligible for an activity. (The roles-and-members picker still lists selectable roles above the members, as it did before.) An activity has no role gate; only an action does, and a manually fired action's `roles` is folded into its `filter` at desugar, so the accepted set is not readable from a deployed definition. A picker has nothing to derive eligibility from, and a ranked list would assert something no engine or Content Lake check backs.

  Stored values are unchanged. An assignee still persists the machine role name, and titles are display only.

  **Docs impact:** Update the `@sanity/workflow-components` member-selection reference for the `ProjectMember.roles` and `AssigneeStack` `roles` shapes and the `roleLabel` / `roleLabelFor` / `memberRoleFor` exports (done in this package's README). Any concept or guide page showing a role in Studio UI should show titles rather than machine names, and the assignment guide should state that a picker never restricts or ranks who may be assigned. Add the `ProjectMember.roles` migration to the release notes.

## 0.26.0

## 0.25.0

### Minor Changes

- 177d600: Deployed workflow environment tags are now discoverable.

  The engine gains two cross-partition GROQ builders: `deployedTagsGroq()` lists
  every tag holding a deployed definition in a resource, and
  `definitionTagsGroq()` narrows that to one definition name via `$definition`.
  Both deliberately span tag partitions — every other read is tag-scoped, and
  `workflow.query` refuses GROQ that isn't — so they answer "which environments
  exist here" for a caller holding a resource but no tag. They report what is
  _observed_: a tag with nothing deployed does not appear.

  The stdio MCP server adds a `list_workflow_tags` tool taking a
  `workflow_resource` and no tag. It is registered by the host rather than exported
  as a tool def, because a def is only ever handed an engine and an engine is
  pinned to one tag. `LIST_WORKFLOW_TAGS_TOOL_NAME` and
  `LIST_WORKFLOW_TAGS_DESCRIPTION` are exported so an embedding host registers the
  same capability under the same name without re-authoring the model-facing
  wording. The `tag` parameter's description now points an agent at that tool where
  a server offers it and at the user otherwise, and requires confirmation either
  way — having the list does not license picking from it.

  Both registration paths share one outcome path, `withToolTelemetry`, so the
  result envelope, error rendering, and the `Editorial Workflows MCP Tool Called`
  event cannot diverge between a def-backed tool and a host-registered one. Tag
  discovery reports its adoption event like every other tool, and because it names
  a resource it can also initialize the stdio server's deferred telemetry shell —
  which matters when discovery is an agent's first call.

  The CLI's definition-tags probe runs the engine's builder instead of its own
  copy of the query, so its `params` key is `definition` rather than `name`, and
  the tag partitions it names in an ambiguity error arrive sorted from the lake.

### Patch Changes

- fc12989: Fixes actor resolution failing with `principal id "…" is not an account-global
user id` for a session scoped to a single project, such as a SAML-SSO Studio
  session.

  `actor.id` is always the account-global user id, and the id's namespace decides
  which read supplies it rather than the host that answered. Whichever `/users/me`
  read returns an already-account-global id supplies it; a project-scoped id is
  bridged to its account-global form first — by string surgery for an
  `e-<globalId>` principal, otherwise through the project's own user directory
  (`/projects/<id>/users/<principal>` → `sanityUserId`). A SAML-SSO session
  resolves through that directory, because the global host holds no
  account-global record for it.

  A session whose id is already account-global issues no directory request. A
  project-scoped id that no route can bridge is refused, naming both failed
  routes.

  The project-user directory admits only a row answering the id it asked for,
  matching the batched member join: a row for another principal reports
  inaccessible rather than resolving to that person's identity.

## 0.24.0

### Minor Changes

- 0bc4328: Render diagram tooltips in the Studio's own idiom, through one seam instead of six hand-assembled bodies:
  - Pin the chrome once (padding 2, radius 3, shadow 2, 280px sentence cap / 400px for dev mode's label-value grids). Bodies no longer carry their own outer padding, which had stacked a `padding={3}` box inside the tooltip's own padding.
  - A title with nothing under it renders in regular weight — it is the whole message, not a heading. Semibold is reserved for a title that actually heads content, one per tooltip: gate headings now separate from their checklist rows by full-strength versus muted text rather than a second bold.
  - Checklists, the grouped-edge roster, the group vertex's stage list and an activity's causal waits render as real `<ul>`/`<li>` rows, so wrapping and nesting come from the browser. Previously these were flattened into padded strings with `white-space: pre-wrap`, which left a wrapped row's continuation aligned under its own marker. Each row leads with its glyph in a fixed-width column and hangs its wrapped lines back to the text: one column for a bullet and a verdict alike, where a `list-style-type` marker box is sized by its own content and put the two on different left edges within one tooltip. The glyph is inline content rather than a marker, so it is selected and copied with the row it belongs to.
  - Space the body on one three-step rhythm, named by the role a gap plays: independent blocks (the activity roster, each gate) separate furthest, a lead-in sits closer to the list it introduces, and rows within a list sit closest. A stage tooltip nests several of these, and at one flat step the whole explanation read as a single mass.
  - `MetaTable` renders rows only; the title and description come from the shared body, so dev-mode and end-user tooltips head identically.

  `OUTCOME_MARKS` and `NEUTRAL_MARK` are now exported (from `@sanity/groq-condition-describe`, re-exported by `@sanity/workflow-engine`), so a structured checklist renderer and `checklistLines` draw their verdict glyphs from one vocabulary.

- 41a3f02: Add `dueDate` and `dueDatetime` field kinds — elevated aliases of `date` / `datetime` (same stored value and validation) that mark THE due date of a level, so surfaces can identify a deadline by kind instead of guessing which date field means "due". Declarable at workflow, stage, and activity scope; optional (no field becomes required). The kind reserves a level's single due slot, so deploy enforces both halves of that: at most one due-\* (either kind, combined) per scope, and none below scope level — a due-\* nested in an `object`/`array` sub-field or an effect's `outputs` is rejected, naming `date` / `datetime` as the fix, because no deadline reader looks there. A `todoList` row's `dueDate` column is unaffected; it is a `date` named `dueDate`, not the kind. Choice lists (`options`) work on the due kinds exactly as on `date` / `datetime`. Persisted-model version 5 (additive, reader floor unchanged).

  The Studio plugin edits and renders the new kinds exactly like the base kinds they elevate: the calendar picker in the start dialog, the Overview pills, the inline field editors and the activity row's date control, a locale-formatted face, and the Workflows tool's Date filter. Every date-family branch now routes through one shared kind predicate, so an elevated alias can't drift out of a site.

### Patch Changes

- Updated dependencies [0bc4328]
  - @sanity/groq-condition-describe@0.4.0

## 0.23.0

### Minor Changes

- 795b4bb: `set-stage` now makes `--to` optional: omit it on an interactive terminal and the command presents a picker of the instance's declared stages, with the current stage marked and the cursor opened on it. Because `set-stage` is an admin override, every declared stage is offered — not just reachable transitions. The candidates come from the instance's pinned definition snapshot (the same model the engine validates the move against), so the menu can never offer a stage the move would reject. Off a non-interactive terminal `--to` stays required, so scripted use is unaffected. The engine now exports `parseDefinitionSnapshotValue` for reading a definition snapshot from a minimal instance shape.

### Patch Changes

- 94d311e: Resolve account-global actor identities when a Studio client is explicitly bound to a project API host, and refuse project-scoped identities returned through custom or malformed API hosts.

## 0.22.0

### Patch Changes

- 88ba4ba: Allow stale reader-model acknowledgements to reach the runtime gate, which provides readers-first rollout guidance before any client access.

## 0.21.0

### Minor Changes

- d9394e5: **BREAKING:** Settle every child created by one spawn commit before the parent reacts to the cohort.

  Parent transitions and triggered actions now observe the complete same-commit cohort instead of intermediate prefixes where later children are still unprimed. Spawn propagation stamps terminal child rows in one parent commit, cascade hops reuse an unchanged drain read, and successful aborts reuse their committed instance for immediate drain and ancestor propagation.

- f4bc057: **BREAKING:** `list_workflow_instances` now returns one page with `has_more` and an optional `next_cursor`; callers that need every match must continue with the cursor. The optional `limit` accepts 1–100 rows and defaults to 25.

  Bound instance and definition list reads with lake-side filtering and consumer-specific projections.

  Document filtering now excludes exited-stage references and includes live unresolved child-workflow references. Definition discovery selects and model-gates only the latest deployed version of each workflow name; historical versions remain stored and available to history-oriented APIs.

  The MCP eval suite now verifies that agents follow list cursors to find a target beyond the first default page, including in persisted Braintrust runs.

  MCP tool telemetry reports a `cursorUsed` boolean so continued list-page adoption is measurable without sending cursor values, arguments, or results.

- bcc30fe: **BREAKING:** One identity namespace inside the engine — every principal id in live state is the account-global user id (`sanityUserId`). The write boundary admits global-namespace ids only (`g…` humans, `p-…` robots verbatim; `e-…` third-party ids normalize to their embedded global form in the persisted output; plain project-scoped ids and unclassifiable forms are rejected with the remediation named). Actor resolution reads `/users/me` on both the workflow resource host and the global host: the global record is the canonical actor id, the resource host supplies roles, and the resource-local principal id rides the in-memory access context to bind `identity()` in guard previews and grant-filter evaluation — so advisory verdicts agree with the lake's own dialect, including per-resource identity for foreign-subject forecasts. Identity-kind guard `metadata` projections deploy in the target dataset's LOCAL spellings (translated through the project member list at deploy/refresh), so attribution predicates work without the author knowing two namespaces exist. Instances written before ids were namespace-classified resolve their live-state ids to global through the project-users directory at the read funnel (all-or-nothing per document, loud when unresolvable) and converge to global spellings on their next commit; `history[]` stays verbatim as audit record. Ships as data model 4 with reader floor 4: pre-classifier engines refuse new instances rather than mis-compare them, and deployment acknowledgements move to `expectedMinReaderModel: 4`. The prefix classifier is public API (`classifyPrincipalId`, `lakePrincipalId`, the `identity()` sentinels) so adapters can share the one namespace rule. **Existing instances written with project-scoped ids may no longer match user-identity queries and list filters until their next engine commit self-heals them; a prerelease deployment with no data worth keeping can reset with `sanity-workflows nuke` and start fresh.** There is no fallback to a project-scoped actor: when the workflow resource host reports a project-scoped principal, resolving the account-global record is required and its failure refuses the call. **Docs impact:** upgrade guidance is canonical in `docs/reader-model-rollout.md` § "Crossing to model 4" — any changelog-derived docs, upgrade notes, or assistant guidance should point there (readers-first sequencing, self-heal semantics, and the `sanity-workflows nuke` reset recommendation for prerelease data).
- e7392af: Add the `resetActivity` admin verb — reset a failed (or otherwise terminal) activity in an instance's current stage back to `active` (re-run) or `skipped` (bypass), then cascade so a `$allActivitiesDone`-gated exit transition can fire. `workflow.diagnose` now marks its `reset-activity` remediation `available`, and the CLI ships the real `reset-activity <instanceId> <activity> [--skip]` command in place of the stub. Emits the `Editorial Workflows Activity Reset` adoption event on every attempt (`changed: false` on a no-op), matching the `set-stage` and `abort` overrides.

  Writes strictly within the existing model-3 grammar: it reuses the `activityStatusChanged` history variant and the existing activity statuses, so it adds no persisted shape — there is no data-model version bump and no reader-floor change.

- fa9c796: **BREAKING:** Replace the singular `start.allowed` and activity requirement record with ordered, named requirement arrays.

  Start readiness now accepts polymorphic `groq` and `singleSubject` nodes:

  ```ts
  // Before
  start: {allowed: '$fields.approved == true'}

  // After
  start: {
    requirements: [
      {type: 'groq', name: 'approved', title: 'Approval required', query: '$fields.approved == true'},
    ],
  }
  ```

  Use `singleSubject` instead of `$subjectHasInFlightInstance` to allow at most one in-flight run of the same definition for a subject. The requirement is definition-scoped and version-blind across deployments:

  ```ts
  // Before
  start: {allowed: '!$subjectHasInFlightInstance'}

  // After
  start: {
    requirements: [
      {type: 'singleSubject', name: 'single-subject', description: 'Finish the existing run first.'},
    ],
  }
  ```

  Activity readiness uses the same ordered descriptor model with `groq` nodes:

  ```ts
  // Before
  requirements: {
    approved: 'defined($fields.approval)'
  }

  // After
  requirements: [{type: 'groq', name: 'approved', query: 'defined($fields.approval)'}]
  ```

  Requirement names must be unique within their owning array. Evaluation preserves author order and reports every unmet requirement with its `name` and optional editor-facing `title` and `description`. Fresh standalone starts enforce the requirements after validating inputs. Resuming an unfinished start and parent-owned spawning continue to bypass start requirements.

  `evaluateStart()` now returns ordered `requirements` entries containing each descriptor, outcome, and GROQ insight where applicable. Its singular top-level `insight` is removed. `StartNotAllowedError.insight` is replaced by `StartNotAllowedError.unmetRequirements`. Activity evaluation likewise reports unmet requirement descriptors instead of names alone.

  Rename the public start-requirement analysis helpers and constants:

  ```ts
  // Before
  explainStartAllowed(args)
  unboundAllowedReads(query, fields)
  START_ALLOWED_VARS

  // After
  explainStartRequirement(args)
  unboundRequirementReads(query, fields)
  START_REQUIREMENT_VARS
  ```

  `definitionsForDocument({document, subject})` becomes `definitionsForDocument({document})`. Start applicability no longer needs a separately supplied subject. The engine-owned start dataset projection exposes only `definition`, `subject`, and `completedAt`; authors no longer query raw instance storage for deduplication.

  Studio pre-flights both requirement kinds against the live document session, disables starts whose requirements are unmet, and renders the authored description or title with a humanized requirement-name fallback. Controls re-enable on the same mount when a blocking run completes.

  Persisted data model 4 unconditionally raises `minReaderModel` to 4 for new definitions and instances because older readers would ignore readiness arrays and could commit invalid transitions. Upgrade every reader and Function before deploying model-4 writers. Legacy deployed definitions are not normalized; prerelease environments with incompatible definitions may use `sanity-workflows nuke` before redeploying.

### Patch Changes

- 92e28bd: Fix reset telemetry test fixtures to use the current reader model.

## 0.20.0

### Minor Changes

- ab5e454: Export project-user response validation for host adapters that consume Sanity project-user APIs.
- e3122cc: New `instancesGuardQuery(instanceIds)` — the set-shaped guard filter (`sourceInstanceId in $instanceIds`, ordered by `_id`) reactive adapters subscribe as one shared live query per resource for every co-mounted session. `instanceGuardQuery(id)` delegates to it, so the per-instance and per-set reads share one filter definition; its compiled query string changes accordingly (same rows selected).
- 7c4dd86: Reduce guard lifecycle request volume and chunk orphan cleanup transactions.

### Patch Changes

- bce09fc: Restore automatic effect request tags while preserving concrete handler client APIs, backed by native request-prefix support in the test client.
- efb4cd9: Discriminator validation now reports an unknown field kind, field source, or op value expression at its exact `type` path instead of collapsing to "Invalid type: Expected Object but received Object". The schemas route on `type` rather than trying indistinguishable object arms in a plain union, so newer syntax used with an older engine identifies the unsupported value and the installed engine's valid options.
- 46b0285: **BREAKING:** Replace manually declared document applicability with automatic
  discovery from deployed first-class subject fields.

  Update Studio configuration as follows:
  - `mappings` is optional. Omit it when every applicable definition declares a
    first-class subject. A mapping may customize an automatically discovered
    `(docType, definition)` binding or explicitly register a definition modeled
    with a plain `doc.ref` instead of a first-class subject.
  - Multiple workflows may target one document type. Use one mapping row for each
    distinct `(docType, definition)` pair. An exact duplicate pair is a
    configuration error rather than a last-row-wins override.
  - Remove the top-level `autoStart` map or function. Put `autoStart: true` on
    each mapping row that should start automatically. Configure workspace-specific
    behavior in that workspace's mapping rows. This also works for explicitly
    registered definitions using the `doc.ref` field named `subject` convention.
  - Replace `workflowDefaultDocumentNode({mappings})` with
    `workflowDefaultDocumentNode()`.

  Before:

  ```ts
  structureTool({defaultDocumentNode: workflowDefaultDocumentNode({mappings})})
  workflowStudioPlugin({
    tag: 'production',
    mappings,
    autoStart: {article: ['article-review', 'legal-review']},
  })
  ```

  After:

  ```ts
  structureTool({defaultDocumentNode: workflowDefaultDocumentNode()})
  workflowStudioPlugin({
    tag: 'production',
    mappings: [
      {
        docType: 'article',
        definition: 'article-review',
        label: 'Article review',
        autoStart: true,
      },
      {
        docType: 'article',
        definition: 'legal-review',
        label: 'Legal review',
        autoStart: true,
      },
    ],
  })
  ```

  Also remove all per-schema Editorial Workflows preview wiring:
  - Remove `components: {preview: WorkflowStagePreview}`.
  - Remove `_id` added only for Editorial Workflows from `preview.select` and
    stop passing it through `preview.prepare`.
  - Remove imports of `WorkflowStagePreview`; that component is no longer a
    public package export.
  - Remove imports of `mappingForDocType` and `workflowDocTypes`; effective
    mappings are resolved inside the plugin and those host-side helpers are no
    longer exported.
  - Keep each schema's native inferred or custom preview unchanged. The plugin
    now installs preview middleware itself, consumes the document identity Studio
    already supplies, and delegates title, subtitle, media, and custom preview
    composition through `renderDefault`.

  Workflow stage pills appear on Studio surfaces that invoke preview middleware,
  including reference and array-item previews. Custom preview components that
  replace Studio's layout must render the `status` prop they receive. Studio's
  Structure document-list rows bypass both plugin and schema preview middleware,
  so they do not show workflow stage pills. Workflow status remains available in
  the document form, footer badge, Workflows view, and Workflows tool.

  Document-reference GDRs for dataset content now reject stored draft IDs
  (`drafts.<id>`) and Content Release version IDs
  (`versions.<release>.<id>`). Use the stable document ID in the GDR and select
  the draft or release through workflow perspective instead. The validation error
  includes the corresponding stable ID so CLI and API callers can correct the
  input before an unresolvable workflow instance is created.

  Previously persisted draft/version GDRs remain invalid workflow identities.
  Read-side Studio displays now tolerate them by showing the raw URI instead of
  crashing, and query-sourced occurrences are discarded through the existing
  fail-soft field-resolution path. Correct existing data by starting a new
  instance with the stable document ID; perspective selects the desired draft or
  release content.

- 8a76c67: Add incremental reactive-session document feeds, coalesce watched-document emissions, and reuse discovery derivations and Studio layout output. Deleted watched documents now leave the held snapshot instead of remaining as stale evaluation input. The component test runner also has aggregate-suite timeout headroom.
- 7e8f459: Batch snapshot hydration to reduce watched-document read latency.
- 98e488e: Stabilize Editorial Workflows discovery subscriptions and limit full reactive sessions to surfaces that need live evaluation.

## 0.19.0

### Minor Changes

- 24b11dd: Effect handlers can report intermediate field state mid-dispatch. The handler context gains `ctx.commitOps({ops, idempotencyKey})` — field ops only, validated like completion ops, executed through the new `workflow.commitEffectOps` verb as a standard engine commit (gate, history, idempotency ledger, compare-and-swap persist, guard refresh, cascade) — and `ctx.setProgress(field, value)`, sugar that coalesces pending absolute sets per field. Calls enqueue synchronously into a bounded per-dispatch queue (depth 32, 200 commits per dispatch) that serializes commits in call order; overflow throws synchronously at the call site, and settlement drains the queue before completion so an un-awaited failed report still fails the effect. Pending-effect claims now carry a `claimToken` minted on every claim and takeover: a report from an expired, released, or superseded dispatch is rejected before writing (`StaleEffectClaimError`), and a successful report renews the claim's lease. Completion semantics are unchanged and remain claim-blind first-writer-wins. Each report emits the sampled `Editorial Workflows Effect State Reported` telemetry event (adoption signal, max one per minute). Persisted-model note: the claim token rides persisted model 3 additively (see `DATAMODEL.md`).
- 2005ab7: Action evaluations carry a `firing` consequence (`FiringConsequence` `{exitsStage, transition?}`): what firing the action would do to the flow right now, computed by replaying the fire in memory through the same machinery a real commit runs — ops, the triggered fixpoint, then transition selection — against the projection's state. The answer is total for the current state and conditional on the commit landing; it is omitted where the replay can't be faithful (caller params, a spawn's dataset-driven fan-out in the hop, a terminal instance, a stage visit whose entries have diverged from the pinned definition) and on cascade-fired actions. Advisory, like every derived verdict. Wrong-shape `field.updateWhere` aborts (a merge resolving to a non-object; a resolved merge carrying reserved row keys) now throw the typed `FieldValueShapeError` on the commit path, joining the other wrong-shape write aborts.
- 24b11dd: Add the `progress` field kind: an elevated `number` carrying application-defined 0–100 completion, so Studio and SDK surfaces can identify and elevate it without guessing which number field means "how far along". Every non-null value must be finite and within 0–100 inclusive (fractions allowed), enforced by one value schema at every write boundary — declaration seeds, start values, edits, ops, nested sub-fields, and effect outputs. Choice lists are rejected on the kind at authoring time. Mints persisted model 3 additively (see `DATAMODEL.md`).
- 59b40fd: **BREAKING:** a deployment's `name` is now its identity in `defineWorkflowConfig`: enforced unique across the config and constrained to the same grammar as `tag` (lowercase letters, digits, dashes — free text like "My cool workflow" is rejected). Tags may now repeat across deployments; the enforced storage invariant is instead the `(workflowResource, tag)` pair — two deployments sharing both are rejected with each entry named, since they would write into the same partition and fight over definition versions.

## 0.18.0

### Minor Changes

- 3af2ca0: Derive each persisted definition and instance reader floor from the model features it actually contains. Export the append-only data-model change manifest and feature diagnostics so compatible model-2 documents remain readable by older engines while typed choice lists still fail closed.
- 7276702: Insight phrases resolve effect titles and drop the "settled" jargon. `$effectStatus` requirement phrases and autonomy effect waits now render the effect's declared `title` — an untitled effect keeps its registry name as-is — and the requirement verbs are plain outcomes: "must have succeeded" / "must have failed" / "must have finished". The `requirement.effect-*` and `autonomy-wait.effect` phrase params carry both `effect` (the registry name) and the resolved `title`, so consumers restyling by phrase id needn't re-derive either.
- 58f8211: Export `expandResourceAliases`, `refsOf`, and the `LogicalRef` type from the package root. Deploy-adjacent tooling can now run the alias expansion as an eager validation (fail-closed on unbound `@<handle>:` references before any write) and walk a definition's spawn references without re-implementing the walk.
- 00c089d: **BREAKING:** Require every definition deployment and workflow deployment configuration to state an `expectedMinReaderModel` literal that exactly matches the installed engine's writer capability.

  Deploy and definition-diff paths now reject missing or stale acknowledgements before client access or telemetry, with a structured error and readers-first rollout guidance.

- cd03973: **BREAKING:** Reject initial workflow field values that cannot be consumed and expose structured preflight issues.

  Calls that supplied unknown, wrong-kind, non-input, non-workflow-scope, or duplicate initial field rows previously succeeded while discarding those rows. They now fail before creating an instance with structured remediation details.

  Deploy also rejects `spawn.with` keys that the resolved child definition cannot consume because the workflow field is missing or is not input-sourced. `SpawnContractsInvalidError` exposes every rejected parent/child row for machine-readable remediation.

- d26cc1a: Add the engine-owned Actor resolution contract with client-backed resolution for server, CLI, and MCP runtimes; add native Studio and App SDK project-user integrations; and migrate the Studio plugin member picker to the shared directory.
- 9126299: **BREAKING:** Delete persisted stage guard documents when their stage exits, and remove the lifted-record `GUARD_LIFTED_PREDICATE` and `isGuardLifted` exports.

  Guard deletion now uses the observed document revision so stale exit reconciliation cannot delete a guard reactivated by a newer stage visit. Reactive guard streams contain only active persisted guards.

- 72018af: Add an extensible action semantics array with decision.accept and decision.decline as the initial engine-owned vocabulary.
- 5cd8ffd: **BREAKING:** Effect handlers now receive each host's concrete Sanity client unchanged, preserving its complete runtime and type surface. Handler traffic is no longer automatically tagged as `workflow.effect` or pinned to the engine API version; handlers own that configuration.
- b82bda4: **BREAKING:** `startInstance` rejects any `initialFields` row that would not land on an input-sourced declared entry — an undeclared name, a kind mismatch, or an entry that seeds itself (query/literal/fieldRead/working memory) — with `InitialFieldsInvalidError`. Previously such rows were silently ignored and the instance started without the caller's value.
- 55a54b3: **BREAKING:** the subject is now a first-class field kind, and the subject-entry rule keys on it.

  New `subject` field kind: an elevated single `doc.ref` (same GDR value, validation, and `types` facet) that names THE document a workflow is about. Deploy enforces its placement — workflow scope only, at most one per workflow, never a nested sub-field. A subject entry dereferences in conditions, joins the reactive watch-set, routes spawn discovery, and canonicalises query/spawn refs exactly like a `doc.ref`. The persisted data model grows the value additively (`DATA_MODEL_VERSION` is now 2). The subject kind itself does not raise the reader floor — model 2's floor of 2 comes from the typed-choice-list change shipping alongside; see `DATAMODEL.md`.

  The breaking half: `isSubjectEntry`, applicability (`acceptsDocumentType` / `definitionsForDocument` / document pickers), the autonomous-start deploy invariant, and the root-reading `start.filter` check now identify the subject by the `subject` kind — a required `doc.ref` / `doc.refs` input no longer counts. A deployed definition using that convention still parses and runs, but stops surfacing from document pickers (and stops satisfying the autonomous/root-read invariants on redeploy) until it declares a `subject` entry.

  New exports: `isSingleDocRefKind` (single-GDR kinds — `doc.ref` and `subject`), `isSingleDocRefEntry` (its resolved-entry narrowing), and `refKindAcceptsTypes` (the kinds carrying the accepted-target `types` facet).

- b82bda4: Add the opt-in `$subjectHasInFlightInstance` start variable for composing subject-exclusive visibility and permission rules.
- 4490442: Add inclusive validation.min/max bounds for workflow string, text, and number declarations, with Studio input constraints and MCP authoring guidance.
- 1540dce: **BREAKING:** Definitions and instances written by this release require a model-2 engine reader; upgrade every reader before deploying its writers.

  Workflow fields, nested field shapes, effect outputs, and action parameters can declare typed scalar choices with `options.list`. The engine validates authored lists and rejects runtime values outside them, Studio renders one shared select control and displays each selected choice by its title, and the MCP authoring guide explains the syntax.

### Patch Changes

- 239d9f6: Fix action operation values to follow the intended lexical lookup order by reading fields on their current activity before the stage and workflow, including writes made earlier in the same transaction.
- 71cd58e: Explain that effect-completion field operations require an explicit workflow or stage target scope when validation rejects a missing scope, and document the requirement on `EffectHandler`.

## 0.17.0

### Minor Changes

- f9389e5: **BREAKING:** the evaluation nodes gain a required causal-autonomy slot — `WorkflowEvaluation.autonomy` (`WorkflowAutonomy`), `StageEvaluation.autonomy` (`StageAutonomy`), `ActivityEvaluation.autonomy` (`AutonomyAnswer`). Code that constructs evaluation shapes by hand (test fixtures, adapters) must now supply them; reading consumers are unaffected.

  Causal autonomy analysis: `deriveWorkflowAutonomy(definition, {children?})` answers "will this activity complete without a caller, and if not, what is it waiting on?" by static dataflow over the stored definition, instance-free. Each gate's reads are classified by their producers — writer actions (caller- vs cascade-fired, followed transitively), `input` seeds, the edit seam, effect completions (autonomous given the host's drain), spawned children (recursed when a `children` map resolves them), lake content reads, `$now` — and rolled up per activity, stage, and workflow as `completesWithoutCaller: 'yes' | 'no' | 'conditional'` plus structured `waitsOn` entries. A cascade-fired action's `roles` execute pin counts as a dependency: the runtime holds a pinned trigger armed until a capable token cascades, so a pinned automation reports `conditional` with an `execute-pin` wait naming the roles. This is the causal refinement of the mechanical `ExecutorClassification`: an all-`when` activity whose triggers only read caller-written fields classifies `autonomous` but answers `no` here, naming the caller action it waits on (role pin recovered from the desugared membership filter). Advisory like every insight — a narratable answer, never a gate.

  Narration joins the insight render surface: `describeAutonomyWait(wait, ctx)` phrases one wait, `narrateAutonomyWaits(waits, ctx)` phrases and de-duplicates a list, `autonomySummary(autonomy, ctx)` gives the workflow-level line ("this workflow runs itself except at …"). `stageAutonomyOf(autonomy, stageName)` / `activityAutonomyOf(stageAutonomy, activityName)` are the total rollup lookups (throw on a miss), and the engine root now also re-exports `atomReadsDataset` alongside the rest of the `@sanity/groq-condition-describe` surface.

- c3eed2e: Export `entryDocRefs` — the canonical `doc.ref`/`doc.refs` GDR extraction over field entries (with its untrusted-lake-data narrowing) — and add `limit` to `InstancesQueryFilter`: a capped read returns the NEWEST rows (`startedAt desc`, sliced), so bounded consumers stop streaming unbounded datasets.
- 092a0d4: **BREAKING:** runtime-supplied refs written into field state are gated on the deployment's declared resource surface.
  - A `doc.ref` / `doc.refs` / `release.ref` value a caller or effect handler supplies — start `initialFields` input, an action's param-sourced op values, `editField` values, effect-completion ops — must target a declared resource: the `workflowResource` itself or a resource the `resourceClients` resolver serves. An off-surface ref throws the new `RefResourceUndeclaredError` and the commit aborts, instead of writing cleanly and failing later when something dereferences it. The check is advisory like every engine check; stored documents are unchanged.
  - Definition-authored refs are exempt: literal `initialValue` seeds, `type: 'query'` texts, spawn `with` projections, and op values that bind no action param were validated (and alias-expanded) at deploy, so they materialize into field state without re-checking.
  - Resource aliases stay a deploy-time abstraction: `deployDefinitions({definitions, resourceAliases?})` expands every `@<alias>:` reference to its physical GDR before fingerprinting, and nothing alias-shaped survives past deploy — the runtime holds no alias map, and an alias-shaped ref supplied to a runtime verb is rejected as malformed like any other non-GDR string.
  - `createBench` takes `serveResources` (dataset siblings served — and thereby declared — straight from the bench's own store) plus a raw `resourceClients` resolver for anything beyond same-store siblings. The engine also exports `sameResource` alongside the existing GDR helpers.
  - The CLI wires no `resourceClients`, so refs supplied at runtime through it (`start --field`, `fire-action` ref params) admit the workflow resource only.

- 5a1a9fe: **BREAKING:** engine reads of persisted documents now parse instead of cast — a malformed `sanity.workflow.instance` or guard document fails the read with a `PersistedDocShapeError` naming the document and the offending fields, where it previously flowed through typed casts and corrupted behavior downstream. Reads that silently tolerated corruption now fail hard: `children` throws on a malformed spawn ref in history (previously skipped the row), and the reactive session rejects malformed self-doc pushes and guard updates with the typed error.

  Runtime valibot schemas are the single source of truth for each persisted doc shape: `WorkflowInstanceSchema` and `MutationGuardDocSchema` (the definition already had one), pinned field-by-field to the hand-written types so drift is a compile error. The parses are tolerant of unknown keys at every level (the data-model round-trip rule) and of unknown future `history[]` variants, and exact on everything the engine interprets. New exports: `parseInstanceDocument`, `parseGuardDocument`, `readInstanceDoc` (model gate + parse composed), `PersistedDocShapeError`, the two schemas, and `schemaTreeShape` (the declared field tree of a schema — what the model-surface ledger now pins for the instance and guard doc types).

- e3a7ba2: **BREAKING:** a supplied `instanceId` is now `startInstance`'s idempotency key. When the id already exists under the engine's tag for the same start, the call RESUMES the outstanding prime/cascade commits — the retry path for a start that failed after its create landed — instead of failing on the `_id` collision. Reusing an id for a different start (definition or explicit version mismatch), or for an unfinished start that was aborted, throws `ContractViolationError`. The mid-sequence failures are typed and carry the retry id: a prime failure after the create committed throws the new `StartNotPrimedError` (a failed but resumable start — the message names the id to retry with), and a first-cascade failure after a successful prime throws the new `StartNotSettledError` (carrying the primed instance when re-readable) — the run exists by then and must not be reported as a failed start; `WorkflowStateDivergedError` still passes through unwrapped. For standalone (`startInstance`) starts the `Editorial Workflows Instance Started` telemetry event fires once the instance is primed (started = created + primed) rather than after the first cascade settles; spawned children keep emitting after they fully settle. New exports: `isUnprimed` (classifies a created-but-unprimed instance — an unfinished, resumable start) and `instanceDocId` (mint an id to hold across start attempts).
- 30fed9e: **BREAKING:** deploy now rejects a set of authoring shapes that previously deployed clean and failed silently at runtime. Already-deployed definitions keep running — the rejections fire on `defineWorkflow` and (re)deploy only:
  - A `$row` read at any condition site that doesn't bind it (only a spawn `with` projection and a where-op `where` do) is rejected — a bare `$row` in a transition `when`, activity `filter`, predicate, effect binding, `spawn.forEach`, or `spawn.context` evaluated as GROQ null and could wedge transition selection.
  - `spawn.forEach` is deploy-checked against the workflow-scope `$fields` window it actually evaluates with — a forEach reading a stage/activity field previously passed deploy and resolved null at spawn time, spawning nothing.
  - The workflow `name` and every guard `name` must match the lake-id-segment grammar (`^[a-z0-9][a-z0-9-]*$`) — both interpolate into deployed document ids. Previously-deployable uppercase, underscore, and dotted names are now rejected: a dot collides with the id's own `.` separator, and looser spellings failed the whole deploy batch (or, for guards, the stage-entry commit) with an opaque lake 400.
  - Static `$fields.<name>.<path>` reads inside condition, forEach, and `start.allowed` GROQ are checked against the entry's declared value shape, the reference envelopes included — a `release.ref` read of `._id` (the envelope key is `id`) silently inverted a fan-out match. Reads resolve to the innermost shadowing entry; windows spanning several possible contexts reject a pathed read only when it fits none of the same-named declarations, so a shape valid in any possible context is never a false rejection. In `start.allowed`, references bind as their raw envelopes — a singular `doc.ref` included, since nothing hydrates at the gate or the pre-flight — so content-field reads are rejected there.

  The `content-release` example's spawn `forEach` now matches on the release envelope's `id` key (it read `._id`, which is not an envelope key, so reviews spawned for articles NOT in the release), and the guard `predicate` TSDoc spells out the polarity: strictly-`true` ALLOWS, anything else DENIES.

- 1321ba5: **BREAKING:** `start.filter` splits into visibility + permission. `filter` is now browse-time-pure — candidate document as root, `$tag`/`$definition`/`$now`, dataset scans — and any `$fields` read in it is deploy-rejected (inputs don't exist at browse time; the unbound-`$fields` evaluation let permission-style filters pass vacuously). The new `start.allowed` is the permission predicate — same context vars plus `$fields` (the caller's `initialFields` as GDR envelopes), never a candidate root — and `startInstance` enforces it: declaring the expression is the opt-in, a false or GROQ-null verdict throws the new `StartNotAllowedError` (kind `start-not-allowed`, `ConditionInsight` attached), no override arg. New reads: the `evaluateStart` verb pre-flights the gates (`StartEvaluation`: `allowed`/`outcome`/`insight`/`unboundReads`/`missingRequired`) — bindability-aware: a predicate reading a not-yet-supplied entry reports `'unevaluable'` with the entries named in `unboundReads`, never the collapsed verdict GROQ equality gives on a missing operand (at the gate absence is final, so `startInstance` evaluates it as-is). `explainStartAllowed` + `startFieldsParam` + `unboundAllowedReads` are the underlying primitives. API renames: `StartFilterScope` is now `StartScope` and no longer carries `fields` (the `$fields` map is `explainStartAllowed`'s own argument); `START_ALLOWED_VARS` joins the condition-scope inventory. For definitions already deployed with a `$fields`-reading `filter`, the read is GROQ null on every surface (nothing binds `$fields` there anymore) and the rule is inert — whether the filter then hides the definition (`defined()`-style reads fail closed) or surfaces it vacuously (`count(...) == 0`-style rules match nothing) depends on its shape; redeploy rejects it until the expression moves to `allowed`.

### Patch Changes

- d0c62ea: A store echo buffered during a session commit that fails read validation no longer throws from the commit's settle path — which could replace a successful commit's result (or shadow its real error). The failure is deferred to the next `update` call, the seam consumers already treat as the validation surface, after that call's own docs are processed.
- df4bd80: Docs: an unbound start-context binding or dangling `$fields` condition read evaluates to GROQ null per read — whether the expression then fails closed or passes vacuously depends on where the null lands, so blanket "fails closed" / "silently never passes" claims are corrected to the per-shape truth across the start-context TSDoc, the deploy-rejection messages (now "silently misevaluates"), and the reference doc. The condition-evaluation module header in `groq-condition-describe` states the same per-read truth ("'unevaluable' only where the null lands as the final result"). A test now pins the genuinely-null-result unevaluable case (an ordered comparison against a missing attribute — total `==` equality can only produce a definite false). No evaluation behavior change.
- e683875: The evaluation projection derives every condition scope from the same rendered-scope assembly the engine's commit paths use (`renderConditionScope` in the pure core), so projection/commit parity holds by construction. Previously the projection bound workflow-scope `$fields` only, while the cascade merged the open stage's field overlay — a transition trigger routing on a stage-scope field (the idiomatic "route on state an action wrote") routed in the cascade but misreported `whenSatisfied`/`unevaluable` in `evaluate`, and the author's predicates pre-evaluated over the narrower scope. Activity `filter` insights and cascade-fired action gates are now also explained caller-free in their activity context — the scope stage entry actually binds — and `queryInScope` binds that same caller-free scope (the open stage's overlay plus the pre-evaluated `$<predicate>` booleans).
- a8ace4d: TSDoc: `WorkflowTransaction.delete` now names both of its consumers — engine-side `deleteDefinition` housekeeping, and the CLI's `nuke` reset outside the engine — instead of claiming `deleteDefinition` is the sole one.
- Updated dependencies [f9389e5]
- Updated dependencies [df4bd80]
  - @sanity/groq-condition-describe@0.3.0

## 0.16.0

### Minor Changes

- 11e2d6f: Export `DEFAULT_TRANSITION_WHEN` — the trigger a transition desugars to when the author declares none — so consumers describing transition triggers can recognize the default's spelling instead of copying the literal.
- 7510fd5: Delivery-surface helpers and an honest remediation contract. The start-surface boundary is now engine-owned and shared: `buildInitialFields` (typing caller-supplied start values against a workflow's declared field entries) and `startRefusal` (the spawn-only refusal message), both previously private to the CLI. Also exported: `documentPrefilter` and `inFlightFilter` (the instance-list document and in-flight arms, for list builders that compose their own conditions) and `parseDefinitionInput` (the deploy boundary's envelope-strip + stored-form parse). The `drain-effects` remediation verb is now flagged `available: true` — the engine's `drainEffects` verb ships, so a hung-effect diagnosis names a fix the consumer can actually run instead of describing it as not yet callable.
- 79c54db: Reactive session reads now match the engine's own reads.
  - The session feeder projects every observed doc onto its watch ref's identity the way the lake's perspective reads do: the published-form id becomes `_id` (Studio/SDK stores resolve drafts and release versions under `drafts.*`/`versions.*` ids, which keyed the session's overlay and snapshot where no transition `when` condition or `$fields.<docref>` deref ever looks — an editor's uncommitted draft could not satisfy a condition the engine's `tick()` would read as satisfied), and a draft/version's stored id rides along as `_originalId`, so conditions like `_originalId in path("versions.**")` read what the engine's own hydration returns. The projection is an engine export (`projectToWatchRef`), one encoding beside `contentDraftFallback`/`contentDocQuery`, and it is strict: only the exact representations a store may legitimately resolve under the instance's perspective are accepted — anything else (another doc's dotted id under a version prefix, a version from an unbound release, a draft the perspective makes invisible) fails loudly instead of being fed under the watched identity.
  - Watches whose perspective makes drafts invisible to the engine no longer fall back to the draft. The engine hydrates a `[release]` stack as version-over-published (and `'published'`/`'raw'` scalars as published/raw) with drafts invisible; the Studio adapter resolved `version ?? draft ?? published` and the SDK's per-doc store has the same fallback built in. The Studio adapter now skips the draft arm unless the effective perspective names `'drafts'`, and the SDK adapter observes such refs through the query store under the instance's exact perspective stack. The SDK's query-store route reads committed state (live), so local uncommitted edits to a release version doc no longer feed the session there — Studio keeps its optimistic `editState` reads. New engine helpers `contentDraftFallback` and `contentDocQuery` are the single encoding of the rule, shared with the engine's own hydration.
  - `useWorkflowSession` resets its surfaced `evaluation` to `undefined` on an `instanceId` swap, as the contract promises, instead of leaving the previous instance's projection visible until the new instance first evaluates.

- 6a46db1: **BREAKING:** the definition root's `applicableWhen` moved to `start.filter`, inside a new `start` block — `{kind?: 'interactive' | 'autonomous', filter?: GROQ}` — describing how standalone runs begin. No alias, no dual-read: definitions authored with `applicableWhen` fail the strict parse until rewritten.
  - `start.kind` classifies who initiates a run — a person from a start surface (`'interactive'`, the default; `startKindOf(def)` is the one reading rule) or a system reacting to a document (`'autonomous'`, hidden from human start pickers). Classification only: `startInstance` stays one verb and one code path for every caller and kind — an interactive start of an autonomous workflow is legal. Deploy invariants: a spawn-only (`lifecycle: 'child'`) definition may not declare `start`; an `'autonomous'` kind requires every required input entry to be subject-style (`doc.ref`/`doc.refs` — the shared `isSubjectEntry` rule); a `start.filter` may read only declared **input-sourced** entries via `$fields` (a typo or a query/literal entry is a silent never-pass); and a root-reading filter (`_type == …`, `@`, or a `^` escaping a scan) requires a subject entry, since a read surface with no subject never binds a root.
  - `start.filter` is a **read-side visibility rule, not a gate** — `startInstance` never evaluates it and never throws on it; it starts whenever the caller supplies the required inputs. The filter decides what appears in / is chosen from Start lists: `definitionsForDocument`/applicability and the Studio start control evaluate it in a widened, named start-filter context (`START_FILTER_VARS`) — the candidate document as root, `$tag`/`$definition`/`$now`/`$fields` bound (`$fields` = the caller's input entries as GDR envelopes, so `$fields.<entry>.id` is the GDR URI), and `*[...]` = the workflow resource's dataset. Filters that never scan keep the cheap pure evaluation (`analyzeCondition(...).readsDataset` decides); scanning filters evaluate over a fetched slice of EVERY instance in the tag (completed included — `*` carries no hidden predicate; filters qualify in-flight themselves with `!defined(completedAt)`), so a filter can bound what surfaces (WIP limits, one-run-per-subject). Absent bindings evaluate GROQ-null and fail closed.

- 35b9b85: Commit/recovery hardening and a locale-independent content fingerprint:
  - `completeEffect` now commits under the engine's shared optimistic-locking retry, like every other claim-protocol write: a lost revision race reloads and re-commits the same reported outcome instead of escaping as a raw 409 — which discarded the handler's outputs and re-dispatched the effect after lease expiry, running the external side effect twice. Exhausting every attempt throws the new `ConcurrentCompleteEffectError` (kind `concurrent-complete-effect`).
  - A retried `abortInstance` of an already-terminal instance now propagates to ancestors unconditionally, matching the condemned-children drain: a crash between the terminal commit and the ancestor walk no longer wedges the parent's subworkflow gate on a child that already died.
  - `hashDefinitionContent` and the model-shape canonicaliser sort object keys by UTF-16 code unit instead of the locale-dependent `localeCompare`, so identical definitions fingerprint identically on every machine. A definition whose key ordering differed under the deploying machine's locale hashes differently once — the next redeploy of such content mints one new version instead of reading as unchanged.

- e5f5b77: **BREAKING:** actions become the only payload mechanism — every op, effect, and spawn in the system lives on an action; structure never does.
  - Actions gain `when` (cascade-fired trigger: the engine fires it the moment it's true, at most once per stage visit, level-triggered; never fireAction-able) and `spawn` (the subworkflow block, unlocking caller-triggered and conditional spawn). Fires-on-entry is spelled `when: 'true'`.
  - Deleted from the model: `activation`, activity-level `ops`/`effects`/`subworkflows`, `completeWhen`/`failWhen`, `kind`, and transition `ops`/`effects`. Transitions are pure edges `{name, when, to}` (the condition key renamed from `filter` — trigger semantics). `target` survives as the off-system marker; `kind` is now always derived, plus a new derived executor classification (autonomous / interactive / off-system / hybrid) on activity evaluations.
  - Activities are `active` from stage entry (no `pending` status, no activation moment, no machine-step implicit); a new deploy invariant requires every activity to have a reachable path to a terminal status.
  - A cascade hop is ONE transaction: the current stage's triggered actions run to in-memory fixpoint, then transition selection, then a single CAS commit; chain hops stay separate commits. The per-visit `firedActions` ledger on the activity entry re-arms on re-entry (a stage resets on re-entry). The cascading token executes triggered actions; `roles` on a triggered action pins which identities may execute it (an incapable token leaves it armed).
  - The context bag split: `$effects` now carries completed effects' outputs ONLY (derived from `effectHistory`), and the new `$context` carries the `startInstance` seed plus a parent's `spawn.context` handoff (the persisted `effectsContext` field renamed `context`; `startInstance`'s seed arg renamed accordingly). `$effectStatus` is unchanged.
  - Spawn registry rows key per (activity entry, spawning action), so two spawn actions on one activity can never cross-adopt each other's children.
  - `fireAction` rejects a `when` action (`cascade-fired` verdict); evaluation projects triggered actions as narratable (`triggered: true` + `whenInsight`), never as buttons.

### Patch Changes

- 01e8042: Fix `fieldRead` values landing in `doc.ref`-kinded slots: a bare (no-path) read of a `doc.ref` source now preserves the stored reference instead of handing over the dereferenced document wherever the result feeds a `doc.ref`-kinded slot — a `doc.ref` entry's `initialValue` seed (the mirror pattern no longer fails `startInstance` with `FieldValueShapeError`), a `field.set` op targeting a `doc.ref` entry, a `field.append` op item landing in a `doc.refs` entry, and `doc.ref` sub-fields reached through an object-expression op value (`field.set` object entries, `field.append` rows, `field.updateWhere` merges — sub-values resolve against the entry's declared sub-field shapes). Identity preservation applies only to bare reads into `doc.ref`-kinded slots; every other surface (conditions, effect bindings, guard metadata, path-carrying reads, undeclared object-expression keys) keeps the doc-centric dereference.
- 01e8042: Close the unvalidated `field.updateWhere` write path. The merged rows now pass the same shape gate as `field.set` / `field.append` — a wrong-kinded merge value for a declared row sub-field throws `FieldValueShapeError` and aborts the commit instead of persisting silently. An `updateWhere` may only target an `array` entry (the one kind whose rows carry declared sub-fields): a definition-carried op against any other kind is rejected at define/deploy time, and the op applier enforces the same gate for the boundaries deploy never sees (effect-completion ops, definition/instance divergence) — previously a merge into a `doc.refs` entry spread the merge value's fields (for a bare `fieldRead` of a `doc.ref`, the whole dereferenced document) into the stored GDR rows with no error. A merge may also never write the reserved row keys `_key` / `_type` — row identity and bookkeeping are engine-stamped, and a merge would restamp every matched row with the same literal; statically-named keys are rejected at define/deploy, and the applier re-checks the resolved merge. `field.removeWhere` is unchanged and keeps accepting every array-valued kind, `doc.refs` included — dropping rows needs no row shape.
- Updated dependencies [7510fd5]
  - @sanity/groq-condition-describe@0.2.0

## 0.15.0

### Minor Changes

- 4ca17bb: **BREAKING:** Deploy validation now rejects caller-bound vars (`$actor`, `$assigned`, `$params`) in the cascade's caller-free gates — transition filters and activity `filter`/`completeWhen`/`failWhen` — exactly as `$can` already was. The cascade never binds a caller at those sites, so such a gate either routed wrong (a comparison against the unbound var fails closed and a later catch-all fires) or wedged the instance (a raw caller read is unevaluable, which halts transition selection), while the caller-bound evaluation projection reported the same gate satisfied.

  The evaluation projection now also evaluates transition filters caller-free, so `filterSatisfied`/`unevaluable` report the route the cascade will actually take — including for definitions deployed before this validation existed.

  Variable-read detection in these checks (and the predicate-body checks) is now AST-exact via groq-js instead of a regex scan, so a `$actor` inside a GROQ string literal no longer counts as a read.

  `validateDefinition` now re-runs the cross-field invariants (`checkWorkflowInvariants`), so `deployDefinitions`, the CLI, and the MCP validate tool reject a stored-shape definition that never went through `defineWorkflow` — deploy enforces exactly what authoring enforces.

- 5143707: **BREAKING:** An abort now records the pending effects it cancels with a real `cancelled` status instead of `failed` — a cancellation is a discarded run, not a failure, so failure counters (dashboards, alerting, retry tooling) no longer see aborted-away effects. The effect-run vocabulary is exported as `EffectRunStatus` (`'done' | 'failed' | 'cancelled'`) and now types `EffectHistoryEntry.status`, the `effectCompleted` history entry, and the `$effectStatus` projection; exhaustive switches over the old two-value union must add the `cancelled` arm. Completion reporting is unchanged in type — `completeEffect` accepts only the new `EffectCompletionStatus` (`'done' | 'failed'`) — and now also refuses anything else at runtime with `ContractViolationError`, so a plain-JS completer cannot forge a cancellation.

  An abort also writes one `effectCompleted` settle event per cancelled effect (paired with the `effectHistory` row by `effectKey`, built by the same constructor as a reported completion's), so the event trail accounts for every queued effect the same way reported completions do.

  `EffectNotFoundError` now carries an optional `settled: {status, ranAt, detail?}` (exported as `EffectSettledInfo`) when the missing key matches an `effectHistory` row, with the message saying how the entry settled — so a completer can tell a double delivery (`done`/`failed`: treat as already-done) from an abort's cancellation (`cancelled`: the reported work was discarded) instead of guessing from a bare not-found. `drainEffects` uses it too: its `lost`-bucket warning now says "cancelled by an abort during dispatch" when that's what happened, instead of guessing "completed by another party".

- 0709ab1: **BREAKING:** `DisabledReason` and `EditDisabledReason` gain an `{kind: 'instance-aborted', abortedAt}` arm — aborted instances now report it instead of `instance-completed` on action verdicts, edit-denial reasons, and the thrown `ActionDisabledError`/`EditFieldDeniedError` (whose detail reads "instance aborted at …"). An exhaustive `switch` over either union needs a new case.

  Promote three canonical helpers to the public surface so consumers stop re-deriving them:
  - `errorMessage(err)` — the one "human-readable message for a caught `unknown`" helper. It now also strips control characters (keeping newlines and tabs) so server-derived error text can't smuggle terminal escape sequences into consumer output; every engine message built through it (including `rethrowWithContext`) gets the same treatment.
  - `terminalState(instance)` (+ the `TerminalState` type) — classifies an instance as `'aborted' | 'completed' | 'in-flight'`, owning the "aborted instances carry `completedAt` too, so `abortedAt` wins" precedence. `diagnoseInstance`, action-verdict lifecycle gating, and the field-editability window/denial checks all derive their terminal branches from it.
  - `parseDefinitionSnapshot(instance)` — the one way to read an instance's frozen definition snapshot, failing with the instance id attached instead of a bare `SyntaxError`.

- 6bbf3ca: **BREAKING:** effect delivery reliability — claim leases with a stale-claim sweeper, and caller-supplied idempotency keys that are actually honored.

  Claim leases (`drainEffects` / `sweepStaleClaims`):
  - Every claim `drainEffects` stamps now carries `leaseExpiresAt` (engine-configurable via `createEngine({effectLeaseMs})`, default 5 minutes). A claim whose lease lapsed no longer protects its entry — the claimer is presumed dead, so a drainer dying between claim and complete no longer wedges the entry forever (previously the only recovery was aborting the whole instance). A claim persisted before leases existed counts as already expired, keeping exactly those stuck entries recoverable. There is deliberately no attempt counter on the claim: the retry count is the `effectClaimReleased` history rows for the entry's `_key` (plus the live claim), and a stored field would drift from that trail.
  - `drainEffects` takes expired claims over in the same CAS write that stamps its own claim, recording an `effectClaimReleased` history row (new `HistoryEntry` variant) with the abandoned claim embedded for audit. The `ifRevisionId` guard is the sweeper election — concurrent recoverers race safely.
  - New standalone `sweepStaleClaims({client, tag, instanceId})` export: force-release expired claims WITHOUT dispatching, for ops/admin housekeeping. Deliberately not an `Engine` verb (same category as the guard-lifecycle helpers) — a drain already self-recovers via takeover. Returns the released entries; the next drain redispatches them.
  - `DrainEffectsResult` gains a required `lost` bucket: entries this drainer dispatched whose completion lost to another party (e.g. a takeover finishing first). Previously that race crashed the drain with `EffectNotFoundError` mid-loop.
  - `EffectHandler`'s TSDoc now states the delivery contract explicitly: **at-least-once — a handler MAY double-run** (crash between dispatch and completion, or a slow dispatch outliving its lease). Check `effectHistory[]` for the run's `ctx.effectKey` before irreversible work, and derive external-system identifiers from `ctx.effectKey` so the receiving system can dedupe.
  - `drainEffects`/`sweepStaleClaims` read the engine clock for claim/lease stamps, so lease timing is deterministic under `createEngine({clock})` (previously drain stamped wall-clock unconditionally).

  Caller idempotency keys (previously a declared-but-dead arg):
  - The commit-owning verbs — `fireAction`, `editField`, `completeEffect`, `setStage`, `abortInstance` — now honor `idempotencyKey`. The first commit records the key on a new `processedRequests[]` instance ledger **in the same CAS write as the operation**, and a blind retry replays instead of double-applying (or, for a completed effect, throwing `EffectNotFoundError`): the op is not re-applied, but the cascade still runs to convergence — repairing the exact crash window a keyed retry exists for (died between the original's commit and its cascade) — so `changed` is `false` unless that cascade moved the instance. The check runs before the verbs' soft gates, so a replay can't die on a gate its own original commit closed (a resolved activity, a moved stage).
  - Ledger rows expire after `idempotencyTtlMs` (engine-scope config, default 24h) and are pruned lazily by later keyed commits; instances whose callers pass no keys never grow the ledger. Reusing a live key on a different verb throws `ContractViolationError`.
  - The moved arg is the breaking part: `idempotencyKey` now lives on `DedupableOperationArgs` (which the five verbs' args extend) instead of `OperationArgs`, so `tick` — which owns no commit and is naturally idempotent — no longer accepts the previously-ignored field.

- 9f5a40f: **BREAKING:** foreign-GDR reads no longer silently query the workflow resource. With no `resourceClients` (or on a resolver miss), the engine now derives a sibling client for the target resource from the workflow client's own credentials; a client that cannot derive siblings (no `withConfig`) makes a foreign GDR throw `ContractViolationError` instead of reading the wrong place. Consumers that relied on the old silent fallback — foreign GDRs quietly reading the workflow resource — see different reads (the correct resource) or a loud error.

  `WorkflowClient` gains an optional `withConfig` seam member (satisfied by both `@sanity/client` and the in-memory test fake — the fake derives dataset siblings only until it learns `resource` upstream); the shared router resolves in order: the `resourceClients` override, the engine's own client for the workflow resource itself, then a derived sibling (cached per operation). Engine-internal verbs now require the router (`EngineCallOptions.clientForGdr`) rather than rebuilding or defaulting one. With an org-capable token, cross-resource workflows route correctly with zero wiring.

- d192d68: Definitions can now declare which documents they're for, and consumers can discover the right workflow to surface or start — no more hand-maintained per-consumer mapping tables.
  - `types?: string[]` on `doc.ref` / `doc.refs` field entries — the engine's `reference.to`. Absent accepts any type; declaring it on any other kind is a define-time error, as is an empty list or a literal seed whose GDR `type` isn't listed.
  - Optional definition-level `applicableWhen` — GROQ evaluated against a candidate document (the doc is the root; no `$` vars are bound, no lake) for value-level routing like `"_type == 'article' && articleType == 'finance'"`. Deploy validation rejects a parse error, any `$var` read, and any `*` dataset scan — each would make the predicate silently wrong at runtime.
  - Discovery is a pure derivation over deployed definitions: startable ∧ a required subject entry accepts the doc's `_type` ∧ `applicableWhen` passes (a GROQ-null result fails closed; a malformed predicate fails LOUD, naming its definition). Exposed as `applicableDefinitions` / `isDefinitionApplicable` / `acceptsDocumentType`, and as the `definitionsForDocument` verb (namespace + `Engine`) — the startable half of `instancesForDocument`. It takes the LOADED candidate document, considers only the latest deployed version per name, and surfaces ALL matches with no engine ranking. Advisory like every engine-side check.
  - Every hard write door honours `types`: `startInstance` initialFields, the spawn `with` handoff, and `editField` / `field.set` / `field.append` ops (resolved ref entries persist their declared `types`, like `object`/`array` persist `fields`/`of`, so instances stay self-describing). A violation fails hard — API-contract validation, the same tier as a missing required field. The spawn error names the projection footgun when (and only when) it applies: a projected bare id / `_ref` canonicalises with the generic type `"document"`, so a typed child entry needs `{"id": _id, "type": _type}` projected. A query-sourced entry's mismatching lake result is discarded with an audit row, like every other query-shape mismatch.
  - Bench: `definitionsForDocument(document)` read helper.

- 109f900: Effects can now declare the outputs they produce, as typed `FieldShape[]` on the effect declaration (each `name` is an output key, read downstream as `$effects['<name>'].<key>`).

  `outputs` is a **strict allowlist enforced at completion**: `completeEffect` validates the handler's returned outputs against the declared shapes and rejects an undeclared key — or a value that doesn't fit its shape — with `EffectOutputsInvalidError`; the completion does not commit, so off-contract data never reaches the instance. Outputs may not accompany a `failed` completion either (they would otherwise bypass the allowlist yet still land on the history rows) — mirroring the existing ops-on-failure rejection. The bound is universal, not opt-in: omitting `outputs` is an **empty allowlist** — the effect produces nothing, and any returned output is rejected. (An effect that returns outputs must declare them; the effects-context _seed_ on `startInstance` stays unrestricted, since it isn't a handler return.)

  Strict because `effectsContext` lives on the instance document: the allowlist keeps it bounded — a handler can't accidentally spread a whole API response into the instance — and the declared shapes let tooling (e.g. the simulator's drain UI) suggest an effect's exact output keys.

  Deploy additionally runs an **advisory** producer/consumer lint (`lintEffectOutputs`, exported for tooling) over `$effects['<name>'].<key>` reads in conditions, effect bindings, and guard reads, returning a warning for a read of a key a declared effect does not produce — surfaced on `DeployDefinitionResult.warnings`, the engine logger, and the deploy CLI. Advisory only (deploy still succeeds): a read of a name that is not a declared effect is left alone, because a `startInstance` seed or a `subworkflows.context` handoff can produce it at runtime.

- 109f900: Effect outputs and the start-time effects context now carry arbitrary JSON, not just scalars and GDRs. `completeEffect`'s `outputs`, the `EffectHandler` return `outputs`, and `startInstance`'s `effectsContext` seed are widened to `Record<string, unknown>`, so an effect can report an object/array result and a run can be seeded with structured context — read back the same under `$effects.<name>`. Scalars and GDRs still store as their typed `effectsContext` entries; any other JSON stores as one `effectsContext.json` entry, so there is no stored-shape change and no migration.

  The `subworkflows.context` parent→child handoff now fails loud when a value resolves to neither a scalar nor a GDR, instead of silently dropping it into an absent handoff.

- 444b0e6: **BREAKING:** Deploy validation now rejects `$params` in the caller-bound condition sites — action filters, `requirements.*`, and `editable` predicates. Those sites bind `$actor`/`$assigned`/`$can` but never `$params`: an action's args exist only once the caller fires it, after its filter has already decided whether the action is enabled. A filter like `$params.urgent` deployed fine yet was a permanently unevaluable gate — the action could never enable, reporting only a bare `filter-failed` with no hint why. `$params` stays bound where it always was: an action's effect bindings and where-op `where`s.
- 2511bb5: **BREAKING:** `CompiledQuery.params` widens from `Record<string, string>` to `Record<string, string | string[]>` — custom observer/client implementations typed to the old shape must widen their param handling.

  Export the canonical helpers consumers were re-deriving, and widen the instance-list prefilter to many documents:
  - `instancesQuery` accepts `filter.documents` — a multi-document prefilter sharing one spelling with the single-document arm — and `filter.ids` — explicitly requested instance ids OR-ed into the match. A DEFINED-but-empty `documents` / `ids` array matches nothing (the GROQ-natural reading); omit a field for no constraint. Entries in `filter.ids` must be bare instance ids — a GDR URI is rejected, mirroring the documents arm
  - new root exports: `isTerminalActivityStatus`, `definitionLookupGroq`, `definitionsListGroq`, `latestDeployedDefinitions` (the head-per-name reduction `definitionsForDocument` applies), `parentRef`, `releaseRef`, `releaseDocId`, `isTodoListEntry`, `isTodoListItem`, `documentActionDenials`, `deniedGuardRefs` (the structured denial payload `deniedGuardLabels` phrases), `missingRequiredInputs` (the required-input predicate behind `RequiredFieldNotProvidedError`), `rejectedRefTypes` (the `doc.ref`/`doc.refs` `types`-facet check), plus the `EffectsContext`, `TodoListItem`, and `DocumentActionDenialsArgs` types
  - `TodoListItem.status` is optional per row — the `todoList` sugar guarantees the columns in the schema, not values per row, and field validation makes every declared column optional — so `isTodoListItem` accepts status-less rows and rejects a non-string status
  - `releaseRef` is the one constructor for the `release.ref` value envelope (`releaseDocId` owns the release system-doc id spelling), and field validation now cross-checks that a stored release ref's `id` names the release in `releaseName`
  - `documentActionDenials` is the prospective guard verdict for document actions (disable-this-button pre-flights); `instanceWriteDenials` rides it

- d4fd8e6: `definitionDeployedData` — the structural derivation behind `Editorial Workflows Definition Deployed` — is exported, so shells can project other events from the same counting code path instead of re-deriving (and drifting from) the counts.
- 30ed0e8: The notes vocabulary joins the todoList helpers on the root surface: `isNotesEntry` recognises a notes-shaped `array` entry (the sugar's `{body, actor, at}` row shape) on both a resolved instance entry and a deployed definition entry, and `NoteItem` types one persisted notes row. `isTodoListEntry` accepts the same two vocabularies (it previously took only a resolved entry), so start-time and runtime surfaces route array entries with one verdict. `resolveFieldEntry` is exported as the one owner of field-site scope resolution — the resolved entry behind a workflow/stage/activity field site, read against the open stage (the same resolution `readFieldValue` and the op path already use) — so consumers stop re-implementing it.
- 2834704: **BREAKING:** the engine owns `ENGINE_API_VERSION` for all engine traffic. Every entry point — `createEngine`, each raw `workflow.*` verb, and the housekeeping exports — derives its working client with `withConfig({apiVersion: ENGINE_API_VERSION})` (memoized per client, so identity-keyed actor/grants caches stay stable), and `resourceClients`-resolved clients are rebound the same way. A caller's configured `apiVersion` never reaches engine reads or writes; before, the pin was a documentation convention, and an older dated version evaluated the engine's GROQ silently incomplete, not loud. The caller's own client instance is untouched — `withConfig` returns a sibling — so any `apiVersion` satisfies `@sanity/client` at construction. The breaking part is the `WorkflowClient.withConfig` contract: its config is now the all-optional exported `WorkflowClientConfig` (`resource` optional, new `apiVersion`), so a custom implementation must accept a version-only rebind — and the one client the engine cannot rebind, a custom `WorkflowClient` without `withConfig`, must be built to serve `ENGINE_API_VERSION` already.
- 2511bb5: Export `findOpenStageEntry` and `findCurrentActivityEntry` from the package root — the open-stage-entry and current-activity-entry lookups over a stored instance's `stages`/`currentStage`, for consumers that read instance state without re-implementing the loop-back semantics.
- 2511bb5: Export `toBareId` from the package root — the canonical lenient GDR-URI → bare document id transform (a non-GDR string passes through unchanged), for consumers that join stored refs against lake `_id`s.
- 2511bb5: Export `tryParseGdr` from the package root — the "is this a GDR, and if so its parts" primitive (returns `undefined` instead of throwing on non-GDR input), for boundaries that classify stored refs without trusting their shape.
- 4607d59: **BREAKING:** A singular `doc.ref` field read is now doc-centric on every surface. `$fields.<doc.ref>` dereferences into its referenced document — read content by name (`$fields.subject.amount`) and identity via the reserved `_id`/`_type` (`$fields.subject._id`) — in conditions, effect bindings, guard `metadata`, op payloads (`ValueExpr`), and a field's `initialValue` (`fieldRead` `FieldSource`) alike, all through one shared resolver. This closes the gap where guard metadata, ops, and `initialValue` reads silently walked the stored `{id, type}` reference envelope instead of the document, and unifies the identity spelling: the reference's GDR URI is the document's `_id`, its `type` the document's `_type`, so a content field named `id`/`type` can never be shadowed.

  Migration: a guard/op/`initialValue` read that reached the reference's `.id`/`.type` must use `._id`/`._type` — identical values. Guard `idRefs` are unchanged (they route a guard write on the stored reference, never its content). `query` `FieldSource`s (arbitrary lake GROQ) are unchanged.

  Scope notes:
  - `doc.refs` (plural) is unchanged: it stays a collection of references (the array of GDR envelopes) for identity/iteration — e.g. a spawn `forEach`. To read a referenced document's content, model it as a singular `doc.ref`. An element's identity is therefore read off the envelope (`$fields.refs[i].id`/`.type`), NOT the doc-centric `._id`/`._type` — the singular-vs-plural spelling difference is deliberate.
  - An op that reads content through a `doc.ref` resolves at op-apply against the commit's snapshot and stamps the result into `opApplied.resolved` — a transactional content→state pin in the same commit, no effect round-trip. An unfilled or unresolvable reference resolves to `null`.
  - On the path-carrying surfaces (guard `metadata`, ops, `initialValue`), reading _through_ a nested, undeclared reference inside a loaded document (e.g. `subject.image.asset.url`) throws — the engine only loads references a workflow declares as `doc.ref`/`doc.refs` entries (best-effort: an unresolvable reference whose document isn't loaded resolves `null`). Conditions and effect bindings run on groq-js, which passes no path here and null-propagates through such a read instead of throwing.
  - A field's `initialValue` resolves at materialisation, before any snapshot exists, so only identity reads (`._id`/`._type`) resolve there; a content read falls back to the field default (consistent with an `initialValue`'s existing unresolvable-read behavior). Content reads through a ref belong in ops/guards/conditions, which resolve against the runtime snapshot.

- 52f6024: The GDR constructors (`refDataset`, `refCanvas`, `refMediaLibrary`, `refDashboard`, `gdrRef`) now preserve the `type` literal they were called with instead of widening it to `string`, so a constructed ref satisfies literal-typed targets — e.g. a `release.ref` field value (`type: 'system.release'`) can be built as a plain spread without re-asserting the literal. `GlobalDocumentReference` gains an optional `TType extends string = string` parameter; the default keeps every existing call site and type annotation compiling unchanged. Zero runtime change.
- adf32f7: **BREAKING:** identity is the token — actor injection is gone from every production path. `WorkflowAccessOverride` and the `access?` argument on every verb, `evaluate`, `drainEffects`, and `engine.session` are removed; `resolveAccess(client, {grantsFromPath?})` always resolves the actor from `/users/me` and grants from `grantsFromPath`. Acting as someone else means a client with their token. The engine's own system actors (`engine.drainEffects`, `engine.machineStep`, `engine.completeWhen`/`failWhen`) are gone too: auto-work (drain claims, gate flips, machine steps, cascade aborts) is attributed to the committing token's user, and `driverKind` no longer classifies any actor as `engine` (the stored legacy value remains readable). New: `createEngine({executionContext: {kind?, id?}})` declares the host once at construction; the engine infers the JavaScript runtime and stamps `executionContext: {runtime, kind?, id?}` on every history entry alongside the actor — advisory "via what" provenance (exported `EXECUTION_KINDS` carries the well-known vocabulary). A server proxy acting with a user's token now expresses itself as `{actor: <user>, executionContext: {kind: 'server', id: '<proxy>'}}` instead of forging an identity.
- 5cb0850: **BREAKING:** every evaluation node now carries derived evaluation state, so consumers constructing evaluation values by hand must supply the new members: `TransitionEvaluation.insight` is required, and `WorkflowEvaluation.fieldInsights` is required (hand-built diagnostics fixtures should use the new narrowed `DiagnosedTransition` instead of the full transition shape), and `ConditionVar` gains a required human `label`. Consumers that only read evaluations are unaffected — everything below is additive data.

  Derived evaluation state from the GROQ AST, riding every `evaluate`:
  - `TransitionEvaluation.insight`, `ActionEvaluation.insight`, `ActivityEvaluation.requirementInsights`/`filterInsight`/`completeWhenInsight`/`failWhenInsight`, `EditableFieldEvaluation.insight` — each gate's `ConditionInsight`: per-atom three-valued verdicts, the unmet frontier (`blockedBy`), single-fix pivotality, and solvable requirements (`equals`/`differs`/`defined`/`undefined`/`truthy`/`falsy`/`compares`). Verdict flags are projections of the insight outcome — one groq-js evaluation feeds both.
  - `WorkflowEvaluation.fieldInsights` — per-field involvement ("this field is read by transition X, requirement Y") plus counterfactually verified proposals ("setting `legalApproved` to `true` flips `to-publish` to satisfied"), computed from the same walk that produced the verdicts.
  - Atoms are opaque about their parse tree (`ConditionAtom.node: unknown`) — the groq-js AST shape is not part of the public contract.
  - The generic machinery (analysis, explanation, what-ifs, phrasing) now lives in the new `@sanity/groq-condition-describe` package; the engine re-exports it and registers its workflow dialect (field titles, condition-var labels, roles/claim desugar shapes, `$now`) through the describe seams. `explainCondition`/`whatIfCondition` take `dataset: unknown[]` (pass `snapshot.docs`).
  - Standalone primitives for tooling: `analyzeCondition` (scope reads + boolean clause tree in negation normal form), `explainCondition`, `whatIfCondition`/`withAssignment` (counterfactual re-evaluation with fabricated containers, sparse-index guarded), `formatRead`, and the `ConditionOutcome` type.
  - The static tier for whole-definition consumers (diagram explain props, docs, CLI): `conditionSitesOf(definition)` enumerates every condition site with addressable keys (the same `InsightSite` vocabulary evaluation insight emits, plus `predicate`), and `describeDefinition(definition)` phrases them all against an empty scope in one call — the site enumeration lives in ONE exported walker, consumed by the rendering corpus test too.
  - `describeSiteHeading(address, ctx)` — the connective mood for tooltips/panels ("«Approval» completes automatically when:" flowing into the checklist lines); `describeSite` stays noun-mood for mid-sentence composition. Accepts the definition-level address superset.
  - One front door for rendering: `describeNode(node, ctx)` accepts any insight-bearing evaluation node (transition, action, activity, editable field, field insight, or a bare condition insight) and returns the shape that node demands via a conditional type — a checklist description, an activity's four gates, or a field's involvement + proposals.
  - Deterministic human rendering (no LLM): `describeCondition`/`checklistLines` (checklist + frontier summary), `describeAtom`/`describeSite`/`describeFieldInsight`. Templates over requirements, the condition-var registry's new `label`s, the definition's own titles, and structural recognizers for the desugarer's canonical shapes (roles gate, claim no-steal) plus common patterns (deadline-vs-`$now`, literal membership, count thresholds). Every rendered phrase is an `InsightPhrase` — `{id, params, text}`: stable namespaced message id + interpolation params + the English default, so an i18n consumer (e.g. a Studio locale bundle) translates by id and ignores `text`. Anything unphrasable falls back to the atom's GROQ with a depends-on hint and marks the description `fullyDescribed: false`. The rendering corpus test over every example definition currently shows zero fallbacks.

  The verdict of record always rides the engine's own evaluation path; the clause-tree math used for frontier/pivotality mirrors GROQ's Kleene semantics and is pinned by tests. Everything is advisory, like every engine-side check. Measured cost of the added derivation: well under 1ms per evaluation on a realistic stage (in-memory groq-js, no I/O). Research notes: `docs/research/derived-evaluation-state.md`.

- 70a136c: Author-declared groups: a `groups: [{name, title?, description?, kind?}]` array on the workflow root, a stage, or an activity declares named groups, and field entries, activities, and actions join them via `group: string | string[]` (stored canonically as a list) — advisory "what belongs together" metadata the engine stores and deploy-checks but never acts on. Memberships resolve lexically up the enclosing chain; names are unique per level (the same name at different levels is intentional nesting, never merged by the engine). `kind` is a closed role vocabulary: `core` = include in condensed views first, `details` = disclose on demand; consumers reading a definition as data treat an unknown kind as unset. New surface: `defineGroup`, `groupSitesOf` (per-level declarations with lexically attributed members), `groupMembershipNames`, `GROUP_KINDS`, `GROUP_KIND_DISPLAY`, and the `Group` / `GroupMembership` / `DefinitionGroupSite` / `GroupMember` / `GroupKind` types.
- 91540de: **BREAKING:** telemetry vocabulary metrics pass — new events, payload enrichments, and commit-time emission threading. Every event name now carries the product name — `Editorial Workflows <X>` instead of `Workflow <X>` — because bare "Workflow(s)" is ambiguous with other initiatives.
  - New unsampled `Editorial Workflows Stage Transitioned` event: one event per committed stage move (cascade hops, propagation passes, and admin overrides included), carrying positional stage indexes, a terminal flag, a loop-back (`isRevisit`) flag, dwell time in the exited stage, and `via: 'transition' | 'setStage'`. Emitted from the commit path itself, so every hop counts exactly once regardless of which verb drove it.
  - `deployDefinitions` mints a random `deployId` per call, stamps it on every `Editorial Workflows Definition Deployed` event, and returns it on `DeployDefinitionsResult` so callers reporting on the same deploy carry the same grouping id.
  - `Editorial Workflows Definition Deployed` payload reshaped: adds `deployId`, distinct `fieldKinds`, `lifecycle`, and counts (`guardCount`, `effectCount`, `subworkflowCount`) replacing the `usesGuards`/`usesSpawn`/`usesEffects` booleans.
  - All instance-scoped events now carry `definitionContentHash` (per-definition slicing) and `instanceId` — the instance document `_id` — so per-instance journeys and distinct-instance funnels are answerable. Effect names and instance ids are the payload policy's two deliberate customer-string exceptions.
  - `Editorial Workflows Instance Started` adds `viaSpawn` and `lifecycle`; spawned children now emit it too (previously only direct starts did).
  - `Editorial Workflows Effect Completed` carries the effect's name and the queueing boundary (`origin: 'activity' | 'transition' | 'action'`), and widens `status` with `'cancelled'`; and the abort commit emits one cancellation per discarded pending effect — exact under races, cascade-driven child aborts (a parent abort, a delete-cascade) included. `CompleteEffectResult` gains `origin`.
  - `Editorial Workflows Effects Drained` carries the dispatched effects' names (`drainedEffects`). Effect names are one of the payload policy's two deliberate customer-string exceptions (with instance ids) — identifying which integration ran outweighs the string hygiene, and the names join donated definitions exactly. `DrainEffectsResult` carries the drained instance's `definitionContentHash`; drain-driven cascades now emit transition events (drained per-effect completions stay silent — successful dispatches ride the drain summary, counted once; drain-time failures emit nothing until the health-telemetry pass). The drain summary is now unsampled when non-empty — outcome counts must be complete — with empty polls throttled engine-side to one per minute.
  - New `processShellUserProperties` export: the execution-environment user-property set process shells attach to their stores.
  - `EditMode`, `EditFieldTarget`, and `DEFAULT_EDIT_MODE` moved to the pure editability core (public import paths unchanged).

- 8455fbb: Persisted data-model governance. The doc types whose format the engine owns outright (definition, instance) are now stamped with a pair — `modelVersion` (provenance: the `DATA_MODEL_VERSION` shape contract that wrote it, re-asserted on every full persist) and `minReaderModel` (compatibility: the oldest engine model that can safely interpret it, `DATA_MODEL_MIN_READER`) — orthogonal to definition-content versioning (`version` / `pinnedVersion` / `contentHash`). Engine reads gate on the reader floor, not the stamp: a document written by a newer model whose changes were additive keeps working on older engines (mixed-version fleets of Functions, Studios, and CLIs interoperate), and only a floor ahead of the engine fails hard with the new `ModelVersionAheadError`. A document without a stamp reads as model 0, and backward compatibility is unconditional. Old writers restamp down, preserve unknown fields (set-only patches, spread copies), and never lower a stored floor. The guard doc deliberately carries no stamp — its format is the Content Lake's forthcoming contract, versioned by the `temp.` prefix cutover itself. The model rules and history live in the package's `DATAMODEL.md` (shipped in the tarball), enforced by a shape-snapshot test; `DATA_MODEL_VERSION`, `DATA_MODEL_MIN_READER`, `modelVersionOf`, `minReaderModelOf`, and `assertReadableModel` are exported for consumers.
- 325c2d1: `InstanceSession` gains `previewField` / `discardFieldPreview` — staged optimistic previews of field edits. `evaluate()` now projects against the held instance with previews applied, so field values and the advisory verdicts derived from them (editability, action verdicts, transition satisfaction) move instantly, while everything the engine writes (stage, activity statuses, history) stays committed by construction: previews apply `field.*` ops only, through the same target resolution, op shape, and value validation as the committed edit path. `editField` stages its own preview on entry and drops the target's previews when the commit settles — success lands the reloaded value, failure reverts the projection. Previews are derived at evaluate time, so a newer held instance (commit reload or store echo) rebases them automatically.

  Previews are edit-window-aware: a target whose window is closed — a pending activity's field before activation, whose runtime entry doesn't exist yet — stages an INERT preview (no echo, no throw) and never reaches the op applier, so one such preview can't poison the projection. Stage- and activity-scope previews are additionally keyed to the stage VISIT they were staged in (the open stage-entry `_key`): a stage bounce delivered as a single `update` drops them deterministically instead of resurrecting a prior visit's values on re-entry, while workflow-scope previews — whose window is the whole in-flight instance — survive stage changes.

  Documents and pins the session commit verbs' existing revision-conflict contract: a lost `ifRevisionId` race on the action/edit commit retries through the engine's shared reload → re-gate → re-apply loop (capped), a re-gate that fails on the reloaded instance surfaces its structured gate error immediately (never a blind replay), and exhausting the cap throws `ConcurrentFireActionError` / `ConcurrentEditFieldError`. Only the instance reloads per attempt — the held content snapshot and staged previews are untouched across attempts.

- d6e92ed: Now published with public npm access (previously restricted) — installable without `@sanity` org membership.
- 7ffdc77: Resource-shaped GDRs (`<type>:<id>` with no document part, e.g. `dataset:abc123.production`, `media-library:mlXyz`) are now a first-class parse/validate shape: `parseResourceGdr(uri)` parses one into a `WorkflowResource` (throwing a clear grammar error on unknown types, document-shaped URIs, or malformed dataset ids), and `resourceGdr(res)` formats the inverse. Use them anywhere a resource — not a document in it — is named across an API boundary, instead of hand-rolling the split.
- 7ffdc77: New `clientConfigFromResource(resource)` export — the `@sanity/client`-config
  fragment addressing a `WorkflowResource` (dataset via the classic
  `{projectId, dataset}` config, other resource types passed through as
  `resource`). The one home for that branch: hosts spread it into their own
  `createClient` call, and the CLI's `clientFor` now derives its config through
  it instead of a private copy.
- ced40e4: `createTelemetryIntake` / `isTelemetryEnvDenied` — the standard Sanity-intake consent/transport recipe (account status from `GET /intake/telemetry-status` with resolved-only caching, `POST /intake/batch` `{projectId, batch}` transport, the `telemetry.*` request tags, and the CI/`DO_NOT_TRACK` environment denial) now lives once in the engine package as structural mirrors of `@sanity/telemetry`'s store options — still no runtime dependency on that package. The SDK and MCP shells consume it instead of carrying twin copies. `WorkflowConfig` additionally accepts an optional `telemetry` logger the CLI routes every event to in place of its built-in shell, and the mirrored event type's `description` is optional to match the real package, so events built with the real `defineEvent` flow through the mirrored logger seam.
- 9b1b40d: **BREAKING:** `workflow.deployDefinitions` and `diffEntry` now normalize and strict-parse incoming definitions at the boundary. A fetched `sanity.workflow.definition` document round-trips cleanly: the document envelope (`_*` system fields, `tag`, `version`, `contentHash`) is stripped before fingerprinting, so redeploying a fetched document reports `unchanged` — previously the envelope was silently fingerprinted as content, minting a spurious new immutable version on every redeploy. Any other unknown key, anywhere in the tree, now fails the deploy with a path-prefixed validation error instead of riding silently into stored content — which also removes the need for consumer-side envelope strip lists. The input types become the new conditional `WorkflowDefinitionInput<T>`: a loosely-typed fetched document (`Record<string, unknown>`) passes without a cast, while precisely-typed input keeps the full `WorkflowDefinition` contract — unknown keys beyond the document envelope are `never`, so authoring literals keep exact compile-time checking and autocomplete.
- 23cf131: Evaluation forecasts prospective subject writes per involved resource: every `doc.ref` / `doc.refs` / `release.ref` subject outside the workflow's own resource is checked against that resource's own ACL, fetched through its resource client (cached per client + path). When the actor's grants there don't allow `update`, effects-bearing actions are forecast disabled with the new `subject-permission-denied` disabled reason — surfaced on `evaluate` and thrown by `fireAction`'s soft-gate as `ActionDisabledError`. `$can` is unchanged (still the instance-doc read against the workflow's own resource), and the forecast is advisory: it degrades open when a resource's grants can't be fetched or evaluated, and the subject's lake remains the enforcement point.

  New exports: `subjectDenialLabels` (the display convention for the denial payload, the subject-forecast twin of `deniedGuardLabels`), `actionDisabledDetail` (the engine's per-reason detail fragment, for dev-facing hosts), and `aclPathForResource` (the canonical resource → ACL-path encoding behind `grantsFromPath`).

- d192d68: **BREAKING:** subworkflow lifecycle is now owned by a workflow-scope registry (`instance.subworkflows`) instead of stage-entry bookkeeping. A child instance is a workflow-level fact; its record now lives (and survives) at workflow scope.
  - Re-entering a spawning stage **adopts** live children whose `forEach` rows are rediscovered instead of spawning a duplicate cohort. Rows that vanished from discovery follow the block's new `onExit` policy — `'detach'` (default) lets the child run to completion outside the gate, `'abort'` kills it. Stage exit applies the same policy to the live cohort.
  - `forEach` rows must carry an identity for adopt-matching: `_key` ?? `_id` for object rows (mint a `_key` in the projection for synthetic rows), the value itself for scalar rows. An identity-less or duplicate-identity row fails the spawn with a teaching error.
  - `abortInstance` now cascades: every live descendant is aborted recursively. An owed abort is recorded ON the child's registry row (`abortPending: {at, reason}` — crash-safe, and kept afterwards as the audit of why); the cascade drains condemned rows, and a condemned row is never adopted into a fresh cohort.
  - `$subworkflows` is now an **always-bound** condition var over ALL registry rows, faceted by `activity` / `definition` / `rowKey` / `status` (`'active' | 'done' | 'aborted'`), with `current` marking the open stage entry's cohort and `stage` the child's current stage — usable in transition filters, requirements, and any stage's gates. The implicit spawn gate scopes itself to the current cohort and settles on not-active (an aborted child releases it); authored gates that assumed spawn-scoped rows must now facet (`$subworkflows[activity == "…" && current && …]`).
  - Live children join the parent's watch-set and snapshot with raw reads, so conditions over child state re-evaluate as children move; a terminal child's state is frozen onto its registry row and its document leaves the watch-set.
  - Child completion propagates through the registry: a detached child (spawning stage exited, parent moved on) still stamps its row and re-cascades the parent; a terminal parent takes the stamp and history record without being reopened; a propagation with no matching registry row records a loud `subworkflowOrphaned` history entry instead of silently dropping.
  - A parent may complete with live detached children — legal, and `diagnose` now reports `liveChildren` on terminal states so consumers can surface it.
  - Removed: `ActivityEntry.spawnedInstances` — the registry replaces it. Instances persisted before the registry have an empty registry, so a spawning activity that was waiting on in-flight children resolves immediately on its next cascade (the cohort gate is vacuously settled) and those children's completions no longer propagate — each is recorded as a `subworkflowOrphaned` history entry on the parent when it terminates. Let in-flight fan-outs finish before upgrading, or expect to re-drive affected parents manually.

- 15337f1: **BREAKING:** `engine.client` now exposes the request-tag-stamping wrapper — a delegating object implementing the `WorkflowClient` interface over the supplied client, no longer the same instance. Identity comparisons against the supplied client and runtime re-widening to a concrete `SanityClient` (`.listen()`, `.config()`, `.withConfig()`) stop working; the typed `WorkflowClient` contract is unchanged.

  Request-tag every Content Lake request. Each engine verb stamps an operation-scoped `workflow.*` request tag (`workflow.fire-action`, `workflow.deploy`, `workflow.guard.deploy`/`refresh`/`retract`, `workflow.access.resolve-actor`, …) through a stamp-if-missing wrapper that never overrides an explicit tag and honors the runtime `null` suppression form; effect-handler traffic through the handler ctx — both `ctx.client` and `clientFor` — falls back to `workflow.effect`, distinct from the drainer's own `workflow.drain` housekeeping. The `WorkflowClient` surface carries the tags: `tag` on `WorkflowFetchOptions` and `WorkflowCommitOptions`, an options bag on `getDocument` and `transaction().commit()`. The request tag is observability metadata in request logs — unrelated to the workflow-domain deployment tag.

- 2d1a8e1: Pluggable product telemetry. `createEngine` accepts an optional `telemetry` logger, defaulting to a no-op — the engine defines and emits adoption events; the app shell owns store creation, consent, and transport. The engine carries no runtime dependency on `@sanity/telemetry`: the event/logger shapes (`WorkflowTelemetryEvent`, `WorkflowTelemetryLogger`) are structural mirrors, so a real `TelemetryLogger` slots straight in and the engine's events feed a real store unchanged (drift is pinned by a type-level test). The v1 vocabulary (exported from the package root): `Editorial Workflows Definition Deployed` (structural counts, activity kinds, capability flags, content hash, created/unchanged status), `Editorial Workflows Instance Started`, `Editorial Workflows Action Fired`, `Editorial Workflows Field Edited` (sampled), `Editorial Workflows Instance Ticked` (sampled), `Editorial Workflows Effect Completed` (direct reports; engine-drained effects surface via the drain event instead), `Editorial Workflows Effects Drained` (sampled), `Editorial Workflows Instance Aborted`, `Editorial Workflows Stage Set`, and `Editorial Workflows Definition Deleted`. Every attempt emits — no-op outcomes ride the payload (`status: 'unchanged'`, `changed: false`, `drainedCount: 0`) rather than suppressing the event; the one silence is an idempotent action replay. Payloads carry no customer-authored strings — structural counts, kind enums, capability flags, and content fingerprints only. A throwing host logger never fails a committed write. The reactive session emits the same events through the engine's logger, and the resolved logger is exposed as `engine.telemetry` for adapters.
- 12cdbd6: **BREAKING:** Deploy validation now rejects dangling references that previously deployed fine and failed silently at runtime:
  - **Unreachable stages** — a stage with no transition path from `initialStage` can never host an instance; its activities, guards, and conditions are dead weight.
  - **Undeclared `$fields.<name>` reads in conditions** — GROQ resolves an unknown attribute to null, so a typo'd read was a silent never-true. Sites nested in a stage/activity are checked against their exact lexical window (workflow + enclosing stage + enclosing activity; transition-level sites see no activity fields); workflow-level sites whose overlay follows the evaluation context (predicate bodies, a workflow field's `editable`) are checked against all declared names. Detection is AST-exact — `"$fields.x"` inside a string literal and dynamic `$fields[$var]` access don't count.
  - **`fieldRead` value sources** — a seed (`initialValue`), op payload, or guard read naming an entry its resolver can't reach returned the default/undefined instead of failing. Seeds must read an earlier same-scope sibling (or workflow scope explicitly — forward and self references are rejected, and scope spellings the resolver can't honour, like `scope: "stage"` on an activity-scope seed, are rejected with the working alternative). Op payloads resolve stage-then-workflow and never see activity fields. Guard reads (`$fields.<name>[.path]` on `match.idRefs` / `metadata`) resolve against workflow-scope fields only, and a guard's `$effects['<name>']` read must name a declared effect.
  - **`fieldRead` / guard-read dot-paths** — a declared `path` must fit the target's value shape: `object.fields` / `array.of` sub-shapes recursively, the fixed GDR / release / actor / assignee envelopes, numeric indices for array kinds, and no paths into scalars.

  Every check reports through `checkWorkflowInvariants` with an exact issue path, so `defineWorkflow`, `validateDefinition`, `deployDefinitions`, the CLI, and the MCP validate tool all reject the same definitions with the same messages.

- 437b544: `validateDefinition` now parse-checks `editable` predicate strings on workflow-, stage-, and activity-scope field entries and stage `editable` tighten-overrides — previously these deployed unchecked (a malformed one threw at evaluate time; a `_type`-scanning one silently left the field non-editable). Every authored condition string gets the full deploy check (GROQ syntax plus the `_type` discovery-scan rejection), reported once at its authored site; plain condition sites are enumerated by the shared `conditionSitesOf` walker so the validator cannot drift from the insight surface. Validation issue labels are uniformly stage-qualified and derived from site addresses — a transition filter reads `stage "draft" transition "auto" filter` (the `(from → to)` arrow is gone), and op `where` / effect-binding labels on transitions and actions now carry their stage too.
- ced40e4: Request tags move to workflows-owned families with the runtime as the segment: `sanity.workflows.cli`, `sanity.workflows.studio`, `sanity.workflows.sdk` — never another team's family (`sanity.cli.*`, `sanity.studio.*`) — and platform analysis zero-rates `sanity.workflows.*`. The MCP server deliberately sits outside that family as `sanity.workflows-mcp` (no dot boundary), so agent-driven traffic bills. Under any workflows-family prefix the engine's tag wrapper strips the now-redundant `workflow.` root from every relative op tag — stamped fallback and explicit alike — so traffic lands as `sanity.workflows.cli.deploy` with exactly one workflows segment; on raw consumer clients and under foreign host prefixes the root stays, since there it is what identifies the traffic. The Studio adapter's engine and resource-router clients and the SDK telemetry shell's intake client now set their family prefix themselves instead of riding the host's.

### Patch Changes

- 6c21009: Correct public TSDoc and README claims that contradicted the implementation: CLI auth precedence (an explicit `SANITY_AUTH_TOKEN` wins over the `sanity login` session), the real CLI verbs (`workflow.diagnose`, `workflow.availableActions`) and document types (`sanity.workflow.instance` / `sanity.workflow.definition`), guard predicates reading the delta-mode `before()`/`after()` natives, glob patterns supporting multiple `*`s, where `$can` actually binds (requirements and the editField gate, not action filters alone), the editField target contract (any-scope match with activity-first precedence), guard observation fan-out across the engine dataset plus each watched subject's dataset, the object value expression being op-payload-only, and the MCP descriptor / SDK observer export pointers. The deploy-time `$can` rejection error now states where `$can` actually binds (the caller-bound projection: action filters, requirements, editable predicates) instead of claiming action filters are its only home.
- a8f1cb9: `subworkflows.forEach` now recognizes the engine's own reference shape as a row identity: a GDR-value row (`{id, type}` with a GDR-URI `id` — what a `doc.refs` field stores) keys on its `id`, extending the row-identity rule to `_key` ?? `_id` ?? GDR `id` ?? scalar. Fanning out over a `doc.refs` field — `forEach: '$fields.documents[]'` — starts instead of failing with "row without an identity", and adopt-matching is unchanged: same document ⇒ same row. The teaching error now names the GDR case alongside `_id`/`_key`/scalar.

  `subworkflows.context` values are now validated where they evaluate: a value that is neither a scalar nor a canonical GDR (`{id, type}` with a GDR-URI `id`) fails the spawn with a teaching error instead of being silently dropped (arrays, plain objects) or persisted malformed (GDR-shaped values with a non-string `id`), and a GDR handoff is normalized to exactly `{id, type}` so extra projected attributes don't ride into every child instance.

- 6c21009: Regression tests pinning documented contracts: a guard `match.idPatterns` glob supports multiple `*`s and matches the whole id (anchored — no substring leak), `$can` binds in activity `requirements.*` and in `editable` predicates (unmet under read-only grants, met under update grants), and deploying a guard whose `idRefs` resolve to documents in different resources fails loudly with the single-resource error instead of picking one.
- 325c2d1: `InstanceSession.editField` keeps its promise shape for op-shape contract bugs: a `set`/`append` call with no `value` now returns a rejected promise carrying `ContractViolationError` instead of throwing synchronously from its preview-staging step.
- 8c319b2: Stage-entry evaluation now reads the post-entry view: an entered stage's activity `filter`s, auto-activation gates, and `fieldRead` entry fields see `$stage` naming the entered stage, its `$fields` overlay, and the firing transition's op writes. Previously they read the exiting stage's context, silently skipping activities gated on the entered stage. Initial-stage filters likewise now see the stage's own entry fields at prime.
- dc64968: Published tarballs no longer include sourcemaps (whose `sourcesContent` embedded the complete TypeScript source) or inline code comments in the compiled JS — license markers and bundler annotations (`/*@__PURE__*/`-style tree-shaking hints) are preserved. Types and TSDoc in `.d.ts` files ship unchanged, and the tarballs shrink accordingly (workflow-engine: ~3× smaller). Each tarball now ships its `CHANGELOG.md`, so release notes reach consumers who can install the package but cannot see the repository.
- Updated dependencies [bae7eb8]
- Updated dependencies [7217e14]
  - @sanity/groq-condition-describe@0.1.0

## 0.14.0

### Minor Changes

- ad9b6f6: **BREAKING:** New reserved condition var `$effectStatus` — a definition with an author predicate named `effectStatus` now fails deploy validation (rename the predicate).

  `$effectStatus` is the declarative "has my effect drained?" read: a map from effect name to `'done'` / `'failed'` for the latest completed run **queued under the current stage entry**, absent until that entry's run drains. It is re-entry-safe where hand-rolled `effectHistory` counting is not — runs queued under a prior entry (even ones completing late, after re-entry) never count — so an effect-drained gate is a one-liner: `completeWhen: "defined($effectStatus['<effect>'])"` (settled either way) or `$effectStatus['<effect>'] == 'done'`. To support the read, queued effects and their completion rows now carry `stageEntryKey` — the `_key` of the stage entry the effect was queued under (a transition's effects belong to the entry being entered). The match is entry **identity**, never a timestamp, so it holds under frozen test clocks and same-commit loop-backs; rows persisted before the stamp never match (fail closed).

  Also new:
  - One exported source of truth for condition-scope variables: `CONDITION_VARS` (each var annotated with the context that binds it: always / caller / spawn), with `RESERVED_CONDITION_VARS`, `FILTER_SCOPE_VARS`, and `GUARD_PREDICATE_VARS` derived alongside — the deploy-time shadow check and the docs now share one inventory, and the `Condition` type carries real TSDoc pointing at it. Exported from both the package root and `./define`.
  - `isGuardLifted(guard)` — the public discriminator for a lifted guard (a lift patches the predicate and keeps the doc, so lifted guards stay in guard queries and streams).

- 83d5924: **BREAKING:** `DeployDefinitionResult.definition` is renamed to `name` — the same noun `DeleteDefinitionResult` already uses for the definition's `name`, so the two result shapes agree on how a definition is identified.
- df00bbb: New `instancesQuery({tag, filter})` — the shared instance-list query builder: one `CompiledQuery` for both read styles, the engine's one-shot fetch and a reactive adapter's live subscription (the same stateless/reactive split as `instanceGuardQuery`, which now also returns the named `CompiledQuery` type). Filters: `document` (GDR prefilter, narrow exactly with `instanceWatchesDocument`), `definition`, `stage`, `includeCompleted`. `instancesForDocument` now builds its prefilter through it. Also exported: `ResourceClientResolver` (for consumers wiring per-resource clients) and `ENGINE_API_VERSION` (the API surface the engine's reads/writes assume — one pin for every client bound to the engine).
- 5c69928: **BREAKING:** runtime API coherence pass — one result shape, one session noun, nameable engine args.
  - `DispatchResult` → `OperationResult`, and its `fired` flag → `changed` with one meaning honored by every verb: this call changed the instance's workflow state (`false` = successful no-op — an idempotent re-fire, a tick that wrote nothing, a `setStage` already at the target, an abort of an already-terminal instance; failures still throw). `tick` derives it from the instance revision, so a persisted activity-gate flip that didn't unlock a transition still reports `changed: true`. `abortInstance` documents its always-`0` cascade (a terminal instance doesn't cascade; ancestor propagation reports on the ancestors).
  - `startInstance` now returns `OperationResult` instead of a bare `WorkflowInstance` — its cascade is finally observable. Reach the instance via `result.instance`.
  - Engine argument types are exported and nameable: the exported `*Args` shapes are now exactly what `Engine` methods take, and the raw `workflow.*` namespace takes `<Verb>Args & EngineScopeArgs` (the new exported scope type: `client` / `tag` / `workflowResource` / `resourceClients`). New named args for the read/housekeeping verbs: `InstanceRefArgs`, `ChildrenArgs`, `GuardsForDefinitionArgs`, `InstancesForDocumentArgs`, `QueryArgs`, `QueryInScopeArgs`, `FindPendingEffectsArgs`, `DrainEffectsArgs`, `SessionArgs`. `EvaluateArgs` is likewise scope-free now.
  - Verb-surface parity between `Engine` and `workflow.*` is exact and documented: `Engine.evaluateInstance` → `Engine.evaluate` (matching `workflow.evaluate`); engine-only members (`session`, `subscriptionDocumentsForInstance`, `drainEffects`, `verifyDeployedDefinitions`) and the namespace-only `workflow.permissions` are called out as deliberate.
  - One noun for the reactive session handle: `engine.instance(doc, opts?)` → `engine.session({instance, access?, grantsFromPath?})` (args object — no positional outlier), still returning `InstanceSession`; workflow-react's `WorkflowInstanceController` → `WorkflowSession`; the studio/sdk hooks `useWorkflowInstance` → `useWorkflowSession`. "Instance" now always means the document.
  - Test bench mirrors the engine: `bench.startInstance` returns `OperationResult`, and the `Bench*Args` types are the engine-bound shapes minus `access`.
  - CLI reports follow the rename: the report objects for `fire-action` / `move-stage` / `abort` (and `fire-action`'s `--json` payload) now say `changed` instead of `fired`.

- 2f081a3: **BREAKING:** Unify the error model under one `WorkflowError` base class with a `kind` discriminant.
  - Every structured error the engine throws at a caller now extends `WorkflowError` and carries a stable `kind`, so a consumer can write one catch-and-render path: `instanceof WorkflowError`, then switch on `kind`. The model covers the runtime verbs' refusals, denials, races, and lookups. Three things deliberately stay plain `Error`: deploy/authoring validation (a structured issue-report design of its own), transient transport failures (retryable, carrying `cause` — not engine verdicts), and internal invariant violations (the remediation is a bug report, not a catch branch).
  - One class for guard denial across all verbs: `fireAction` and `editField` now throw `MutationGuardDeniedError` when a deployed mutation guard denies the instance write — the same error `tick` and the reactive session already threw — instead of wrapping the identical condition in `ActionDisabledError` / `EditFieldDeniedError`. Those two classes now statically exclude the `mutation-guard-denied` arm from their `reason`, and the commit-time re-checks of `filter-failed` / `activity-not-active` also throw `ActionDisabledError`, so a caller racing a state change sees the same typed error either way.
  - One payload shape for the same denial: the `mutation-guard-denied` verdict arm carries `denied: {guardId, name?}[]` (the `DeniedGuardRef` shape the thrown error also carries) instead of `guardIds: string[]` + `detail`; `deniedGuardLabels(denied)` is the shared display convention (authored name over id).
  - Contract violations are typed: an invalid `tag`, a `workflow.query` GROQ that never binds `$tag`, a non-GDR `document` to `instancesForDocument`, firing an undeclared action or activity, editing an undeclared field, a set/append edit without a value, malformed `initialFields` values, and a client that cannot resolve an actor all throw `ContractViolationError`; a missing/invisible instance throws `InstanceNotFoundError` and a missing deployed definition throws `DefinitionNotFoundError` (all previously untyped `Error`s).
  - Operation refusals and runtime lookups are typed too: `deleteDefinition` refusals throw `DefinitionInUseError` (with a `blockedBy` payload naming the non-terminal instances or spawn-referrers), `completeEffect` on an unknown/already-drained key throws `EffectNotFoundError` (so an at-least-once runtime can treat a double delivery as already-done), and the `missingHandler: 'fail'` policy throws `MissingHandlerError` carrying its `MissingHandlerInfo`.
  - New exports: `WorkflowError`, `WorkflowErrorKind`, `ContractViolationError`, `InstanceNotFoundError`, `DefinitionNotFoundError`, `DefinitionInUseError` (+ `DefinitionInUseBlocker`), `EffectNotFoundError`, `MissingHandlerError`, `FieldValueShapeError`, `DeniedGuardRef`, `deniedGuardLabels`, `ActionDisabledReason`, `EditFieldDeniedReason`, `MutationGuardDenial`. The verdict↔exception mapping is documented on `DisabledReason`.

- df00bbb: The reactive watch-set now includes the open stage's **activity-scope** `doc.ref`/`doc.refs`/`release.ref` fields — the third field scope. Everything deriving from `collectWatchRefs` follows together: session subscriptions re-evaluate when an activity-scope subject changes, snapshot hydration loads it, `instanceWatchesDocument`/`instancesForDocument` (and the reactive discovery hooks) match instances whose only reference to a document is an activity-scope field, and guard housekeeping unions across the datasets activity-scope refs name. Exited stages drop out at all three scopes, as before.
- 2829643: **BREAKING:** guard `match.idRefs` and `metadata` values are now authored as typed `GuardRead` expressions — `{type: 'self'}`, `{type: 'now'}`, `{type: 'fieldRead', field, path?}`, `{type: 'effectsRead', effect, path?}` — instead of the `"$self"` / `"$fields.<name>"` string mini-language. Desugar prints the exact stored string form the deploy resolver and guard refresh already speak, so deployed definitions and the lake guard contract are byte-identical; only the authoring surface changes. Guard `predicate` (lake GROQ) is untouched. A read `path` must be single-line (the printed stored form is parsed by single-line expressions). Migrate `'$fields.subject'` to `{type: 'fieldRead', field: 'subject'}` and `"$effects['x'].y"` to `{type: 'effectsRead', effect: 'x', path: 'y'}`.

  **BREAKING:** literal `initialValue` seeds are now **pinned to the entry's declared kind at define time**: a mismatched shape, a `null` seed (omit `initialValue` instead), or a ref id outside the bare `_id` | GDR URI | `@<alias>:<id>` grammar fails `defineWorkflow` with a labeled error instead of surfacing at materialization — a malformed `@alias` ref can no longer degrade to a bare id and read the wrong resource, and the `@<alias>:` id part is held to the Sanity `_id` charset so junk can't ride through deploy into a never-matching GDR. The grammar applies at every depth: a `doc.ref` sub-field inside an `object`/`array` literal speaks the same three id forms as a top-level entry. Bare ids (including system ids like `_.releases.<name>`) are rooted at the workflow's home resource when the instance materializes the field.

- 6ee9068: **BREAKING:** vocabulary sweep — one word per concept across the public surface.
  - "slot" is purged in favor of the field vocabulary: `EditableSlotEvaluation` → `EditableFieldEvaluation`, `Evaluation.editableSlots` → `editableFields`, `FIELD_SLOT_DISPLAY` → `FIELD_KIND_DISPLAY`; runtime strings follow (`EditFieldDeniedError` now renders `field is not declared editable`, unresolved edit targets throw `No field "…" resolves`).
  - One who-acts taxonomy: `Actor.kind` is now `'person' | 'agent' | 'system'` (was `'user' | 'ai' | 'system'`), sharing its vocabulary with `DriverKind` — `driverKind()` passes `person`/`agent` through and only splits `system` into `engine` vs `service` (anything out-of-vocabulary still lands inside `DRIVER_KINDS`). The shared `ACTOR_KINDS` const (and `ActorKind` type) is exported and feeds both the `Actor` type and the runtime `ActorShape` validator. `ActivityKind` (`user`/`service`/`script`/`manual`/`receive`) is a different axis and is unchanged; its TSDoc gloss now uses the actual values. Actors persisted on new history entries carry the new kinds. **Pre-rename persisted data is not migrated:** an actor-typed field value stored with an old kind fails `ActorShape` validation if an op re-writes it (a `fieldRead` copy, an effect completion `field.set`), and a stored definition seeding an actor literal with an old kind fails new instance starts — finish or migrate in-flight instances and redeploy such definitions.
  - `WorkflowRole` → `WorkflowLifecycle`: the definition key `role: 'workflow' | 'child'` is now `lifecycle: 'standalone' | 'child'` (read by `isStartableDefinition`), leaving `role`/`roleAliases` to mean lake authorization roles only. Definitions authored with `role` must move to `lifecycle` and redeploy.
  - The README now disambiguates workflow fields from Sanity schema fields — including aliasing the `defineField` name clash — and documents the four nesting-level meanings of the `fields` key.

- 2829643: **BREAKING:** `field.updateWhere` / `field.removeWhere` now take a GROQ condition as `where` instead of the typed `OpPredicate` object, and the `OpPredicate` type is removed. Row matching is the same condition grammar as every filter, with two op-only variables bound: `$row` (the row under test) and `$params` (the firing action's args) — e.g. `where: "$row.status == 'done'"`. A truthy result matches; GROQ `null` (an unevaluable comparison) never matches. The `where` string is parse-validated by `validateDefinition` like every other condition (`_type` discovery scans rejected) — on activity, action, and transition ops alike — and an effect handler's completion-returned where-ops get the same checks at the completion boundary, failing with a labeled `EffectOpsInvalidError` before any mutation. The `where` scope's bound set is closed and deploy-enforced: reading any variable outside it (`$can`, `$assigned`, `$parent`, `$subworkflows`, a named-condition `$<name>`, or a typo) is rejected up front, because GROQ evaluates an unbound variable to `null` and the op would silently match no rows. Migrate `{type: 'field', field: 'x', equals: {type: 'literal', value: y}}` to `"$row.x == <y>"`, `all`/`any` compositions to `&&`/`||`, and `{type: 'param'}` comparisons to `$params.<name>`.
- a0443c4: Add `defineWorkflowConfig` and the `WorkflowConfig` type — a typed, validated deploy-config surface that binds a definition's logical resource handles to physical resources per environment (tag). A deployment's `resourceAliases` bindings (`{name, resource}[]`) are collapsed by `resourceAliasesToMap` into the `resourceAliases` map that `deployDefinitions` consumes.

### Patch Changes

- a0443c4: `defineWorkflowConfig` now validates that a `dataset` resource id has the `<projectId>.<dataset>` shape at the config boundary. A malformed id (e.g. missing the dot) previously validated clean and then threw a raw error late, when a client was built from it; it now fails with a path-prefixed config error up front. The other resource types carry an opaque id the engine never destructures, so a non-empty string remains their whole contract.
- a0443c4: `defineWorkflowConfig` now rejects a config whose deployments don't all have unique tags. A tag identifies which deployment to act on, so a duplicate is a config error rather than a silent ambiguity.
- 7a655bd: Document the terminal activity status vocabulary as a health axis: `done` means the work concluded (whatever was decided), `skipped` means it never applied, and `failed` is reserved for work that genuinely could not complete — only `done`/`skipped` satisfy `$allActivitiesDone`; a `failed` activity blocks it permanently. A routine decision (decline, send back, hold) resolves `done` and writes the decision into a field the transition filters read — never `status: 'failed'`. The API overview's cancel-from-anywhere guidance now prescribes the same pattern instead of `failed` + `$anyActivityFailed`.
- d9c8179: Drop the remaining "POC" branding from the guard docs and single-source the persisted guard doc type. Doc comments reference the type via `GUARD_DOC_TYPE` instead of hardcoding the literal, tests build guard ids and `_type` assertions with the exported `GUARD_DOC_TYPE` / `lakeGuardId`, and a contract-pin test pins the persisted wire literals so the eventual stored-type rename is a deliberate act. The `GUARD_DOC_TYPE` doc also notes that the cutover rename is a breaking type change for already-persisted guard docs.
- 0a7979a: Reconcile the guard enforcement story across the public surface. The packages previously asserted both that "the lake enforces guards" and that "enforcement is optimistic — the lake does not enforce `temp.system.guard`". Only the second is true: the lake does not evaluate the guard doc type yet (it is the placeholder for the lake's forthcoming guard primitive), so deployed guards deny optimistically engine-side on every plan and the lake ACL is the only hard gate. Every TSDoc block and README now tells that one story, with `GUARD_DOC_TYPE` as the canonical anchor; the bench's write rejection is described as a simulation of the intended lake contract, not a reproduction of current production behavior.
- 113a796: Docs honesty sweep over the public TSDoc. The workflow API module doc now describes the real verb surface (`deployDefinitions`, `editField`, the admin overrides and pure reads) instead of a stale five-method framing that named a nonexistent `deployDefinition`. `createEngine`'s effect-handler doc points at `drainEffects` / `verifyDeployedDefinitions` — the functions that actually consume handlers — instead of an internal plan step. Actor, history, and guard-owner docs state the caller-asserted, advisory reality: the actor is provenance, not an authenticated principal; the guard `owner` field is an unenforced provenance stamp (with the self-lockout hazard spelled out); `WorkflowAccess.grants` documents the real `$can` mechanism (grants feed advisory `$can.*` params — there is no `permission-denied` verdict — and a failed grants fetch degrades open; the grants-fetch warning no longer claims a "permission gate" is being skipped). `validateDefinition`'s aggregated error now names `validateDefinition` and its deploy-time boundary instead of impersonating `defineWorkflow`.
- df00bbb: The reactive instance session now applies pushed self-docs newest-wins (by `_updatedAt`): a consumer store echo that lags behind the session's own committed reload can no longer regress the held instance to a state the session has already moved past. Content docs stay last-write-wins — the consumer's store owns content truth; the session owns instance truth.

## 0.13.0

### Minor Changes

- 416d4c9: Let an effect handler return `ops` from its completion — `field.*` ops applied in the completion commit through the same op applier (target resolution + value-kind validation) an action's field ops use. This gives an effect the state half of an action: it can put a produced result into the instance's own fields (e.g. `field.set` a created document's ref into `$fields`, or write a screened outcome into a field an activity/stage gate then reads) — folding away the proxy-action and `freshEffect` GROQ workarounds. Completion ops are the `field.*` subset only (a new exported `FieldOp` type, shared with transitions): an effect is outside the activity's own awaiting, so it reports its result as field state and never sets an activity status — `status.set` is rejected at the completion boundary, the same boundary a transition already draws. Returned ops are validated like an action's, are not actor-gated (no actor fires an effect), apply once per completion, and target workflow- or stage-scope fields. Adds the `EffectOpsInvalidError` export (thrown when returned ops don't parse / aren't field ops) and an `effect` origin on `opApplied` history entries.
- 5bbc3f0: **BREAKING:** Public functions that took 3+ positional parameters now take a single named options object. Notably the GDR ref constructors, the definition diff helpers, and the guard matcher:
  - `refDataset(projectId, dataset, documentId, type)` → `refDataset({projectId, dataset, documentId, type})`
  - `refCanvas(resourceId, documentId, type)` → `refCanvas({resourceId, documentId, type})`
  - `refMediaLibrary(resourceId, documentId, type)` → `refMediaLibrary({resourceId, documentId, type})`
  - `refDashboard(resourceId, documentId, type)` → `refDashboard({resourceId, documentId, type})`
  - `gdrRef(res, documentId, type)` → `gdrRef({res, documentId, type})`
  - `diffEntry(...)` / `computeDiffEntries(...)` and `guardMatches(...)` likewise now take a single options object.

  Behavior is unchanged — only the calling convention. Update call sites to pass a single object.

- 6e51913: Add resource aliases so a definition can reference content portably across deploys. A definition addresses content through a named alias — `@content:<id>` — instead of a hardcoded physical GDR. `deployDefinitions` accepts a `resourceAliases` map binding each alias to a physical `WorkflowResource` (`ResourceAliases`, the sibling of role aliases), and expands every `@<alias>:` reference to its bound physical GDR at deploy: the deployed definition holds only physical references, so no alias and no runtime resolver survive past deploy. Switching environments is just deploying the same source with a different map.

  Expansion runs in the shared deploy planner, before the content fingerprint, so `deployDefinitions` and `definition diff` always fingerprint the same physical content (they can't drift), and rebinding an alias and redeploying the same source surfaces as changed content — a new version — never a silent shift in what the workflow reads. Deploy fails closed when a definition references an alias the deploy doesn't bind, or when a standalone reference expands to a malformed GDR. Expansion is a structural walk that rewrites references in GROQ and literal ref values only, never in `title`/`description` prose. Bare ids and physical GDRs are unchanged, so single-resource setups need no `resourceAliases`. The test bench accepts `resourceAliases` on `deployDefinitions`.

### Patch Changes

- 4dfe72a: Finish de-duplicating the internal idioms the structural clone detector misses (the deferred half of the engine dedup sweep), with no change to the public API surface. Each is now expressed once:
  - `applyGateOutcome` in `engine/spawn.ts` is the single home for the "a satisfied resolution gate fired → flip the activity, attributed to the gate's system actor" idiom. All three gate-driven flips route through it — the auto-resolve sweep and ancestor propagation (`engine/cascade.ts`) and the on-activate resolution (`engine/activities.ts`) — so the gate-actor attribution can't drift across paths; `gateActor` becomes a spawn-internal detail. The `ctx.actor`-stamped and `machineStep`-stamped flips are deliberately left alone.
  - Doc-id minting is consolidated into named helpers: `definitionDocId({tag, definition, version})` in `core/refs.ts` (pure, deterministic) and `instanceDocId(tag)` in `keys.ts` (shell-side — it draws `randomKey`). This removes `api/deploy.ts`'s local `definitionDocId` (which carried an unused resource param) and the inline `wf-instance` id templates in `api/workflow.ts` and `engine/spawn.ts`, and carries the "Sanity rejects `:` in document IDs" invariant once.
  - The `ParsedGdr → WorkflowResource` mapping now lives in exactly one place. `resourceFromParsed` moves to its proper pure home in `core/refs.ts` (beside its inverse `gdrFromResource`), and `resourceFromGdrUri` becomes a thin parse-from-string front door over it (`tryParseGdr` then `resourceFromParsed`) — collapsing a second copy of the mapping and dropping its never-firing per-field guards. `guard-bindings.ts` drops its own `Resource` interface + `resourceOf` (a third copy) for the shared helper and no longer depends on the shell module `snapshot.ts`; `assertSingleResource` now returns a `WorkflowResource`. The public `resourceFromParsed` export is unchanged — only its re-export source moved (`snapshot.ts` → `core/refs.ts`).
  - `findCurrentActivityEntry(host, activityName)` in `types/instance-state.ts` is the shared "current-stage activity entry by name" selector, replacing the `findOpenStageEntry(host)?.activities.find(...)` idiom at five standalone sites (`core/editability.ts`, `core/params.ts`, `engine/ops.ts`, `api/operations.ts`, `api/workflow.ts`). The reuse-local `stageEntry` variants that also mutate are left as-is.

- 0bf7503: Fix `defineWorkflow` (and the authoring/stored definition types) tripping `TS2589` — "Type instantiation is excessively deep and possibly infinite" — for consumers that resolve the **published** package, i.e. its bundled `.d.ts`. Code compiled against the engine source was unaffected, so the monorepo never saw it.

  The node types (`WorkflowDefinition` / `Stage` / `Activity` / `Action` / `FieldEntry` and their `Authoring*` twins) are now hand-written named types pinned to their valibot schemas, instead of `v.InferOutput<typeof schema>` over the schema value. api-extractor inlines a non-pinned schema const's type into one multi-thousand-line `v.StrictObjectSchema<{…}>`; computing `InferOutput` over that inlined form instantiated eagerly and blew TypeScript's depth cap. Pinning each node schema to `v.GenericSchema<Named>` short-circuits the inlining, so the bundled `.d.ts` carries named types and the consumer never re-derives the full tree.

  Runtime validation is unchanged — the schema values are identical, only how their types are expressed changed. The pin is bidirectional (the schema's inferred output must be the exact same shape as the hand-written type), so the schema and its type cannot drift in either direction without a compile error. The exported schema consts (`AuthoringWorkflowSchema`, …) are now typed as `v.GenericSchema<T>` rather than their concrete valibot schema type.

- 3229f41: De-duplicate several internal idioms that the structural clone detector misses (semantic/copy-paste-then-diverge repeats), with no change to the public API surface. Each is now expressed once:
  - `toBareId` in `core/refs.ts` is the single "GDR URI → bare id" transform, now used directly by `core/params.ts` (`paramsForLake`) and the engine's cross-resource ref stripping in `cascade.ts`/`spawn.ts`. This removes both prior spellings — `core/params.ts`'s `bareId` (which passed a non-GDR colon string through) and `engine/context.ts`'s `gdrToBareId` (which used `uri.includes(':')` and threw on one) — collapsing the divergence onto the pass-through behavior.
  - `tryParseGdr` in `core/refs.ts` is the single "parse-or-undefined" primitive, reused by `isGdrUri`, `resourceFromGdrUri`, `guards-query`, `discover`, and `snapshot`.
  - `core/errors.ts` adds `rethrowWithContext` for the wrap-rethrow-with-cause shape shared by `params`, `field-resolution`, and `types/instance`.
  - `engine/context.ts` adds `retryOnRevisionConflict` (the optimistic-locking retry shell shared by `fireAction`/`editField`) and the public verbs (`abort`/`setStage`/`invokeActivity`/`completeEffect`) now reload through the existing `loadCallContext` instead of hand-rolling the clock/`clientForGdr` spread.
  - `engine/persist-deploy.ts` adds `persistThenMaybeRefresh` for the conditional stage-guard refresh shared by the action/edit/effect-completion paths.
  - `api/deploy.ts` adds `loadDefinitionVersionsOrThrow` for the "no deployed definition" guard, and `api/operations.ts` adds `engineOptionsForActor` for the actor/clock/`clientForGdr` option spread.

## 0.12.0

### Minor Changes

- 5b10863: **BREAKING:** Compositional Field kinds, Sanity-aligned scalar names, and `todoList`/`notes` as sugar.

  Lean into Sanity's model so any value shape composes instead of minting a bespoke array kind per row layout:
  - **Add `object` and `array` kinds** — `{ type: 'object', name, fields: [...] }` and `{ type: 'array', name, of: [...] }`, mirroring Sanity's `object.fields` / `array.of`. `fields`/`of` are lightweight recursive field shapes (`{ type, name, title?, description?, fields?/of? }`) — no slot-level `source`/`editable`/`required`, since a sub-field's value comes from the parent value. Object/array entries persist their declared shape on the instance, and writes are validated against it.
  - **Scalar names aligned to Sanity** — drop the `value.` prefix: `value.string`→`string`, `value.number`→`number`, `value.boolean`→`boolean`, `value.dateTime`→`datetime`, `value.url`→`url`, `value.actor`→`actor`. **Adds** `text` (multiline) and `date` (date-only, `YYYY-MM-DD`).
  - **Add the singular `assignee` kind** — one `Assignee` (`{type:'user',id} | {type:'role',role}`), the singular of `assignees`. It's the value shape for a single user-or-role assignee (e.g. a `todoList` row's owner); it is NOT wired into the engine's `$assigned` / inbox gate (that remains the task-level plural `assignees`).
  - **`todoList` and `notes` are now authoring sugar** that desugar to an `array` kind: `todoList` → `array of { label, status, assignee?, dueDate? }`, `notes` → `array of { body, actor, at }` (the `actor`/`at` sub-fields match the `audit` op's stamp names, so an `audit`-appended row lands in the declared shape). **The bespoke `checklist` kind is removed** — a plain checklist is a `todoList` used with `{label, status}` only.

  The `ChecklistItem` / `NoteItem` value types are removed (the kinds they typed are gone); `FieldShape` is now exported. `@sanity/workflow-examples` and the `@sanity/workflow-mcp` authoring guide are updated to the new names and kinds.

- ae1434e: Give effect handlers a cross-resource router so they can reach subject docs in another Sanity resource. The `EffectHandler` ctx now carries `clientFor(ref)` alongside `client`: pass the subject's GDR (e.g. the URI a `$fields.subject._id` binding resolves to, or a `GlobalDocumentReference`) and get the client bound to that resource, falling back to the engine's own client for unmapped resources. In a split-dataset deploy the handler patches the subject through `clientFor` while the drainer's `completeEffect` writes the instance through the engine client — one client could not address both, which broke cross-resource drains. `clientFor` throws on a non-GDR ref rather than silently patching the wrong dataset. Additive: existing handlers that only read `client`/`params` are unaffected.
- d850aef: **BREAKING:** Workflow definitions are now immutable and content-addressed — the author no longer writes a `version`.

  A definition's `version` (and a new `contentHash` fingerprint) are stamped onto the deployed _document_ at deploy time, derived from the content itself — the same envelope as `_id`/`_type`/`tag`. `defineWorkflow` no longer accepts a `version` (the authoring schema rejects it), and the `WorkflowDefinition` type no longer carries one.

  `deployDefinitions` is now create-only: it hashes the authored content and compares it to the latest deployed version of that name. Identical content is a no-op (`unchanged`); any change mints the next version (`created`). It never patches a deployed version in place, so a definition can no longer change out from under the instances pinned to it. (Engine-side only — true immutability of the deployed document still requires a Content Lake guard; the engine enforces nothing.) Deploying two definitions with the same name in one batch is now rejected.

  Instances pin `pinnedContentHash` alongside `pinnedVersion`, so a consumer can detect a deployed definition that has drifted from what an instance started on.

  API changes:
  - `defineWorkflow({ version })` / `WorkflowDefinition.version` removed — drop `version` from authored definitions.
  - `DeployDefinitionResult.status` drops `'updated'` (now `'created' | 'unchanged'`); `DiffEntry.status` drops `'update'` (now `'create' | 'unchanged'`) — a content change is always a new version.
  - `isDefinitionUnchanged` removed; the content fingerprint is now exposed as `hashDefinitionContent`. `DeployedDefinition` is exported for consumers reading deployed documents.
  - Spawn refs (`task.subworkflows.definition.version`) are unchanged — you can still pin another definition's deployed version.

- 9519c76: **BREAKING:** Rename the structural `Task` node in the workflow DSL to `Activity`. The node holds multiple Actions, its own scoped Fields, and a status lifecycle — it is not atomic, so in process-modelling terms it is an _Activity_ (BPMN: Activity is the umbrella for work, Task the atomic kind). This frees the word "task" so it never appears in the model — "Tasks" is now purely a product/UI worklist view, not a model entity.

  `Action` (the actor-fired command) is unchanged.

  The rename cascades across the whole surface:
  - Authoring: `defineTask` → `defineActivity`; the `tasks:` array on a stage → `activities:`; `Task`/`AuthoringTask` types → `Activity`/`AuthoringActivity`.
  - Classification: `TASK_KINDS` → `ACTIVITY_KINDS`, `TaskKind` → `ActivityKind`, `deriveTaskKind`/`taskKind` → `deriveActivityKind`/`activityKind` (kind values `user`/`service`/`script`/`manual`/`receive` are unchanged). The shipped "task kinds" surface is retitled "Activity kinds".
  - Status: `TASK_STATUSES`/`TaskStatus` → `ACTIVITY_STATUSES`/`ActivityStatus` (and the terminal-status counterparts); status _values_ are unchanged.
  - Predicate sentinels: `$tasks` → `$activities`, `$allTasksDone` → `$allActivitiesDone`, `$anyTaskFailed` → `$anyActivityFailed`, `$requiredTasksDone` → `$requiredActivitiesDone`, `$task` → `$activity`. Authored GROQ filters referencing the old names must be updated.
  - Persisted/wire format: the `'task'` field scope value → `'activity'`, history entry types (`taskActivated`/`taskStatusChanged` → `activityActivated`/`activityStatusChanged`), and engine result/diagnostic codes (`failed-task` → `failed-activity`, `task-not-active` → `activity-not-active`, `reset-task` → `reset-activity`, etc.).
  - `workflow-react`: the `fireAction` argument `{task}` → `{activity}`.

  Nothing referencing "task" remains in the model. This is a deliberate pre-customer breaking change to land the correct, permanent vocabulary.

- 9233cd3: Add `engine.instancesForDocument({document})` — the reverse of the watch-set, finding every in-flight instance whose evaluation depends on a given document. The forward watch-set (`subscriptionDocumentsForInstance` / `collectWatchRefs`) answers "which docs does this instance watch"; this answers "which instances watch this doc", which a non-reactive, content-change-driven runtime (a Sanity Function, an Inngest/durable worker) needs to know which instances a changed document should `tick`. It mirrors the forward method's name (`subscriptionDocumentsForInstance` ↔ `instancesForDocument`) and sits alongside the existing `instancesForSubject` / `instancesByStage` read helpers.

  It matches the same ref set the forward watch-set uses — the instance itself, its ancestors, and the docs named by `doc.ref` / `doc.refs` / `release.ref` field entries on the workflow scope **and the current stage** — via the new pure `instanceWatchesDocument(instance, document)` helper, which derives from `collectWatchRefs`, so forward and reverse stay in lockstep (the same way `hydrateSnapshot`'s load-set does). A coarse GROQ prefilter narrows candidates server-side; the shared matcher does the exact, open-stage-only narrowing. The subject is matched by its full, resource-qualified GDR URI, so a cross-dataset doc never matches a same-id doc in another resource. The test bench gains a matching `bench.instancesForDocument(document)` read helper.

  This replaces the hand-rolled, incomplete GROQ a content forwarder would otherwise write (which misses stage-scope refs, `release.ref`, and ancestors).

- e5a862a: **BREAKING:** Split the field `source` union into two purpose-built types.

  One `Source` union served two unrelated jobs — how a field _initialises_ vs what
  an op _writes_ — and an illegal mix was caught by a runtime `throw "…is a
field-entry origin, not a value"` rather than the type system. It is now two types:
  - **`FieldSource`** — a field's seed recipe, exposed as the field's optional
    `initialValue` property (renamed from `source`). Arms: `input` (renamed from
    `init`), `query`, `literal`, `fieldRead`.
  - **`ValueExpr`** — an op's `value` payload (property unchanged). Arms:
    `literal`, `param`, `actor`, `now`, `self`, `stage`, `fieldRead`, `object`.

  Authoring changes:
  - Rename the field property `source` → `initialValue`; it is now **optional**.
  - The `write` arm is **dropped** — an absent `initialValue` is working memory
    (the slot starts empty and an op fills it later), the common default.
  - The `init` arm is renamed to `input`.
  - The exported `Source` type is replaced by `FieldSource` and `ValueExpr`.

  The runtime field-entry-origin `throw` is gone: the split makes that state
  unrepresentable.

  **Also removes the `query` field _kind_ (the untyped escape hatch).** There is
  no longer an `unknown`-valued field — every field declares a concrete kind, and
  "computed" is just a concrete kind + `initialValue: {type:'query'}`. A
  query-sourced field's GROQ result is validated against its declared kind:
  - conforming results are stored (with `resolvedAt` stamped — now driven by the
    `query` _source_, present on any kind, not the old `query` kind);
  - a non-conforming result is **discarded** (the field falls to its default) and
    a new `fieldQueryDiscarded` history entry is logged — fail-soft for runtime
    lake data, rather than the previous hard throw. `FieldKind`, `FieldValueMap`,
    `ResolvedFieldEntry` (`resolvedAt` is now optional) and `InitialFieldValue`
    change accordingly.

  Field `initialValue` lives only on deployed definitions (never on instances) and
  the shared/value discriminator strings are unchanged, so this is a type-level
  break only — redeploy definitions, no instance data migration.

### Patch Changes

- 3ea4953: Fix `roleAliases` with the universal `"*"` key failing to deploy. `"*"` is the only way to express "fulfills any gate" (e.g. `{ "*": ["administrator"] }`), but the Content Lake rejects `"*"` as a document attribute name, so a definition carrying it 400'd against a real dataset while passing in-bench. `defineWorkflow` now normalizes the authored `"*"` to a lake-safe key in the stored definition. Authoring is unchanged — keep writing `"*"` — and the baked `roles` gate and runtime `$assigned` resolution are unaffected.

## 0.11.0

### Minor Changes

- 3b8f3de: **BREAKING:** `TaskEvaluation` gains a required `kind` field. Additive for code
  that _reads_ evaluation output (the engine always populates it), but a compile
  break for any code that _constructs_ a `TaskEvaluation` (test mocks, fixtures).

  Classify tasks by an advisory `kind` (BPMN-aligned: `user` / `service` /
  `script` / `manual` / `receive`). `kind` is a label so tooling can render each
  task as what it is — it changes no gating or how a task resolves; a transition
  still fires exactly as the rest of the task's shape dictates.
  - **Derived (P0):** every `TaskEvaluation` now carries a `kind`, computed from
    the task's shape when not declared (`deriveTaskKind` / `taskKind`, also
    exported): `actions` → `user`, else `effects` → `service`, else a
    `completeWhen`/`subworkflows` wait → `receive`, else an inline machine step →
    `script`. `manual` is never derived — it is explicit only.
  - **Explicit (P1):** an optional `kind` field on the task definition, validated
    at deploy against the task's shape (e.g. a `user` task needs an action, a
    `receive` task waits and carries none) — every contradiction is reported in
    one error. Plus an optional `manual` `target` deep-link (`{type:"url"}` or a
    `{type:"field"}` reference to a document-valued entry, resolved at deploy).
  - **Driver kind (P2):** the `actionFired` history entry records the firing
    actor's `driverKind` (`person` / `agent` / `service` / `engine`, via the
    exported `driverKind`) for the audit-trail glyph — any driver can fire any
    kind.

  `TASK_KIND_DISPLAY` / `DRIVER_KIND_DISPLAY` provide labels for each. Existing
  definitions need no edits: `kind` is optional and derived when omitted.

## 0.10.0

### Minor Changes

- fae3553: **BREAKING:** Rename the domain concept **state → fields** across the whole API and persisted data model.

  "State" was too easily conflated with "stage". The typed, valued data attached to workflows, stages, and tasks is now called **fields** — clearer, and aligned with Sanity schemas: the fields on a workflow, stage, and task can have typed values. This is a clean break (no migration, no back-compat); already-deployed definitions and instances must be redeployed/recreated.

  **Authoring DSL**
  - `defineState(...)` → `defineField(...)`
  - The `state: [...]` array on a workflow / stage / task → `fields: [...]`
  - The `$state.<name>` GROQ scope token → `$fields.<name>`
  - A `claim` action's `state:` reference → `field:`
  - A `stateRead` source → `fieldRead`; its `state:` (entry name) → `field:`
  - Op targets address the entry by `field:` instead of `state:`

  **Persisted / wire format**
  - Op type strings `state.set` / `state.unset` / `state.append` / `state.updateWhere` / `state.removeWhere` → `field.*`
  - The stored `state[]` array on instances, stage entries, and task entries → `fields[]`
  - `startInstance({ initialState })` → `startInstance({ initialFields })`

  **Types & functions** (engine)

  `StateEntry`→`FieldEntry`, `AuthoringStateEntry`→`AuthoringFieldEntry`, `ResolvedStateEntry`→`ResolvedFieldEntry`, `InitialStateValue`→`InitialFieldValue`, `StateKind`→`FieldKind`, `StateValueMap`→`FieldValueMap`, `StateScope`→`FieldScope`, `StoredStateRef`→`StoredFieldRef`, `STATE_SLOT_DISPLAY`→`FIELD_SLOT_DISPLAY`, `EditStateArgs`→`EditFieldArgs`, `EditStateTarget`→`EditFieldTarget`, `EditStateDeniedError`→`EditFieldDeniedError`, `ConcurrentEditStateError`→`ConcurrentEditFieldError`, `RequiredStateNotProvidedError`→`RequiredFieldNotProvidedError`, and the `editState` verb → `editField`.

  Unchanged: runtime/lifecycle instance "state" (stage moves, `WorkflowStateDivergedError`, the projected instance snapshot), the `field`/`fields` JSON-matching primitives in `updateWhere`/`removeWhere` predicates and object Sources, and the Content Lake release `state`.

## 0.9.0

### Minor Changes

- 2e4c980: Add a generic edit seam for declared-editable workflow state.

  State slots can now declare `editable` (default off) and be written directly
  through one `editState` verb — reassign, reschedule, claim-by-hand, append to a
  log — instead of a bespoke action per field.
  - `editable` on a state slot — default off. _Who_ may edit is expressed with
    the gating actions already have, not a new permission concept: `true` (anyone
    in the slot's scope window), a **role list** (the same `action.roles` sugar —
    it desugars to the identical `count($actor.roles[@ in [...]]) > 0` membership
    predicate), or a raw GROQ predicate (checked like `action.filter`). A stage
    may TIGHTEN a slot via an `editable` override map — the override is ANDed with
    the slot's baseline, so it can only narrow, never open a closed slot.
  - `editState` engine verb (and `engine.editState` / `instanceSession.editState`):
    gates on the slot's editability and scope window, applies the edit as a
    `state.*` op (so provenance + history are stamped by the op path), refreshes
    the stage's guards, then cascades — an edit to a value a transition reads can
    move the instance. Advisory like every engine gate; the lake ACL + guards are
    the only hard locks.
  - Scope is the editable window: a workflow slot is editable while the instance
    is live, a stage slot while its stage is current, a task slot while its task
    is active.
  - The projection gains `editableSlots`: each declared-editable slot in scope
    with this actor's edit verdict and the current value's provenance (`setBy` /
    `setAt`, read off `opApplied` history — no denormalised copy). `EditDisabledReason`
    and `EditStateDeniedError` mirror the action verdict surface.
  - `@sanity/workflow-react`'s controller exposes `editState`, threaded through
    the Studio and App SDK adapters.

- fd6b866: Add role aliasing to the authoring DSL: a definition-level `roleAliases` map
  ("can be fulfilled by"). It's an authoring convenience — the same capability is
  often carried by different role names depending on how a project deploys its
  Content Lake roles, so rather than enumerate every equivalent role inline in
  each `roles` gate (or fork the definition per deployment), declare once which
  other roles fulfill it. Each key is a role a gate or `assignees` entry names;
  its value lists the roles that also satisfy it. The reserved `"*"` key lists
  roles that fulfill any gate (e.g. `{ "*": ["administrator"] }` for a
  deployment's broad role).

  The map expands the **required** side — never the actor's roles — and is applied
  in both places roles are matched: the `roles` gate bakes the expanded membership
  into its desugared GROQ at define time, and `$assigned` resolves the assignee's
  role through the map at runtime. Expansion is one level (non-transitive).

  This also corrects the misleading `Actor."*"` documentation: an actor's `roles`
  are matched by literal membership only — there is no actor-side wildcard — with
  the definition's `roleAliases` as the sole mechanism for widening, so the
  advisory gate can never grant access the actor was not actually given. Like
  every engine gate it is advisory; the registrant owns keeping the map true to
  the deployment's real Content Lake ACLs.

## 0.8.0

### Minor Changes

- c298ee2: Make two guard deploy/rollback divergence cases loud instead of silent. (1) When a stage deploys multiple guards and a later one fails after an earlier one already landed, the move now rolls back and throws `WorkflowStateDivergedError` (the earlier lock is orphaned and can't be cleanly undone) instead of re-throwing the bare write error. (2) When a spawned child fails to settle after the spawn transaction committed — e.g. its initial-stage guard can't deploy — the failure now surfaces as `WorkflowStateDivergedError` at the parent boundary instead of a raw child error unwinding past the parent's rollback scope (which left the parent move committed with the intended scream never raised). A new exported `PartialGuardDeployError` carries the partial-deploy detail; a direct caller of `deployStageGuards` (outside the engine's rollback wrapper) can catch it by type. True cross-resource atomicity remains impossible (a guard can live in a different resource than the instance); the direction stays over-lock, but divergence is no longer silent.
- 8131dd5: Keep mutation guards coherent when an effect completes. The guard read mini-language (`match.idRefs` and `metadata` values) now accepts `$effects['<name>'][.path]` alongside `$self`/`$now`/`$state.<name>` — so a guard can bake a completed effect's output into its resolved metadata (the lake only ever sees the resolved value, never `$effects`). `completeEffect` writes outputs into `effectsContext`, but until now a guard reading one stayed stale unless a transition followed. The engine now refreshes the current stage's guards on the effect-completion path when the completion wrote outputs, with the same fail-loud rollback policy as the action-ops refresh. `materializeInstance` carries `effectsContext` so the refresh resolves `$effects` against the new context, and the shared commit-then-deploy primitives moved to their own module so the effect path can reuse them without a cyclic import.
- 8bf467e: Add a definition `role` and a `required` flag on state entries — so spawn-only child workflows can be kept out of standalone-start surfaces, and a load-bearing init slot fails fast instead of silently defaulting.
  - **`role: 'workflow' | 'child'` on a definition (default `'workflow'`).** A `'child'` definition is spawn-only — instantiated by a parent's `task.subworkflows`, never started cold by a human. The exported `isStartableDefinition(definition)` predicate (plus the `WorkflowRole` type) is the single place that decides "can a human start this", so every consumer filters its start picker the same way. Advisory: the engine does **not** refuse a `startInstance` on a `'child'` def — it's a discoverability flag, not a gate. `@sanity/workflow-cli`'s `definition list` gains a **Startable** column derived from the predicate.
  - **`required?: boolean` on a state entry — the start/spawn counterpart to action-param validation.** A missing `init`-sourced value previously resolved silently to `null`/`[]`, which is what let a cold-started child come up structurally incomplete (a review with no subject, no assignee). A `required` entry the caller doesn't supply — via `initialState` at start, or the parent's `subworkflows.with` at spawn — now throws the exported `RequiredStateNotProvidedError` and creates nothing, exactly as a missing `required` action param already does. Valid only on a workflow-scope `init` entry; `required` on any other scope or source is a deploy error (`defineWorkflow` rejects it with the offending field path).

  The two compose: `role` keeps a child out of pickers; `required` stops the engine from constructing an incomplete instance if a UI (or a human) starts one anyway.

## 0.7.0

### Minor Changes

- ef927bc: Carry per-task assignees on `DiagnoseInput`, and stop exporting `openStage` / `assigneesOf`.

  The "who is this task waiting on" answer is now derived once into `DiagnoseInput.assignees` — a `Record<string, Assignee[]>` keyed by task name — when `diagnoseInputFromEvaluation` builds the input, rather than left for each consumer to recompute. `openStage` and `assigneesOf`, which only ever existed to derive that data, are no longer part of the public surface; they stay internal to the diagnostics module. `DiagnoseInput.instance` also drops `stages`, which no longer has a reader now that the assignee lookup is precomputed.

- 32f5e64: Name the remediations that would unstick a stuck instance from the engine, not the CLI.

  `workflow.diagnose` now returns `remediations` alongside the diagnosis — a `SuggestedRemediation[]`, empty unless the instance is `stuck`. Each entry names a surface-neutral `RemediationVerb` (`retry-effect` | `drain-effects` | `reset-task` | `set-stage` | `abort`), whether it's runnable as an engine operation today (`available`), and a one-line rationale. The new `remediationsFor` reasoning plus the `SuggestedRemediation` / `RemediationVerb` types are exported. Previously the cause→fix mapping — including which repair verbs exist versus are still planned — lived only in the CLI, so every other consumer (MCP, a future UI) would have had to re-derive it.

  The CLI `diagnose` command now renders its "suggested fix" block from these remediations — a not-yet-runnable verb is dimmed and marked `(planned)` — instead of hardcoding the prose, and includes `remediations` in `--json` output.

- df7582f: Fix two stacked bugs that let a threshold-gated workflow auto-advance past a review it couldn't actually evaluate.
  - **Filters fail closed on unevaluable operands.** A `task.filter` / `transition.filter` that evaluates to GROQ `null` (a referenced operand was missing or incomparable, e.g. `$state.subject.amount > 10000` when the subject isn't loaded) is no longer coerced to `false`. A `null` gate previously _skipped_ the task / fell through the transition — fail-open. Now an unevaluable `task.filter` keeps the task in scope (the stage holds rather than cascading through), an unevaluable transition filter halts selection, and the undecidability is recorded on `TaskEntry.filterEvaluation.unevaluable` so the audit trail distinguishes "genuinely below threshold" from "couldn't read the field". Unevaluability also propagates through nullary predicates (an unevaluable predicate binds `null`, not `false`).
  - **Content hydration is draft-preferring.** When an instance has no explicit release perspective, content reads now use a drafts-preferring perspective (drafts overlay published) instead of a published-only point read — uniformly across `doc.ref`/`doc.refs` hydration, `type: "query"` state-entry resolution, and `subworkflows.forEach` discovery (single-sourced as `DEFAULT_CONTENT_PERSPECTIVE`). A subject that exists only as a draft — or whose in-flight edits live in the draft — is now what filters evaluate. Instance / ancestor / `system.release` documents continue to read raw. The reactive App SDK adapter (`@sanity/workflow-sdk`) matches: a content doc with no release is read under the `drafts` perspective instead of relying on the SDK's default, so a reactive session and the engine cascade resolve the same draft-aware view. (The Studio adapter already preferred `version ?? draft ?? published`.)
  - **Diagnostics tell an undecidable hold from a dead-end.** `TransitionEvaluation` now carries `unevaluable`, and `diagnose` reports a new `transition-unevaluable` stuck cause when every task is resolved but an exit filter can't be evaluated (a recoverable hold — the cascade re-fires once the operand resolves) rather than mislabeling it the permanent `no-transition-fires` routing dead-end. `@sanity/workflow-cli`'s `diagnose` renders the distinct cause.
  - **Single-document writes commit `visibility: 'sync'`.** `create` and `patch().commit()` now set `visibility: 'sync'` explicitly (via the new `WorkflowCommitOptions`) so the engine never reads a stale value back through a query. Adds `WorkflowCommitOptions` / `WorkflowVisibility` to the public client surface.

- 129258c: Add task `requirements` — a readiness axis for visible-but-not-yet-executable tasks, distinct from ACL and guards.

  A task definition can now declare `requirements: { <name>: <groq-condition> }`: preconditions over the rendered scope that gate _executability_ without affecting visibility. While a requirement is unmet the task stays visible, and every action on it is reported disabled with a new `requirements-unmet` verdict that names the unmet requirements; `TaskEvaluation.unmetRequirements` summarises the same set at the task level so a consumer can explain why the whole task is gated. Requirements are all-of (express any-of inside a single condition), evaluated in the same scope as `filter`, and — like every engine-side check — advisory; the lake remains the enforcement point.

  Diagnostics gain a `blocked` state: an active task held by an unmet requirement is reported as visible-but-not-yet-executable (healthy and transient), distinct from `stuck`, and a requirements-held task no longer masks an actionable sibling in the `waiting` verdict.

  The CLI `fire-action` listing and the MCP server's disabled-reason copy both render the new reason; the CLI `diagnose` command renders the new `blocked` state.

### Patch Changes

- ed4174c: Route subworkflow spawn discovery by a `release.ref` subject, not just `doc.ref`. A release-subject workflow (e.g. content-release) carries only a `release.ref` state entry; spawn discovery previously picked its lake client from the first `doc.ref` entry only, so with no `doc.ref` it fell back to the engine's own resource. On a multi-dataset setup — engine docs in one dataset, content/version docs in another — the `forEach` then queried the wrong dataset and matched nothing, spawning zero children. Discovery now follows the first `doc.ref` _or_ `release.ref` subject GDR in declaration order, so a release workflow's `forEach` hits the content resource (under the already-threaded `[releaseName]` perspective) where the release's version docs live. A workflow that declared a `release.ref` before a `doc.ref` would now route by the earlier `release.ref` (no such workflow exists today; authors put the intended routing subject first).

  Also fail loud on a related footgun: when spawn discovery runs against a foreign resource but a `subworkflows.with` value projects a **bare** id, that id would silently root at the parent (engine) resource — minting a child whose subject references a document that doesn't exist there. The engine now throws with guidance to project an explicit GDR URI in the `with` GROQ (`"dataset:<projectId>:<dataset>:" + _id`), instead of spawning a child that reads nothing.

## 0.6.0

### Minor Changes

- c6d1762: Model the engine tag as a single environment partition: `tags: string[]` becomes `tag: string`.

  The array + set-intersection matching was over-modelled — an engine operates against exactly one environment (test vs prod) at a time. `createEngine`, the raw `workflow.*` args (`DeployDefinitionsArgs`, `StartInstanceArgs`, `OperationArgs`, `EvaluateArgs`, `DeleteDefinitionArgs`), and the stored `workflow.definition` / `workflow.instance` documents now carry a single `tag`. Reads filter by equality (`tag == $tag`) instead of intersection, and `workflow.query` requires a `$tag` filter rather than `$engineTags`. Consumer-authored `type: "query"` state entries that referenced the `$engineTags` scope param now receive `$tag` (a single string) instead. `validateTags` is replaced by `validateTag`, and `canonicalTag` is removed (the tag is the ID prefix directly).

  The `tag` is **required** — there is no default. The engine enforces nothing, so the partition is the only thing keeping reads and writes off the wrong environment; an engine must not guess. `createEngine` requires it, and the CLI (`WORKFLOW_TAG` / `--tag`) and MCP server (`WORKFLOW_TAG`) both fail at startup when it's absent.

  The test bench's `createBench({ tags })` option becomes `createBench({ tag })`.

## 0.5.0

### Minor Changes

- dbc4afa: Move the instance-reasoning behind the CLI's read commands into the engine so every consumer shares one implementation rather than re-deriving it. The engine now exports the stuck-instance classifier (`diagnoseInstance` with `Diagnosis` / `StuckCause` / `DiagnoseInput`, plus `abortReason`, `openStage`, `assigneesOf`, `diagnoseInputFromEvaluation`), the available-actions projection (`availableActions` with `AvailableAction`), and definition-diff classification (`diffEntry` / `computeDiffEntries` with `DiffEntry` / `DeployTarget`) — all reusing the engine's own doc-id minting and no-op verdict. Two instance-id-keyed verbs compose this with `evaluate`: `workflow.diagnose` and `workflow.availableActions` (also on the `Engine` wrapper).

  The CLI's `diagnose`, `fire-action`, `deploy`, and `definition diff` commands keep only their rendering and now call the engine for the reasoning, and the MCP's `get_workflow_state` projects its action verdicts through the same shared `availableActions`. No behavioural change to the CLI or MCP surfaces.

- e2a6d5d: Add `workflow.deleteDefinition` — remove a deployed workflow definition from the lake by its `name`, every version by default or a single one via `version`. Definitions are the only thing the engine ever deletes: without `cascade` the delete refuses while non-terminal instances exist; with it those instances are hard-stopped through the same abort primitive as `workflow.abortInstance` (with ancestor propagation), and their documents remain in the lake as the audit record. Deletes refuse while any surviving deployed definition — another workflow, or a remaining version of the same one — still spawn-references a target (a version-pinned ref blocks its version; a version-less or `latest` ref blocks only the last version). Once the last version goes, the definition's orphaned guard docs are removed across every datasource its versions statically named.

  Supporting changes: `WorkflowTransaction` gains a `delete(id)` member (transaction-only by design — the top-level client surface stays delete-free), the shared `abortAndPropagate` primitive backs both aborting verbs, and the `Engine` wrapper gains `deleteDefinition`.

### Patch Changes

- aa87a1c: Fix cross-resource mutation-guard deploy/retract routing. When a workflow instance lives in one resource (the engine's `workflowResource`) and its subject document lives in another (routed via the caller's `resourceClients`), a stage's `guards[]` are now WRITTEN and LIFTED through the SUBJECT's resource rather than silently falling back to the engine's own dataset. A guard stored in the wrong dataset is a silent no-op — that dataset's write boundary never enforces it.

  The `fireAction`, `setStage`, `abortInstance`, `completeEffect`, and `invokeTask` engine entry points — and the reactive `InstanceSession.fireAction` — dropped the routed `clientForGdr` before reaching `deployStageGuards` / `retractStageGuards` / `refreshStageGuards`, falling back to the default client. `EngineCallOptions` now carries `clientForGdr`, and both the stateless API layer and the reactive session thread the resolver (built from `resourceClients`) through every guard-touching commit path. The transition/cascade path was already routed correctly. Cross-resource retraction (stage exit, lift, abort) now routes to the subject resource too, so a cross-resource-deployed guard is liftable.

## 0.4.0

### Minor Changes

- 4b5f59a: Add `workflow.abortInstance` — an admin hard-stop for in-flight instances. Aborting stamps a new `abortedAt` timestamp alongside `completedAt` (in-flight queries keep their `!defined(completedAt)` shape; `abortedAt` distinguishes aborted from completed), exits the open stage entry with task statuses frozen as-is, cancels every pending effect into `effectHistory`, appends a `workflow.history.aborted` audit entry, lifts the aborted stage's lake guards, and propagates to ancestors so a parent's spawn-completion gate re-evaluates. Aborting an already-terminal instance is a `{fired: false}` no-op.

  Supporting behaviour fixes: a terminal instance never moves again — neither auto-transitions nor `setStage` fire once `completedAt` is stamped (previously a completed instance could be moved off its terminal stage into an incoherent half-state); spawn-completion counting treats any `completedAt`-stamped child as terminal so an aborted child can't hang its parent's gate; stage-guard retraction now lifts guards for a terminal instance still parked on its stage; and stage-guard deployment refuses aborted instances, so a stale reconcile racing the abort can't re-lock subjects that nothing could ever unlock again.

- fcf938a: Rebuild the authoring DSL and stored model around generic primitives plus
  define-time sugar. Breaking across the board:
  - **Name identity everywhere.** `name` replaces `id`/`workflowId` on
    definitions, stages, tasks, actions, transitions, state entries, and
    effects; instances carry `definition` + `currentStage` by name. The API
    boundary follows: `startInstance({definition})`,
    `guardsForDefinition({definition})`, `children({task})`, deploy results
    carry `definition`, and guard provenance is `sourceDefinition` /
    `sourceStage`. The pre-rebuild "slot" vocabulary is gone — state values
    validate as state entries (`StateValueShapeError` with `entryType` /
    `entryName`). Bare
    in-array `type` discriminators replace namespaced `_type` kinds
    (`doc.ref`, `assignees`, `state.set`, …). Engine-owned lake doc types are
    `sanity.workflow.definition` / `sanity.workflow.instance`.
  - **Two-layer schemas.** Authoring shapes (primitives + sugar) desugar at
    define-time into the stored definition: the claim pair, the `audit` op
    (stamped append), `roles`/`status` field sugar, lexical scope resolution
    for op targets, and the default `$allTasksDone` transition filter.
    State-entry names and predicate keys must be GROQ-safe identifiers (they
    are referenced as `$state.<name>` / `$<name>` in conditions). Deploy
    invariants reject duplicate names (stages, tasks, actions, transitions,
    state entries per scope, guards across the definition, effects), unknown
    targets, reserved-var shadowing, predicate cross-references and
    caller-scoped vars in predicates, `$can` outside action filters, and
    malformed guard reads.
  - **Ops are the only mutation vocabulary.** `state.set` / `state.unset` /
    `state.append` / `state.updateWhere` / `state.removeWhere` /
    `status.set`, with `{scope, state}` targets resolved at deploy and
    `status.set` as the single task-resolution mechanism (stamps completion +
    history).
  - **Lifecycle payloads.** Tasks own activation (`activation: 'auto' |
'manual'`, machine-step auto-resolution, `completeWhen`/`failWhen`,
    `subworkflows` fan-out with `$subworkflows` completion gates and parent
    `context` handoff); transitions own exit/arrival (always-filtered,
    first-truthy wins, carry ops + effects); terminal stages are structural
    (no transitions).
  - **One gate mechanism.** Conditions are GROQ over the rendered scope
    (`$self`, `$state`, `$actor`, `$assigned`, `$can`, `$effects`, `$tasks`,
    `$subworkflows`, `$now`, …) with author predicates pre-bound as boolean
    params. Everything engine-side is advisory; hard enforcement is the lake
    ACL plus guards (`temp.system.guard` docs with `metadata` projections and
    name-derived ids).
  - **Effects registry.** Effects are `{name, bindings, input}` with
    GROQ-string bindings over the rendered scope; completed-effect `outputs`
    land in `effectsContext` namespaced under the effect's name and read as
    `$effects['<effect name>'].<output>`.

  The test bench mirrors the new surface (`task` instead of `taskId`,
  name-keyed reads, `effectsContextMap` returning the rendered `$effects`
  map).

- 6c4e0a0: Add `guardsForDefinition` — find every guard a workflow deployed without needing a live instance. Guard docs are stamped with the version-less workflowId, so it spans the datasources statically named across all deployed versions: the workflow resource, plus any resource a guard idRef names statically (a hardcoded GDR literal, directly or via a `stateRead` of a slot whose source is a literal GDR). Guards whose resource is only known per-instance (a `subject`/`init`-sourced slot) are not reachable this way — `guardsForInstance` covers those. Exposed on the engine (`engine.guardsForDefinition({workflowId})`) and the bench (`bench.guardsForDefinition(workflowId)`), reusing the existing `GUARD_DOC_TYPE` + provenance fields.
- 12e23b0: Live lake mutation guards now flow through the reactive stack and into evaluation.

  **Engine:** `InstanceSession` gains `updateGuards(guards)`, and `evaluateFromSnapshot` accepts `guards` — every action commit is an `update` write to the instance doc, so a held guard that matches the instance and denies that write disables every action with the (previously declared but never produced) `mutation-guard-denied` reason, carrying the denying `guardIds`. A lifted guard (predicate `"true"`) allows; deny-all (`""`) denies; fail-closed. `fireAction`'s soft-gate uses the same projection, so firing while guard-denied throws `ActionDisabledError` with the structured reason. The stateless fetch path agrees: `workflow.evaluate` / `workflow.fireAction` load the instance's guards (new `verdictGuardsForInstance`) before evaluating, so both paths produce the same verdicts for the same state. Verdict loads are **physically scoped to the engine's own datasource** — a guard enforces solely within the datasource it lives in, so neither an honestly-stamped foreign guard nor a forged guard doc planted in a watched content dataset can ever flip a verdict (the cross-datasource `guardsForInstance` union remains housekeeping-only). `tick` (session and stateless) pre-flights the same instance write and fails fast with `MutationGuardDeniedError` before entering the multi-step cascade, instead of risking a partially-applied move; best-effort — the lake remains the final arbiter and the rollback machinery stays the backstop. New `instanceGuardQuery(instanceId)` is the single definition of the per-instance guard filter, shared by the verdict load and the adapters' subscriptions.

  **Adapters:** `useWorkflowInstance` / `useWorkflowSession` expose a live `guards` field and feed the stream into the session, so action verdicts re-evaluate as guards are deployed on stage entry and lifted on exit. Driven by a new required `observeGuards` method on `WorkflowObserver` (breaking for custom observers; the first-party SDK and Studio observers implement it via the SDK query store / Studio's `listenQuery`, engine-dataset-scoped), built on the engine's `instanceGuardQuery` and workflow-react's shared `NO_GUARDS` unresolved snapshot.

- 12e23b0: New shared primitives so consumers and tests build the engine's shapes exactly the way the engine does:
  - `datasetResourceParts(id)` — the one parser for `<projectId>.<dataset>` resource ids (`gdrFromResource` and the React adapters' routing both delegate to it; malformed ids now fail on empty parts too).
  - `subscriptionDocument(ref)` — build one `SubscriptionDocument` from a `GlobalDocumentReference`, the same construction `subscriptionDocumentsForInstance` uses.
  - `MutationGuardDeniedError.fromGuards({documentId, action, guards})` — the one mapping from denying guard docs to the structured `denied` payload, used by the engine's pre-flight and the test bench's write seam.

## 0.3.0

### Minor Changes

- 41ddd80: Add a reactive, opt-in instance session so the engine can be driven by live document state — without owning any subscription or refetching content the consumer already holds.
  - `engine.instance(instanceDoc)` returns a stateful session: `subscriptionDocuments` (the `WatchSet` to feed), `update(docs)` (last-write-wins replace of the held content — deep-copied so it's decoupled from the consumer's live objects, and gated single-writer so it can't swap state out from under an in-flight commit), `evaluate()` (best-effort projection on the held content; async only because filter eval is groq-js, no network), and `tick()` / `fireAction()` (advance on the held content, committing via `ifRevisionId`; a `_rev` conflict surfaces). The engine never observes or auto-ticks — the consumer drives it.
  - `hydrateSnapshot` takes an optional content overlay (present id → held value; absent → load), threaded through the cascade so guards/filters/transitions evaluate against the consumer's optimistic content. The instance/ancestors keep reloading (their own writes); `release.ref` (`system.release`) docs read raw; content honours `instance.perspective`.
  - Watch-set/inject surface: `subscriptionDocumentsForInstance` / `WatchSet` (incl. `release.ref`), `readsRaw` (the raw-vs-content read rule a consumer applies when resolving perspective) and `contentReleaseName` (turns the watch-set perspective into the per-doc release a store reads under), `evaluateFromSnapshot`, and `buildSnapshot` / `HydratedSnapshot` / `LoadedDoc` / `resourceFromParsed` are exported so a consumer can assemble and inject snapshots.

- 0c6ccde: Extract shared definition-query primitives so the "tag-scoped, latest-or-pinned `workflow.definition`" query lives in one place instead of being hand-written at each call site.

  The engine now exports two reusable GROQ primitives:
  - `WORKFLOW_DEFINITION_TYPE` / `WORKFLOW_INSTANCE_TYPE` — the lake document-type constants, replacing scattered string literals.
  - `tagScopeFilter(param?)` — the tag-partition GROQ predicate (`count(tags[@ in $engineTags]) > 0`), defaulting to the `engineTags` parameter the `workflow.query` guard expects.

  Internally these compose into a single `definitionLookupGroq` selector for the "latest-or-pinned definition" query. The engine's own lookups (`deploy`, `spawn`, `drain`) and the CLI (`definition show`/`list`, `list`, `deploy`) now build on these primitives, and every tag-scoped query in those paths standardizes on the `$engineTags` parameter — removing the prior `$tags`/`$engineTags` drift.

## 0.2.0

### Minor Changes

- 870188e: The auto-transition cascade now aborts a runaway loop with a typed
  `CascadeLimitError` (carrying `instanceId` and `limit`) instead of a generic
  `Error`. A runaway is the classic op-driven flip-flop: an `op.state.set` lands a
  value that trips the very transition guard that fired it, and nothing clears it,
  so two stages bounce forever. The new error is exported from the package root so
  callers can `instanceof`-narrow it and read its fields. Ops need no separate
  per-action limit — an action's `ops[]` is a finite list that runs once per
  `fireAction`, so the transition cascade is the only place a runaway can live.
- a4f6d81: The `fireAction` commit is now safe against concurrent callers. Each attempt
  reloads the instance and commits through `persist`'s existing `ifRevisionId`
  guard, so two clients firing the same action on the same task can no longer
  silently clobber each other's commit. A commit that loses the optimistic-locking
  race reloads and retries — three attempts total — then throws a new
  `ConcurrentFireActionError` (exported from the package root, carrying
  `instanceId` / `taskId` / `action` / `attempts`). Reloading re-gates the action,
  so a retry whose task the winning writer already completed fails with the normal
  "task must be active" error rather than looping.

  Scope: this covers the action-commit write. The pending→active auto-invoke and
  the post-commit cascade are separate writes, still single-shot (a race there
  surfaces as the underlying conflict, not `ConcurrentFireActionError`).

  `drainEffects`' claim step now uses the same conflict predicate: a lost
  `ifRevisionId` race still means "another drainer won, skip", but a genuine error
  during the claim now surfaces instead of being silently swallowed as a missed
  claim.

- eff2a77: Export `isDefinitionUnchanged` and `stripSystemFields` from the package root. Deploy-preview tooling (e.g. a `deploy --dry-run` that wants to predict whether `deployDefinitions` would treat a definition as a no-op) can now reuse the engine's exact "unchanged definition" verdict — comparing definition documents with Sanity-managed system fields (`_rev` / `_createdAt` / `_updatedAt`) stripped — instead of reimplementing it. `isDefinitionUnchanged` now accepts any `Record<string, unknown>` for the existing document (previously required a full `SanityDocument`).
- ce6960d: Guard provenance + housekeeping queries.
  - Mutation guard docs now carry explicit `sourceInstanceId` / `sourceDefinitionId` / `sourceStageId` provenance fields, so the engine can find its guards for coherency refresh and housekeeping without parsing them out of `_id`.
  - New `engine.guardsForInstance({instanceId})` returns every guard an instance registered, unioned across the resource the instance lives in and the resource of each `doc.ref`/`doc.refs` GDR it holds in state (same "if it's in the workflow, we pull it in" scope as snapshot hydration).
  - New exported `guardsForInstance` / `guardsForResource` helpers and a centralized `GUARD_DOC_TYPE` constant (single rename point for the eventual `temp.` prefix drop).
  - The bench exposes `guardsForInstance`; its `listGuards` now delegates to `guardsForResource`.

- 782272a: Keep mutation guards coherent with workflow state. A guard snapshots the state its `match`/`metadata` Sources resolve to at deploy time; when an action's ops change that state without a stage transition, the engine now re-deploys the current stage's guards so the lock follows the new state ("use the engine, stay consistent"). Fail-loud on a failed re-deploy for now — the rollback-or-scream policy lands separately.
- 2b800a8: Roll a state move back (or scream) when its guards can't deploy. Guards deploy _after_ the state commits, through a shared `deployOrRollback` primitive — wired by `persistThenDeploy` for the transition and action paths, and called directly by the initial-prime path. If the deploy fails, the engine restores the pre-commit instance and re-throws the original error, so the caller sees the failure with state intact. When a clean rollback is impossible (the move spawned child docs a parent-only undo can't remove) or the rollback write itself fails, it throws the newly exported `WorkflowStateDivergedError` — divergence is loud, never silent. This replaces the fail-loud stub the refresh path previously left.
- 0432670: Injectable clock for deterministic time. The engine now threads a single
  `Clock` (`() => string`, default wall-clock) through each verb-driven
  operation, taking one reading per operation so `$now` in filters, the `now`
  op-source, and the timestamps the engine stamps (history `at`, `completedAt`,
  `enteredAt`, `lastChangedAt`, queued/ran effect stamps, query-slot `resolvedAt`)
  all share one instant. Production passes nothing and is unchanged. The clock is
  injected ONCE — via `createEngine({ clock })`, or the test bench's `setNow` /
  `advance` — not as a per-verb option; the raw `workflow.*` verbs accept it only
  through an internal seam, keeping the public `*Args` interfaces free of it. The
  external effect drainer (`drainEffects`) is out of scope and still uses
  wall-clock. The pure
  core (`buildParams`, `resolveSource`) now takes `now` as a value rather than
  reading wall-clock itself, restoring `core/`'s "no `new Date()`" contract.
  `Clock` and `wallClock` are exported from the package root.

  The bench (`@sanity/workflow-engine-test`) exposes the knob: `bench.setNow(iso)`
  freezes time, `bench.advance(ms)` moves it forward, `bench.now()` reads it, and
  `createBench({ now })` starts frozen. The clock is threaded into every wrapped
  verb, so a time-based `completeWhen` / `failWhen` / SLA predicate fires by
  advancing the clock and ticking — without mutating the subject document.

  Also removes the never-implemented `dueAt` hint field from `TaskEntry`: nothing
  ever wrote or read it, so it carried no behaviour. Re-add it with a real
  implementation if a cron-indexing fast-path is built later.

- c2ad7a9: Resolve two reserved-but-unimplemented surfaces:
  - **Removed the `source.kind: "computed"` state-slot reserved word.** It was
    accepted by the schema but always rejected at deploy ("reserved (not
    implemented)"), with no real usage — a dead word. Dropped from the authoring
    schema, the deploy validator, and the resolver. The actual re-resolving-slot
    feature remains deferred to a future version; it can be re-introduced as a
    real source kind then.
  - **Implemented `Source.self` inside ops.** `resolveOpSource` previously
    returned `undefined` for `source: "self"` — a silent no-op. It now resolves to
    the instance's own GDR URI, matching `$self` in filters and `Source.self` in
    spawn sources, so an op can stamp the instance's own ref into a slot. (The
    effect/binding resolver's `self` keeps returning the bare `_id` it already
    did.)

### Patch Changes

- d04cbea: Fix actor/grants resolution crashing on `@sanity/client` >= 7.22. The engine pulled `request` off the client and called it detached, so the method's private-field access through `this` threw before any request was issued (`Cannot read private member #httpRequest…`). The client's `request` is now bound at the single point it leaves the client, so consumers no longer need to pre-bind `client.request` before calling `evaluate`.
- dff88ff: Guard reconcile is now gated on the instance's live committed stage. Deploy/retract run as a post-persist step outside the instance's `ifRevisionId` guard, so a stale or retried reconcile could previously land after a newer transition had already moved the instance on — re-enforcing a stage the instance had left, or lifting the lock it was actively under. `deployStageGuards` now only deploys while the instance is still committed to that stage, and `retractStageGuards` only lifts while it is no longer there. The cross-resource TOCTOU between the live-stage read and the guard write remains a documented seam (same non-atomicity as orphan accumulation).
- 53a0598: Replace zod with valibot for authoring-schema and slot-value validation. Validation lives in two places — the `defineWorkflow` authoring schema (`@sanity/workflow-engine/define`) and per-slot value validation — both of which a consumer bundles into a client. Tree-shaken, that surface drops from ~67 KB to ~5 KB gzip (the full package entry from ~105 KB to ~42 KB), because valibot's modular API only pulls in the validators actually used. Authoring error messages, paths, and validation behaviour are unchanged; cross-field invariant checks now run as an explicit second phase after the structural parse.

## 0.1.0

### Minor Changes

- 43d6b81: Initial release.
  - **`@sanity/workflow-engine`** — a workflow / BPM engine for Sanity content. Define workflows as data (stages, tasks, actions, guards, effects), run them as instances against a Sanity client, gate transitions on GROQ predicates, and queue side effects for runtimes to drain. Multi-tenant via engine-scope tags; ships a typed authoring surface under `@sanity/workflow-engine/define`.
  - **`@sanity/workflow-engine-test`** — an in-memory `createBench` harness for exercising workflows against the engine without a live Sanity client (deploy definitions, start instances, fire actions, assert state).

### Patch Changes

- 127be08: Split the two largest source files into folders of focused, single-concern modules. `src/engine.ts` (2321 lines) becomes `src/engine/` (`results`, `context`, `mutation`, `effects`, `ops`, `spawn`, `tasks`, `stages`, `actions`, `cascade`), and `src/api.ts` (1876 lines) becomes `src/api/` (`types`, `validate`, `deploy`, `operations`, `workflow`, `engine-factory`, `drain`). There is no internal barrel — each module imports the concrete files it needs directly, and the public surface (`src/index.ts`) re-exports the same symbols from those files. No public API change — every exported symbol keeps its name and shape.

  The one irreducible cycle (`mutation.persist` ⇄ `cascade`, the essential commit/spawned-child-lifecycle mutual recursion centralized at the single transactional commit chokepoint) is documented with a `fallow-ignore-file` directive explaining why it cannot be topologically ordered without breaking synchronous nested-workflow semantics.

- bf62213: Reorganize the engine's type model: the monolithic `src/types.ts` is split into a layered `src/types/` directory (`enums`, `ids`, `actor`, `state-slots`, `instance-state`, `effects`, `authorization`, `history`, `client`, `instance`, `evaluation`). The modules form a strict dependency DAG, and `define/schema.ts` imports its value enums from the schema-free `types/enums.ts` leaf so the schema ↔ type-model relationship is acyclic by construction. There is no internal barrel — each module imports the concrete type files it needs directly; the package's public surface (`src/index.ts`) re-exports the same symbols from those files. No public API change — every exported symbol keeps its name and shape.
