@sanity/workflow-mcp 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @sanity/workflow-mcp
2
2
 
3
+ ## 0.31.0
4
+
5
+ ### Patch Changes
6
+
7
+ - 36c0aca: The MCP authoring guide and `workflows_deploy_definition` schema now report the engine-required reader-model floor for role-constrained assignment fields instead of stale deployment guidance.
8
+
9
+ Upgrade the MCP server to receive the corrected guidance. Before deploying a definition with assignment `roles`, upgrade every runtime sharing the workflow resource and then acknowledge the model reported by the guide; an older acknowledgement is rejected.
10
+
11
+ **Docs impact:** Update the MCP tool reference and authoring examples to source reader-model requirements from the engine; the readers-first rollout remains canonical in the Workflows prerelease guide.
12
+
13
+ - Updated dependencies [ff72ece]
14
+ - @sanity/workflow-engine@0.31.0
15
+
3
16
  ## 0.30.0
4
17
 
5
18
  ### Minor Changes
@@ -1,4 +1,4 @@
1
- import { errorMessage, validateTag, parseResourceGdr, WorkflowError, createTelemetryIntake, isTelemetryEnvDenied, processShellUserProperties, parseDefinitionInput, extractDocumentId, parseDefinitionSnapshot, displayTitle, autonomySummary, actionRendering, isTerminalStage, describeCondition, actionVerdict, narrateAutonomyWaits, subjectDenialLabels, deniedGuardLabels, definitionLookupGroq, assertReadableModel, unsatisfiedTransitionSummaries, describeSite, latestDefinitionsGroq, startKindOf, isStartableDefinition, instancesQuery, instanceWatchesDocument, parseGdr, resourceGdr, startRefusal, buildInitialFields, StartNotPrimedError, StartNotSettledError, validateDefinition, createEngine, clientConfigFromResource, ENGINE_API_VERSION } from "@sanity/workflow-engine";
1
+ import { errorMessage, validateTag, parseResourceGdr, WorkflowError, createTelemetryIntake, isTelemetryEnvDenied, processShellUserProperties, parseDefinitionInput, DATA_MODEL_MIN_READER, requiredDefinitionReaderModel, extractDocumentId, parseDefinitionSnapshot, displayTitle, autonomySummary, actionRendering, isTerminalStage, describeCondition, actionVerdict, narrateAutonomyWaits, subjectDenialLabels, deniedGuardLabels, definitionLookupGroq, assertReadableModel, unsatisfiedTransitionSummaries, describeSite, latestDefinitionsGroq, startKindOf, isStartableDefinition, instancesQuery, instanceWatchesDocument, parseGdr, resourceGdr, startRefusal, buildInitialFields, StartNotPrimedError, StartNotSettledError, validateDefinition, createEngine, clientConfigFromResource, ENGINE_API_VERSION } from "@sanity/workflow-engine";
2
2
 
3
3
  import { z } from "zod/v3";
4
4
 
@@ -107,6 +107,17 @@ function parseWorkflowDefinition(definition) {
107
107
  }
108
108
  }
109
109
 
110
+ const roleConstrainedAssignmentDefinition = {
111
+ fields: [ {
112
+ type: "assignee",
113
+ name: "reviewer",
114
+ roles: [ "editor" ]
115
+ } ]
116
+ }, READER_MODEL_GUIDANCE = Object.freeze({
117
+ baseline: DATA_MODEL_MIN_READER,
118
+ roleConstrainedAssignments: requiredDefinitionReaderModel([ roleConstrainedAssignmentDefinition ])
119
+ });
120
+
110
121
  function defineWorkflowTool(def) {
111
122
  const {run: run, ...rest} = def;
112
123
  return {
@@ -142,7 +153,7 @@ const deployWorkflowDefinitionTool = defineWorkflowTool({
142
153
  description: "Deploy workflow definitions you have authored into one workflow environment. Call workflows_validate_definition first and deploy only after it returns valid:true — deploy runs the same checks but errors instead of returning the problem list. Pass a parent and the child workflows it spawns in ONE call — the engine deploys children before the parents that reference them. Deploys are create-only and content-addressed: content identical to the latest deployed version is a no-op (status 'unchanged'), any change mints the next version (status 'created'; a new name starts at version 1), and a deployed version is never patched — running instances keep the definition version they started under. Returns {results, deployId} with one {name, version, status} per definition, in the resolved deploy order (children first). Do NOT use this to check a definition (workflows_validate_definition) or to see what is already deployed (workflows_list_definitions / workflows_get_definition).",
143
154
  inputSchema: {
144
155
  definitions: z.array(z.record(z.string(), z.unknown())).min(1).describe("The workflow definitions to deploy, as JSON objects in authoring shape — the same values workflows_validate_definition takes. A single workflow is a one-element array; a parent and its child workflows belong in one call. See workflows_get_authoring_guide for the shape and examples."),
145
- expectedMinReaderModel: z.number().int().min(0).optional().describe("Highest reader model already verified across every runtime sharing this workflow resource. Omit to retain the model-4 baseline. Pass 6 only after upgrading all shared Studio, CLI, MCP, Function, and other runtimes.")
156
+ expectedMinReaderModel: z.number().int().min(0).optional().describe(`Highest reader model already verified across every runtime sharing this workflow resource. Omit to retain the model-${READER_MODEL_GUIDANCE.baseline} baseline. Definitions with role-constrained assignment fields require model ${READER_MODEL_GUIDANCE.roleConstrainedAssignments}; pass it only after upgrading all shared Studio, CLI, MCP, Function, and other runtimes.`)
146
157
  },
147
158
  requiresAddress: !0,
148
159
  annotations: {
@@ -162,7 +173,7 @@ const deployWorkflowDefinitionTool = defineWorkflowTool({
162
173
  if (problems.length > 0) throw new Error(problems.join(`\n`));
163
174
  const {engine: engine} = await context();
164
175
  return engine.deployDefinitions({
165
- expectedMinReaderModel: input.expectedMinReaderModel ?? 4,
176
+ expectedMinReaderModel: input.expectedMinReaderModel ?? READER_MODEL_GUIDANCE.baseline,
166
177
  definitions: stored
167
178
  });
168
179
  }
@@ -699,7 +710,7 @@ const diagnoseWorkflowTool = defineWorkflowTool({
699
710
  title: "Approved",
700
711
  description: "Terminal — no transitions out."
701
712
  } ]
702
- }, ORIENTATION = "# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (triggers, filters, predicates, guards) is a GROQ *string*. Generate\nthe JSON, then call `workflows_validate_definition` (it takes a `definitions`\narray — validate a parent and its child workflows together) to check it; fix\nthe reported errors and re-validate until it returns `valid: true`. Each\n`results` entry pairs with your input and carries the *desugared* definition\nunder `definition` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: `{ name, title, description?, initialStage, fields?, stages[], predicates? }`.\n `name` must match `^[a-z0-9][a-z0-9-]*$` (lowercase + digits + dashes — it\n interpolates into every deployed document id, so spaces, uppercase, dots,\n and underscores are rejected). `initialStage` must be the `name` of a\n declared stage. Do NOT include a `version` — definitions are immutable and\n content-addressed; deploy assigns the version from the content, the author\n never writes one.\n- **Stage**: `{ name, title?, description?, activities?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: `{ name, title?, filter?, actions?, fields? }` — a unit of work\n that carries NO payload of its own; everything that DOES anything lives on\n its actions. Every in-scope activity is **active from the moment its stage\n is entered** (there is no activation step) and stays active until an action\n resolves it `done`/`skipped`/`failed`. `filter` is existence, evaluated\n once at stage entry: a definite `false` skips the activity for this visit.\n- **Action**: `{ name, title?, when?, status?, params?, ops? }` — actions are\n the ONLY payload mechanism. Two firing modes:\n - **No `when`** — invoked by a caller (a person or agent calling\n `workflows_fire_action`).\n - **With `when`** — CASCADE-FIRED: the engine fires it on its own the\n moment the GROQ trigger is true (at most once per stage visit), and no\n caller can ever invoke it. Fires-on-entry work is `when: 'true'`.\n `status: 'done' | 'skipped' | 'failed'` is sugar that resolves the *firing\n activity* to that status when the action fires. Status is a health axis, not\n a decision: a routine decision (reject, send back, decline, hold) resolves\n `'done'` and writes the decision into a field the transition triggers read —\n reserve `'failed'` for work that genuinely could not complete (e.g. a missed\n deadline via `{name: 'deadline', when: '$now > $fields.dueBy', status: 'failed'}`).\n `ops` are mutations applied when the action fires (e.g.\n `{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}`).\n `params` are values a caller-fired action collects from the caller\n (referenced by `{type:'param', param:'<name>'}` sources); a `when` action\n has no caller, so `params` is rejected there. Scalar params may constrain\n callers to titled choices with\n `options:{list:[{title:'Approve', value:'approve'}]}`, and string/text or\n number params may declare inclusive `validation:{min,max}` bounds.\n- **Transition**: `{ name, title?, to, when? }` — a pure edge; transitions\n carry no ops or effects (only actions do). `to` must name a declared stage.\n `when` is the GROQ trigger gating the exit; omit it and it defaults to\n `$allActivitiesDone`. The first transition whose `when` is true (in\n declaration order) fires.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, initialValue?, options?, validation? }`.\n Scalar `type`s mirror Sanity: `string`, `text` (multiline), `number`,\n `progress` (a number elevated to mean 0–100 completion; always finite and\n within 0–100 inclusive, fractions allowed), `boolean`, `date` (YYYY-MM-DD),\n `datetime` (ISO), `url`. Plus references\n (`doc.ref`, `doc.refs`, `release.ref`, and `subject` — a single `doc.ref`\n elevated to name THE document the workflow is about; workflow scope only, at\n most one, and what document pickers match against), identities (`actor` — one\n concrete principal; `assignee` / `assignees` — one or many user-or-role\n assignees), and\n the compositional kinds `object` (`{ type:'object', name, fields: [...] }`) and\n `array` (`{ type:'array', name, of: [...] }`) — `fields`/`of` are themselves\n field shapes, so any structure composes. `initialValue` seeds the field once at\n materialisation and is **optional** — omit it for op-filled working memory\n (the common default). Arms: `{type:'input'}` (the caller supplies it when the\n instance starts), `{type:'query', query:'<groq>'}` (computed from the lake),\n `{type:'literal', value:<json>}`, or `{type:'fieldRead', field:'<name>'}`.\n String/text, number, URL, date, and datetime fields may declare a non-empty\n `options.list` of `{title, value}` choices. Values must match the field kind,\n be unique, and every non-null runtime value must be listed. The same syntax\n works on nested field shapes, effect outputs, and action params (where datetime\n is spelled `dateTime`).\n String/text, number, and progress declarations may also use inclusive\n `validation:{min,max}` bounds. String/text bounds measure character length\n and must be non-negative integers; number bounds measure the numeric value;\n progress bounds may only narrow the kind's intrinsic 0–100 (each declared\n bound must itself sit within 0–100). Choices must satisfy any bounds. The\n same syntax works on nested field shapes, effect outputs, and action params.\n Assignment fields may declare a non-empty `roles:['editor', ...]` list.\n It limits newly written users to project members who hold or fulfill one of\n those roles, and limits collective role values to literal listed roles. The\n facet works on `assignee` / `assignees` at every field-shape level,\n including nested shapes and effect outputs. Before deploying such a\n definition, upgrade every runtime sharing the workflow resource and pass\n `expectedMinReaderModel:6` to `workflows_deploy_definition`; otherwise\n omit that tool argument and retain the model-4 baseline.\n A workflow about a document declares an `input`-sourced `subject` entry — the\n runtime and every surface identify the subject by that kind.\n Two list sugars desugar to `array`: `{type:'todoList', name}` (ad-hoc\n status-tracked work — rows `{ label, status, assignee?, dueDate? }`) and\n `{type:'notes', name}` (an append-only audit/comment log — rows\n `{ body, actor, at }`; pairs with the `audit` op, which stamps `actor`/`at`).\n\n## GROQ in conditions\n\nBuilt-in variables available in triggers/filters/predicates (the engine's\nexported `CONDITION_VARS` inventory is the source of truth):\n`$allActivitiesDone`, `$anyActivityFailed` (booleans over the current stage's\nactivities), `$activities` (the activity list), `$fields` (field values),\n`$context` (the start-time context bag — values seeded when the instance\nstarted; written once, never mutated), `$now`,\n`$self`/`$stage`/`$parent`/`$ancestors` (instance identity + position),\n`$effectStatus` (effect name → `'done'`/`'failed'` of the run queued during\nthe CURRENT stage entry — the re-entry-safe way to gate on an effect having\ndrained, e.g. a trigger action\n`{name: 'settled', when: \"defined($effectStatus['my.effect'])\", status: 'done'}`),\nand the caller-scoped vars `$actor` (the acting user), `$assigned` (whether\nthe caller is the activity's assignee — the idiomatic permission gate, used as\nan action `filter: '$assigned'`), `$can`, and `$attributes` (the caller's\norg-level User Attributes when available — Enterprise; same values lake filters\nread via `user::attributes()`, e.g. `$attributes.department == \"politics\"`;\nunbound and fail-closed on expected absence; unexpected fetch failures throw). `$actor`/`$assigned`/`$can`/`$attributes`\nbelong in the **caller-bound projection**: fireAction action filters, activity\nrequirements, and editable predicates. The cascade is deliberately\ncaller-blind: transition `when`s, activity `filter`s, and a cascade-fired\naction's `when`/`filter` re-evaluate on every trigger (another editor's\naction, an effect draining, a tick) and must resolve the same way regardless\nof whose token that is, so deploy rejects `$actor`/`$assigned`/`$can`/`$attributes`/`$params`\nthere — route on instance state an action wrote instead. `$params` (the firing\naction's args) is not usable in **any** filter — action filters included: a\nfilter decides whether the action is enabled before the caller supplies args,\nso deploy rejects it there too. Collect caller input with the action's\n`params` and consume it in the action's `ops` (a `{type:'param'}` value).\n(Identity still gates every move: the commit rides the caller's token, and the\nlake's ACL accepts or rejects the write wholesale. Engine checks including\n`$attributes` are advisory — not a security boundary.) Define reusable named\nconditions under top-level `predicates: { name: '<groq>' }` and reference\nthem as `$name` (e.g.\n`predicates: { ready: \"count($activities[status != 'done']) == 0\" }` → `$ready`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by `_type` (e.g. `*[_type==\"article\"]`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a `doc.ref` field for it.\n\n`$fields.<name>` must name a declared field entry visible at the reading\nsite: workflow fields everywhere, plus the enclosing stage's fields at that\nstage's sites, plus the enclosing activity's fields inside that activity.\nTransition triggers cannot see activity fields — put a decision a transition\nroutes on at stage scope (Example 2). A read's dot-path must also fit the\nentry's declared value shape — reference envelopes especially: a\n`release.ref` value carries `id`/`type`/`releaseName` (never `_id`), a\n`doc.refs` element `id`/`type`. The validator rejects reads of\nundeclared names, condition dot-paths that don't fit the declared shape,\nstages no transition path reaches, and `fieldRead` value sources whose\ntarget entry or dot-path doesn't resolve.\n\n## Sugars worth knowing\n\n- Action `status: 'done' | 'skipped' | 'failed'` — resolves the firing activity (shown above).\n- Omitted transition `when` — defaults to `$allActivitiesDone`.\n- Action `roles: ['editor', ...]` — on a caller-fired action, folds a\n role-membership check into its `filter`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. `review → drafting` gated\n on a `decision` field the reject action wrote), not to a terminal stage.\n Reserve terminal stages for completion and for explicit\n cancellation/abandonment — a workflow should not dead-end just because\n something was declined.\n- **Decisions are fields, not failures.** When a stage branches on a human\n decision, declare a stage-scoped `string` field (stage scope resets on\n re-entry, so loop-backs start clean), have each deciding action `field.set`\n it, and gate every outbound transition on its value (Example 2). Do not\n encode a decision as `status: 'failed'` + `$anyActivityFailed` — reporting\n would count healthy loops as failures.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition `to` and `initialStage` names a declared stage.\n- Every activity must have a path to a terminal status — some action in the\n stage (its own, or a sibling's via a `status.set` op) resolves it\n `done`/`skipped`/`failed`; an activity nothing can ever resolve is rejected.\n- A terminal stage (no transitions) declares no activities — entering it\n completes the instance, so they could never run.\n- Custom `predicates` must not shadow a built-in (e.g. `allActivitiesDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\`\`\`json\n${JSON.stringify(minimalExample, null, 2)}\n\`\`\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\`\`\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\`\`\`\n`, getWorkflowAuthoringGuideTool = defineWorkflowTool({
713
+ }, ORIENTATION = `# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (triggers, filters, predicates, guards) is a GROQ *string*. Generate\nthe JSON, then call \`workflows_validate_definition\` (it takes a \`definitions\`\narray — validate a parent and its child workflows together) to check it; fix\nthe reported errors and re-validate until it returns \`valid: true\`. Each\n\`results\` entry pairs with your input and carries the *desugared* definition\nunder \`definition\` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: \`{ name, title, description?, initialStage, fields?, stages[], predicates? }\`.\n \`name\` must match \`^[a-z0-9][a-z0-9-]*$\` (lowercase + digits + dashes — it\n interpolates into every deployed document id, so spaces, uppercase, dots,\n and underscores are rejected). \`initialStage\` must be the \`name\` of a\n declared stage. Do NOT include a \`version\` — definitions are immutable and\n content-addressed; deploy assigns the version from the content, the author\n never writes one.\n- **Stage**: \`{ name, title?, description?, activities?, transitions? }\`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: \`{ name, title?, filter?, actions?, fields? }\` — a unit of work\n that carries NO payload of its own; everything that DOES anything lives on\n its actions. Every in-scope activity is **active from the moment its stage\n is entered** (there is no activation step) and stays active until an action\n resolves it \`done\`/\`skipped\`/\`failed\`. \`filter\` is existence, evaluated\n once at stage entry: a definite \`false\` skips the activity for this visit.\n- **Action**: \`{ name, title?, when?, status?, params?, ops? }\` — actions are\n the ONLY payload mechanism. Two firing modes:\n - **No \`when\`** — invoked by a caller (a person or agent calling\n \`workflows_fire_action\`).\n - **With \`when\`** — CASCADE-FIRED: the engine fires it on its own the\n moment the GROQ trigger is true (at most once per stage visit), and no\n caller can ever invoke it. Fires-on-entry work is \`when: 'true'\`.\n \`status: 'done' | 'skipped' | 'failed'\` is sugar that resolves the *firing\n activity* to that status when the action fires. Status is a health axis, not\n a decision: a routine decision (reject, send back, decline, hold) resolves\n \`'done'\` and writes the decision into a field the transition triggers read —\n reserve \`'failed'\` for work that genuinely could not complete (e.g. a missed\n deadline via \`{name: 'deadline', when: '$now > $fields.dueBy', status: 'failed'}\`).\n \`ops\` are mutations applied when the action fires (e.g.\n \`{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}\`).\n \`params\` are values a caller-fired action collects from the caller\n (referenced by \`{type:'param', param:'<name>'}\` sources); a \`when\` action\n has no caller, so \`params\` is rejected there. Scalar params may constrain\n callers to titled choices with\n \`options:{list:[{title:'Approve', value:'approve'}]}\`, and string/text or\n number params may declare inclusive \`validation:{min,max}\` bounds.\n- **Transition**: \`{ name, title?, to, when? }\` — a pure edge; transitions\n carry no ops or effects (only actions do). \`to\` must name a declared stage.\n \`when\` is the GROQ trigger gating the exit; omit it and it defaults to\n \`$allActivitiesDone\`. The first transition whose \`when\` is true (in\n declaration order) fires.\n- **Field** (workflow- or stage-scoped persistent state): \`{ type, name, title?, initialValue?, options?, validation? }\`.\n Scalar \`type\`s mirror Sanity: \`string\`, \`text\` (multiline), \`number\`,\n \`progress\` (a number elevated to mean 0–100 completion; always finite and\n within 0–100 inclusive, fractions allowed), \`boolean\`, \`date\` (YYYY-MM-DD),\n \`datetime\` (ISO), \`url\`. Plus references\n (\`doc.ref\`, \`doc.refs\`, \`release.ref\`, and \`subject\` — a single \`doc.ref\`\n elevated to name THE document the workflow is about; workflow scope only, at\n most one, and what document pickers match against), identities (\`actor\` — one\n concrete principal; \`assignee\` / \`assignees\` — one or many user-or-role\n assignees), and\n the compositional kinds \`object\` (\`{ type:'object', name, fields: [...] }\`) and\n \`array\` (\`{ type:'array', name, of: [...] }\`) — \`fields\`/\`of\` are themselves\n field shapes, so any structure composes. \`initialValue\` seeds the field once at\n materialisation and is **optional** — omit it for op-filled working memory\n (the common default). Arms: \`{type:'input'}\` (the caller supplies it when the\n instance starts), \`{type:'query', query:'<groq>'}\` (computed from the lake),\n \`{type:'literal', value:<json>}\`, or \`{type:'fieldRead', field:'<name>'}\`.\n String/text, number, URL, date, and datetime fields may declare a non-empty\n \`options.list\` of \`{title, value}\` choices. Values must match the field kind,\n be unique, and every non-null runtime value must be listed. The same syntax\n works on nested field shapes, effect outputs, and action params (where datetime\n is spelled \`dateTime\`).\n String/text, number, and progress declarations may also use inclusive\n \`validation:{min,max}\` bounds. String/text bounds measure character length\n and must be non-negative integers; number bounds measure the numeric value;\n progress bounds may only narrow the kind's intrinsic 0–100 (each declared\n bound must itself sit within 0–100). Choices must satisfy any bounds. The\n same syntax works on nested field shapes, effect outputs, and action params.\n Assignment fields may declare a non-empty \`roles:['editor', ...]\` list.\n It limits newly written users to project members who hold or fulfill one of\n those roles, and limits collective role values to literal listed roles. The\n facet works on \`assignee\` / \`assignees\` at every field-shape level,\n including nested shapes and effect outputs. Before deploying such a\n definition, upgrade every runtime sharing the workflow resource and pass\n \`expectedMinReaderModel:${READER_MODEL_GUIDANCE.roleConstrainedAssignments}\` to\n \`workflows_deploy_definition\`; otherwise omit that tool argument and retain\n the model-${READER_MODEL_GUIDANCE.baseline} baseline.\n A workflow about a document declares an \`input\`-sourced \`subject\` entry — the\n runtime and every surface identify the subject by that kind.\n Two list sugars desugar to \`array\`: \`{type:'todoList', name}\` (ad-hoc\n status-tracked work — rows \`{ label, status, assignee?, dueDate? }\`) and\n \`{type:'notes', name}\` (an append-only audit/comment log — rows\n \`{ body, actor, at }\`; pairs with the \`audit\` op, which stamps \`actor\`/\`at\`).\n\n## GROQ in conditions\n\nBuilt-in variables available in triggers/filters/predicates (the engine's\nexported \`CONDITION_VARS\` inventory is the source of truth):\n\`$allActivitiesDone\`, \`$anyActivityFailed\` (booleans over the current stage's\nactivities), \`$activities\` (the activity list), \`$fields\` (field values),\n\`$context\` (the start-time context bag — values seeded when the instance\nstarted; written once, never mutated), \`$now\`,\n\`$self\`/\`$stage\`/\`$parent\`/\`$ancestors\` (instance identity + position),\n\`$effectStatus\` (effect name → \`'done'\`/\`'failed'\` of the run queued during\nthe CURRENT stage entry — the re-entry-safe way to gate on an effect having\ndrained, e.g. a trigger action\n\`{name: 'settled', when: "defined($effectStatus['my.effect'])", status: 'done'}\`),\nand the caller-scoped vars \`$actor\` (the acting user), \`$assigned\` (whether\nthe caller is the activity's assignee — the idiomatic permission gate, used as\nan action \`filter: '$assigned'\`), \`$can\`, and \`$attributes\` (the caller's\norg-level User Attributes when available — Enterprise; same values lake filters\nread via \`user::attributes()\`, e.g. \`$attributes.department == "politics"\`;\nunbound and fail-closed on expected absence; unexpected fetch failures throw). \`$actor\`/\`$assigned\`/\`$can\`/\`$attributes\`\nbelong in the **caller-bound projection**: fireAction action filters, activity\nrequirements, and editable predicates. The cascade is deliberately\ncaller-blind: transition \`when\`s, activity \`filter\`s, and a cascade-fired\naction's \`when\`/\`filter\` re-evaluate on every trigger (another editor's\naction, an effect draining, a tick) and must resolve the same way regardless\nof whose token that is, so deploy rejects \`$actor\`/\`$assigned\`/\`$can\`/\`$attributes\`/\`$params\`\nthere — route on instance state an action wrote instead. \`$params\` (the firing\naction's args) is not usable in **any** filter — action filters included: a\nfilter decides whether the action is enabled before the caller supplies args,\nso deploy rejects it there too. Collect caller input with the action's\n\`params\` and consume it in the action's \`ops\` (a \`{type:'param'}\` value).\n(Identity still gates every move: the commit rides the caller's token, and the\nlake's ACL accepts or rejects the write wholesale. Engine checks including\n\`$attributes\` are advisory — not a security boundary.) Define reusable named\nconditions under top-level \`predicates: { name: '<groq>' }\` and reference\nthem as \`$name\` (e.g.\n\`predicates: { ready: "count($activities[status != 'done']) == 0" }\` → \`$ready\`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by \`_type\` (e.g. \`*[_type=="article"]\`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a \`doc.ref\` field for it.\n\n\`$fields.<name>\` must name a declared field entry visible at the reading\nsite: workflow fields everywhere, plus the enclosing stage's fields at that\nstage's sites, plus the enclosing activity's fields inside that activity.\nTransition triggers cannot see activity fields — put a decision a transition\nroutes on at stage scope (Example 2). A read's dot-path must also fit the\nentry's declared value shape — reference envelopes especially: a\n\`release.ref\` value carries \`id\`/\`type\`/\`releaseName\` (never \`_id\`), a\n\`doc.refs\` element \`id\`/\`type\`. The validator rejects reads of\nundeclared names, condition dot-paths that don't fit the declared shape,\nstages no transition path reaches, and \`fieldRead\` value sources whose\ntarget entry or dot-path doesn't resolve.\n\n## Sugars worth knowing\n\n- Action \`status: 'done' | 'skipped' | 'failed'\` — resolves the firing activity (shown above).\n- Omitted transition \`when\` — defaults to \`$allActivitiesDone\`.\n- Action \`roles: ['editor', ...]\` — on a caller-fired action, folds a\n role-membership check into its \`filter\`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. \`review → drafting\` gated\n on a \`decision\` field the reject action wrote), not to a terminal stage.\n Reserve terminal stages for completion and for explicit\n cancellation/abandonment — a workflow should not dead-end just because\n something was declined.\n- **Decisions are fields, not failures.** When a stage branches on a human\n decision, declare a stage-scoped \`string\` field (stage scope resets on\n re-entry, so loop-backs start clean), have each deciding action \`field.set\`\n it, and gate every outbound transition on its value (Example 2). Do not\n encode a decision as \`status: 'failed'\` + \`$anyActivityFailed\` — reporting\n would count healthy loops as failures.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition \`to\` and \`initialStage\` names a declared stage.\n- Every activity must have a path to a terminal status — some action in the\n stage (its own, or a sibling's via a \`status.set\` op) resolves it\n \`done\`/\`skipped\`/\`failed\`; an activity nothing can ever resolve is rejected.\n- A terminal stage (no transitions) declares no activities — entering it\n completes the instance, so they could never run.\n- Custom \`predicates\` must not shadow a built-in (e.g. \`allActivitiesDone\`).\n- Every GROQ string must parse and must not be a \`_type\` discovery scan.`, AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\`\`\`json\n${JSON.stringify(minimalExample, null, 2)}\n\`\`\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\`\`\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\`\`\`\n`, getWorkflowAuthoringGuideTool = defineWorkflowTool({
703
714
  name: "workflows_get_authoring_guide",
704
715
  description: "Get the guide for authoring a workflow definition: the DSL shape, the GROQ condition built-ins, the sugars, the rules the validator enforces, and two worked JSON examples. Call this BEFORE writing a definition from a description, then generate the JSON and check it with workflows_validate_definition. Pure read; takes no arguments.",
705
716
  inputSchema: {},
package/dist/index.cjs CHANGED
@@ -83,6 +83,17 @@ function parseWorkflowDefinition(definition) {
83
83
  }
84
84
  }
85
85
 
86
+ const roleConstrainedAssignmentDefinition = {
87
+ fields: [ {
88
+ type: "assignee",
89
+ name: "reviewer",
90
+ roles: [ "editor" ]
91
+ } ]
92
+ }, READER_MODEL_GUIDANCE = Object.freeze({
93
+ baseline: workflowEngine.DATA_MODEL_MIN_READER,
94
+ roleConstrainedAssignments: workflowEngine.requiredDefinitionReaderModel([ roleConstrainedAssignmentDefinition ])
95
+ });
96
+
86
97
  function defineWorkflowTool(def) {
87
98
  const {run: run, ...rest} = def;
88
99
  return {
@@ -118,7 +129,7 @@ const deployWorkflowDefinitionTool = defineWorkflowTool({
118
129
  description: "Deploy workflow definitions you have authored into one workflow environment. Call workflows_validate_definition first and deploy only after it returns valid:true — deploy runs the same checks but errors instead of returning the problem list. Pass a parent and the child workflows it spawns in ONE call — the engine deploys children before the parents that reference them. Deploys are create-only and content-addressed: content identical to the latest deployed version is a no-op (status 'unchanged'), any change mints the next version (status 'created'; a new name starts at version 1), and a deployed version is never patched — running instances keep the definition version they started under. Returns {results, deployId} with one {name, version, status} per definition, in the resolved deploy order (children first). Do NOT use this to check a definition (workflows_validate_definition) or to see what is already deployed (workflows_list_definitions / workflows_get_definition).",
119
130
  inputSchema: {
120
131
  definitions: v3.z.array(v3.z.record(v3.z.string(), v3.z.unknown())).min(1).describe("The workflow definitions to deploy, as JSON objects in authoring shape — the same values workflows_validate_definition takes. A single workflow is a one-element array; a parent and its child workflows belong in one call. See workflows_get_authoring_guide for the shape and examples."),
121
- expectedMinReaderModel: v3.z.number().int().min(0).optional().describe("Highest reader model already verified across every runtime sharing this workflow resource. Omit to retain the model-4 baseline. Pass 6 only after upgrading all shared Studio, CLI, MCP, Function, and other runtimes.")
132
+ expectedMinReaderModel: v3.z.number().int().min(0).optional().describe(`Highest reader model already verified across every runtime sharing this workflow resource. Omit to retain the model-${READER_MODEL_GUIDANCE.baseline} baseline. Definitions with role-constrained assignment fields require model ${READER_MODEL_GUIDANCE.roleConstrainedAssignments}; pass it only after upgrading all shared Studio, CLI, MCP, Function, and other runtimes.`)
122
133
  },
123
134
  requiresAddress: !0,
124
135
  annotations: {
@@ -139,7 +150,7 @@ const deployWorkflowDefinitionTool = defineWorkflowTool({
139
150
  if (problems.length > 0) throw new Error(problems.join(`\n`));
140
151
  const {engine: engine} = await context();
141
152
  return engine.deployDefinitions({
142
- expectedMinReaderModel: input.expectedMinReaderModel ?? 4,
153
+ expectedMinReaderModel: input.expectedMinReaderModel ?? READER_MODEL_GUIDANCE.baseline,
143
154
  definitions: stored
144
155
  });
145
156
  }
@@ -676,7 +687,7 @@ const diagnoseWorkflowTool = defineWorkflowTool({
676
687
  title: "Approved",
677
688
  description: "Terminal — no transitions out."
678
689
  } ]
679
- }, ORIENTATION = "# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (triggers, filters, predicates, guards) is a GROQ *string*. Generate\nthe JSON, then call `workflows_validate_definition` (it takes a `definitions`\narray — validate a parent and its child workflows together) to check it; fix\nthe reported errors and re-validate until it returns `valid: true`. Each\n`results` entry pairs with your input and carries the *desugared* definition\nunder `definition` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: `{ name, title, description?, initialStage, fields?, stages[], predicates? }`.\n `name` must match `^[a-z0-9][a-z0-9-]*$` (lowercase + digits + dashes — it\n interpolates into every deployed document id, so spaces, uppercase, dots,\n and underscores are rejected). `initialStage` must be the `name` of a\n declared stage. Do NOT include a `version` — definitions are immutable and\n content-addressed; deploy assigns the version from the content, the author\n never writes one.\n- **Stage**: `{ name, title?, description?, activities?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: `{ name, title?, filter?, actions?, fields? }` — a unit of work\n that carries NO payload of its own; everything that DOES anything lives on\n its actions. Every in-scope activity is **active from the moment its stage\n is entered** (there is no activation step) and stays active until an action\n resolves it `done`/`skipped`/`failed`. `filter` is existence, evaluated\n once at stage entry: a definite `false` skips the activity for this visit.\n- **Action**: `{ name, title?, when?, status?, params?, ops? }` — actions are\n the ONLY payload mechanism. Two firing modes:\n - **No `when`** — invoked by a caller (a person or agent calling\n `workflows_fire_action`).\n - **With `when`** — CASCADE-FIRED: the engine fires it on its own the\n moment the GROQ trigger is true (at most once per stage visit), and no\n caller can ever invoke it. Fires-on-entry work is `when: 'true'`.\n `status: 'done' | 'skipped' | 'failed'` is sugar that resolves the *firing\n activity* to that status when the action fires. Status is a health axis, not\n a decision: a routine decision (reject, send back, decline, hold) resolves\n `'done'` and writes the decision into a field the transition triggers read —\n reserve `'failed'` for work that genuinely could not complete (e.g. a missed\n deadline via `{name: 'deadline', when: '$now > $fields.dueBy', status: 'failed'}`).\n `ops` are mutations applied when the action fires (e.g.\n `{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}`).\n `params` are values a caller-fired action collects from the caller\n (referenced by `{type:'param', param:'<name>'}` sources); a `when` action\n has no caller, so `params` is rejected there. Scalar params may constrain\n callers to titled choices with\n `options:{list:[{title:'Approve', value:'approve'}]}`, and string/text or\n number params may declare inclusive `validation:{min,max}` bounds.\n- **Transition**: `{ name, title?, to, when? }` — a pure edge; transitions\n carry no ops or effects (only actions do). `to` must name a declared stage.\n `when` is the GROQ trigger gating the exit; omit it and it defaults to\n `$allActivitiesDone`. The first transition whose `when` is true (in\n declaration order) fires.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, initialValue?, options?, validation? }`.\n Scalar `type`s mirror Sanity: `string`, `text` (multiline), `number`,\n `progress` (a number elevated to mean 0–100 completion; always finite and\n within 0–100 inclusive, fractions allowed), `boolean`, `date` (YYYY-MM-DD),\n `datetime` (ISO), `url`. Plus references\n (`doc.ref`, `doc.refs`, `release.ref`, and `subject` — a single `doc.ref`\n elevated to name THE document the workflow is about; workflow scope only, at\n most one, and what document pickers match against), identities (`actor` — one\n concrete principal; `assignee` / `assignees` — one or many user-or-role\n assignees), and\n the compositional kinds `object` (`{ type:'object', name, fields: [...] }`) and\n `array` (`{ type:'array', name, of: [...] }`) — `fields`/`of` are themselves\n field shapes, so any structure composes. `initialValue` seeds the field once at\n materialisation and is **optional** — omit it for op-filled working memory\n (the common default). Arms: `{type:'input'}` (the caller supplies it when the\n instance starts), `{type:'query', query:'<groq>'}` (computed from the lake),\n `{type:'literal', value:<json>}`, or `{type:'fieldRead', field:'<name>'}`.\n String/text, number, URL, date, and datetime fields may declare a non-empty\n `options.list` of `{title, value}` choices. Values must match the field kind,\n be unique, and every non-null runtime value must be listed. The same syntax\n works on nested field shapes, effect outputs, and action params (where datetime\n is spelled `dateTime`).\n String/text, number, and progress declarations may also use inclusive\n `validation:{min,max}` bounds. String/text bounds measure character length\n and must be non-negative integers; number bounds measure the numeric value;\n progress bounds may only narrow the kind's intrinsic 0–100 (each declared\n bound must itself sit within 0–100). Choices must satisfy any bounds. The\n same syntax works on nested field shapes, effect outputs, and action params.\n Assignment fields may declare a non-empty `roles:['editor', ...]` list.\n It limits newly written users to project members who hold or fulfill one of\n those roles, and limits collective role values to literal listed roles. The\n facet works on `assignee` / `assignees` at every field-shape level,\n including nested shapes and effect outputs. Before deploying such a\n definition, upgrade every runtime sharing the workflow resource and pass\n `expectedMinReaderModel:6` to `workflows_deploy_definition`; otherwise\n omit that tool argument and retain the model-4 baseline.\n A workflow about a document declares an `input`-sourced `subject` entry — the\n runtime and every surface identify the subject by that kind.\n Two list sugars desugar to `array`: `{type:'todoList', name}` (ad-hoc\n status-tracked work — rows `{ label, status, assignee?, dueDate? }`) and\n `{type:'notes', name}` (an append-only audit/comment log — rows\n `{ body, actor, at }`; pairs with the `audit` op, which stamps `actor`/`at`).\n\n## GROQ in conditions\n\nBuilt-in variables available in triggers/filters/predicates (the engine's\nexported `CONDITION_VARS` inventory is the source of truth):\n`$allActivitiesDone`, `$anyActivityFailed` (booleans over the current stage's\nactivities), `$activities` (the activity list), `$fields` (field values),\n`$context` (the start-time context bag — values seeded when the instance\nstarted; written once, never mutated), `$now`,\n`$self`/`$stage`/`$parent`/`$ancestors` (instance identity + position),\n`$effectStatus` (effect name → `'done'`/`'failed'` of the run queued during\nthe CURRENT stage entry — the re-entry-safe way to gate on an effect having\ndrained, e.g. a trigger action\n`{name: 'settled', when: \"defined($effectStatus['my.effect'])\", status: 'done'}`),\nand the caller-scoped vars `$actor` (the acting user), `$assigned` (whether\nthe caller is the activity's assignee — the idiomatic permission gate, used as\nan action `filter: '$assigned'`), `$can`, and `$attributes` (the caller's\norg-level User Attributes when available — Enterprise; same values lake filters\nread via `user::attributes()`, e.g. `$attributes.department == \"politics\"`;\nunbound and fail-closed on expected absence; unexpected fetch failures throw). `$actor`/`$assigned`/`$can`/`$attributes`\nbelong in the **caller-bound projection**: fireAction action filters, activity\nrequirements, and editable predicates. The cascade is deliberately\ncaller-blind: transition `when`s, activity `filter`s, and a cascade-fired\naction's `when`/`filter` re-evaluate on every trigger (another editor's\naction, an effect draining, a tick) and must resolve the same way regardless\nof whose token that is, so deploy rejects `$actor`/`$assigned`/`$can`/`$attributes`/`$params`\nthere — route on instance state an action wrote instead. `$params` (the firing\naction's args) is not usable in **any** filter — action filters included: a\nfilter decides whether the action is enabled before the caller supplies args,\nso deploy rejects it there too. Collect caller input with the action's\n`params` and consume it in the action's `ops` (a `{type:'param'}` value).\n(Identity still gates every move: the commit rides the caller's token, and the\nlake's ACL accepts or rejects the write wholesale. Engine checks including\n`$attributes` are advisory — not a security boundary.) Define reusable named\nconditions under top-level `predicates: { name: '<groq>' }` and reference\nthem as `$name` (e.g.\n`predicates: { ready: \"count($activities[status != 'done']) == 0\" }` → `$ready`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by `_type` (e.g. `*[_type==\"article\"]`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a `doc.ref` field for it.\n\n`$fields.<name>` must name a declared field entry visible at the reading\nsite: workflow fields everywhere, plus the enclosing stage's fields at that\nstage's sites, plus the enclosing activity's fields inside that activity.\nTransition triggers cannot see activity fields — put a decision a transition\nroutes on at stage scope (Example 2). A read's dot-path must also fit the\nentry's declared value shape — reference envelopes especially: a\n`release.ref` value carries `id`/`type`/`releaseName` (never `_id`), a\n`doc.refs` element `id`/`type`. The validator rejects reads of\nundeclared names, condition dot-paths that don't fit the declared shape,\nstages no transition path reaches, and `fieldRead` value sources whose\ntarget entry or dot-path doesn't resolve.\n\n## Sugars worth knowing\n\n- Action `status: 'done' | 'skipped' | 'failed'` — resolves the firing activity (shown above).\n- Omitted transition `when` — defaults to `$allActivitiesDone`.\n- Action `roles: ['editor', ...]` — on a caller-fired action, folds a\n role-membership check into its `filter`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. `review → drafting` gated\n on a `decision` field the reject action wrote), not to a terminal stage.\n Reserve terminal stages for completion and for explicit\n cancellation/abandonment — a workflow should not dead-end just because\n something was declined.\n- **Decisions are fields, not failures.** When a stage branches on a human\n decision, declare a stage-scoped `string` field (stage scope resets on\n re-entry, so loop-backs start clean), have each deciding action `field.set`\n it, and gate every outbound transition on its value (Example 2). Do not\n encode a decision as `status: 'failed'` + `$anyActivityFailed` — reporting\n would count healthy loops as failures.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition `to` and `initialStage` names a declared stage.\n- Every activity must have a path to a terminal status — some action in the\n stage (its own, or a sibling's via a `status.set` op) resolves it\n `done`/`skipped`/`failed`; an activity nothing can ever resolve is rejected.\n- A terminal stage (no transitions) declares no activities — entering it\n completes the instance, so they could never run.\n- Custom `predicates` must not shadow a built-in (e.g. `allActivitiesDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\`\`\`json\n${JSON.stringify(minimalExample, null, 2)}\n\`\`\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\`\`\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\`\`\`\n`, getWorkflowAuthoringGuideTool = defineWorkflowTool({
690
+ }, ORIENTATION = `# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (triggers, filters, predicates, guards) is a GROQ *string*. Generate\nthe JSON, then call \`workflows_validate_definition\` (it takes a \`definitions\`\narray — validate a parent and its child workflows together) to check it; fix\nthe reported errors and re-validate until it returns \`valid: true\`. Each\n\`results\` entry pairs with your input and carries the *desugared* definition\nunder \`definition\` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: \`{ name, title, description?, initialStage, fields?, stages[], predicates? }\`.\n \`name\` must match \`^[a-z0-9][a-z0-9-]*$\` (lowercase + digits + dashes — it\n interpolates into every deployed document id, so spaces, uppercase, dots,\n and underscores are rejected). \`initialStage\` must be the \`name\` of a\n declared stage. Do NOT include a \`version\` — definitions are immutable and\n content-addressed; deploy assigns the version from the content, the author\n never writes one.\n- **Stage**: \`{ name, title?, description?, activities?, transitions? }\`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: \`{ name, title?, filter?, actions?, fields? }\` — a unit of work\n that carries NO payload of its own; everything that DOES anything lives on\n its actions. Every in-scope activity is **active from the moment its stage\n is entered** (there is no activation step) and stays active until an action\n resolves it \`done\`/\`skipped\`/\`failed\`. \`filter\` is existence, evaluated\n once at stage entry: a definite \`false\` skips the activity for this visit.\n- **Action**: \`{ name, title?, when?, status?, params?, ops? }\` — actions are\n the ONLY payload mechanism. Two firing modes:\n - **No \`when\`** — invoked by a caller (a person or agent calling\n \`workflows_fire_action\`).\n - **With \`when\`** — CASCADE-FIRED: the engine fires it on its own the\n moment the GROQ trigger is true (at most once per stage visit), and no\n caller can ever invoke it. Fires-on-entry work is \`when: 'true'\`.\n \`status: 'done' | 'skipped' | 'failed'\` is sugar that resolves the *firing\n activity* to that status when the action fires. Status is a health axis, not\n a decision: a routine decision (reject, send back, decline, hold) resolves\n \`'done'\` and writes the decision into a field the transition triggers read —\n reserve \`'failed'\` for work that genuinely could not complete (e.g. a missed\n deadline via \`{name: 'deadline', when: '$now > $fields.dueBy', status: 'failed'}\`).\n \`ops\` are mutations applied when the action fires (e.g.\n \`{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}\`).\n \`params\` are values a caller-fired action collects from the caller\n (referenced by \`{type:'param', param:'<name>'}\` sources); a \`when\` action\n has no caller, so \`params\` is rejected there. Scalar params may constrain\n callers to titled choices with\n \`options:{list:[{title:'Approve', value:'approve'}]}\`, and string/text or\n number params may declare inclusive \`validation:{min,max}\` bounds.\n- **Transition**: \`{ name, title?, to, when? }\` — a pure edge; transitions\n carry no ops or effects (only actions do). \`to\` must name a declared stage.\n \`when\` is the GROQ trigger gating the exit; omit it and it defaults to\n \`$allActivitiesDone\`. The first transition whose \`when\` is true (in\n declaration order) fires.\n- **Field** (workflow- or stage-scoped persistent state): \`{ type, name, title?, initialValue?, options?, validation? }\`.\n Scalar \`type\`s mirror Sanity: \`string\`, \`text\` (multiline), \`number\`,\n \`progress\` (a number elevated to mean 0–100 completion; always finite and\n within 0–100 inclusive, fractions allowed), \`boolean\`, \`date\` (YYYY-MM-DD),\n \`datetime\` (ISO), \`url\`. Plus references\n (\`doc.ref\`, \`doc.refs\`, \`release.ref\`, and \`subject\` — a single \`doc.ref\`\n elevated to name THE document the workflow is about; workflow scope only, at\n most one, and what document pickers match against), identities (\`actor\` — one\n concrete principal; \`assignee\` / \`assignees\` — one or many user-or-role\n assignees), and\n the compositional kinds \`object\` (\`{ type:'object', name, fields: [...] }\`) and\n \`array\` (\`{ type:'array', name, of: [...] }\`) — \`fields\`/\`of\` are themselves\n field shapes, so any structure composes. \`initialValue\` seeds the field once at\n materialisation and is **optional** — omit it for op-filled working memory\n (the common default). Arms: \`{type:'input'}\` (the caller supplies it when the\n instance starts), \`{type:'query', query:'<groq>'}\` (computed from the lake),\n \`{type:'literal', value:<json>}\`, or \`{type:'fieldRead', field:'<name>'}\`.\n String/text, number, URL, date, and datetime fields may declare a non-empty\n \`options.list\` of \`{title, value}\` choices. Values must match the field kind,\n be unique, and every non-null runtime value must be listed. The same syntax\n works on nested field shapes, effect outputs, and action params (where datetime\n is spelled \`dateTime\`).\n String/text, number, and progress declarations may also use inclusive\n \`validation:{min,max}\` bounds. String/text bounds measure character length\n and must be non-negative integers; number bounds measure the numeric value;\n progress bounds may only narrow the kind's intrinsic 0–100 (each declared\n bound must itself sit within 0–100). Choices must satisfy any bounds. The\n same syntax works on nested field shapes, effect outputs, and action params.\n Assignment fields may declare a non-empty \`roles:['editor', ...]\` list.\n It limits newly written users to project members who hold or fulfill one of\n those roles, and limits collective role values to literal listed roles. The\n facet works on \`assignee\` / \`assignees\` at every field-shape level,\n including nested shapes and effect outputs. Before deploying such a\n definition, upgrade every runtime sharing the workflow resource and pass\n \`expectedMinReaderModel:${READER_MODEL_GUIDANCE.roleConstrainedAssignments}\` to\n \`workflows_deploy_definition\`; otherwise omit that tool argument and retain\n the model-${READER_MODEL_GUIDANCE.baseline} baseline.\n A workflow about a document declares an \`input\`-sourced \`subject\` entry — the\n runtime and every surface identify the subject by that kind.\n Two list sugars desugar to \`array\`: \`{type:'todoList', name}\` (ad-hoc\n status-tracked work — rows \`{ label, status, assignee?, dueDate? }\`) and\n \`{type:'notes', name}\` (an append-only audit/comment log — rows\n \`{ body, actor, at }\`; pairs with the \`audit\` op, which stamps \`actor\`/\`at\`).\n\n## GROQ in conditions\n\nBuilt-in variables available in triggers/filters/predicates (the engine's\nexported \`CONDITION_VARS\` inventory is the source of truth):\n\`$allActivitiesDone\`, \`$anyActivityFailed\` (booleans over the current stage's\nactivities), \`$activities\` (the activity list), \`$fields\` (field values),\n\`$context\` (the start-time context bag — values seeded when the instance\nstarted; written once, never mutated), \`$now\`,\n\`$self\`/\`$stage\`/\`$parent\`/\`$ancestors\` (instance identity + position),\n\`$effectStatus\` (effect name → \`'done'\`/\`'failed'\` of the run queued during\nthe CURRENT stage entry — the re-entry-safe way to gate on an effect having\ndrained, e.g. a trigger action\n\`{name: 'settled', when: "defined($effectStatus['my.effect'])", status: 'done'}\`),\nand the caller-scoped vars \`$actor\` (the acting user), \`$assigned\` (whether\nthe caller is the activity's assignee — the idiomatic permission gate, used as\nan action \`filter: '$assigned'\`), \`$can\`, and \`$attributes\` (the caller's\norg-level User Attributes when available — Enterprise; same values lake filters\nread via \`user::attributes()\`, e.g. \`$attributes.department == "politics"\`;\nunbound and fail-closed on expected absence; unexpected fetch failures throw). \`$actor\`/\`$assigned\`/\`$can\`/\`$attributes\`\nbelong in the **caller-bound projection**: fireAction action filters, activity\nrequirements, and editable predicates. The cascade is deliberately\ncaller-blind: transition \`when\`s, activity \`filter\`s, and a cascade-fired\naction's \`when\`/\`filter\` re-evaluate on every trigger (another editor's\naction, an effect draining, a tick) and must resolve the same way regardless\nof whose token that is, so deploy rejects \`$actor\`/\`$assigned\`/\`$can\`/\`$attributes\`/\`$params\`\nthere — route on instance state an action wrote instead. \`$params\` (the firing\naction's args) is not usable in **any** filter — action filters included: a\nfilter decides whether the action is enabled before the caller supplies args,\nso deploy rejects it there too. Collect caller input with the action's\n\`params\` and consume it in the action's \`ops\` (a \`{type:'param'}\` value).\n(Identity still gates every move: the commit rides the caller's token, and the\nlake's ACL accepts or rejects the write wholesale. Engine checks including\n\`$attributes\` are advisory — not a security boundary.) Define reusable named\nconditions under top-level \`predicates: { name: '<groq>' }\` and reference\nthem as \`$name\` (e.g.\n\`predicates: { ready: "count($activities[status != 'done']) == 0" }\` → \`$ready\`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by \`_type\` (e.g. \`*[_type=="article"]\`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a \`doc.ref\` field for it.\n\n\`$fields.<name>\` must name a declared field entry visible at the reading\nsite: workflow fields everywhere, plus the enclosing stage's fields at that\nstage's sites, plus the enclosing activity's fields inside that activity.\nTransition triggers cannot see activity fields — put a decision a transition\nroutes on at stage scope (Example 2). A read's dot-path must also fit the\nentry's declared value shape — reference envelopes especially: a\n\`release.ref\` value carries \`id\`/\`type\`/\`releaseName\` (never \`_id\`), a\n\`doc.refs\` element \`id\`/\`type\`. The validator rejects reads of\nundeclared names, condition dot-paths that don't fit the declared shape,\nstages no transition path reaches, and \`fieldRead\` value sources whose\ntarget entry or dot-path doesn't resolve.\n\n## Sugars worth knowing\n\n- Action \`status: 'done' | 'skipped' | 'failed'\` — resolves the firing activity (shown above).\n- Omitted transition \`when\` — defaults to \`$allActivitiesDone\`.\n- Action \`roles: ['editor', ...]\` — on a caller-fired action, folds a\n role-membership check into its \`filter\`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. \`review → drafting\` gated\n on a \`decision\` field the reject action wrote), not to a terminal stage.\n Reserve terminal stages for completion and for explicit\n cancellation/abandonment — a workflow should not dead-end just because\n something was declined.\n- **Decisions are fields, not failures.** When a stage branches on a human\n decision, declare a stage-scoped \`string\` field (stage scope resets on\n re-entry, so loop-backs start clean), have each deciding action \`field.set\`\n it, and gate every outbound transition on its value (Example 2). Do not\n encode a decision as \`status: 'failed'\` + \`$anyActivityFailed\` — reporting\n would count healthy loops as failures.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition \`to\` and \`initialStage\` names a declared stage.\n- Every activity must have a path to a terminal status — some action in the\n stage (its own, or a sibling's via a \`status.set\` op) resolves it\n \`done\`/\`skipped\`/\`failed\`; an activity nothing can ever resolve is rejected.\n- A terminal stage (no transitions) declares no activities — entering it\n completes the instance, so they could never run.\n- Custom \`predicates\` must not shadow a built-in (e.g. \`allActivitiesDone\`).\n- Every GROQ string must parse and must not be a \`_type\` discovery scan.`, AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\`\`\`json\n${JSON.stringify(minimalExample, null, 2)}\n\`\`\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\`\`\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\`\`\`\n`, getWorkflowAuthoringGuideTool = defineWorkflowTool({
680
691
  name: "workflows_get_authoring_guide",
681
692
  description: "Get the guide for authoring a workflow definition: the DSL shape, the GROQ condition built-ins, the sugars, the rules the validator enforces, and two worked JSON examples. Call this BEFORE writing a definition from a description, then generate the JSON and check it with workflows_validate_definition. Pure read; takes no arguments.",
682
693
  inputSchema: {},
package/dist/stdio.js CHANGED
@@ -6,7 +6,7 @@ import { deployedTagsGroq, parseResourceGdr, datasetResourceParts, EXECUTION_KIN
6
6
 
7
7
  import { LIST_WORKFLOW_TAGS_TOOL_NAME, workflowAddressFields, LIST_WORKFLOW_TAGS_DESCRIPTION, withToolTelemetry, clientForResource, registerWorkflowTools, workflowAddressFromInput, createMcpTelemetry, createEngineCache } from "./_chunks-es/index.js";
8
8
 
9
- var version = "0.30.0", packageJson = {
9
+ var version = "0.31.0", packageJson = {
10
10
  version: version
11
11
  };
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workflow-mcp",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "description": "MCP server exposing Sanity workflow tools to agents — operate running workflow instances and author new definitions.",
5
5
  "keywords": [
6
6
  "agent",
@@ -62,14 +62,14 @@
62
62
  "@types/node": "^24.12.4",
63
63
  "vitest": "^4.1.8",
64
64
  "zod": "^4.4.3",
65
- "@sanity/workflow-engine": "0.30.0",
66
- "@sanity/workflow-engine-test": "0.30.0",
67
- "@sanity/workflow-examples": "0.11.0"
65
+ "@sanity/workflow-engine": "0.31.0",
66
+ "@sanity/workflow-engine-test": "0.31.0",
67
+ "@sanity/workflow-examples": "0.11.1"
68
68
  },
69
69
  "peerDependencies": {
70
70
  "@modelcontextprotocol/sdk": "^1.29.0",
71
71
  "zod": "^3.25.28 || ^4",
72
- "@sanity/workflow-engine": "0.30.0"
72
+ "@sanity/workflow-engine": "0.31.0"
73
73
  },
74
74
  "engines": {
75
75
  "node": ">=20"